@prunellejs/auth 0.1.1 → 0.7.0
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/LICENSE +21 -0
- package/llms.txt +53 -23
- package/package.json +5 -4
- package/src/account.ts +101 -0
- package/src/crypto.ts +57 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +132 -24
- package/src/index.ts +312 -234
- package/src/links.ts +154 -0
- package/src/oauth-routes.ts +112 -53
- package/src/org-routes.ts +216 -0
- package/src/orgs.ts +403 -0
- package/src/passkey-client.ts +207 -0
- package/src/passkey-routes.ts +210 -0
- package/src/passkeys.ts +421 -0
- package/src/routes.ts +160 -120
- package/src/session-cookie.ts +55 -0
- package/src/session.ts +157 -104
- package/src/sqlite-ext.ts +516 -0
- package/src/sqlite.ts +136 -71
- package/src/store-ext.ts +425 -0
- package/src/store.ts +120 -48
- package/src/totp-routes.ts +144 -0
- package/src/totp.ts +334 -0
- package/src/webauthn-crypto.ts +284 -0
package/src/totp.ts
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
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 } 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
|
+
export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpManagerDeps<TUser>): TotpManager {
|
|
180
|
+
const { store, sessions, secret, twoFactorCookieName, getDefaultIssuer, isSecureCookie } = deps
|
|
181
|
+
|
|
182
|
+
async function tryConsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean> {
|
|
183
|
+
const ts = requireTotpStore(store)
|
|
184
|
+
const normalized = normalizeRecoveryCode(rawCode)
|
|
185
|
+
if (normalized.length < 6)
|
|
186
|
+
return false
|
|
187
|
+
const records = await sessions.observeAsync(ts.listRecoveryCodes(userId))
|
|
188
|
+
for (const rec of records) {
|
|
189
|
+
const candidate = sha256Hex(`${rec.salt}:${normalized}`)
|
|
190
|
+
if (safeEqual(candidate, rec.codeHash)) {
|
|
191
|
+
const consumed = await sessions.observeAsync(ts.consumeRecoveryCode(rec.id))
|
|
192
|
+
if (consumed)
|
|
193
|
+
return true
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return false
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }> {
|
|
200
|
+
const ts = requireTotpStore(store)
|
|
201
|
+
const record = await sessions.observeAsync(ts.getTotp(userId))
|
|
202
|
+
if (!record || !record.enabled)
|
|
203
|
+
return { valid: false }
|
|
204
|
+
|
|
205
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
206
|
+
const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
|
|
207
|
+
if (matchedStep !== undefined) {
|
|
208
|
+
await sessions.observeAsync(ts.setTotp({
|
|
209
|
+
...record,
|
|
210
|
+
lastUsedStep: matchedStep,
|
|
211
|
+
updatedAt: Date.now(),
|
|
212
|
+
}))
|
|
213
|
+
return { valid: true, method: 'totp' }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (await tryConsumeRecoveryCode(userId, code))
|
|
217
|
+
return { valid: true, method: 'recovery' }
|
|
218
|
+
|
|
219
|
+
return { valid: false }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
async setupTotp(userId, opts) {
|
|
224
|
+
const ts = requireTotpStore(store)
|
|
225
|
+
const user = await sessions.observeAsync(store.getUserById(userId))
|
|
226
|
+
if (!user)
|
|
227
|
+
throw new Error('prunelle: user not found')
|
|
228
|
+
const existing = await sessions.observeAsync(ts.getTotp(userId))
|
|
229
|
+
if (existing?.enabled)
|
|
230
|
+
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
231
|
+
|
|
232
|
+
const base32Secret = generateTotpSecret()
|
|
233
|
+
const encryptedSecret = await encryptSecret(secret(), base32Secret)
|
|
234
|
+
const now = Date.now()
|
|
235
|
+
await sessions.observeAsync(ts.setTotp({
|
|
236
|
+
userId,
|
|
237
|
+
encryptedSecret,
|
|
238
|
+
enabled: false,
|
|
239
|
+
createdAt: now,
|
|
240
|
+
updatedAt: now,
|
|
241
|
+
}))
|
|
242
|
+
const issuer = opts?.issuer?.trim() || getDefaultIssuer()
|
|
243
|
+
return {
|
|
244
|
+
secret: base32Secret,
|
|
245
|
+
otpauthUrl: buildOtpauthUrl(issuer, user.email, base32Secret),
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
async confirmTotp(userId, code) {
|
|
250
|
+
const ts = requireTotpStore(store)
|
|
251
|
+
const record = await sessions.observeAsync(ts.getTotp(userId))
|
|
252
|
+
if (!record)
|
|
253
|
+
throw new Error('prunelle: no pending TOTP enrollment found')
|
|
254
|
+
if (record.enabled)
|
|
255
|
+
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
256
|
+
|
|
257
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
258
|
+
const matchedStep = matchTotpStep(plainSecret, code, Date.now())
|
|
259
|
+
if (matchedStep === undefined)
|
|
260
|
+
throw new Error('prunelle: invalid TOTP verification code')
|
|
261
|
+
|
|
262
|
+
const { plain, records } = generateRecoveryCodeBatch(userId)
|
|
263
|
+
await sessions.observeAsync(ts.setTotp({
|
|
264
|
+
...record,
|
|
265
|
+
enabled: true,
|
|
266
|
+
lastUsedStep: matchedStep,
|
|
267
|
+
updatedAt: Date.now(),
|
|
268
|
+
}))
|
|
269
|
+
await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
|
|
270
|
+
return { enabled: true, recoveryCodes: plain }
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
verifyTotp,
|
|
274
|
+
|
|
275
|
+
async disableTotp(userId, code) {
|
|
276
|
+
const ts = requireTotpStore(store)
|
|
277
|
+
const result = await verifyTotp(userId, code)
|
|
278
|
+
if (!result.valid)
|
|
279
|
+
return false
|
|
280
|
+
await sessions.observeAsync(ts.deleteTotp(userId))
|
|
281
|
+
await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
|
|
282
|
+
return true
|
|
283
|
+
},
|
|
284
|
+
|
|
285
|
+
async regenerateRecoveryCodes(userId) {
|
|
286
|
+
const ts = requireTotpStore(store)
|
|
287
|
+
const record = await sessions.observeAsync(ts.getTotp(userId))
|
|
288
|
+
if (!record || !record.enabled)
|
|
289
|
+
throw new Error('prunelle: TOTP is not enabled for this account')
|
|
290
|
+
const { plain, records } = generateRecoveryCodeBatch(userId)
|
|
291
|
+
await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
|
|
292
|
+
return plain
|
|
293
|
+
},
|
|
294
|
+
|
|
295
|
+
async getTwoFactorMethods(userId) {
|
|
296
|
+
if (!store.getTotp)
|
|
297
|
+
return []
|
|
298
|
+
const record = await sessions.observeAsync(store.getTotp(userId))
|
|
299
|
+
if (!record?.enabled)
|
|
300
|
+
return []
|
|
301
|
+
const methods: TwoFactorMethod[] = ['totp']
|
|
302
|
+
if (store.listPasskeys) {
|
|
303
|
+
const passkeys = await sessions.observeAsync(store.listPasskeys(userId))
|
|
304
|
+
if (passkeys.length > 0)
|
|
305
|
+
methods.push('passkey')
|
|
306
|
+
}
|
|
307
|
+
return methods
|
|
308
|
+
},
|
|
309
|
+
|
|
310
|
+
issuePendingCookie(ctx, userId, redirect, methods) {
|
|
311
|
+
const payload: PendingTwoFactor = {
|
|
312
|
+
userId,
|
|
313
|
+
redirect,
|
|
314
|
+
methods,
|
|
315
|
+
exp: Date.now() + PENDING_2FA_TTL_MS,
|
|
316
|
+
}
|
|
317
|
+
ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
|
|
318
|
+
},
|
|
319
|
+
|
|
320
|
+
readPendingCookie(ctx) {
|
|
321
|
+
const raw = ctx.cookies.get(twoFactorCookieName)
|
|
322
|
+
if (!raw)
|
|
323
|
+
return undefined
|
|
324
|
+
const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
|
|
325
|
+
if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
|
|
326
|
+
return undefined
|
|
327
|
+
return parsed
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
clearPendingCookie(ctx) {
|
|
331
|
+
ctx.cookies.delete(twoFactorCookieName, { path: '/' })
|
|
332
|
+
},
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -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
|
+
}
|