@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,143 @@
1
+ // Web Crypto helpers. Everything here runs unchanged on Node 22+, Bun,
2
+ // Deno, Cloudflare Workers, Vercel/Next.js edge and browsers: nothing
3
+ // imports node:crypto or relies on Buffer.
4
+
5
+ const encoder = new TextEncoder()
6
+ const decoder = new TextDecoder()
7
+
8
+ function webcrypto() {
9
+ const c = globalThis.crypto
10
+ if (!c?.subtle || typeof c.getRandomValues !== 'function') {
11
+ throw new Error('@tylix/auth needs the Web Crypto API (globalThis.crypto.subtle). Use Node 22+ or another runtime that provides it.')
12
+ }
13
+ return c
14
+ }
15
+
16
+ export function utf8(value) {
17
+ return typeof value === 'string' ? encoder.encode(value) : value
18
+ }
19
+
20
+ export function fromUtf8(bytes) {
21
+ return decoder.decode(bytes)
22
+ }
23
+
24
+ // --- base64url (RFC 4648 section 5, no padding) ---------------------------
25
+
26
+ export function base64urlEncode(input) {
27
+ const bytes = utf8(input)
28
+ let binary = ''
29
+ for (let i = 0; i < bytes.length; i += 0x8000) {
30
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
31
+ }
32
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
33
+ }
34
+
35
+ const BASE64URL = /^[A-Za-z0-9_-]*$/
36
+
37
+ // Strict: rejects padding, foreign characters and non-canonical encodings
38
+ // (where the unused low bits of the last character are not zero). Without
39
+ // the canonical check, several different strings decode to the same bytes,
40
+ // so a signed token could be altered without breaking its signature.
41
+ export function base64urlDecode(input) {
42
+ if (typeof input !== 'string' || !BASE64URL.test(input) || input.length % 4 === 1) {
43
+ throw new TypeError('Invalid base64url')
44
+ }
45
+ const padded = input.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((input.length + 3) % 4)
46
+ const binary = atob(padded)
47
+ const bytes = new Uint8Array(binary.length)
48
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
49
+ if (base64urlEncode(bytes) !== input) throw new TypeError('Non-canonical base64url')
50
+ return bytes
51
+ }
52
+
53
+ // --- randomness -------------------------------------------------------------
54
+
55
+ export function randomBytes(length) {
56
+ const bytes = new Uint8Array(length)
57
+ webcrypto().getRandomValues(bytes)
58
+ return bytes
59
+ }
60
+
61
+ /** A URL- and cookie-safe random string with `bytes` bytes of entropy (default 32 = 256 bits). */
62
+ export function randomToken(bytes = 32) {
63
+ return base64urlEncode(randomBytes(bytes))
64
+ }
65
+
66
+ // --- hashing ----------------------------------------------------------------
67
+
68
+ export async function sha256(input) {
69
+ return new Uint8Array(await webcrypto().subtle.digest('SHA-256', utf8(input)))
70
+ }
71
+
72
+ export function toHex(bytes) {
73
+ let out = ''
74
+ for (const b of bytes) out += b.toString(16).padStart(2, '0')
75
+ return out
76
+ }
77
+
78
+ export async function sha256Hex(input) {
79
+ return toHex(await sha256(input))
80
+ }
81
+
82
+ // --- constant-time comparison -------------------------------------------
83
+
84
+ /** Compares two byte arrays or strings without an early exit. Only the length can leak. */
85
+ export function timingSafeEqual(a, b) {
86
+ const x = utf8(a)
87
+ const y = utf8(b)
88
+ if (x.length !== y.length) return false
89
+ let diff = 0
90
+ for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i]
91
+ return diff === 0
92
+ }
93
+
94
+ // --- keys -------------------------------------------------------------------
95
+
96
+ // A fixed, public salt: HKDF's security here comes from the secret, the
97
+ // salt only separates Tylix's derivations from anything else using the
98
+ // same secret.
99
+ const HKDF_SALT = utf8('tylix-auth/v2')
100
+
101
+ export async function deriveKeyBytes(secret, info, length = 32) {
102
+ const subtle = webcrypto().subtle
103
+ const base = await subtle.importKey('raw', utf8(secret), 'HKDF', false, ['deriveBits'])
104
+ const bits = await subtle.deriveBits(
105
+ { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: utf8(info) },
106
+ base,
107
+ length * 8,
108
+ )
109
+ return new Uint8Array(bits)
110
+ }
111
+
112
+ export async function importHmacKey(rawBytes, hash = 'SHA-256') {
113
+ return webcrypto().subtle.importKey('raw', rawBytes, { name: 'HMAC', hash }, false, ['sign', 'verify'])
114
+ }
115
+
116
+ export async function hmacSign(key, data) {
117
+ return new Uint8Array(await webcrypto().subtle.sign('HMAC', key, utf8(data)))
118
+ }
119
+
120
+ // subtle.verify compares in constant time.
121
+ export async function hmacVerify(key, signature, data) {
122
+ return webcrypto().subtle.verify('HMAC', key, signature, utf8(data))
123
+ }
124
+
125
+ export async function importAesKey(rawBytes) {
126
+ return webcrypto().subtle.importKey('raw', rawBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
127
+ }
128
+
129
+ export async function aesGcmEncrypt(key, iv, plaintext, additionalData) {
130
+ return new Uint8Array(
131
+ await webcrypto().subtle.encrypt({ name: 'AES-GCM', iv, additionalData: utf8(additionalData) }, key, utf8(plaintext)),
132
+ )
133
+ }
134
+
135
+ export async function aesGcmDecrypt(key, iv, ciphertext, additionalData) {
136
+ return new Uint8Array(
137
+ await webcrypto().subtle.decrypt({ name: 'AES-GCM', iv, additionalData: utf8(additionalData) }, key, ciphertext),
138
+ )
139
+ }
140
+
141
+ export function subtle() {
142
+ return webcrypto().subtle
143
+ }
@@ -0,0 +1,83 @@
1
+ import { base64urlEncode, deriveKeyBytes, importAesKey, importHmacKey } from './crypto.js'
2
+
3
+ export const MIN_SECRET_LENGTH = 32
4
+
5
+ const warned = new Set()
6
+ function warnOnce(message) {
7
+ if (warned.has(message)) return
8
+ warned.add(message)
9
+ console.warn(`[@tylix/auth] ${message}`)
10
+ }
11
+
12
+ export function isProduction() {
13
+ return globalThis.process?.env?.NODE_ENV === 'production'
14
+ }
15
+
16
+ // Accepts one secret or a list for rotation: the first signs, all of them
17
+ // verify. To rotate: put the new secret first, keep the old one until the
18
+ // longest-lived token signed with it has expired, then remove it.
19
+ export function normalizeSecrets(secret) {
20
+ const list = (Array.isArray(secret) ? secret : [secret]).filter((s) => s != null && s !== '')
21
+ if (list.length === 0) {
22
+ throw new Error('@tylix/auth needs a secret: pass `secret` (for example process.env.AUTH_SECRET). Generate one with: openssl rand -base64 48')
23
+ }
24
+ for (const s of list) {
25
+ if (typeof s !== 'string') throw new TypeError('Auth secrets must be strings.')
26
+ if (s.length < MIN_SECRET_LENGTH) {
27
+ const message = `An auth secret is only ${s.length} characters; use at least ${MIN_SECRET_LENGTH} random characters (openssl rand -base64 48).`
28
+ if (isProduction()) throw new Error(message)
29
+ warnOnce(message)
30
+ }
31
+ }
32
+ return list
33
+ }
34
+
35
+ // Every purpose gets its own key, derived from the secret with HKDF. A
36
+ // token made for one purpose (say an email-verification link) can then
37
+ // never pass as another (an access token), even if someone forgets to
38
+ // check its type: the signature itself is wrong.
39
+ export function createKeyring(secret) {
40
+ const secrets = normalizeSecrets(secret)
41
+ const cache = new Map()
42
+
43
+ const cached = (key, make) => {
44
+ if (!cache.has(key)) cache.set(key, make())
45
+ return cache.get(key)
46
+ }
47
+
48
+ // Key ids are derived too, so they say which secret signed a token
49
+ // without revealing anything about it.
50
+ const kid = (index) =>
51
+ cached(`kid:${index}`, async () => base64urlEncode((await deriveKeyBytes(secrets[index], 'tylix-auth:kid', 9))))
52
+
53
+ return {
54
+ size: secrets.length,
55
+ kid,
56
+ hmac: (purpose, index = 0, hash = 'SHA-256') =>
57
+ cached(`hmac:${purpose}:${index}:${hash}`, async () =>
58
+ importHmacKey(await deriveKeyBytes(secrets[index], `tylix-auth:hmac:${purpose}`), hash),
59
+ ),
60
+ aes: (purpose, index = 0) =>
61
+ cached(`aes:${purpose}:${index}`, async () => importAesKey(await deriveKeyBytes(secrets[index], `tylix-auth:aes:${purpose}`))),
62
+ async indexOfKid(value) {
63
+ for (let i = 0; i < secrets.length; i++) if ((await kid(i)) === value) return i
64
+ return -1
65
+ },
66
+ }
67
+ }
68
+
69
+ // --- durations ---------------------------------------------------------
70
+
71
+ const UNITS = { s: 1, m: 60, h: 3600, d: 86400, w: 604800 }
72
+
73
+ /** 900, "900", "15m", "12h", "30d", "2w" -> seconds. */
74
+ export function toSeconds(value, name = 'duration') {
75
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.floor(value)
76
+ const match = typeof value === 'string' && /^\s*(\d+)\s*([smhdw]?)\s*$/.exec(value)
77
+ if (!match || Number(match[1]) <= 0) throw new TypeError(`Invalid ${name}: ${JSON.stringify(value)} (use seconds or "15m", "12h", "30d")`)
78
+ return Number(match[1]) * (UNITS[match[2] || 's'])
79
+ }
80
+
81
+ export function nowSeconds() {
82
+ return Math.floor(Date.now() / 1000)
83
+ }
@@ -0,0 +1,43 @@
1
+ import { aesGcmDecrypt, aesGcmEncrypt, base64urlDecode, base64urlEncode, fromUtf8, randomBytes } from './crypto.js'
2
+ import { createKeyring, nowSeconds, toSeconds } from './keys.js'
3
+
4
+ // Authenticated encryption (AES-256-GCM) for values that must stay secret
5
+ // AND untampered: OAuth state cookies, TOTP secrets in the database, any
6
+ // small server-side value you hand to the browser.
7
+ //
8
+ // v1.<kid>.<iv>.<ciphertext>
9
+ //
10
+ // The purpose is bound in as additional data, so a value sealed for one
11
+ // purpose fails to open as another. An optional expiry is sealed inside.
12
+
13
+ export function createSealer({ secret, keyring = createKeyring(secret) } = {}) {
14
+ async function seal(value, { purpose = 'default', expiresIn } = {}) {
15
+ const body = { v: value }
16
+ if (expiresIn != null) body.exp = nowSeconds() + toSeconds(expiresIn, 'expiresIn')
17
+ const iv = randomBytes(12)
18
+ const ciphertext = await aesGcmEncrypt(await keyring.aes(`seal:${purpose}`, 0), iv, JSON.stringify(body), purpose)
19
+ return `v1.${await keyring.kid(0)}.${base64urlEncode(iv)}.${base64urlEncode(ciphertext)}`
20
+ }
21
+
22
+ // Resolves the original value, or null for anything forged, altered,
23
+ // expired, sealed for another purpose, or with an unknown key.
24
+ async function unseal(sealed, { purpose = 'default' } = {}) {
25
+ if (typeof sealed !== 'string' || sealed.length > 16384) return null
26
+ const parts = sealed.split('.')
27
+ if (parts.length !== 4 || parts[0] !== 'v1') return null
28
+ try {
29
+ const index = await keyring.indexOfKid(parts[1])
30
+ if (index === -1) return null
31
+ const iv = base64urlDecode(parts[2])
32
+ if (iv.length !== 12) return null
33
+ const plaintext = await aesGcmDecrypt(await keyring.aes(`seal:${purpose}`, index), iv, base64urlDecode(parts[3]), purpose)
34
+ const body = JSON.parse(fromUtf8(plaintext))
35
+ if (body.exp != null && nowSeconds() >= body.exp) return null
36
+ return body.v
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ return { seal, unseal }
43
+ }
@@ -1,15 +1,21 @@
1
1
  export interface AuthGeneratorResults {
2
2
  userModel: string
3
- refreshTokenModel: string
3
+ sessionModel: string
4
4
  passwordResetModel: string
5
5
  validator: string
6
6
  controller: string
7
7
  mailer: string
8
+ verifyEmailMail: string
9
+ resetPasswordMail: string
10
+ verifyEmailView: string
11
+ resetPasswordView: string
8
12
  userMigration: string
9
- refreshTokenMigration: string
13
+ sessionMigration: string
10
14
  passwordResetMigration: string
15
+ userObserver: string
16
+ welcomeJob: string
11
17
  }
12
18
 
13
19
  export declare class AuthGenerator {
14
20
  generate(baseDir: string): Promise<AuthGeneratorResults>
15
- }
21
+ }
@@ -60,9 +60,19 @@ export class AuthGenerator {
60
60
  'welcome-job',
61
61
  )
62
62
 
63
- results.refreshTokenModel = await writeFile(
64
- path.join(baseDir, 'app', 'models', `RefreshToken.${ext}`),
65
- await read('refresh-token-model'),
63
+ // Server-side sessions (rotating refresh tokens, revocation, device
64
+ // list). Replaces the RefreshToken model of apps generated before 1.5;
65
+ // an existing RefreshToken file is left alone (nothing reads it now).
66
+ results.sessionModel = await writeFile(
67
+ path.join(baseDir, 'app', 'models', `AuthSession.${ext}`),
68
+ await read('auth-session-model'),
69
+ { overwrite: true },
70
+ )
71
+
72
+ // Social sign-in: which provider accounts belong to which user.
73
+ results.oauthAccountModel = await writeFile(
74
+ path.join(baseDir, 'app', 'models', `OAuthAccount.${ext}`),
75
+ await read('oauth-account-model'),
66
76
  { overwrite: true },
67
77
  )
68
78
 
@@ -137,10 +147,12 @@ export class AuthGenerator {
137
147
 
138
148
  results.userMigration = await writeMigration('create_users_table', 0, 'user-migration')
139
149
 
140
- results.refreshTokenMigration = await writeMigration('create_refresh_tokens_table', 1000, 'refresh-token-migration')
150
+ results.sessionMigration = await writeMigration('create_auth_sessions_table', 1000, 'auth-session-migration')
141
151
 
142
152
  results.passwordResetMigration = await writeMigration('create_password_resets_table', 2000, 'password-reset-migration')
143
153
 
154
+ results.oauthAccountMigration = await writeMigration('create_oauth_accounts_table', 3000, 'oauth-account-migration')
155
+
144
156
  return results
145
157
  }
146
158
  }