@fabrika/iam 0.0.0-stage → 0.9.0-dev.26
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/fabrika.config.ts +267 -0
- package/migrations/0001_init.sql +316 -0
- package/migrations/0002_oauth.sql +38 -0
- package/migrations/0003_contract_apps.sql +11 -0
- package/migrations/0004_membership.sql +93 -0
- package/migrations/0005_workloads.sql +23 -0
- package/migrations/0006_membership_transport_keys.sql +16 -0
- package/migrations/0007_member_directory.sql +7 -0
- package/migrations/0008_durable_audit.sql +28 -0
- package/migrations/0009_member_lookups.sql +7 -0
- package/migrations/0010_workload_issues.sql +6 -0
- package/migrations/0011_app_presentation.sql +15 -0
- package/migrations/0012_external_principals.sql +10 -0
- package/migrations/0013_app_mail_templates.sql +14 -0
- package/migrations/0014_invitation_wording.sql +8 -0
- package/migrations/0015_app_schema_revisions.sql +15 -0
- package/migrations/0016_principal_grant_revision.sql +9 -0
- package/migrations/0017_app_sign_ins.sql +12 -0
- package/migrations/0018_app_members.sql +13 -0
- package/migrations/0019_app_mail_html.sql +7 -0
- package/migrations/0020_public_workloads.sql +34 -0
- package/migrations/0021_installation_brand.sql +19 -0
- package/migrations/0022_password_policy.sql +12 -0
- package/migrations/0023_terminals.sql +155 -0
- package/migrations/0024_app_terminals.sql +10 -0
- package/migrations/0025_terminal_completion.sql +10 -0
- package/migrations/0026_terminal_generation.sql +12 -0
- package/migrations/0027_application_exact_actions.sql +28 -0
- package/migrations/0028_oauth_client_assertions.sql +10 -0
- package/migrations/0029_role_via.sql +6 -0
- package/migrations/0030_membership_role_via.sql +12 -0
- package/migrations/0031_person_locale.sql +11 -0
- package/migrations-postgres/0001_init.sql +331 -0
- package/migrations-postgres/0002_oauth.sql +36 -0
- package/migrations-postgres/0003_contract_apps.sql +8 -0
- package/migrations-postgres/0004_membership.sql +92 -0
- package/migrations-postgres/0005_workloads.sql +18 -0
- package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
- package/migrations-postgres/0007_member_directory.sql +7 -0
- package/migrations-postgres/0008_durable_audit.sql +8 -0
- package/migrations-postgres/0009_member_lookups.sql +7 -0
- package/migrations-postgres/0010_workload_issues.sql +6 -0
- package/migrations-postgres/0011_app_presentation.sql +15 -0
- package/migrations-postgres/0012_external_principals.sql +10 -0
- package/migrations-postgres/0013_app_mail_templates.sql +14 -0
- package/migrations-postgres/0014_invitation_wording.sql +8 -0
- package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
- package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
- package/migrations-postgres/0017_app_sign_ins.sql +12 -0
- package/migrations-postgres/0018_app_members.sql +13 -0
- package/migrations-postgres/0019_app_mail_html.sql +7 -0
- package/migrations-postgres/0020_public_workloads.sql +9 -0
- package/migrations-postgres/0021_installation_brand.sql +19 -0
- package/migrations-postgres/0022_password_policy.sql +12 -0
- package/migrations-postgres/0023_terminals.sql +70 -0
- package/migrations-postgres/0024_app_terminals.sql +10 -0
- package/migrations-postgres/0025_terminal_completion.sql +10 -0
- package/migrations-postgres/0026_terminal_generation.sql +12 -0
- package/migrations-postgres/0027_application_exact_actions.sql +28 -0
- package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
- package/migrations-postgres/0029_role_via.sql +4 -0
- package/migrations-postgres/0030_membership_role_via.sql +7 -0
- package/migrations-postgres/0031_person_locale.sql +11 -0
- package/package.json +70 -5
- package/src/admin/access.ts +47 -0
- package/src/admin/api-keys.ts +280 -0
- package/src/admin/app-people.ts +209 -0
- package/src/admin/app-schema.ts +308 -0
- package/src/admin/audit.ts +81 -0
- package/src/admin/brand.ts +54 -0
- package/src/admin/connections.ts +48 -0
- package/src/admin/context.ts +70 -0
- package/src/admin/grant-support.ts +192 -0
- package/src/admin/grants.ts +189 -0
- package/src/admin/handlers.ts +102 -0
- package/src/admin/http.ts +24 -0
- package/src/admin/membership-keys.ts +38 -0
- package/src/admin/pagination.ts +28 -0
- package/src/admin/password-policy.ts +48 -0
- package/src/admin/passwords.ts +78 -0
- package/src/admin/policies.ts +136 -0
- package/src/admin/principals.ts +226 -0
- package/src/admin/router.ts +291 -0
- package/src/admin/rpc.ts +387 -0
- package/src/admin/sessions.ts +115 -0
- package/src/admin/share-links.ts +127 -0
- package/src/admin/terminals.ts +115 -0
- package/src/admin/user-admin.ts +76 -0
- package/src/admin/workloads.ts +85 -0
- package/src/app-presentation.ts +178 -0
- package/src/app.ts +158 -0
- package/src/auth/cookies.ts +64 -0
- package/src/auth/failure.ts +25 -0
- package/src/auth/handoff.ts +136 -0
- package/src/auth/http.ts +88 -0
- package/src/auth/invitations.ts +220 -0
- package/src/auth/known-device.ts +44 -0
- package/src/auth/login.ts +162 -0
- package/src/auth/oidc-flight.ts +91 -0
- package/src/auth/oidc.ts +148 -0
- package/src/auth/password.ts +416 -0
- package/src/auth/routes.ts +108 -0
- package/src/auth/sessions.ts +249 -0
- package/src/auth/terminals.ts +284 -0
- package/src/auth.ts +193 -0
- package/src/binding-identity.ts +25 -0
- package/src/bounded-body.ts +35 -0
- package/src/catalog/cs.ts +147 -0
- package/src/catalog/en.ts +148 -0
- package/src/catalog/index.ts +122 -0
- package/src/catalog/uk.ts +164 -0
- package/src/client-address.ts +39 -0
- package/src/common-passwords.ts +37 -0
- package/src/contract-rules.ts +80 -0
- package/src/cron.ts +54 -0
- package/src/db.ts +128 -0
- package/src/delegation.ts +100 -0
- package/src/device-http.ts +39 -0
- package/src/device.ts +269 -0
- package/src/email-identity.ts +2 -0
- package/src/env.ts +132 -0
- package/src/handoff.ts +175 -0
- package/src/html.ts +4 -0
- package/src/human-admission.ts +40 -0
- package/src/identification.ts +185 -0
- package/src/index.ts +292 -0
- package/src/installation-brand.ts +82 -0
- package/src/issue.ts +265 -0
- package/src/json.ts +30 -0
- package/src/log.ts +26 -0
- package/src/membership-http.ts +135 -0
- package/src/membership.ts +1210 -0
- package/src/messages.ts +44 -0
- package/src/narrow-permissions.ts +26 -0
- package/src/node/browser-identity.ts +69 -0
- package/src/node/migrate.ts +52 -0
- package/src/node/prune.ts +34 -0
- package/src/node/runtime.ts +221 -0
- package/src/node/server.ts +104 -0
- package/src/oauth-client-auth.ts +93 -0
- package/src/oauth-client.ts +145 -0
- package/src/oauth-config.ts +72 -0
- package/src/oauth-http.ts +262 -0
- package/src/oauth.ts +272 -0
- package/src/oidc.ts +260 -0
- package/src/origin.ts +29 -0
- package/src/password-crypto.ts +148 -0
- package/src/password-db.ts +419 -0
- package/src/password-minimum.ts +44 -0
- package/src/password-pages.ts +397 -0
- package/src/password-policy.ts +79 -0
- package/src/password-service.ts +67 -0
- package/src/person-locale.ts +103 -0
- package/src/proxy-proof.ts +36 -0
- package/src/relay-mail.ts +64 -0
- package/src/repositories/app-schema.ts +550 -0
- package/src/repositories/audit.ts +405 -0
- package/src/repositories/brand.ts +66 -0
- package/src/repositories/credentials.ts +331 -0
- package/src/repositories/device.ts +137 -0
- package/src/repositories/grants.ts +404 -0
- package/src/repositories/handoff.ts +103 -0
- package/src/repositories/membership-transport.ts +49 -0
- package/src/repositories/membership.ts +875 -0
- package/src/repositories/oauth.ts +122 -0
- package/src/repositories/password-policy.ts +44 -0
- package/src/repositories/principals.ts +358 -0
- package/src/repositories/sessions.ts +339 -0
- package/src/repositories/sql.ts +23 -0
- package/src/repositories/terminals.ts +346 -0
- package/src/repositories/workloads.ts +134 -0
- package/src/request-id.ts +46 -0
- package/src/resolve.ts +396 -0
- package/src/retention.ts +34 -0
- package/src/roles.ts +54 -0
- package/src/rpc-http.ts +333 -0
- package/src/rpc-inputs.ts +110 -0
- package/src/rpc.ts +440 -0
- package/src/secret.ts +45 -0
- package/src/service.ts +59 -0
- package/src/services.ts +199 -0
- package/src/signing.ts +260 -0
- package/src/stored-chain.ts +23 -0
- package/src/stored-permissions.ts +34 -0
- package/src/terminals.ts +15 -0
- package/src/tokens.ts +506 -0
- package/src/workload-token.ts +130 -0
- package/types/fabrika.config.d.ts +11 -0
- package/types/src/admin/access.d.ts +19 -0
- package/types/src/admin/api-keys.d.ts +26 -0
- package/types/src/admin/app-people.d.ts +8 -0
- package/types/src/admin/app-schema.d.ts +32 -0
- package/types/src/admin/audit.d.ts +10 -0
- package/types/src/admin/brand.d.ts +10 -0
- package/types/src/admin/connections.d.ts +5 -0
- package/types/src/admin/context.d.ts +46 -0
- package/types/src/admin/grant-support.d.ts +59 -0
- package/types/src/admin/grants.d.ts +8 -0
- package/types/src/admin/handlers.d.ts +82 -0
- package/types/src/admin/http.d.ts +9 -0
- package/types/src/admin/membership-keys.d.ts +8 -0
- package/types/src/admin/pagination.d.ts +5 -0
- package/types/src/admin/password-policy.d.ts +9 -0
- package/types/src/admin/passwords.d.ts +5 -0
- package/types/src/admin/policies.d.ts +15 -0
- package/types/src/admin/principals.d.ts +15 -0
- package/types/src/admin/router.d.ts +75 -0
- package/types/src/admin/rpc.d.ts +6 -0
- package/types/src/admin/sessions.d.ts +14 -0
- package/types/src/admin/share-links.d.ts +21 -0
- package/types/src/admin/terminals.d.ts +13 -0
- package/types/src/admin/user-admin.d.ts +30 -0
- package/types/src/admin/workloads.d.ts +5 -0
- package/types/src/app-presentation.d.ts +86 -0
- package/types/src/app.d.ts +62 -0
- package/types/src/auth/cookies.d.ts +29 -0
- package/types/src/auth/failure.d.ts +47 -0
- package/types/src/auth/handoff.d.ts +66 -0
- package/types/src/auth/http.d.ts +29 -0
- package/types/src/auth/invitations.d.ts +18 -0
- package/types/src/auth/known-device.d.ts +12 -0
- package/types/src/auth/login.d.ts +10 -0
- package/types/src/auth/oidc-flight.d.ts +39 -0
- package/types/src/auth/oidc.d.ts +7 -0
- package/types/src/auth/password.d.ts +7 -0
- package/types/src/auth/routes.d.ts +15 -0
- package/types/src/auth/sessions.d.ts +60 -0
- package/types/src/auth/terminals.d.ts +47 -0
- package/types/src/auth.d.ts +70 -0
- package/types/src/binding-identity.d.ts +12 -0
- package/types/src/bounded-body.d.ts +12 -0
- package/types/src/catalog/cs.d.ts +2 -0
- package/types/src/catalog/en.d.ts +2 -0
- package/types/src/catalog/index.d.ts +112 -0
- package/types/src/catalog/uk.d.ts +2 -0
- package/types/src/client-address.d.ts +31 -0
- package/types/src/common-passwords.d.ts +2 -0
- package/types/src/contract-rules.d.ts +25 -0
- package/types/src/cron.d.ts +15 -0
- package/types/src/db.d.ts +58 -0
- package/types/src/delegation.d.ts +38 -0
- package/types/src/device-http.d.ts +2 -0
- package/types/src/device.d.ts +11 -0
- package/types/src/email-identity.d.ts +1 -0
- package/types/src/env.d.ts +127 -0
- package/types/src/handoff.d.ts +57 -0
- package/types/src/html.d.ts +2 -0
- package/types/src/human-admission.d.ts +22 -0
- package/types/src/identification.d.ts +30 -0
- package/types/src/index.d.ts +62 -0
- package/types/src/installation-brand.d.ts +22 -0
- package/types/src/issue.d.ts +62 -0
- package/types/src/json.d.ts +15 -0
- package/types/src/log.d.ts +15 -0
- package/types/src/membership-http.d.ts +8 -0
- package/types/src/membership.d.ts +156 -0
- package/types/src/messages.d.ts +20 -0
- package/types/src/narrow-permissions.d.ts +7 -0
- package/types/src/node/browser-identity.d.ts +1 -0
- package/types/src/node/migrate.d.ts +4 -0
- package/types/src/node/prune.d.ts +1 -0
- package/types/src/node/runtime.d.ts +51 -0
- package/types/src/node/server.d.ts +5 -0
- package/types/src/oauth-client-auth.d.ts +26 -0
- package/types/src/oauth-client.d.ts +17 -0
- package/types/src/oauth-config.d.ts +16 -0
- package/types/src/oauth-http.d.ts +7 -0
- package/types/src/oauth.d.ts +51 -0
- package/types/src/oidc.d.ts +81 -0
- package/types/src/origin.d.ts +9 -0
- package/types/src/password-crypto.d.ts +37 -0
- package/types/src/password-db.d.ts +134 -0
- package/types/src/password-minimum.d.ts +23 -0
- package/types/src/password-pages.d.ts +143 -0
- package/types/src/password-policy.d.ts +19 -0
- package/types/src/password-service.d.ts +24 -0
- package/types/src/person-locale.d.ts +50 -0
- package/types/src/proxy-proof.d.ts +21 -0
- package/types/src/relay-mail.d.ts +25 -0
- package/types/src/repositories/app-schema.d.ts +244 -0
- package/types/src/repositories/audit.d.ts +187 -0
- package/types/src/repositories/brand.d.ts +41 -0
- package/types/src/repositories/credentials.d.ts +148 -0
- package/types/src/repositories/device.d.ts +50 -0
- package/types/src/repositories/grants.d.ts +177 -0
- package/types/src/repositories/handoff.d.ts +52 -0
- package/types/src/repositories/membership-transport.d.ts +31 -0
- package/types/src/repositories/membership.d.ts +273 -0
- package/types/src/repositories/oauth.d.ts +55 -0
- package/types/src/repositories/password-policy.d.ts +25 -0
- package/types/src/repositories/principals.d.ts +159 -0
- package/types/src/repositories/sessions.d.ts +150 -0
- package/types/src/repositories/sql.d.ts +13 -0
- package/types/src/repositories/terminals.d.ts +144 -0
- package/types/src/repositories/workloads.d.ts +61 -0
- package/types/src/request-id.d.ts +25 -0
- package/types/src/resolve.d.ts +118 -0
- package/types/src/retention.d.ts +18 -0
- package/types/src/roles.d.ts +34 -0
- package/types/src/rpc-http.d.ts +53 -0
- package/types/src/rpc-inputs.d.ts +707 -0
- package/types/src/rpc.d.ts +4 -0
- package/types/src/secret.d.ts +21 -0
- package/types/src/service.d.ts +19 -0
- package/types/src/services.d.ts +72 -0
- package/types/src/signing.d.ts +72 -0
- package/types/src/stored-chain.d.ts +6 -0
- package/types/src/stored-permissions.d.ts +12 -0
- package/types/src/terminals.d.ts +7 -0
- package/types/src/tokens.d.ts +113 -0
- package/types/src/workload-token.d.ts +7 -0
- package/README.md +0 -3
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
export const PBKDF2_SHA256_ALGORITHM = 'pbkdf2-sha256'
|
|
4
|
+
/** OWASP's PBKDF2-HMAC-SHA256 cost, which the Bun process uses. */
|
|
5
|
+
export const PBKDF2_SHA256_ITERATIONS = 600_000
|
|
6
|
+
/** Production Cloudflare Workers refuse PBKDF2 above this with `NotSupportedError`; workerd, miniflare and Bun do not. */
|
|
7
|
+
export const PBKDF2_SHA256_WORKERS_MAX_ITERATIONS = 100_000
|
|
8
|
+
export const PBKDF2_SHA256_SALT_BYTES = 16
|
|
9
|
+
export const PBKDF2_SHA256_OUTPUT_BYTES = 32
|
|
10
|
+
|
|
11
|
+
export interface StoredPasswordHash {
|
|
12
|
+
algorithm: string
|
|
13
|
+
parameters: string
|
|
14
|
+
salt: string
|
|
15
|
+
passwordHash: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PasswordVerification {
|
|
19
|
+
valid: boolean
|
|
20
|
+
needsRehash: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface PasswordHasher {
|
|
24
|
+
hash(password: string): Promise<StoredPasswordHash>
|
|
25
|
+
verify(password: string, stored: StoredPasswordHash): Promise<PasswordVerification>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface Pbkdf2Parameters {
|
|
29
|
+
iterations: number
|
|
30
|
+
outputBytes: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The PBKDF2 cost a composition root picks for its runtime. */
|
|
34
|
+
export interface Pbkdf2Cost {
|
|
35
|
+
/** What `hash` derives with; a stored verifier with any other count is rehashed on login. */
|
|
36
|
+
readonly iterations: number
|
|
37
|
+
/** The most this runtime's WebCrypto derives. A stored verifier above it cannot be checked here. */
|
|
38
|
+
readonly maxIterations: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const MAX_STORED_ITERATIONS = 10_000_000
|
|
42
|
+
|
|
43
|
+
export const BUN_PBKDF2_COST: Pbkdf2Cost = { iterations: PBKDF2_SHA256_ITERATIONS, maxIterations: MAX_STORED_ITERATIONS }
|
|
44
|
+
export const WORKERS_PBKDF2_COST: Pbkdf2Cost = {
|
|
45
|
+
iterations: PBKDF2_SHA256_WORKERS_MAX_ITERATIONS,
|
|
46
|
+
maxIterations: PBKDF2_SHA256_WORKERS_MAX_ITERATIONS,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function encodeHex(bytes: Uint8Array): string {
|
|
50
|
+
let value = ''
|
|
51
|
+
for (const byte of bytes) {
|
|
52
|
+
value += byte.toString(16).padStart(2, '0')
|
|
53
|
+
}
|
|
54
|
+
return value
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function decodeHex(value: string): Uint8Array<ArrayBuffer> | null {
|
|
58
|
+
if (value.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(value)) {
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
const bytes = new Uint8Array(value.length / 2)
|
|
62
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
63
|
+
const byte = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16)
|
|
64
|
+
if (!Number.isFinite(byte)) {
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
bytes[index] = byte
|
|
68
|
+
}
|
|
69
|
+
return bytes
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const parametersSchema = z.object({
|
|
73
|
+
iterations: z.number().int().positive().max(MAX_STORED_ITERATIONS),
|
|
74
|
+
outputBytes: z.number().int().positive().max(128),
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
function parseParameters(value: string): Pbkdf2Parameters | null {
|
|
78
|
+
let parsed: unknown
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(value)
|
|
81
|
+
} catch {
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
84
|
+
const parameters = parametersSchema.safeParse(parsed)
|
|
85
|
+
return parameters.success ? parameters.data : null
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function derive(password: string, salt: Uint8Array<ArrayBuffer>, parameters: Pbkdf2Parameters): Promise<Uint8Array<ArrayBuffer>> {
|
|
89
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits'])
|
|
90
|
+
const bits = await crypto.subtle.deriveBits(
|
|
91
|
+
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: parameters.iterations },
|
|
92
|
+
key,
|
|
93
|
+
parameters.outputBytes * 8,
|
|
94
|
+
)
|
|
95
|
+
return new Uint8Array(bits)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function constantTimeEqual(left: Uint8Array, right: Uint8Array): boolean {
|
|
99
|
+
let difference = left.length ^ right.length
|
|
100
|
+
const length = Math.max(left.length, right.length)
|
|
101
|
+
for (let index = 0; index < length; index += 1) {
|
|
102
|
+
difference |= (left[index] ?? 0) ^ (right[index] ?? 0)
|
|
103
|
+
}
|
|
104
|
+
return difference === 0
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class WebCryptoPasswordHasher implements PasswordHasher {
|
|
108
|
+
private readonly current: Pbkdf2Parameters
|
|
109
|
+
|
|
110
|
+
constructor(private readonly cost: Pbkdf2Cost = BUN_PBKDF2_COST) {
|
|
111
|
+
this.current = { iterations: cost.iterations, outputBytes: PBKDF2_SHA256_OUTPUT_BYTES }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async hash(password: string): Promise<StoredPasswordHash> {
|
|
115
|
+
const salt = crypto.getRandomValues(new Uint8Array(PBKDF2_SHA256_SALT_BYTES))
|
|
116
|
+
const passwordHash = await derive(password, salt, this.current)
|
|
117
|
+
return {
|
|
118
|
+
algorithm: PBKDF2_SHA256_ALGORITHM,
|
|
119
|
+
parameters: JSON.stringify(this.current),
|
|
120
|
+
salt: encodeHex(salt),
|
|
121
|
+
passwordHash: encodeHex(passwordHash),
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async verify(password: string, stored: StoredPasswordHash): Promise<PasswordVerification> {
|
|
126
|
+
if (stored.algorithm !== PBKDF2_SHA256_ALGORITHM) {
|
|
127
|
+
return { valid: false, needsRehash: false }
|
|
128
|
+
}
|
|
129
|
+
const parameters = parseParameters(stored.parameters)
|
|
130
|
+
const salt = decodeHex(stored.salt)
|
|
131
|
+
const expected = decodeHex(stored.passwordHash)
|
|
132
|
+
if (parameters === null || salt === null || expected === null) {
|
|
133
|
+
return { valid: false, needsRehash: false }
|
|
134
|
+
}
|
|
135
|
+
if (parameters.iterations > this.cost.maxIterations) {
|
|
136
|
+
// Spend the current cost anyway, so a refused verifier answers no faster than a wrong password.
|
|
137
|
+
await derive(password, salt, this.current)
|
|
138
|
+
return { valid: false, needsRehash: false }
|
|
139
|
+
}
|
|
140
|
+
const actual = await derive(password, salt, parameters)
|
|
141
|
+
const valid = constantTimeEqual(actual, expected)
|
|
142
|
+
const needsRehash = valid
|
|
143
|
+
&& (parameters.iterations !== this.current.iterations
|
|
144
|
+
|| parameters.outputBytes !== this.current.outputBytes
|
|
145
|
+
|| salt.length !== PBKDF2_SHA256_SALT_BYTES)
|
|
146
|
+
return { valid, needsRehash }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
|
|
2
|
+
import { normalizeEmailIdentity } from './email-identity'
|
|
3
|
+
import type { StoredPasswordHash } from './password-crypto'
|
|
4
|
+
import { type AuditEventInput, auditEventStatement, AuditWriter, type SqlChange } from './repositories/audit'
|
|
5
|
+
import { principalLockStatements, type PrincipalRow } from './repositories/principals'
|
|
6
|
+
|
|
7
|
+
export type PasswordActionPurpose = 'enrollment' | 'reset'
|
|
8
|
+
export type PasswordAccountState = 'disabled' | 'pending' | 'enabled'
|
|
9
|
+
|
|
10
|
+
export interface PasswordAccountRow {
|
|
11
|
+
principal_id: string
|
|
12
|
+
state: PasswordAccountState
|
|
13
|
+
created_at: number
|
|
14
|
+
updated_at: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PasswordCredentialRow {
|
|
18
|
+
principal_id: string
|
|
19
|
+
algorithm: string
|
|
20
|
+
parameters: string
|
|
21
|
+
salt: string
|
|
22
|
+
password_hash: string
|
|
23
|
+
created_at: number
|
|
24
|
+
updated_at: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PasswordActionTokenRow {
|
|
28
|
+
id: string
|
|
29
|
+
principal_id: string
|
|
30
|
+
purpose: PasswordActionPurpose
|
|
31
|
+
token_hash: string
|
|
32
|
+
issued_by: string | null
|
|
33
|
+
expires_at: number
|
|
34
|
+
consumed_at: number | null
|
|
35
|
+
consumption_id: string | null
|
|
36
|
+
created_at: number
|
|
37
|
+
/** The application the action keeps (`presentationFor`), or NULL for one on the installation itself. */
|
|
38
|
+
app: string | null
|
|
39
|
+
/** The language its mail was written in, which the page its link opens speaks too; NULL before migration 0031. */
|
|
40
|
+
locale: string | null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A new action token: only its hash is stored. */
|
|
44
|
+
export interface ActionTokenInput {
|
|
45
|
+
principalId: string
|
|
46
|
+
purpose: PasswordActionPurpose
|
|
47
|
+
tokenHash: string
|
|
48
|
+
issuedBy?: string | null
|
|
49
|
+
expiresAt: number
|
|
50
|
+
app?: string | null
|
|
51
|
+
locale?: string | null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PasswordLoginThrottleRow {
|
|
55
|
+
login_key_hash: string
|
|
56
|
+
window_started_at: number
|
|
57
|
+
attempt_count: number
|
|
58
|
+
blocked_until: number | null
|
|
59
|
+
updated_at: number
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type PasswordLoginLookup =
|
|
63
|
+
| { status: 'missing' }
|
|
64
|
+
| { status: 'ambiguous' }
|
|
65
|
+
| { status: 'found'; principal: PrincipalRow; credential: PasswordCredentialRow }
|
|
66
|
+
|
|
67
|
+
export type PasswordActionUserLookup =
|
|
68
|
+
| { status: 'missing' }
|
|
69
|
+
| { status: 'ambiguous' }
|
|
70
|
+
| { status: 'found'; principal: PrincipalRow; account: PasswordAccountRow | null }
|
|
71
|
+
|
|
72
|
+
function unixNow(): number {
|
|
73
|
+
return Math.floor(Date.now() / 1000)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The issuance of an action, by an administrator or a recovery request: its record, and the enrollment opt-in it turns on. */
|
|
77
|
+
export interface ActionIssuance {
|
|
78
|
+
readonly audit: AuditEventInput
|
|
79
|
+
readonly enableEnrollment: boolean
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function firstRow<T>(statement: SqlStatement): Promise<T> {
|
|
83
|
+
const row = await statement.first<T>()
|
|
84
|
+
if (row === null) {
|
|
85
|
+
throw new Error('expected a row from a RETURNING statement, got none')
|
|
86
|
+
}
|
|
87
|
+
return row
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class PasswordRepository {
|
|
91
|
+
constructor(
|
|
92
|
+
protected readonly db: SqlDatabase,
|
|
93
|
+
protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
94
|
+
) {}
|
|
95
|
+
|
|
96
|
+
async getAccount(principalId: string): Promise<PasswordAccountRow | null> {
|
|
97
|
+
return this.db.prepare('SELECT * FROM password_accounts WHERE principal_id = ?').bind(principalId).first<PasswordAccountRow>()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Metadata only: a closed link may have been used, replaced or revoked. */
|
|
101
|
+
latestAction(principalId: string): Promise<Pick<PasswordActionTokenRow, 'purpose' | 'created_at' | 'expires_at' | 'consumed_at'> | null> {
|
|
102
|
+
return this.db.prepare(`SELECT purpose, created_at, expires_at, consumed_at FROM password_action_tokens
|
|
103
|
+
WHERE principal_id = ? ORDER BY id DESC LIMIT 1`).bind(principalId).first()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Preserve the administrator's opt-in independently of enrollment token lifetime. */
|
|
107
|
+
async enableEnrollment(principalId: string): Promise<void> {
|
|
108
|
+
await this.enableEnrollmentStatement(principalId).run()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private enableEnrollmentStatement(principalId: string): SqlStatement {
|
|
112
|
+
const now = unixNow()
|
|
113
|
+
return this.db.prepare(`INSERT INTO password_accounts (principal_id, state, created_at, updated_at)
|
|
114
|
+
VALUES (?, 'pending', ?, ?)
|
|
115
|
+
ON CONFLICT (principal_id) DO UPDATE SET
|
|
116
|
+
state = CASE WHEN password_accounts.state = 'enabled' THEN 'enabled' ELSE 'pending' END,
|
|
117
|
+
updated_at = excluded.updated_at`)
|
|
118
|
+
.bind(principalId, now, now)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async getCredential(principalId: string): Promise<PasswordCredentialRow | null> {
|
|
122
|
+
return this.db.prepare('SELECT * FROM password_credentials WHERE principal_id = ?').bind(principalId).first<PasswordCredentialRow>()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Match login email case-insensitively, but fail closed when legacy case variants collide. */
|
|
126
|
+
async lookupLogin(email: string): Promise<PasswordLoginLookup> {
|
|
127
|
+
const lookup = await this.lookupActionUser(email)
|
|
128
|
+
if (lookup.status !== 'found') {
|
|
129
|
+
return lookup
|
|
130
|
+
}
|
|
131
|
+
const { principal, account } = lookup
|
|
132
|
+
if (principal.disabled_at !== null || principal.activated_at === null || account?.state !== 'enabled') {
|
|
133
|
+
return { status: 'missing' }
|
|
134
|
+
}
|
|
135
|
+
const credential = await this.getCredential(principal.id)
|
|
136
|
+
return credential === null ? { status: 'missing' } : { status: 'found', principal, credential }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Resolve enrollment/reset/bootstrap candidates by mailbox.
|
|
141
|
+
*
|
|
142
|
+
* Plain equality against the stored NORMALIZED mailbox, never `LOWER(email) = LOWER(?)`: SQLite's
|
|
143
|
+
* `LOWER()` folds ASCII only where Postgres's folds all of Unicode, so the engine used to decide
|
|
144
|
+
* whether `JOSÉ@x.cz` and `josé@x.cz` were one human. `LIMIT 2` stays as the fail-closed belt —
|
|
145
|
+
* the schema forbids two rows per mailbox, and if one ever appears this refuses rather than picks.
|
|
146
|
+
*/
|
|
147
|
+
async lookupActionUser(email: string): Promise<PasswordActionUserLookup> {
|
|
148
|
+
const { results } = await this.db.prepare(`SELECT * FROM principals
|
|
149
|
+
WHERE type = 'user' AND email = ?
|
|
150
|
+
ORDER BY id
|
|
151
|
+
LIMIT 2`)
|
|
152
|
+
.bind(normalizeEmailIdentity(email))
|
|
153
|
+
.all<PrincipalRow>()
|
|
154
|
+
if (results.length === 0) {
|
|
155
|
+
return { status: 'missing' }
|
|
156
|
+
}
|
|
157
|
+
if (results.length > 1) {
|
|
158
|
+
return { status: 'ambiguous' }
|
|
159
|
+
}
|
|
160
|
+
const principal = results[0]
|
|
161
|
+
if (principal === undefined) {
|
|
162
|
+
return { status: 'missing' }
|
|
163
|
+
}
|
|
164
|
+
return { status: 'found', principal, account: await this.getAccount(principal.id) }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Replace the password, activate the principal, revoke prior password sessions, and write `audit`, atomically. */
|
|
168
|
+
async upsertCredential(principalId: string, password: StoredPasswordHash, audit?: AuditEventInput): Promise<void> {
|
|
169
|
+
const now = unixNow()
|
|
170
|
+
await this.db.batch([
|
|
171
|
+
...principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [principalId] }),
|
|
172
|
+
this.db.prepare(`INSERT INTO password_accounts (principal_id, state, created_at, updated_at)
|
|
173
|
+
VALUES (?, 'enabled', ?, ?)
|
|
174
|
+
ON CONFLICT (principal_id) DO UPDATE SET state = 'enabled', updated_at = excluded.updated_at`)
|
|
175
|
+
.bind(principalId, now, now),
|
|
176
|
+
this.db.prepare(`INSERT INTO password_credentials
|
|
177
|
+
(principal_id, algorithm, parameters, salt, password_hash, created_at, updated_at)
|
|
178
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
179
|
+
ON CONFLICT (principal_id) DO UPDATE SET
|
|
180
|
+
algorithm = excluded.algorithm,
|
|
181
|
+
parameters = excluded.parameters,
|
|
182
|
+
salt = excluded.salt,
|
|
183
|
+
password_hash = excluded.password_hash,
|
|
184
|
+
updated_at = excluded.updated_at`)
|
|
185
|
+
.bind(principalId, password.algorithm, password.parameters, password.salt, password.passwordHash, now, now),
|
|
186
|
+
this.db.prepare(`UPDATE principals SET activated_at = COALESCE(activated_at, ?)
|
|
187
|
+
WHERE id = ? AND type = 'user'`).bind(now, principalId),
|
|
188
|
+
this.revokePasswordSessionsStatement(principalId, now),
|
|
189
|
+
...(audit === undefined ? [] : [auditEventStatement(this.db, audit)]),
|
|
190
|
+
])
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Remove password login and revoke only sessions that originated from a password. */
|
|
194
|
+
async disableCredential(principalId: string, audit?: AuditEventInput): Promise<void> {
|
|
195
|
+
const now = unixNow()
|
|
196
|
+
await this.db.batch([
|
|
197
|
+
...principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [principalId] }),
|
|
198
|
+
this.db.prepare(`INSERT INTO password_accounts (principal_id, state, created_at, updated_at)
|
|
199
|
+
VALUES (?, 'disabled', ?, ?)
|
|
200
|
+
ON CONFLICT (principal_id) DO UPDATE SET state = 'disabled', updated_at = excluded.updated_at`)
|
|
201
|
+
.bind(principalId, now, now),
|
|
202
|
+
this.db.prepare('DELETE FROM password_credentials WHERE principal_id = ?').bind(principalId),
|
|
203
|
+
this.db.prepare(`UPDATE password_action_tokens SET consumed_at = ?
|
|
204
|
+
WHERE principal_id = ? AND consumed_at IS NULL`).bind(now, principalId),
|
|
205
|
+
this.revokePasswordSessionsStatement(principalId, now),
|
|
206
|
+
...(audit === undefined ? [] : [auditEventStatement(this.db, audit)]),
|
|
207
|
+
])
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async revokePasswordSessions(principalId: string): Promise<number> {
|
|
211
|
+
const result = await this.revokePasswordSessionsStatement(principalId, unixNow()).run()
|
|
212
|
+
return result.meta.changes
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private revokePasswordSessionsStatement(principalId: string, now: number): SqlStatement {
|
|
216
|
+
return this.db.prepare(`UPDATE sessions SET revoked_at = ?
|
|
217
|
+
WHERE principal_id = ? AND authentication_method = 'password' AND revoked_at IS NULL`).bind(now, principalId)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Supersede active tokens for the same action, then persist only the new token hash. */
|
|
221
|
+
async issueActionToken(input: ActionTokenInput, issuance?: ActionIssuance): Promise<string> {
|
|
222
|
+
const id = uuidv7()
|
|
223
|
+
const now = unixNow()
|
|
224
|
+
try {
|
|
225
|
+
await this.replaceActionToken(id, now, input, issuance)
|
|
226
|
+
} catch {
|
|
227
|
+
// A concurrent issuer may win the active-token unique index; retry once for last-writer-wins.
|
|
228
|
+
await this.replaceActionToken(id, now, input, issuance)
|
|
229
|
+
}
|
|
230
|
+
return id
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private async replaceActionToken(
|
|
234
|
+
id: string,
|
|
235
|
+
now: number,
|
|
236
|
+
input: ActionTokenInput,
|
|
237
|
+
issuance: ActionIssuance | undefined,
|
|
238
|
+
): Promise<void> {
|
|
239
|
+
await this.db.batch([
|
|
240
|
+
...principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [input.principalId] }),
|
|
241
|
+
...(issuance?.enableEnrollment === true ? [this.enableEnrollmentStatement(input.principalId)] : []),
|
|
242
|
+
this.db.prepare(`UPDATE password_action_tokens SET consumed_at = ?
|
|
243
|
+
WHERE principal_id = ? AND purpose = ? AND consumed_at IS NULL`).bind(now, input.principalId, input.purpose),
|
|
244
|
+
this.db.prepare(`INSERT INTO password_action_tokens
|
|
245
|
+
(id, principal_id, purpose, token_hash, issued_by, expires_at, consumed_at, consumption_id, created_at, app, locale)
|
|
246
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)`)
|
|
247
|
+
.bind(
|
|
248
|
+
id,
|
|
249
|
+
input.principalId,
|
|
250
|
+
input.purpose,
|
|
251
|
+
input.tokenHash,
|
|
252
|
+
input.issuedBy ?? null,
|
|
253
|
+
input.expiresAt,
|
|
254
|
+
now,
|
|
255
|
+
input.app ?? null,
|
|
256
|
+
input.locale ?? null,
|
|
257
|
+
),
|
|
258
|
+
...(issuance === undefined ? [] : [auditEventStatement(this.db, issuance.audit)]),
|
|
259
|
+
])
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Atomically mark one valid action token used and return it; concurrent consumers lose. */
|
|
263
|
+
async consumeActionToken(tokenHash: string, purpose: PasswordActionPurpose): Promise<PasswordActionTokenRow | null> {
|
|
264
|
+
const now = unixNow()
|
|
265
|
+
return this.db.prepare(`UPDATE password_action_tokens SET consumed_at = ?
|
|
266
|
+
WHERE token_hash = ? AND purpose = ? AND consumed_at IS NULL AND expires_at > ?
|
|
267
|
+
RETURNING *`).bind(now, tokenHash, purpose, now).first<PasswordActionTokenRow>()
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Validate a scanner-safe GET without consuming the token. */
|
|
271
|
+
async inspectActionToken(tokenHash: string, purpose: PasswordActionPurpose): Promise<PasswordActionTokenRow | null> {
|
|
272
|
+
return this.db.prepare(`SELECT t.* FROM password_action_tokens t
|
|
273
|
+
JOIN principals p ON p.id = t.principal_id
|
|
274
|
+
JOIN password_accounts a ON a.principal_id = t.principal_id
|
|
275
|
+
WHERE t.token_hash = ? AND t.purpose = ? AND t.consumed_at IS NULL AND t.expires_at > ?
|
|
276
|
+
AND p.disabled_at IS NULL AND a.state <> 'disabled'`)
|
|
277
|
+
.bind(tokenHash, purpose, unixNow())
|
|
278
|
+
.first<PasswordActionTokenRow>()
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Consume an action token and replace the credential as one race-safe transaction, with `audit` written exactly when
|
|
283
|
+
* this call consumed the token.
|
|
284
|
+
*/
|
|
285
|
+
async completeAction(input: {
|
|
286
|
+
tokenHash: string
|
|
287
|
+
purpose: PasswordActionPurpose
|
|
288
|
+
password: StoredPasswordHash
|
|
289
|
+
}, audit?: AuditEventInput): Promise<{ principalId: string } | null> {
|
|
290
|
+
const now = unixNow()
|
|
291
|
+
const consumptionId = uuidv7()
|
|
292
|
+
const consume: SqlChange = {
|
|
293
|
+
sql: `UPDATE password_action_tokens SET consumed_at = ?, consumption_id = ?
|
|
294
|
+
WHERE token_hash = ? AND purpose = ? AND consumed_at IS NULL AND expires_at > ?
|
|
295
|
+
AND EXISTS (
|
|
296
|
+
SELECT 1 FROM principals p
|
|
297
|
+
JOIN password_accounts a ON a.principal_id = p.id
|
|
298
|
+
WHERE p.id = password_action_tokens.principal_id
|
|
299
|
+
AND p.disabled_at IS NULL AND a.state <> 'disabled'
|
|
300
|
+
)
|
|
301
|
+
RETURNING *`,
|
|
302
|
+
binds: [now, consumptionId, input.tokenHash, input.purpose, now],
|
|
303
|
+
}
|
|
304
|
+
const consumed = this.writer.changed([consume], audit)
|
|
305
|
+
// The principal before the token, as a promotion locks it (`principalLockStatements`).
|
|
306
|
+
const lock = principalLockStatements(this.db, this.writer.dialect, {
|
|
307
|
+
sql: 'SELECT principal_id FROM password_action_tokens WHERE token_hash = ?',
|
|
308
|
+
binds: [input.tokenHash],
|
|
309
|
+
})
|
|
310
|
+
const results = await this.db.batch<PasswordActionTokenRow>([
|
|
311
|
+
...lock,
|
|
312
|
+
...consumed.statements,
|
|
313
|
+
this.db.prepare(`INSERT INTO password_accounts (principal_id, state, created_at, updated_at)
|
|
314
|
+
SELECT principal_id, 'enabled', ?, ? FROM password_action_tokens WHERE consumption_id = ?
|
|
315
|
+
ON CONFLICT (principal_id) DO UPDATE SET state = 'enabled', updated_at = excluded.updated_at`)
|
|
316
|
+
.bind(now, now, consumptionId),
|
|
317
|
+
this.db.prepare(`INSERT INTO password_credentials
|
|
318
|
+
(principal_id, algorithm, parameters, salt, password_hash, created_at, updated_at)
|
|
319
|
+
SELECT principal_id, ?, ?, ?, ?, ?, ? FROM password_action_tokens WHERE consumption_id = ?
|
|
320
|
+
ON CONFLICT (principal_id) DO UPDATE SET
|
|
321
|
+
algorithm = excluded.algorithm,
|
|
322
|
+
parameters = excluded.parameters,
|
|
323
|
+
salt = excluded.salt,
|
|
324
|
+
password_hash = excluded.password_hash,
|
|
325
|
+
updated_at = excluded.updated_at`)
|
|
326
|
+
.bind(input.password.algorithm, input.password.parameters, input.password.salt, input.password.passwordHash, now, now, consumptionId),
|
|
327
|
+
this.db.prepare(`UPDATE principals SET activated_at = COALESCE(activated_at, ?)
|
|
328
|
+
WHERE id = (SELECT principal_id FROM password_action_tokens WHERE consumption_id = ?)
|
|
329
|
+
AND type = 'user'`).bind(now, consumptionId),
|
|
330
|
+
this.db.prepare(`UPDATE sessions SET revoked_at = ?
|
|
331
|
+
WHERE principal_id = (SELECT principal_id FROM password_action_tokens WHERE consumption_id = ?)
|
|
332
|
+
AND authentication_method = 'password' AND revoked_at IS NULL`).bind(now, consumptionId),
|
|
333
|
+
])
|
|
334
|
+
const principalId = consumed.rows(results, lock.length)[0]?.principal_id
|
|
335
|
+
return principalId === undefined ? null : { principalId }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async getLoginThrottle(loginKeyHash: string): Promise<PasswordLoginThrottleRow | null> {
|
|
339
|
+
return this.db.prepare('SELECT * FROM password_login_throttles WHERE login_key_hash = ?')
|
|
340
|
+
.bind(loginKeyHash)
|
|
341
|
+
.first<PasswordLoginThrottleRow>()
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Atomically record one failed login and establish a fixed-window block at the threshold. */
|
|
345
|
+
async recordLoginFailure(input: {
|
|
346
|
+
loginKeyHash: string
|
|
347
|
+
windowSeconds: number
|
|
348
|
+
maxAttempts: number
|
|
349
|
+
blockSeconds: number
|
|
350
|
+
}): Promise<PasswordLoginThrottleRow> {
|
|
351
|
+
if (!Number.isSafeInteger(input.windowSeconds) || input.windowSeconds <= 0) {
|
|
352
|
+
throw new Error('windowSeconds must be a positive integer')
|
|
353
|
+
}
|
|
354
|
+
if (!Number.isSafeInteger(input.maxAttempts) || input.maxAttempts <= 0) {
|
|
355
|
+
throw new Error('maxAttempts must be a positive integer')
|
|
356
|
+
}
|
|
357
|
+
if (!Number.isSafeInteger(input.blockSeconds) || input.blockSeconds <= 0) {
|
|
358
|
+
throw new Error('blockSeconds must be a positive integer')
|
|
359
|
+
}
|
|
360
|
+
const now = unixNow()
|
|
361
|
+
const windowCutoff = now - input.windowSeconds
|
|
362
|
+
return firstRow<PasswordLoginThrottleRow>(
|
|
363
|
+
this.db.prepare(`INSERT INTO password_login_throttles
|
|
364
|
+
(login_key_hash, window_started_at, attempt_count, blocked_until, updated_at)
|
|
365
|
+
VALUES (?, ?, 1, CASE WHEN ? <= 1 THEN ? ELSE NULL END, ?)
|
|
366
|
+
ON CONFLICT (login_key_hash) DO UPDATE SET
|
|
367
|
+
window_started_at = CASE
|
|
368
|
+
WHEN password_login_throttles.window_started_at <= ? THEN excluded.window_started_at
|
|
369
|
+
ELSE password_login_throttles.window_started_at END,
|
|
370
|
+
attempt_count = CASE
|
|
371
|
+
WHEN password_login_throttles.blocked_until > ? THEN password_login_throttles.attempt_count
|
|
372
|
+
WHEN password_login_throttles.window_started_at <= ? THEN 1
|
|
373
|
+
ELSE password_login_throttles.attempt_count + 1 END,
|
|
374
|
+
blocked_until = CASE
|
|
375
|
+
WHEN password_login_throttles.blocked_until > ? THEN password_login_throttles.blocked_until
|
|
376
|
+
WHEN password_login_throttles.window_started_at <= ? AND ? <= 1 THEN ?
|
|
377
|
+
WHEN password_login_throttles.window_started_at > ? AND password_login_throttles.attempt_count + 1 >= ? THEN ?
|
|
378
|
+
ELSE NULL END,
|
|
379
|
+
updated_at = excluded.updated_at
|
|
380
|
+
RETURNING *`)
|
|
381
|
+
.bind(
|
|
382
|
+
input.loginKeyHash,
|
|
383
|
+
now,
|
|
384
|
+
input.maxAttempts,
|
|
385
|
+
now + input.blockSeconds,
|
|
386
|
+
now,
|
|
387
|
+
windowCutoff,
|
|
388
|
+
now,
|
|
389
|
+
windowCutoff,
|
|
390
|
+
now,
|
|
391
|
+
windowCutoff,
|
|
392
|
+
input.maxAttempts,
|
|
393
|
+
now + input.blockSeconds,
|
|
394
|
+
windowCutoff,
|
|
395
|
+
input.maxAttempts,
|
|
396
|
+
now + input.blockSeconds,
|
|
397
|
+
),
|
|
398
|
+
)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async clearLoginFailures(loginKeyHash: string): Promise<void> {
|
|
402
|
+
await this.db.prepare('DELETE FROM password_login_throttles WHERE login_key_hash = ?').bind(loginKeyHash).run()
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async pruneLoginThrottles(olderThan: number): Promise<number> {
|
|
406
|
+
const result = await this.db.prepare('DELETE FROM password_login_throttles WHERE updated_at < ? AND (blocked_until IS NULL OR blocked_until < ?)')
|
|
407
|
+
.bind(olderThan, unixNow())
|
|
408
|
+
.run()
|
|
409
|
+
return result.meta.changes
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async pruneActionTokens(olderThan: number): Promise<number> {
|
|
413
|
+
const result = await this.db.prepare(`DELETE FROM password_action_tokens
|
|
414
|
+
WHERE expires_at < ? OR (consumed_at IS NOT NULL AND consumed_at < ?)`)
|
|
415
|
+
.bind(olderThan, olderThan)
|
|
416
|
+
.run()
|
|
417
|
+
return result.meta.changes
|
|
418
|
+
}
|
|
419
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { PASSWORD_DEFAULT_MIN_LENGTH, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH_FLOOR } from '@fabrika/iam-contract'
|
|
2
|
+
import { PBKDF2_SHA256_ITERATIONS, type Pbkdf2Cost } from './password-crypto'
|
|
3
|
+
import type { PasswordPolicyRow } from './repositories/password-policy'
|
|
4
|
+
import type { Services } from './services'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The lowest minimum this runtime accepts. A short password survives a leaked database only as long as its verifier is
|
|
8
|
+
* expensive, so the floor is low only where `hash` derives with OWASP's PBKDF2 cost (the Bun process). A Worker derives
|
|
9
|
+
* a sixth of it (backlog 201) and keeps the default as its floor until it hashes with a stronger algorithm.
|
|
10
|
+
*/
|
|
11
|
+
export function passwordMinLengthFloor(cost: Pbkdf2Cost): number {
|
|
12
|
+
return cost.iterations >= PBKDF2_SHA256_ITERATIONS ? PASSWORD_MIN_LENGTH_FLOOR : PASSWORD_DEFAULT_MIN_LENGTH
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Why a minimum cannot be stored, in the words the administration API answers with; null when it can. */
|
|
16
|
+
export function minLengthProblem(minLength: number, floor: number): string | null {
|
|
17
|
+
if (!Number.isInteger(minLength)) return 'the minimum password length must be a whole number'
|
|
18
|
+
if (minLength < floor) return `the minimum password length cannot be below ${floor} on this installation`
|
|
19
|
+
if (minLength > PASSWORD_MAX_LENGTH) return `the minimum password length cannot be above ${PASSWORD_MAX_LENGTH}`
|
|
20
|
+
return null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The minimum a stored row sets, checked again as the administration API checks it: no row is the default, and a row this
|
|
25
|
+
* runtime would not accept (one an installation on another runtime wrote, or a hand edit) is the default too, never a
|
|
26
|
+
* value below the floor.
|
|
27
|
+
*/
|
|
28
|
+
export function storedMinLength(row: PasswordPolicyRow | null, floor: number): number {
|
|
29
|
+
if (row === null) return PASSWORD_DEFAULT_MIN_LENGTH
|
|
30
|
+
if (minLengthProblem(row.min_length, floor) !== null) {
|
|
31
|
+
console.warn('password policy: the stored minimum is outside what this runtime accepts, so the default applies')
|
|
32
|
+
return PASSWORD_DEFAULT_MIN_LENGTH
|
|
33
|
+
}
|
|
34
|
+
return row.min_length
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The minimum every new password meets, read once per request. A read that fails throws, like every other read of the
|
|
39
|
+
* request it serves: falling back to the default would accept a shorter password than an installation that raised the
|
|
40
|
+
* minimum requires.
|
|
41
|
+
*/
|
|
42
|
+
export async function passwordMinLength(services: Services): Promise<number> {
|
|
43
|
+
return storedMinLength(await services.repositories.passwordPolicy.get(), services.config.authentication.password.minLengthFloor)
|
|
44
|
+
}
|