Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add email token normalization #3197

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/pds/src/account-manager/helpers/email-token.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { InvalidRequestError } from '@atproto/xrpc-server'
import { MINUTE, lessThanAgoMs } from '@atproto/common'
import { getRandomToken } from '../../api/com/atproto/server/util'
import {
getEmailToken,
normalizeEmailToken,
} from '../../api/com/atproto/server/util'
import { AccountDb, EmailTokenPurpose } from '../db'

export const createEmailToken = async (
db: AccountDb,
did: string,
purpose: EmailTokenPurpose,
): Promise<string> => {
const token = getRandomToken().toUpperCase()
const token = getEmailToken()
const now = new Date().toISOString()
await db.executeWithRetry(
db.db
Expand Down Expand Up @@ -73,7 +76,7 @@ export const assertValidTokenAndFindDid = async (
.selectFrom('email_token')
.selectAll()
.where('purpose', '=', purpose)
.where('token', '=', token.toUpperCase())
.where('token', '=', normalizeEmailToken(token))
.executeTakeFirst()
if (!res) {
throw new InvalidRequestError('Token is invalid', 'InvalidToken')
Expand Down
14 changes: 10 additions & 4 deletions packages/pds/src/api/com/atproto/server/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,18 @@ export const genInvCodes = (cfg: ServerConfig, count: number): string[] => {
return codes
}

// Formatted xxxxx-xxxxx where digits are in base32
export const getRandomToken = () => {
const token = crypto.randomStr(8, 'base32').slice(0, 10)
return token.slice(0, 5) + '-' + token.slice(5, 10)
// Random token formatted XXXXX-XXXXX where digits are in base32
export const getEmailToken = () => {
return normalizeEmailToken(crypto.randomStr(8, 'base32'))
}

// Transforms a badly-formed email token to XXXXX-XXXXX
// (i.e from xxXxxxx-xxx or xxxxxxxxxx)
export const normalizeEmailToken = (input: string): string => {
const normalized = input.trim().toUpperCase().replace('-', ''); // normalize to XXXXXXXXXX
return normalized.slice(0, 5) + '-' + normalized.slice(5, 10); // insert hyphen
};

export const safeResolveDidDoc = async (
ctx: AppContext,
did: string,
Expand Down