Skip to content

Commit

Permalink
add email token normalization
Browse files Browse the repository at this point in the history
use regex to normalize email tokens

use token normalization function when generating tokens
  • Loading branch information
cowtoolz committed Dec 16, 2024
1 parent 0bec389 commit 6dfe39d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
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

0 comments on commit 6dfe39d

Please sign in to comment.