@tylix/auth 1.4.0 → 1.5.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/README.md +284 -14
- package/package.json +95 -9
- package/src/client/client.d.ts +14 -0
- package/src/client/client.js +83 -0
- package/src/cookies/authCookies.d.ts +8 -6
- package/src/cookies/authCookies.js +43 -28
- package/src/core/crypto.js +143 -0
- package/src/core/keys.js +83 -0
- package/src/core/seal.js +43 -0
- package/src/generators/AuthGenerator.d.ts +9 -3
- package/src/generators/AuthGenerator.js +16 -4
- package/src/generators/templates/auth-controller-ts.tyx +401 -98
- package/src/generators/templates/auth-controller.tyx +384 -96
- package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
- package/src/generators/templates/auth-session-migration.tyx +32 -0
- package/src/generators/templates/auth-session-model-ts.tyx +53 -0
- package/src/generators/templates/auth-session-model.tyx +34 -0
- package/src/generators/templates/auth-validator-ts.tyx +17 -0
- package/src/generators/templates/auth-validator.tyx +17 -0
- package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
- package/src/generators/templates/oauth-account-migration.tyx +27 -0
- package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
- package/src/generators/templates/oauth-account-model.tyx +45 -0
- package/src/generators/templates/password-reset-model-ts.tyx +26 -4
- package/src/generators/templates/password-reset-model.tyx +26 -4
- package/src/generators/templates/reset-password-view.html +30 -3
- package/src/generators/templates/verify-email-view.html +30 -3
- package/src/http/cookies.js +91 -0
- package/src/http/origin.js +68 -0
- package/src/http/request.js +179 -0
- package/src/index.d.ts +9 -1
- package/src/index.js +5 -0
- package/src/integrations/h3.d.ts +6 -0
- package/src/integrations/h3.js +70 -0
- package/src/integrations/hono.d.ts +6 -0
- package/src/integrations/hono.js +36 -0
- package/src/integrations/next.d.ts +16 -0
- package/src/integrations/next.js +36 -0
- package/src/integrations/node.d.ts +7 -0
- package/src/integrations/node.js +87 -0
- package/src/integrations/routes.js +92 -0
- package/src/integrations/sveltekit.d.ts +5 -0
- package/src/integrations/sveltekit.js +52 -0
- package/src/integrations/web.js +69 -0
- package/src/mfa/totp.js +150 -0
- package/src/oauth/oauth.js +142 -0
- package/src/oauth/providers.js +112 -0
- package/src/password/hashPassword.d.ts +5 -1
- package/src/password/hashPassword.js +96 -30
- package/src/password/index.d.ts +2 -0
- package/src/password/index.js +2 -0
- package/src/password/policy.js +108 -0
- package/src/rateLimiter/loginRateLimiter.js +16 -6
- package/src/ratelimit/limiter.js +129 -0
- package/src/session/adapters/keyValue.js +87 -0
- package/src/session/adapters/memory.js +38 -0
- package/src/session/adapters/model.js +97 -0
- package/src/session/adapters/prisma.js +67 -0
- package/src/session/adapters/sql.js +128 -0
- package/src/session/createAuth.js +420 -0
- package/src/token/jwt.js +144 -0
- package/src/token/signToken.js +41 -22
- package/src/tylix/accessTokens.js +61 -0
- package/src/web.d.ts +359 -0
- package/src/web.js +47 -0
|
@@ -5,14 +5,21 @@ import {
|
|
|
5
5
|
} from 'node:crypto'
|
|
6
6
|
import { promisify } from 'node:util'
|
|
7
7
|
|
|
8
|
+
// Password hashing with scrypt (memory-hard), using node:crypto, which Node,
|
|
9
|
+
// Bun, Deno and Cloudflare Workers (nodejs_compat) all provide.
|
|
10
|
+
//
|
|
11
|
+
// scrypt$<N>$<r>$<p>$<salt>$<key>
|
|
12
|
+
//
|
|
13
|
+
// The parameters live in each hash, so they can be raised later: call
|
|
14
|
+
// needsRehash() after a successful login and store a fresh hash when it
|
|
15
|
+
// says so (the generated Tylix controller does).
|
|
16
|
+
|
|
8
17
|
const scrypt = promisify(scryptCallback)
|
|
9
18
|
|
|
10
19
|
const KEY_LENGTH = 64
|
|
11
20
|
const PREFIX = 'scrypt'
|
|
12
21
|
|
|
13
|
-
//
|
|
14
|
-
// scrypt setting). The parameters are stored inside each hash string, so they
|
|
15
|
-
// can be raised later without breaking existing hashes.
|
|
22
|
+
// N=2^15, r=8, p=3: about 32 MiB per hash, an OWASP-recommended setting.
|
|
16
23
|
const COST = 1 << 15
|
|
17
24
|
const BLOCK_SIZE = 8
|
|
18
25
|
const PARALLELISM = 3
|
|
@@ -24,6 +31,10 @@ const MAX_BLOCK_SIZE = 32
|
|
|
24
31
|
const MAX_PARALLELISM = 16
|
|
25
32
|
const MAX_KEY_LENGTH = 128
|
|
26
33
|
|
|
34
|
+
// Longer inputs are refused outright: hashing megabytes per request is a
|
|
35
|
+
// cheap way to burn CPU, and no real password is this long.
|
|
36
|
+
export const MAX_PASSWORD_BYTES = 1024
|
|
37
|
+
|
|
27
38
|
function maxmemFor(cost, blockSize, parallelism) {
|
|
28
39
|
return 128 * blockSize * (cost + parallelism + 2) * 2
|
|
29
40
|
}
|
|
@@ -32,9 +43,24 @@ function isPowerOfTwo(value) {
|
|
|
32
43
|
return Number.isInteger(value) && value > 1 && (value & (value - 1)) === 0
|
|
33
44
|
}
|
|
34
45
|
|
|
46
|
+
function tooLong(value) {
|
|
47
|
+
return Buffer.byteLength(value, 'utf8') > MAX_PASSWORD_BYTES
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The same password typed on different keyboards can arrive as different
|
|
51
|
+
// Unicode sequences ("é" as one code point or as "e" + accent). NFC makes
|
|
52
|
+
// them one, so nobody is locked out by their input method.
|
|
53
|
+
function normalize(value) {
|
|
54
|
+
return value.normalize('NFC')
|
|
55
|
+
}
|
|
56
|
+
|
|
35
57
|
export async function hashPassword(plainPassword) {
|
|
58
|
+
if (typeof plainPassword !== 'string' || plainPassword.length === 0) {
|
|
59
|
+
throw new TypeError('hashPassword needs a non-empty string.')
|
|
60
|
+
}
|
|
61
|
+
if (tooLong(plainPassword)) throw new RangeError(`Passwords are limited to ${MAX_PASSWORD_BYTES} bytes.`)
|
|
36
62
|
const salt = randomBytes(16).toString('hex')
|
|
37
|
-
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH, {
|
|
63
|
+
const derivedKey = await scrypt(normalize(plainPassword), salt, KEY_LENGTH, {
|
|
38
64
|
N: COST,
|
|
39
65
|
r: BLOCK_SIZE,
|
|
40
66
|
p: PARALLELISM,
|
|
@@ -43,15 +69,16 @@ export async function hashPassword(plainPassword) {
|
|
|
43
69
|
return `${PREFIX}$${COST}$${BLOCK_SIZE}$${PARALLELISM}$${salt}$${derivedKey.toString('hex')}`
|
|
44
70
|
}
|
|
45
71
|
|
|
46
|
-
|
|
47
|
-
const
|
|
72
|
+
function parseCurrent(storedHash) {
|
|
73
|
+
const parts = storedHash.split('$')
|
|
74
|
+
if (parts.length !== 6) return null
|
|
75
|
+
const [, n, r, p, salt, key] = parts
|
|
48
76
|
const cost = Number(n)
|
|
49
77
|
const blockSize = Number(r)
|
|
50
78
|
const parallelism = Number(p)
|
|
51
|
-
|
|
52
79
|
if (
|
|
53
|
-
|
|
54
|
-
|
|
80
|
+
!/^[0-9a-f]{16,128}$/i.test(salt) ||
|
|
81
|
+
!/^[0-9a-f]+$/i.test(key) ||
|
|
55
82
|
!isPowerOfTwo(cost) ||
|
|
56
83
|
cost > MAX_COST ||
|
|
57
84
|
!Number.isInteger(blockSize) ||
|
|
@@ -61,47 +88,86 @@ async function verifyCurrent(plainPassword, storedHash) {
|
|
|
61
88
|
parallelism < 1 ||
|
|
62
89
|
parallelism > MAX_PARALLELISM
|
|
63
90
|
) {
|
|
64
|
-
return
|
|
91
|
+
return null
|
|
65
92
|
}
|
|
66
|
-
|
|
67
93
|
const keyBuffer = Buffer.from(key, 'hex')
|
|
68
|
-
if (keyBuffer.length
|
|
94
|
+
if (keyBuffer.length < 16 || keyBuffer.length > MAX_KEY_LENGTH) return null
|
|
95
|
+
return { cost, blockSize, parallelism, salt, keyBuffer }
|
|
96
|
+
}
|
|
69
97
|
|
|
70
|
-
|
|
98
|
+
async function derive(password, { cost, blockSize, parallelism, salt, keyBuffer }) {
|
|
99
|
+
return scrypt(password, salt, keyBuffer.length, {
|
|
71
100
|
N: cost,
|
|
72
101
|
r: blockSize,
|
|
73
102
|
p: parallelism,
|
|
74
103
|
maxmem: maxmemFor(cost, blockSize, parallelism),
|
|
75
104
|
})
|
|
105
|
+
}
|
|
76
106
|
|
|
77
|
-
|
|
78
|
-
|
|
107
|
+
async function verifyCurrent(plainPassword, storedHash) {
|
|
108
|
+
const parsed = parseCurrent(storedHash)
|
|
109
|
+
if (!parsed) return false
|
|
110
|
+
|
|
111
|
+
const normalized = normalize(plainPassword)
|
|
112
|
+
const derived = await derive(normalized, parsed)
|
|
113
|
+
if (timingSafeEqual(derived, parsed.keyBuffer)) return true
|
|
114
|
+
|
|
115
|
+
// Hashes made before normalization was added used the raw input.
|
|
116
|
+
if (normalized !== plainPassword) {
|
|
117
|
+
return timingSafeEqual(await derive(plainPassword, parsed), parsed.keyBuffer)
|
|
118
|
+
}
|
|
119
|
+
return false
|
|
79
120
|
}
|
|
80
121
|
|
|
81
122
|
// Hashes created before parameters were stored: "salt:key", Node's default
|
|
82
|
-
// scrypt settings. Still accepted so nobody is locked out;
|
|
83
|
-
//
|
|
123
|
+
// scrypt settings. Still accepted so nobody is locked out; needsRehash()
|
|
124
|
+
// is true for them, so the login flow replaces them.
|
|
84
125
|
async function verifyLegacy(plainPassword, storedHash) {
|
|
85
|
-
const [salt, key] = storedHash.split(':')
|
|
86
|
-
if (!salt || !key) return false
|
|
126
|
+
const [salt, key, extra] = storedHash.split(':')
|
|
127
|
+
if (!salt || !key || extra !== undefined || !/^[0-9a-f]+$/i.test(key)) return false
|
|
87
128
|
|
|
88
|
-
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
89
129
|
const keyBuffer = Buffer.from(key, 'hex')
|
|
130
|
+
if (keyBuffer.length !== KEY_LENGTH) return false
|
|
90
131
|
|
|
91
|
-
|
|
92
|
-
// or it throws -- guard against a corrupted/foreign-format stored
|
|
93
|
-
// hash rather than letting a length mismatch crash the login route.
|
|
94
|
-
if (derivedKey.length !== keyBuffer.length) return false
|
|
95
|
-
|
|
132
|
+
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
96
133
|
return timingSafeEqual(derivedKey, keyBuffer)
|
|
97
134
|
}
|
|
98
135
|
|
|
136
|
+
// A real hash of a random password, made once. Verifying against it costs
|
|
137
|
+
// what a real verification costs, which is the point: see verifyPassword.
|
|
138
|
+
let dummyHash = null
|
|
139
|
+
function getDummyHash() {
|
|
140
|
+
dummyHash ??= hashPassword(randomBytes(24).toString('hex'))
|
|
141
|
+
return dummyHash
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Checks a password against a stored hash. Always resolves a boolean.
|
|
146
|
+
*
|
|
147
|
+
* Pass `null`/`undefined` as the hash when the account doesn't exist: the
|
|
148
|
+
* same scrypt work is still done against a dummy hash, so the response
|
|
149
|
+
* time doesn't reveal which emails are registered.
|
|
150
|
+
*/
|
|
99
151
|
export async function verifyPassword(plainPassword, storedHash) {
|
|
100
|
-
|
|
152
|
+
const hasHash = typeof storedHash === 'string' && storedHash.length > 0
|
|
101
153
|
|
|
102
|
-
if (
|
|
103
|
-
|
|
154
|
+
if (typeof plainPassword !== 'string' || plainPassword.length === 0 || tooLong(plainPassword) || !hasHash) {
|
|
155
|
+
await verifyCurrent(randomBytes(12).toString('hex'), await getDummyHash())
|
|
156
|
+
return false
|
|
104
157
|
}
|
|
105
158
|
|
|
106
|
-
|
|
107
|
-
}
|
|
159
|
+
try {
|
|
160
|
+
if (storedHash.startsWith(`${PREFIX}$`)) return await verifyCurrent(plainPassword, storedHash)
|
|
161
|
+
return await verifyLegacy(plainPassword, storedHash)
|
|
162
|
+
} catch {
|
|
163
|
+
return false
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** True when a stored hash uses an old format or weaker parameters than current ones. */
|
|
168
|
+
export function needsRehash(storedHash) {
|
|
169
|
+
if (typeof storedHash !== 'string' || !storedHash.startsWith(`${PREFIX}$`)) return true
|
|
170
|
+
const parsed = parseCurrent(storedHash)
|
|
171
|
+
if (!parsed) return true
|
|
172
|
+
return parsed.cost < COST || parsed.blockSize < BLOCK_SIZE || parsed.parallelism < PARALLELISM || parsed.keyBuffer.length < KEY_LENGTH
|
|
173
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { subtle, toHex, utf8 } from '../core/crypto.js'
|
|
2
|
+
|
|
3
|
+
// Password rules in the spirit of NIST SP 800-63B: length matters, forced
|
|
4
|
+
// "one symbol and one digit" rules don't. Instead, reject what attackers
|
|
5
|
+
// try first: very common passwords, passwords built from the user's own
|
|
6
|
+
// name or email, trivial patterns, and (optionally) any password already
|
|
7
|
+
// seen in a public breach.
|
|
8
|
+
|
|
9
|
+
// The most common passwords from public breach corpora (lowercased). A
|
|
10
|
+
// short list on purpose: it catches what credential-stuffing tries first,
|
|
11
|
+
// and the breach check below covers the long tail.
|
|
12
|
+
const COMMON = new Set(`
|
|
13
|
+
123456 123456789 12345678 password qwerty123 qwerty 12345 1234567 111111 123123 abc123 password1 1234567890
|
|
14
|
+
000000 iloveyou 1q2w3e4r 1qaz2wsx qwertyuiop 654321 666666 987654321 121212 123321 7777777 112233
|
|
15
|
+
dragon monkey letmein football baseball welcome admin login master hello freedom whatever shadow
|
|
16
|
+
sunshine princess trustno1 starwars passw0rd password123 superman batman michael jennifer charlie
|
|
17
|
+
donald zaq12wsx asdfghjkl asdfgh qazwsx 1q2w3e 1q2w3e4r5t q1w2e3r4 aa123456 qwer1234 abcd1234 a123456
|
|
18
|
+
123qwe 123abc admin123 root toor changeme default secret letmein1 welcome1 welcome123 password! p@ssw0rd
|
|
19
|
+
p@ssword pa$$word passwort motdepasse contraseña senha 11111111 00000000 88888888 12341234 123654
|
|
20
|
+
1111111111 zxcvbnm zxcvbnm123 asdf1234 qwerty1 iloveyou1 princess1 football1 monkey123 dragon123
|
|
21
|
+
mustang access hunter2 ninja azerty solo loveme flower hottie lovely 696969 baseball1 jordan23
|
|
22
|
+
computer internet samsung google apple1 tylix tylix123 testtest test1234 test123 guest guest123
|
|
23
|
+
summer2024 winter2024 spring2024 autumn2024 summer2025 winter2025 summer2026 winter2026 spring2026
|
|
24
|
+
`.split(/\s+/).filter(Boolean))
|
|
25
|
+
|
|
26
|
+
function isSequential(value) {
|
|
27
|
+
if (value.length < 4) return false
|
|
28
|
+
let up = true
|
|
29
|
+
let down = true
|
|
30
|
+
for (let i = 1; i < value.length; i++) {
|
|
31
|
+
const d = value.charCodeAt(i) - value.charCodeAt(i - 1)
|
|
32
|
+
if (d !== 1) up = false
|
|
33
|
+
if (d !== -1) down = false
|
|
34
|
+
}
|
|
35
|
+
return up || down
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function contextualParts(inputs) {
|
|
39
|
+
const parts = new Set()
|
|
40
|
+
for (const input of inputs) {
|
|
41
|
+
if (typeof input !== 'string') continue
|
|
42
|
+
const lower = input.toLowerCase()
|
|
43
|
+
const local = lower.split('@')[0]
|
|
44
|
+
for (const piece of [local, ...lower.split(/[^a-z0-9]+/i)]) if (piece.length >= 4) parts.add(piece)
|
|
45
|
+
}
|
|
46
|
+
return [...parts]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Checks a new password. Resolves { ok, errors: string[] }.
|
|
51
|
+
* minLength default 8 (NIST: 8 with MFA, 15 for password-only accounts)
|
|
52
|
+
* maxLength default 128 characters
|
|
53
|
+
* userInputs the user's name, email, username... (never allowed inside)
|
|
54
|
+
* breached true to also check Have I Been Pwned (k-anonymity; only a
|
|
55
|
+
* 5-character hash prefix leaves the server). Fails open.
|
|
56
|
+
*/
|
|
57
|
+
export async function checkPasswordStrength(password, { minLength = 8, maxLength = 128, userInputs = [], breached = false, fetch: fetchImpl } = {}) {
|
|
58
|
+
const errors = []
|
|
59
|
+
if (typeof password !== 'string') return { ok: false, errors: ['Choose a password.'] }
|
|
60
|
+
|
|
61
|
+
const length = [...password].length
|
|
62
|
+
if (length < minLength) errors.push(`Password must be at least ${minLength} characters.`)
|
|
63
|
+
if (length > maxLength) errors.push(`Password must be at most ${maxLength} characters.`)
|
|
64
|
+
|
|
65
|
+
const lower = password.toLowerCase()
|
|
66
|
+
if (COMMON.has(lower) || COMMON.has(lower.replace(/[!@#$.]+$/, ''))) {
|
|
67
|
+
errors.push('This password is too common. Choose something less predictable.')
|
|
68
|
+
} else if (/^(.)\1+$/.test(password) || isSequential(lower)) {
|
|
69
|
+
errors.push('Avoid repeated or sequential characters.')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (contextualParts(userInputs).some((part) => lower.includes(part))) {
|
|
73
|
+
errors.push("Don't use your name or email address in your password.")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (errors.length === 0 && breached) {
|
|
77
|
+
const count = await breachCount(password, { fetch: fetchImpl })
|
|
78
|
+
if (count > 0) errors.push('This password has appeared in a data breach. Choose a different one.')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return { ok: errors.length === 0, errors }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* How many times a password appears in Have I Been Pwned's breach corpus.
|
|
86
|
+
* Uses the range API: only the first 5 hex characters of the SHA-1 are
|
|
87
|
+
* sent, with response padding on. Resolves 0 on any network failure so a
|
|
88
|
+
* third-party outage never blocks sign-ups.
|
|
89
|
+
*/
|
|
90
|
+
export async function breachCount(password, { fetch: fetchImpl = globalThis.fetch, timeoutMs = 2500 } = {}) {
|
|
91
|
+
try {
|
|
92
|
+
const hash = toHex(new Uint8Array(await subtle().digest('SHA-1', utf8(password)))).toUpperCase()
|
|
93
|
+
const prefix = hash.slice(0, 5)
|
|
94
|
+
const suffix = hash.slice(5)
|
|
95
|
+
const response = await fetchImpl(`https://api.pwnedpasswords.com/range/${prefix}`, {
|
|
96
|
+
headers: { 'Add-Padding': 'true', 'User-Agent': '@tylix/auth' },
|
|
97
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
98
|
+
})
|
|
99
|
+
if (!response.ok) return 0
|
|
100
|
+
for (const line of (await response.text()).split('\n')) {
|
|
101
|
+
const [candidate, count] = line.trim().split(':')
|
|
102
|
+
if (candidate === suffix) return Number(count) || 0
|
|
103
|
+
}
|
|
104
|
+
return 0
|
|
105
|
+
} catch {
|
|
106
|
+
return 0
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* In-memory login attempt limiter, keyed by email.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* (INCR + EXPIRE) using the same function signatures.
|
|
4
|
+
* @deprecated Per-process and keyed only by account, so it neither holds
|
|
5
|
+
* across servers nor resists someone locking a victim out. Use
|
|
6
|
+
* createLoginThrottle({ store }) instead (per account+IP, per account and
|
|
7
|
+
* per IP, over a shared store). Kept for apps generated before 1.5.
|
|
9
8
|
*/
|
|
10
9
|
|
|
11
10
|
const attempts = new Map()
|
|
@@ -13,9 +12,19 @@ const attempts = new Map()
|
|
|
13
12
|
const MAX_ATTEMPTS = 5
|
|
14
13
|
const WINDOW_MS = 15 * 60 * 1000 // 15 minutes
|
|
15
14
|
const LOCKOUT_MS = 15 * 60 * 1000 // 15 minutes
|
|
15
|
+
const MAX_KEYS = 50_000
|
|
16
16
|
|
|
17
17
|
function keyFor(identifier) {
|
|
18
|
-
return String(identifier ?? '').toLowerCase()
|
|
18
|
+
return String(identifier ?? '').trim().toLowerCase()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Without this, every distinct email ever tried stays in memory forever.
|
|
22
|
+
function sweep(now) {
|
|
23
|
+
for (const [key, record] of attempts) {
|
|
24
|
+
const lockOver = !record.lockedUntil || record.lockedUntil <= now
|
|
25
|
+
if (lockOver && now - record.firstAttemptAt > WINDOW_MS) attempts.delete(key)
|
|
26
|
+
}
|
|
27
|
+
while (attempts.size >= MAX_KEYS) attempts.delete(attempts.keys().next().value)
|
|
19
28
|
}
|
|
20
29
|
|
|
21
30
|
export function checkLoginAllowed(identifier) {
|
|
@@ -35,6 +44,7 @@ export function checkLoginAllowed(identifier) {
|
|
|
35
44
|
export function recordFailedLogin(identifier) {
|
|
36
45
|
const key = keyFor(identifier)
|
|
37
46
|
const now = Date.now()
|
|
47
|
+
if (attempts.size >= MAX_KEYS) sweep(now)
|
|
38
48
|
const record = attempts.get(key) ?? {
|
|
39
49
|
count: 0,
|
|
40
50
|
firstAttemptAt: now,
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { sha256Hex } from '../core/crypto.js'
|
|
2
|
+
import { toSeconds } from '../core/keys.js'
|
|
3
|
+
|
|
4
|
+
// Rate limiting over any counter store:
|
|
5
|
+
//
|
|
6
|
+
// { increment(key, { ttlMs }) -> Promise<number>, get(key), delete(key) }
|
|
7
|
+
//
|
|
8
|
+
// The Tylix store (getStore()) already has that shape; so does a thin
|
|
9
|
+
// wrapper around Redis (INCR + PEXPIRE) or Upstash. The default memory
|
|
10
|
+
// store is per-process: fine for one server, not for several.
|
|
11
|
+
|
|
12
|
+
const MAX_MEMORY_KEYS = 100_000
|
|
13
|
+
|
|
14
|
+
export function createMemoryCounterStore({ maxKeys = MAX_MEMORY_KEYS } = {}) {
|
|
15
|
+
const entries = new Map()
|
|
16
|
+
const live = (key) => {
|
|
17
|
+
const e = entries.get(key)
|
|
18
|
+
if (!e) return null
|
|
19
|
+
if (e.expiresAt <= Date.now()) {
|
|
20
|
+
entries.delete(key)
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
return e
|
|
24
|
+
}
|
|
25
|
+
const sweep = () => {
|
|
26
|
+
const now = Date.now()
|
|
27
|
+
for (const [k, e] of entries) if (e.expiresAt <= now) entries.delete(k)
|
|
28
|
+
// Still too many (a flood of distinct keys): drop the oldest, so an
|
|
29
|
+
// attacker can't exhaust memory by rotating identifiers.
|
|
30
|
+
while (entries.size >= maxKeys) entries.delete(entries.keys().next().value)
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
async get(key) {
|
|
34
|
+
return live(key)?.value ?? null
|
|
35
|
+
},
|
|
36
|
+
async increment(key, { by = 1, ttlMs = 60_000 } = {}) {
|
|
37
|
+
const e = live(key)
|
|
38
|
+
if (e) {
|
|
39
|
+
e.value += by
|
|
40
|
+
return e.value
|
|
41
|
+
}
|
|
42
|
+
if (entries.size >= maxKeys) sweep()
|
|
43
|
+
entries.set(key, { value: by, expiresAt: Date.now() + ttlMs })
|
|
44
|
+
return by
|
|
45
|
+
},
|
|
46
|
+
async delete(key) {
|
|
47
|
+
entries.delete(key)
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Identifiers (emails, usernames) are hashed before they become store
|
|
53
|
+
// keys, so the counter store never holds a list of who tried to log in.
|
|
54
|
+
async function keyOf(name, identifier) {
|
|
55
|
+
return `rl:${name}:${(await sha256Hex(String(identifier ?? '').trim().toLowerCase())).slice(0, 32)}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Fixed-window limiter. check() counts a hit; peek() only reads.
|
|
60
|
+
* const limit = createRateLimiter({ name: 'signup', max: 10, window: '1h' })
|
|
61
|
+
* const { allowed, retryAfterSeconds } = await limit.check(ip)
|
|
62
|
+
*/
|
|
63
|
+
export function createRateLimiter({ name, max, window, store = createMemoryCounterStore() }) {
|
|
64
|
+
if (!name) throw new TypeError('createRateLimiter needs a name')
|
|
65
|
+
if (!Number.isInteger(max) || max < 1) throw new TypeError('createRateLimiter needs max >= 1')
|
|
66
|
+
const windowMs = toSeconds(window, 'window') * 1000
|
|
67
|
+
|
|
68
|
+
const slot = async (identifier) => {
|
|
69
|
+
const start = Math.floor(Date.now() / windowMs) * windowMs
|
|
70
|
+
return { key: `${await keyOf(name, identifier)}:${start}`, retryAfterSeconds: Math.max(1, Math.ceil((start + windowMs - Date.now()) / 1000)) }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
async check(identifier, { cost = 1 } = {}) {
|
|
75
|
+
const { key, retryAfterSeconds } = await slot(identifier)
|
|
76
|
+
const count = await store.increment(key, { by: cost, ttlMs: windowMs })
|
|
77
|
+
const allowed = count <= max
|
|
78
|
+
return { allowed, remaining: Math.max(0, max - count), retryAfterSeconds: allowed ? 0 : retryAfterSeconds }
|
|
79
|
+
},
|
|
80
|
+
async peek(identifier) {
|
|
81
|
+
const { key, retryAfterSeconds } = await slot(identifier)
|
|
82
|
+
const count = Number((await store.get(key)) ?? 0)
|
|
83
|
+
const allowed = count < max
|
|
84
|
+
return { allowed, remaining: Math.max(0, max - count), retryAfterSeconds: allowed ? 0 : retryAfterSeconds }
|
|
85
|
+
},
|
|
86
|
+
async reset(identifier) {
|
|
87
|
+
const { key } = await slot(identifier)
|
|
88
|
+
await store.delete?.(key)
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Brute-force protection for logins (and 2FA codes) that can't be turned
|
|
95
|
+
* into a way to lock someone else out:
|
|
96
|
+
*
|
|
97
|
+
* per account + IP 5 failures / 15 min stops guessing one account
|
|
98
|
+
* per account 50 failures / hour slows a botnet on one account
|
|
99
|
+
* per IP 100 failures / hour slows credential stuffing
|
|
100
|
+
*
|
|
101
|
+
* Only failures count, and only check() is needed before the password is
|
|
102
|
+
* verified. A victim logging in from their own IP is blocked only if
|
|
103
|
+
* someone fails 50 times on their account within the hour, from many IPs.
|
|
104
|
+
*/
|
|
105
|
+
export function createLoginThrottle({ store = createMemoryCounterStore(), name = 'login', limits = {} } = {}) {
|
|
106
|
+
const pair = createRateLimiter({ name: `${name}:pair`, store, max: limits.pair?.max ?? 5, window: limits.pair?.window ?? '15m' })
|
|
107
|
+
const account = createRateLimiter({ name: `${name}:account`, store, max: limits.account?.max ?? 50, window: limits.account?.window ?? '1h' })
|
|
108
|
+
const ip = createRateLimiter({ name: `${name}:ip`, store, max: limits.ip?.max ?? 100, window: limits.ip?.window ?? '1h' })
|
|
109
|
+
|
|
110
|
+
const pairKey = (identifier, address) => `${String(identifier ?? '').trim().toLowerCase()}|${address}`
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
/** Call before checking the password. */
|
|
114
|
+
async check({ identifier, ip: address = 'unknown' }) {
|
|
115
|
+
const results = await Promise.all([pair.peek(pairKey(identifier, address)), account.peek(identifier), ip.peek(address)])
|
|
116
|
+
const blocked = results.filter((r) => !r.allowed)
|
|
117
|
+
if (blocked.length === 0) return { allowed: true, retryAfterSeconds: 0 }
|
|
118
|
+
return { allowed: false, retryAfterSeconds: Math.max(...blocked.map((r) => r.retryAfterSeconds)) }
|
|
119
|
+
},
|
|
120
|
+
/** Call after a wrong password (or unknown account). */
|
|
121
|
+
async fail({ identifier, ip: address = 'unknown' }) {
|
|
122
|
+
await Promise.all([pair.check(pairKey(identifier, address)), account.check(identifier), ip.check(address)])
|
|
123
|
+
},
|
|
124
|
+
/** Call after a successful login: clears this account+IP's failures. */
|
|
125
|
+
async succeed({ identifier, ip: address = 'unknown' }) {
|
|
126
|
+
await pair.reset(pairKey(identifier, address))
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Sessions in any key-value store with expiry:
|
|
2
|
+
//
|
|
3
|
+
// { get(key), set(key, value, { ttlMs }), delete(key) }
|
|
4
|
+
//
|
|
5
|
+
// That is the Tylix store (getStore()), and a few lines of glue for Redis,
|
|
6
|
+
// Upstash, Vercel KV, Cloudflare KV or Deno KV. Values are plain JSON.
|
|
7
|
+
//
|
|
8
|
+
// Rotation here is check-then-set, not atomic: two refreshes of the same
|
|
9
|
+
// token landing within microseconds can both rotate (the session survives
|
|
10
|
+
// and the grace period covers the loser). Use a SQL/Prisma/model adapter
|
|
11
|
+
// if you need strict compare-and-swap.
|
|
12
|
+
export function keyValueAdapter(store, { prefix = 'auth:' } = {}) {
|
|
13
|
+
if (!store || typeof store.get !== 'function' || typeof store.set !== 'function' || typeof store.delete !== 'function') {
|
|
14
|
+
throw new TypeError('keyValueAdapter needs a store with get(key), set(key, value, { ttlMs }) and delete(key).')
|
|
15
|
+
}
|
|
16
|
+
const sessionKey = (id) => `${prefix}session:${id}`
|
|
17
|
+
const userKey = (userId) => `${prefix}user:${encodeURIComponent(String(userId))}`
|
|
18
|
+
|
|
19
|
+
const parse = (value) => (typeof value === 'string' ? JSON.parse(value) : value)
|
|
20
|
+
const ttlOf = (record) => Math.max(1000, record.expiresAt - Date.now())
|
|
21
|
+
|
|
22
|
+
async function readIndex(userId) {
|
|
23
|
+
const ids = parse(await store.get(userKey(userId)))
|
|
24
|
+
return Array.isArray(ids) ? ids : []
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function writeIndex(userId, ids, ttlMs) {
|
|
28
|
+
if (ids.length === 0) await store.delete(userKey(userId))
|
|
29
|
+
else await store.set(userKey(userId), JSON.stringify(ids), { ttlMs })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
async create(record) {
|
|
34
|
+
const ttlMs = ttlOf(record)
|
|
35
|
+
await store.set(sessionKey(record.id), JSON.stringify(record), { ttlMs })
|
|
36
|
+
const ids = await readIndex(record.userId)
|
|
37
|
+
if (!ids.includes(record.id)) ids.push(record.id)
|
|
38
|
+
// The index lives as long as the longest session could.
|
|
39
|
+
await writeIndex(record.userId, ids, Math.max(ttlMs, 400 * 86400 * 1000))
|
|
40
|
+
},
|
|
41
|
+
async get(id) {
|
|
42
|
+
const value = await store.get(sessionKey(id))
|
|
43
|
+
return value == null ? null : parse(value)
|
|
44
|
+
},
|
|
45
|
+
async update(id, patch, { expectTokenHash } = {}) {
|
|
46
|
+
const record = await this.get(id)
|
|
47
|
+
if (!record) return false
|
|
48
|
+
if (expectTokenHash !== undefined && record.tokenHash !== expectTokenHash) return false
|
|
49
|
+
const next = { ...record, ...patch }
|
|
50
|
+
await store.set(sessionKey(id), JSON.stringify(next), { ttlMs: ttlOf(next) })
|
|
51
|
+
return true
|
|
52
|
+
},
|
|
53
|
+
async delete(id) {
|
|
54
|
+
const record = await this.get(id)
|
|
55
|
+
await store.delete(sessionKey(id))
|
|
56
|
+
if (record) {
|
|
57
|
+
const ids = (await readIndex(record.userId)).filter((x) => x !== id)
|
|
58
|
+
await writeIndex(record.userId, ids, 400 * 86400 * 1000)
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
async deleteByUser(userId, { exceptId } = {}) {
|
|
62
|
+
const ids = await readIndex(userId)
|
|
63
|
+
let count = 0
|
|
64
|
+
for (const id of ids) {
|
|
65
|
+
if (id === exceptId) continue
|
|
66
|
+
await store.delete(sessionKey(id))
|
|
67
|
+
count++
|
|
68
|
+
}
|
|
69
|
+
await writeIndex(userId, exceptId && ids.includes(exceptId) ? [exceptId] : [], 400 * 86400 * 1000)
|
|
70
|
+
return count
|
|
71
|
+
},
|
|
72
|
+
async listByUser(userId) {
|
|
73
|
+
const ids = await readIndex(userId)
|
|
74
|
+
const records = []
|
|
75
|
+
const live = []
|
|
76
|
+
for (const id of ids) {
|
|
77
|
+
const record = await this.get(id)
|
|
78
|
+
if (record) {
|
|
79
|
+
records.push(record)
|
|
80
|
+
live.push(id)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (live.length !== ids.length) await writeIndex(userId, live, 400 * 86400 * 1000)
|
|
84
|
+
return records
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Sessions in this process's memory. For tests, scripts and single-process
|
|
2
|
+
// dev only: they vanish on restart and other servers can't see them.
|
|
3
|
+
export function memoryAdapter() {
|
|
4
|
+
const sessions = new Map()
|
|
5
|
+
return {
|
|
6
|
+
ephemeral: true,
|
|
7
|
+
async create(record) {
|
|
8
|
+
sessions.set(record.id, { ...record })
|
|
9
|
+
},
|
|
10
|
+
async get(id) {
|
|
11
|
+
const record = sessions.get(id)
|
|
12
|
+
return record ? { ...record } : null
|
|
13
|
+
},
|
|
14
|
+
async update(id, patch, { expectTokenHash } = {}) {
|
|
15
|
+
const record = sessions.get(id)
|
|
16
|
+
if (!record) return false
|
|
17
|
+
if (expectTokenHash !== undefined && record.tokenHash !== expectTokenHash) return false
|
|
18
|
+
Object.assign(record, patch)
|
|
19
|
+
return true
|
|
20
|
+
},
|
|
21
|
+
async delete(id) {
|
|
22
|
+
sessions.delete(id)
|
|
23
|
+
},
|
|
24
|
+
async deleteByUser(userId, { exceptId } = {}) {
|
|
25
|
+
let count = 0
|
|
26
|
+
for (const [id, record] of sessions) {
|
|
27
|
+
if (String(record.userId) === String(userId) && id !== exceptId) {
|
|
28
|
+
sessions.delete(id)
|
|
29
|
+
count++
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return count
|
|
33
|
+
},
|
|
34
|
+
async listByUser(userId) {
|
|
35
|
+
return [...sessions.values()].filter((r) => String(r.userId) === String(userId)).map((r) => ({ ...r }))
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
}
|