|
| 1 | +import { createHash, randomBytes, timingSafeEqual } from 'crypto' |
| 2 | +import { |
| 3 | + generateAuthenticationOptions, |
| 4 | + generateRegistrationOptions, |
| 5 | + verifyAuthenticationResponse, |
| 6 | + verifyRegistrationResponse, |
| 7 | + type AuthenticationResponseJSON, |
| 8 | + type PublicKeyCredentialCreationOptionsJSON, |
| 9 | + type PublicKeyCredentialRequestOptionsJSON, |
| 10 | + type RegistrationResponseJSON, |
| 11 | +} from '@simplewebauthn/server' |
| 12 | +import { HubStore, type HubUser } from './hub-store' |
| 13 | + |
| 14 | +const CHALLENGE_TTL_MS = 5 * 60_000 |
| 15 | +export const HUB_BOOTSTRAP_TTL_MS = 10 * 60_000 |
| 16 | +export const HUB_SESSION_TTL_MS = 12 * 60 * 60_000 |
| 17 | + |
| 18 | +interface PendingChallenge { |
| 19 | + challenge: string |
| 20 | + expiresAt: number |
| 21 | + bootstrapDigest?: Buffer |
| 22 | +} |
| 23 | + |
| 24 | +function digest(value: string): Buffer { |
| 25 | + return createHash('sha256').update(value).digest() |
| 26 | +} |
| 27 | + |
| 28 | +function matches(value: string, expected: Buffer): boolean { |
| 29 | + const actual = digest(value) |
| 30 | + return actual.length === expected.length && timingSafeEqual(actual, expected) |
| 31 | +} |
| 32 | + |
| 33 | +export class HubAuth { |
| 34 | + private readonly registrationChallenges = new Map<string, PendingChallenge>() |
| 35 | + private readonly authenticationChallenges = new Map<string, PendingChallenge>() |
| 36 | + private bootstrapDigest: Buffer | null = null |
| 37 | + private bootstrapExpiresAt = 0 |
| 38 | + private bootstrapUsed = false |
| 39 | + |
| 40 | + constructor( |
| 41 | + private readonly store: HubStore, |
| 42 | + readonly publicOrigin: string, |
| 43 | + private readonly now: () => number = Date.now, |
| 44 | + ) {} |
| 45 | + |
| 46 | + get rpId(): string { return new URL(this.publicOrigin).hostname } |
| 47 | + |
| 48 | + issueBootstrap(): { token: string; expiresAt: number } | null { |
| 49 | + if (this.store.owner()) return null |
| 50 | + const token = randomBytes(32).toString('base64url') |
| 51 | + this.bootstrapDigest = digest(token) |
| 52 | + this.bootstrapExpiresAt = this.now() + HUB_BOOTSTRAP_TTL_MS |
| 53 | + this.bootstrapUsed = false |
| 54 | + return { token, expiresAt: this.bootstrapExpiresAt } |
| 55 | + } |
| 56 | + |
| 57 | + async registrationOptions(token: string, username: string): Promise<{ flowId: string; options: PublicKeyCredentialCreationOptionsJSON }> { |
| 58 | + this.requireBootstrap(token) |
| 59 | + const normalized = username.trim() |
| 60 | + if (!/^[\p{L}\p{N}_. -]{1,64}$/u.test(normalized)) throw new Error('owner name must be 1-64 letters, numbers, spaces, dots, underscores, or hyphens') |
| 61 | + const options = await generateRegistrationOptions({ |
| 62 | + rpName: 'CrewCode Hub', |
| 63 | + rpID: this.rpId, |
| 64 | + userName: normalized, |
| 65 | + userDisplayName: normalized, |
| 66 | + attestationType: 'none', |
| 67 | + authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' }, |
| 68 | + }) |
| 69 | + const flowId = randomBytes(16).toString('hex') |
| 70 | + this.registrationChallenges.set(flowId, { challenge: options.challenge, expiresAt: this.now() + CHALLENGE_TTL_MS, bootstrapDigest: digest(token) }) |
| 71 | + return { flowId, options } |
| 72 | + } |
| 73 | + |
| 74 | + async verifyRegistration(input: { token: string; flowId: string; username: string; response: RegistrationResponseJSON }): Promise<{ user: HubUser; token: string; csrf: string }> { |
| 75 | + this.requireBootstrap(input.token) |
| 76 | + const pending = this.registrationChallenges.get(input.flowId) |
| 77 | + this.registrationChallenges.delete(input.flowId) |
| 78 | + if (!pending || pending.expiresAt <= this.now() || !pending.bootstrapDigest || !matches(input.token, pending.bootstrapDigest)) throw new Error('registration challenge is invalid or expired') |
| 79 | + const verification = await verifyRegistrationResponse({ |
| 80 | + response: input.response, |
| 81 | + expectedChallenge: pending.challenge, |
| 82 | + expectedOrigin: this.publicOrigin, |
| 83 | + expectedRPID: this.rpId, |
| 84 | + requireUserVerification: true, |
| 85 | + }) |
| 86 | + if (!verification.verified || !verification.registrationInfo) throw new Error('passkey registration could not be verified') |
| 87 | + const username = input.username.trim() |
| 88 | + const user = this.store.createOwnerWithCredential({ |
| 89 | + username, |
| 90 | + credential: verification.registrationInfo.credential, |
| 91 | + deviceType: verification.registrationInfo.credentialDeviceType, |
| 92 | + backedUp: verification.registrationInfo.credentialBackedUp, |
| 93 | + now: this.now(), |
| 94 | + }) |
| 95 | + this.bootstrapUsed = true |
| 96 | + this.bootstrapDigest = null |
| 97 | + const session = this.store.createSession(user.id, this.now(), HUB_SESSION_TTL_MS) |
| 98 | + return { user, token: session.token, csrf: session.csrf } |
| 99 | + } |
| 100 | + |
| 101 | + async authenticationOptions(): Promise<{ flowId: string; options: PublicKeyCredentialRequestOptionsJSON }> { |
| 102 | + const owner = this.store.owner() |
| 103 | + if (!owner) throw new Error('Hub owner setup is incomplete') |
| 104 | + const credentials = this.store.credentialsForUser(owner.id) |
| 105 | + const options = await generateAuthenticationOptions({ |
| 106 | + rpID: this.rpId, |
| 107 | + allowCredentials: credentials.map(credential => ({ id: credential.id, transports: credential.transports })), |
| 108 | + userVerification: 'required', |
| 109 | + }) |
| 110 | + const flowId = randomBytes(16).toString('hex') |
| 111 | + this.authenticationChallenges.set(flowId, { challenge: options.challenge, expiresAt: this.now() + CHALLENGE_TTL_MS }) |
| 112 | + return { flowId, options } |
| 113 | + } |
| 114 | + |
| 115 | + async verifyAuthentication(input: { flowId: string; response: AuthenticationResponseJSON }): Promise<{ user: HubUser; token: string; csrf: string }> { |
| 116 | + const pending = this.authenticationChallenges.get(input.flowId) |
| 117 | + this.authenticationChallenges.delete(input.flowId) |
| 118 | + if (!pending || pending.expiresAt <= this.now()) throw new Error('authentication challenge is invalid or expired') |
| 119 | + const credential = this.store.credential(input.response.id) |
| 120 | + if (!credential) throw new Error('passkey is not registered with this Hub') |
| 121 | + const verification = await verifyAuthenticationResponse({ |
| 122 | + response: input.response, |
| 123 | + expectedChallenge: pending.challenge, |
| 124 | + expectedOrigin: this.publicOrigin, |
| 125 | + expectedRPID: this.rpId, |
| 126 | + credential: { id: credential.id, publicKey: new Uint8Array(credential.publicKey), counter: credential.counter, transports: credential.transports }, |
| 127 | + requireUserVerification: true, |
| 128 | + }) |
| 129 | + if (!verification.verified) throw new Error('passkey authentication could not be verified') |
| 130 | + this.store.updateCredentialCounter(credential.id, verification.authenticationInfo.newCounter) |
| 131 | + const owner = this.store.owner() |
| 132 | + if (!owner || owner.id !== credential.userId) throw new Error('passkey owner is unavailable') |
| 133 | + const session = this.store.createSession(owner.id, this.now(), HUB_SESSION_TTL_MS) |
| 134 | + return { user: owner, token: session.token, csrf: session.csrf } |
| 135 | + } |
| 136 | + |
| 137 | + private requireBootstrap(token: string): void { |
| 138 | + if (this.store.owner()) throw new Error('Hub owner already exists') |
| 139 | + if (this.bootstrapUsed || !this.bootstrapDigest || this.bootstrapExpiresAt <= this.now() || !matches(token, this.bootstrapDigest)) { |
| 140 | + throw new Error('bootstrap token is invalid, expired, or already used') |
| 141 | + } |
| 142 | + } |
| 143 | +} |
0 commit comments