@tylix/auth 1.4.0 → 2.0.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.
Files changed (65) hide show
  1. package/README.md +284 -14
  2. package/package.json +95 -9
  3. package/src/client/client.d.ts +14 -0
  4. package/src/client/client.js +83 -0
  5. package/src/cookies/authCookies.d.ts +8 -6
  6. package/src/cookies/authCookies.js +43 -28
  7. package/src/core/crypto.js +143 -0
  8. package/src/core/keys.js +83 -0
  9. package/src/core/seal.js +43 -0
  10. package/src/generators/AuthGenerator.d.ts +9 -3
  11. package/src/generators/AuthGenerator.js +16 -4
  12. package/src/generators/templates/auth-controller-ts.tyx +401 -98
  13. package/src/generators/templates/auth-controller.tyx +384 -96
  14. package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
  15. package/src/generators/templates/auth-session-migration.tyx +32 -0
  16. package/src/generators/templates/auth-session-model-ts.tyx +53 -0
  17. package/src/generators/templates/auth-session-model.tyx +34 -0
  18. package/src/generators/templates/auth-validator-ts.tyx +17 -0
  19. package/src/generators/templates/auth-validator.tyx +17 -0
  20. package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
  21. package/src/generators/templates/oauth-account-migration.tyx +27 -0
  22. package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
  23. package/src/generators/templates/oauth-account-model.tyx +45 -0
  24. package/src/generators/templates/password-reset-model-ts.tyx +26 -4
  25. package/src/generators/templates/password-reset-model.tyx +26 -4
  26. package/src/generators/templates/reset-password-view.html +30 -3
  27. package/src/generators/templates/verify-email-view.html +30 -3
  28. package/src/http/cookies.js +91 -0
  29. package/src/http/origin.js +68 -0
  30. package/src/http/request.js +179 -0
  31. package/src/index.d.ts +9 -1
  32. package/src/index.js +5 -0
  33. package/src/integrations/h3.d.ts +6 -0
  34. package/src/integrations/h3.js +70 -0
  35. package/src/integrations/hono.d.ts +6 -0
  36. package/src/integrations/hono.js +36 -0
  37. package/src/integrations/next.d.ts +16 -0
  38. package/src/integrations/next.js +36 -0
  39. package/src/integrations/node.d.ts +7 -0
  40. package/src/integrations/node.js +87 -0
  41. package/src/integrations/routes.js +92 -0
  42. package/src/integrations/sveltekit.d.ts +5 -0
  43. package/src/integrations/sveltekit.js +52 -0
  44. package/src/integrations/web.js +69 -0
  45. package/src/mfa/totp.js +150 -0
  46. package/src/oauth/oauth.js +142 -0
  47. package/src/oauth/providers.js +112 -0
  48. package/src/password/hashPassword.d.ts +5 -1
  49. package/src/password/hashPassword.js +96 -30
  50. package/src/password/index.d.ts +2 -0
  51. package/src/password/index.js +2 -0
  52. package/src/password/policy.js +108 -0
  53. package/src/rateLimiter/loginRateLimiter.js +16 -6
  54. package/src/ratelimit/limiter.js +129 -0
  55. package/src/session/adapters/keyValue.js +87 -0
  56. package/src/session/adapters/memory.js +38 -0
  57. package/src/session/adapters/model.js +97 -0
  58. package/src/session/adapters/prisma.js +67 -0
  59. package/src/session/adapters/sql.js +128 -0
  60. package/src/session/createAuth.js +420 -0
  61. package/src/token/jwt.js +144 -0
  62. package/src/token/signToken.js +41 -22
  63. package/src/tylix/accessTokens.js +61 -0
  64. package/src/web.d.ts +359 -0
  65. package/src/web.js +47 -0
