Skip to content

Commit

Permalink
add email token normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
cowtoolz committed Dec 6, 2024
1 parent 0bec389 commit 387d187
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 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
15 changes: 12 additions & 3 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,21 @@ 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)
// Random token formatted XXXXX-XXXXX where digits are in base32
export const getEmailToken = () => {
const token = crypto.randomStr(8, 'base32').slice(0, 10).toUpperCase()
return token.slice(0, 5) + '-' + token.slice(5, 10)
}

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

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

0 comments on commit 387d187

Please sign in to comment.