@sssb/kit 0.0.0 → 0.3.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.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +212 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +313 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +248 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +93 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,172 @@
1
+ 'use client'
2
+
3
+ import { Badge, Button, Card, Code, Group, MultiSelect, Stack, Switch, Text, TextInput, Title } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import { useState } from 'react'
6
+
7
+ export interface WebhookEndpointItem {
8
+ id: string
9
+ url: string
10
+ eventKinds: string[]
11
+ enabled: boolean
12
+ createdAt: string
13
+ }
14
+
15
+ /**
16
+ * Router-agnostic outbound-webhook endpoints card, the two-list card pattern: an org
17
+ * admin lists, adds, enables/disables and removes egress endpoints for the active team. Presentational
18
+ * only — the glue owns fetching + the authorize()-gated mutations. The shared secret is generated
19
+ * server-side and shown ONCE, right after create (house-simple: it's not retrievable again); the card
20
+ * surfaces it in a dismissible callout so the admin can copy it into their receiver.
21
+ */
22
+ export function WebhookEndpointsCard({
23
+ endpoints,
24
+ eventKindOptions,
25
+ newSecret,
26
+ onCreate,
27
+ onToggle,
28
+ onDelete,
29
+ onDismissSecret,
30
+ }: {
31
+ endpoints: WebhookEndpointItem[]
32
+ /** The registered event kinds an endpoint may subscribe to (packages/kit/src/core/webhook-events.ts). */
33
+ eventKindOptions: string[]
34
+ /** Set once immediately after a create — the plaintext secret to show exactly once. */
35
+ newSecret: string | null
36
+ onCreate: (input: { url: string; eventKinds: string[] }) => Promise<void>
37
+ onToggle: (id: string, enabled: boolean) => Promise<void>
38
+ onDelete: (id: string) => Promise<void>
39
+ onDismissSecret: () => void
40
+ }) {
41
+ const t = useTranslations('webhooks')
42
+ const [url, setUrl] = useState('')
43
+ const [kinds, setKinds] = useState<string[]>([])
44
+ const [busy, setBusy] = useState(false)
45
+
46
+ return (
47
+ <Card withBorder padding="lg" radius="md" data-testid="webhook-endpoints-card">
48
+ <Stack gap="md">
49
+ <Title order={2} size="h3">
50
+ {t('cardTitle')}
51
+ </Title>
52
+ <Text size="sm" c="gray.7">
53
+ {t('cardDescription')}
54
+ </Text>
55
+
56
+ {newSecret ? (
57
+ <Card withBorder padding="md" radius="sm" bg="yellow.0" data-testid="webhook-new-secret">
58
+ <Stack gap="xs">
59
+ <Text size="sm" fw={600}>
60
+ {t('secretHeading')}
61
+ </Text>
62
+ <Text size="xs" c="gray.7">
63
+ {t('secretOnce')}
64
+ </Text>
65
+ <Code data-testid="webhook-new-secret-value">{newSecret}</Code>
66
+ <Button
67
+ variant="default"
68
+ size="xs"
69
+ data-testid="webhook-secret-dismiss"
70
+ style={{ alignSelf: 'flex-start' }}
71
+ onClick={onDismissSecret}
72
+ >
73
+ {t('secretDismiss')}
74
+ </Button>
75
+ </Stack>
76
+ </Card>
77
+ ) : null}
78
+
79
+ {endpoints.length === 0 ? (
80
+ <Text size="sm" c="gray.7" data-testid="webhook-endpoints-empty">
81
+ {t('endpointsEmpty')}
82
+ </Text>
83
+ ) : (
84
+ <Stack gap="xs" data-testid="webhook-endpoints-list">
85
+ {endpoints.map((endpoint) => (
86
+ <Group
87
+ key={endpoint.id}
88
+ justify="space-between"
89
+ wrap="nowrap"
90
+ data-testid={`webhook-endpoint-${endpoint.id}`}
91
+ >
92
+ <Stack gap={2} style={{ minWidth: 0 }}>
93
+ <Text size="sm" fw={600} truncate>
94
+ {endpoint.url}
95
+ </Text>
96
+ <Group gap={4} wrap="wrap">
97
+ {endpoint.eventKinds.map((kind) => (
98
+ <Badge key={kind} variant="light" radius="sm" color="blue">
99
+ {kind}
100
+ </Badge>
101
+ ))}
102
+ </Group>
103
+ </Stack>
104
+ <Group gap="sm" wrap="nowrap">
105
+ <Switch
106
+ checked={endpoint.enabled}
107
+ aria-label={t('toggleAriaLabel')}
108
+ data-testid={`webhook-endpoint-toggle-${endpoint.id}`}
109
+ disabled={busy}
110
+ onChange={(event) => {
111
+ setBusy(true)
112
+ void onToggle(endpoint.id, event.currentTarget.checked).finally(() =>
113
+ setBusy(false),
114
+ )
115
+ }}
116
+ />
117
+ <Button
118
+ size="xs"
119
+ variant="default"
120
+ color="red"
121
+ disabled={busy}
122
+ data-testid={`webhook-endpoint-delete-${endpoint.id}`}
123
+ onClick={() => {
124
+ setBusy(true)
125
+ void onDelete(endpoint.id).finally(() => setBusy(false))
126
+ }}
127
+ >
128
+ {t('deleteButton')}
129
+ </Button>
130
+ </Group>
131
+ </Group>
132
+ ))}
133
+ </Stack>
134
+ )}
135
+
136
+ <Stack gap="xs">
137
+ <TextInput
138
+ label={t('urlLabel')}
139
+ placeholder={t('urlPlaceholder')}
140
+ value={url}
141
+ data-testid="webhook-url"
142
+ onChange={(event) => setUrl(event.currentTarget.value)}
143
+ />
144
+ <MultiSelect
145
+ label={t('eventKindsLabel')}
146
+ data={eventKindOptions.map((kind) => ({ value: kind, label: kind }))}
147
+ value={kinds}
148
+ data-testid="webhook-event-kinds"
149
+ onChange={setKinds}
150
+ />
151
+ <Button
152
+ loading={busy}
153
+ disabled={!url.trim() || kinds.length === 0}
154
+ data-testid="webhook-create"
155
+ style={{ alignSelf: 'flex-start' }}
156
+ onClick={() => {
157
+ setBusy(true)
158
+ onCreate({ url: url.trim(), eventKinds: kinds })
159
+ .then(() => {
160
+ setUrl('')
161
+ setKinds([])
162
+ })
163
+ .finally(() => setBusy(false))
164
+ }}
165
+ >
166
+ {t('createButton')}
167
+ </Button>
168
+ </Stack>
169
+ </Stack>
170
+ </Card>
171
+ )
172
+ }
@@ -0,0 +1,464 @@
1
+ import {
2
+ appAbilityRules,
3
+ appMachineAbilityRules,
4
+ nonSessionAdministration,
5
+ type AppMachineCredentialKind,
6
+ type AppPersonCredentialKind,
7
+ type AppSubjectFields,
8
+ type AppSubjectType,
9
+ } from '@sssb/app-config/abilities'
10
+ import { canManageOrg, isRole, type Role } from './roles'
11
+
12
+ /**
13
+ * The authorization model. PURE TypeScript — imports only ./roles and the app-config seam
14
+ * (ADR-0006/-0012, lint-enforced): this file is the single source of truth for "who may do what" for
15
+ * the FRAMEWORK's base subjects, shared verbatim by the server seam (packages/kit/src/authz/authorize.ts) and the
16
+ * static demo twin. The public shape is deliberately CASL-like (can/cannot over action+subject) so the
17
+ * hand-rolled rule table can be swapped for @casl/ability later without touching callers. Deny by
18
+ * default: every path that isn't explicitly allowed is denied.
19
+ *
20
+ * FRAMEWORK/APP LINE (ADR-0012): the base union + switch below are framework; the APP's own subjects
21
+ * register through the seam — the `default:` case delegates to appAbilityRules,
22
+ * and the composed SubjectType is BaseSubjectType | AppSubjectType. An adopter extends abilities by
23
+ * editing src/app-config/abilities.ts, never this file's base union or switch.
24
+ *
25
+ * TWO KINDS OF ACTOR, each carrying the {@link Credential} it proved itself with (ADR-0012 addendum,
26
+ * 2026-11-16):
27
+ * - A PERSON ({@link AbilityActor}) is judged by the rules below, whether it came through a session or
28
+ * through another credential a person holds (an inbound email, a personal API token). Only an actor
29
+ * that STATES a session credential wields `manageAll`; for any other credential, or none, this file
30
+ * ignores it.
31
+ * - A MACHINE ({@link MachineActor}), such as a service key or a CI identity, is judged by a SEPARATE,
32
+ * deny-by-default table: the framework's {@link frameworkMachineRules} for base subjects and the app's
33
+ * `appMachineAbilityRules` for its own. A machine has no role, no `restricted` flag and no
34
+ * `manageAll`, so it can never reach a rule written for people.
35
+ */
36
+
37
+ export type AbilityAction = 'create' | 'read' | 'update' | 'delete' | 'manage'
38
+
39
+ /**
40
+ * The framework's base subjects. 'JobSchedule', 'WebhookDelivery' and 'InboundEmail' have no per-actor
41
+ * ability rules (all are system-managed — advanced by the cross-tenant scheduler / drained by the
42
+ * webhook system / filed by the inbound-email intake, never mutated through a per-user route); each
43
+ * exists as a SubjectType only so the audit trail can name it as a subject, and the switch denies them.
44
+ * 'WebhookEndpoint' DOES have rules (the org-admin endpoint card). 'Notification'/
45
+ * 'NotificationPref' and 'AgreementAcceptance' are SELF-ONLY, like 'User'. A new base subject must also
46
+ * say what a MACHINE may do with it: {@link frameworkMachineRules} is keyed by this union, so leaving it
47
+ * out fails the typecheck.
48
+ */
49
+ type BaseSubjectType =
50
+ | 'Job'
51
+ | 'Membership'
52
+ | 'Org'
53
+ | 'User'
54
+ | 'JobSchedule'
55
+ | 'WebhookEndpoint'
56
+ | 'WebhookDelivery'
57
+ | 'InboundEmail'
58
+ | 'Notification'
59
+ | 'NotificationPref'
60
+ | 'AgreementAcceptance'
61
+
62
+ /** The full subject union: framework base + the app's registered subjects (src/app-config/abilities.ts). */
63
+ export type SubjectType = BaseSubjectType | AppSubjectType
64
+
65
+ /**
66
+ * The subject an ability is checked against: the shape below, with the app's own fields (`AppSubjectFields`) intersected in.
67
+ * An INTERSECTION, not an `interface extends`, so the app may declare those fields as an interface, a type alias or a mapped type, and
68
+ * an app with none writes `Record<never, never>` rather than an empty interface it must silence the linter for.
69
+ */
70
+ export type AbilitySubject = AppSubjectFields & {
71
+ type: SubjectType
72
+ /** The org the subject lives in. `null`/absent means "not org-scoped" and never satisfies sameOrg. */
73
+ orgId?: string | null
74
+ /** Owner of the subject, for self-only rules (User.update). */
75
+ ownerId?: string
76
+ }
77
+
78
+ /**
79
+ * The credential kinds a PERSON can reach the app with: a browser `session`, an `inbound-email` from a
80
+ * member's address (SSSB's intake), and whatever the app registers on the seam (`AppPersonCredentialKind`,
81
+ * e.g. a personal API token). Composed, never edited, so an app's kinds need no framework change.
82
+ */
83
+ export type PersonCredentialKind = 'session' | 'inbound-email' | AppPersonCredentialKind
84
+
85
+ /**
86
+ * The credential kinds a MACHINE can reach the app with: SSSB's own per-org `service-key`, and whatever
87
+ * the app registers on the seam (`AppMachineCredentialKind`, e.g. a CI OIDC token).
88
+ */
89
+ export type MachineCredentialKind = 'service-key' | AppMachineCredentialKind
90
+
91
+ /**
92
+ * The framework subjects whose non-read actions take a browser SESSION:
93
+ * - ADMINISTRATION: inviting and managing members (Membership), changing the org (Org), registering and
94
+ * managing outbound webhook endpoints (WebhookEndpoint);
95
+ * - ACCEPTING TERMS (AgreementAcceptance): a legal act a person makes in a browser, not by token or email.
96
+ * A person may take these only through a stated session, unless the app widens one to a non-session
97
+ * kind on the seam (`nonSessionAdministration`). Reads are not gated.
98
+ *
99
+ * Not listed: service keys (no route mints one, and they are no ability subject), the other self-only
100
+ * subjects (User, Notification, NotificationPref: a person acting on their own things), the
101
+ * system-managed subjects (JobSchedule, WebhookDelivery, InboundEmail: denied to everyone), and Job (a
102
+ * product action).
103
+ */
104
+ export const ADMINISTRATIVE_SUBJECTS = ['Membership', 'Org', 'WebhookEndpoint', 'AgreementAcceptance'] as const
105
+ export type AdministrativeSubjectType = (typeof ADMINISTRATIVE_SUBJECTS)[number]
106
+
107
+ /**
108
+ * The non-session person credentials an app may widen a session-only subject to. Never `inbound-email`:
109
+ * an email's From line is the weakest credential SSSB has, so nothing it sends may administer anything.
110
+ * (`defineAbilitiesFor` refuses it at run time too, against a cast.)
111
+ */
112
+ export type WidenableCredentialKind = Exclude<PersonCredentialKind, 'session' | 'inbound-email'>
113
+
114
+ /**
115
+ * The contract for the app's `nonSessionAdministration` (src/app-config/abilities.ts): for each
116
+ * session-only subject, the non-session person credential kinds that may act on it too. Empty, the
117
+ * default, means each takes a browser session.
118
+ */
119
+ export type NonSessionAdministration = {
120
+ readonly [Subject in AdministrativeSubjectType]?: readonly WidenableCredentialKind[]
121
+ }
122
+
123
+ /**
124
+ * True when two kind unions share no member, checked in BOTH directions: `Extract<A, B>` alone misses a
125
+ * wide member, since `string` is not assignable to `'service-key'` while `'service-key'` is to `string`.
126
+ */
127
+ type Disjoint<A, B> = [Extract<A, B> | Extract<B, A>] extends [never] ? true : false
128
+ /** True when a kind union is a set of named kinds, not `string` (which would admit every kind). */
129
+ type Named<K> = string extends K ? false : true
130
+
131
+ /**
132
+ * The two kind unions must not overlap: a kind is a person's or a machine's, never both, or an audit
133
+ * row's `credential_kind` could not say which. And each must be NAMED kinds: an app that registers
134
+ * `string` would let a person claim `service-key`. Either mistake fails the typecheck here.
135
+ */
136
+ const credentialKindsAreDisjoint: Disjoint<PersonCredentialKind, MachineCredentialKind> = true
137
+ const credentialKindsAreNamed: Named<PersonCredentialKind> & Named<MachineCredentialKind> = true
138
+ void credentialKindsAreDisjoint
139
+ void credentialKindsAreNamed
140
+
141
+ /**
142
+ * HOW an actor proved who it is. `id` names WHICH credential (a token's row id, a service key's id, the
143
+ * inbound email's id), so an audit row can say which one acted and a revocation can be traced. It is
144
+ * never a secret. `null` when there is nothing to name: a session.
145
+ */
146
+ export interface Credential<Kind extends string = PersonCredentialKind | MachineCredentialKind> {
147
+ kind: Kind
148
+ id: string | null
149
+ }
150
+
151
+ /** The fields every PERSON actor has, whichever credential brought them. */
152
+ interface PersonActorFields {
153
+ kind?: 'person'
154
+ userId: string
155
+ /** Role in the ACTIVE org (mirrors AuthUser.role). */
156
+ role: Role
157
+ /** Limited-access seam: restricted members have a reduced feature surface (auth port). */
158
+ restricted: boolean
159
+ /** The org this actor is currently acting in — the anchor for every sameOrg check. */
160
+ activeOrgId: string
161
+ }
162
+
163
+ /**
164
+ * A PERSON acting in one org: built from a session by `abilityActorFromUser`, or, for a person who
165
+ * reached the app with another credential, by `abilityActorFromCredential`, which re-reads the person's
166
+ * standing through the auth port on every call (both in ../authz/authorize.ts). `kind` and `credential`
167
+ * are optional, so a literal written before credentials existed still compiles where it can, and is still
168
+ * judged by the person rules.
169
+ *
170
+ * TWO SHAPES, so the one mistake that matters is a type error. An actor whose `manageAll` may be true
171
+ * must STATE a session credential, because only a stated session wields it ({@link defineAbilitiesFor}
172
+ * enforces that at run time too). Every other actor has `manageAll: false`:
173
+ * - `credential`: how this person reached the app. Absent means NOT STATED, which is never read as a
174
+ * session: such an actor does not wield `manageAll`, takes no session-only action on a framework
175
+ * subject, and records no credential in the audit trail. A literal that stands for a session says
176
+ * `{ kind: 'session', id: null }`, as `abilityActorFromUser` does.
177
+ * - `manageAll`: the staff-org superpower, and it is LIVE. `abilityActorFromUser` sets it when the actor
178
+ * is ACTING AS the app's designated operator org (`staffOrgSlug` on the ADR-0012 seam). True
179
+ * short-circuits every per-subject rule below. It never crosses tenants: the rules it skips are already
180
+ * tenant-bounded, and every product query still runs inside withTenant (ADR-0004).
181
+ */
182
+ export type AbilityActor = PersonActorFields &
183
+ (
184
+ | { credential?: Credential<PersonCredentialKind>; manageAll: false }
185
+ | { credential: Credential<'session'>; manageAll: boolean }
186
+ )
187
+
188
+ /**
189
+ * A MACHINE acting in one org: a caller that is not a person — SSSB's own service keys, or a verifier
190
+ * the app owns (a CI identity, an integration). Built by `abilityActorFromService` or `machineActor`
191
+ * (../authz/authorize.ts), from a credential the route has already VERIFIED. Nothing in the type can
192
+ * tell a verified machine from a literal built out of request input. Under `service/` the authorize
193
+ * scan also requires `withServiceCaller`; anywhere else, the route is the only guard.
194
+ *
195
+ * Deliberately has no `role`, no `restricted` and no `manageAll`: a machine is not a member of anything,
196
+ * so nothing written for people can be satisfied by one. What a machine may do is exactly what
197
+ * {@link frameworkMachineRules} and the app's `appMachineAbilityRules` grant it, and both deny by default.
198
+ */
199
+ export interface MachineActor {
200
+ kind: 'machine'
201
+ /** What vouched for it: SSSB's `service-key`, or a credential kind the app registers (a CI token). */
202
+ credential: Credential<MachineCredentialKind>
203
+ /**
204
+ * `<credential kind>:<machine id>` — the machine's identity everywhere one is recorded: the audit
205
+ * trail's `actor_user_id`, an owner column. Qualified by kind so two verifiers' ids cannot collide.
206
+ */
207
+ principalId: string
208
+ /** The org the verified credential is bound to — the anchor for every sameOrg check. */
209
+ activeOrgId: string
210
+ }
211
+
212
+ /** Anyone `authorize()` can judge: a person or a machine. */
213
+ export type Actor = AbilityActor | MachineActor
214
+
215
+ /**
216
+ * The id to RECORD for an actor — `recordAuditEvent`'s `actorUserId`, or an owner column: a person's
217
+ * user id, or a machine's kind-qualified principal id. One function so every call site attributes
218
+ * a machine the same way.
219
+ */
220
+ export function principalIdOf(actor: Actor): string {
221
+ return actor.kind === 'machine' ? actor.principalId : actor.userId
222
+ }
223
+
224
+ /** The `sameOrg` helper the framework injects into every rule, its own and the app's. */
225
+ type SameOrg = (subject: AbilitySubject) => boolean
226
+
227
+ /**
228
+ * The contract the app's `appMachineAbilityRules` (src/app-config/abilities.ts) conforms to. It is
229
+ * called for APP subjects only; base subjects are {@link frameworkMachineRules}'s. An app that grants
230
+ * machines nothing registers `() => false`.
231
+ */
232
+ export type MachineAbilityRules = (
233
+ actor: MachineActor,
234
+ action: AbilityAction,
235
+ subject: AbilitySubject,
236
+ helpers: { sameOrg: SameOrg },
237
+ ) => boolean
238
+
239
+ type FrameworkMachineRule = (
240
+ actor: MachineActor,
241
+ action: AbilityAction,
242
+ subject: AbilitySubject,
243
+ sameOrg: SameOrg,
244
+ ) => boolean
245
+ const denyMachine: FrameworkMachineRule = () => false
246
+
247
+ /**
248
+ * What a MACHINE may do with each framework base subject. Keyed by BaseSubjectType, so a new base
249
+ * subject cannot be added without deciding this. One grant only:
250
+ * - Job: read|update = an SSSB service-key caller, sameOrg. It is the counterparty the job service API
251
+ * exists for — it polls its own org's jobs and reports their status. Any other machine gets nothing.
252
+ * - Everything else is denied: memberships, orgs and webhook endpoints are administrative acts a person
253
+ * answers for; User, Notification, NotificationPref and AgreementAcceptance are self-only and a machine
254
+ * has no self; the system-managed subjects have no per-actor rule for anyone.
255
+ */
256
+ const frameworkMachineRules: Record<BaseSubjectType, FrameworkMachineRule> = {
257
+ Job: (actor, action, subject, sameOrg) =>
258
+ actor.credential.kind === 'service-key' && (action === 'read' || action === 'update') && sameOrg(subject),
259
+ Membership: denyMachine,
260
+ Org: denyMachine,
261
+ User: denyMachine,
262
+ JobSchedule: denyMachine,
263
+ WebhookEndpoint: denyMachine,
264
+ WebhookDelivery: denyMachine,
265
+ InboundEmail: denyMachine,
266
+ Notification: denyMachine,
267
+ NotificationPref: denyMachine,
268
+ AgreementAcceptance: denyMachine,
269
+ }
270
+
271
+ export interface Ability {
272
+ can(action: AbilityAction, subject: AbilitySubject): boolean
273
+ cannot(action: AbilityAction, subject: AbilitySubject): boolean
274
+ }
275
+
276
+ /**
277
+ * Compile the rule table for one actor. The framework rules (deny by default):
278
+ * - manageAll → allow everything (held by a member acting AS the app's operator org; see above).
279
+ * - Job: read = sameOrg; create = !restricted && sameOrg.
280
+ * - Membership: read = sameOrg; create|manage = canManageOrg && sameOrg.
281
+ * - Org: read = sameOrg; update|manage = canManageOrg && sameOrg.
282
+ * - User: update = self only (subject.ownerId === actor.userId).
283
+ * - AgreementAcceptance: create|read = self only (subject.ownerId === actor.userId) — accept for myself.
284
+ * - Notification / NotificationPref: self only (subject.ownerId === actor.userId).
285
+ * - WebhookEndpoint: read = sameOrg; create|update|delete = canManageOrg && sameOrg (org-admin only).
286
+ * - JobSchedule / WebhookDelivery / InboundEmail: system-managed, no rules (denied).
287
+ * App-registered subjects are delegated to appAbilityRules via `default:`.
288
+ *
289
+ * A MACHINE actor never reaches any of that: it is judged by {@link frameworkMachineRules} for base
290
+ * subjects and the app's `appMachineAbilityRules` for its own, and both deny by default.
291
+ *
292
+ * NARROWING. The app's rules see `actor.credential.kind`, so "this needs a browser session" is a line in
293
+ * `appAbilityRules`. A per-CREDENTIAL ceiling (one token allowed less than its owner) is not built; if
294
+ * one is ever needed it intersects here, `can(...) && withinCeiling(actor.credential, action, subject)`,
295
+ * so every caller of `can` honours it.
296
+ */
297
+ export function defineAbilitiesFor(actor: Actor): Ability {
298
+ // Same org iff the subject is org-scoped AND its org is the one the actor is acting in.
299
+ const sameOrg: SameOrg = (subject) => subject.orgId != null && subject.orgId === actor.activeOrgId
300
+
301
+ if (actor.kind === 'machine') {
302
+ const machine = actor
303
+ // Typed against the contract here, at CALL time rather than module load. A seam module that
304
+ // value-imports this file AND exports this rule as a `const` would otherwise meet the binding before
305
+ // it is initialized (an `export function` is hoisted and would not).
306
+ const appMachineRules: MachineAbilityRules = appMachineAbilityRules
307
+ const machineCan = (action: AbilityAction, subject: AbilitySubject): boolean =>
308
+ Object.hasOwn(frameworkMachineRules, subject.type)
309
+ ? frameworkMachineRules[subject.type as BaseSubjectType](machine, action, subject, sameOrg)
310
+ : appMachineRules(machine, action, subject, { sameOrg })
311
+ return { can: machineCan, cannot: (action, subject) => !machineCan(action, subject) }
312
+ }
313
+ // The person is judged as a COPY made by naming each field the rules read, never as `{ ...actor }`:
314
+ // a spread copies own enumerable fields only, so an actor whose fields are getters on a class, or
315
+ // live on a prototype, would arrive with no `restricted` and no `userId`. What is copied is what is
316
+ // validated, and what is validated is all that is judged.
317
+ const fields = personFieldsOf(actor)
318
+ // Anything that is not a well-formed person is denied everything. A machine-shaped object that lost
319
+ // its `kind` (a cast, a value rehydrated from storage) would otherwise be judged as a person with no
320
+ // role, and `!restricted` holds for an undefined flag.
321
+ if (!isWellFormedPerson(fields)) return { can: () => false, cannot: () => true }
322
+ const copy = fields as AbilityActor
323
+
324
+ // The staff superpower belongs to a SESSION acting as the operator org. Enforced here rather than
325
+ // trusted to whoever built the actor: a person who came through any other credential (an email, a
326
+ // token), or who states none, never wields it, even acting in the staff org. The app's rules are
327
+ // handed the same effective value.
328
+ const session = copy.credential?.kind === 'session'
329
+ // Read at call time, like the app's machine rules (see the machine branch above).
330
+ const widening: NonSessionAdministration = nonSessionAdministration
331
+ const person: AbilityActor =
332
+ copy.manageAll && session
333
+ ? { ...copy, manageAll: true, credential: { kind: 'session', id: copy.credential?.id ?? null } }
334
+ : { ...copy, manageAll: false }
335
+ // sameOrg for the person reads the COPY's org, like every other person rule.
336
+ const personSameOrg: SameOrg = (subject) => subject.orgId != null && subject.orgId === person.activeOrgId
337
+
338
+ function can(action: AbilityAction, subject: AbilitySubject): boolean {
339
+ // The staff-org superpower. manageAll precedes
340
+ // the restricted checks: a restricted staff-org member would gain full authoring. Staff-org
341
+ // membership is assumed non-restricted (nothing enforces it); if a restricted operator ever
342
+ // becomes a real configuration, gate authoring verbs here first.
343
+ if (person.manageAll) return true
344
+
345
+ // Administration, and accepting terms, take a stated session, unless the app widened this subject
346
+ // to this credential.
347
+ // A refusal here is final; a pass falls through to the subject's own rule below.
348
+ if (action !== 'read' && (ADMINISTRATIVE_SUBJECTS as readonly string[]).includes(subject.type) && !session) {
349
+ const widenedTo: readonly string[] = widening[subject.type as AdministrativeSubjectType] ?? []
350
+ const kind = person.credential?.kind
351
+ // `inbound-email` is refused even if a cast put it in the list (WidenableCredentialKind).
352
+ if (kind === undefined || kind === 'inbound-email' || !widenedTo.includes(kind)) return false
353
+ }
354
+
355
+ switch (subject.type) {
356
+ case 'Job':
357
+ if (action === 'read') return personSameOrg(subject)
358
+ if (action === 'create') return !person.restricted && personSameOrg(subject)
359
+ return false
360
+ case 'Membership':
361
+ if (action === 'read') return personSameOrg(subject)
362
+ if (action === 'create' || action === 'manage')
363
+ return canManageOrg(person.role) && personSameOrg(subject)
364
+ return false
365
+ case 'Org':
366
+ if (action === 'read') return personSameOrg(subject)
367
+ if (action === 'update' || action === 'manage')
368
+ return canManageOrg(person.role) && personSameOrg(subject)
369
+ return false
370
+ case 'User':
371
+ if (action === 'update') return subject.ownerId === person.userId
372
+ return false
373
+ case 'Notification':
374
+ // Self-only (like User): read/mark-read only your OWN notifications. The route ALSO
375
+ // filters by recipient_user_id (the rls-independent recipient guard) — belt and braces.
376
+ if (action === 'read' || action === 'update') return subject.ownerId === person.userId
377
+ return false
378
+ case 'NotificationPref':
379
+ // Self-only: a user manages ONLY their own preferences. read/update/create/manage all
380
+ // require ownership; the route always uses the session's user id, never a client one.
381
+ if (action === 'read' || action === 'update' || action === 'create' || action === 'manage') {
382
+ return subject.ownerId === person.userId
383
+ }
384
+ return false
385
+ case 'AgreementAcceptance':
386
+ // Self-only (like User/Notification): a user may record/read only THEIR OWN acceptance.
387
+ // The route always uses the session's user id as ownerId, never a client-supplied one.
388
+ if (action === 'create' || action === 'read') return subject.ownerId === person.userId
389
+ return false
390
+ case 'WebhookEndpoint':
391
+ // Registering/managing an egress endpoint is an administrative act, gated like Org.
392
+ if (action === 'read') return personSameOrg(subject)
393
+ if (action === 'create' || action === 'update' || action === 'delete') {
394
+ return canManageOrg(person.role) && personSameOrg(subject)
395
+ }
396
+ return false
397
+ case 'JobSchedule':
398
+ case 'WebhookDelivery':
399
+ case 'InboundEmail':
400
+ // System-managed subjects: no per-actor rule, denied (they exist only to be named in
401
+ // the audit trail). See the BaseSubjectType note above.
402
+ return false
403
+ default:
404
+ // App subjects register through the seam (src/app-config/abilities.ts). Deny by default:
405
+ // appAbilityRules returns false for anything it does not explicitly allow.
406
+ return appAbilityRules(person, action, subject, { sameOrg: personSameOrg })
407
+ }
408
+ }
409
+
410
+ return {
411
+ can,
412
+ cannot: (action, subject) => !can(action, subject),
413
+ }
414
+ }
415
+
416
+ /** The loose record {@link personFieldsOf} copies into, before it is validated. */
417
+ interface PersonFieldsCopy {
418
+ kind: unknown
419
+ credential: unknown
420
+ userId: unknown
421
+ role: unknown
422
+ restricted: unknown
423
+ activeOrgId: unknown
424
+ manageAll: unknown
425
+ }
426
+
427
+ /**
428
+ * Copy, by NAME, every field the person rules read, reading through getters and prototypes exactly
429
+ * once. The credential is copied too, so a getter cannot answer `session` to the check and something
430
+ * else to the rule.
431
+ */
432
+ function personFieldsOf(actor: AbilityActor): PersonFieldsCopy {
433
+ const loose = actor as unknown as Record<string, unknown>
434
+ const credential = loose['credential'] as { kind?: unknown; id?: unknown } | undefined | null
435
+ return {
436
+ kind: loose['kind'],
437
+ credential: credential == null ? undefined : { kind: credential.kind, id: credential.id },
438
+ userId: loose['userId'],
439
+ role: loose['role'],
440
+ restricted: loose['restricted'],
441
+ activeOrgId: loose['activeOrgId'],
442
+ manageAll: loose['manageAll'],
443
+ }
444
+ }
445
+
446
+ /**
447
+ * The shape the person rules can judge: `kind` is 'person' or absent, `role` is a real role,
448
+ * `restricted` and `manageAll` are booleans, and a credential, if any, has a string kind. The type
449
+ * promises this; the check is for values that arrive around it.
450
+ */
451
+ function isWellFormedPerson(loose: PersonFieldsCopy): boolean {
452
+ const credential = loose.credential as { kind?: unknown; id?: unknown } | undefined
453
+ return (
454
+ (loose.kind === undefined || loose.kind === 'person') &&
455
+ typeof loose.role === 'string' &&
456
+ isRole(loose.role) &&
457
+ typeof loose.restricted === 'boolean' &&
458
+ typeof loose.userId === 'string' &&
459
+ typeof loose.activeOrgId === 'string' &&
460
+ typeof loose.manageAll === 'boolean' &&
461
+ (credential === undefined ||
462
+ (typeof credential.kind === 'string' && (credential.id === null || typeof credential.id === 'string')))
463
+ )
464
+ }