@@ -0,0 +1,420 @@
1
+ import { base64urlEncode, hmacSign, randomToken, timingSafeEqual } from '../core/crypto.js'
2
+ import { createKeyring, isProduction, toSeconds } from '../core/keys.js'
3
+ import { createSealer } from '../core/seal.js'
4
+ import { createTokenSigner } from '../token/jwt.js'
5
+ import { expireCookie, serializeCookie } from '../http/cookies.js'
6
+ import { getClientIp, getCookiesAll, getHeader, isSecureRequest } from '../http/request.js'
7
+ import { isCrossSiteRequest } from '../http/origin.js'
8
+ import { memoryAdapter } from './adapters/memory.js'
9
+
10
+ // Sessions for any framework.
11
+ //
12
+ // A login creates a server-side session and two cookies:
13
+ // access a short-lived signed JWT (default 15 min). Verifying it needs
14
+ // no database, so it works in edge middleware.
15
+ // refresh "<sessionId>.<secret>", httpOnly, path-scoped. Only an HMAC
16
+ // of it is stored. Every refresh ROTATES it; presenting an old
17
+ // one again (outside a short grace period for parallel tabs)
18
+ // means it was copied, and the whole session is revoked.
19
+ //
20
+ // Sessions have an absolute lifetime and an idle timeout, can be listed
21
+ // ("your devices") and revoked one by one or all at once, and a login
22
+ // always replaces whatever session the browser had (no fixation).
23
+
24
+ const SESSION_ID = /^[A-Za-z0-9_-]{22}$/
25
+ const SECRET = /^[A-Za-z0-9_-]{43}$/
26
+
27
+ function publicSession(record, currentId) {
28
+ if (!record) return null
29
+ const { tokenHash, prevTokenHash, rotatedAt, ...rest } = record
30
+ return currentId === undefined ? rest : { ...rest, current: record.id === currentId }
31
+ }
32
+
33
+ function parseRefreshToken(value) {
34
+ if (typeof value !== 'string') return null
35
+ const dot = value.indexOf('.')
36
+ if (dot === -1) return null
37
+ const id = value.slice(0, dot)
38
+ const secret = value.slice(dot + 1)
39
+ if (!SESSION_ID.test(id) || !SECRET.test(secret)) return null
40
+ return { id, secret }
41
+ }
42
+
43
+ export function createAuth(options = {}) {
44
+ const {
45
+ secret,
46
+ adapter = memoryAdapter(),
47
+ issuer,
48
+ audience,
49
+ accessTokenTtl = '15m',
50
+ sessionTtl = '30d',
51
+ shortSessionTtl = '1d',
52
+ idleTimeout = '14d',
53
+ rotationGrace = '30s',
54
+ trustProxy = false,
55
+ trustedOrigins = [],
56
+ checkRevocation = true,
57
+ allowBearer = true,
58
+ csrf = true,
59
+ storeIp = true,
60
+ storeUserAgent = true,
61
+ claims: extraClaims,
62
+ validateSession,
63
+ onEvent,
64
+ } = options
65
+
66
+ const cookieOptions = {
67
+ accessName: 'auth.access',
68
+ refreshName: 'auth.refresh',
69
+ prefix: true,
70
+ refreshPath: '/api/auth',
71
+ sameSite: 'lax',
72
+ domain: undefined,
73
+ secure: 'auto',
74
+ legacyRefreshPaths: [],
75
+ ...options.cookies,
76
+ }
77
+
78
+ if (adapter.ephemeral && isProduction()) {
79
+ console.warn('[@tylix/auth] Sessions are kept in memory: they vanish on restart and are not shared between servers. Pass an `adapter`.')
80
+ }
81
+
82
+ const keyring = createKeyring(secret)
83
+ const tokens = createTokenSigner({ keyring, issuer, audience })
84
+ const sealer = createSealer({ keyring })
85
+
86
+ const accessTtl = toSeconds(accessTokenTtl, 'accessTokenTtl')
87
+ const longTtlMs = toSeconds(sessionTtl, 'sessionTtl') * 1000
88
+ const shortTtlMs = toSeconds(shortSessionTtl, 'shortSessionTtl') * 1000
89
+ const idleMs = toSeconds(idleTimeout, 'idleTimeout') * 1000
90
+ const graceMs = toSeconds(rotationGrace, 'rotationGrace') * 1000
91
+
92
+ const emit = (type, details) => {
93
+ if (typeof onEvent !== 'function') return
94
+ try {
95
+ Promise.resolve(onEvent({ type, at: new Date().toISOString(), ...details })).catch(() => {})
96
+ } catch {}
97
+ }
98
+
99
+ // --- cookies ---------------------------------------------------------
100
+
101
+ function secureFor(request) {
102
+ if (cookieOptions.secure === true || cookieOptions.secure === false) return cookieOptions.secure
103
+ return isProduction() || (request ? isSecureRequest(request, { trustProxy }) : false)
104
+ }
105
+
106
+ // __Host- (access, Path=/) and __Secure- (refresh) prefixes stop a
107
+ // sibling subdomain or an http:// page from planting or overwriting the
108
+ // cookies. They need HTTPS, so plain-http dev uses the bare names.
109
+ function cookieNames(request) {
110
+ const secure = secureFor(request)
111
+ if (!cookieOptions.prefix || !secure) {
112
+ return { access: cookieOptions.accessName, refresh: cookieOptions.refreshName, secure }
113
+ }
114
+ return {
115
+ access: `${cookieOptions.domain ? '__Secure-' : '__Host-'}${cookieOptions.accessName}`,
116
+ refresh: `__Secure-${cookieOptions.refreshName}`,
117
+ secure,
118
+ }
119
+ }
120
+
121
+ function base(secure) {
122
+ return { secure, httpOnly: true, sameSite: cookieOptions.sameSite, domain: cookieOptions.domain }
123
+ }
124
+
125
+ function sessionCookies(request, { accessToken, refreshToken, session }) {
126
+ const names = cookieNames(request)
127
+ const opts = base(names.secure)
128
+ const out = []
129
+ if (accessToken) {
130
+ out.push(serializeCookie(names.access, accessToken, { ...opts, path: '/', maxAge: session?.persistent === false ? undefined : accessTtl }))
131
+ }
132
+ if (refreshToken) {
133
+ const maxAge = session?.persistent === false ? undefined : Math.max(0, Math.floor((session.expiresAt - Date.now()) / 1000))
134
+ out.push(serializeCookie(names.refresh, refreshToken, { ...opts, path: cookieOptions.refreshPath, priority: 'High', maxAge }))
135
+ for (const path of cookieOptions.legacyRefreshPaths) out.push(expireCookie(names.refresh, { ...opts, path }))
136
+ }
137
+ return out
138
+ }
139
+
140
+ function clearCookies(request) {
141
+ const names = cookieNames(request)
142
+ const opts = base(names.secure)
143
+ return [
144
+ expireCookie(names.access, { ...opts, path: '/' }),
145
+ expireCookie(names.refresh, { ...opts, path: cookieOptions.refreshPath }),
146
+ ...cookieOptions.legacyRefreshPaths.map((path) => expireCookie(names.refresh, { ...opts, path })),
147
+ ]
148
+ }
149
+
150
+ // --- refresh tokens ---------------------------------------------------
151
+
152
+ async function hashSecret(id, value, index = 0) {
153
+ return base64urlEncode(await hmacSign(await keyring.hmac('refresh', index), `${id}.${value}`))
154
+ }
155
+
156
+ // Which stored hash (current/previous) the presented secret matches,
157
+ // trying every configured key so rotation of AUTH_SECRET keeps sessions.
158
+ async function matchSecret(record, value) {
159
+ for (let i = 0; i < keyring.size; i++) {
160
+ const hash = await hashSecret(record.id, value, i)
161
+ if (record.tokenHash && timingSafeEqual(hash, record.tokenHash)) return 'current'
162
+ if (record.prevTokenHash && timingSafeEqual(hash, record.prevTokenHash)) return 'previous'
163
+ }
164
+ return null
165
+ }
166
+
167
+ function readRefreshCandidates(request) {
168
+ const all = getCookiesAll(request)[cookieNames(request).refresh] ?? []
169
+ return all.map(parseRefreshToken).filter(Boolean)
170
+ }
171
+
172
+ function isExpired(record, now = Date.now()) {
173
+ return record.expiresAt <= now || (record.idleExpiresAt != null && record.idleExpiresAt <= now)
174
+ }
175
+
176
+ async function issueAccessToken(record) {
177
+ const extra = typeof extraClaims === 'function' ? await extraClaims(publicSession(record)) : {}
178
+ return tokens.sign({ ...extra, sid: record.id, uid: record.userId }, { type: 'access', expiresIn: accessTtl, subject: record.userId })
179
+ }
180
+
181
+ function requestMeta(request) {
182
+ if (!request) return {}
183
+ return {
184
+ ip: storeIp ? getClientIp(request, { trustProxy }) : null,
185
+ userAgent: storeUserAgent ? (getHeader(request, 'user-agent') ?? '').slice(0, 512) || null : null,
186
+ }
187
+ }
188
+
189
+ // --- public API ---------------------------------------------------------
190
+
191
+ async function signIn(request, userId, { persistent = true, data = null } = {}) {
192
+ if (userId == null || userId === '') throw new TypeError('signIn needs a user id')
193
+
194
+ // Whatever session this browser had is ended first: a login must
195
+ // never continue a session someone else may have planted.
196
+ if (request) {
197
+ for (const candidate of readRefreshCandidates(request)) {
198
+ const existing = await adapter.get(candidate.id)
199
+ if (existing && (await matchSecret(existing, candidate.secret))) await adapter.delete(existing.id)
200
+ }
201
+ }
202
+
203
+ const now = Date.now()
204
+ const id = randomToken(16)
205
+ const value = randomToken(32)
206
+ const expiresAt = now + (persistent ? longTtlMs : shortTtlMs)
207
+ const meta = requestMeta(request)
208
+ const record = {
209
+ id,
210
+ userId,
211
+ tokenHash: await hashSecret(id, value),
212
+ prevTokenHash: null,
213
+ rotatedAt: null,
214
+ createdAt: now,
215
+ lastUsedAt: now,
216
+ expiresAt,
217
+ idleExpiresAt: Math.min(now + idleMs, expiresAt),
218
+ persistent,
219
+ ip: meta.ip ?? null,
220
+ userAgent: meta.userAgent ?? null,
221
+ data,
222
+ }
223
+ await adapter.create(record)
224
+
225
+ const accessToken = await issueAccessToken(record)
226
+ const refreshToken = `${id}.${value}`
227
+ const cookies = sessionCookies(request, { accessToken, refreshToken, session: record })
228
+ emit('session.created', { sessionId: id, userId, ip: record.ip, userAgent: record.userAgent })
229
+ return { session: publicSession(record), accessToken, refreshToken, cookies }
230
+ }
231
+
232
+ /** Stateless check of an access token: signature, type and expiry only. */
233
+ async function verifyAccessToken(token) {
234
+ const result = await tokens.verify(token, { type: 'access' })
235
+ return result.valid ? result.payload : null
236
+ }
237
+
238
+ function readAccessToken(request) {
239
+ if (allowBearer) {
240
+ const header = getHeader(request, 'authorization')
241
+ const match = header && /^Bearer\s+([A-Za-z0-9._~+/-]+=*)\s*$/i.exec(header)
242
+ if (match) return { token: match[1], via: 'bearer' }
243
+ }
244
+ const cookie = getCookiesAll(request)[cookieNames(request).access]?.[0]
245
+ return cookie ? { token: cookie, via: 'cookie' } : null
246
+ }
247
+
248
+ /**
249
+ * The signed-in user for this request, or null. With checkRevocation
250
+ * (the default) the session is looked up too, so logout, "sign out
251
+ * everywhere" and password resets take effect immediately rather than
252
+ * when the access token expires. Pass { checkRevocation: false } in
253
+ * edge middleware that can't reach the session store.
254
+ */
255
+ async function getSession(request, { checkRevocation: check = checkRevocation } = {}) {
256
+ const found = readAccessToken(request)
257
+ if (!found) return null
258
+ // Cookies ride along on cross-site requests; bearer tokens don't.
259
+ if (found.via === 'cookie' && csrf && isCrossSiteRequest(request, { trustedOrigins, trustProxy })) return null
260
+
261
+ const claims = await verifyAccessToken(found.token)
262
+ if (!claims || typeof claims.sid !== 'string') return null
263
+
264
+ if (!check) return { userId: claims.uid ?? claims.sub, sessionId: claims.sid, claims, session: null, via: found.via }
265
+
266
+ const record = await adapter.get(claims.sid)
267
+ if (!record || isExpired(record) || String(record.userId) !== String(claims.uid ?? claims.sub)) return null
268
+ return { userId: record.userId, sessionId: record.id, claims, session: publicSession(record), via: found.via }
269
+ }
270
+
271
+ /** Rotates the refresh token and issues a new access token. */
272
+ async function refresh(request) {
273
+ const denied = (reason, extra = {}) => ({ ok: false, reason, cookies: clearCookies(request), ...extra })
274
+ if (csrf && isCrossSiteRequest(request, { trustedOrigins, trustProxy })) {
275
+ return { ok: false, reason: 'cross-site', cookies: [] }
276
+ }
277
+
278
+ const candidates = readRefreshCandidates(request)
279
+ if (candidates.length === 0) return denied('missing')
280
+
281
+ for (const candidate of candidates) {
282
+ let record = await adapter.get(candidate.id)
283
+ if (!record) continue
284
+ const now = Date.now()
285
+ if (isExpired(record, now)) {
286
+ await adapter.delete(record.id)
287
+ emit('session.expired', { sessionId: record.id, userId: record.userId })
288
+ return denied('expired')
289
+ }
290
+
291
+ let match = await matchSecret(record, candidate.secret)
292
+ if (match === null) continue
293
+
294
+ if (match === 'current') {
295
+ const value = randomToken(32)
296
+ const tokenHash = await hashSecret(record.id, value)
297
+ const patch = {
298
+ tokenHash,
299
+ prevTokenHash: record.tokenHash,
300
+ rotatedAt: now,
301
+ lastUsedAt: now,
302
+ idleExpiresAt: Math.min(now + idleMs, record.expiresAt),
303
+ }
304
+ const swapped = await adapter.update(record.id, patch, { expectTokenHash: record.tokenHash })
305
+ if (swapped) {
306
+ record = { ...record, ...patch }
307
+ if (typeof validateSession === 'function' && !(await validateSession(publicSession(record)))) {
308
+ await adapter.delete(record.id)
309
+ emit('session.rejected', { sessionId: record.id, userId: record.userId })
310
+ return denied('rejected')
311
+ }
312
+ const accessToken = await issueAccessToken(record)
313
+ const refreshToken = `${record.id}.${value}`
314
+ emit('session.refreshed', { sessionId: record.id, userId: record.userId })
315
+ return { ok: true, session: publicSession(record), accessToken, refreshToken, cookies: sessionCookies(request, { accessToken, refreshToken, session: record }) }
316
+ }
317
+ // Another request (a second tab) rotated it first: re-read and
318
+ // handle this one as a token that was just superseded.
319
+ record = await adapter.get(candidate.id)
320
+ if (!record) return denied('revoked')
321
+ match = await matchSecret(record, candidate.secret)
322
+ }
323
+
324
+ if (match === 'previous' && record.rotatedAt != null && now - record.rotatedAt <= graceMs) {
325
+ // A parallel refresh: give this request an access token but leave
326
+ // the refresh cookie to the response that rotated it.
327
+ const accessToken = await issueAccessToken(record)
328
+ return { ok: true, session: publicSession(record), accessToken, refreshToken: null, cookies: sessionCookies(request, { accessToken, session: record }) }
329
+ }
330
+
331
+ // An already-rotated token, replayed after the grace period: someone
332
+ // holds a copy. End the session for both of them.
333
+ await adapter.delete(record.id)
334
+ emit('session.reuse_detected', { sessionId: record.id, userId: record.userId, ...requestMeta(request) })
335
+ return denied('reused')
336
+ }
337
+ return denied('invalid')
338
+ }
339
+
340
+ /** Ends this browser's session and clears its cookies. */
341
+ async function signOut(request) {
342
+ let ended = null
343
+ for (const candidate of readRefreshCandidates(request)) {
344
+ const record = await adapter.get(candidate.id)
345
+ if (record && (await matchSecret(record, candidate.secret))) {
346
+ await adapter.delete(record.id)
347
+ ended = record
348
+ }
349
+ }
350
+ if (!ended) {
351
+ // No refresh cookie reached us (another path, or a bearer client):
352
+ // a valid access token identifies the session just as well.
353
+ const found = readAccessToken(request)
354
+ const claims = found && (found.via === 'bearer' || !isCrossSiteRequest(request, { trustedOrigins, trustProxy })) ? await verifyAccessToken(found.token) : null
355
+ if (claims?.sid) {
356
+ const record = await adapter.get(claims.sid)
357
+ if (record && String(record.userId) === String(claims.uid ?? claims.sub)) {
358
+ await adapter.delete(record.id)
359
+ ended = record
360
+ }
361
+ }
362
+ }
363
+ if (ended) emit('session.revoked', { sessionId: ended.id, userId: ended.userId, reason: 'sign-out' })
364
+ return { ok: true, sessionId: ended?.id ?? null, cookies: clearCookies(request) }
365
+ }
366
+
367
+ async function revokeSession(sessionId) {
368
+ const record = await adapter.get(sessionId)
369
+ if (!record) return false
370
+ await adapter.delete(sessionId)
371
+ emit('session.revoked', { sessionId, userId: record.userId, reason: 'revoked' })
372
+ return true
373
+ }
374
+
375
+ /** "Sign out everywhere" (optionally keeping one session). Use after password changes. */
376
+ async function revokeAllSessions(userId, { exceptSessionId } = {}) {
377
+ const count = await adapter.deleteByUser(userId, { exceptId: exceptSessionId })
378
+ emit('session.revoked_all', { userId, count, exceptSessionId: exceptSessionId ?? null })
379
+ return count
380
+ }
381
+
382
+ async function listSessions(userId, { currentSessionId } = {}) {
383
+ const now = Date.now()
384
+ const records = await adapter.listByUser(userId)
385
+ return records.filter((r) => !isExpired(r, now)).sort((a, b) => b.lastUsedAt - a.lastUsedAt).map((r) => publicSession(r, currentSessionId))
386
+ }
387
+
388
+ /** True while the session exists, belongs to userId (when given) and hasn't expired. */
389
+ async function isSessionActive(sessionId, userId) {
390
+ if (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId)) return false
391
+ const record = await adapter.get(sessionId)
392
+ if (!record || isExpired(record)) return false
393
+ return userId === undefined || String(record.userId) === String(userId)
394
+ }
395
+
396
+ /** Stores extra data on a session (for example { mfa: true } after a second factor). */
397
+ async function updateSessionData(sessionId, data) {
398
+ return adapter.update(sessionId, { data })
399
+ }
400
+
401
+ return {
402
+ signIn,
403
+ signOut,
404
+ refresh,
405
+ getSession,
406
+ verifyAccessToken,
407
+ revokeSession,
408
+ revokeAllSessions,
409
+ listSessions,
410
+ updateSessionData,
411
+ isSessionActive,
412
+ clearCookies,
413
+ cookieNames,
414
+ isCrossSite: (request) => isCrossSiteRequest(request, { trustedOrigins, trustProxy }),
415
+ tokens,
416
+ sealer,
417
+ adapter,
418
+ options: { accessTokenTtl: accessTtl, refreshPath: cookieOptions.refreshPath, trustProxy, trustedOrigins },
419
+ }
420
+ }
@@ -0,0 +1,144 @@
1
+ import { base64urlDecode, base64urlEncode, fromUtf8, hmacSign, hmacVerify, randomToken } from '../core/crypto.js'
2
+ import { createKeyring, nowSeconds, toSeconds } from '../core/keys.js'
3
+
4
+ // Standard compact JWTs (HS256), hardened:
5
+ // - the algorithm is pinned: "none", RS/ES and alg-confusion tricks fail
6
+ // - every token has a type ("access", "email-verify", ...) carried in the
7
+ // header AND bound into the key, so one kind can never pass as another
8
+ // - exp is required; nbf/iat in the future are refused (with a little
9
+ // clock tolerance); iss/aud are checked when configured
10
+ // - key ids select the right secret during rotation
11
+ // - oversized tokens are refused before any work is done
12
+ // - verify() never throws: it answers { valid, payload, error }
13
+
14
+ const RESERVED_TYPE = /^[a-z][a-z0-9-]{0,39}$/
15
+ const MAX_TOKEN_LENGTH = 8192
16
+
17
+ function fail(error) {
18
+ return { valid: false, payload: null, error }
19
+ }
20
+
21
+ function decodeJson(segment) {
22
+ const value = JSON.parse(fromUtf8(base64urlDecode(segment)))
23
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('not an object')
24
+ return value
25
+ }
26
+
27
+ export function createTokenSigner({
28
+ secret,
29
+ keyring = createKeyring(secret),
30
+ issuer,
31
+ audience,
32
+ clockToleranceSeconds = 5,
33
+ maxTokenLength = MAX_TOKEN_LENGTH,
34
+ } = {}) {
35
+ const keyFor = (type, index) => keyring.hmac(`jwt:${type}`, index)
36
+
37
+ function checkType(type) {
38
+ if (!RESERVED_TYPE.test(type)) throw new TypeError(`Invalid token type ${JSON.stringify(type)}: use lowercase letters, digits and dashes.`)
39
+ }
40
+
41
+ async function sign(claims = {}, { type = 'access', expiresIn, notBefore, jwtId = true, subject } = {}) {
42
+ checkType(type)
43
+ if (expiresIn == null) throw new TypeError('sign() needs expiresIn: tokens that never expire are refused.')
44
+ if (claims == null || typeof claims !== 'object' || Array.isArray(claims)) throw new TypeError('Token claims must be an object.')
45
+
46
+ const now = nowSeconds()
47
+ const payload = { ...claims, iat: now, exp: now + toSeconds(expiresIn, 'expiresIn') }
48
+ if (subject != null) payload.sub = String(subject)
49
+ if (notBefore != null) payload.nbf = now + toSeconds(notBefore, 'notBefore')
50
+ if (jwtId && payload.jti == null) payload.jti = randomToken(16)
51
+ if (issuer && payload.iss == null) payload.iss = issuer
52
+ if (audience && payload.aud == null) payload.aud = Array.isArray(audience) ? audience[0] : audience
53
+
54
+ const header = { alg: 'HS256', typ: `${type}+jwt`, kid: await keyring.kid(0) }
55
+ const signingInput = `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(payload))}`
56
+ const signature = await hmacSign(await keyFor(type, 0), signingInput)
57
+ return `${signingInput}.${base64urlEncode(signature)}`
58
+ }
59
+
60
+ async function verify(token, { type = 'access', issuer: expectedIssuer = issuer, audience: expectedAudience = audience, maxAgeSeconds } = {}) {
61
+ try {
62
+ checkType(type)
63
+ } catch {
64
+ return fail('Invalid token type')
65
+ }
66
+ if (typeof token !== 'string' || token.length === 0) return fail('Malformed token')
67
+ if (token.length > maxTokenLength) return fail('Token too large')
68
+
69
+ const parts = token.split('.')
70
+ if (parts.length !== 3) return fail('Malformed token')
71
+ const [headerB64, payloadB64, signatureB64] = parts
72
+
73
+ let header, signature
74
+ try {
75
+ header = decodeJson(headerB64)
76
+ signature = base64urlDecode(signatureB64)
77
+ } catch {
78
+ return fail('Malformed token')
79
+ }
80
+
81
+ if (header.alg !== 'HS256') return fail('Unsupported algorithm')
82
+ if (header.typ !== `${type}+jwt`) return fail('Wrong token type')
83
+ if ('crit' in header) return fail('Unsupported token header')
84
+
85
+ // With a key id, only that secret is tried; an unknown id is refused
86
+ // rather than tried against every key.
87
+ let indexes
88
+ if (header.kid !== undefined) {
89
+ const index = typeof header.kid === 'string' ? await keyring.indexOfKid(header.kid) : -1
90
+ if (index === -1) return fail('Unknown signing key')
91
+ indexes = [index]
92
+ } else {
93
+ indexes = Array.from({ length: keyring.size }, (_, i) => i)
94
+ }
95
+
96
+ const signingInput = `${headerB64}.${payloadB64}`
97
+ let verified = false
98
+ for (const index of indexes) {
99
+ if (await hmacVerify(await keyFor(type, index), signature, signingInput)) {
100
+ verified = true
101
+ break
102
+ }
103
+ }
104
+ if (!verified) return fail('Invalid signature')
105
+
106
+ let payload
107
+ try {
108
+ payload = decodeJson(payloadB64)
109
+ } catch {
110
+ return fail('Invalid payload')
111
+ }
112
+
113
+ const now = nowSeconds()
114
+ const tolerance = clockToleranceSeconds
115
+ if (!Number.isFinite(payload.exp)) return fail('Token has no expiry')
116
+ if (now - tolerance >= payload.exp) return fail('Token expired')
117
+ if (payload.nbf != null && (!Number.isFinite(payload.nbf) || payload.nbf > now + tolerance)) return fail('Token not yet valid')
118
+ if (payload.iat != null && (!Number.isFinite(payload.iat) || payload.iat > now + tolerance)) return fail('Token issued in the future')
119
+ if (maxAgeSeconds != null && (!Number.isFinite(payload.iat) || now - payload.iat > toSeconds(maxAgeSeconds, 'maxAgeSeconds'))) {
120
+ return fail('Token too old')
121
+ }
122
+ if (expectedIssuer && payload.iss !== expectedIssuer) return fail('Wrong issuer')
123
+ if (expectedAudience) {
124
+ const wanted = Array.isArray(expectedAudience) ? expectedAudience : [expectedAudience]
125
+ const got = Array.isArray(payload.aud) ? payload.aud : [payload.aud]
126
+ if (!got.some((a) => wanted.includes(a))) return fail('Wrong audience')
127
+ }
128
+
129
+ return { valid: true, payload, error: null }
130
+ }
131
+
132
+ return { sign, verify }
133
+ }
134
+
135
+ /** Reads a JWT's claims WITHOUT checking anything. Never use the result for access decisions. */
136
+ export function decodeTokenUnsafe(token) {
137
+ try {
138
+ const parts = String(token).split('.')
139
+ if (parts.length !== 3) return null
140
+ return { header: decodeJson(parts[0]), payload: decodeJson(parts[1]) }
141
+ } catch {
142
+ return null
143
+ }
144
+ }
@@ -1,49 +1,68 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
1
+ import { createHmac, timingSafeEqual } from 'node:crypto'
2
+
3
+ // The original Tylix token format: "<base64url payload>.<HMAC-SHA256>".
4
+ // Synchronous and kept for compatibility (existing sessions, the test
5
+ // helper, apps generated before 1.5). New code should use createAuth()
6
+ // sessions or createTokenSigner() JWTs, which add token types, key
7
+ // rotation, per-purpose keys and mandatory expiry.
8
+
9
+ const MAX_TOKEN_LENGTH = 8192
10
+ const BASE64URL = /^[A-Za-z0-9_-]+$/
2
11
 
