@fabrika/iam 0.0.1 → 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 +69 -8
- 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,346 @@
|
|
|
1
|
+
import { parseJsonStringArray } from '@fabrika/auth-core'
|
|
2
|
+
import { type SqlDatabase, type SqlStatement } from '@fabrika/platform'
|
|
3
|
+
import { type AuditEventInput, AuditWriter, type AuthLogInput, authLogStatement, type SqlChange, type SqlGuard } from './audit'
|
|
4
|
+
import type { LogoutLogInput } from './sessions'
|
|
5
|
+
import { unixNow } from './sql'
|
|
6
|
+
|
|
7
|
+
/** How long a person's session on a terminal lasts unless its profile says otherwise (ADR-0067). */
|
|
8
|
+
export const DEFAULT_TERMINAL_SESSION_TTL_SECONDS = 300
|
|
9
|
+
|
|
10
|
+
/** The longest session a terminal's profile may set; the `terminals.session_ttl` CHECK states the same bound. */
|
|
11
|
+
export const MAX_TERMINAL_SESSION_TTL_SECONDS = 3600
|
|
12
|
+
|
|
13
|
+
/** An enrolled browser (the `terminals` table), the side table of its `service` principal. */
|
|
14
|
+
export interface TerminalRow {
|
|
15
|
+
principal_id: string
|
|
16
|
+
label: string
|
|
17
|
+
/** The administrator who enrolled it; null once that principal is gone. */
|
|
18
|
+
enrolled_by: string | null
|
|
19
|
+
/** SHA-256 of the `__Host-px_terminal` cookie value. */
|
|
20
|
+
token_hash: string
|
|
21
|
+
session_ttl: number
|
|
22
|
+
created_at: number
|
|
23
|
+
last_seen_at: number | null
|
|
24
|
+
revoked_at: number | null
|
|
25
|
+
/** Incremented by every release; the sessions and identifications of an earlier generation are over. */
|
|
26
|
+
generation: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** An application that may assert a person on a terminal, with its ceiling of action patterns. */
|
|
30
|
+
export interface TerminalAsserter {
|
|
31
|
+
app: string
|
|
32
|
+
ceiling: string[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What a terminal is for: its name, who may assert on it and how long a session on it lasts. */
|
|
36
|
+
export interface TerminalProfile {
|
|
37
|
+
label: string
|
|
38
|
+
asserters: TerminalAsserter[]
|
|
39
|
+
sessionTtl: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One identification IAM opened for a terminal's browser (the `terminal_identifications` table). */
|
|
43
|
+
export interface TerminalIdentificationRow {
|
|
44
|
+
id_hash: string
|
|
45
|
+
terminal_id: string
|
|
46
|
+
app: string
|
|
47
|
+
return_url: string
|
|
48
|
+
handoff_state: string
|
|
49
|
+
handoff_challenge: string
|
|
50
|
+
created_at: number
|
|
51
|
+
expires_at: number
|
|
52
|
+
consumed_at: number | null
|
|
53
|
+
/** The login an assertion opened for the person; the terminal's browser completes the identification with it. */
|
|
54
|
+
session_id: string | null
|
|
55
|
+
/** When the terminal's browser completed the identification and IAM issued the handoff code. */
|
|
56
|
+
completed_at: number | null
|
|
57
|
+
/** The terminal's generation the identification was opened in; it is over once the terminal's moves on. */
|
|
58
|
+
generation: number
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface TerminalAsserterRow {
|
|
62
|
+
terminal_id: string
|
|
63
|
+
app: string
|
|
64
|
+
ceiling: string
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Terminals and their identifications (ADR-0067). A terminal is a `service` principal plus its row here; enrolment
|
|
69
|
+
* composes `PrincipalRepository.createServiceStatement` with `enrolStatement` in one batch.
|
|
70
|
+
*/
|
|
71
|
+
export class TerminalRepository {
|
|
72
|
+
constructor(
|
|
73
|
+
protected readonly db: SqlDatabase,
|
|
74
|
+
protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
75
|
+
) {}
|
|
76
|
+
|
|
77
|
+
/** The INSERT of a terminal beside its service principal `principalId`, which the same batch creates first. */
|
|
78
|
+
enrolStatement(input: { principalId: string; label: string; enrolledBy: string; tokenHash: string; sessionTtl: number }): SqlStatement {
|
|
79
|
+
return this.db
|
|
80
|
+
.prepare(`INSERT INTO terminals (principal_id, label, enrolled_by, token_hash, session_ttl, created_at)
|
|
81
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
82
|
+
.bind(input.principalId, input.label, input.enrolledBy, input.tokenHash, input.sessionTtl, unixNow())
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The enrolled terminal whose cookie hashes to `tokenHash`; null when there is none or it was revoked. */
|
|
86
|
+
async getActiveByTokenHash(tokenHash: string): Promise<TerminalRow | null> {
|
|
87
|
+
return this.db.prepare('SELECT * FROM terminals WHERE token_hash = ? AND revoked_at IS NULL').bind(tokenHash).first<TerminalRow>()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A terminal by its principal id, revoked or not — the admin read. */
|
|
91
|
+
async getById(terminalId: string): Promise<TerminalRow | null> {
|
|
92
|
+
return this.db.prepare('SELECT * FROM terminals WHERE principal_id = ?').bind(terminalId).first<TerminalRow>()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** One page of terminals, newest first, revoked or not. `before` is a keyset cursor over the UUIDv7 principal id. */
|
|
96
|
+
async list(options: { before?: string; limit: number }): Promise<TerminalRow[]> {
|
|
97
|
+
const where = options.before === undefined ? '' : ' WHERE principal_id < ?'
|
|
98
|
+
const binds = options.before === undefined ? [options.limit] : [options.before, options.limit]
|
|
99
|
+
const { results } = await this.db
|
|
100
|
+
.prepare(`SELECT * FROM terminals${where} ORDER BY principal_id DESC LIMIT ?`)
|
|
101
|
+
.bind(...binds)
|
|
102
|
+
.all<TerminalRow>()
|
|
103
|
+
return results
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The applications that may assert on the terminal, each with its ceiling. A malformed ceiling reads as empty. */
|
|
107
|
+
async listAsserters(terminalId: string): Promise<TerminalAsserter[]> {
|
|
108
|
+
return (await this.listAssertersFor([terminalId])).get(terminalId) ?? []
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The asserters of every terminal in `terminalIds`, in one query — the fan-out of one admin page. */
|
|
112
|
+
async listAssertersFor(terminalIds: readonly string[]): Promise<Map<string, TerminalAsserter[]>> {
|
|
113
|
+
const byTerminal = new Map<string, TerminalAsserter[]>()
|
|
114
|
+
if (terminalIds.length === 0) {
|
|
115
|
+
return byTerminal
|
|
116
|
+
}
|
|
117
|
+
const { results } = await this.db
|
|
118
|
+
.prepare(`SELECT terminal_id, app, ceiling FROM terminal_asserters WHERE terminal_id IN (${terminalIds.map(() => '?').join(', ')})
|
|
119
|
+
ORDER BY terminal_id, app`)
|
|
120
|
+
.bind(...terminalIds)
|
|
121
|
+
.all<TerminalAsserterRow>()
|
|
122
|
+
for (const row of results) {
|
|
123
|
+
const asserters = byTerminal.get(row.terminal_id) ?? []
|
|
124
|
+
asserters.push(toAsserter(row))
|
|
125
|
+
byTerminal.set(row.terminal_id, asserters)
|
|
126
|
+
}
|
|
127
|
+
return byTerminal
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `app`'s entry on the terminal, or null when `app` may not assert there. */
|
|
131
|
+
async getAsserter(terminalId: string, app: string): Promise<TerminalAsserter | null> {
|
|
132
|
+
const row = await this.db
|
|
133
|
+
.prepare('SELECT terminal_id, app, ceiling FROM terminal_asserters WHERE terminal_id = ? AND app = ?')
|
|
134
|
+
.bind(terminalId, app)
|
|
135
|
+
.first<TerminalAsserterRow>()
|
|
136
|
+
return row === null ? null : toAsserter(row)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Replace an enrolled terminal's profile in one batch: its label (on its principal too, which audit rows name), its
|
|
141
|
+
* session TTL and its whole set of asserters. Answers false, and changes nothing, when the terminal is unknown or
|
|
142
|
+
* revoked; `audit` is written only when it changed.
|
|
143
|
+
*/
|
|
144
|
+
async setProfile(terminalId: string, profile: TerminalProfile, audit?: AuditEventInput): Promise<boolean> {
|
|
145
|
+
const enrolled = 'SELECT 1 FROM terminals WHERE principal_id = ? AND revoked_at IS NULL'
|
|
146
|
+
const update: SqlChange = {
|
|
147
|
+
sql: 'UPDATE terminals SET label = ?, session_ttl = ? WHERE principal_id = ? AND revoked_at IS NULL RETURNING principal_id',
|
|
148
|
+
binds: [profile.label, profile.sessionTtl, terminalId],
|
|
149
|
+
}
|
|
150
|
+
const change = this.writer.changed([update], audit)
|
|
151
|
+
const asserters: SqlStatement[] = [
|
|
152
|
+
this.db.prepare(`UPDATE principals SET label = ? WHERE id = ? AND EXISTS (${enrolled})`).bind(profile.label, terminalId, terminalId),
|
|
153
|
+
this.db.prepare(`DELETE FROM terminal_asserters WHERE terminal_id = ? AND EXISTS (${enrolled})`).bind(terminalId, terminalId),
|
|
154
|
+
...profile.asserters.map((asserter) =>
|
|
155
|
+
this.db
|
|
156
|
+
.prepare(`INSERT INTO terminal_asserters (terminal_id, app, ceiling) SELECT ?, ?, ? WHERE EXISTS (${enrolled})`)
|
|
157
|
+
.bind(terminalId, asserter.app, JSON.stringify(asserter.ceiling), terminalId)
|
|
158
|
+
),
|
|
159
|
+
]
|
|
160
|
+
const results = await this.db.batch([...change.statements, ...asserters])
|
|
161
|
+
return change.rows(results).length > 0
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Revoke a terminal, every session issued on it and every identification still pending on it, in one transaction. Idempotent: answers false, and writes no
|
|
166
|
+
* `audit`, when the terminal was already revoked or is unknown. The validity join ends its sessions either way; the
|
|
167
|
+
* sessions are revoked too so an operator sees them ended.
|
|
168
|
+
*/
|
|
169
|
+
async revoke(terminalId: string, audit?: AuditEventInput): Promise<boolean> {
|
|
170
|
+
const now = unixNow()
|
|
171
|
+
const changes: SqlChange[] = [
|
|
172
|
+
endIdentificationsChange(terminalId, now),
|
|
173
|
+
revokeSessionsChange(terminalId, now),
|
|
174
|
+
{ sql: 'UPDATE terminals SET revoked_at = ? WHERE principal_id = ? AND revoked_at IS NULL RETURNING principal_id', binds: [now, terminalId] },
|
|
175
|
+
]
|
|
176
|
+
return (await this.writer.run(changes, audit)).length > 0
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Release the terminal, as its sign-out does (ADR-0067 §5), in one transaction: move it to its next generation, which
|
|
181
|
+
* ends every session and identification of the current one at once, however an assertion in flight interleaves; then
|
|
182
|
+
* end its pending identifications and revoke its live sessions, so an operator sees them ended. Answers how many
|
|
183
|
+
* sessions. A sign-out passes `log`: each login this call ends gets its `logout` row, with the login's principal,
|
|
184
|
+
* terminal and asserter, like `SessionRepository.revokeSessionByHash`. Its children end with it through the join.
|
|
185
|
+
*/
|
|
186
|
+
async release(terminalId: string, log?: LogoutLogInput): Promise<number> {
|
|
187
|
+
const now = unixNow()
|
|
188
|
+
const ended = endIdentificationsChange(terminalId, now)
|
|
189
|
+
const before = [
|
|
190
|
+
this.db.prepare('UPDATE terminals SET generation = generation + 1 WHERE principal_id = ?').bind(terminalId),
|
|
191
|
+
this.db.prepare(ended.sql).bind(...ended.binds),
|
|
192
|
+
]
|
|
193
|
+
const revoke = revokeSessionsChange(terminalId, now)
|
|
194
|
+
if (log === undefined) {
|
|
195
|
+
const results = await this.db.batch([...before, this.db.prepare(revoke.sql).bind(...revoke.binds)])
|
|
196
|
+
return results[before.length]?.results.length ?? 0
|
|
197
|
+
}
|
|
198
|
+
const values = [log.requestId, log.app, log.reason ?? null, now]
|
|
199
|
+
const columns = '(request_id, app, kind, principal_id, credential_id, decision, reason, privileged, created_at, terminal_id, asserted_by)'
|
|
200
|
+
const logged = "SELECT ?, ?, 'logout', principal_id, NULL, 'allow', ?, 0, ?, terminal_id, asserted_by"
|
|
201
|
+
if (this.writer.dialect === 'postgres') {
|
|
202
|
+
const results = await this.db.batch([
|
|
203
|
+
...before,
|
|
204
|
+
this.db
|
|
205
|
+
.prepare(`WITH changed AS (${revoke.sql}), logged AS (
|
|
206
|
+
INSERT INTO auth_log ${columns} ${logged} FROM changed WHERE parent_session_id IS NULL
|
|
207
|
+
) SELECT id FROM changed`)
|
|
208
|
+
.bind(...revoke.binds, ...values),
|
|
209
|
+
])
|
|
210
|
+
return results[before.length]?.results.length ?? 0
|
|
211
|
+
}
|
|
212
|
+
// SQLite serializes writers, so the logins read here are exactly the ones the UPDATE after it ends.
|
|
213
|
+
const results = await this.db.batch([
|
|
214
|
+
...before,
|
|
215
|
+
this.db
|
|
216
|
+
.prepare(`INSERT INTO auth_log ${columns} ${logged} FROM sessions
|
|
217
|
+
WHERE terminal_id = ? AND revoked_at IS NULL AND parent_session_id IS NULL`)
|
|
218
|
+
.bind(...values, terminalId),
|
|
219
|
+
this.db.prepare(revoke.sql).bind(...revoke.binds),
|
|
220
|
+
])
|
|
221
|
+
return results[before.length + 1]?.results.length ?? 0
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ── Identifications ───────────────────────────────────────────────────────
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Open an identification and record that its terminal was seen now, in one batch with `log`, the identification's
|
|
228
|
+
* `auth_log` row. Only the hash of its id is stored; the plaintext lives in one redirect.
|
|
229
|
+
*/
|
|
230
|
+
async createIdentification(input: {
|
|
231
|
+
idHash: string
|
|
232
|
+
terminalId: string
|
|
233
|
+
app: string
|
|
234
|
+
returnUrl: string
|
|
235
|
+
handoffState: string
|
|
236
|
+
handoffChallenge: string
|
|
237
|
+
expiresAt: number
|
|
238
|
+
}, log?: AuthLogInput): Promise<void> {
|
|
239
|
+
const now = unixNow()
|
|
240
|
+
await this.db.batch([
|
|
241
|
+
this.db
|
|
242
|
+
.prepare(`INSERT INTO terminal_identifications
|
|
243
|
+
(id_hash, terminal_id, app, return_url, handoff_state, handoff_challenge, created_at, expires_at, generation)
|
|
244
|
+
SELECT ?, ?, ?, ?, ?, ?, ?, ?, generation FROM terminals WHERE principal_id = ?`)
|
|
245
|
+
.bind(
|
|
246
|
+
input.idHash,
|
|
247
|
+
input.terminalId,
|
|
248
|
+
input.app,
|
|
249
|
+
input.returnUrl,
|
|
250
|
+
input.handoffState,
|
|
251
|
+
input.handoffChallenge,
|
|
252
|
+
now,
|
|
253
|
+
input.expiresAt,
|
|
254
|
+
input.terminalId,
|
|
255
|
+
),
|
|
256
|
+
this.db.prepare('UPDATE terminals SET last_seen_at = ? WHERE principal_id = ?').bind(now, input.terminalId),
|
|
257
|
+
...(log === undefined ? [] : [authLogStatement(this.db, log)]),
|
|
258
|
+
])
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** An identification by its id's hash, in any state — the caller judges expiry and consumption. */
|
|
262
|
+
async getIdentification(idHash: string): Promise<TerminalIdentificationRow | null> {
|
|
263
|
+
return this.db.prepare('SELECT * FROM terminal_identifications WHERE id_hash = ?').bind(idHash).first<TerminalIdentificationRow>()
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Consume an identification for the login `sessionId`, atomically and at most once, and give its completion until
|
|
268
|
+
* `completeBy`. `login` is the batch that opens that login, written only when this call consumed the identification
|
|
269
|
+
* (see `consumedFor`), so a failed write leaves the identification open and a refused consumption opens nothing.
|
|
270
|
+
* Answers the row this call consumed, or null for an unknown, expired, cancelled or already consumed one.
|
|
271
|
+
*/
|
|
272
|
+
async consumeIdentification(
|
|
273
|
+
consumption: { idHash: string; sessionId: string; now: number; completeBy: number },
|
|
274
|
+
login: readonly SqlStatement[] = [],
|
|
275
|
+
): Promise<TerminalIdentificationRow | null> {
|
|
276
|
+
const { idHash, sessionId, now, completeBy } = consumption
|
|
277
|
+
const [consumed] = await this.db.batch<TerminalIdentificationRow>([
|
|
278
|
+
this.db
|
|
279
|
+
.prepare(`UPDATE terminal_identifications SET consumed_at = ?, session_id = ?, expires_at = ?
|
|
280
|
+
WHERE id_hash = ? AND consumed_at IS NULL AND expires_at > ?
|
|
281
|
+
AND generation = (SELECT t.generation FROM terminals t WHERE t.principal_id = terminal_identifications.terminal_id AND t.revoked_at IS NULL)
|
|
282
|
+
RETURNING *`)
|
|
283
|
+
.bind(now, sessionId, completeBy, idHash, now),
|
|
284
|
+
...login,
|
|
285
|
+
])
|
|
286
|
+
return consumed?.results[0] ?? null
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The guard of the statements after `consumeIdentification` in its batch: the identification is consumed for `sessionId`. */
|
|
290
|
+
consumedFor(idHash: string, sessionId: string): SqlGuard {
|
|
291
|
+
return { sql: 'SELECT 1 FROM terminal_identifications WHERE id_hash = ? AND session_id = ?', binds: [idHash, sessionId] }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Complete an asserted identification of `terminalId`, atomically and at most once: the terminal's own browser asks,
|
|
296
|
+
* before the completion window closes. Null for any other identification, a second completion included.
|
|
297
|
+
*/
|
|
298
|
+
async completeIdentification(idHash: string, terminalId: string, now: number): Promise<TerminalIdentificationRow | null> {
|
|
299
|
+
return this.db
|
|
300
|
+
.prepare(`UPDATE terminal_identifications SET completed_at = ?
|
|
301
|
+
WHERE id_hash = ? AND terminal_id = ? AND session_id IS NOT NULL AND completed_at IS NULL AND expires_at > ? RETURNING *`)
|
|
302
|
+
.bind(now, idHash, terminalId, now)
|
|
303
|
+
.first<TerminalIdentificationRow>()
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** End an open identification of `app` that the person abandoned. Answers false when there was none to end. */
|
|
307
|
+
async cancelIdentification(idHash: string, app: string): Promise<boolean> {
|
|
308
|
+
const result = await this.db
|
|
309
|
+
.prepare('UPDATE terminal_identifications SET consumed_at = ? WHERE id_hash = ? AND app = ? AND consumed_at IS NULL')
|
|
310
|
+
.bind(unixNow(), idHash, app)
|
|
311
|
+
.run()
|
|
312
|
+
return (result.meta.changes ?? 0) > 0
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Prune expired, cancelled and completed identifications (cron). An asserted one waits for its completion until it
|
|
317
|
+
* expires. Returns the number removed.
|
|
318
|
+
*/
|
|
319
|
+
async pruneIdentifications(now: number): Promise<number> {
|
|
320
|
+
const result = await this.db
|
|
321
|
+
.prepare(`DELETE FROM terminal_identifications
|
|
322
|
+
WHERE expires_at < ? OR completed_at IS NOT NULL OR (consumed_at IS NOT NULL AND session_id IS NULL)`)
|
|
323
|
+
.bind(now)
|
|
324
|
+
.run()
|
|
325
|
+
return result.meta.changes ?? 0
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function endIdentificationsChange(terminalId: string, now: number): SqlChange {
|
|
330
|
+
return {
|
|
331
|
+
sql: 'UPDATE terminal_identifications SET consumed_at = ? WHERE terminal_id = ? AND consumed_at IS NULL RETURNING id_hash',
|
|
332
|
+
binds: [now, terminalId],
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function revokeSessionsChange(terminalId: string, now: number): SqlChange {
|
|
337
|
+
return {
|
|
338
|
+
sql: `UPDATE sessions SET revoked_at = ? WHERE terminal_id = ? AND revoked_at IS NULL
|
|
339
|
+
RETURNING id, principal_id, terminal_id, asserted_by, parent_session_id`,
|
|
340
|
+
binds: [now, terminalId],
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function toAsserter(row: TerminalAsserterRow): TerminalAsserter {
|
|
345
|
+
return { app: row.app, ceiling: parseJsonStringArray(row.ceiling) }
|
|
346
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { parseJsonStringArray, type WorkloadKind } from '@fabrika/auth-core'
|
|
2
|
+
import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
|
|
3
|
+
import { auditEventAboutStatement, type AuditEventInput } from './audit'
|
|
4
|
+
import type { PrincipalRow } from './principals'
|
|
5
|
+
import { unixNow } from './sql'
|
|
6
|
+
|
|
7
|
+
/** A workload's identity (the `workload_principals` table). */
|
|
8
|
+
export interface WorkloadPrincipalRow {
|
|
9
|
+
principal_id: string
|
|
10
|
+
app: string
|
|
11
|
+
kind: WorkloadKind
|
|
12
|
+
name: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* One workload a schema reconcile declared (the `app_workloads` table). `actions` is a JSON array of exact actions;
|
|
17
|
+
* `issues` the link mount a job may issue links of, or null.
|
|
18
|
+
*/
|
|
19
|
+
export interface AppWorkloadRow {
|
|
20
|
+
app: string
|
|
21
|
+
kind: WorkloadKind
|
|
22
|
+
name: string
|
|
23
|
+
actions: string
|
|
24
|
+
issues: string | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What the app's schema declares for one workload now. */
|
|
28
|
+
export interface WorkloadDeclaration {
|
|
29
|
+
actions: string[]
|
|
30
|
+
issues: string | null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A workload's principal is a `service` row under this external id, which the (type, external_id) index keeps unique. */
|
|
34
|
+
function workloadExternalId(app: string, kind: WorkloadKind, name: string): string {
|
|
35
|
+
return `workload:${app}:${kind}:${name}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Workload principals and their declared actions (ADR-0022 "Principal kinds"). Issuing a key creates the principal;
|
|
40
|
+
* the schema reconcile declares what it may do (`AppSchemaRepository.reconcileAppSchema` writes `app_workloads`).
|
|
41
|
+
*/
|
|
42
|
+
export class WorkloadRepository {
|
|
43
|
+
constructor(protected readonly db: SqlDatabase) {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Issue one key of a workload in ONE transaction: the principal and its identity on first use, the revocation of every
|
|
47
|
+
* other live key except `keep`, the key, and `audit` about the principal. The principal is addressed by its external
|
|
48
|
+
* id throughout, and both identity inserts do nothing on a conflict, so two concurrent first issuances end with one
|
|
49
|
+
* principal that holds both keys' history. Answers the principal's id.
|
|
50
|
+
*/
|
|
51
|
+
async issueKey(
|
|
52
|
+
input: {
|
|
53
|
+
app: string
|
|
54
|
+
kind: WorkloadKind
|
|
55
|
+
name: string
|
|
56
|
+
credentialId: string
|
|
57
|
+
tokenHash: string
|
|
58
|
+
issuedBy: string
|
|
59
|
+
expiresAt: number
|
|
60
|
+
keep: string | null
|
|
61
|
+
},
|
|
62
|
+
audit: AuditEventInput,
|
|
63
|
+
): Promise<string> {
|
|
64
|
+
const externalId = workloadExternalId(input.app, input.kind, input.name)
|
|
65
|
+
const label = `${input.kind}:${input.name}`
|
|
66
|
+
const now = unixNow()
|
|
67
|
+
const principal = { sql: `SELECT id FROM principals WHERE type = 'service' AND external_id = ?`, binds: [externalId] }
|
|
68
|
+
const statements: SqlStatement[] = [
|
|
69
|
+
...this.identityStatements(input.app, input.kind, input.name, externalId, label, now),
|
|
70
|
+
this.db
|
|
71
|
+
.prepare(`UPDATE credentials SET revoked_at = ? WHERE principal_id = (${principal.sql}) AND revoked_at IS NULL AND id <> ?`)
|
|
72
|
+
.bind(now, externalId, input.keep ?? ''),
|
|
73
|
+
this.db
|
|
74
|
+
.prepare(`INSERT INTO credentials (id, token_hash, label, principal_id, app, issued_by, expires_at, created_at)
|
|
75
|
+
SELECT ?, ?, label, id, ?, ?, ?, ? FROM principals WHERE type = 'service' AND external_id = ?`)
|
|
76
|
+
.bind(input.credentialId, input.tokenHash, input.app, input.issuedBy, input.expiresAt, now, externalId),
|
|
77
|
+
auditEventAboutStatement(this.db, audit, principal),
|
|
78
|
+
]
|
|
79
|
+
await this.db.batch(statements)
|
|
80
|
+
const principalId = await this.findPrincipalId(input.app, input.kind, input.name)
|
|
81
|
+
if (principalId === null) throw new Error('a workload principal vanished after its key was issued')
|
|
82
|
+
return principalId
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The workload's principal, or null when no key was ever issued for it. */
|
|
86
|
+
async findPrincipal(app: string, kind: WorkloadKind, name: string): Promise<PrincipalRow | null> {
|
|
87
|
+
return this.db
|
|
88
|
+
.prepare(`SELECT p.* FROM principals p JOIN workload_principals w ON w.principal_id = p.id
|
|
89
|
+
WHERE w.app = ? AND w.kind = ? AND w.name = ?`)
|
|
90
|
+
.bind(app, kind, name)
|
|
91
|
+
.first<PrincipalRow>()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private identityStatements(app: string, kind: WorkloadKind, name: string, externalId: string, label: string, now: number): SqlStatement[] {
|
|
95
|
+
return [
|
|
96
|
+
this.db
|
|
97
|
+
.prepare(`INSERT INTO principals (id, type, external_id, email, label, activated_at, created_at)
|
|
98
|
+
VALUES (?, 'service', ?, NULL, ?, ?, ?) ON CONFLICT DO NOTHING`)
|
|
99
|
+
.bind(uuidv7(), externalId, label, now, now),
|
|
100
|
+
this.db
|
|
101
|
+
.prepare(`INSERT INTO workload_principals (principal_id, app, kind, name)
|
|
102
|
+
SELECT id, ?, ?, ? FROM principals WHERE type = 'service' AND external_id = ?
|
|
103
|
+
ON CONFLICT DO NOTHING`)
|
|
104
|
+
.bind(app, kind, name, externalId),
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The workload's principal id, or null when no key was ever issued for it. */
|
|
109
|
+
async findPrincipalId(app: string, kind: WorkloadKind, name: string): Promise<string | null> {
|
|
110
|
+
const row = await this.db
|
|
111
|
+
.prepare('SELECT principal_id FROM workload_principals WHERE app = ? AND kind = ? AND name = ?')
|
|
112
|
+
.bind(app, kind, name)
|
|
113
|
+
.first<{ principal_id: string }>()
|
|
114
|
+
return row?.principal_id ?? null
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async getByPrincipal(principalId: string): Promise<WorkloadPrincipalRow | null> {
|
|
118
|
+
return this.db.prepare('SELECT * FROM workload_principals WHERE principal_id = ?').bind(principalId).first<WorkloadPrincipalRow>()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The workload's declared actions, or null when the app's schema declares no such workload. */
|
|
122
|
+
async declaredActions(app: string, kind: WorkloadKind, name: string): Promise<string[] | null> {
|
|
123
|
+
return (await this.declaration(app, kind, name))?.actions ?? null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The workload's declaration, or null when the app's schema declares no such workload. */
|
|
127
|
+
async declaration(app: string, kind: WorkloadKind, name: string): Promise<WorkloadDeclaration | null> {
|
|
128
|
+
const row = await this.db
|
|
129
|
+
.prepare('SELECT * FROM app_workloads WHERE app = ? AND kind = ? AND name = ?')
|
|
130
|
+
.bind(app, kind, name)
|
|
131
|
+
.first<AppWorkloadRow>()
|
|
132
|
+
return row === null ? null : { actions: parseJsonStringArray(row.actions), issues: row.issues }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The correlation id written to `auth_log` and `audit_events`, and the rule about where it may come from.
|
|
3
|
+
*
|
|
4
|
+
* Same shape as `src/client-address.ts`: IAM does not choose a header. The COMPOSITION ROOT names the
|
|
5
|
+
* one header its own ingress overwrites, and shared code reads that one and nothing else. Naming none
|
|
6
|
+
* is supported and means every request gets a generated id.
|
|
7
|
+
*
|
|
8
|
+
* - `src/index.ts` (Cloudflare) — `cf-ray`. The Worker holds its own Custom Domain, so no proxy hop
|
|
9
|
+
* strips a caller's `X-Request-Id`; only the edge-written ray id is outside the caller's reach.
|
|
10
|
+
* - `src/node/server.ts` (Bun/Zerops) — `X-Request-Id`, which the Caddy proxy deletes at ingress and
|
|
11
|
+
* re-injects. Once the installation's proxy secret is configured, a request without it gets a
|
|
12
|
+
* generated id (`src/proxy-proof.ts`).
|
|
13
|
+
*
|
|
14
|
+
* Even a trusted header is bounded: an audit column never takes an unbounded or free-form string. The
|
|
15
|
+
* `IamRpc` surface (`src/rpc.ts`) holds the `requestId` its callers pass to the same rule.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Longest id we store. A UUID is 36 characters and a `cf-ray` about 20. */
|
|
19
|
+
const MAX_LENGTH = 64
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The characters a UUID, a UUIDv7, or a `cf-ray` (`<hex>-<colo>`) use. It excludes `,` and space, so
|
|
23
|
+
* the `", "` join that `Headers.get` applies to a repeated header never passes.
|
|
24
|
+
*/
|
|
25
|
+
const ALLOWED = /^[A-Za-z0-9._:-]+$/
|
|
26
|
+
|
|
27
|
+
/** A fresh id, for a composition that names no header or a request whose value was refused. */
|
|
28
|
+
export function generateRequestId(): string {
|
|
29
|
+
return crypto.randomUUID()
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Read the id from the named header, or generate one when the header is unnamed, absent, or invalid. */
|
|
33
|
+
export function readRequestId(request: Request, header: string | undefined, generate: () => string = generateRequestId): string {
|
|
34
|
+
if (header === undefined || header === '') {
|
|
35
|
+
return generate()
|
|
36
|
+
}
|
|
37
|
+
return acceptRequestId(request.headers.get(header), generate)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Keep a correlation id that is within the length cap and the allowlist, or replace it with a generated
|
|
42
|
+
* one. Never truncated: a cut id could collide with another request's trail.
|
|
43
|
+
*/
|
|
44
|
+
export function acceptRequestId(value: string | null, generate: () => string = generateRequestId): string {
|
|
45
|
+
return value !== null && value.length <= MAX_LENGTH && ALLOWED.test(value) ? value : generate()
|
|
46
|
+
}
|