@sssb/kit 0.0.0-stage → 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.
Files changed (214) 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 +209 -3
  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 +312 -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 +270 -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 +94 -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 +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,205 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { expect } from 'vitest'
4
+ import seamSpecifiers from '../seam-specifiers.json'
5
+ import type { CheckImpl } from './types'
6
+
7
+ /**
8
+ * `seam-map`: every `@sssb/app-config/*` specifier the shipped kit source imports (../seam-specifiers.json, held equal
9
+ * to a scan of the source by the kit's own test) resolves for this app. Two halves (ADR-0014 part 1):
10
+ *
11
+ * - When the app's seam is a PACKAGE (`src/app-config/package.json`, a workspace package the app declares as
12
+ * `@sssb/app-config`, which is how an adopter's install reaches it), it has the name that declaration names, and
13
+ * each specifier resolves through that package's `exports` map to a FILE
14
+ * (a directory is not something an import can load). The `./*` pattern covers flat `.ts` modules only, so a
15
+ * directory module (`db/migrations`) or a `.tsx` one needs its own entry, and a map that forgets one fails here by
16
+ * name rather than at the first import. Inside SSSB's own repo the seam resolves through each app's alias, and
17
+ * there is no package to read.
18
+ * - Each specifier loads when imported FROM KIT CODE. Under Vitest that import goes through the project's
19
+ * `@sssb/app-config` alias (the `@sssb/tools/vitest` preset sets it, as this repo's config does), never through
20
+ * the `exports` map, so this half proves every seam module exists and loads; that the map reaches it is the first
21
+ * half's to prove.
22
+ */
23
+ const SEAM = '@sssb/app-config'
24
+
25
+ type ExportsTarget = string | null | { [condition: string]: ExportsTarget } | ExportsTarget[]
26
+
27
+ /**
28
+ * The conditions matched, NODE'S OWN for an ES `import` of the seam (`node`, `import`, `module-sync`, `default`;
29
+ * Node 22.12+ and 24 match `module-sync` by default): every tool that imports it outside a bundler (Node, tsx, a
30
+ * migration script) matches these, and a bundler matches its own (`module`, `browser`, `development`, ...), which
31
+ * belong to one environment and so cannot stand in for the rest. `types` is never one: it resolves for the type
32
+ * checker only, and a target behind it loads nothing at run time.
33
+ */
34
+ const CONDITIONS: ReadonlySet<string> = new Set(['node', 'import', 'module-sync', 'default'])
35
+
36
+ /**
37
+ * What resolving one target gives: a file (relative to the package), a target Node refuses (`invalid`, why; Node
38
+ * throws ERR_INVALID_PACKAGE_TARGET), `null` for an explicit exclusion, which stops a conditions object's search (an
39
+ * array goes on to its next item), or `undefined` for "no condition matched", which the caller falls through.
40
+ */
41
+ type Resolved = { file: string } | { target: string; invalid: string } | null | undefined
42
+
43
+ /** True when a path has a `.`, `..` or `node_modules` segment, percent-encoded or not, in any case (Node's rule). */
44
+ function hasInvalidSegment(value: string): boolean {
45
+ let decoded = value
46
+ try {
47
+ decoded = decodeURIComponent(value)
48
+ } catch {
49
+ // a malformed escape: judge the raw text
50
+ }
51
+ return decoded.split(/[\\/]/).some((segment) => ['.', '..', 'node_modules'].includes(segment.toLowerCase()))
52
+ }
53
+
54
+ /**
55
+ * A string target, held to Node's rules (PACKAGE_TARGET_RESOLVE): it must start with `./` (so no bare name, no `../`,
56
+ * no absolute path or URL), and neither it (past that `./`) nor the pattern's match may have a `.`, `..` or
57
+ * `node_modules` segment. An empty segment is only deprecated by Node, so it passes here too.
58
+ */
59
+ function stringTarget(target: string, match: string | undefined): Resolved {
60
+ if (!target.startsWith('./')) return { target, invalid: 'it does not start with "./"' }
61
+ if (hasInvalidSegment(target.slice(2))) return { target, invalid: 'it has a ".", ".." or "node_modules" segment' }
62
+ if (match === undefined) return { file: target }
63
+ const file = target.replaceAll('*', match)
64
+ if (hasInvalidSegment(match))
65
+ return { target: file, invalid: 'its `*` matches a ".", ".." or "node_modules" segment' }
66
+ return { file }
67
+ }
68
+
69
+ /**
70
+ * A conditional export target, resolved as Node does (PACKAGE_TARGET_RESOLVE): an object's conditions in its OWN key
71
+ * order, the first that matches and yields something winning, and one whose nested target matches no condition
72
+ * falling through to the next; an array's items in order, an invalid, `null` or unmatched one falling through, the
73
+ * first file winning, and when none does, the last invalid-or-`null` item's result (an empty array is `null`, and
74
+ * one whose items all matched nothing is unmatched, so the condition holding it falls through too).
75
+ */
76
+ function resolveTarget(target: ExportsTarget | undefined, match: string | undefined): Resolved {
77
+ if (typeof target === 'string') return stringTarget(target, match)
78
+ if (target === null) return null
79
+ if (target === undefined) return undefined
80
+ if (Array.isArray(target)) {
81
+ if (target.length === 0) return null
82
+ let last: Resolved = undefined
83
+ for (const item of target) {
84
+ const resolved = resolveTarget(item, match)
85
+ if (resolved === undefined) continue
86
+ if (resolved === null || 'invalid' in resolved) {
87
+ last = resolved
88
+ continue
89
+ }
90
+ return resolved
91
+ }
92
+ return last
93
+ }
94
+ for (const [condition, value] of Object.entries(target)) {
95
+ if (!CONDITIONS.has(condition)) continue
96
+ const resolved = resolveTarget(value, match)
97
+ if (resolved !== undefined) return resolved
98
+ }
99
+ return undefined
100
+ }
101
+
102
+ /**
103
+ * Node's PATTERN_KEY_COMPARE, as a sort comparator: the key with the longer prefix before its `*` first, and between
104
+ * equal prefixes the longer key first.
105
+ */
106
+ function patternKeyCompare(a: string, b: string): number {
107
+ const [baseA, baseB] = [a.indexOf('*'), b.indexOf('*')]
108
+ if (baseA !== baseB) return baseB - baseA
109
+ return b.length - a.length
110
+ }
111
+
112
+ /**
113
+ * Node's subpath resolution over one `exports` map (PACKAGE_IMPORTS_EXPORTS_RESOLVE): an exact key, else the first
114
+ * pattern key (one `*`, in PATTERN_KEY_COMPARE order) that matches with a NON-EMPTY `*`; whatever that one key's
115
+ * target resolves to is the answer, as in Node, which never tries a second pattern.
116
+ */
117
+ function resolveExport(exportsMap: Record<string, ExportsTarget>, subpath: string): Resolved {
118
+ if (Object.hasOwn(exportsMap, subpath) && !subpath.includes('*')) {
119
+ return resolveTarget(exportsMap[subpath], undefined)
120
+ }
121
+ const patterns = Object.keys(exportsMap)
122
+ .filter((key) => key.split('*').length === 2)
123
+ .sort(patternKeyCompare)
124
+ for (const key of patterns) {
125
+ const star = key.indexOf('*')
126
+ const [base, trailer] = [key.slice(0, star), key.slice(star + 1)]
127
+ if (!subpath.startsWith(base) || subpath === base) continue
128
+ if (trailer !== '' && !(subpath.endsWith(trailer) && subpath.length >= key.length)) continue
129
+ return resolveTarget(exportsMap[key], subpath.slice(base.length, subpath.length - trailer.length))
130
+ }
131
+ return null
132
+ }
133
+
134
+ /**
135
+ * The name the app's seam package must have: the package a `workspace:<name>@<range>` declaration of
136
+ * `@sssb/app-config` in the app's `package.json` names (each app's seam is a workspace package of a name of its own,
137
+ * which pnpm's `add`, `remove` and `update` keep linked), else `@sssb/app-config` itself.
138
+ */
139
+ function seamPackageName(appDir: string): string {
140
+ const file = path.join(appDir, 'package.json')
141
+ if (!existsSync(file)) return SEAM
142
+ const manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>
143
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
144
+ const deps = manifest[field]
145
+ const spec = typeof deps === 'object' && deps !== null ? (deps as Record<string, unknown>)[SEAM] : undefined
146
+ if (typeof spec === 'string') return /^workspace:(@?[^@]+)@/.exec(spec)?.[1] ?? SEAM
147
+ }
148
+ return SEAM
149
+ }
150
+
151
+ export const seamMap: CheckImpl = {
152
+ tests: {
153
+ "through the exports map of the app's seam package, when it has one": ({ appDir }) => {
154
+ const seamDir = path.join(appDir, 'src/app-config')
155
+ const manifestFile = path.join(seamDir, 'package.json')
156
+ if (!existsSync(manifestFile)) return
157
+ const manifest = JSON.parse(readFileSync(manifestFile, 'utf8')) as {
158
+ name?: unknown
159
+ exports?: unknown
160
+ }
161
+ const problems: string[] = []
162
+ const name = seamPackageName(appDir)
163
+ if (manifest.name !== name)
164
+ problems.push(`src/app-config/package.json is named ${String(manifest.name)}, not ${name}`)
165
+ const exportsMap =
166
+ typeof manifest.exports === 'object' && manifest.exports !== null && !Array.isArray(manifest.exports)
167
+ ? (manifest.exports as Record<string, ExportsTarget>)
168
+ : undefined
169
+ if (!exportsMap) problems.push('src/app-config/package.json has no `exports` map')
170
+ else {
171
+ for (const specifier of seamSpecifiers.specifiers) {
172
+ const subpath = `.${specifier.slice(SEAM.length)}`
173
+ const resolved = resolveExport(exportsMap, subpath)
174
+ if (resolved === null || resolved === undefined) {
175
+ problems.push(
176
+ `${specifier}: no \`exports\` entry for ${subpath} that resolves under the conditions ` +
177
+ `${[...CONDITIONS].join(', ')}`,
178
+ )
179
+ } else if ('invalid' in resolved) {
180
+ problems.push(
181
+ `${specifier}: \`exports\` maps ${subpath} to ${resolved.target}, which Node refuses: ` +
182
+ `${resolved.invalid} (ERR_INVALID_PACKAGE_TARGET)`,
183
+ )
184
+ } else if (!statSync(path.join(seamDir, resolved.file), { throwIfNoEntry: false })?.isFile()) {
185
+ problems.push(
186
+ `${specifier}: \`exports\` maps ${subpath} to ${resolved.file}, which is not a file`,
187
+ )
188
+ }
189
+ }
190
+ }
191
+ expect(problems, problems.join('\n')).toEqual([])
192
+ },
193
+ "from the kit's own code": async () => {
194
+ const problems: string[] = []
195
+ for (const specifier of seamSpecifiers.specifiers) {
196
+ try {
197
+ await import(/* @vite-ignore */ specifier)
198
+ } catch (error) {
199
+ problems.push(`${specifier}: ${error instanceof Error ? error.message : String(error)}`)
200
+ }
201
+ }
202
+ expect(problems).toEqual([])
203
+ },
204
+ },
205
+ }
@@ -0,0 +1,59 @@
1
+ import path from 'node:path'
2
+ import { authzMutations } from './authz'
3
+ import { appRolesCheck, migrationOrder, rlsPglite } from './db'
4
+ import { demoPresets } from './demo-presets'
5
+ import { i18nParity, i18nPartition } from './i18n'
6
+ import { checkOptOut, registerChecks } from './register'
7
+ import { seamMap } from './seam-map'
8
+ import type { CheckContext, CheckImpl } from './types'
9
+ import { registerTestTmpDirCleanup } from '../tmp-dir'
10
+
11
+ /**
12
+ * THE CONFORMANCE SUITE (ADR-0014 part 3, step P5): the framework's checks that must hold for EVERY app, run
13
+ * against the app's own seam from the app's own tree. Each app carries `src/sssb.conformance.test.ts`, which calls
14
+ *
15
+ * conformanceSuite({ appDir: path.resolve(import.meta.dirname, '..'), optOut: {} })
16
+ *
17
+ * and nothing else. A file in the app's tree is what makes it run by default: an `include` of a file under
18
+ * `node_modules` never runs (Vitest's default `exclude` drops it, and an app extending that exclude drops it again).
19
+ *
20
+ * WHAT IT REGISTERS is fixed by `../checks.json` (exported as `@sssb/kit/testing/checks.json`, which `sssb doctor`
21
+ * reads without loading the kit): its `unit` checks, each a `describe('[sssb:<id>] <title>')` holding exactly the
22
+ * named `it`s. The registration, the opt-outs (`optOut: { '<id>': '<why>' }`, refused while the file is collected
23
+ * when the id is unknown or the reason empty, and listed as `[sssb:opt-out:<id>] <why>`) and the skip guard (the run
24
+ * fails if a check that is not opted out did not run) are ./register.ts's, which the contract runner
25
+ * (`@sssb/kit/testing/contract`) shares.
26
+ */
27
+
28
+ /** The unit checks' implementations, by id. The contract checks are `@sssb/kit/testing/contract`'s. */
29
+ const IMPLEMENTATIONS: Readonly<Record<string, CheckImpl>> = {
30
+ 'authz-mutations': authzMutations,
31
+ 'i18n-partition': i18nPartition,
32
+ 'i18n-parity': i18nParity,
33
+ 'rls-pglite': rlsPglite,
34
+ 'migration-order': migrationOrder,
35
+ 'app-roles': appRolesCheck,
36
+ 'demo-presets': demoPresets,
37
+ 'seam-map': seamMap,
38
+ }
39
+
40
+ export interface ConformanceOptions {
41
+ /** The app's directory (the one holding its `package.json` and `src/`), absolute or relative to the working directory. */
42
+ appDir: string
43
+ /** Checks this app leaves out, each with the reason: `{ '<check id>': '<why>' }`. */
44
+ optOut?: Readonly<Record<string, string>>
45
+ }
46
+
47
+ /** Registers the conformance suite in the calling test file. Call it once, at the file's top level. */
48
+ export function conformanceSuite(options: ConformanceOptions): void {
49
+ // First, so the scratch directories' cleanup is this file's own, at its top level, and runs after the checks'
50
+ // teardown, even under `isolate: false`, where the helper loads once per worker (../tmp-dir.ts).
51
+ registerTestTmpDirCleanup()
52
+ const optOut = options.optOut ?? {}
53
+ checkOptOut('conformanceSuite', 'unit', optOut)
54
+ if (typeof options.appDir !== 'string' || options.appDir === '') {
55
+ throw new Error('conformanceSuite: appDir must name the app directory')
56
+ }
57
+ const context: CheckContext = { appDir: path.resolve(options.appDir) }
58
+ registerChecks({ caller: 'conformanceSuite', runner: 'unit', implementations: IMPLEMENTATIONS, optOut, context })
59
+ }
@@ -0,0 +1,18 @@
1
+ /** What every unit check is handed: the app it is checking. */
2
+ export interface CheckContext {
3
+ /** The app's directory: the one holding its `package.json`, `src/app`, `src/app-config` and `messages/`. */
4
+ appDir: string
5
+ }
6
+
7
+ /**
8
+ * One check's implementation: a body per test, under exactly the names `checks.json` gives it (the suite refuses to
9
+ * register a check whose names differ), and an optional `setup` the suite runs while the file is collected, inside
10
+ * the check's `describe`, before any test of the file runs. `C` is what the runner hands each test: the unit suite's
11
+ * `CheckContext`, or the contract runner's server.
12
+ */
13
+ export interface CheckImpl<C = CheckContext> {
14
+ setup?: (context: C) => void
15
+ /** Per-test timeouts, by test name, for the ones that migrate a database. */
16
+ timeouts?: Readonly<Record<string, number>>
17
+ tests: Readonly<Record<string, (context: C) => unknown>>
18
+ }
@@ -0,0 +1,200 @@
1
+ import { sql } from 'kysely'
2
+ import { afterAll, beforeAll, expect } from 'vitest'
3
+ import { startContractServer, type ContractServer } from '../adapters/real/contract-postgres'
4
+ import { checkOptOut, registerChecks, runsAny } from './conformance/register'
5
+ import type { CheckImpl } from './conformance/types'
6
+ import { registerTestTmpDirCleanup } from './tmp-dir'
7
+
8
+ /**
9
+ * `@sssb/kit/testing/contract`: THE CONTRACT RUNNER (ADR-0014 part 3, step P5). The migrations and the
10
+ * tenant-isolation proofs the unit suite runs on pglite, on REAL Postgres, over the app's own tables, in a database of
11
+ * the app's own. Every app calls it from its `tests/contract/rls-contract.test.ts`, run by the contract Vitest config
12
+ * (`pnpm test:contract`), never by the unit run:
13
+ *
14
+ * contractSuite({ port: portFor('contractPg'), optOut: {} })
15
+ *
16
+ * Generic: it knows nothing of the app but what the seam hands it (the slug, the migrations, the app's half of the RLS
17
+ * proofs), so every app's file is that one call. Its checks are `contract` checks in `./checks.json`, registered,
18
+ * opted out and guarded against skipping exactly as the unit suite's are (./conformance/register.ts), in this order,
19
+ * which is deliberate:
20
+ * 1. `contract-owner-pass`: a NON-SUPERUSER OWNER migrates and runs the proofs, as Aurora's master user does
21
+ * (../db/owner-pass.ts says why no other pass could see a missing role switch). It runs first so that on a fresh
22
+ * server the owner's own migration 0001 is what creates `app_user`; then the same again, now that `app_user`
23
+ * exists: the branch a reused server takes (CI's service container is shared, so every suite after the first takes
24
+ * it). Each makes a throwaway database and role and removes them, with what the role granted; a role it cannot
25
+ * remove fails the pass. The same holds for every cluster-wide role the app's own migrations create and name in
26
+ * `appRoles` (../db/app-roles.ts): the second pass finds it there, and the owner is granted the ADMIN its creator
27
+ * holds, on an ordinary role only.
28
+ * 2. `contract-rls`: the full proof suite as a superuser, in the app's own database (`<slug>_contract`).
29
+ * 3. `contract-data-api`: the same app's migrations and proofs over the RDS Data API transport, through the
30
+ * emulator (../adapters/real/rds-data-emulator.ts) on the same server, in a database of its own made empty first,
31
+ * and the owner pass through it too: the transport an Aurora deployment outside a VPC reaches the database by.
32
+ *
33
+ * It does not prove the framework's migration 0015 branch by branch, a second owner on one cluster, or the Data API
34
+ * transport's own behaviour (its one-transaction migrator, the lock race, the emulator's strictness): those are about
35
+ * the framework, and run once, against SSSB's fixture (packages/kit/src/adapters/real/*.contract.test.ts).
36
+ *
37
+ * The server is CONTRACT_DATABASE_URL's (a superuser's URL; CI's service container) or, unset, an embedded-postgres
38
+ * of the file's own on `port` (or CONTRACT_PG_PORT). `embedded-postgres` is an optional peer: an app that runs this
39
+ * locally has it in its devDependencies (../adapters/real/contract-postgres.ts).
40
+ */
41
+
42
+ export interface ContractOptions {
43
+ /** The embedded server's port: `portFor('contractPg')` from `@sssb/tools/ports`; CONTRACT_PG_PORT when omitted. */
44
+ port?: number
45
+ /** The app's database; `contractDatabaseName` of the seam's `APP_SLUG` when omitted. */
46
+ database?: string
47
+ /** Checks this app leaves out, each with the reason: `{ '<check id>': '<why>' }`. */
48
+ optOut?: Readonly<Record<string, string>>
49
+ }
50
+
51
+ /**
52
+ * The database name a suite uses for an app: `<slug>_contract`, the slug folded to what an unquoted Postgres
53
+ * identifier may hold. `acme-corp` becomes `acme_corp_contract`, so a renamed app gets its own
54
+ * name with no edit anywhere.
55
+ */
56
+ export function contractDatabaseName(slug: string): string {
57
+ // 63 is Postgres's identifier limit; "_contract" is 9 of it.
58
+ const underscored = slug.toLowerCase().replace(/[^a-z0-9]+/g, '_')
59
+ // The leading and trailing underscore trimmed by a loop rather than `/^_+|_+$/`, a pattern that backtracks
60
+ // quadratically on a long run (CodeQL flags it on a caller's input); the collapse above already leaves at most one
61
+ // underscore at each end, so this changes no result.
62
+ let from = 0
63
+ let to = underscored.length
64
+ while (from < to && underscored[from] === '_') from++
65
+ while (to > from && underscored[to - 1] === '_') to--
66
+ const folded = underscored.slice(from, to).slice(0, 50)
67
+ const base = /^[a-z]/.test(folded) ? folded : `app_${folded}`
68
+ return `${base}_contract`
69
+ }
70
+
71
+ /** The Data API pass's own database, beside the app's: the same name with `_data_api`, within the 63 of an identifier. */
72
+ const dataApiDatabaseName = (database: string) => `${database.slice(0, 63 - '_data_api'.length)}_data_api`
73
+
74
+ /** What each contract check is handed: the server and the app's database, both set when the file's tests start. */
75
+ interface ContractContext {
76
+ server(): ContractServer
77
+ database(): string
78
+ }
79
+
80
+ // Everything that composes the framework's migrations with the app's reaches the seam, so it is imported when a test
81
+ // runs, not when the file is collected: `contractDatabaseName` stays importable with no seam at all.
82
+ const migrate = () => import('../db/migrate')
83
+ const proofs = () => import('../db/rls-proof-runner')
84
+ const dataApi = () => import('../adapters/real/contract-data-api')
85
+
86
+ const TIMEOUT_MS = 120_000
87
+
88
+ async function ownerPass(context: ContractContext): Promise<void> {
89
+ const { runOwnerPass } = await import('../db/owner-pass')
90
+ const server = context.server()
91
+ const admin = server.connectAsSuperuser(server.maintenanceDatabase)
92
+ try {
93
+ await runOwnerPass(
94
+ {
95
+ admin,
96
+ superuser: server.superuser,
97
+ maintenanceDatabase: server.maintenanceDatabase,
98
+ connect: (login) => server.connect(login),
99
+ },
100
+ expect,
101
+ )
102
+ } finally {
103
+ await admin.destroy()
104
+ }
105
+ }
106
+
107
+ const IMPLEMENTATIONS: Readonly<Record<string, CheckImpl<ContractContext>>> = {
108
+ 'contract-owner-pass': {
109
+ timeouts: {
110
+ 'a non-superuser owner migrates, and switches to app_user inside withTenant': TIMEOUT_MS,
111
+ 'a non-superuser owner migrates where app_user already exists, and switches too': TIMEOUT_MS,
112
+ },
113
+ tests: {
114
+ 'a non-superuser owner migrates, and switches to app_user inside withTenant': ownerPass,
115
+ 'a non-superuser owner migrates where app_user already exists, and switches too': async (context) => {
116
+ const server = context.server()
117
+ const admin = server.connectAsSuperuser(server.maintenanceDatabase)
118
+ try {
119
+ const existing = await sql<{
120
+ n: number
121
+ }>`SELECT count(*)::int AS n FROM pg_roles WHERE rolname = 'app_user'`.execute(admin)
122
+ expect(existing.rows[0]!.n).toBe(1)
123
+ // ...and so does every role the app names in `appRoles`, which the first pass's migrations created.
124
+ const { appRoles } = await import('../db/app-roles')
125
+ for (const role of await appRoles()) {
126
+ const named = await sql<{
127
+ n: number
128
+ }>`SELECT count(*)::int AS n FROM pg_roles WHERE rolname = ${role}`.execute(admin)
129
+ expect(named.rows[0]!.n, role).toBe(1)
130
+ }
131
+ } finally {
132
+ await admin.destroy()
133
+ }
134
+ await ownerPass(context)
135
+ },
136
+ },
137
+ },
138
+ 'contract-rls': {
139
+ timeouts: { 'the full RLS proof suite passes': TIMEOUT_MS },
140
+ tests: {
141
+ 'the full RLS proof suite passes': async (context) => {
142
+ const db = context.server().connectAsSuperuser(context.database())
143
+ await (await migrate()).migrateToLatest(db)
144
+ await (await proofs()).runRlsProofs(db, expect)
145
+ },
146
+ },
147
+ },
148
+ 'contract-data-api': {
149
+ timeouts: {
150
+ 'the full RLS proof suite passes through the Data API': TIMEOUT_MS,
151
+ 'a non-superuser owner migrates, and switches to app_user inside withTenant, through the Data API':
152
+ TIMEOUT_MS,
153
+ },
154
+ tests: {
155
+ 'the full RLS proof suite passes through the Data API': async (context) =>
156
+ (await dataApi()).proveRlsThroughDataApi(context.server(), dataApiDatabaseName(context.database())),
157
+ 'a non-superuser owner migrates, and switches to app_user inside withTenant, through the Data API': async (
158
+ context,
159
+ ) => (await dataApi()).runDataApiOwnerPass(context.server()),
160
+ },
161
+ },
162
+ }
163
+
164
+ /** Registers the contract suite in the calling test file. Call it once, at the file's top level. */
165
+ export function contractSuite(options: ContractOptions = {}): void {
166
+ // First, before the server's own afterAll: the server's data directory is a scratch directory, removed only after
167
+ // the server has stopped, and this file's own, even under `isolate: false` (./tmp-dir.ts).
168
+ registerTestTmpDirCleanup()
169
+ const optOut = options.optOut ?? {}
170
+ checkOptOut('contractSuite', 'contract', optOut)
171
+ if (options.database !== undefined && !/^[a-z][a-z0-9_]{0,62}$/.test(options.database)) {
172
+ throw new Error(`contractSuite: database "${options.database}" is not an unquoted Postgres identifier`)
173
+ }
174
+
175
+ let server: ContractServer | undefined
176
+ let database: string | undefined
177
+ const context: ContractContext = {
178
+ server: () => server ?? unstarted(),
179
+ database: () => database ?? unstarted(),
180
+ }
181
+
182
+ // Every check opted out: no server to start.
183
+ if (runsAny('contract', optOut)) {
184
+ beforeAll(async () => {
185
+ database = options.database ?? contractDatabaseName((await import('@sssb/app-config/identity')).APP_SLUG)
186
+ server = await startContractServer(database, { port: options.port })
187
+ await server.createDatabase(database)
188
+ }, TIMEOUT_MS)
189
+
190
+ afterAll(async () => {
191
+ await server?.stop()
192
+ })
193
+ }
194
+
195
+ registerChecks({ caller: 'contractSuite', runner: 'contract', implementations: IMPLEMENTATIONS, optOut, context })
196
+ }
197
+
198
+ function unstarted(): never {
199
+ throw new Error('contractSuite: the contract server did not start (see the beforeAll failure above)')
200
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@sssb/kit/testing/e2e` — everything SSSB offers a Playwright spec, and the ONLY way a spec may reach the kit
3
+ * (ADR-0014 part 2).
4
+ *
5
+ * Playwright loads specs with Node, and Node neither strips types under `node_modules` nor resolves the app's
6
+ * `@sssb/app-config/*` seam the way a bundler does. So in the packed package this subpath resolves to compiled
7
+ * JavaScript (`dist/testing/e2e.js` and its `.d.ts`, built by `scripts/build-testing-e2e.mjs` when the package
8
+ * is packed), and everything it reaches must be SEAM-FREE: that build fails if any file in this
9
+ * entry's closure imports `@sssb/app-config/*`, or if the closure grows past the files it allows. Inside this repo
10
+ * the apps' tsconfig `paths` resolve `@sssb/kit/*` to source, so a spec here runs this file through Playwright's
11
+ * own TypeScript transform; the compiled copy is what an adopter's spec loads.
12
+ *
13
+ * Add a name here only if it is seam-free, and add its file to the build's allowed set deliberately.
14
+ */
15
+ export { WEBHOOK_REPLAY_TOLERANCE_MS, verifyWebhookSignature } from '../core/webhook-hmac'
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@sssb/kit/testing`: the conformance suite an app runs from its own tree (`src/sssb.conformance.test.ts`), so the
3
+ * framework's checks hold against the app's own seam (ADR-0014 part 3). The checks it registers are data:
4
+ * `@sssb/kit/testing/checks.json`.
5
+ */
6
+ export { conformanceSuite } from './conformance/suite'
@@ -0,0 +1,22 @@
1
+ {
2
+ "specifiers": [
3
+ "@sssb/app-config/abilities",
4
+ "@sssb/app-config/actors",
5
+ "@sssb/app-config/audit",
6
+ "@sssb/app-config/db/migrations",
7
+ "@sssb/app-config/db/rls-proofs",
8
+ "@sssb/app-config/db/schema",
9
+ "@sssb/app-config/digest",
10
+ "@sssb/app-config/identity",
11
+ "@sssb/app-config/inbound-email",
12
+ "@sssb/app-config/jobs",
13
+ "@sssb/app-config/messages",
14
+ "@sssb/app-config/notifications",
15
+ "@sssb/app-config/preset-operations",
16
+ "@sssb/app-config/presets",
17
+ "@sssb/app-config/seed",
18
+ "@sssb/app-config/simulator",
19
+ "@sssb/app-config/tours",
20
+ "@sssb/app-config/webhooks"
21
+ ]
22
+ }
@@ -0,0 +1,4 @@
1
+ // The marker module is plain .mjs so the leak guard can import it under bare node; this declares it for TypeScript.
2
+ // Installed, the .mjs sits under node_modules, and at its default `maxNodeModuleJsDepth` of 0 TypeScript takes no
3
+ // types from a JavaScript file there, allowJs or not (TS7016), so without this tmp-dir.ts fails from the tarball.
4
+ export declare const TMP_DIR_MARKER_SUFFIX: string
@@ -0,0 +1,5 @@
1
+ // The suffix of the empty sibling file that tmp-dir.ts (beside it) drops next to every scratch
2
+ // directory it creates (`<dir>` + this suffix). The leak guard (`sssb check-tmpdir-leak`, @sssb/tools) reads
3
+ // @sssb/tools' own copy of this constant, since the framework depends on no other SSSB package; tests/tooling/tmp-dir.test.ts
4
+ // holds the two spellings equal. Plain .mjs, so it needs no TypeScript loader.
5
+ export const TMP_DIR_MARKER_SUFFIX = '.sssb-test-tmp'