3
12
  function base64url(input) {
4
- return Buffer.from(input).toString("base64url");
13
+ return Buffer.from(input).toString('base64url')
5
14
  }
6
15
 
7
16
  function sign(payloadB64, secret) {
8
- return createHmac("sha256", secret).update(payloadB64).digest("base64url");
17
+ return createHmac('sha256', secret).update(payloadB64).digest('base64url')
18
+ }
19
+
20
+ function fail(error) {
21
+ return { valid: false, payload: null, error }
9
22
  }
10
23
 
11
24
  export function signToken(payload, secret, { expiresInSeconds } = {}) {
12
- const body = { ...payload };
25
+ if (!secret) throw new TypeError('signToken needs a secret')
26
+ const body = { ...payload }
13
27
  if (expiresInSeconds) {
14
- body.exp = Math.floor(Date.now() / 1000) + expiresInSeconds;
28
+ body.exp = Math.floor(Date.now() / 1000) + expiresInSeconds
15
29
  }
16
30
 
17
- const payloadB64 = base64url(JSON.stringify(body));
18
- const signature = sign(payloadB64, secret);
19
- return `${payloadB64}.${signature}`;
31
+ const payloadB64 = base64url(JSON.stringify(body))
32
+ const signature = sign(payloadB64, secret)
33
+ return `${payloadB64}.${signature}`
20
34
  }
