@sssb/kit 0.3.0 → 0.5.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 (67) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/email-message.ts +30 -0
  4. package/src/adapters/fake/analytics.ts +1 -1
  5. package/src/adapters/fake/auth.ts +31 -4
  6. package/src/adapters/fake/data-dir.ts +32 -2
  7. package/src/adapters/fake/db.ts +4 -2
  8. package/src/adapters/fake/email.ts +2 -0
  9. package/src/adapters/real/absent.ts +13 -0
  10. package/src/adapters/real/accept-invite-form.tsx +86 -21
  11. package/src/adapters/real/analytics.ts +30 -3
  12. package/src/adapters/real/auth.ts +82 -20
  13. package/src/adapters/real/contract-postgres.ts +15 -11
  14. package/src/adapters/real/db-port.ts +3 -2
  15. package/src/adapters/real/email.ts +2 -0
  16. package/src/adapters/real/index.ts +49 -12
  17. package/src/adapters/real/jobs-in-process.ts +32 -14
  18. package/src/adapters/real/jobs.ts +6 -3
  19. package/src/adapters/real/migrate-handler.ts +3 -1
  20. package/src/adapters/real/no-analytics.ts +17 -0
  21. package/src/adapters/real/optional-ports.ts +35 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/s3-storage.ts +7 -1
  25. package/src/adapters/real/sign-in-form.tsx +29 -13
  26. package/src/adapters/real/storage-settings.ts +37 -0
  27. package/src/adapters/real/storage.ts +65 -0
  28. package/src/authz/app-exemptions.ts +79 -9
  29. package/src/authz/route-scan.ts +626 -55
  30. package/src/components/auth/accept-invite-screen.tsx +5 -1
  31. package/src/components/auth/people-picker.tsx +20 -2
  32. package/src/components/profile-screen.tsx +27 -2
  33. package/src/core/inbound-email.ts +41 -6
  34. package/src/cutover/rows.json +13 -1
  35. package/src/db/audit.ts +2 -2
  36. package/src/db/family-suite.ts +42 -0
  37. package/src/db/family.ts +91 -0
  38. package/src/db/jobs.ts +19 -9
  39. package/src/db/keyset.ts +19 -30
  40. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  41. package/src/db/notifications.ts +2 -2
  42. package/src/db/rls-coverage.ts +51 -17
  43. package/src/db/rls-proof-runner.ts +3 -2
  44. package/src/db/schedules.ts +11 -4
  45. package/src/db/webhooks.ts +4 -4
  46. package/src/demo-static/actor-drivers.ts +8 -2
  47. package/src/demo-static/email-html.ts +9 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +76 -37
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +26 -7
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +21 -2
  56. package/src/ports/db.ts +19 -0
  57. package/src/server-lib/invite.ts +34 -26
  58. package/src/server-lib/scheduled-tick.ts +5 -1
  59. package/src/server-lib/webhook-dispatch.ts +3 -0
  60. package/src/service-auth/mailgun.ts +19 -4
  61. package/src/testing/checks.json +9 -0
  62. package/src/testing/conformance/auth-provider.ts +308 -0
  63. package/src/testing/conformance/authz.ts +6 -2
  64. package/src/testing/conformance/db.ts +6 -5
  65. package/src/testing/conformance/i18n.ts +99 -5
  66. package/src/testing/conformance/suite.ts +65 -3
  67. package/src/testing/contract.ts +6 -4
