@sssb/kit 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +209 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +312 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +270 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +94 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +115 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db.ts +88 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +89 -0
- package/src/adapters/real/jobs.ts +32 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-panel.tsx +716 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +459 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1479 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +118 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +97 -0
- package/src/observability/scrub.ts +42 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +48 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +53 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +38 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +73 -0
- package/src/service-auth/webhook.ts +60 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { type AcceptanceView, type AgreementView, isAgreementGating, isAgreementKind } from '../core/agreements'
|
|
2
|
+
import type { DbPort } from '../ports/db'
|
|
3
|
+
import { toIso } from './jobs'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The agreements DB layer. Every function goes through db.withTenant — the tenant is the
|
|
7
|
+
* WHOLE isolation boundary here (agreements are tenant-level, NOT org-scoped; migration 0013). Reads
|
|
8
|
+
* feed the gate seam: the protected layout assembles a user's pending agreements from
|
|
9
|
+
* listAgreementsForTenant + readAcceptancesForUser and hands them to packages/kit/src/core/gates.ts. Writes are the
|
|
10
|
+
* append-only acceptance (recordAcceptance) and the version bump (bumpAgreementVersion) that re-arms
|
|
11
|
+
* the gate for everyone.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Map a DB agreements row to the core AgreementView, validating the two text-typed enums at the
|
|
15
|
+
* boundary (unknown kind/gating rows are dropped defensively — a stale row can't widen the type). */
|
|
16
|
+
function toAgreementView(row: {
|
|
17
|
+
id: string
|
|
18
|
+
kind: string
|
|
19
|
+
version: number
|
|
20
|
+
title: string
|
|
21
|
+
body_md: string
|
|
22
|
+
gating: string
|
|
23
|
+
}): AgreementView | null {
|
|
24
|
+
if (!isAgreementKind(row.kind) || !isAgreementGating(row.gating)) return null
|
|
25
|
+
return {
|
|
26
|
+
id: row.id,
|
|
27
|
+
kind: row.kind,
|
|
28
|
+
version: Number(row.version),
|
|
29
|
+
title: row.title,
|
|
30
|
+
bodyMd: row.body_md,
|
|
31
|
+
gating: row.gating,
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** All current agreements for a tenant (the universe the gate registry is built from). */
|
|
36
|
+
export async function listAgreementsForTenant(db: DbPort, tenantId: string): Promise<AgreementView[]> {
|
|
37
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
38
|
+
const rows = await trx
|
|
39
|
+
.selectFrom('agreements')
|
|
40
|
+
.select(['id', 'kind', 'version', 'title', 'body_md', 'gating'])
|
|
41
|
+
.orderBy('created_at', 'asc')
|
|
42
|
+
.execute()
|
|
43
|
+
return rows.flatMap((r) => {
|
|
44
|
+
const view = toAgreementView(r)
|
|
45
|
+
return view ? [view] : []
|
|
46
|
+
})
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One agreement by id (the accept route reads the CURRENT version to denormalize onto the acceptance —
|
|
51
|
+
* never trusting a client-supplied version). Null when absent in the tenant. */
|
|
52
|
+
export async function readAgreement(db: DbPort, tenantId: string, agreementId: string): Promise<AgreementView | null> {
|
|
53
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
54
|
+
const row = await trx
|
|
55
|
+
.selectFrom('agreements')
|
|
56
|
+
.select(['id', 'kind', 'version', 'title', 'body_md', 'gating'])
|
|
57
|
+
.where('id', '=', agreementId)
|
|
58
|
+
.executeTakeFirst()
|
|
59
|
+
return row ? toAgreementView(row) : null
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A user's acceptance rows (agreementId + the version they accepted), for the pending computation. */
|
|
64
|
+
export async function readAcceptancesForUser(db: DbPort, tenantId: string, userId: string): Promise<AcceptanceView[]> {
|
|
65
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
66
|
+
const rows = await trx
|
|
67
|
+
.selectFrom('agreement_acceptances')
|
|
68
|
+
.select(['agreement_id', 'agreement_version', 'accepted_at'])
|
|
69
|
+
.where('user_id', '=', userId)
|
|
70
|
+
.execute()
|
|
71
|
+
return rows.map((r) => ({
|
|
72
|
+
agreementId: r.agreement_id,
|
|
73
|
+
version: Number(r.agreement_version),
|
|
74
|
+
acceptedAt: toIso(r.accepted_at),
|
|
75
|
+
}))
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One acceptance joined to its agreement (title/kind), for the profile "which have I accepted" list.
|
|
80
|
+
* Newest first. A user only ever reads their OWN acceptances (the user_id filter + route authorize). */
|
|
81
|
+
export interface AcceptanceRecord {
|
|
82
|
+
agreementId: string
|
|
83
|
+
title: string
|
|
84
|
+
kind: string
|
|
85
|
+
version: number
|
|
86
|
+
acceptedAt: string
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function listUserAcceptanceRecords(
|
|
90
|
+
db: DbPort,
|
|
91
|
+
tenantId: string,
|
|
92
|
+
userId: string,
|
|
93
|
+
): Promise<AcceptanceRecord[]> {
|
|
94
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
95
|
+
const rows = await trx
|
|
96
|
+
.selectFrom('agreement_acceptances as a')
|
|
97
|
+
.innerJoin('agreements as g', 'g.id', 'a.agreement_id')
|
|
98
|
+
.select([
|
|
99
|
+
'a.agreement_id as agreement_id',
|
|
100
|
+
'a.agreement_version as agreement_version',
|
|
101
|
+
'a.accepted_at as accepted_at',
|
|
102
|
+
'g.title as title',
|
|
103
|
+
'g.kind as kind',
|
|
104
|
+
])
|
|
105
|
+
.where('a.user_id', '=', userId)
|
|
106
|
+
.orderBy('a.accepted_at', 'desc')
|
|
107
|
+
.execute()
|
|
108
|
+
return rows.map((r) => ({
|
|
109
|
+
agreementId: r.agreement_id,
|
|
110
|
+
title: r.title,
|
|
111
|
+
kind: r.kind,
|
|
112
|
+
version: Number(r.agreement_version),
|
|
113
|
+
acceptedAt: toIso(r.accepted_at),
|
|
114
|
+
}))
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Record a user's acceptance of an agreement at a version (APPEND-ONLY — SELECT/INSERT grant only, no
|
|
120
|
+
* update path). `agreementVersion` is the agreement's CURRENT version, read server-side by the caller;
|
|
121
|
+
* the client never supplies it. `metadata` is minimal capture context (user-agent). Returns the new
|
|
122
|
+
* acceptance id (for the audit subject).
|
|
123
|
+
*/
|
|
124
|
+
export async function recordAcceptance(
|
|
125
|
+
db: DbPort,
|
|
126
|
+
input: {
|
|
127
|
+
tenantId: string
|
|
128
|
+
agreementId: string
|
|
129
|
+
agreementVersion: number
|
|
130
|
+
userId: string
|
|
131
|
+
metadata: Record<string, unknown>
|
|
132
|
+
},
|
|
133
|
+
): Promise<{ id: string }> {
|
|
134
|
+
return db.withTenant(input.tenantId, (trx) =>
|
|
135
|
+
trx
|
|
136
|
+
.insertInto('agreement_acceptances')
|
|
137
|
+
.values({
|
|
138
|
+
tenant_id: input.tenantId,
|
|
139
|
+
agreement_id: input.agreementId,
|
|
140
|
+
agreement_version: input.agreementVersion,
|
|
141
|
+
user_id: input.userId,
|
|
142
|
+
metadata: input.metadata,
|
|
143
|
+
})
|
|
144
|
+
.returning('id')
|
|
145
|
+
.executeTakeFirstOrThrow(),
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Bump an agreement's version IN PLACE (version + 1, effective_at = now) — the demo story: re-arms the
|
|
151
|
+
* gate for EVERYONE whose latest acceptance is now below the new version. Exercises the app_user UPDATE
|
|
152
|
+
* grant through withTenant (the shape a real admin agreements UI would use). Returns the new version, or
|
|
153
|
+
* null when the agreement is absent in the tenant.
|
|
154
|
+
*/
|
|
155
|
+
export async function bumpAgreementVersion(
|
|
156
|
+
db: DbPort,
|
|
157
|
+
tenantId: string,
|
|
158
|
+
agreementId: string,
|
|
159
|
+
now: Date,
|
|
160
|
+
): Promise<{ version: number } | null> {
|
|
161
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
162
|
+
const current = await trx
|
|
163
|
+
.selectFrom('agreements')
|
|
164
|
+
.select('version')
|
|
165
|
+
.where('id', '=', agreementId)
|
|
166
|
+
.executeTakeFirst()
|
|
167
|
+
if (!current) return null
|
|
168
|
+
const nextVersion = Number(current.version) + 1
|
|
169
|
+
await trx
|
|
170
|
+
.updateTable('agreements')
|
|
171
|
+
.set({ version: nextVersion, effective_at: now.toISOString() })
|
|
172
|
+
.where('id', '=', agreementId)
|
|
173
|
+
.execute()
|
|
174
|
+
return { version: nextVersion }
|
|
175
|
+
})
|
|
176
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE APP'S OWN CLUSTER-WIDE ROLES: the roles an app's migrations create, which it names in an OPTIONAL export of its
|
|
3
|
+
* `@sssb/app-config/db/migrations` module, beside `appMigrations`:
|
|
4
|
+
*
|
|
5
|
+
* export const appRoles = ['fixture_docket_clerk'] as const
|
|
6
|
+
*
|
|
7
|
+
* A role is cluster-wide, like `app_user`: on a server an earlier owner has migrated, the role is already there, and a
|
|
8
|
+
* later owner's migration that ALTERs it, or grants it to another role, needs the ADMIN option the earlier owner got by
|
|
9
|
+
* creating it. The contract suite's owner pass (./owner-pass.ts) grants a later owner exactly that, on the roles named
|
|
10
|
+
* here and on no other; the conformance suite's `app-roles` check holds the list to what the migrations really create
|
|
11
|
+
* (../testing/conformance/db.ts). An app that creates no role exports nothing, and changes nothing.
|
|
12
|
+
*
|
|
13
|
+
* Read with `in` on the module namespace, because the seam need not declare it: the starter's does not, and each app's
|
|
14
|
+
* typecheck compiles the framework against that app's own seam (`apps/starter/tsconfig.json` includes
|
|
15
|
+
* `packages/kit/src`; reading `.appRoles` directly fails both apps' `tsc` with TS2339).
|
|
16
|
+
*
|
|
17
|
+
* An app's role is ORDINARY (`refusedOf`): it cannot log in, create databases or roles, is no superuser and bypasses
|
|
18
|
+
* no RLS, holds no privilege on a server parameter and owns no database or tablespace, and it is a member of no role but
|
|
19
|
+
* `app_user` and the app's other named roles, at any depth. ADMIN on a role lets its holder grant itself SET on it, and
|
|
20
|
+
* so act as that role and as every role it is a member of: ADMIN on a role that is a member of a superuser, of
|
|
21
|
+
* `pg_execute_server_program` or of `rds_superuser`, or that may `ALTER SYSTEM SET archive_command`, is that role's
|
|
22
|
+
* power, not the app's. `app_user`, on which every later owner gets ADMIN too, is held to the same, and may be a member
|
|
23
|
+
* of the named roles and of any role ordinary in shape, which another app on the same server may have granted it.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { type Kysely, sql } from 'kysely'
|
|
27
|
+
import type { DB } from './schema'
|
|
28
|
+
|
|
29
|
+
/** The framework's own role, which migration 0001 creates and the owner pass grants a later owner ADMIN on itself. */
|
|
30
|
+
export const FRAMEWORK_ROLE = 'app_user'
|
|
31
|
+
|
|
32
|
+
/** What an app's role is named: an unquoted Postgres identifier, lowercase, within its 63 characters. */
|
|
33
|
+
const ROLE_NAME = /^[a-z][a-z0-9_]{0,62}$/
|
|
34
|
+
|
|
35
|
+
/** Where an app names its roles, as every message says it. */
|
|
36
|
+
export const APP_ROLES_HOME =
|
|
37
|
+
'export `appRoles` from `src/app-config/db/migrations.ts` (`@sssb/app-config/db/migrations`; ' +
|
|
38
|
+
'`src/app-config/db/migrations/index.ts` when the migrations are a directory)'
|
|
39
|
+
|
|
40
|
+
/** What `refusedOf` holds every role to, as every message says it: the attributes and the catalogs. */
|
|
41
|
+
const ORDINARY_ALONE =
|
|
42
|
+
'NOLOGIN, with no other attribute (CREATEDB, CREATEROLE, SUPERUSER, BYPASSRLS, REPLICATION), no privilege on a ' +
|
|
43
|
+
'server parameter, no database or tablespace of its own'
|
|
44
|
+
|
|
45
|
+
/** What `refusedOf` holds a named role to, as every message says it. */
|
|
46
|
+
export const ORDINARY_NAMED = `${ORDINARY_ALONE}, and a member of no role but app_user and the app's other named roles, at any depth`
|
|
47
|
+
|
|
48
|
+
/** What `refusedOf` holds `app_user` to, as every message says it. */
|
|
49
|
+
export const ORDINARY_APP_USER =
|
|
50
|
+
`${ORDINARY_ALONE}, and a member of no role but the app's named roles and roles ordinary in shape (none of the ` +
|
|
51
|
+
'above, and no pg_* or rds_* role), at any depth'
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Validates an `appRoles` value: an array of distinct role names an app may own. Refuses a name that is not a
|
|
55
|
+
* lowercase unquoted identifier, `app_user` (the framework's), a predefined role's prefix (`pg_`) and Amazon RDS's
|
|
56
|
+
* (`rds_`): the owner pass grants ADMIN on every name here, so a name must only ever be the app's own.
|
|
57
|
+
*/
|
|
58
|
+
export function checkAppRoles(raw: unknown): readonly string[] {
|
|
59
|
+
if (!Array.isArray(raw)) {
|
|
60
|
+
throw new Error(`appRoles must be an array of role names (${APP_ROLES_HOME}); got ${shown(raw)}`)
|
|
61
|
+
}
|
|
62
|
+
const seen = new Set<string>()
|
|
63
|
+
for (const role of raw as unknown[]) {
|
|
64
|
+
if (typeof role !== 'string' || !ROLE_NAME.test(role)) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`appRoles: ${shown(role)} is not a role name an app may own: a lowercase unquoted Postgres ` +
|
|
67
|
+
'identifier (a letter, then letters, digits or underscores, at most 63 characters)',
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
if (role === FRAMEWORK_ROLE || role.startsWith('pg_') || role.startsWith('rds_')) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`appRoles: "${role}" is not the app's own role (${FRAMEWORK_ROLE} is the framework's, pg_* are ` +
|
|
73
|
+
"Postgres's predefined roles and rds_* are Amazon RDS's); name only the roles the app's migrations create",
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
if (seen.has(role)) throw new Error(`appRoles names "${role}" twice`)
|
|
77
|
+
seen.add(role)
|
|
78
|
+
}
|
|
79
|
+
return [...seen]
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The roles an app's migrations module names: its `appRoles`, validated, or none when it exports none. */
|
|
83
|
+
export function appRolesOf(seam: object): readonly string[] {
|
|
84
|
+
return 'appRoles' in seam ? checkAppRoles(seam.appRoles) : []
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The running app's named roles, read from its seam when called. */
|
|
88
|
+
export async function appRoles(): Promise<readonly string[]> {
|
|
89
|
+
return appRolesOf(await import('@sssb/app-config/db/migrations'))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** A role that exists on a server, and what makes it more than an ordinary role there (none when it is one). */
|
|
93
|
+
export interface FoundRole {
|
|
94
|
+
rolname: string
|
|
95
|
+
refused: string[]
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Reads `app_user` and each named role that exists on the server `db` reaches (every role a later owner is handed
|
|
100
|
+
* ADMIN on), with what makes it more than ordinary. A role that does not exist is left out; `app_user` comes first.
|
|
101
|
+
*
|
|
102
|
+
* None may hold SUPERUSER, BYPASSRLS, REPLICATION, CREATEROLE, CREATEDB or LOGIN, nor what the cluster-wide catalogs
|
|
103
|
+
* record for it: a privilege on a server parameter (`pg_parameter_acl`: `GRANT ALTER SYSTEM ON PARAMETER ...`), or a
|
|
104
|
+
* database or tablespace it owns (`pg_database.datdba`, `pg_tablespace.spcowner`). Its memberships, at any depth through
|
|
105
|
+
* `pg_auth_members` and whatever their INHERIT and SET options say (ADMIN on the role lets its holder grant itself
|
|
106
|
+
* both), are read as `member of "<role>"`, by two rules:
|
|
107
|
+
*
|
|
108
|
+
* - A NAMED role may be a member of `app_user` and of the other named roles only. Its walk stops at `app_user`, which
|
|
109
|
+
* is read on its own: what `app_user` is a member of is held to `app_user`'s rule.
|
|
110
|
+
* - `app_user` may be a member of the named roles, and of a role that is ordinary in shape: none of the six attributes,
|
|
111
|
+
* none of those catalog entries, and none of Postgres's predefined roles (`pg_*`) or Amazon RDS's (`rds_*`), at any
|
|
112
|
+
* depth. It is shared by every
|
|
113
|
+
* database on the server, so where several apps' suites share one (CI's `CONTRACT_DATABASE_URL`), it is a member of
|
|
114
|
+
* the roles OTHER apps' migrations granted it, which this app does not name and cannot.
|
|
115
|
+
*/
|
|
116
|
+
export async function refusedOf(db: Kysely<DB>, named: readonly string[]): Promise<FoundRole[]> {
|
|
117
|
+
const allowed = new Set([FRAMEWORK_ROLE, ...named])
|
|
118
|
+
const found: FoundRole[] = []
|
|
119
|
+
for (const role of new Set([FRAMEWORK_ROLE, ...named])) {
|
|
120
|
+
const { rows } = await sql<{
|
|
121
|
+
rolname: string
|
|
122
|
+
rolsuper: boolean
|
|
123
|
+
rolbypassrls: boolean
|
|
124
|
+
rolreplication: boolean
|
|
125
|
+
rolcreaterole: boolean
|
|
126
|
+
rolcreatedb: boolean
|
|
127
|
+
rolcanlogin: boolean
|
|
128
|
+
}>`
|
|
129
|
+
SELECT rolname, rolsuper, rolbypassrls, rolreplication, rolcreaterole, rolcreatedb, rolcanlogin
|
|
130
|
+
FROM pg_roles WHERE rolname = ${role}`.execute(db)
|
|
131
|
+
const row = rows[0]
|
|
132
|
+
if (!row) continue
|
|
133
|
+
// What the cluster-wide catalogs record for it, readable from any database by any role.
|
|
134
|
+
const held = await sql<{ reason: string }>`
|
|
135
|
+
WITH me AS (SELECT oid FROM pg_roles WHERE rolname = ${role})
|
|
136
|
+
SELECT reason FROM (
|
|
137
|
+
SELECT 1 AS k, p.parname AS n,
|
|
138
|
+
'granted ' || a.privilege_type || ' on parameter "' || p.parname || '"' AS reason
|
|
139
|
+
FROM pg_parameter_acl p, aclexplode(p.paracl) a, me WHERE a.grantee = me.oid
|
|
140
|
+
UNION ALL
|
|
141
|
+
SELECT 2, d.datname, 'owner of database "' || d.datname || '"'
|
|
142
|
+
FROM pg_database d, me WHERE d.datdba = me.oid
|
|
143
|
+
UNION ALL
|
|
144
|
+
SELECT 3, t.spcname, 'owner of tablespace "' || t.spcname || '"'
|
|
145
|
+
FROM pg_tablespace t, me WHERE t.spcowner = me.oid
|
|
146
|
+
) catalog ORDER BY k, n, reason`.execute(db)
|
|
147
|
+
// Every role this one is a member of, directly or through another, never through app_user (read on its own):
|
|
148
|
+
// UNION, not UNION ALL, so a role reached twice is followed once. `shaped`: ordinary in shape, as above.
|
|
149
|
+
const memberships = await sql<{ rolname: string; shaped: boolean }>`
|
|
150
|
+
WITH RECURSIVE up(roleid) AS (
|
|
151
|
+
SELECT m.roleid FROM pg_auth_members m JOIN pg_roles me ON me.oid = m.member WHERE me.rolname = ${role}
|
|
152
|
+
UNION
|
|
153
|
+
SELECT m.roleid FROM pg_auth_members m
|
|
154
|
+
JOIN up ON m.member = up.roleid
|
|
155
|
+
JOIN pg_roles via ON via.oid = up.roleid AND via.rolname <> ${FRAMEWORK_ROLE}
|
|
156
|
+
)
|
|
157
|
+
SELECT r.rolname,
|
|
158
|
+
NOT (r.rolsuper OR r.rolbypassrls OR r.rolreplication OR r.rolcreaterole OR r.rolcreatedb
|
|
159
|
+
OR r.rolcanlogin OR starts_with(r.rolname, 'pg_') OR starts_with(r.rolname, 'rds_')
|
|
160
|
+
OR EXISTS (SELECT FROM pg_parameter_acl p, aclexplode(p.paracl) a WHERE a.grantee = r.oid)
|
|
161
|
+
OR EXISTS (SELECT FROM pg_database d WHERE d.datdba = r.oid)
|
|
162
|
+
OR EXISTS (SELECT FROM pg_tablespace t WHERE t.spcowner = r.oid)) AS shaped
|
|
163
|
+
FROM up JOIN pg_roles r ON r.oid = up.roleid ORDER BY r.rolname`.execute(db)
|
|
164
|
+
const refused = [
|
|
165
|
+
row.rolsuper && 'SUPERUSER',
|
|
166
|
+
row.rolbypassrls && 'BYPASSRLS',
|
|
167
|
+
row.rolreplication && 'REPLICATION',
|
|
168
|
+
row.rolcreaterole && 'CREATEROLE',
|
|
169
|
+
row.rolcreatedb && 'CREATEDB',
|
|
170
|
+
row.rolcanlogin && 'LOGIN',
|
|
171
|
+
...held.rows.map((entry) => entry.reason),
|
|
172
|
+
...memberships.rows
|
|
173
|
+
.filter((membership) =>
|
|
174
|
+
role === FRAMEWORK_ROLE
|
|
175
|
+
? !named.includes(membership.rolname) && !membership.shaped
|
|
176
|
+
: !allowed.has(membership.rolname),
|
|
177
|
+
)
|
|
178
|
+
.map((membership) => `member of "${membership.rolname}"`),
|
|
179
|
+
].filter((reason): reason is string => typeof reason === 'string')
|
|
180
|
+
found.push({ rolname: row.rolname, refused })
|
|
181
|
+
}
|
|
182
|
+
return found
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The roles `refusedOf` found more than ordinary, as one clause: `"a" (LOGIN), "b" (member of "c")`. */
|
|
186
|
+
export function shownRefused(found: readonly FoundRole[]): string {
|
|
187
|
+
return found
|
|
188
|
+
.filter((role) => role.refused.length > 0)
|
|
189
|
+
.map((role) => `"${role.rolname}" (${role.refused.join(', ')})`)
|
|
190
|
+
.join(', ')
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function shown(value: unknown): string {
|
|
194
|
+
if (typeof value === 'string') return JSON.stringify(value)
|
|
195
|
+
if (Array.isArray(value)) return 'an array'
|
|
196
|
+
return value === null ? 'null' : typeof value
|
|
197
|
+
}
|