@prunellejs/auth 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/totp.ts ADDED
@@ -0,0 +1,395 @@
1
+ // Pure RFC 6238 TOTP (HMAC-SHA1, 6 digits, 30s period, ±1 step window), AES-256-GCM secret encryption,
2
+ // single-use recovery codes, and signed pending-2FA cookie helpers.
3
+
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { SessionManager } from './session'
6
+ import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
7
+ import { safeEqual, wantsJson } from 'prunelle/server'
8
+ import { decryptSecret, encryptSecret, randomToken, sha256Hex, signPayload, verifyPayload } from './crypto'
9
+ import { authCookie } from './http'
10
+
11
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
12
+ const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
13
+ const TOTP_PERIOD_SECONDS = 30
14
+ const TOTP_DIGITS = 6
15
+ const RECOVERY_CODE_COUNT = 10
16
+ const PENDING_2FA_TTL_MS = 5 * 60 * 1000
17
+
18
+ export type TwoFactorMethod = 'totp' | 'passkey'
19
+
20
+ export interface TotpOptions {
21
+ /** Issuer label displayed in authenticator apps (defaults to `site` hostname or `'Prunelle'`). */
22
+ issuer?: string | undefined
23
+ /** Path HTML form sign-ins redirect to when 2FA is required (default: `${basePath}/totp/verify`). */
24
+ verifyPath?: string | undefined
25
+ }
26
+
27
+ export interface PendingTwoFactor {
28
+ userId: string
29
+ redirect: string
30
+ methods: TwoFactorMethod[]
31
+ exp: number
32
+ }
33
+
34
+ export function base32Encode(bytes: Uint8Array): string {
35
+ let out = ''
36
+ let bits = 0
37
+ let value = 0
38
+ for (let i = 0; i < bytes.length; i++) {
39
+ value = (value << 8) | bytes[i]!
40
+ bits += 8
41
+ while (bits >= 5) {
42
+ out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]!
43
+ bits -= 5
44
+ }
45
+ }
46
+ if (bits > 0)
47
+ out += BASE32_ALPHABET[(value << (5 - bits)) & 31]!
48
+ return out
49
+ }
50
+
51
+ export function base32Decode(input: string): Uint8Array {
52
+ const clean = input.toUpperCase().replace(/[\s=-]+/g, '')
53
+ const out: number[] = []
54
+ let bits = 0
55
+ let value = 0
56
+ for (let i = 0; i < clean.length; i++) {
57
+ const idx = BASE32_ALPHABET.indexOf(clean[i]!)
58
+ if (idx === -1)
59
+ throw new Error('prunelle: invalid base32 character in TOTP secret')
60
+ value = (value << 5) | idx
61
+ bits += 5
62
+ if (bits >= 8) {
63
+ out.push((value >>> (bits - 8)) & 0xFF)
64
+ bits -= 8
65
+ }
66
+ }
67
+ return new Uint8Array(out)
68
+ }
69
+
70
+ export function generateTotpSecret(): string {
71
+ const bytes = new Uint8Array(20)
72
+ crypto.getRandomValues(bytes)
73
+ return base32Encode(bytes)
74
+ }
75
+
76
+ export function generateTotpCode(secretBase32: string, timestampMs = Date.now()): string {
77
+ const key = base32Decode(secretBase32)
78
+ const step = Math.floor(timestampMs / 1000 / TOTP_PERIOD_SECONDS)
79
+ const counter = new Uint8Array(8)
80
+ const view = new DataView(counter.buffer)
81
+ view.setUint32(0, Math.floor(step / 0x1_0000_0000), false)
82
+ view.setUint32(4, step >>> 0, false)
83
+
84
+ const digest = new Uint8Array(new Bun.CryptoHasher('sha1', key).update(counter).digest())
85
+ const offset = digest[19]! & 0x0F
86
+ const binary = ((digest[offset]! & 0x7F) << 24)
87
+ | ((digest[offset + 1]! & 0xFF) << 16)
88
+ | ((digest[offset + 2]! & 0xFF) << 8)
89
+ | (digest[offset + 3]! & 0xFF)
90
+ const code = binary % (10 ** TOTP_DIGITS)
91
+ return String(code).padStart(TOTP_DIGITS, '0')
92
+ }
93
+
94
+ export function buildOtpauthUrl(issuer: string, email: string, secretBase32: string): string {
95
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(email)}`
96
+ return `otpauth://totp/${label}?secret=${encodeURIComponent(secretBase32)}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=${TOTP_DIGITS}&period=${TOTP_PERIOD_SECONDS}`
97
+ }
98
+
99
+ function matchTotpStep(secretBase32: string, rawCode: string, nowMs: number, lastUsedStep?: number): number | undefined {
100
+ const clean = rawCode.replace(/[\s-]+/g, '')
101
+ if (!/^\d{6}$/.test(clean))
102
+ return undefined
103
+ const currentStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SECONDS)
104
+ for (const offset of [-1, 0, 1]) {
105
+ const step = currentStep + offset
106
+ if (lastUsedStep !== undefined && step <= lastUsedStep)
107
+ continue
108
+ const expected = generateTotpCode(secretBase32, step * TOTP_PERIOD_SECONDS * 1000)
109
+ if (safeEqual(clean, expected))
110
+ return step
111
+ }
112
+ return undefined
113
+ }
114
+
115
+ function normalizeRecoveryCode(code: string): string {
116
+ return code.replace(/[\s-]+/g, '').toUpperCase()
117
+ }
118
+
119
+ function generateRecoveryCodeBatch(userId: string): { plain: string[], records: RecoveryCodeRecord[] } {
120
+ const now = Date.now()
121
+ const plain: string[] = []
122
+ const records: RecoveryCodeRecord[] = []
123
+ for (let i = 0; i < RECOVERY_CODE_COUNT; i++) {
124
+ const bytes = new Uint8Array(8)
125
+ crypto.getRandomValues(bytes)
126
+ let raw = ''
127
+ for (let j = 0; j < 8; j++)
128
+ raw += RECOVERY_ALPHABET[bytes[j]! & 31]!
129
+ const formatted = `${raw.slice(0, 4)}-${raw.slice(4)}`
130
+ const salt = randomToken(16)
131
+ plain.push(formatted)
132
+ records.push({
133
+ id: crypto.randomUUID(),
134
+ userId,
135
+ codeHash: sha256Hex(`${salt}:${raw}`),
136
+ salt,
137
+ createdAt: now,
138
+ })
139
+ }
140
+ return { plain, records }
141
+ }
142
+
143
+ export interface TotpManagerDeps<TUser extends AuthUser = AuthUser> {
144
+ store: AuthStore<TUser>
145
+ sessions: SessionManager<TUser>
146
+ /** The app's signing secret, resolved at first use. */
147
+ secret: () => string
148
+ twoFactorCookieName: string
149
+ getDefaultIssuer: () => string
150
+ isSecureCookie: (ctx: RequestContext) => boolean
151
+ }
152
+
153
+ export interface TotpManager {
154
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
155
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
156
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
157
+ disableTotp(userId: string, code: string): Promise<boolean>
158
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
159
+ getTwoFactorMethods(userId: string): Promise<TwoFactorMethod[]>
160
+ issuePendingCookie(ctx: RequestContext, userId: string, redirect: string, methods: TwoFactorMethod[]): void
161
+ readPendingCookie(ctx: RequestContext): PendingTwoFactor | undefined
162
+ clearPendingCookie(ctx: RequestContext): void
163
+ }
164
+
165
+ function requireTotpStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
166
+ if (!store.getTotp || !store.setTotp || !store.deleteTotp || !store.listRecoveryCodes || !store.setRecoveryCodes || !store.consumeRecoveryCode || !store.deleteRecoveryCodes)
167
+ throw new Error('prunelle: configured AuthStore does not support TOTP')
168
+ return {
169
+ getTotp: store.getTotp.bind(store),
170
+ setTotp: store.setTotp.bind(store),
171
+ deleteTotp: store.deleteTotp.bind(store),
172
+ listRecoveryCodes: store.listRecoveryCodes.bind(store),
173
+ setRecoveryCodes: store.setRecoveryCodes.bind(store),
174
+ consumeRecoveryCode: store.consumeRecoveryCode.bind(store),
175
+ deleteRecoveryCodes: store.deleteRecoveryCodes.bind(store),
176
+ }
177
+ }
178
+
179
+ function createKeyedLock() {
180
+ const queues = new Map<string, Promise<void>>()
181
+ return async function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
182
+ const prev = queues.get(key) ?? Promise.resolve()
183
+ let release!: () => void
184
+ const current = new Promise<void>((resolve) => { release = resolve })
185
+ const tail = prev.then(() => current)
186
+ queues.set(key, tail)
187
+ await prev
188
+ try {
189
+ return await fn()
190
+ }
191
+ finally {
192
+ release()
193
+ if (queues.get(key) === tail)
194
+ queues.delete(key)
195
+ }
196
+ }
197
+ }
198
+
199
+ export function respondTwoFactorChallenge(
200
+ totp: Pick<TotpManager, 'issuePendingCookie'>,
201
+ ctx: RequestContext,
202
+ userId: string,
203
+ redirectTarget: string,
204
+ twoFactorRedirect: string,
205
+ methods: TwoFactorMethod[],
206
+ redirectStatus: 302 | 303 = 303,
207
+ ): Response {
208
+ totp.issuePendingCookie(ctx, userId, redirectTarget, methods)
209
+ if (wantsJson(ctx.request))
210
+ return ctx.json({ ok: true, twoFactorRequired: true, methods, userId }, { status: 200 })
211
+ const sep = twoFactorRedirect.includes('?') ? '&' : '?'
212
+ return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, redirectStatus)
213
+ }
214
+
215
+ function createPendingCookieHelpers(
216
+ secret: () => string,
217
+ twoFactorCookieName: string,
218
+ isSecureCookie: (ctx: RequestContext) => boolean,
219
+ ): Pick<TotpManager, 'issuePendingCookie' | 'readPendingCookie' | 'clearPendingCookie'> {
220
+ return {
221
+ issuePendingCookie(ctx, userId, redirect, methods) {
222
+ const payload: PendingTwoFactor = {
223
+ userId,
224
+ redirect,
225
+ methods,
226
+ exp: Date.now() + PENDING_2FA_TTL_MS,
227
+ }
228
+ ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
229
+ },
230
+
231
+ readPendingCookie(ctx) {
232
+ const raw = ctx.cookies.get(twoFactorCookieName)
233
+ if (!raw)
234
+ return undefined
235
+ const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
236
+ if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
237
+ return undefined
238
+ return parsed
239
+ },
240
+
241
+ clearPendingCookie(ctx) {
242
+ ctx.cookies.delete(twoFactorCookieName, { path: '/' })
243
+ },
244
+ }
245
+ }
246
+
247
+ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpManagerDeps<TUser>): TotpManager {
248
+ const { store, sessions, secret, twoFactorCookieName, getDefaultIssuer, isSecureCookie } = deps
249
+ const withUserLock = createKeyedLock()
250
+
251
+ async function tryConsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean> {
252
+ const ts = requireTotpStore(store)
253
+ const normalized = normalizeRecoveryCode(rawCode)
254
+ if (normalized.length < 6)
255
+ return false
256
+ const records = await sessions.observeAsync(ts.listRecoveryCodes(userId))
257
+ for (const rec of records) {
258
+ const candidate = sha256Hex(`${rec.salt}:${normalized}`)
259
+ if (safeEqual(candidate, rec.codeHash)) {
260
+ const consumed = await sessions.observeAsync(ts.consumeRecoveryCode(rec.id))
261
+ if (consumed)
262
+ return true
263
+ }
264
+ }
265
+ return false
266
+ }
267
+
268
+ async function claimTotpStep(userId: string, encryptedSecret: string, matchedStep: number): Promise<boolean> {
269
+ const now = Date.now()
270
+ if (store.advanceTotpStep)
271
+ return await sessions.observeAsync(store.advanceTotpStep(userId, matchedStep, now))
272
+ return withUserLock(userId, async () => {
273
+ const ts = requireTotpStore(store)
274
+ const latest = await sessions.observeAsync(ts.getTotp(userId))
275
+ if (!latest || !latest.enabled || latest.encryptedSecret !== encryptedSecret)
276
+ return false
277
+ if (latest.lastUsedStep !== undefined && matchedStep <= latest.lastUsedStep)
278
+ return false
279
+ await sessions.observeAsync(ts.setTotp({ ...latest, lastUsedStep: matchedStep, updatedAt: now }))
280
+ return true
281
+ })
282
+ }
283
+
284
+ async function verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }> {
285
+ const ts = requireTotpStore(store)
286
+ const record = await sessions.observeAsync(ts.getTotp(userId))
287
+ if (!record || !record.enabled)
288
+ return { valid: false }
289
+
290
+ const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
291
+ const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
292
+ if (matchedStep !== undefined) {
293
+ const claimed = await claimTotpStep(userId, record.encryptedSecret, matchedStep)
294
+ return claimed ? { valid: true, method: 'totp' } : { valid: false }
295
+ }
296
+
297
+ if (await tryConsumeRecoveryCode(userId, code))
298
+ return { valid: true, method: 'recovery' }
299
+
300
+ return { valid: false }
301
+ }
302
+
303
+ return {
304
+ async setupTotp(userId, opts) {
305
+ const ts = requireTotpStore(store)
306
+ const user = await sessions.observeAsync(store.getUserById(userId))
307
+ if (!user)
308
+ throw new Error('prunelle: user not found')
309
+ const existing = await sessions.observeAsync(ts.getTotp(userId))
310
+ if (existing?.enabled)
311
+ throw new Error('prunelle: TOTP is already enabled for this account')
312
+
313
+ const base32Secret = generateTotpSecret()
314
+ const encryptedSecret = await encryptSecret(secret(), base32Secret)
315
+ const now = Date.now()
316
+ await sessions.observeAsync(ts.setTotp({
317
+ userId,
318
+ encryptedSecret,
319
+ enabled: false,
320
+ createdAt: now,
321
+ updatedAt: now,
322
+ }))
323
+ const issuer = opts?.issuer?.trim() || getDefaultIssuer()
324
+ return {
325
+ secret: base32Secret,
326
+ otpauthUrl: buildOtpauthUrl(issuer, user.email, base32Secret),
327
+ }
328
+ },
329
+
330
+ async confirmTotp(userId, code) {
331
+ const ts = requireTotpStore(store)
332
+ const record = await sessions.observeAsync(ts.getTotp(userId))
333
+ if (!record)
334
+ throw new Error('prunelle: no pending TOTP enrollment found')
335
+ if (record.enabled)
336
+ throw new Error('prunelle: TOTP is already enabled for this account')
337
+
338
+ const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
339
+ const matchedStep = matchTotpStep(plainSecret, code, Date.now())
340
+ if (matchedStep === undefined)
341
+ throw new Error('prunelle: invalid TOTP verification code')
342
+
343
+ const { plain, records } = generateRecoveryCodeBatch(userId)
344
+ await sessions.observeAsync(ts.setTotp({
345
+ ...record,
346
+ enabled: true,
347
+ lastUsedStep: matchedStep,
348
+ updatedAt: Date.now(),
349
+ }))
350
+ await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
351
+ return { enabled: true, recoveryCodes: plain }
352
+ },
353
+
354
+ verifyTotp,
355
+
356
+ async disableTotp(userId, code) {
357
+ const ts = requireTotpStore(store)
358
+ const result = await verifyTotp(userId, code)
359
+ if (!result.valid)
360
+ return false
361
+ await withUserLock(userId, async () => {
362
+ await sessions.observeAsync(ts.deleteTotp(userId))
363
+ await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
364
+ })
365
+ return true
366
+ },
367
+
368
+ async regenerateRecoveryCodes(userId) {
369
+ const ts = requireTotpStore(store)
370
+ const record = await sessions.observeAsync(ts.getTotp(userId))
371
+ if (!record || !record.enabled)
372
+ throw new Error('prunelle: TOTP is not enabled for this account')
373
+ const { plain, records } = generateRecoveryCodeBatch(userId)
374
+ await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
375
+ return plain
376
+ },
377
+
378
+ async getTwoFactorMethods(userId) {
379
+ if (!store.getTotp)
380
+ return []
381
+ const record = await sessions.observeAsync(store.getTotp(userId))
382
+ if (!record?.enabled)
383
+ return []
384
+ const methods: TwoFactorMethod[] = ['totp']
385
+ if (store.listPasskeys) {
386
+ const passkeys = await sessions.observeAsync(store.listPasskeys(userId))
387
+ if (passkeys.length > 0)
388
+ methods.push('passkey')
389
+ }
390
+ return methods
391
+ },
392
+
393
+ ...createPendingCookieHelpers(secret, twoFactorCookieName, isSecureCookie),
394
+ }
395
+ }
@@ -0,0 +1,284 @@
1
+ // Pure TypeScript + Web Crypto WebAuthn L2 primitives: minimal CBOR decoder,
2
+ // authenticatorData parser, COSE-to-JWK converter (ES256, RS256, EdDSA), and DER ECDSA verification.
3
+
4
+ import { sha256Bytes, toBase64Url } from './crypto'
5
+
6
+ const MAX_CBOR_DEPTH = 16
7
+
8
+ export const COSE_ALG_ES256 = -7
9
+ export const COSE_ALG_RS256 = -257
10
+ export const COSE_ALG_EDDSA = -8
11
+
12
+ interface CborDecodeResult {
13
+ value: unknown
14
+ nextOffset: number
15
+ }
16
+
17
+ function readCborUint(bytes: Uint8Array, offset: number, ai: number): { value: number, nextOffset: number } {
18
+ if (ai < 24)
19
+ return { value: ai, nextOffset: offset }
20
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
21
+ if (ai === 24) {
22
+ if (offset + 1 > bytes.length)
23
+ throw new Error('prunelle: truncated CBOR uint8')
24
+ return { value: bytes[offset]!, nextOffset: offset + 1 }
25
+ }
26
+ if (ai === 25) {
27
+ if (offset + 2 > bytes.length)
28
+ throw new Error('prunelle: truncated CBOR uint16')
29
+ return { value: view.getUint16(offset, false), nextOffset: offset + 2 }
30
+ }
31
+ if (ai === 26) {
32
+ if (offset + 4 > bytes.length)
33
+ throw new Error('prunelle: truncated CBOR uint32')
34
+ return { value: view.getUint32(offset, false), nextOffset: offset + 4 }
35
+ }
36
+ if (ai === 27) {
37
+ if (offset + 8 > bytes.length)
38
+ throw new Error('prunelle: truncated CBOR uint64')
39
+ const big = view.getBigUint64(offset, false)
40
+ if (big > BigInt(Number.MAX_SAFE_INTEGER))
41
+ throw new Error('prunelle: CBOR integer exceeds safe range')
42
+ return { value: Number(big), nextOffset: offset + 8 }
43
+ }
44
+ throw new Error(`prunelle: unsupported CBOR additional info ${ai}`)
45
+ }
46
+
47
+ function decodeCborSimple(bytes: Uint8Array, offset: number, ai: number): CborDecodeResult {
48
+ if (ai === 20)
49
+ return { value: false, nextOffset: offset }
50
+ if (ai === 21)
51
+ return { value: true, nextOffset: offset }
52
+ if (ai === 22)
53
+ return { value: null, nextOffset: offset }
54
+ if (ai === 23)
55
+ return { value: undefined, nextOffset: offset }
56
+ if (ai === 25 && offset + 2 <= bytes.length)
57
+ return { value: 0, nextOffset: offset + 2 }
58
+ if (ai === 26 && offset + 4 <= bytes.length) {
59
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
60
+ return { value: view.getFloat32(offset, false), nextOffset: offset + 4 }
61
+ }
62
+ if (ai === 27 && offset + 8 <= bytes.length) {
63
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
64
+ return { value: view.getFloat64(offset, false), nextOffset: offset + 8 }
65
+ }
66
+ throw new Error(`prunelle: unsupported CBOR simple value ${ai}`)
67
+ }
68
+
69
+ export function decodeCbor(bytes: Uint8Array, offset = 0, depth = 0): CborDecodeResult {
70
+ if (depth > MAX_CBOR_DEPTH)
71
+ throw new Error('prunelle: CBOR nesting limit exceeded')
72
+ if (offset >= bytes.length)
73
+ throw new Error('prunelle: unexpected end of CBOR data')
74
+
75
+ const initial = bytes[offset]!
76
+ const major = initial >>> 5
77
+ const ai = initial & 0x1F
78
+ let pos = offset + 1
79
+
80
+ if (major === 7)
81
+ return decodeCborSimple(bytes, pos, ai)
82
+
83
+ const arg = readCborUint(bytes, pos, ai)
84
+ pos = arg.nextOffset
85
+
86
+ if (major === 0)
87
+ return { value: arg.value, nextOffset: pos }
88
+ if (major === 1)
89
+ return { value: -1 - arg.value, nextOffset: pos }
90
+ if (major === 2) {
91
+ if (pos + arg.value > bytes.length)
92
+ throw new Error('prunelle: truncated CBOR byte string')
93
+ return { value: bytes.slice(pos, pos + arg.value), nextOffset: pos + arg.value }
94
+ }
95
+ if (major === 3) {
96
+ if (pos + arg.value > bytes.length)
97
+ throw new Error('prunelle: truncated CBOR text string')
98
+ return { value: new TextDecoder().decode(bytes.subarray(pos, pos + arg.value)), nextOffset: pos + arg.value }
99
+ }
100
+ if (major === 4) {
101
+ const arr: unknown[] = []
102
+ for (let i = 0; i < arg.value; i++) {
103
+ const item = decodeCbor(bytes, pos, depth + 1)
104
+ arr.push(item.value)
105
+ pos = item.nextOffset
106
+ }
107
+ return { value: arr, nextOffset: pos }
108
+ }
109
+ if (major === 5) {
110
+ const map = new Map<unknown, unknown>()
111
+ for (let i = 0; i < arg.value; i++) {
112
+ const k = decodeCbor(bytes, pos, depth + 1)
113
+ const v = decodeCbor(bytes, k.nextOffset, depth + 1)
114
+ map.set(k.value, v.value)
115
+ pos = v.nextOffset
116
+ }
117
+ return { value: map, nextOffset: pos }
118
+ }
119
+ if (major === 6)
120
+ return decodeCbor(bytes, pos, depth + 1)
121
+ throw new Error(`prunelle: unsupported CBOR major type ${major}`)
122
+ }
123
+
124
+ export interface ParsedAuthData {
125
+ rpIdHash: Uint8Array
126
+ flags: number
127
+ up: boolean
128
+ uv: boolean
129
+ at: boolean
130
+ signCount: number
131
+ aaguid?: string | undefined
132
+ credentialId?: Uint8Array | undefined
133
+ cosePublicKey?: Map<unknown, unknown> | undefined
134
+ }
135
+
136
+ function formatAaguid(bytes: Uint8Array): string {
137
+ const hex = Buffer.from(bytes).toString('hex')
138
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
139
+ }
140
+
141
+ export function parseAuthenticatorData(authData: Uint8Array): ParsedAuthData {
142
+ if (authData.length < 37)
143
+ throw new Error('prunelle: authenticatorData too short')
144
+ const view = new DataView(authData.buffer, authData.byteOffset, authData.byteLength)
145
+ const rpIdHash = authData.slice(0, 32)
146
+ const flags = authData[32]!
147
+ const up = (flags & 0x01) !== 0
148
+ const uv = (flags & 0x04) !== 0
149
+ const at = (flags & 0x40) !== 0
150
+ const signCount = view.getUint32(33, false)
151
+
152
+ if (!at)
153
+ return { rpIdHash, flags, up, uv, at, signCount }
154
+
155
+ if (authData.length < 55)
156
+ throw new Error('prunelle: attested credential data truncated')
157
+ const aaguid = formatAaguid(authData.subarray(37, 53))
158
+ const credIdLen = view.getUint16(53, false)
159
+ if (credIdLen === 0 || 55 + credIdLen >= authData.length)
160
+ throw new Error('prunelle: invalid credential ID length')
161
+ const credentialId = authData.slice(55, 55 + credIdLen)
162
+ const decoded = decodeCbor(authData, 55 + credIdLen)
163
+ if (!(decoded.value instanceof Map))
164
+ throw new Error('prunelle: COSE public key must be a CBOR map')
165
+
166
+ return { rpIdHash, flags, up, uv, at, signCount, aaguid, credentialId, cosePublicKey: decoded.value }
167
+ }
168
+
169
+ export function coseKeyToJwk(cose: Map<unknown, unknown>): { algorithm: number, jwk: JsonWebKey } {
170
+ const kty = cose.get(1)
171
+ const alg = cose.get(3)
172
+
173
+ if (kty === 2 && alg === COSE_ALG_ES256) {
174
+ const crv = cose.get(-1)
175
+ const x = cose.get(-2)
176
+ const y = cose.get(-3)
177
+ if (crv !== 1 || !(x instanceof Uint8Array) || !(y instanceof Uint8Array) || x.length !== 32 || y.length !== 32)
178
+ throw new Error('prunelle: invalid ES256 COSE public key')
179
+ return {
180
+ algorithm: COSE_ALG_ES256,
181
+ jwk: { kty: 'EC', crv: 'P-256', x: toBase64Url(x), y: toBase64Url(y), ext: true },
182
+ }
183
+ }
184
+
185
+ if (kty === 3 && alg === COSE_ALG_RS256) {
186
+ const n = cose.get(-1)
187
+ const e = cose.get(-2)
188
+ if (!(n instanceof Uint8Array) || !(e instanceof Uint8Array) || n.length === 0 || e.length === 0)
189
+ throw new Error('prunelle: invalid RS256 COSE public key')
190
+ return {
191
+ algorithm: COSE_ALG_RS256,
192
+ jwk: { kty: 'RSA', n: toBase64Url(n), e: toBase64Url(e), ext: true },
193
+ }
194
+ }
195
+
196
+ if (kty === 1 && alg === COSE_ALG_EDDSA) {
197
+ const crv = cose.get(-1)
198
+ const x = cose.get(-2)
199
+ if (crv !== 6 || !(x instanceof Uint8Array) || x.length !== 32)
200
+ throw new Error('prunelle: invalid EdDSA COSE public key')
201
+ return {
202
+ algorithm: COSE_ALG_EDDSA,
203
+ jwk: { kty: 'OKP', crv: 'Ed25519', x: toBase64Url(x), ext: true },
204
+ }
205
+ }
206
+
207
+ throw new Error(`prunelle: unsupported COSE key algorithm (${String(alg)})`)
208
+ }
209
+
210
+ function readDerLength(der: Uint8Array, offset: number): { length: number, nextOffset: number } {
211
+ if (offset >= der.length)
212
+ throw new Error('prunelle: truncated DER length')
213
+ const first = der[offset]!
214
+ if (first < 0x80)
215
+ return { length: first, nextOffset: offset + 1 }
216
+ const count = first & 0x7F
217
+ if (count === 0 || count > 2 || offset + 1 + count > der.length)
218
+ throw new Error('prunelle: unsupported DER length')
219
+ let length = 0
220
+ for (let i = 0; i < count; i++)
221
+ length = (length << 8) | der[offset + 1 + i]!
222
+ return { length, nextOffset: offset + 1 + count }
223
+ }
224
+
225
+ function readDerInteger(der: Uint8Array, offset: number, coordSize: number): { value: Uint8Array, nextOffset: number } {
226
+ if (offset >= der.length || der[offset] !== 0x02)
227
+ throw new Error('prunelle: expected DER integer tag')
228
+ const { length, nextOffset } = readDerLength(der, offset + 1)
229
+ if (length === 0 || nextOffset + length > der.length)
230
+ throw new Error('prunelle: truncated DER integer')
231
+ let slice = der.subarray(nextOffset, nextOffset + length)
232
+ if (slice[0] === 0x00 && slice.length > 1)
233
+ slice = slice.subarray(1)
234
+ if (slice.length > coordSize)
235
+ throw new Error('prunelle: DER integer exceeds coordinate size')
236
+ const out = new Uint8Array(coordSize)
237
+ out.set(slice, coordSize - slice.length)
238
+ return { value: out, nextOffset: nextOffset + length }
239
+ }
240
+
241
+ export function derToRawEcdsa(der: Uint8Array, coordSize = 32): Uint8Array {
242
+ if (der.length < 8 || der[0] !== 0x30)
243
+ throw new Error('prunelle: invalid DER ECDSA signature')
244
+ const seq = readDerLength(der, 1)
245
+ if (seq.nextOffset + seq.length !== der.length)
246
+ throw new Error('prunelle: DER ECDSA sequence length mismatch')
247
+ const r = readDerInteger(der, seq.nextOffset, coordSize)
248
+ const s = readDerInteger(der, r.nextOffset, coordSize)
249
+ if (s.nextOffset !== der.length)
250
+ throw new Error('prunelle: trailing bytes in DER ECDSA signature')
251
+ const raw = new Uint8Array(coordSize * 2)
252
+ raw.set(r.value, 0)
253
+ raw.set(s.value, coordSize)
254
+ return raw
255
+ }
256
+
257
+ export async function verifyWebAuthnSignature(
258
+ publicKeyJwkJson: string,
259
+ algorithm: number,
260
+ signature: Uint8Array,
261
+ authenticatorData: Uint8Array,
262
+ clientDataJsonBytes: Uint8Array,
263
+ ): Promise<boolean> {
264
+ const jwk = JSON.parse(publicKeyJwkJson) as JsonWebKey
265
+ const clientHash = sha256Bytes(clientDataJsonBytes)
266
+ const signedData = new Uint8Array(authenticatorData.length + clientHash.length)
267
+ signedData.set(authenticatorData, 0)
268
+ signedData.set(clientHash, authenticatorData.length)
269
+
270
+ if (algorithm === COSE_ALG_ES256) {
271
+ const key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
272
+ const rawSig = derToRawEcdsa(signature, 32)
273
+ return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, new Uint8Array(rawSig), new Uint8Array(signedData))
274
+ }
275
+ if (algorithm === COSE_ALG_RS256) {
276
+ const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify'])
277
+ return crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, key, new Uint8Array(signature), new Uint8Array(signedData))
278
+ }
279
+ if (algorithm === COSE_ALG_EDDSA) {
280
+ const key = await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify'])
281
+ return crypto.subtle.verify({ name: 'Ed25519' }, key, new Uint8Array(signature), new Uint8Array(signedData))
282
+ }
283
+ throw new Error(`prunelle: unsupported passkey algorithm ${algorithm}`)
284
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.