@@ -117,7 +117,11 @@ export function AcceptInviteScreen({
117
117
  <Text size="xs" c="gray.7" data-testid="accept-agreements-notice">
118
118
  {t('agreementsNotice')}
119
119
  </Text>
120
- {error ? <Text c="red.8">{error}</Text> : null}
120
+ {error ? (
121
+ <Text c="red.8" role="alert">
122
+ {error}
123
+ </Text>
124
+ ) : null}
121
125
  </Stack>
122
126
  </form>
123
127
  }
@@ -14,8 +14,18 @@ export interface PickerPerson {
14
14
  /**
15
15
  * Simulated-mode sign-in: the same card layout the real credential form uses, listing seeded
16
16
  * people. One auth UI in every mode (ADR-0003).
17
+ *
18
+ * `onPick` may answer a promise: one that resolves `false` or rejects (the sign-in was refused, the dev server is
19
+ * down) clears the spinner so the person can pick again; anything else (`true`, or nothing, as an `async` handler
20
+ * that returns no value resolves) keeps it while the page navigates.
17
21
  */
18
- export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPick: (id: string) => void }) {
22
+ export function PeoplePicker({
23
+ people,
24
+ onPick,
25
+ }: {
26
+ people: PickerPerson[]
27
+ onPick: (id: string) => void | Promise<boolean | void>
28
+ }) {
19
29
  const t = useTranslations('auth')
20
30
  const [busy, setBusy] = useState<string | null>(null)
21
31
 
@@ -39,7 +49,15 @@ export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPic
39
49
  }
40
50
  onClick={() => {
41
51
  setBusy(person.id)
42
- onPick(person.id)
52
+ const result = onPick(person.id)
53
+ if (result) {
54
+ result.then(
55
+ (outcome) => {
56
+ if (outcome === false) setBusy(null)
57
+ },
58
+ () => setBusy(null),
59
+ )
60
+ }
43
61
  }}
44
62
  >
45
63
  {person.name}
@@ -10,6 +10,9 @@ export interface ProfileValues {
10
10
  locale: string
11
11
  }
12
12
 
13
+ /** The longest display name SSSB's auth adapters accept; a blank one is refused too. */
14
+ const PROFILE_NAME_MAX_LENGTH = 256
15
+
13
16
  /**
14
17
  * Lean take on Clerk's UserProfile (ADR-0003): a sectioned account page. The Profile section is live;
15
18
  * the Security section is a named seam so MFA / password / connected accounts have a home when those
@@ -27,13 +30,25 @@ export function ProfileScreen({
27
30
  initial: ProfileValues
28
31
  email: string
29
32
  locales: string[]
33
+ /** Rejects when the profile was not saved: the screen then keeps the form and says so. */
30
34
  onSave: (values: ProfileValues) => Promise<void>
31
35
  extraSection?: ReactNode
32
36
  }) {
33
37
  const t = useTranslations('profile')
34
38
  const [saved, setSaved] = useState(false)
35
39
  const [busy, setBusy] = useState(false)
36
- const form = useForm({ initialValues: initial })
40
+ const [saveFailed, setSaveFailed] = useState(false)
41
+ const form = useForm({
42
+ initialValues: initial,
43
+ validate: {
44
+ name: (value) =>
45
+ !value.trim()
46
+ ? t('nameRequired')
47
+ : value.length > PROFILE_NAME_MAX_LENGTH
48
+ ? t('nameTooLong', { max: PROFILE_NAME_MAX_LENGTH })
49
+ : null,
50
+ },
51
+ })
37
52
 
38
53
  return (
39
54
  <Container component="main" size="sm" py="xl">
@@ -48,8 +63,12 @@ export function ProfileScreen({
48
63
  onSubmit={form.onSubmit((values) => {
49
64
  setBusy(true)
50
65
  setSaved(false)
66
+ setSaveFailed(false)
51
67
  onSave(values)
52
- .then(() => setSaved(true))
68
+ .then(
69
+ () => setSaved(true),
70
+ () => setSaveFailed(true),
71
+ )
53
72
  .finally(() => setBusy(false))
54
73
  })}
55
74
  >
@@ -58,6 +77,7 @@ export function ProfileScreen({
58
77
  <TextInput
59
78
  label={t('nameLabel')}
60
79
  data-testid="profile-name"
80
+ withAsterisk
61
81
  {...form.getInputProps('name')}
62
82
  />
63
83
  <Select
@@ -75,6 +95,11 @@ export function ProfileScreen({
75
95
  >
76
96
  {t('saveButton')}
77
97
  </Button>
98
+ {saveFailed ? (
99
+ <Text c="red.8" size="sm" role="alert" data-testid="profile-save-error">
100
+ {t('saveError')}
101
+ </Text>
102
+ ) : null}
78
103
  {saved ? (
79
104
  <Text c="green.8" size="sm" data-testid="profile-saved">
80
105
  {t('saved')}
@@ -42,14 +42,49 @@ export interface InboundRecipient {
42
42
  const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
43
43
 
44
44
  /**
45
- * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`,
46
- * a bare `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local
47
- * parts are case-insensitive in every practical mail system — we normalize so a sender/member match is
48
- * not defeated by case). Returns '' for anything without an addr-spec.
45
+ * `raw` with each double-quoted string taken out, a backslash escaping the character after it. A quote that never
46
+ * closes is left where it is, with everything after it. One pass by hand: the regular expression for this
47
+ * (`"(?:[^"\\]|\\.)*"`) rescans from every opening quote, which is quadratic on a header an attacker writes.
48
+ */
49
+ function withoutQuotedStrings(raw: string): string {
50
+ let out = ''
51
+ let at = 0
52
+ while (at < raw.length) {
53
+ if (raw[at] !== '"') {
54
+ out += raw[at]
55
+ at += 1
56
+ continue
57
+ }
58
+ let end = at + 1
59
+ while (end < raw.length && raw[end] !== '"') end += raw[end] === '\\' ? 2 : 1
60
+ if (end >= raw.length) return out + raw.slice(at)
61
+ at = end + 1
62
+ }
63
+ return out
64
+ }
65
+
66
+ /**
67
+ * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`, a bare
68
+ * `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local parts are
69
+ * case-insensitive in every practical mail system — we normalize so a sender/member match is not defeated by case).
70
+ *
71
+ * It fails closed: anything it cannot read one way only returns '' ("no address"), never a guess. Double-quoted
72
+ * strings (a display name) are dropped first, so `"<victim@org.test>" <attacker@evil.test>` is the attacker's own
73
+ * address. Then a value with angle brackets must hold exactly one `<...>` with nothing but whitespace after its `>`:
74
+ * a comment after the address (`<a@x> (<b@y>)`), a second address (`<a@x>, <b@y>`) or text after the brackets
75
+ * (`x<b@y>a@x`) each name another address, so they return ''. Returns '' for anything without an addr-spec too.
49
76
  */
50
77
  export function normalizeEmailAddress(raw: string): string {
51
- const angle = raw.match(/<([^>]+)>/)
52
- const candidate = (angle ? angle[1]! : raw).trim().toLowerCase()
78
+ const unquoted = withoutQuotedStrings(raw)
79
+ let candidate: string
80
+ if (/[<>]/.test(unquoted)) {
81
+ const only = /^[^<>]*<([^<>]*)>\s*$/.exec(unquoted)
82
+ if (!only) return ''
83
+ candidate = only[1]!
84
+ } else {
85
+ candidate = unquoted
86
+ }
87
+ candidate = candidate.trim().toLowerCase()
53
88
  // A single '@' with non-empty both sides, else not a usable address.
54
89
  const at = candidate.indexOf('@')
55
90
  if (at <= 0 || at !== candidate.lastIndexOf('@') || at === candidate.length - 1) return ''
@@ -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
  })
@@ -97,13 +98,22 @@ export async function recordJobStatus(
97
98
  // Outbound webhooks: a job status change is an emitted event. Enqueue only — cheap; the
98
99
  // drain delivers async. Deliberately AFTER the status transaction commits (the audit precedent),
99
100
  // and skipped when the job has no org (RLS-proof / legacy rows can't have subscribed endpoints).
101
+ // The status is durable by now, so a failed enqueue must not fail the caller: a runner that saw
102
+ // `running` throw would never run the handler, and one that saw `completed` throw would answer an
103
+ // error for a job that finished. The event is lost and logged (console.warn reaches CloudWatch in
104
+ // Lambda; SSSB has no logger port, as ../adapters/real/db.ts says).
100
105
  if (job.orgId) {
101
- await enqueueWebhookEvent(db, {
102
- tenantId,
103
- orgId: job.orgId,
104
- kind: 'job.status_changed',
105
- payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
106
- })
106
+ try {
107
+ await enqueueWebhookEvent(db, {
108
+ tenantId,
109
+ orgId: job.orgId,
110
+ kind: 'job.status_changed',
111
+ payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
112
+ })
113
+ } catch (error) {
114
+ const message = error instanceof Error ? error.message : String(error)
115
+ console.warn(`SSSB jobs: job ${jobId} is ${next}, but enqueueing its webhook event failed: ${message}`)
116
+ }
107
117
  }
108
118
  }
109
119
 
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
  /**
@@ -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
  */
@@ -100,15 +101,17 @@ export interface KeysetPage<TRow> {
100
101
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
101
102
 
102
103
  /**
103
- * `parseKeysetCursor` plus the one constraint only this layer knows about: the id half is bound to a
104
- * `uuid`, so an id that is not one can never be a real row here and is rejected at the boundary
105
- * rather than becoming a cast error (a 500, and a probe signal) inside the query. Routes over SQL
106
- * tables should use THIS, not the core parser; an in-memory twin uses the core one, whose row handles
107
- * are not uuids.
104
+ * `parseKeysetCursor` plus the constraints only this layer knows about, each a cast error (a 500, and a
105
+ * probe signal) inside the query if it were let through: the id half is bound to a `uuid`, so an id
106
+ * that is not one can never be a real row here; and the `at` half is bound to a `timestamptz`, which
107
+ * has no year 0000 (JavaScript's calendar does, so the core parser accepts it). Both are rejected at
108
+ * the boundary. Routes over SQL tables should use THIS, not the core parser; an in-memory twin uses
109
+ * the core one, whose row handles are not uuids.
108
110
  */
109
111
  export function parseDbKeysetCursor(raw: string | null | undefined): KeysetCursorParse {
110
112
  const parsed = parseKeysetCursor(raw)
111
- if (parsed.kind === 'after' && !UUID_PATTERN.test(parsed.position.id)) return { kind: 'invalid' }
113
+ if (parsed.kind !== 'after') return parsed
114
+ if (!UUID_PATTERN.test(parsed.position.id) || parsed.position.at.startsWith('0000-')) return { kind: 'invalid' }
112
115
  return parsed
113
116
  }
114
117
 
@@ -146,29 +149,15 @@ export async function keysetPage<TB extends KeysetTableName, O extends { id: str
146
149
  ): Promise<KeysetPage<O>> {
147
150
  const limit = clampKeysetLimit(request.limit)
148
151
  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.
152
+ // The type already restricted the ordering column to a real column of `TB`, and nothing from a request ever
153
+ // reaches it. The family writes the ordering, the cursor comparison and the cursor's rendering (./family.ts).
152
154
  const orderColumn = (orderBy ?? 'created_at') as KeysetOrderColumn<TB>
153
- const orderRef = sql.ref(orderColumn)
154
155
  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()
156
+ // The caller's scope, applied on EVERY page — this is the query, not a first-page-only one. The cursor can
157
+ // only ADD a conjunct to it, and both its halves are bound parameters, pattern-checked before they got here
158
+ // (parseDbKeysetCursor). One extra row is the "is there a next page" probe — cheaper and race-free compared
159
+ // with a COUNT(*), which would be a second query against a moving table.
160
+ const probed = await family.keysetSlice(build(trx), { orderColumn, after, take: limit + 1 }).execute()
172
161
  const rows = probed.slice(0, limit)
173
162
  const last = rows.at(-1)
174
163
  return {
@@ -55,7 +55,7 @@ export async function up(db: Kysely<any>): Promise<void> {
55
55
  END IF;
56
56
  EXCEPTION WHEN insufficient_privilege THEN
57
57
  -- The statement is printed with the role QUOTED, so copying it runs as-is for any role name.
58
- RAISE EXCEPTION 'keel: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
58
+ RAISE EXCEPTION 'SSSB: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
59
59
  END $$
60
60
  `.execute(db)
61
61
  }
@@ -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(),
@@ -112,8 +112,15 @@ interface RelationRow {
112
112
  enabled: boolean
113
113
  forced: boolean
114
114
  is_partition: boolean
115
- policies: number
116
- policy_src: string
115
+ }
116
+
117
+ interface PolicyRow {
118
+ schema_name: string
119
+ table_name: string
120
+ policy_name: string
121
+ permissive: boolean
122
+ using_src: string | null
123
+ check_src: string | null
117
124
  }
118
125
 
119
126
  interface PrivilegeRow {
@@ -153,14 +160,7 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
153
160
  c.relkind::text AS kind,
154
161
  c.relrowsecurity AS enabled,
155
162
  c.relforcerowsecurity AS forced,
156
- c.relispartition AS is_partition,
157
- (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid)::int AS policies,
158
- COALESCE((
159
- SELECT string_agg(
160
- COALESCE(pg_get_expr(p.polqual, p.polrelid), '') || ' ' ||
161
- COALESCE(pg_get_expr(p.polwithcheck, p.polrelid), ''), ' ')
162
- FROM pg_policy p WHERE p.polrelid = c.oid
163
- ), '') AS policy_src
163
+ c.relispartition AS is_partition
164
164
  FROM reachable r
165
165
  JOIN pg_class c ON c.oid = r.oid
166
166
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -168,6 +168,26 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
168
168
  ORDER BY n.nspname, c.relname
169
169
  `.execute(db)
170
170
 
171
+ // Policies one row each. They used to be read as one string per table, and since PERMISSIVE policies
172
+ // are OR-ed, one isolating policy hid a `USING (true)` beside it: the table leaked with the gate green.
173
+ const { rows: policyRows } = await sql<PolicyRow>`
174
+ SELECT n.nspname AS schema_name,
175
+ c.relname AS table_name,
176
+ p.polname AS policy_name,
177
+ p.polpermissive AS permissive,
178
+ pg_get_expr(p.polqual, p.polrelid) AS using_src,
179
+ pg_get_expr(p.polwithcheck, p.polrelid) AS check_src
180
+ FROM pg_policy p
181
+ JOIN pg_class c ON c.oid = p.polrelid
182
+ JOIN pg_namespace n ON n.oid = c.relnamespace
183
+ ORDER BY n.nspname, c.relname, p.polname
184
+ `.execute(db)
185
+ const policiesOf = new Map<string, PolicyRow[]>()
186
+ for (const policy of policyRows) {
187
+ const key = `${policy.schema_name}.${policy.table_name}`
188
+ policiesOf.set(key, [...(policiesOf.get(key) ?? []), policy])
189
+ }
190
+
171
191
  const failures: string[] = []
172
192
  const name = (row: RelationRow) => `${row.schema_name}.${row.table_name}`
173
193
  const present = new Set(rows.map(name))
@@ -213,17 +233,31 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
213
233
  continue
214
234
  }
215
235
 
236
+ const policies = policiesOf.get(key) ?? []
216
237
  if (!row.enabled) failures.push(`${key} is reachable by app_user but has no ROW LEVEL SECURITY`)
217
238
  else if (!row.forced) failures.push(`${key} has RLS but not FORCE ROW LEVEL SECURITY`)
218
- else if (row.policies === 0) failures.push(`${key} has RLS enabled but no policy`)
219
- else if (!row.policy_src.includes(TENANT_SETTING)) {
239
+ else if (policies.length === 0) failures.push(`${key} has RLS enabled but no policy`)
240
+ else {
220
241
  // Coverage used to accept any policy at all, so `USING (true)` — a policy that exists and
221
242
  // isolates nothing — passed. Reading the expression is what distinguishes a policy from a
222
- // policy that does something.
223
- failures.push(
224
- `${key} has a policy that never reads ${TENANT_SETTING}, so it does not isolate tenants: ` +
225
- `${row.policy_src.trim()}`,
226
- )
243
+ // policy that does something. Each PERMISSIVE policy is read on its own (they are OR-ed, so
244
+ // one tenant-blind policy opens the table whatever the others say), and each expression it
245
+ // has on its own: a USING that isolates beside a `WITH CHECK (true)` still lets a write land
246
+ // in another tenant. A missing expression is fine (an INSERT policy has no USING; an absent
247
+ // WITH CHECK falls back to USING). RESTRICTIVE policies are AND-ed on top and can only narrow
248
+ // access, so they are not read here (a table with only restrictive policies shows app_user nothing).
249
+ for (const policy of policies) {
250
+ if (!policy.permissive) continue
251
+ const blind = [policy.using_src, policy.check_src].filter(
252
+ (expression): expression is string => expression !== null && !expression.includes(TENANT_SETTING),
253
+ )
254
+ if (blind.length > 0) {
255
+ failures.push(
256
+ `${key} has a permissive policy \`${policy.policy_name}\` that never reads ${TENANT_SETTING}, ` +
257
+ `so it does not isolate tenants (permissive policies are OR-ed): ${blind.join(' / ')}`,
258
+ )
259
+ }
260
+ }
227
261
  }
228
262
  }
229
263