21
35
 
22
36
  export function verifyToken(token, secret) {
23
- if (typeof token !== "string" || !token.includes(".")) {
24
- return { valid: false, payload: null, error: "Malformed token" };
25
- }
37
+ if (!secret) return fail('No secret configured')
38
+ if (typeof token !== 'string' || token.length > MAX_TOKEN_LENGTH) return fail('Malformed token')
26
39
 
27
- const [payloadB64, signature] = token.split(".");
28
- const expectedSignature = sign(payloadB64, secret);
40
+ // Exactly two canonical base64url segments: trailing segments or
41
+ // alternative encodings of the same bytes are refused.
42
+ const parts = token.split('.')
43
+ if (parts.length !== 2) return fail('Malformed token')
44
+ const [payloadB64, signature] = parts
45
+ if (!BASE64URL.test(payloadB64) || !BASE64URL.test(signature)) return fail('Malformed token')
29
46
 
30
- const sigBuffer = Buffer.from(signature ?? "", "base64url");
31
- const expectedBuffer = Buffer.from(expectedSignature, "base64url");
47
+ const sigBuffer = Buffer.from(signature, 'base64url')
48
+ if (sigBuffer.toString('base64url') !== signature) return fail('Malformed token')
49
+ const expectedBuffer = Buffer.from(sign(payloadB64, secret), 'base64url')
32
50
 
33
51
  if (sigBuffer.length !== expectedBuffer.length || !timingSafeEqual(sigBuffer, expectedBuffer)) {
34
- return { valid: false, payload: null, error: "Invalid signature" };
52
+ return fail('Invalid signature')
35
53
  }
36
54
 
37
- let payload;
55
+ let payload
38
56
  try {
39
- payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf-8"));
57
+ payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf-8'))
40
58
  } catch {
41
- return { valid: false, payload: null, error: "Invalid payload" };
59
+ return fail('Invalid payload')
42
60
  }
61
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return fail('Invalid payload')
43
62
 
44
- if (payload.exp && Math.floor(Date.now() / 1000) > payload.exp) {
45
- return { valid: false, payload: null, error: "Token expired" };
63
+ if (payload.exp != null && (!Number.isFinite(payload.exp) || Math.floor(Date.now() / 1000) >= payload.exp)) {
64
+ return fail('Token expired')
46
65
  }
47
66
 
48
- return { valid: true, payload, error: null };
67
+ return { valid: true, payload, error: null }
49
68
  }