@sssb/kit 0.2.0 → 0.4.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 (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +4 -1
  3. package/src/adapters/fake/auth.ts +18 -6
  4. package/src/adapters/fake/db.ts +4 -2
  5. package/src/adapters/fake/jobs.ts +17 -39
  6. package/src/adapters/fake/simulator.ts +2 -3
  7. package/src/adapters/index.ts +33 -6
  8. package/src/adapters/lazy-jobs.ts +25 -0
  9. package/src/adapters/proxy.ts +34 -0
  10. package/src/adapters/real/absent.ts +54 -0
  11. package/src/adapters/real/accept-invite-form.tsx +62 -15
  12. package/src/adapters/real/analytics.ts +1 -1
  13. package/src/adapters/real/auth.ts +28 -2
  14. package/src/adapters/real/clerk-proxy.ts +111 -0
  15. package/src/adapters/real/db-data-api.ts +1 -1
  16. package/src/adapters/real/db-port.ts +27 -0
  17. package/src/adapters/real/db.ts +2 -21
  18. package/src/adapters/real/index.ts +117 -30
  19. package/src/adapters/real/jobs-in-process.ts +118 -0
  20. package/src/adapters/real/jobs.ts +2 -1
  21. package/src/adapters/real/no-analytics.ts +17 -0
  22. package/src/adapters/real/optional-ports.ts +112 -0
  23. package/src/adapters/real/s3-storage.ts +7 -1
  24. package/src/adapters/real/storage-settings.ts +37 -0
  25. package/src/adapters/real/storage.ts +65 -0
  26. package/src/adapters/run-mode.ts +11 -0
  27. package/src/components/app-header.tsx +1 -1
  28. package/src/components/simulator/simulator-host.tsx +335 -0
  29. package/src/components/simulator/simulator-panel.tsx +45 -57
  30. package/src/core/abilities.ts +6 -1
  31. package/src/core/same-origin-path.ts +20 -0
  32. package/src/cutover/rows.json +13 -1
  33. package/src/db/audit.ts +2 -2
  34. package/src/db/family-suite.ts +42 -0
  35. package/src/db/family.ts +91 -0
  36. package/src/db/jobs.ts +4 -3
  37. package/src/db/keyset.ts +12 -25
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/notifications.ts +2 -2
  40. package/src/db/org-lookup.ts +1 -1
  41. package/src/db/rls-proof-runner.ts +3 -2
  42. package/src/db/schedules.ts +2 -1
  43. package/src/db/webhooks.ts +4 -4
  44. package/src/demo-static/world.ts +5 -4
  45. package/src/guide.md +23 -4
  46. package/src/jobs/digest-email.ts +32 -17
  47. package/src/jobs/run-in-process.ts +82 -0
  48. package/src/observability/scrub.ts +3 -1
  49. package/src/ports/auth.ts +21 -2
  50. package/src/ports/db.ts +19 -0
  51. package/src/ports/jobs.ts +25 -4
  52. package/src/server-lib/defer.ts +4 -0
  53. package/src/server-lib/invite.ts +34 -26
  54. package/src/server-lib/scheduled-tick.ts +13 -3
  55. package/src/server-lib/simulator-api.ts +311 -0
  56. package/src/service-auth/credential.ts +20 -0
  57. package/src/service-auth/mailgun.ts +2 -2
  58. package/src/service-auth/verify.ts +10 -3
  59. package/src/service-auth/webhook.ts +14 -5
  60. package/src/testing/checks.json +9 -0
  61. package/src/testing/conformance/auth-provider.ts +296 -0
  62. package/src/testing/conformance/db.ts +6 -5
  63. package/src/testing/conformance/suite.ts +2 -0
  64. package/src/testing/contract.ts +6 -4
@@ -0,0 +1,20 @@
1
+ const BASE = 'http://same-origin.invalid'
2
+
3
+ /**
4
+ * `value` as a path on the current origin (path, query and fragment, normalised), or null when a browser given it
5
+ * would leave the origin, run a script, or land on a path that reads as another origin.
6
+ *
7
+ * The Simulator navigates to strings it does not write: a remembered `lastPath` (recorded from a page-view beacon's
8
+ * body), a link in a caught email. A prefix check is not enough, because a browser reads `/\host` as `//host`, drops a
9
+ * tab or newline anywhere (`/<tab>/host` is `//host`), and resolves dot segments (`/.//host` is the path `//host`,
10
+ * which a later relative use turns into another origin). So the string must start with one `/`, hold no control
11
+ * character, and no backslash or whitespace in its path (the query and fragment may: they cannot change the origin),
12
+ * resolve against a fixed origin to that same origin, and resolve to a path that does not itself start with `//`.
13
+ * What it returns is the parser's serialisation, never the input.
14
+ */
15
+ export function sameOriginPath(value: unknown): string | null {
16
+ if (typeof value !== 'string' || !/^\/(?![/\\])[^\s\\\p{Cc}?#]*(?:[?#][^\p{Cc}]*)?$/u.test(value)) return null
17
+ const url = new URL(value, BASE)
18
+ if (url.origin !== BASE || url.pathname.startsWith('//')) return null
19
+ return url.pathname + url.search + url.hash
20
+ }
@@ -30,7 +30,7 @@
30
30
  },
31
31
  {
32
32
  "id": "db-role-not-superuser",
33
- "what": "The role in `DATABASE_URL` holds neither `SUPERUSER` nor `BYPASSRLS`"
33
+ "what": "The role the app connects as (the one in `DATABASE_URL` on `pg`, the one the secret at `DATABASE_SECRET_ARN` holds on `data-api`) holds neither `SUPERUSER` nor `BYPASSRLS`"
34
34
  },
35
35
  {
36
36
  "id": "origin-not-publicly-reachable",
@@ -64,6 +64,18 @@
64
64
  "id": "storage-head",
65
65
  "what": "The storage port's `head`, and `copy`'s `ifMatch`, against the real bucket"
66
66
  },
67
+ {
68
+ "id": "storage-compatible-store",
69
+ "what": "An S3-compatible store's bucket, endpoint, region and upload-target setting (`params.ports.storage: 's3-compatible'`, so `STORAGE_PROVIDER=s3-compatible`: Cloudflare R2, MinIO, Backblaze B2)"
70
+ },
71
+ {
72
+ "id": "storage-compatible-credentials",
73
+ "what": "The access key pair for an S3-compatible store (`STORAGE_ACCESS_KEY_ID`, `STORAGE_SECRET_ACCESS_KEY`), in the deployment's secret store and never in the repository"
74
+ },
75
+ {
76
+ "id": "storage-compatible-live",
77
+ "what": "The storage port's methods against a real bucket on the S3-compatible store the app chose (for R2: a real R2 bucket)"
78
+ },
67
79
  {
68
80
  "id": "job-runner",
69
81
  "what": "Async job compute + the shared webhook secret"
package/src/db/audit.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { AppAuditAction } from '@sssb/app-config/audit'
2
2
  import { type Actor, type Credential, principalIdOf, type SubjectType } from '../core/abilities'
3
3
  import type { DbPort } from '../ports/db'
4
- import { jsonb } from './jsonb'
4
+ import { family } from './family'
5
5
 
6
6
  /**
7
7
  * The FRAMEWORK's audit-action vocabulary. The app's own verbs register through the seam
@@ -338,7 +338,7 @@ export async function recordAuditEvent(db: DbPort, input: AuditEventInput): Prom
338
338
  credential_id: input.credential?.id ?? null,
339
339
  // Undefined means the column default, the database's `now()`: what a real adapter gets.
340
340
  at: db.now?.().toISOString(),
341
- detail: detail === null ? null : jsonb(detail),
341
+ detail: detail === null ? null : family.json(detail),
342
342
  })
343
343
  .execute(),
344
344
  )
@@ -0,0 +1,42 @@
1
+ import type { Kysely } from 'kysely'
2
+ import type { Migration } from 'kysely/migration'
3
+ // TYPE-ONLY (erased): the proof runner reads the app's seam, and only the loader below may bring it in.
4
+ import type { runRlsProofs } from './rls-proof-runner'
5
+ import type { DB } from './schema'
6
+
7
+ /**
8
+ * The SUITE half of the database family (the runtime half, and what a family is, are `./family.ts`): what the
9
+ * conformance suite (`../testing/conformance/db.ts`) and the contract runner (`../testing/contract.ts`) load to migrate
10
+ * a database and prove its isolation. Nothing on the request path imports it, so the proofs, the app's among them,
11
+ * never enter a server build.
12
+ *
13
+ * Every member is a LOADER, not a value. The migration registry composes the app's migrations and the proof runner the
14
+ * app's proofs, both through `@sssb/app-config/*`, and collecting a test must not reach the seam: the suites import
15
+ * this module when they are collected, and it imports nothing at all until a loader runs.
16
+ *
17
+ * The proofs are in two halves: the framework's (`./rls-proofs.ts`, `./rls-coverage.ts`, `./owner-pass.ts`, composed
18
+ * by `./rls-proof-runner.ts`) and the app's (`src/app-config/db/rls-proofs.ts`, through the seam), which belongs to
19
+ * the app's family too: it switches roles and sets the tenant the way this family's scope does, so an app on another
20
+ * database writes its proofs for that database.
21
+ */
22
+ export interface DbFamilySuite {
23
+ /** Loads the framework's migrations, and the registry composing them with the app's. */
24
+ migrations(): Promise<{
25
+ frameworkMigrations: Record<string, Migration>
26
+ migrations: Record<string, Migration>
27
+ }>
28
+ /** Loads the migrator, which applies the composed registry (or any registry it is given). */
29
+ migrator(): Promise<{
30
+ migrateToLatest(db: Kysely<DB>): Promise<void>
31
+ migrateRegistryToLatest(db: Kysely<DB>, registry: Record<string, Migration>): Promise<void>
32
+ }>
33
+ /** Loads the isolation proof suite: the framework's proofs and the app's, as one run. */
34
+ proofs(): Promise<{ runRlsProofs: typeof runRlsProofs }>
35
+ }
36
+
37
+ /** The Postgres family's suite half, for the family `./family.ts` runs on. */
38
+ export const familySuite: DbFamilySuite = {
39
+ migrations: () => import('./migrations/index'),
40
+ migrator: () => import('./migrate'),
41
+ proofs: () => import('./rls-proof-runner'),
42
+ }
@@ -0,0 +1,91 @@
1
+ import { type Kysely, type RawBuilder, type SelectQueryBuilder, sql, type SqlBool, type Transaction } from 'kysely'
2
+ import type { KeysetPosition } from '../core/keyset'
3
+ import type { DbIsolation } from '../ports/db'
4
+ import { jsonb } from './jsonb'
5
+ import type { DB } from './schema'
6
+ import { runWithTenant } from './with-tenant'
7
+
8
+ /**
9
+ * The database family (ADR-0015, second addendum, point 3): what is specific to one database engine, gathered behind
10
+ * one object so the framework's logic stays generic over the engine. SSSB has one family today, Postgres, with three
11
+ * transports (pglite, node-postgres, the RDS Data API); a second family (libsql, `.claude/future-tasks/db-libsql-family.md`)
12
+ * is a second object of this shape, not a fork of the data layer.
13
+ *
14
+ * A family owns:
15
+ *
16
+ * - its DIALECT HELPERS, the few places the framework's runtime logic needs engine SQL: encoding a JSON value, locking
17
+ * a row for the rest of the transaction, the database's own clock, and the keyset ordering. The framework's data
18
+ * modules (`./jobs.ts`, `./schedules.ts`, `./webhooks.ts`, `./audit.ts`, `./notifications.ts`, `./keyset.ts`) call
19
+ * these and write no engine SQL of their own; `tests/lint/db-family-fence.test.ts` holds them to it;
20
+ * - its ISOLATION, the guarantee every one of its transports declares as `DbPort.isolation`;
21
+ * - its TENANT SCOPE, the mechanism behind `DbPort.withTenant` that every one of its transports runs;
22
+ * - its MIGRATIONS (`./migrations/`) and its MIGRATOR (`./migrate.ts`), which reads the engine's own bookkeeping;
23
+ * - its ISOLATION PROOFS, the framework's half and the app's (`./family-suite.ts` says what each is, and why the
24
+ * app's belongs to its family too);
25
+ * - its catalog-reading tooling (`./app-roles.ts`, the conformance suite's schema reads, the contract server).
26
+ *
27
+ * The family comes in two halves, by who imports them. This module is the RUNTIME half: the data modules and the
28
+ * transports import it on the request path, so it imports nothing but Kysely, `./jsonb` and `./with-tenant`, statically
29
+ * or by `import()`: a bundler follows a literal `import()` into the server build. The SUITE half, `./family-suite.ts`,
30
+ * loads the migrations, the migrator and the proofs for the conformance suite and the contract runner.
31
+ *
32
+ * Today's modules are referenced where they stand, not moved: docs cite them by path.
33
+ *
34
+ * Choosing a family from the app's declaration comes with the second family. Until then `family` is Postgres.
35
+ */
36
+ export interface DbFamily {
37
+ readonly name: string
38
+ /** What its transports declare as `DbPort.isolation`: how the database keeps one tenant from another. */
39
+ readonly isolation: DbIsolation
40
+ /** A JSON value as a column parameter (`jsonb` in Postgres), safe for an array as well as an object. */
41
+ json<T>(value: T): RawBuilder<T>
42
+ /** The selected rows, locked for the rest of the transaction (`FOR UPDATE` in Postgres). Use with `$call`. */
43
+ lockRow<D, TB extends keyof D, O>(query: SelectQueryBuilder<D, TB, O>): SelectQueryBuilder<D, TB, O>
44
+ /** The database's own clock, as a value to write (`now()` in Postgres: the transaction's start). */
45
+ currentTime(): RawBuilder<string>
46
+ /**
47
+ * One page of a keyset read: `query`'s rows after `after` (or the first page), newest first by `orderColumn` then
48
+ * `id`, at most `take` of them, each with `keyset_at`, the ordering instant as an ISO-8601 UTC string to the
49
+ * microsecond (the cursor's `at`). `./keyset.ts` owns the paging itself: the clamp, the probe row, the cursor.
50
+ */
51
+ keysetSlice<TB extends keyof DB, O>(
52
+ query: SelectQueryBuilder<DB, TB, O>,
53
+ page: { orderColumn: string; after: KeysetPosition | null; take: number },
54
+ ): SelectQueryBuilder<DB, TB, O & { keyset_at: string }>
55
+ /** The tenant scope every transport's `withTenant` runs: `fn` inside one transaction scoped to `tenantId`. */
56
+ runWithTenant<T>(db: Kysely<DB>, tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T>
57
+ }
58
+
59
+ const postgresFamily: DbFamily = {
60
+ name: 'postgres',
61
+ // Row-level security: every tenant table's policy compares `tenant_id` with the transaction's tenant setting,
62
+ // under a role that cannot bypass it (ADR-0004).
63
+ isolation: 'rls',
64
+ json: jsonb,
65
+ lockRow: (query) => query.forUpdate(),
66
+ currentTime: () => sql<string>`now()`,
67
+ keysetSlice: (query, { orderColumn, after, take }) => {
68
+ // ONE reference to the ordering column, used by the comparison, the cursor rendering and the ORDER BY.
69
+ // `sql.ref` quotes it as an identifier; `./keyset.ts`'s type restricted it to a real column of the table, and
70
+ // nothing from a request ever reaches it. Both halves of `after` are bound parameters, pattern-checked before
71
+ // they got here (`parseDbKeysetCursor`).
72
+ const orderRef = sql.ref(orderColumn)
73
+ const windowed = after
74
+ ? query.where(sql<SqlBool>`(${orderRef}, id) < (${after.at}::timestamptz, ${after.id}::uuid)`)
75
+ : query
76
+ return windowed
77
+ .select(
78
+ sql<string>`to_char(${orderRef} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`.as('keyset_at'),
79
+ )
80
+ .orderBy(orderRef, 'desc')
81
+ .orderBy(sql`id`, 'desc')
82
+ .limit(take)
83
+ },
84
+ runWithTenant,
85
+ }
86
+
87
+ /**
88
+ * The family the framework runs on: its data modules' dialect helpers, and its transports' isolation and tenant scope.
89
+ * Postgres, the one family today; choosing it from the app's declaration arrives with a second.
90
+ */
91
+ export const family: DbFamily = postgresFamily
package/src/db/jobs.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { sql, type Kysely, type Transaction } from 'kysely'
1
+ import type { Kysely, Transaction } from 'kysely'
2
2
  import { exportKeyPrefix, type JobStatus, jobStatusMachine } from '../core/jobs'
3
3
  import { InvalidTransitionError } from '../core/state-machine'
4
4
  import type { DbPort } from '../ports/db'
5
5
  import { NotFoundError } from '../ports/errors'
6
6
  import type { JobsPort } from '../ports/jobs'
7
+ import { family } from './family'
7
8
  import type { DB } from './schema'
8
9
  import { enqueueWebhookEvent } from './webhooks'
9
10
 
@@ -74,14 +75,14 @@ export async function recordJobStatus(
74
75
  .selectFrom('jobs')
75
76
  .select(['status', 'org_id', 'kind'])
76
77
  .where('id', '=', jobId)
77
- .forUpdate()
78
+ .$call(family.lockRow)
78
79
  .executeTakeFirstOrThrow()
79
80
  jobStatusMachine.assertTransition(current.status as JobStatus, next)
80
81
  await trx
81
82
  .updateTable('jobs')
82
83
  .set({
83
84
  status: next,
84
- updated_at: sql`now()`,
85
+ updated_at: family.currentTime(),
85
86
  ...(extra?.resultKey !== undefined ? { result_key: extra.resultKey } : {}),
86
87
  ...(extra?.error !== undefined ? { error: extra.error } : {}),
87
88
  })
package/src/db/keyset.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { sql, type SelectQueryBuilder, type SqlBool, type Transaction } from 'kysely'
1
+ import type { SelectQueryBuilder, Transaction } from 'kysely'
2
2
  import {
3
3
  type KeysetCursorParse,
4
4
  type KeysetPosition,
@@ -7,6 +7,7 @@ import {
7
7
  parseKeysetCursor,
8
8
  } from '../core/keyset'
9
9
  import type { DbPort } from '../ports/db'
10
+ import { family } from './family'
10
11
  import type { DB } from './schema'
11
12
 
12
13
  /**
@@ -37,7 +38,7 @@ import type { DB } from './schema'
37
38
  * The page predicate is a row-value comparison, `(created_at, id) < ($1, $2)`, which is both the
38
39
  * exact meaning of "strictly after this position in `created_at DESC, id DESC`" and the form Postgres
39
40
  * can satisfy from an index on `(…, created_at DESC, id DESC)` — see
40
- * each app’s own `1004_*_keyset_index` migration for the index a paged table wants.
41
+ * each app’s own `*_keyset_index` migration for the index a paged table wants.
41
42
  *
42
43
  * **Ordering by another column.** `created_at` is the default ordering key, and the optional trailing
43
44
  * `orderBy` argument swaps it for any other NOT NULL `timestamptz` column of the paged table — a list
@@ -81,8 +82,8 @@ export type KeysetTableName = {
81
82
  * What the types cannot say is that the column is a `timestamptz`: the schema has no nominal
82
83
  * timestamp type, so `created_at: Generated<string>` is the same TypeScript type as a text column
83
84
  * such as `JobsTable.status`, and this type admits both. That half is enforced at the SQL boundary
84
- * instead. The column goes in through `sql.ref` — a quoted identifier, never an interpolated string —
85
- * and is then fed to `to_char(… at time zone 'UTC', …)` and compared against a `::timestamptz`
85
+ * instead, by the family's `keysetSlice` (./family.ts). In Postgres the column goes in through `sql.ref` (a quoted
86
+ * identifier, never an interpolated string), and is then fed to `to_char(… at time zone 'UTC', …)` and compared against a `::timestamptz`
86
87
  * parameter, so naming a non-timestamp column fails with a Postgres type error on the first page.
87
88
  * It is loud, not a silently wrong order.
88
89
  */
@@ -146,29 +147,15 @@ export async function keysetPage<TB extends KeysetTableName, O extends { id: str
146
147
  ): Promise<KeysetPage<O>> {
147
148
  const limit = clampKeysetLimit(request.limit)
148
149
  const after = request.after
149
- // ONE reference to the ordering column, used by the comparison, the cursor rendering and the
150
- // ORDER BY below. `sql.ref` quotes it as an identifier; the type already restricted it to a real
151
- // column of `TB`, and nothing from a request ever reaches it.
150
+ // The type already restricted the ordering column to a real column of `TB`, and nothing from a request ever
151
+ // reaches it. The family writes the ordering, the cursor comparison and the cursor's rendering (./family.ts).
152
152
  const orderColumn = (orderBy ?? 'created_at') as KeysetOrderColumn<TB>
153
- const orderRef = sql.ref(orderColumn)
154
153
  return db.withTenant(request.tenantId, async (trx) => {
155
- // The caller's scope, applied on EVERY page — this is the query, not a first-page-only one.
156
- const scoped = build(trx)
157
- // The cursor can only ADD a conjunct to it. Both halves are bound parameters, and both were
158
- // pattern-checked before they got here (parseDbKeysetCursor).
159
- const windowed = after
160
- ? scoped.where(sql<SqlBool>`(${orderRef}, id) < (${after.at}::timestamptz, ${after.id}::uuid)`)
161
- : scoped
162
- // One extra row is the "is there a next page" probe — cheaper and race-free compared with a
163
- // COUNT(*), which would be a second query against a moving table.
164
- const probed = await windowed
165
- .select(
166
- sql<string>`to_char(${orderRef} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`.as('keyset_at'),
167
- )
168
- .orderBy(orderRef, 'desc')
169
- .orderBy(sql`id`, 'desc')
170
- .limit(limit + 1)
171
- .execute()
154
+ // The caller's scope, applied on EVERY page — this is the query, not a first-page-only one. The cursor can
155
+ // only ADD a conjunct to it, and both its halves are bound parameters, pattern-checked before they got here
156
+ // (parseDbKeysetCursor). One extra row is the "is there a next page" probe — cheaper and race-free compared
157
+ // with a COUNT(*), which would be a second query against a moving table.
158
+ const probed = await family.keysetSlice(build(trx), { orderColumn, after, take: limit + 1 }).execute()
172
159
  const rows = probed.slice(0, limit)
173
160
  const last = rows.at(-1)
174
161
  return {
@@ -11,7 +11,7 @@ import { Kysely, sql } from 'kysely'
11
11
  * could not switch to the role it had created, and every tenant-scoped query failed closed with
12
12
  * `permission denied to set role "app_user"`.
13
13
  *
14
- * NEEDS POSTGRES 16 OR LATER, which is SSSB's stated minimum (docs/adopting.md, "Cutover"):
14
+ * NEEDS POSTGRES 16 OR LATER, which is SSSB's stated minimum (docs/adopting-reference.md, "Cutover"):
15
15
  * `pg_has_role(..., 'SET')` and `GRANT ... WITH SET` both arrived in 16. Every server SSSB targets is 16
16
16
  * or later (Aurora 16.10 in @sssb/cdk's SssbApp, CI's postgres:16, pglite's 18.6), so this does not branch on
17
17
  * `server_version_num`.
@@ -7,7 +7,7 @@ import {
7
7
  isNotificationKind,
8
8
  } from '../core/notifications'
9
9
  import type { DbPort } from '../ports/db'
10
- import { jsonb } from './jsonb'
10
+ import { family } from './family'
11
11
  import { toIso } from './jobs'
12
12
 
13
13
  /**
@@ -45,7 +45,7 @@ export async function insertNotification(
45
45
  org_id: input.orgId,
46
46
  recipient_user_id: input.recipientUserId,
47
47
  kind: input.kind,
48
- payload: jsonb(input.payload),
48
+ payload: family.json(input.payload),
49
49
  })
50
50
  .returning('id')
51
51
  .executeTakeFirstOrThrow(),
@@ -52,7 +52,7 @@ export async function orgIdentityForSlug(db: DbPort, tenantId: string, orgSlug:
52
52
  /**
53
53
  * Resolves an org uuid back to its slug + name — the reverse of orgIdForSlug, same RLS-free raw read.
54
54
  * Used by the scheduled digest handler, which knows its job's org_id but needs the slug to
55
- * find recipients (@app/seed people) and the name for the digest copy. Null when the org is gone.
55
+ * list the org's members (`auth.listMembers`) and the name for the digest copy. Null when the org is gone.
56
56
  */
57
57
  export async function orgForId(db: DbPort, orgId: string): Promise<{ slug: string; name: string } | null> {
58
58
  await db.ready()
@@ -4,7 +4,7 @@ import type { DbPort } from '../ports/db'
4
4
  import { proveRlsCoverage } from './rls-coverage'
5
5
  import { frameworkRlsProofs, type ProofExpectation } from './rls-proofs'
6
6
  import type { DB } from './schema'
7
- import { runWithTenant } from './with-tenant'
7
+ import { family } from './family'
8
8
 
9
9
  /**
10
10
  * The composition root of THE tenant-isolation proof suite (ADR-0004): framework proofs ∪ app proofs,
@@ -64,8 +64,9 @@ export async function runRlsProofs(
64
64
  // (`keysetPage`, which takes a DbPort and opens `withTenant` itself) rather than a re-implementation
65
65
  // of them. Migration/ready are not this suite's business — it is handed an already-migrated engine.
66
66
  const dbPort: DbPort = {
67
+ isolation: family.isolation,
67
68
  getDb: () => db,
68
- withTenant: (tenantId, fn) => runWithTenant(appDb, tenantId, fn),
69
+ withTenant: (tenantId, fn) => family.runWithTenant(appDb, tenantId, fn),
69
70
  ready: () => Promise.resolve(),
70
71
  migrateToLatest: () => Promise.resolve(),
71
72
  }
@@ -2,6 +2,7 @@ import { computeNextRunAt, parseScheduleSpec, type ScheduleSpec } from '../core/
2
2
  import type { DbPort } from '../ports/db'
3
3
  import type { JobsPort } from '../ports/jobs'
4
4
  import { recordAuditEvent } from './audit'
5
+ import { family } from './family'
5
6
  import { toIso } from './jobs'
6
7
 
7
8
  /** Opaque actor id for the system-initiated scheduler in the audit trail (no user drives a tick). */
@@ -87,7 +88,7 @@ async function drainOne(
87
88
  .selectFrom('job_schedules')
88
89
  .select(['enabled', 'spec', 'kind', 'org_id', 'next_run_at'])
89
90
  .where('id', '=', schedule.id)
90
- .forUpdate()
91
+ .$call(family.lockRow)
91
92
  .executeTakeFirst()
92
93
  // Re-check under the lock: enabled may have flipped, or a concurrent tick may have already
93
94
  // advanced next_run_at past `now` — either way this tick does nothing for the row.
@@ -15,7 +15,7 @@ import type { DbPort } from '../ports/db'
15
15
  // TYPE-ONLY import (erased): keeps packages/kit/src/db free of a runtime @/adapters dependency — see WebhookDispatch.
16
16
  import type { WebhookDispatch } from '../server-lib/webhook-dispatch'
17
17
  import { recordAuditEvent } from './audit'
18
- import { jsonb } from './jsonb'
18
+ import { family } from './family'
19
19
 
20
20
  /** timestamptz comes back from both engines as a Date; local (avoids a jobs.ts import cycle since
21
21
  * jobs.ts imports enqueueWebhookEvent from here). */
@@ -57,7 +57,7 @@ export async function enqueueWebhookEvent(
57
57
  tenant_id: input.tenantId,
58
58
  endpoint_id: endpoint.id,
59
59
  event_kind: input.kind,
60
- payload: jsonb(input.payload),
60
+ payload: family.json(input.payload),
61
61
  next_attempt_at: now,
62
62
  })),
63
63
  )
@@ -164,7 +164,7 @@ async function deliverOne(
164
164
  'e.enabled as enabled',
165
165
  ])
166
166
  .where('d.id', '=', delivery.id)
167
- .forUpdate()
167
+ .$call(family.lockRow)
168
168
  .executeTakeFirst()
169
169
  // Re-check under the lock: a concurrent tick may have delivered it, killed it, or advanced its
170
170
  // next_attempt_at past `now`.
@@ -338,7 +338,7 @@ export async function createEndpoint(
338
338
  org_id: input.orgId,
339
339
  url: input.url,
340
340
  secret: input.secret,
341
- event_kinds: jsonb(input.eventKinds),
341
+ event_kinds: family.json(input.eventKinds),
342
342
  created_by: input.createdBy,
343
343
  })
344
344
  .returning('id')
@@ -139,10 +139,11 @@ function digestSnippet(body: string): string {
139
139
  return oneLine.length > DIGEST_SNIPPET_LENGTH ? `${oneLine.slice(0, DIGEST_SNIPPET_LENGTH - 1)}…` : oneLine
140
140
  }
141
141
 
142
- /** A team's digest recipient (twin of the real handler's digestRecipient): its admin, else its first
142
+ /** A team's digest recipient (twin of the server handler's `digestRecipient` in a simulated world): among everyone
143
+ * in the world (the seed and accepted invitees, as the fake auth adapter lists members), its admin, else its first
143
144
  * member, else a synthetic per-org address. */
144
- function digestRecipientEmail(orgSlug: string): string {
145
- const members = people.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
145
+ function digestRecipientEmail(orgSlug: string, everyone: readonly SeedPerson[]): string {
146
+ const members = everyone.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
146
147
  const admin = members.find((p) => p.memberships.some((m) => m.orgSlug === orgSlug && m.role === 'admin'))
147
148
  return (admin ?? members[0])?.email ?? `${orgSlug}@digest.example`
148
149
  }
@@ -727,7 +728,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
727
728
  const recent = bodies.slice(0, DIGEST_RECENT_LIMIT).map(digestSnippet)
728
729
  newEmails.push({
729
730
  id: `${worldNowMs}-${jobId.slice(0, 8)}`,
730
- to: digestRecipientEmail(schedule.orgSlug),
731
+ to: digestRecipientEmail(schedule.orgSlug, allPeople),
731
732
  subject: tEmail('digestSubject', { org: orgName }),
732
733
  at: iso,
733
734
  html: buildDigestEmailHtml(
package/src/guide.md CHANGED
@@ -32,10 +32,26 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
32
32
  tests and in the app-root tool configs (Playwright, Vite). Every other module imports the resolved value: deployment
33
33
  parameters from `config/params.ts`, the run mode from `isSimulated`.
34
34
  - Deployment and service parameters exist only in `config/params.ts`. Secret values never enter the repository.
35
+ - Declare which of SSSB's optional ports the app uses in `config/params.ts`'s `ports` (`llm`, `email`, `inboundEmail`,
36
+ `jobs`, `storage`). A port the app does not use is `none`, never configured with placeholder values.
37
+ - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
38
+ `ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
35
39
  - `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
36
40
  anything that phones home.
37
41
  - Anything that needs real credentials, accounts or money is a row in the workspace's cutover checklist, never a
38
42
  blocker: the app boots, and is tested, without it.
43
+ - `src/proxy.ts` default-exports the app's proxy wrapped in `withAuthProxy` from `@sssb/kit/adapters/proxy`, and its
44
+ `config.matcher` sends it every page and every `/api` route: in real mode SSSB's auth adapter needs its provider's
45
+ middleware to have seen the request, and `withAuthProxy` runs that middleware around your proxy (loading none of it
46
+ in simulated mode). Never import the provider's middleware yourself. A page path has no dot in it (the generated
47
+ matcher leaves those out, as static files), and Next buffers at most `proxyClientMaxBodySize` (10MB by default) of a
48
+ body the proxy sees, so an upload limit above it raises
49
+ `experimental.proxyClientMaxBodySize` in `next.config.ts` too.
50
+ - The locale layout (`src/app/[locale]/layout.tsx`) mounts `RealAuthProviders` from
51
+ `@sssb/kit/adapters/real/providers` in real mode, loaded with `import()` when `!isSimulated`: SSSB's real
52
+ sign-in and invite forms call the auth provider's client hooks, which throw outside it. The conformance suite's
53
+ `real-auth-provider` check fails a page that reaches one of those forms through its imports unless a layout or
54
+ template wrapping it reaches the provider.
39
55
 
40
56
  ## Data
41
57
 
@@ -109,10 +125,13 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
109
125
  route once, and `DEV_TICK_SECONDS=<n> pnpm dev` ticks it every n seconds. The ticker is off by default and stays off
110
126
  under e2e. The cron route (`src/app/api/webhooks/cron/route.ts`) stays behind `withWebhookSecret`: never add a
111
127
  bypass for the ticker.
128
+ - The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
129
+ layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
130
+ imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
112
131
  - In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
113
- server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json
114
- (`"sssb": { "port": "starter" }`), and every app of a workspace needs a slot of its own: a second app declares
115
- `"sssb": { "port": { "name": "ledger", "default": 3700 } }`, which `sssb doctor` checks, and reads its override from
116
- `LEDGER_PORT`.
132
+ server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
133
+ `"sssb": { "port": { "name": "ledger", "default": 3800 } }`, and reads its override from `LEDGER_PORT`; its scripts and
134
+ Playwright config name no slot (`sssb tick`, `sssb dev-tick`, `originForApp(__dirname)`), so they read it. Every app of
135
+ a workspace needs a slot of its own, which `sssb doctor` checks: `pnpm exec sssb add-app <slug>` gives a new app one.
117
136
  - Before finishing a change, run `pnpm verify` from the workspace root. Format with `pnpm lint:fix`, never by hand.
118
137
  Commit messages are conventional commits; the commit-msg hook runs commitlint.
@@ -1,10 +1,14 @@
1
1
  import { digestBodies } from '@sssb/app-config/digest'
2
- import { people } from '@sssb/app-config/seed'
3
2
  import { getTranslations } from 'next-intl/server'
3
+ // The run mode without the registry (as the request proxy asks it): the registry loads the job handlers, this one
4
+ // included, so importing it here would close that loop.
5
+ import { isSimulated } from '../adapters/run-mode'
6
+ import type { Locale } from '../core/locale'
4
7
  import { orgForId } from '../db/org-lookup'
5
8
  import { sendTemplate } from '../email/send'
6
9
  import { DigestEmail } from '../email/templates/digest-email'
7
10
  import { routing } from '../i18n/routing'
11
+ import type { AuthPort } from '../ports/auth'
8
12
  import type { DbPort } from '../ports/db'
9
13
  import type { JobHandler } from '../ports/jobs'
10
14
 
@@ -38,18 +42,26 @@ function snippet(body: string): string {
38
42
  }
39
43
 
40
44
  /**
41
- * Resolves who a team's digest is addressed to and in which locale, from the static seed people:
42
- * the team's admin if there is one, else its first member. A team with no seeded person (e.g. a
43
- * dynamically-created org) falls back to a synthetic per-org address in the app's default locale —
44
- * still visible under Simulator Mail's "all" scope, so the demo never shows an empty digest.
45
+ * Who a team's digest is addressed to, and in which locale: the team's first active admin, else its first active
46
+ * member, as the auth port lists them (the identity provider in a deployment, the simulated world's people in a
47
+ * demo). Never the seed: a deployment has none, and its people are the provider's.
48
+ *
49
+ * The locale is the person's own where the runner can say it (`resolveLocale`, which the simulated world's runner
50
+ * supplies); the auth port carries none, so a deployment writes in the app's default. Only an address is addressed:
51
+ * the real auth adapter lists a member's Clerk identifier, which may be a phone number rather than an email address.
52
+ *
53
+ * A team with no active member with an email address: in a simulated world, a synthetic per-org address, still visible under Simulator
54
+ * Mail's "all" scope, so the demo never shows an empty digest; in a deployment, nobody (null), and nothing is sent.
45
55
  */
46
- function digestRecipient(orgSlug: string): { to: string; locale: 'en' | 'es' } {
47
- const members = people.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
48
- const admin = members.find((p) => p.memberships.some((m) => m.orgSlug === orgSlug && m.role === 'admin'))
49
- const chosen = admin ?? members[0]
50
- return chosen
51
- ? { to: chosen.email, locale: chosen.locale }
52
- : { to: `${orgSlug}@digest.example`, locale: routing.defaultLocale }
56
+ async function digestRecipient(
57
+ auth: AuthPort,
58
+ resolveLocale: ((userId: string) => Locale | undefined) | undefined,
59
+ orgSlug: string,
60
+ ): Promise<{ to: string; locale: Locale } | null> {
61
+ const members = (await auth.listMembers(orgSlug)).filter((m) => m.status === 'active' && m.email.includes('@'))
62
+ const chosen = members.find((m) => m.role === 'admin') ?? members[0]
63
+ if (!chosen) return isSimulated ? { to: `${orgSlug}@digest.example`, locale: routing.defaultLocale } : null
64
+ return { to: chosen.email, locale: resolveLocale?.(chosen.id) ?? routing.defaultLocale }
53
65
  }
54
66
 
55
67
  /**
@@ -59,16 +71,19 @@ function digestRecipient(orgSlug: string): { to: string; locale: 'en' | 'es' } {
59
71
  * carries no app table name; a team with nothing to report still gets a valid (empty-state) digest.
60
72
  *
61
73
  * A scheduled email has no request/user locale at fire time (unlike the invite, sent by an acting
62
- * user), so the recipient's own seed locale drives the copy — falling back to the app default. Sends
63
- * nothing to storage: the effect IS the email, so it returns no resultKey.
74
+ * user), so the recipient's locale drives the copy where it is known (`digestRecipient`), falling back to the app
75
+ * default. Sends nothing to storage: the effect IS the email, so it returns no resultKey.
64
76
  */
65
77
  export const digestEmailHandler: JobHandler = async (_payload, ctx) => {
66
- const { db, email, tenantId, orgId } = ctx
78
+ const { db, email, auth, resolveLocale, tenantId, orgId } = ctx
67
79
  if (orgId === null) return {} // schedules are org-scoped (org_id NOT NULL), so this is unreachable; guard anyway
68
80
 
69
81
  const org = await orgForId(db, orgId)
70
- const orgName = org?.name ?? orgId
71
- const { to, locale } = digestRecipient(org?.slug ?? '')
82
+ if (!org) return {} // the org is gone: nobody to address, and no team to digest
83
+ const orgName = org.name
84
+ const recipient = await digestRecipient(auth, resolveLocale, org.slug)
85
+ if (!recipient) return {} // a deployment's team with no active member with an email address: nobody to send it to
86
+ const { to, locale } = recipient
72
87
 
73
88
  // The app supplies its own rows, newest first; counting and snipping stay here, so every app's
74
89
  // digest reads identically and the twin's numbers match the server's by construction.