@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,122 @@
|
|
|
1
|
+
import type { SqlDatabase } from '@fabrika/platform'
|
|
2
|
+
import { type AuditEventInput, auditEventStatement, AuditWriter } from './audit'
|
|
3
|
+
|
|
4
|
+
export interface OAuthGrantRow {
|
|
5
|
+
id: string
|
|
6
|
+
principal_id: string
|
|
7
|
+
session_id: string
|
|
8
|
+
client_id: string
|
|
9
|
+
app: string
|
|
10
|
+
resource: string
|
|
11
|
+
/** JSON array of the consented scope names. */
|
|
12
|
+
scopes: string
|
|
13
|
+
created_at: number
|
|
14
|
+
expires_at: number
|
|
15
|
+
revoked_at: number | null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface OAuthCodeRow {
|
|
19
|
+
token_hash: string
|
|
20
|
+
grant_id: string
|
|
21
|
+
redirect_uri: string
|
|
22
|
+
challenge: string
|
|
23
|
+
expires_at: number
|
|
24
|
+
used_at: number | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface OAuthRefreshTokenRow {
|
|
28
|
+
token_hash: string
|
|
29
|
+
grant_id: string
|
|
30
|
+
expires_at: number
|
|
31
|
+
used_at: number | null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Codes and refresh tokens are addressed by hash only; the plaintext never reaches this layer. */
|
|
35
|
+
export class OAuthRepository {
|
|
36
|
+
constructor(
|
|
37
|
+
private readonly db: SqlDatabase,
|
|
38
|
+
private readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
39
|
+
) {}
|
|
40
|
+
|
|
41
|
+
/** Record a consent, its one authorization code and `audit` together. */
|
|
42
|
+
async createGrant(grant: OAuthGrantRow, code: Omit<OAuthCodeRow, 'grant_id' | 'used_at'>, audit?: AuditEventInput): Promise<void> {
|
|
43
|
+
await this.db.batch([
|
|
44
|
+
this.db.prepare(`INSERT INTO oauth_grants (id, principal_id, session_id, client_id, app, resource, scopes, created_at, expires_at, revoked_at)
|
|
45
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).bind(
|
|
46
|
+
grant.id,
|
|
47
|
+
grant.principal_id,
|
|
48
|
+
grant.session_id,
|
|
49
|
+
grant.client_id,
|
|
50
|
+
grant.app,
|
|
51
|
+
grant.resource,
|
|
52
|
+
grant.scopes,
|
|
53
|
+
grant.created_at,
|
|
54
|
+
grant.expires_at,
|
|
55
|
+
),
|
|
56
|
+
this.db.prepare('INSERT INTO oauth_codes (token_hash, grant_id, redirect_uri, challenge, expires_at, used_at) VALUES (?, ?, ?, ?, ?, NULL)')
|
|
57
|
+
.bind(code.token_hash, grant.id, code.redirect_uri, code.challenge, code.expires_at),
|
|
58
|
+
...(audit === undefined ? [] : [auditEventStatement(this.db, audit)]),
|
|
59
|
+
])
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
grant(id: string): Promise<OAuthGrantRow | null> {
|
|
63
|
+
return this.db.prepare('SELECT * FROM oauth_grants WHERE id = ?').bind(id).first<OAuthGrantRow>()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async listForPrincipal(principalId: string, before: string | undefined, limit: number): Promise<OAuthGrantRow[]> {
|
|
67
|
+
const { results } = await this.db.prepare(`SELECT * FROM oauth_grants WHERE principal_id = ?${before === undefined ? '' : ' AND id < ?'}
|
|
68
|
+
ORDER BY id DESC LIMIT ?`).bind(principalId, ...(before === undefined ? [] : [before]), limit).all<OAuthGrantRow>()
|
|
69
|
+
return results
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Revoke a grant; `audit` is written exactly when this call revoked it. */
|
|
73
|
+
async revokeGrant(id: string, now: number, audit?: AuditEventInput): Promise<void> {
|
|
74
|
+
await this.writer.run([{ sql: 'UPDATE oauth_grants SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL RETURNING id', binds: [now, id] }], audit)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Spend a code. Exactly one caller gets the row back; a replay gets null and finds it via `code`. */
|
|
78
|
+
consumeCode(tokenHash: string, now: number): Promise<OAuthCodeRow | null> {
|
|
79
|
+
return this.db.prepare('UPDATE oauth_codes SET used_at = ? WHERE token_hash = ? AND used_at IS NULL RETURNING *')
|
|
80
|
+
.bind(now, tokenHash).first<OAuthCodeRow>()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
code(tokenHash: string): Promise<OAuthCodeRow | null> {
|
|
84
|
+
return this.db.prepare('SELECT * FROM oauth_codes WHERE token_hash = ?').bind(tokenHash).first<OAuthCodeRow>()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async insertRefreshToken(row: Omit<OAuthRefreshTokenRow, 'used_at'>): Promise<void> {
|
|
88
|
+
await this.db.prepare('INSERT INTO oauth_refresh_tokens (token_hash, grant_id, expires_at, used_at) VALUES (?, ?, ?, NULL)')
|
|
89
|
+
.bind(row.token_hash, row.grant_id, row.expires_at).run()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Spend a refresh token for rotation. A second presentation gets null and finds the spent row via `refreshToken`. */
|
|
93
|
+
consumeRefreshToken(tokenHash: string, now: number): Promise<OAuthRefreshTokenRow | null> {
|
|
94
|
+
return this.db.prepare('UPDATE oauth_refresh_tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL RETURNING *')
|
|
95
|
+
.bind(now, tokenHash).first<OAuthRefreshTokenRow>()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
refreshToken(tokenHash: string): Promise<OAuthRefreshTokenRow | null> {
|
|
99
|
+
return this.db.prepare('SELECT * FROM oauth_refresh_tokens WHERE token_hash = ?').bind(tokenHash).first<OAuthRefreshTokenRow>()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Record an accepted client assertion's `jti`. False when the client already presented it: a replay. */
|
|
103
|
+
async recordClientAssertion(clientId: string, jti: string, expiresAt: number): Promise<boolean> {
|
|
104
|
+
const row = await this.db.prepare(
|
|
105
|
+
'INSERT INTO oauth_client_assertions (client_id, jti, expires_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING RETURNING jti',
|
|
106
|
+
)
|
|
107
|
+
.bind(clientId, jti, expiresAt).first<{ jti: string }>()
|
|
108
|
+
return row !== null
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Delete codes, refresh tokens and client assertion ids past expiry. Spent rows stay until then because they are what
|
|
113
|
+
* detects a replay. Grants go with their session row (`ON DELETE CASCADE`), which shares their expiry.
|
|
114
|
+
*/
|
|
115
|
+
async prune(now: number): Promise<void> {
|
|
116
|
+
await this.db.batch([
|
|
117
|
+
this.db.prepare('DELETE FROM oauth_codes WHERE expires_at <= ?').bind(now),
|
|
118
|
+
this.db.prepare('DELETE FROM oauth_refresh_tokens WHERE expires_at <= ?').bind(now),
|
|
119
|
+
this.db.prepare('DELETE FROM oauth_client_assertions WHERE expires_at <= ?').bind(now),
|
|
120
|
+
])
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type SqlDatabase } from '@fabrika/platform'
|
|
2
|
+
import { type AuditEventInput, AuditWriter } from './audit'
|
|
3
|
+
import { unixNow } from './sql'
|
|
4
|
+
|
|
5
|
+
/** The one row of `password_policy` (migration 0022). No row is the default minimum. */
|
|
6
|
+
export interface PasswordPolicyRow {
|
|
7
|
+
id: number
|
|
8
|
+
min_length: number
|
|
9
|
+
/** When an administrator last changed the minimum, in epoch seconds. */
|
|
10
|
+
updated_at: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const COLUMNS = 'id, min_length, updated_at'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The installation's minimum password length (ADR-0020). The row is the installation's, so its key is the constant 1. The
|
|
17
|
+
* caller has held the value to the runtime's floor; this stores it as given, and the reader checks it again.
|
|
18
|
+
*/
|
|
19
|
+
export class PasswordPolicyRepository {
|
|
20
|
+
constructor(
|
|
21
|
+
protected readonly db: SqlDatabase,
|
|
22
|
+
private readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
23
|
+
) {}
|
|
24
|
+
|
|
25
|
+
/** The stored row, or null when nobody ever set a minimum. */
|
|
26
|
+
async get(): Promise<PasswordPolicyRow | null> {
|
|
27
|
+
return this.db.prepare(`SELECT ${COLUMNS} FROM password_policy WHERE id = 1`).first<PasswordPolicyRow>()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Store the minimum, with its record in the same statement group. Only a value that differs from the stored one is a
|
|
32
|
+
* change, so setting the minimum it already has writes neither the row nor its record; null then.
|
|
33
|
+
*/
|
|
34
|
+
async setMinLength(minLength: number, audit: AuditEventInput): Promise<PasswordPolicyRow | null> {
|
|
35
|
+
const [row] = await this.writer.run<PasswordPolicyRow>([{
|
|
36
|
+
sql: `INSERT INTO password_policy (${COLUMNS}) VALUES (1, ?, ?)
|
|
37
|
+
ON CONFLICT (id) DO UPDATE SET min_length = excluded.min_length, updated_at = excluded.updated_at
|
|
38
|
+
WHERE password_policy.min_length <> excluded.min_length
|
|
39
|
+
RETURNING ${COLUMNS}`,
|
|
40
|
+
binds: [minLength, unixNow()],
|
|
41
|
+
}], audit)
|
|
42
|
+
return row ?? null
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import type { PrincipalAffiliation } from '@fabrika/auth-core'
|
|
2
|
+
import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
|
|
3
|
+
import { normalizeEmailIdentity } from '../email-identity'
|
|
4
|
+
import { type AuditEventInput, auditEventStatement, AuditWriter, type SqlChange, type SqlDialect } from './audit'
|
|
5
|
+
import { firstRow, unixNow } from './sql'
|
|
6
|
+
|
|
7
|
+
export interface PrincipalRow {
|
|
8
|
+
id: string
|
|
9
|
+
type: 'user' | 'service'
|
|
10
|
+
external_id: string | null
|
|
11
|
+
/** THE NORMALIZED MAILBOX (`normalizeEmailIdentity`), never the display spelling — see `PrincipalRepository`. */
|
|
12
|
+
email: string | null
|
|
13
|
+
/** Display text: the mailbox as the IdP or the inviting admin spelled it. */
|
|
14
|
+
label: string
|
|
15
|
+
disabled_at: number | null
|
|
16
|
+
activated_at: number | null
|
|
17
|
+
created_at: number
|
|
18
|
+
/** `external`: a person from outside the organization, who holds only roles declared external (ADR-0051). */
|
|
19
|
+
affiliation: PrincipalAffiliation
|
|
20
|
+
/** Moved on by every removal of one of its grants (`grantRemovalStatement`); an acceptance writes only under the one it checked. */
|
|
21
|
+
grant_revision: number
|
|
22
|
+
/**
|
|
23
|
+
* The language the person reads IAM in, as an accepted invitation named it (`InvitationOptions.locale`), or NULL for
|
|
24
|
+
* none: their application's then. Parsed at read; a value IAM no longer speaks counts as none.
|
|
25
|
+
*/
|
|
26
|
+
locale: string | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Derived principal status — invited (not activated) → active → disabled. */
|
|
30
|
+
export type PrincipalStatus = 'invited' | 'active' | 'disabled'
|
|
31
|
+
|
|
32
|
+
export function principalStatus(row: PrincipalRow): PrincipalStatus {
|
|
33
|
+
if (row.disabled_at !== null) {
|
|
34
|
+
return 'disabled'
|
|
35
|
+
}
|
|
36
|
+
if (row.type === 'user' && row.activated_at === null) {
|
|
37
|
+
return 'invited'
|
|
38
|
+
}
|
|
39
|
+
return 'active'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* IAM persistence capabilities over the `SqlDatabase` port — never a cloud-specific handle.
|
|
44
|
+
* Portable operations use prepared statements via `db.prepare(...).bind(...)`; a runtime composition
|
|
45
|
+
* root may replace one complete capability when its operation shape must differ by dialect.
|
|
46
|
+
*
|
|
47
|
+
* **ONE MAILBOX RULE.** `principals.email` holds the NORMALIZED mailbox and nothing else, so every
|
|
48
|
+
* comparison is plain equality and no query asks the engine to case-fold (SQLite's `LOWER()` is
|
|
49
|
+
* ASCII-only where Postgres's is full Unicode — the same input used to resolve differently per
|
|
50
|
+
* backend). This class is the single place that applies `normalizeEmailIdentity`: callers hand over
|
|
51
|
+
* whatever spelling they hold, the mailbox lands in `email` and the spelling in `label`.
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* On Postgres, the first statement of every transaction that writes more than one of a principal's rows among
|
|
55
|
+
* `principals`, `password_accounts`, `password_credentials`, `password_action_tokens` and `sessions`: it takes the
|
|
56
|
+
* principal row `FOR NO KEY UPDATE`, so every such writer waits at the same row before it locks anything else, and two
|
|
57
|
+
* of them never hold each other's rows. The writers: `promoteToInternal`, and `PasswordRepository`'s `upsertCredential`,
|
|
58
|
+
* `disableCredential`, `completeAction` and action-token issuance. A new one must start here too. `FOR NO KEY UPDATE`
|
|
59
|
+
* leaves a foreign-key check (an inserted session, token or grant) unblocked. `principalId` is SQL that yields the id,
|
|
60
|
+
* with its binds. SQLite and D1 run one writer at a time and need none.
|
|
61
|
+
*/
|
|
62
|
+
export function principalLockStatements(db: SqlDatabase, dialect: SqlDialect, principalId: SqlChange): SqlStatement[] {
|
|
63
|
+
if (dialect !== 'postgres') return []
|
|
64
|
+
return [db.prepare(`SELECT id FROM principals WHERE id = (${principalId.sql}) FOR NO KEY UPDATE`).bind(...principalId.binds)]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class PrincipalRepository {
|
|
68
|
+
constructor(
|
|
69
|
+
protected readonly db: SqlDatabase,
|
|
70
|
+
protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
71
|
+
) {}
|
|
72
|
+
|
|
73
|
+
// ── Principals ──────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
async getUserByExternalId(sub: string): Promise<PrincipalRow | null> {
|
|
76
|
+
return this.db
|
|
77
|
+
.prepare(`SELECT * FROM principals WHERE type = 'user' AND external_id = ?`)
|
|
78
|
+
.bind(sub)
|
|
79
|
+
.first<PrincipalRow>()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async getServiceByExternalId(commonName: string): Promise<PrincipalRow | null> {
|
|
83
|
+
return this.db
|
|
84
|
+
.prepare(`SELECT * FROM principals WHERE type = 'service' AND external_id = ?`)
|
|
85
|
+
.bind(commonName)
|
|
86
|
+
.first<PrincipalRow>()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async getPrincipalById(id: string): Promise<PrincipalRow | null> {
|
|
90
|
+
return this.db.prepare('SELECT * FROM principals WHERE id = ?').bind(id).first<PrincipalRow>()
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Keep `locale` as the language the person reads IAM in. It picks words and nothing else, so it is written alone,
|
|
95
|
+
* outside any principal's lock order, and leaves no audit record: no grant, credential or session depends on it.
|
|
96
|
+
*/
|
|
97
|
+
async setLocale(id: string, locale: string): Promise<void> {
|
|
98
|
+
await this.db.prepare('UPDATE principals SET locale = ? WHERE id = ?').bind(locale, id).run()
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Resolve a user by mailbox. `email` is normalized here, so any spelling of it finds the same row. */
|
|
102
|
+
async getUserByEmail(email: string): Promise<PrincipalRow | null> {
|
|
103
|
+
return this.db
|
|
104
|
+
.prepare(`SELECT * FROM principals WHERE type = 'user' AND email = ?`)
|
|
105
|
+
.bind(normalizeEmailIdentity(email))
|
|
106
|
+
.first<PrincipalRow>()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Refresh a returning user's mailbox/label if the token's email changed. No-op when unchanged.
|
|
111
|
+
*
|
|
112
|
+
* `IS DISTINCT FROM` is the null-safe `<>` — it must treat a NULL email as "different" so the
|
|
113
|
+
* first login of an invited row still fills it in. SQLite's `IS NOT <expr>` means the same
|
|
114
|
+
* thing but does not exist in Postgres (there `IS NOT` only takes NULL/TRUE/FALSE/UNKNOWN/
|
|
115
|
+
* DISTINCT FROM/DOCUMENT/JSON); `IS DISTINCT FROM` is standard and valid in both (SQLite ≥ 3.39).
|
|
116
|
+
*
|
|
117
|
+
* The reservation moves WITH the mailbox: leaving a stale claim behind would let the next invite
|
|
118
|
+
* of the new address create a second principal for the same human.
|
|
119
|
+
*/
|
|
120
|
+
async refreshUserLabel(id: string, email: string, audit?: AuditEventInput): Promise<void> {
|
|
121
|
+
const mailbox = normalizeEmailIdentity(email)
|
|
122
|
+
const refresh: SqlChange = {
|
|
123
|
+
sql: 'UPDATE principals SET email = ?, label = ? WHERE id = ? AND (email IS DISTINCT FROM ? OR label IS DISTINCT FROM ?) RETURNING id',
|
|
124
|
+
binds: [mailbox, email, id, mailbox, email],
|
|
125
|
+
}
|
|
126
|
+
await this.db.batch([...this.writer.changed([refresh], audit).statements, this.claimMailboxStatement(mailbox, id)])
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Claim an invited row in one statement: bind `external_id = sub`, activate it, and set the
|
|
131
|
+
* display label, but only while still unclaimed (`external_id IS NULL`) to avoid a race claiming
|
|
132
|
+
* a row twice, and only an internal one: an IdP never claims an external principal (ADR-0051). The mailbox is untouched — it is what matched this row in the first place.
|
|
133
|
+
* Returns the claimed row, or null if the row was concurrently claimed / not found.
|
|
134
|
+
*/
|
|
135
|
+
async claimInvitedUser(id: string, sub: string, label: string, audit?: AuditEventInput): Promise<PrincipalRow | null> {
|
|
136
|
+
const claim: SqlChange = {
|
|
137
|
+
sql: `UPDATE principals SET external_id = ?, label = ?, activated_at = COALESCE(activated_at, ?)
|
|
138
|
+
WHERE id = ? AND type = 'user' AND external_id IS NULL AND affiliation = 'internal'
|
|
139
|
+
RETURNING *`,
|
|
140
|
+
binds: [sub, label, unixNow(), id],
|
|
141
|
+
}
|
|
142
|
+
const [claimed] = await this.writer.run<PrincipalRow>([claim], audit)
|
|
143
|
+
return claimed ?? null
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Lazy-create a user keyed by the verified `sub`, reserving its mailbox and writing `audit` in the same transaction. */
|
|
147
|
+
async createUser(sub: string, email: string, audit?: (principalId: string) => AuditEventInput): Promise<PrincipalRow> {
|
|
148
|
+
const id = uuidv7()
|
|
149
|
+
const now = unixNow()
|
|
150
|
+
const mailbox = normalizeEmailIdentity(email)
|
|
151
|
+
return this.insertUser([
|
|
152
|
+
this.db
|
|
153
|
+
.prepare(`INSERT INTO principals (id, type, external_id, email, label, activated_at, created_at)
|
|
154
|
+
VALUES (?, 'user', ?, ?, ?, ?, ?) RETURNING *`)
|
|
155
|
+
.bind(id, sub, mailbox, email, now, now),
|
|
156
|
+
this.claimMailboxStatement(mailbox, id),
|
|
157
|
+
...(audit === undefined ? [] : [auditEventStatement(this.db, audit(id))]),
|
|
158
|
+
])
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Invite a user by mailbox (external_id NULL = unclaimed), reserving it and writing `audit` in the same transaction.
|
|
163
|
+
* An installation or a user administrator (ADR-0058) creates an `external` one; OIDC never claims it (ADR-0051).
|
|
164
|
+
*/
|
|
165
|
+
async inviteUser(
|
|
166
|
+
email: string,
|
|
167
|
+
label: string = email,
|
|
168
|
+
audit?: (principalId: string) => AuditEventInput,
|
|
169
|
+
affiliation: PrincipalAffiliation = 'internal',
|
|
170
|
+
): Promise<PrincipalRow> {
|
|
171
|
+
const id = uuidv7()
|
|
172
|
+
const mailbox = normalizeEmailIdentity(email)
|
|
173
|
+
return this.insertUser([
|
|
174
|
+
this.db
|
|
175
|
+
.prepare(`INSERT INTO principals (id, type, external_id, email, label, created_at, affiliation)
|
|
176
|
+
VALUES (?, 'user', NULL, ?, ?, ?, ?) RETURNING *`)
|
|
177
|
+
.bind(id, mailbox, label, unixNow(), affiliation),
|
|
178
|
+
this.claimMailboxStatement(mailbox, id),
|
|
179
|
+
...(audit === undefined ? [] : [auditEventStatement(this.db, audit(id))]),
|
|
180
|
+
])
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Reserve one mailbox for one principal. `principal_email_claims` is a second lock over the same
|
|
185
|
+
* rule `idx_principals_uq_email` enforces, and it moves with a principal whose address changes —
|
|
186
|
+
* every user row that carries a mailbox carries a claim for it.
|
|
187
|
+
*/
|
|
188
|
+
private claimMailboxStatement(mailbox: string, principalId: string): SqlStatement {
|
|
189
|
+
return this.db
|
|
190
|
+
.prepare(`INSERT INTO principal_email_claims (normalized_email, principal_id) VALUES (?, ?)
|
|
191
|
+
ON CONFLICT (principal_id) DO UPDATE SET normalized_email = excluded.normalized_email`)
|
|
192
|
+
.bind(mailbox, principalId)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Run a principal INSERT + its mailbox reservation as one transaction and return the new row. */
|
|
196
|
+
private async insertUser(statements: SqlStatement[]): Promise<PrincipalRow> {
|
|
197
|
+
const results = await this.db.batch<PrincipalRow>(statements)
|
|
198
|
+
const principal = results[0]?.results[0]
|
|
199
|
+
if (principal === undefined) throw new Error('expected a row from a RETURNING statement, got none')
|
|
200
|
+
return principal
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Create a native service (machine) principal. `external_id` is NULL — a native service is resolved
|
|
205
|
+
* through its `px_` credential (credential.principal_id → principal), never an external id. (The
|
|
206
|
+
* legacy CF service-token path still resolves existing services by their stored external_id.)
|
|
207
|
+
*/
|
|
208
|
+
async createService(label: string): Promise<PrincipalRow> {
|
|
209
|
+
return firstRow<PrincipalRow>(this.createServiceStatement(uuidv7(), label))
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The INSERT of a native service principal with a caller-generated id, for a batch that also writes its key. */
|
|
213
|
+
createServiceStatement(id: string, label: string): SqlStatement {
|
|
214
|
+
const now = unixNow()
|
|
215
|
+
return this.db
|
|
216
|
+
.prepare(`INSERT INTO principals (id, type, external_id, email, label, activated_at, created_at)
|
|
217
|
+
VALUES (?, 'service', NULL, NULL, ?, ?, ?) RETURNING *`)
|
|
218
|
+
.bind(id, label, now, now)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* One page of principals, newest first.
|
|
223
|
+
*
|
|
224
|
+
* `status` is evaluated in SQL rather than by filtering a full table in memory. It is derived from
|
|
225
|
+
* exactly two columns (`disabled_at`, `activated_at` — see `principalStatus`), so expressing it
|
|
226
|
+
* here costs nothing and is what makes the page a real page: filtering after the read returned a
|
|
227
|
+
* short page from a long table and made `limit` mean nothing (SEC-22).
|
|
228
|
+
*
|
|
229
|
+
* Ordering is by `id DESC` alone. `created_at` is whole seconds, so rows written in the same second
|
|
230
|
+
* have no order of their own; the id is a monotonic UUIDv7, so it both orders and paginates
|
|
231
|
+
* (`before` is a keyset cursor that can neither skip nor repeat a row).
|
|
232
|
+
*/
|
|
233
|
+
async listPrincipals(filter: {
|
|
234
|
+
type?: 'user' | 'service'
|
|
235
|
+
status?: PrincipalStatus
|
|
236
|
+
q?: string
|
|
237
|
+
before?: string
|
|
238
|
+
limit: number
|
|
239
|
+
/** Leave out workload principals: a job's or a webhook's key is not an API key. */
|
|
240
|
+
withoutWorkloads?: boolean
|
|
241
|
+
/** Leave out terminals (ADR-0067), which hold no key. */
|
|
242
|
+
withoutTerminals?: boolean
|
|
243
|
+
}): Promise<PrincipalRow[]> {
|
|
244
|
+
const where: string[] = []
|
|
245
|
+
const binds: (string | number)[] = []
|
|
246
|
+
if (filter.type) {
|
|
247
|
+
where.push('type = ?')
|
|
248
|
+
binds.push(filter.type)
|
|
249
|
+
}
|
|
250
|
+
if (filter.withoutWorkloads === true) {
|
|
251
|
+
where.push('NOT EXISTS (SELECT 1 FROM workload_principals w WHERE w.principal_id = principals.id)')
|
|
252
|
+
}
|
|
253
|
+
if (filter.withoutTerminals === true) {
|
|
254
|
+
where.push('NOT EXISTS (SELECT 1 FROM terminals t WHERE t.principal_id = principals.id)')
|
|
255
|
+
}
|
|
256
|
+
if (filter.status === 'disabled') {
|
|
257
|
+
where.push('disabled_at IS NOT NULL')
|
|
258
|
+
} else if (filter.status === 'invited') {
|
|
259
|
+
where.push(`disabled_at IS NULL AND type = 'user' AND activated_at IS NULL`)
|
|
260
|
+
} else if (filter.status === 'active') {
|
|
261
|
+
where.push(`disabled_at IS NULL AND (type <> 'user' OR activated_at IS NOT NULL)`)
|
|
262
|
+
}
|
|
263
|
+
if (filter.q) {
|
|
264
|
+
// LOWER() on BOTH sides, deliberately: SQLite's LIKE case-folds ASCII, Postgres's does
|
|
265
|
+
// not, so a bare `label LIKE ?` would silently stop matching 'Alice' for 'alice' after
|
|
266
|
+
// the port. (`ILIKE` is Postgres-only, so it is not an option.)
|
|
267
|
+
where.push('(LOWER(label) LIKE LOWER(?) OR LOWER(email) LIKE LOWER(?))')
|
|
268
|
+
binds.push(`%${filter.q}%`, `%${filter.q}%`)
|
|
269
|
+
}
|
|
270
|
+
if (filter.before !== undefined) {
|
|
271
|
+
where.push('id < ?')
|
|
272
|
+
binds.push(filter.before)
|
|
273
|
+
}
|
|
274
|
+
binds.push(filter.limit)
|
|
275
|
+
const sql = `SELECT * FROM principals${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ?`
|
|
276
|
+
const { results } = await this.db.prepare(sql).bind(...binds).all<PrincipalRow>()
|
|
277
|
+
return results
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The USER principals who can access `app` — every user holding at least one non-expired
|
|
282
|
+
* grant that applies to the app (the grant's `app` is NULL = cross-app, OR equals `app`).
|
|
283
|
+
* `DISTINCT` collapses the per-grant duplicates a principal with several grants produces.
|
|
284
|
+
* Services are excluded — this is the people directory (assignable users / actor labels),
|
|
285
|
+
* not machine principals. Disabled users ARE returned (the caller decides whether to hide
|
|
286
|
+
* them) so their labels still resolve. Ordered by label for a stable picker.
|
|
287
|
+
*/
|
|
288
|
+
async getPrincipalsForApp(app: string, options: { includeCrossApp: boolean }): Promise<PrincipalRow[]> {
|
|
289
|
+
const appFilter = options.includeCrossApp ? '(g.app IS NULL OR g.app = ?)' : 'g.app = ?'
|
|
290
|
+
const { results } = await this.db
|
|
291
|
+
.prepare(`SELECT DISTINCT p.* FROM principals p
|
|
292
|
+
JOIN grants g ON g.principal_id = p.id
|
|
293
|
+
WHERE p.type = 'user'
|
|
294
|
+
AND ${appFilter}
|
|
295
|
+
AND (g.expires_at IS NULL OR g.expires_at > ?)
|
|
296
|
+
ORDER BY p.label`)
|
|
297
|
+
.bind(app, unixNow())
|
|
298
|
+
.all<PrincipalRow>()
|
|
299
|
+
return results
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Disable a principal. Returns whether this call disabled it; `audit` is written only then. */
|
|
303
|
+
disablePrincipal(id: string, audit?: AuditEventInput): Promise<boolean> {
|
|
304
|
+
return this.guardedUpdate(this.disablePrincipalChange(id), audit)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** The disabling of a principal, as a change an audited revocation groups with others. */
|
|
308
|
+
disablePrincipalChange(id: string): SqlChange {
|
|
309
|
+
return { sql: 'UPDATE principals SET disabled_at = ? WHERE id = ? AND disabled_at IS NULL RETURNING id', binds: [unixNow(), id] }
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Enable a principal. Returns whether this call enabled it; `audit` is written only then. */
|
|
313
|
+
enablePrincipal(id: string, audit?: AuditEventInput): Promise<boolean> {
|
|
314
|
+
return this.guardedUpdate(
|
|
315
|
+
{ sql: 'UPDATE principals SET disabled_at = NULL WHERE id = ? AND disabled_at IS NOT NULL RETURNING id', binds: [id] },
|
|
316
|
+
audit,
|
|
317
|
+
)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Make an external principal internal (ADR-0051), an installation administrator's operation, and in the same
|
|
322
|
+
* transaction revoke every session it holds and spend every password action still pending: they were issued to an
|
|
323
|
+
* external person, and promotion can widen what they reach (a bootstrap mailbox becomes an installation admin).
|
|
324
|
+
* Returns whether this call promoted it; `audit` is written only then. There is no demotion.
|
|
325
|
+
*
|
|
326
|
+
* On Postgres the principal row is locked first (`principalLockStatements`), as a password action's completion does,
|
|
327
|
+
* because the three changes are one statement whose parts lock rows in no order of their own. The revocations test
|
|
328
|
+
* the affiliation themselves, so on SQLite, where they run in order, they come before the promotion.
|
|
329
|
+
*/
|
|
330
|
+
async promoteToInternal(id: string, audit?: AuditEventInput): Promise<boolean> {
|
|
331
|
+
const now = unixNow()
|
|
332
|
+
const external = `EXISTS (SELECT 1 FROM principals WHERE id = ? AND affiliation = 'external')`
|
|
333
|
+
const lock = principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [id] })
|
|
334
|
+
const promotion = this.writer.changed([
|
|
335
|
+
{
|
|
336
|
+
sql: `UPDATE sessions SET revoked_at = ? WHERE principal_id = ? AND revoked_at IS NULL AND ${external} RETURNING id`,
|
|
337
|
+
binds: [now, id, id],
|
|
338
|
+
},
|
|
339
|
+
{
|
|
340
|
+
sql: `UPDATE password_action_tokens SET consumed_at = ? WHERE principal_id = ? AND consumed_at IS NULL AND ${external} RETURNING id`,
|
|
341
|
+
binds: [now, id, id],
|
|
342
|
+
},
|
|
343
|
+
{ sql: `UPDATE principals SET affiliation = 'internal' WHERE id = ? AND affiliation = 'external' RETURNING id`, binds: [id] },
|
|
344
|
+
], audit)
|
|
345
|
+
const results = await this.db.batch([...lock, ...promotion.statements])
|
|
346
|
+
return promotion.rows(results, lock.length).length > 0
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private async guardedUpdate(update: SqlChange, audit: AuditEventInput | undefined): Promise<boolean> {
|
|
350
|
+
return (await this.writer.run([update], audit)).length > 0
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Hard-delete a principal (cancels an unclaimed invite; cascades grants). */
|
|
354
|
+
async deletePrincipal(id: string): Promise<boolean> {
|
|
355
|
+
const result = await this.db.prepare('DELETE FROM principals WHERE id = ?').bind(id).run()
|
|
356
|
+
return (result.meta.changes ?? 0) > 0
|
|
357
|
+
}
|
|
358
|
+
}
|