@sssb/kit 0.3.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.
- package/dist/release.json +1 -1
- package/package.json +1 -1
- package/src/adapters/fake/auth.ts +13 -2
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/real/absent.ts +13 -0
- package/src/adapters/real/accept-invite-form.tsx +62 -15
- package/src/adapters/real/analytics.ts +1 -1
- package/src/adapters/real/auth.ts +28 -2
- package/src/adapters/real/db-port.ts +3 -2
- package/src/adapters/real/index.ts +49 -12
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +35 -1
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/cutover/rows.json +13 -1
- package/src/db/audit.ts +2 -2
- package/src/db/family-suite.ts +42 -0
- package/src/db/family.ts +91 -0
- package/src/db/jobs.ts +4 -3
- package/src/db/keyset.ts +11 -24
- package/src/db/notifications.ts +2 -2
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +2 -1
- package/src/db/webhooks.ts +4 -4
- package/src/guide.md +6 -1
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +296 -0
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/suite.ts +2 -0
- package/src/testing/contract.ts +6 -4
package/src/cutover/rows.json
CHANGED
|
@@ -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 {
|
|
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 :
|
|
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
|
+
}
|
package/src/db/family.ts
ADDED
|
@@ -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 {
|
|
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
|
-
.
|
|
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:
|
|
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 {
|
|
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.
|
|
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
|
-
//
|
|
150
|
-
//
|
|
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
|
-
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
const
|
|
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 {
|
package/src/db/notifications.ts
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
isNotificationKind,
|
|
8
8
|
} from '../core/notifications'
|
|
9
9
|
import type { DbPort } from '../ports/db'
|
|
10
|
-
import {
|
|
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:
|
|
48
|
+
payload: family.json(input.payload),
|
|
49
49
|
})
|
|
50
50
|
.returning('id')
|
|
51
51
|
.executeTakeFirstOrThrow(),
|
|
@@ -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 {
|
|
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
|
}
|
package/src/db/schedules.ts
CHANGED
|
@@ -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
|
-
.
|
|
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.
|
package/src/db/webhooks.ts
CHANGED
|
@@ -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 {
|
|
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:
|
|
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
|
-
.
|
|
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:
|
|
341
|
+
event_kinds: family.json(input.eventKinds),
|
|
342
342
|
created_by: input.createdBy,
|
|
343
343
|
})
|
|
344
344
|
.returning('id')
|
package/src/guide.md
CHANGED
|
@@ -33,7 +33,7 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
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
35
|
- Declare which of SSSB's optional ports the app uses in `config/params.ts`'s `ports` (`llm`, `email`, `inboundEmail`,
|
|
36
|
-
`jobs`). A port the app does not use is `none`, never configured with placeholder values.
|
|
36
|
+
`jobs`, `storage`). A port the app does not use is `none`, never configured with placeholder values.
|
|
37
37
|
- A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
|
|
38
38
|
`ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
|
|
39
39
|
- `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
|
|
@@ -47,6 +47,11 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
47
47
|
matcher leaves those out, as static files), and Next buffers at most `proxyClientMaxBodySize` (10MB by default) of a
|
|
48
48
|
body the proxy sees, so an upload limit above it raises
|
|
49
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.
|
|
50
55
|
|
|
51
56
|
## Data
|
|
52
57
|
|
package/src/ports/auth.ts
CHANGED
|
@@ -52,6 +52,22 @@ export interface InviteInput {
|
|
|
52
52
|
email: string
|
|
53
53
|
role: Role
|
|
54
54
|
orgSlug: string
|
|
55
|
+
/**
|
|
56
|
+
* The absolute URL of the app's accept page, with no query (`https://host/en/accept-invite`): where the invitee
|
|
57
|
+
* lands. The adapter builds the link it returns from it, with whatever that page reads to find the invitation.
|
|
58
|
+
*/
|
|
59
|
+
acceptPageUrl: string
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A recorded invitation, and the link that lets its invitee accept it. */
|
|
63
|
+
export interface CreatedInvite extends Membership {
|
|
64
|
+
/**
|
|
65
|
+
* The link the invitation mail carries, or null when the provider gives none (it delivers the invitation itself).
|
|
66
|
+
* Only the adapter can build it, since only the adapter knows what its accept page reads: the fake's
|
|
67
|
+
* `?invite=<id>`, the provider's own ticket. It is the invitee's credential: mail it to them, and never return it
|
|
68
|
+
* to the inviter.
|
|
69
|
+
*/
|
|
70
|
+
acceptUrl: string | null
|
|
55
71
|
}
|
|
56
72
|
|
|
57
73
|
/**
|
|
@@ -78,8 +94,11 @@ export interface AuthPort {
|
|
|
78
94
|
* once.
|
|
79
95
|
*/
|
|
80
96
|
getMember(orgSlug: string, userId: string): Promise<MemberStanding | null>
|
|
81
|
-
/**
|
|
82
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Records the invitation (per-org) and returns the link to accept it; sending the invitation email is the caller's
|
|
99
|
+
* job (email port), with that link.
|
|
100
|
+
*/
|
|
101
|
+
createInvite(invite: InviteInput): Promise<CreatedInvite>
|
|
83
102
|
/** Orgs the current user belongs to (drives the OrgSwitcher). */
|
|
84
103
|
listMyOrgs(): Promise<OrgRef[]>
|
|
85
104
|
/** @throws ForbiddenError when the user has no membership in that org */
|
package/src/ports/db.ts
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import type { Kysely, Transaction } from 'kysely'
|
|
2
2
|
import type { DB } from '../db/schema'
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* How a database adapter keeps one tenant's rows from another's (ADR-0015, second addendum, point 3).
|
|
6
|
+
*
|
|
7
|
+
* - `'rls'`: row-level security. Every tenant table's policy compares `tenant_id` with the tenant `withTenant` set for
|
|
8
|
+
* the transaction, under a role that cannot bypass it, proven by the isolation proof suite on pglite and on real
|
|
9
|
+
* Postgres (ADR-0004). Every transport SSSB ships declares it.
|
|
10
|
+
*
|
|
11
|
+
* Other arrangements (a database per tenant, a single-tenant deployment, an unenforced filter chosen by name) join this
|
|
12
|
+
* union with the database family that has the mechanism and the proofs for them, never before: a declared guarantee
|
|
13
|
+
* with nothing behind it is not allowed.
|
|
14
|
+
*/
|
|
15
|
+
export type DbIsolation = 'rls'
|
|
16
|
+
|
|
4
17
|
/**
|
|
5
18
|
* Database port (ADR-0002, ADR-0004). All tenant-scoped access goes through withTenant, which
|
|
6
19
|
* runs fn inside a transaction whose first statements set the app_user role and tenant context —
|
|
@@ -8,6 +21,12 @@ import type { DB } from '../db/schema'
|
|
|
8
21
|
* and infrastructure work only.
|
|
9
22
|
*/
|
|
10
23
|
export interface DbPort {
|
|
24
|
+
/**
|
|
25
|
+
* The tenant isolation this adapter gives, declared rather than implied. Required: an adapter that does not say
|
|
26
|
+
* how it isolates tenants is not one SSSB can make a promise about. A test double states the guarantee of the
|
|
27
|
+
* adapter it stands in for (`'rls'` for any of SSSB's).
|
|
28
|
+
*/
|
|
29
|
+
readonly isolation: DbIsolation
|
|
11
30
|
getDb(): Kysely<DB>
|
|
12
31
|
withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T>
|
|
13
32
|
/** Resolves once the database is usable (fake: migrated + seeded). Await before raw getDb reads. */
|
package/src/server-lib/invite.ts
CHANGED
|
@@ -35,7 +35,15 @@ export async function sendOrgInvite(input: {
|
|
|
35
35
|
/** Any absolute URL on this host; the accept link is built against its origin. */
|
|
36
36
|
baseUrl: string
|
|
37
37
|
}): Promise<Membership> {
|
|
38
|
-
|
|
38
|
+
// The adapter builds the link the invitee follows, from the app's accept page: only it knows what that page reads
|
|
39
|
+
// to find the invitation (the fake's `?invite=<id>`, Clerk's `__clerk_ticket`).
|
|
40
|
+
const acceptPageUrl = new URL(`/${input.inviter.locale}/accept-invite`, input.baseUrl).toString()
|
|
41
|
+
const { acceptUrl, ...membership } = await auth.createInvite({
|
|
42
|
+
email: input.email,
|
|
43
|
+
role: input.role,
|
|
44
|
+
orgSlug: input.orgSlug,
|
|
45
|
+
acceptPageUrl,
|
|
46
|
+
})
|
|
39
47
|
|
|
40
48
|
// Audit trail: the invite is the audited mutation — a Membership was created.
|
|
41
49
|
await recordAuditEvent(db, {
|
|
@@ -47,32 +55,32 @@ export async function sendOrgInvite(input: {
|
|
|
47
55
|
subjectId: membership.id,
|
|
48
56
|
})
|
|
49
57
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
58
|
+
// No link means the provider delivers the invitation itself; a mail of ours with no working link would only
|
|
59
|
+
// confuse the invitee.
|
|
60
|
+
if (acceptUrl !== null) {
|
|
61
|
+
// The invitee has no account (and so no locale) yet — the inviter's locale is the best available
|
|
62
|
+
// signal for the email copy (ADR-0008).
|
|
63
|
+
const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
|
|
64
|
+
// Deferred: the notification email is a post-response side effect — a slow mail provider must never
|
|
65
|
+
// add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
|
|
66
|
+
// Simulator events); real mode sends it via Next's after().
|
|
67
|
+
await deferAfterResponse('invite-email', () =>
|
|
68
|
+
sendTemplate(email, {
|
|
69
|
+
to: input.email,
|
|
70
|
+
subject: t('inviteSubject', { org: input.orgName }),
|
|
71
|
+
template: InviteEmail({
|
|
72
|
+
labels: {
|
|
73
|
+
preview: t('invitePreview', { org: input.orgName }),
|
|
74
|
+
heading: t('inviteHeading', { org: input.orgName }),
|
|
75
|
+
body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
|
|
76
|
+
button: t('inviteButton'),
|
|
77
|
+
linkFallback: t('inviteLinkFallback'),
|
|
78
|
+
},
|
|
79
|
+
acceptUrl,
|
|
80
|
+
}),
|
|
73
81
|
}),
|
|
74
|
-
|
|
75
|
-
|
|
82
|
+
)
|
|
83
|
+
}
|
|
76
84
|
await analytics.capture('org_invite_sent', { tenant: input.tenantSlug, org: input.orgSlug, role: input.role })
|
|
77
85
|
|
|
78
86
|
// Notification fan-out: tell the inviting team's OTHER admins that an invite went out. The invitee
|
package/src/testing/checks.json
CHANGED
|
@@ -10,6 +10,15 @@
|
|
|
10
10
|
"the app's own exemptions are well formed, collide with no framework entry, and are not stale"
|
|
11
11
|
]
|
|
12
12
|
},
|
|
13
|
+
{
|
|
14
|
+
"id": "real-auth-provider",
|
|
15
|
+
"runner": "unit",
|
|
16
|
+
"title": "real-mode auth forms sit under their provider",
|
|
17
|
+
"tests": [
|
|
18
|
+
"the app's src/app is really walked",
|
|
19
|
+
"every page that reaches a real auth form sits under a layout that reaches RealAuthProviders"
|
|
20
|
+
]
|
|
21
|
+
},
|
|
13
22
|
{
|
|
14
23
|
"id": "i18n-partition",
|
|
15
24
|
"runner": "unit",
|