@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,351 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import {
3
+ BeginTransactionCommand,
4
+ CommitTransactionCommand,
5
+ ExecuteStatementCommand,
6
+ RollbackTransactionCommand,
7
+ type ArrayValue,
8
+ type ColumnMetadata,
9
+ type ExecuteStatementCommandOutput,
10
+ type Field,
11
+ type SqlParameter,
12
+ } from '@aws-sdk/client-rds-data'
13
+ import { Pool, type PoolClient } from 'pg'
14
+ import { isMultistatement, sqlSegments } from './rds-data-codec'
15
+ import type { RdsDataClientLike, RdsDataCommand } from './rds-data-dialect'
16
+
17
+ /**
18
+ * TEST ONLY: the RDS Data API's documented behaviour, emulated over a real Postgres so the contract
19
+ * suite can run SSSB's proofs THROUGH the Data API dialect (./rds-data.contract.test.ts) without AWS,
20
+ * docker or credentials. Nothing in an app or a deployment imports it.
21
+ *
22
+ * It is deliberately STRICT where AWS is strict, because a lenient emulator proves nothing (the popular
23
+ * community emulator types untyped strings as `unknown`, so code that fails on real Aurora passes on it):
24
+ *
25
+ * - an untyped `stringValue` is bound as `varchar`, so `uuid = :p` without a cast or a UUID typeHint
26
+ * fails here exactly as it does on Aurora; typeHints bind as their documented types;
27
+ * - an `arrayValue` parameter is refused ("Array parameters are not supported");
28
+ * - every connection is reset with `DISCARD ALL` before it is reused, so session state never survives
29
+ * between calls outside a transaction (AWS: "Session management with Amazon RDS Data API");
30
+ * - a statement inside a transaction runs on that transaction's one connection, until Commit/Rollback;
31
+ * - a response over 1 MiB is refused, and an unknown transaction id is TransactionNotFoundException;
32
+ * - database errors come back as a message only, WITHOUT a SQLSTATE — the least the Data API is
33
+ * reported to give, so what is proven is that SSSB's error handling survives the worst case.
34
+ *
35
+ * What it cannot know is AWS's exact wire format (column `typeName`s, timestamp strings, error wording).
36
+ * It follows PgJDBC's conventions, which the Data API is built on; the `data-api` cutover row is the live
37
+ * check of the same contract.
38
+ */
39
+ export interface EmulatedCall {
40
+ operation: 'BeginTransaction' | 'ExecuteStatement' | 'CommitTransaction' | 'RollbackTransaction'
41
+ transactionId: string | undefined
42
+ sql?: string
43
+ }
44
+
45
+ const RESPONSE_LIMIT_BYTES = 1024 * 1024
46
+
47
+ export class RdsDataEmulator implements RdsDataClientLike {
48
+ /** Every call, in order — the contract suite asserts on the transaction sequence. */
49
+ readonly calls: EmulatedCall[] = []
50
+
51
+ readonly #pool: Pool
52
+ readonly #database: string
53
+ readonly #transactions = new Map<string, PoolClient>()
54
+ readonly #reset: boolean
55
+ #typeNames: Map<number, string> | undefined
56
+
57
+ /**
58
+ * `resetConnections: false` and `maxConnections: 1` are for ONE kind of test only: proving that state
59
+ * is transaction-local in its own right, which the documented reset would otherwise hide by wiping it
60
+ * anyway. They make the emulator less like AWS, never more lenient about what reaches the database.
61
+ */
62
+ constructor(connectionString: string, options: { resetConnections?: boolean; maxConnections?: number } = {}) {
63
+ this.#database = decodeURIComponent(new URL(connectionString).pathname.replace(/^\//, ''))
64
+ this.#reset = options.resetConnections ?? true
65
+ this.#pool = new Pool({
66
+ connectionString,
67
+ max: options.maxConnections ?? 8,
68
+ // The Data API returns timestamptz in UTC; a UTC session makes Postgres print it that way.
69
+ options: '-c TimeZone=UTC',
70
+ // Raw text for every type: the emulator does its own typing, as the Data API does.
71
+ types: { getTypeParser: () => (value: string) => value },
72
+ })
73
+ // An IDLE pooled connection the server ends is the pool's to drop and replace, as the Data API's own
74
+ // pool does. A test's `DROP DATABASE … WITH (FORCE)`, such as the owner pass's teardown, ends it with
75
+ // 57P01, and with no listener pg-pool's 'error' event fails the whole run as an unhandled error.
76
+ // A connection that is IN USE still fails its statement as before.
77
+ this.#pool.on('error', () => undefined)
78
+ }
79
+
80
+ async send(command: RdsDataCommand): Promise<unknown> {
81
+ if (command instanceof BeginTransactionCommand) {
82
+ this.#checkDatabase(command.input.database)
83
+ const client = await this.#pool.connect()
84
+ await client.query('BEGIN')
85
+ const transactionId = randomUUID()
86
+ this.#transactions.set(transactionId, client)
87
+ this.calls.push({ operation: 'BeginTransaction', transactionId })
88
+ return { transactionId }
89
+ }
90
+ if (command instanceof CommitTransactionCommand || command instanceof RollbackTransactionCommand) {
91
+ const commit = command instanceof CommitTransactionCommand
92
+ const transactionId = command.input.transactionId!
93
+ const client = this.#transactions.get(transactionId)
94
+ this.calls.push({ operation: commit ? 'CommitTransaction' : 'RollbackTransaction', transactionId })
95
+ if (!client) throw awsError('TransactionNotFoundException', `Transaction ${transactionId} is not found`)
96
+ this.#transactions.delete(transactionId)
97
+ let ended
98
+ try {
99
+ ended = await client.query(commit ? 'COMMIT' : 'ROLLBACK')
100
+ } catch (error) {
101
+ // A commit can fail (a deferred constraint); it comes back like any statement's error.
102
+ throw awsError('DatabaseErrorException', `ERROR: ${(error as Error).message}`, error)
103
+ } finally {
104
+ await this.#release(client)
105
+ }
106
+ // Postgres answers COMMIT on an aborted transaction with ROLLBACK; report what actually happened.
107
+ return {
108
+ transactionStatus: commit && ended.command === 'COMMIT' ? 'Transaction Committed' : 'Rollback Complete',
109
+ }
110
+ }
111
+ if (command instanceof ExecuteStatementCommand) return this.#execute(command)
112
+ throw new Error('the emulator handles BeginTransaction, ExecuteStatement, Commit and Rollback only')
113
+ }
114
+
115
+ /** Rolls back anything still open and closes the pool. */
116
+ async close(): Promise<void> {
117
+ for (const client of this.#transactions.values()) {
118
+ await client.query('ROLLBACK').catch(() => undefined)
119
+ client.release()
120
+ }
121
+ this.#transactions.clear()
122
+ await this.#pool.end()
123
+ }
124
+
125
+ async #execute(command: ExecuteStatementCommand): Promise<ExecuteStatementCommandOutput> {
126
+ const input = command.input
127
+ this.#checkDatabase(input.database)
128
+ const sql = input.sql ?? ''
129
+ this.calls.push({ operation: 'ExecuteStatement', transactionId: input.transactionId, sql })
130
+ if (sql.length > 65536) throw awsError('ValidationException', 'sql must be at most 65536 characters')
131
+ // Refused before anything runs. The name and wording are this emulator's; step 4 of
132
+ // docs/runbooks/data-api.md records what AWS sends.
133
+ if (isMultistatement(sql)) throw awsError('ValidationException', "Multistatements aren't supported.")
134
+ if (input.formatRecordsAs === 'JSON') throw new Error('the emulator does not implement formatRecordsAs JSON')
135
+ const parameters = input.parameters ?? []
136
+ if (parameters.some((p) => p.value?.arrayValue !== undefined)) {
137
+ throw awsError('ValidationException', 'Array parameters are not supported')
138
+ }
139
+ const { text, values } = toPositional(sql, parameters)
140
+
141
+ const inTransaction = input.transactionId !== undefined
142
+ let client: PoolClient
143
+ if (inTransaction) {
144
+ const found = this.#transactions.get(input.transactionId!)
145
+ if (!found)
146
+ throw awsError('TransactionNotFoundException', `Transaction ${input.transactionId} is not found`)
147
+ client = found
148
+ } else {
149
+ client = await this.#pool.connect()
150
+ }
151
+
152
+ try {
153
+ const typeNames = await this.#types(client)
154
+ let result
155
+ try {
156
+ result = await client.query({ text, values, rowMode: 'array' })
157
+ } catch (error) {
158
+ // Message only, no SQLSTATE: the worst case the Data API is reported to return.
159
+ throw awsError('DatabaseErrorException', `ERROR: ${(error as Error).message}`, error)
160
+ }
161
+ const longAsString = input.resultSetOptions?.longReturnType === 'STRING'
162
+ const columns: ColumnMetadata[] = result.fields.map((field) => ({
163
+ name: field.name,
164
+ label: field.name,
165
+ type: field.dataTypeID,
166
+ typeName: typeNames.get(field.dataTypeID) ?? 'unknown',
167
+ }))
168
+ const records = (result.rows as (string | null)[][]).map((row) =>
169
+ row.map((raw, i) => encodeField(raw, columns[i]!.typeName!, longAsString)),
170
+ )
171
+ if (Buffer.byteLength(JSON.stringify(records)) > RESPONSE_LIMIT_BYTES) {
172
+ throw awsError('DatabaseErrorException', 'Database returned more than the allowed response size limit')
173
+ }
174
+ const dml = ['INSERT', 'UPDATE', 'DELETE', 'MERGE'].includes(result.command)
175
+ return {
176
+ $metadata: {},
177
+ columnMetadata: input.includeResultMetadata ? columns : undefined,
178
+ records,
179
+ numberOfRecordsUpdated: dml ? (result.rowCount ?? 0) : 0,
180
+ }
181
+ } finally {
182
+ if (!inTransaction) await this.#release(client)
183
+ }
184
+ }
185
+
186
+ /** `DISCARD ALL` before a connection goes back to the pool — the reset AWS documents. */
187
+ async #release(client: PoolClient): Promise<void> {
188
+ try {
189
+ if (this.#reset) await client.query('DISCARD ALL')
190
+ client.release()
191
+ } catch (error) {
192
+ client.release(error as Error)
193
+ }
194
+ }
195
+
196
+ #checkDatabase(database: string | undefined): void {
197
+ if (database !== undefined && database !== this.#database) {
198
+ throw new Error(`emulator serves database "${this.#database}", not "${database}"`)
199
+ }
200
+ }
201
+
202
+ /** `pg_type.typname` by oid, which is what PgJDBC reports as a column's type name (`_text` for text[]). */
203
+ // On the connection already held — with `maxConnections: 1` a second checkout would wait forever.
204
+ async #types(client: PoolClient): Promise<Map<number, string>> {
205
+ if (!this.#typeNames) {
206
+ const { rows } = await client.query<{ oid: string; typname: string }>('SELECT oid, typname FROM pg_type')
207
+ this.#typeNames = new Map(rows.map((row) => [Number(row.oid), row.typname]))
208
+ }
209
+ return this.#typeNames
210
+ }
211
+ }
212
+
213
+ function awsError(name: string, message: string, cause?: unknown): Error {
214
+ const error = new Error(message, { cause })
215
+ error.name = name
216
+ return error
217
+ }
218
+
219
+ /**
220
+ * `:name` placeholders to `$n`, in code only — not in strings, E-strings, quoted identifiers, nested
221
+ * comments or dollar quotes, by the dialect's own scanner (`sqlSegments`), so the two cannot disagree —
222
+ * and never the second colon of a `::` cast. Each is bound the way the Data API binds it: an untyped
223
+ * string as `varchar`, a typeHint as its type, a long as `int8` — which is what makes a missing cast fail
224
+ * here.
225
+ */
226
+ function toPositional(sql: string, parameters: readonly SqlParameter[]): { text: string; values: unknown[] } {
227
+ const byName = new Map(parameters.map((p) => [p.name, p]))
228
+ const order: string[] = []
229
+ const bind = (_: string, name: string): string => {
230
+ const parameter = byName.get(name)
231
+ if (!parameter) throw awsError('ValidationException', `No value specified for parameter ${name}`)
232
+ let index = order.indexOf(name)
233
+ if (index === -1) index = order.push(name) - 1
234
+ return `($${index + 1}${bindType(parameter)})`
235
+ }
236
+ const text = sqlSegments(sql)
237
+ .map((segment) =>
238
+ segment.code ? segment.text.replace(/(?<!:):([A-Za-z_][A-Za-z0-9_]*)/g, bind) : segment.text,
239
+ )
240
+ .join('')
241
+ const values = order.map((name) => bindValue(byName.get(name)!))
242
+ return { text, values }
243
+ }
244
+
245
+ /** A `Field` read member by member — the SDK types it as a union, one member per kind of value. */
246
+ type FieldShape = {
247
+ isNull?: boolean
248
+ stringValue?: string
249
+ longValue?: number
250
+ doubleValue?: number
251
+ booleanValue?: boolean
252
+ blobValue?: Uint8Array
253
+ }
254
+
255
+ const TYPE_HINTS: Record<string, string> = {
256
+ UUID: '::uuid',
257
+ JSON: '::json',
258
+ TIMESTAMP: '::timestamp',
259
+ DATE: '::date',
260
+ TIME: '::time',
261
+ DECIMAL: '::numeric',
262
+ }
263
+
264
+ function bindType(parameter: SqlParameter): string {
265
+ const value: FieldShape = parameter.value ?? {}
266
+ if (value.isNull) return ''
267
+ if (value.stringValue !== undefined)
268
+ return parameter.typeHint ? (TYPE_HINTS[parameter.typeHint] ?? '') : '::varchar'
269
+ if (value.longValue !== undefined) return '::int8'
270
+ if (value.doubleValue !== undefined) return '::float8'
271
+ if (value.booleanValue !== undefined) return '::bool'
272
+ if (value.blobValue !== undefined) return '::bytea'
273
+ return ''
274
+ }
275
+
276
+ function bindValue(parameter: SqlParameter): unknown {
277
+ const value: FieldShape = parameter.value ?? {}
278
+ if (value.isNull) return null
279
+ if (value.blobValue !== undefined) return Buffer.from(value.blobValue)
280
+ return value.stringValue ?? value.longValue ?? value.doubleValue ?? value.booleanValue ?? null
281
+ }
282
+
283
+ const LONG_TYPES = new Set(['int2', 'int4', 'int8', 'oid'])
284
+ const DOUBLE_TYPES = new Set(['float4', 'float8'])
285
+
286
+ function encodeField(raw: string | null, typeName: string, longAsString: boolean): Field {
287
+ if (raw === null) return { isNull: true }
288
+ if (typeName.startsWith('_'))
289
+ return { arrayValue: encodeArray(parseArrayLiteral(raw), typeName.slice(1), longAsString) }
290
+ if (LONG_TYPES.has(typeName)) return longAsString ? { stringValue: raw } : { longValue: Number(raw) }
291
+ if (DOUBLE_TYPES.has(typeName)) return { doubleValue: Number(raw) }
292
+ if (typeName === 'bool') return { booleanValue: raw === 't' }
293
+ if (typeName === 'bytea') return { blobValue: Buffer.from(raw.replace(/^\\x/, ''), 'hex') }
294
+ if (typeName === 'timestamptz') return { stringValue: utcTimestamp(raw) }
295
+ return { stringValue: raw }
296
+ }
297
+
298
+ /** `2026-11-16 23:00:00.123+00` -> `2026-11-16 23:00:00.123`: UTC wall-clock time, as AWS documents. */
299
+ function utcTimestamp(raw: string): string {
300
+ return raw.replace(/\+00(?::?00)?$/, '')
301
+ }
302
+
303
+ type Nested = (string | null | Nested)[]
304
+
305
+ function encodeArray(items: Nested, baseType: string, longAsString: boolean): ArrayValue {
306
+ if (items.some((item) => Array.isArray(item))) {
307
+ return { arrayValues: items.map((item) => encodeArray((item ?? []) as Nested, baseType, longAsString)) }
308
+ }
309
+ const flat = items as (string | null)[]
310
+ if (LONG_TYPES.has(baseType) && !longAsString)
311
+ return { longValues: flat.map((v) => (v === null ? null : Number(v))) as number[] }
312
+ if (DOUBLE_TYPES.has(baseType))
313
+ return { doubleValues: flat.map((v) => (v === null ? null : Number(v))) as number[] }
314
+ if (baseType === 'bool') return { booleanValues: flat.map((v) => (v === null ? null : v === 't')) as boolean[] }
315
+ const strings = baseType === 'timestamptz' ? flat.map((v) => (v === null ? null : utcTimestamp(v))) : flat
316
+ return { stringValues: strings as string[] }
317
+ }
318
+
319
+ /** Postgres's array output (`{a,"b c",NULL,{1,2}}`) to nested arrays of strings and nulls. */
320
+ function parseArrayLiteral(text: string): Nested {
321
+ let i = 0
322
+ const parse = (): Nested => {
323
+ const out: Nested = []
324
+ i += 1 // `{`
325
+ while (i < text.length && text[i] !== '}') {
326
+ if (text[i] === ',') {
327
+ i += 1
328
+ } else if (text[i] === '{') {
329
+ out.push(parse())
330
+ } else if (text[i] === '"') {
331
+ let value = ''
332
+ i += 1
333
+ while (text[i] !== '"') {
334
+ if (text[i] === '\\') i += 1
335
+ value += text[i]
336
+ i += 1
337
+ }
338
+ i += 1
339
+ out.push(value)
340
+ } else {
341
+ let value = ''
342
+ while (text[i] !== ',' && text[i] !== '}') value += text[i++]
343
+ out.push(value === 'NULL' ? null : value)
344
+ }
345
+ }
346
+ i += 1 // `}`
347
+ return out
348
+ }
349
+ // A lower-bound decoration (`[0:1]={…}`) only appears for non-default bounds; SSSB never writes one.
350
+ return parse()
351
+ }
@@ -0,0 +1,233 @@
1
+ import {
2
+ CopyObjectCommand,
3
+ DeleteObjectsCommand,
4
+ GetObjectCommand,
5
+ HeadObjectCommand,
6
+ ListObjectsV2Command,
7
+ PutObjectCommand,
8
+ S3Client,
9
+ type S3ClientConfig,
10
+ } from '@aws-sdk/client-s3'
11
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
12
+ import { createPresignedPost } from '@aws-sdk/s3-presigned-post'
13
+ import { NotFoundError, PreconditionFailedError } from '../../ports/errors'
14
+ import type { CopyOptions, StoragePort, StoredObject, StoredObjectInfo } from '../../ports/storage'
15
+
16
+ /** S3's hard cap on keys in one DeleteObjects request. */
17
+ const DELETE_BATCH_SIZE = 1000
18
+
19
+ /**
20
+ * `CopySource` for an object in `bucket`: `<bucket>/<key>`, with each key SEGMENT percent-encoded and the
21
+ * slashes between them left alone (the shape AWS documents: `awsexamplebucket/reports/january.pdf`). The
22
+ * SDK sends the string as given and AWS says "The value must be URL-encoded", so a `?` left in a key would
23
+ * start the `?versionId=` suffix AWS documents and a `%` would start an escape; a `+` is ambiguous in URL
24
+ * decoding, so it is encoded too. The bucket is always the adapter's own, so a key can
25
+ * never name another bucket: `other-bucket/x` is the key `other-bucket/x` of THIS one.
26
+ */
27
+ function copySourceFor(bucket: string, key: string): string {
28
+ return `${bucket}/${key.split('/').map(encodeURIComponent).join('/')}`
29
+ }
30
+
31
+ /**
32
+ * Where the adapter's bucket is, and how it reaches it. Only `bucket` is required: with the rest left out, the
33
+ * S3 client finds its region and credentials the AWS SDK's own way (environment, profile, the Lambda's role).
34
+ */
35
+ export interface S3StorageOptions {
36
+ /** The bucket every key lives in. A key never names another bucket. */
37
+ bucket: string
38
+ /** The bucket's region. */
39
+ region?: string | undefined
40
+ /** An S3-compatible endpoint other than AWS's (a local stand-in, another provider), as a URL. */
41
+ endpoint?: string | undefined
42
+ /** Credentials, or a provider of them, in place of the SDK's own lookup. */
43
+ credentials?: S3ClientConfig['credentials'] | undefined
44
+ /** Address the bucket in the path (`https://host/bucket/key`), as most S3-compatible endpoints need. */
45
+ forcePathStyle?: boolean | undefined
46
+ /**
47
+ * A client the caller built, used as it is: for a client shared with other code, or one a test controls.
48
+ * Given with any of `region`, `endpoint`, `credentials` or `forcePathStyle`, it is refused, since those would be
49
+ * silently ignored.
50
+ */
51
+ client?: S3Client | undefined
52
+ }
53
+
54
+ /**
55
+ * SSSB's storage port on a real S3 bucket (or an S3-compatible endpoint): the adapter SSSB's own registry uses in
56
+ * real mode, published so an app that needs storage outside the registry (a simulated app run against a real
57
+ * bucket, say) uses this one rather than a copy that drifts. The port contract is `@sssb/kit/ports/storage`'s.
58
+ *
59
+ * AUTHORED — CUTOVER (`cloud-accounts`; `list` and `delete` also `storage-list-delete`, `copy` also
60
+ * `storage-copy`): typechecked, never run against a real bucket by SSSB's own tests.
61
+ */
62
+ export function createS3Storage(options: S3StorageOptions): StoragePort {
63
+ const { bucket, client: given, ...config } = options
64
+ if (!bucket) throw new Error('createS3Storage: bucket is required')
65
+ const configured = Object.entries(config).filter(([, value]) => value !== undefined)
66
+ if (given && configured.length > 0) {
67
+ throw new Error(
68
+ `createS3Storage: a client was given, so ${configured.map(([name]) => name).join(', ')} would be ignored; ` +
69
+ 'configure the client instead',
70
+ )
71
+ }
72
+ const client = given ?? new S3Client(Object.fromEntries(configured) as S3ClientConfig)
73
+
74
+ return {
75
+ async put(key, body, contentType) {
76
+ await client.send(new PutObjectCommand({ Bucket: bucket, Key: key, Body: body, ContentType: contentType }))
77
+ },
78
+
79
+ async get(key): Promise<StoredObject | null> {
80
+ try {
81
+ const result = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
82
+ const body = await result.Body!.transformToByteArray()
83
+ return { body, contentType: result.ContentType ?? 'application/octet-stream' }
84
+ } catch (error) {
85
+ if ((error as { name?: string }).name === 'NoSuchKey') return null
86
+ throw error
87
+ }
88
+ },
89
+
90
+ async head(key): Promise<StoredObjectInfo | null> {
91
+ let result
92
+ try {
93
+ result = await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
94
+ } catch (error) {
95
+ // `NotFound` is the SDK's error for a HEAD 404, which has no body to say which of key and bucket
96
+ // is missing (AWS: "It's not possible to retrieve the exact exception"), so a missing bucket reads
97
+ // as null too. `NoSuchKey` for a stub or a future SDK that does say. A 403 (no `s3:ListBucket`)
98
+ // and everything else are not a missing object and reach the caller as they came.
99
+ const { name } = error as { name?: string }
100
+ if (name === 'NotFound' || name === 'NoSuchKey') return null
101
+ throw error
102
+ }
103
+ // A size of 0 or an invented date would let a caller's check pass on something S3 never said.
104
+ const { ContentLength, ContentType, ETag, LastModified } = result
105
+ if (ContentLength === undefined || ETag === undefined || LastModified === undefined) {
106
+ throw new Error(`storage head: S3 answered for ${key} without a ContentLength, ETag and LastModified`)
107
+ }
108
+ return {
109
+ size: ContentLength,
110
+ contentType: ContentType ?? 'application/octet-stream',
111
+ etag: ETag,
112
+ lastModified: LastModified,
113
+ }
114
+ },
115
+
116
+ async getSignedDownloadUrl(key, expiresInSeconds = 900): Promise<string> {
117
+ // Force attachment disposition so user-uploaded content (whose Content-Type the uploader
118
+ // declared) can never render inline on the bucket/CDN origin — the stored-XSS defense the
119
+ // fake download route applies with nosniff+attachment. Keep the two paths in parity.
120
+ return getSignedUrl(
121
+ client,
122
+ new GetObjectCommand({
123
+ Bucket: bucket,
124
+ Key: key,
125
+ ResponseContentDisposition: 'attachment',
126
+ }),
127
+ { expiresIn: expiresInSeconds },
128
+ )
129
+ },
130
+
131
+ async list(prefix) {
132
+ const keys: string[] = []
133
+ let continuationToken: string | undefined
134
+ do {
135
+ const page = await client.send(
136
+ new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken: continuationToken }),
137
+ )
138
+ for (const object of page.Contents ?? []) if (object.Key !== undefined) keys.push(object.Key)
139
+ continuationToken = page.IsTruncated ? page.NextContinuationToken : undefined
140
+ } while (continuationToken)
141
+ return keys.sort()
142
+ },
143
+
144
+ async delete(keys) {
145
+ for (let start = 0; start < keys.length; start += DELETE_BATCH_SIZE) {
146
+ const batch = keys.slice(start, start + DELETE_BATCH_SIZE)
147
+ // Quiet: S3 answers with failures only, so a clean batch has no `Errors` to read. A
148
+ // missing key is not a failure (S3 reports it as deleted), which is the idempotency we promise.
149
+ const result = await client.send(
150
+ new DeleteObjectsCommand({
151
+ Bucket: bucket,
152
+ Delete: { Objects: batch.map((Key) => ({ Key })), Quiet: true },
153
+ }),
154
+ )
155
+ const failed = result.Errors?.[0]
156
+ if (failed) {
157
+ throw new Error(`storage delete failed for ${failed.Key}: ${failed.Code} ${failed.Message}`)
158
+ }
159
+ }
160
+ },
161
+
162
+ async copy(from, to, options?: CopyOptions) {
163
+ // HTTP gives an empty If-Match no meaning and `*` the meaning "any version", so S3 could read either as
164
+ // "no condition" and copy unchecked, where the fake would refuse. No etag `head` returns is either.
165
+ if (options?.ifMatch !== undefined && (options.ifMatch.trim() === '' || options.ifMatch.trim() === '*')) {
166
+ throw new Error('storage copy: ifMatch must be the etag head returned, not empty and not "*"')
167
+ }
168
+ // A copy onto itself changes nothing, and is nearly always two keys built the same way by mistake:
169
+ // refuse it before spending a request, with the same error the fake gives.
170
+ if (from === to) throw new Error(`storage copy: source and destination are the same key: ${from}`)
171
+ try {
172
+ // One server-side CopyObject: the bytes never leave S3. `MetadataDirective: 'COPY'` carries the
173
+ // content type and user metadata over (naming a ContentType here would be ignored under COPY).
174
+ // An existing `to` is overwritten, as `put` does. If S3 answers 200 with an error in the body,
175
+ // the SDK's own middleware turns that into a thrown error, so this never reports a false success.
176
+ await client.send(
177
+ new CopyObjectCommand({
178
+ Bucket: bucket,
179
+ Key: to,
180
+ CopySource: copySourceFor(bucket, from),
181
+ MetadataDirective: 'COPY',
182
+ // Only when asked for: S3 then copies only if the source's ETag is this one. The value
183
+ // is exactly what `head` returned (an opaque string, quotes and all), never rebuilt.
184
+ ...(options?.ifMatch !== undefined ? { CopySourceIfMatch: options.ifMatch } : {}),
185
+ }),
186
+ )
187
+ } catch (error) {
188
+ const { name, message, $metadata } = error as {
189
+ name?: string
190
+ message?: string
191
+ $metadata?: { httpStatusCode?: number }
192
+ }
193
+ // The source is no longer the version `ifMatch` names: S3's 412. (The CopyObject reference gives
194
+ // 412 for its other conditional headers and no code for this one, which is HTTP's rule for a
195
+ // failed If-Match; the cutover row asks to confirm it.) Nothing was copied.
196
+ if (name === 'PreconditionFailed' || $metadata?.httpStatusCode === 412) {
197
+ throw new PreconditionFailedError(
198
+ `storage copy: ${from} is no longer the version ${options?.ifMatch ?? '(none given)'}; nothing was copied`,
199
+ )
200
+ }
201
+ // A missing SOURCE. (A missing bucket is NoSuchBucket, a misconfiguration, and is not mapped.)
202
+ if (name === 'NoSuchKey') throw new NotFoundError(`storage object not found: ${from}`)
203
+ // One CopyObject copies at most 5 GB (AWS's CopyObject reference; UploadPartCopy is the route
204
+ // above it). Say so rather than relay S3's wording.
205
+ if (name === 'InvalidRequest' && /larger than the maximum allowable size/i.test(message ?? '')) {
206
+ throw new Error(
207
+ `storage copy: ${from} is over the 5 GB one CopyObject call can copy (multipart copy is not implemented)`,
208
+ { cause: error },
209
+ )
210
+ }
211
+ throw error
212
+ }
213
+ },
214
+
215
+ async createUploadTarget(key, { contentType, maxBytes }) {
216
+ // A presigned POST the browser uploads to directly. The Conditions ARE the security policy:
217
+ // the object lands at exactly `key` (server-built — never client-chosen), its declared
218
+ // Content-Type must equal `contentType`, and its size must fall within [0, maxBytes]. AWS
219
+ // rejects any POST that violates them (403/400) before a byte is stored.
220
+ const { url, fields } = await createPresignedPost(client, {
221
+ Bucket: bucket,
222
+ Key: key,
223
+ Conditions: [
224
+ ['content-length-range', 0, maxBytes],
225
+ ['eq', '$Content-Type', contentType],
226
+ ],
227
+ Fields: { 'Content-Type': contentType },
228
+ Expires: 900,
229
+ })
230
+ return { url, fields }
231
+ },
232
+ }
233
+ }
@@ -0,0 +1,59 @@
1
+ 'use client'
2
+
3
+ import { useSignIn } from '@clerk/nextjs'
4
+ import { Button, PasswordInput, Stack, Text, TextInput } from '@mantine/core'
5
+ import { useForm } from '@mantine/form'
6
+ import { useState } from 'react'
7
+
8
+ /**
9
+ * Clerk-headless credential form (ADR-0003) using @clerk/nextjs v7's signals API
10
+ * (signIn.password → status → finalize). MFA verification (status 'needs_second_factor') is a
11
+ * documented follow-up slice — see ADR-0003's MFA rider seam.
12
+ *
13
+ * AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance.
14
+ * Lives in packages/kit/src/adapters because it imports the vendor SDK; the SignInScreen renders it as a slot.
15
+ */
16
+ export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; returnTo: string }) {
17
+ const { signIn, fetchStatus } = useSignIn()
18
+ const [formError, setFormError] = useState<string | null>(null)
19
+ const form = useForm({ initialValues: { email: '', password: '' } })
20
+
21
+ const submit = form.onSubmit(async (values) => {
22
+ setFormError(null)
23
+ const { error } = await signIn.password({ identifier: values.email, password: values.password })
24
+ if (error) {
25
+ setFormError(labels.genericError)
26
+ return
27
+ }
28
+ if (signIn.status === 'complete') {
29
+ const finalized = await signIn.finalize()
30
+ if (finalized.error) setFormError(labels.genericError)
31
+ else window.location.assign(returnTo)
32
+ } else if (signIn.status === 'needs_second_factor') {
33
+ setFormError(labels.mfaNotImplemented)
34
+ } else {
35
+ setFormError(labels.genericError)
36
+ }
37
+ })
38
+
39
+ return (
40
+ <form onSubmit={submit}>
41
+ <Stack>
42
+ <TextInput label={labels.email} type="email" required {...form.getInputProps('email')} />
43
+ <PasswordInput label={labels.password} required {...form.getInputProps('password')} />
44
+ <Button type="submit" loading={fetchStatus === 'fetching'}>
45
+ {labels.submit}
46
+ </Button>
47
+ {formError ? <Text c="red.8">{formError}</Text> : null}
48
+ </Stack>
49
+ </form>
50
+ )
51
+ }
52
+
53
+ export interface SignInLabels {
54
+ email: string
55
+ password: string
56
+ submit: string
57
+ genericError: string
58
+ mfaNotImplemented: string
59
+ }
@@ -0,0 +1,10 @@
1
+ import type { StoragePort } from '../../ports/storage'
2
+ import { createS3Storage } from './s3-storage'
3
+
4
+ /**
5
+ * The storage the real-mode registry builds (`./index.ts`): the published S3 adapter (`./s3-storage.ts`,
6
+ * `@sssb/kit/adapters/real/s3-storage`) on the deployment's bucket and region.
7
+ */
8
+ export function createRealStorage(bucket: string, region: string): StoragePort {
9
+ return createS3Storage({ bucket, region })
10
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The run mode, read once. Everything imports it from the registry (./index.ts), which re-exports it; this module
3
+ * exists so code that must not load the registry (the request proxy, ./proxy.ts; the digest job handler,
4
+ * ../jobs/digest-email.ts, which the registry itself loads) can ask the mode without its ports and their fakes.
5
+ *
6
+ * `APP_MODE` only ever tests for `'real'`, so an older `APP_MODE=fake` still resolves to `simulated`
7
+ * and no deployed config breaks.
8
+ */
9
+ export type AppMode = 'simulated' | 'real'
10
+ export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
11
+ export const isSimulated = appMode === 'simulated'