@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,331 @@
|
|
|
1
|
+
import type { Scope } from '@fabrika/auth-core'
|
|
2
|
+
import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
|
|
3
|
+
|
|
4
|
+
import { type AuditEventInput, auditEventStatement, AuditWriter, type SqlChange } from './audit'
|
|
5
|
+
import { unixNow } from './sql'
|
|
6
|
+
|
|
7
|
+
/** What a new credential carries: its secret's hash, its binding and its inline grants. */
|
|
8
|
+
export interface CreateCredentialInput {
|
|
9
|
+
tokenHash: string
|
|
10
|
+
label?: string | null
|
|
11
|
+
principalId?: string | null
|
|
12
|
+
/** The app the credential mints for. NULL = cross-app; illegal for an anonymous credential. */
|
|
13
|
+
app?: string | null
|
|
14
|
+
issuedBy: string
|
|
15
|
+
expiresAt?: number | null
|
|
16
|
+
grants: { action: string; scopeType?: string | null; scopeValue?: string | null }[]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A unified credential row (the `credentials` table). Only the secret's hash is stored. */
|
|
20
|
+
export interface CredentialRow {
|
|
21
|
+
id: string
|
|
22
|
+
token_hash: string
|
|
23
|
+
label: string | null
|
|
24
|
+
/** Bound principal (live perms), or NULL for an anonymous (frozen inline-grant) credential. */
|
|
25
|
+
principal_id: string | null
|
|
26
|
+
/**
|
|
27
|
+
* The app this credential may mint for. NULL = cross-app, which is legal ONLY for a
|
|
28
|
+
* principal-bound credential (its permissions are still resolved per app through `grants`) and is
|
|
29
|
+
* REFUSED for an anonymous one, whose frozen grants were delegation-checked against exactly one
|
|
30
|
+
* app at issue time. See `resolveCredential`.
|
|
31
|
+
*/
|
|
32
|
+
app: string | null
|
|
33
|
+
issued_by: string | null
|
|
34
|
+
expires_at: number | null
|
|
35
|
+
revoked_at: number | null
|
|
36
|
+
created_at: number
|
|
37
|
+
/** The link mount of a share link; NULL on every other credential. */
|
|
38
|
+
link_mount: string | null
|
|
39
|
+
/** The dimension of the object the link is bound to, as the mount declared it at issue. */
|
|
40
|
+
link_dimension: string | null
|
|
41
|
+
/** JSON array of the link's containment chain (`{type, value}`, the object first). */
|
|
42
|
+
link_chain: string | null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One inline grant on a credential (the `credential_grants` table). Matched by `permits`. */
|
|
46
|
+
export interface CredentialGrantRow {
|
|
47
|
+
credential_id: string
|
|
48
|
+
action: string
|
|
49
|
+
scope_type: string | null
|
|
50
|
+
scope_value: string | null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export class CredentialRepository {
|
|
54
|
+
constructor(
|
|
55
|
+
protected readonly db: SqlDatabase,
|
|
56
|
+
protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
57
|
+
) {}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Insert a credential + its inline grant rows (if any) in one batch, with `audit` when given. Only the hash is
|
|
61
|
+
* stored. `principalId` null = an anonymous (frozen-grant) credential; non-null = principal-bound.
|
|
62
|
+
*/
|
|
63
|
+
async createCredential(input: CreateCredentialInput, audit?: (credentialId: string) => AuditEventInput): Promise<string> {
|
|
64
|
+
const id = uuidv7()
|
|
65
|
+
await this.db.batch([...this.credentialStatements(id, input), ...(audit === undefined ? [] : [auditEventStatement(this.db, audit(id))])])
|
|
66
|
+
return id
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The INSERTs of one credential with a caller-generated id and its inline grants, for a batch with its record. A
|
|
71
|
+
* credential not bound to its issuer (a service key, a standalone key) holds authority of its own, so an external
|
|
72
|
+
* issuer, whose authority is only its live external roles, writes none (ADR-0051): the guard's NOT NULL violation
|
|
73
|
+
* rolls the batch back, behind `issueKey`'s refusal.
|
|
74
|
+
*/
|
|
75
|
+
credentialStatements(id: string, input: CreateCredentialInput): SqlStatement[] {
|
|
76
|
+
const independent = (input.principalId ?? null) !== input.issuedBy
|
|
77
|
+
const statements: SqlStatement[] = [
|
|
78
|
+
...(independent
|
|
79
|
+
? [
|
|
80
|
+
this.db
|
|
81
|
+
.prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL WHERE EXISTS (
|
|
82
|
+
SELECT 1 FROM principals WHERE id = ? AND affiliation = 'external')`)
|
|
83
|
+
.bind(`${input.issuedBy}#external-issuer`, input.issuedBy),
|
|
84
|
+
]
|
|
85
|
+
: []),
|
|
86
|
+
this.db
|
|
87
|
+
.prepare(`INSERT INTO credentials (id, token_hash, label, principal_id, app, issued_by, expires_at, created_at)
|
|
88
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
89
|
+
.bind(
|
|
90
|
+
id,
|
|
91
|
+
input.tokenHash,
|
|
92
|
+
input.label ?? null,
|
|
93
|
+
input.principalId ?? null,
|
|
94
|
+
input.app ?? null,
|
|
95
|
+
input.issuedBy,
|
|
96
|
+
input.expiresAt ?? null,
|
|
97
|
+
unixNow(),
|
|
98
|
+
),
|
|
99
|
+
]
|
|
100
|
+
for (const grant of input.grants) {
|
|
101
|
+
statements.push(
|
|
102
|
+
this.db
|
|
103
|
+
.prepare('INSERT INTO credential_grants (credential_id, action, scope_type, scope_value) VALUES (?, ?, ?, ?)')
|
|
104
|
+
.bind(id, grant.action, grant.scopeType ?? null, grant.scopeValue ?? null),
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
return statements
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Insert a share link and its grants only while the app's schema still declares exactly what `checked` says was
|
|
112
|
+
* authorized: the mount with its dimension, grants, issuing action and lifetime, the chain's containment, and for
|
|
113
|
+
* a job its actions and the mount it issues — all in one transaction. The first statement locks the mount row with
|
|
114
|
+
* the one row lock SQLite and Postgres share (D1 runs a batch serially anyway); every reconcile deletes and rewrites
|
|
115
|
+
* that row, so one already writing makes this wait and then compare against what it committed, and one that comes
|
|
116
|
+
* later waits for this key. Returns the id, or null when the declaration changed; `audit` is written exactly when
|
|
117
|
+
* the key is.
|
|
118
|
+
*/
|
|
119
|
+
async createLinkCredential(
|
|
120
|
+
input: {
|
|
121
|
+
tokenHash: string
|
|
122
|
+
label: string
|
|
123
|
+
app: string
|
|
124
|
+
issuedBy: string
|
|
125
|
+
expiresAt: number
|
|
126
|
+
grants: { action: string; scopeType: string; scopeValue: string }[]
|
|
127
|
+
link: { mount: string; chain: Scope[] }
|
|
128
|
+
checked: CheckedLinkDeclaration
|
|
129
|
+
},
|
|
130
|
+
audit?: (credentialId: string) => AuditEventInput,
|
|
131
|
+
): Promise<string | null> {
|
|
132
|
+
const id = uuidv7()
|
|
133
|
+
const dimension = input.link.chain[0]?.type ?? ''
|
|
134
|
+
const declared = declaredLink(input.app, input.link, input.checked)
|
|
135
|
+
const insert: SqlChange = {
|
|
136
|
+
sql: `INSERT INTO credentials (id, token_hash, label, principal_id, app, issued_by, expires_at, created_at, link_mount, link_dimension, link_chain)
|
|
137
|
+
SELECT ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?
|
|
138
|
+
WHERE ${declared.sql}
|
|
139
|
+
RETURNING id`,
|
|
140
|
+
binds: [
|
|
141
|
+
id,
|
|
142
|
+
input.tokenHash,
|
|
143
|
+
input.label,
|
|
144
|
+
input.app,
|
|
145
|
+
input.issuedBy,
|
|
146
|
+
input.expiresAt,
|
|
147
|
+
unixNow(),
|
|
148
|
+
input.link.mount,
|
|
149
|
+
dimension,
|
|
150
|
+
JSON.stringify(input.link.chain),
|
|
151
|
+
...declared.binds,
|
|
152
|
+
],
|
|
153
|
+
}
|
|
154
|
+
const inserted = this.writer.changed([insert], audit?.(id))
|
|
155
|
+
const statements: SqlStatement[] = [
|
|
156
|
+
this.db
|
|
157
|
+
.prepare('UPDATE app_link_mounts SET max_days = max_days WHERE app = ? AND mount = ? AND dimension = ?')
|
|
158
|
+
.bind(input.app, input.link.mount, dimension),
|
|
159
|
+
...inserted.statements,
|
|
160
|
+
]
|
|
161
|
+
for (const grant of input.grants) {
|
|
162
|
+
statements.push(
|
|
163
|
+
this.db
|
|
164
|
+
.prepare(`INSERT INTO credential_grants (credential_id, action, scope_type, scope_value)
|
|
165
|
+
SELECT ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM credentials WHERE id = ?)`)
|
|
166
|
+
.bind(id, grant.action, grant.scopeType, grant.scopeValue, id),
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
const results = await this.db.batch<{ id: string }>(statements)
|
|
170
|
+
return inserted.rows(results, 1).length > 0 ? id : null
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Look up a credential by the secret's hash, but ONLY while still valid (not revoked, not
|
|
175
|
+
* expired). An invalid/absent credential returns null. Single-statement so the validity check
|
|
176
|
+
* and the read can't race a concurrent revoke.
|
|
177
|
+
*/
|
|
178
|
+
async getActiveCredentialByHash(tokenHash: string): Promise<CredentialRow | null> {
|
|
179
|
+
return this.db
|
|
180
|
+
.prepare(`SELECT * FROM credentials
|
|
181
|
+
WHERE token_hash = ? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)`)
|
|
182
|
+
.bind(tokenHash, unixNow())
|
|
183
|
+
.first<CredentialRow>()
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async getCredentialById(id: string): Promise<CredentialRow | null> {
|
|
187
|
+
return this.db.prepare('SELECT * FROM credentials WHERE id = ?').bind(id).first<CredentialRow>()
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async getCredentialGrants(credentialId: string): Promise<CredentialGrantRow[]> {
|
|
191
|
+
const { results } = await this.db
|
|
192
|
+
.prepare('SELECT * FROM credential_grants WHERE credential_id = ?')
|
|
193
|
+
.bind(credentialId)
|
|
194
|
+
.all<CredentialGrantRow>()
|
|
195
|
+
return results
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Credentials for a principal (admin list / bulk revoke on disable). */
|
|
199
|
+
async listCredentialsForPrincipal(principalId: string): Promise<CredentialRow[]> {
|
|
200
|
+
const { results } = await this.db
|
|
201
|
+
.prepare('SELECT * FROM credentials WHERE principal_id = ? ORDER BY created_at DESC, id DESC')
|
|
202
|
+
.bind(principalId)
|
|
203
|
+
.all<CredentialRow>()
|
|
204
|
+
return results
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The live credential of each of a PAGE of principals, in one statement: an admin list needs each key's expiry, and
|
|
209
|
+
* one query per row would cost 1+N round trips (SEC-22). Newest first, like `listCredentialsForPrincipal`; rotation
|
|
210
|
+
* revokes every older key, so the first live row of a principal is its live credential.
|
|
211
|
+
*/
|
|
212
|
+
async listLiveCredentialsFor(principalIds: readonly string[]): Promise<CredentialRow[]> {
|
|
213
|
+
if (principalIds.length === 0) {
|
|
214
|
+
return []
|
|
215
|
+
}
|
|
216
|
+
const placeholders = principalIds.map(() => '?').join(', ')
|
|
217
|
+
const { results } = await this.db
|
|
218
|
+
.prepare(`SELECT * FROM credentials WHERE principal_id IN (${placeholders}) AND revoked_at IS NULL ORDER BY created_at DESC, id DESC`)
|
|
219
|
+
.bind(...principalIds)
|
|
220
|
+
.all<CredentialRow>()
|
|
221
|
+
return results
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Anonymous credentials — the share links (no bound principal). The admin share-links list.
|
|
226
|
+
*
|
|
227
|
+
* One page at a time, keyset-ordered by the UUIDv7 id like every other admin list, and REVOKED
|
|
228
|
+
* rows are excluded unless asked for: the console's default view is "links that still work", and
|
|
229
|
+
* an installation that has been revoking links for a year should not have to scroll through them.
|
|
230
|
+
* `app` filters to one app's links — with the credential now bound to an app there is finally
|
|
231
|
+
* something to filter on (SEC-2).
|
|
232
|
+
*/
|
|
233
|
+
async listAnonymousCredentials(filter: { app?: string; includeRevoked?: boolean; before?: string; limit: number }): Promise<CredentialRow[]> {
|
|
234
|
+
const where: string[] = ['principal_id IS NULL']
|
|
235
|
+
const binds: (string | number)[] = []
|
|
236
|
+
if (filter.app !== undefined) {
|
|
237
|
+
where.push('app = ?')
|
|
238
|
+
binds.push(filter.app)
|
|
239
|
+
}
|
|
240
|
+
if (filter.includeRevoked !== true) {
|
|
241
|
+
where.push('revoked_at IS NULL')
|
|
242
|
+
}
|
|
243
|
+
if (filter.before !== undefined) {
|
|
244
|
+
where.push('id < ?')
|
|
245
|
+
binds.push(filter.before)
|
|
246
|
+
}
|
|
247
|
+
binds.push(filter.limit)
|
|
248
|
+
const { results } = await this.db
|
|
249
|
+
.prepare(`SELECT * FROM credentials WHERE ${where.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
|
250
|
+
.bind(...binds)
|
|
251
|
+
.all<CredentialRow>()
|
|
252
|
+
return results
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Inline grants for a PAGE of credentials, in one statement. The admin lists used to issue one
|
|
257
|
+
* query per row, so a page cost 1+N round trips against an unbounded N (SEC-22); the page is
|
|
258
|
+
* bounded, so the `IN` list is too.
|
|
259
|
+
*/
|
|
260
|
+
async getCredentialGrantsFor(credentialIds: readonly string[]): Promise<CredentialGrantRow[]> {
|
|
261
|
+
if (credentialIds.length === 0) {
|
|
262
|
+
return []
|
|
263
|
+
}
|
|
264
|
+
const placeholders = credentialIds.map(() => '?').join(', ')
|
|
265
|
+
const { results } = await this.db
|
|
266
|
+
.prepare(`SELECT * FROM credential_grants WHERE credential_id IN (${placeholders})`)
|
|
267
|
+
.bind(...credentialIds)
|
|
268
|
+
.all<CredentialGrantRow>()
|
|
269
|
+
return results
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Revoke a credential by id (idempotent — already-revoked → false). `audit` is written exactly when this call revoked it. */
|
|
273
|
+
async revokeCredential(id: string, audit?: AuditEventInput): Promise<boolean> {
|
|
274
|
+
const revoke: SqlChange = { sql: 'UPDATE credentials SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL RETURNING id', binds: [unixNow(), id] }
|
|
275
|
+
return (await this.writer.run([revoke], audit)).length > 0
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Revoke every active credential bound to a principal (key revoke / rotate). Returns the count. */
|
|
279
|
+
async revokeCredentialsForPrincipal(principalId: string): Promise<number> {
|
|
280
|
+
return (await this.writer.run([this.revokeCredentialsForPrincipalChange(principalId)], undefined)).length
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** `revokeCredentialsForPrincipalChange` as a statement, for a batch whose record does not depend on it. */
|
|
284
|
+
revokeCredentialsForPrincipalStatement(principalId: string): SqlStatement {
|
|
285
|
+
const change = this.revokeCredentialsForPrincipalChange(principalId)
|
|
286
|
+
return this.db.prepare(change.sql).bind(...change.binds)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Revoke every active credential of a principal except `keep`, as a change an audited revocation groups with others. */
|
|
290
|
+
revokeCredentialsForPrincipalChange(principalId: string, keep: readonly string[] = []): SqlChange {
|
|
291
|
+
const kept = keep.map(() => ' AND id <> ?').join('')
|
|
292
|
+
return {
|
|
293
|
+
sql: `UPDATE credentials SET revoked_at = ? WHERE principal_id = ? AND revoked_at IS NULL${kept} RETURNING id`,
|
|
294
|
+
binds: [unixNow(), principalId, ...keep],
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** What `issueLink` authorized against: the mount as it read it and, for a job, the job's declaration. */
|
|
300
|
+
export interface CheckedLinkDeclaration {
|
|
301
|
+
readonly grants: readonly string[]
|
|
302
|
+
readonly issuedBy: string
|
|
303
|
+
readonly maxDays: number
|
|
304
|
+
readonly job?: { readonly name: string; readonly actions: readonly string[] }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The condition that the schema still declares `checked`: stored lists compare as the JSON the reconcile writes, and
|
|
309
|
+
* each value of the chain names the dimension the schema contains the previous one in, the last one none.
|
|
310
|
+
*/
|
|
311
|
+
function declaredLink(app: string, link: { mount: string; chain: Scope[] }, checked: CheckedLinkDeclaration): { sql: string; binds: unknown[] } {
|
|
312
|
+
const terms = [
|
|
313
|
+
'EXISTS (SELECT 1 FROM app_link_mounts WHERE app = ? AND mount = ? AND dimension = ? AND grants = ? AND issued_by = ? AND max_days = ?)',
|
|
314
|
+
]
|
|
315
|
+
const binds: unknown[] = [app, link.mount, link.chain[0]?.type ?? '', JSON.stringify(checked.grants), checked.issuedBy, checked.maxDays]
|
|
316
|
+
for (const [index, scope] of link.chain.entries()) {
|
|
317
|
+
const parent = link.chain[index + 1]
|
|
318
|
+
if (parent === undefined) {
|
|
319
|
+
terms.push('EXISTS (SELECT 1 FROM app_scopes WHERE app = ? AND scope_type = ? AND parent_scope IS NULL)')
|
|
320
|
+
binds.push(app, scope.type)
|
|
321
|
+
} else {
|
|
322
|
+
terms.push('EXISTS (SELECT 1 FROM app_scopes WHERE app = ? AND scope_type = ? AND parent_scope = ?)')
|
|
323
|
+
binds.push(app, scope.type, parent.type)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (checked.job !== undefined) {
|
|
327
|
+
terms.push(`EXISTS (SELECT 1 FROM app_workloads WHERE app = ? AND kind = 'job' AND name = ? AND actions = ? AND issues = ?)`)
|
|
328
|
+
binds.push(app, checked.job.name, JSON.stringify(checked.job.actions), link.mount)
|
|
329
|
+
}
|
|
330
|
+
return { sql: terms.join(' AND '), binds }
|
|
331
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { type DeviceAuthorizationConsent, MAX_KEY_LIFETIME_SECONDS, type StartDeviceAuthorizationInput } from '@fabrika/auth-core'
|
|
2
|
+
import { type SqlDatabase, uuidv7 } from '@fabrika/platform'
|
|
3
|
+
import { unixNow } from './sql'
|
|
4
|
+
|
|
5
|
+
export interface DeviceAuthorizationRow {
|
|
6
|
+
id: string
|
|
7
|
+
app: string
|
|
8
|
+
label: string
|
|
9
|
+
permissions: string
|
|
10
|
+
key_lifetime_seconds: number
|
|
11
|
+
redemption_challenge: string
|
|
12
|
+
approval_challenge: string
|
|
13
|
+
expires_at: number
|
|
14
|
+
next_poll_at: number
|
|
15
|
+
status: 'pending' | 'approved' | 'issued' | 'denied' | 'cancelled' | 'authority_lost'
|
|
16
|
+
approver_id: string | null
|
|
17
|
+
consent_id: string | null
|
|
18
|
+
scope_type: string | null
|
|
19
|
+
scope_value: string | null
|
|
20
|
+
key_expires_at: number | null
|
|
21
|
+
claim_id: string | null
|
|
22
|
+
credential_id: string | null
|
|
23
|
+
principal_id: string | null
|
|
24
|
+
issued_at: number | null
|
|
25
|
+
created_at: number
|
|
26
|
+
}
|
|
27
|
+
export interface DeviceReceiptRow extends DeviceAuthorizationRow {
|
|
28
|
+
revoked_at: number | null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The approver `approver` (a column or a placeholder) is internal: a device key is a service principal with frozen
|
|
33
|
+
* grants, never an external principal's (ADR-0051).
|
|
34
|
+
*/
|
|
35
|
+
const internalApprover = (approver: string): string =>
|
|
36
|
+
`NOT EXISTS (SELECT 1 FROM principals ap WHERE ap.id = ${approver} AND ap.affiliation = 'external')`
|
|
37
|
+
|
|
38
|
+
export class DeviceAuthorizationRepository {
|
|
39
|
+
constructor(protected readonly db: SqlDatabase) {}
|
|
40
|
+
|
|
41
|
+
async start(input: StartDeviceAuthorizationInput): Promise<{ attemptId: string; expiresAt: number; pollIntervalSeconds: 3 }> {
|
|
42
|
+
const attemptId = uuidv7()
|
|
43
|
+
const now = unixNow()
|
|
44
|
+
const expiresAt = now + 600
|
|
45
|
+
await this.db.prepare(`INSERT INTO device_authorizations
|
|
46
|
+
(id, app, label, permissions, key_lifetime_seconds, redemption_challenge, approval_challenge, expires_at, next_poll_at, status, created_at)
|
|
47
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`).bind(
|
|
48
|
+
attemptId,
|
|
49
|
+
input.app,
|
|
50
|
+
input.label,
|
|
51
|
+
JSON.stringify(input.permissions),
|
|
52
|
+
Math.min(input.keyLifetimeSeconds, MAX_KEY_LIFETIME_SECONDS),
|
|
53
|
+
input.redemptionChallenge,
|
|
54
|
+
input.approvalChallenge,
|
|
55
|
+
expiresAt,
|
|
56
|
+
now,
|
|
57
|
+
now,
|
|
58
|
+
).run()
|
|
59
|
+
return { attemptId, expiresAt, pollIntervalSeconds: 3 }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get(id: string): Promise<DeviceReceiptRow | null> {
|
|
63
|
+
return this.db.prepare(`SELECT d.*, c.revoked_at FROM device_authorizations d
|
|
64
|
+
LEFT JOIN credentials c ON c.id = d.credential_id WHERE d.id = ?`).bind(id).first<DeviceReceiptRow>()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async poll(id: string, challenge: string): Promise<boolean> {
|
|
68
|
+
const now = unixNow()
|
|
69
|
+
return await this.db.prepare(`UPDATE device_authorizations SET next_poll_at = ?
|
|
70
|
+
WHERE id = ? AND redemption_challenge = ? AND next_poll_at <= ? RETURNING id`)
|
|
71
|
+
.bind(now + 3, id, challenge, now).first<{ id: string }>() !== null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async approve(id: string, approverId: string, consent: DeviceAuthorizationConsent): Promise<boolean> {
|
|
75
|
+
return await this.db.prepare(`UPDATE device_authorizations
|
|
76
|
+
SET status = 'approved', approver_id = ?, consent_id = ?, scope_type = ?, scope_value = ?, key_expires_at = ?
|
|
77
|
+
WHERE id = ? AND status = 'pending' AND expires_at > ? AND ${internalApprover('?')} RETURNING id`)
|
|
78
|
+
.bind(approverId, consent.consentId, consent.scope.type, consent.scope.value, consent.keyExpiresAt, id, unixNow(), approverId)
|
|
79
|
+
.first<{ id: string }>() !== null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async terminate(id: string, status: 'denied' | 'cancelled' | 'authority_lost'): Promise<void> {
|
|
83
|
+
await this.db.prepare(`UPDATE device_authorizations SET status = ?
|
|
84
|
+
WHERE id = ? AND status IN ('pending', 'approved')`).bind(status, id).run()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async deny(id: string): Promise<void> {
|
|
88
|
+
await this.db.prepare(`UPDATE device_authorizations SET status = 'denied' WHERE id = ? AND status = 'pending' AND expires_at > ?`)
|
|
89
|
+
.bind(id, unixNow()).run()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async issue(
|
|
93
|
+
input: { attemptId: string; consentId: string; tokenHash: string; requestId: string; approverLabel: string },
|
|
94
|
+
): Promise<DeviceAuthorizationRow | null> {
|
|
95
|
+
const claimId = uuidv7()
|
|
96
|
+
const principalId = uuidv7()
|
|
97
|
+
const credentialId = uuidv7()
|
|
98
|
+
const now = unixNow()
|
|
99
|
+
// Every insert depends on this batch's fresh claim, including the final RETURNING witness.
|
|
100
|
+
const results = await this.db.batch<DeviceAuthorizationRow>([
|
|
101
|
+
// The grant below is raw SQL, so the contract rule (no wildcard) is part of the claim itself.
|
|
102
|
+
this.db.prepare(`UPDATE device_authorizations SET claim_id = ?
|
|
103
|
+
WHERE id = ? AND consent_id = ? AND status = 'approved' AND claim_id IS NULL
|
|
104
|
+
AND expires_at > ? AND key_expires_at > ?
|
|
105
|
+
AND NOT (permissions LIKE '%*%' AND EXISTS (SELECT 1 FROM contract_apps c WHERE c.app = device_authorizations.app))
|
|
106
|
+
AND ${internalApprover('device_authorizations.approver_id')}`)
|
|
107
|
+
.bind(claimId, input.attemptId, input.consentId, now, now),
|
|
108
|
+
this.db.prepare(`INSERT INTO principals (id, type, label, created_at)
|
|
109
|
+
SELECT ?, 'service', label, ? FROM device_authorizations WHERE claim_id = ?`).bind(principalId, now, claimId),
|
|
110
|
+
this.db.prepare(`INSERT INTO grants (id, principal_id, app, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
|
|
111
|
+
SELECT ?, ?, app, permissions, scope_type, scope_value, approver_id, key_expires_at, ?
|
|
112
|
+
FROM device_authorizations WHERE claim_id = ?`).bind(uuidv7(), principalId, now, claimId),
|
|
113
|
+
this.db.prepare(`INSERT INTO credentials (id, token_hash, label, principal_id, app, issued_by, expires_at, created_at)
|
|
114
|
+
SELECT ?, ?, label, ?, app, approver_id, key_expires_at, ? FROM device_authorizations WHERE claim_id = ?`)
|
|
115
|
+
.bind(credentialId, input.tokenHash, principalId, now, claimId),
|
|
116
|
+
this.db.prepare(`INSERT INTO audit_events (id, request_id, principal_id, principal_label, app, action, resource_type, resource_id, created_at)
|
|
117
|
+
SELECT ?, ?, approver_id, ?, app, 'iam.credential.create', 'credential', ?, ?
|
|
118
|
+
FROM device_authorizations WHERE claim_id = ?`).bind(uuidv7(), input.requestId, input.approverLabel, credentialId, now, claimId),
|
|
119
|
+
this.db.prepare(`UPDATE device_authorizations SET status = 'issued', principal_id = ?, credential_id = ?, issued_at = ?
|
|
120
|
+
WHERE claim_id = ? AND status = 'approved' RETURNING *`).bind(principalId, credentialId, now, claimId),
|
|
121
|
+
])
|
|
122
|
+
return results.at(-1)?.results[0] ?? null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async list(approverId: string, app: string, before: string | undefined, limit: number): Promise<DeviceReceiptRow[]> {
|
|
126
|
+
const { results } = await this.db.prepare(`SELECT d.*, c.revoked_at FROM device_authorizations d
|
|
127
|
+
LEFT JOIN credentials c ON c.id = d.credential_id
|
|
128
|
+
WHERE d.approver_id = ? AND d.app = ? AND d.status = 'issued' ${before === undefined ? '' : 'AND d.id < ?'}
|
|
129
|
+
ORDER BY d.id DESC LIMIT ?`).bind(approverId, app, ...(before === undefined ? [] : [before]), limit).all<DeviceReceiptRow>()
|
|
130
|
+
return results
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async prune(now: number): Promise<void> {
|
|
134
|
+
await this.db.prepare(`DELETE FROM device_authorizations WHERE
|
|
135
|
+
(status <> 'issued' AND expires_at <= ?) OR (status = 'issued' AND key_expires_at + 86400 <= ?)`).bind(now, now).run()
|
|
136
|
+
}
|
|
137
|
+
}
|