@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.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/email-message.ts +30 -0
- package/src/adapters/fake/analytics.ts +1 -1
- package/src/adapters/fake/auth.ts +31 -4
- package/src/adapters/fake/data-dir.ts +32 -2
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/fake/email.ts +2 -0
- package/src/adapters/real/absent.ts +13 -0
- package/src/adapters/real/accept-invite-form.tsx +86 -21
- package/src/adapters/real/analytics.ts +30 -3
- package/src/adapters/real/auth.ts +82 -20
- package/src/adapters/real/contract-postgres.ts +15 -11
- package/src/adapters/real/db-port.ts +3 -2
- package/src/adapters/real/email.ts +2 -0
- package/src/adapters/real/index.ts +49 -12
- package/src/adapters/real/jobs-in-process.ts +32 -14
- package/src/adapters/real/jobs.ts +6 -3
- package/src/adapters/real/migrate-handler.ts +3 -1
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +35 -1
- package/src/adapters/real/rds-data-codec.ts +88 -4
- package/src/adapters/real/rds-data-emulator.ts +12 -4
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/sign-in-form.tsx +29 -13
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/authz/app-exemptions.ts +79 -9
- package/src/authz/route-scan.ts +626 -55
- package/src/components/auth/accept-invite-screen.tsx +5 -1
- package/src/components/auth/people-picker.tsx +20 -2
- package/src/components/profile-screen.tsx +27 -2
- package/src/core/inbound-email.ts +41 -6
- 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 +19 -9
- package/src/db/keyset.ts +19 -30
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/notifications.ts +2 -2
- package/src/db/rls-coverage.ts +51 -17
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +11 -4
- package/src/db/webhooks.ts +4 -4
- package/src/demo-static/actor-drivers.ts +8 -2
- package/src/demo-static/email-html.ts +9 -0
- package/src/demo-static/tour/use-tours.tsx +8 -2
- package/src/demo-static/world.ts +76 -37
- package/src/email/send.ts +6 -2
- package/src/guide.md +26 -7
- package/src/i18n/messages/en.json +3 -0
- package/src/i18n/messages/es.json +3 -0
- package/src/i18n/messages.ts +3 -2
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/server-lib/scheduled-tick.ts +5 -1
- package/src/server-lib/webhook-dispatch.ts +3 -0
- package/src/service-auth/mailgun.ts +19 -4
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +308 -0
- package/src/testing/conformance/authz.ts +6 -2
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/i18n.ts +99 -5
- package/src/testing/conformance/suite.ts +65 -3
- package/src/testing/contract.ts +6 -4
|
@@ -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). */
|
|
@@ -37,9 +38,15 @@ const MAX_COALESCE = 100_000
|
|
|
37
38
|
* skipped period. jobs.start() runs only AFTER that transaction commits, exactly as submitJob does, so
|
|
38
39
|
* a handler never observes a job — or a schedule state — that isn't durable yet.
|
|
39
40
|
*
|
|
40
|
-
* FAULT ISOLATION. One bad row
|
|
41
|
-
*
|
|
42
|
-
*
|
|
41
|
+
* FAULT ISOLATION. One bad row must not stall every other schedule: each schedule drains inside its
|
|
42
|
+
* own try/catch, counted in `failed`. What a failure leaves depends on where it happens. A failure
|
|
43
|
+
* INSIDE the transaction (a malformed spec that parseScheduleSpec rejects, a failed insert) rolls it
|
|
44
|
+
* back, so next_run_at never advanced and the next tick tries the row again. A failure AFTER it
|
|
45
|
+
* commits (the audit insert, or jobs.start()) is NOT retried: the job row is already `queued` and the
|
|
46
|
+
* schedule has already moved on to its next slot, so that period's run is not started by this code.
|
|
47
|
+
* Retrying would make the spawn at-least-once for handlers written to run at most once. The job left
|
|
48
|
+
* `queued` is the runner's to deal with: the in-process runner's sweep fails a job left queued too
|
|
49
|
+
* long; under any other runner it stays queued.
|
|
43
50
|
*/
|
|
44
51
|
export async function runDueSchedules(
|
|
45
52
|
db: DbPort,
|
|
@@ -87,7 +94,7 @@ async function drainOne(
|
|
|
87
94
|
.selectFrom('job_schedules')
|
|
88
95
|
.select(['enabled', 'spec', 'kind', 'org_id', 'next_run_at'])
|
|
89
96
|
.where('id', '=', schedule.id)
|
|
90
|
-
.
|
|
97
|
+
.$call(family.lockRow)
|
|
91
98
|
.executeTakeFirst()
|
|
92
99
|
// Re-check under the lock: enabled may have flipped, or a concurrent tick may have already
|
|
93
100
|
// 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')
|
|
@@ -32,6 +32,10 @@ interface DemoDriverDeps {
|
|
|
32
32
|
jobsRef: RefObject<DemoJob[]>
|
|
33
33
|
setJobs: Dispatch<SetStateAction<DemoJob[]>>
|
|
34
34
|
log: ActorLog
|
|
35
|
+
/** What the world emits once a job this driver completed is completed, as the server route this driver stands
|
|
36
|
+
* in for does: the service actor's, the job.status_changed webhook; the builder's, the webhook and the admin
|
|
37
|
+
* notification. */
|
|
38
|
+
onCompleted: (job: DemoJob) => void
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
/** The one team a service actor is scoped to — the twin of its minted token's tenant/org claims. */
|
|
@@ -41,7 +45,7 @@ export interface DemoServiceScope {
|
|
|
41
45
|
}
|
|
42
46
|
|
|
43
47
|
export function createDemoServiceDriver(
|
|
44
|
-
{ jobsRef, setJobs, log }: DemoDriverDeps,
|
|
48
|
+
{ jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
|
|
45
49
|
scope: DemoServiceScope,
|
|
46
50
|
): ServiceDriver {
|
|
47
51
|
return {
|
|
@@ -95,13 +99,14 @@ export function createDemoServiceDriver(
|
|
|
95
99
|
: j,
|
|
96
100
|
),
|
|
97
101
|
)
|
|
102
|
+
onCompleted(job)
|
|
98
103
|
return 'applied'
|
|
99
104
|
},
|
|
100
105
|
}
|
|
101
106
|
}
|
|
102
107
|
|
|
103
108
|
export function createDemoBuilderDriver(
|
|
104
|
-
{ jobsRef, setJobs, log }: DemoDriverDeps,
|
|
109
|
+
{ jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
|
|
105
110
|
/** Teams already served by a dedicated service actor (@sssb/app-config/jobs' serviceManagedOrgSlugs) —
|
|
106
111
|
* excluded so the two actors' job pools stay disjoint, exactly like listPendingBuilds. */
|
|
107
112
|
serviceManagedOrgSlugs: readonly string[],
|
|
@@ -155,6 +160,7 @@ export function createDemoBuilderDriver(
|
|
|
155
160
|
return { ...j, status: 'completed', timeline }
|
|
156
161
|
}),
|
|
157
162
|
)
|
|
163
|
+
onCompleted(job)
|
|
158
164
|
return 'applied'
|
|
159
165
|
},
|
|
160
166
|
}
|
|
@@ -12,6 +12,15 @@ function escapeHtml(value: string): string {
|
|
|
12
12
|
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Twin of the server's notification email (../server-lib/notify.ts): a heading, a body line and the footer. The
|
|
17
|
+
* values are already-translated copy, and that copy interpolates what people typed (an invited address, an app's
|
|
18
|
+
* subject line), so each is escaped.
|
|
19
|
+
*/
|
|
20
|
+
export function buildNotificationEmailHtml(labels: { title: string; body: string; footer: string }): string {
|
|
21
|
+
return `<h2>${escapeHtml(labels.title)}</h2><p>${escapeHtml(labels.body)}</p><p>${escapeHtml(labels.footer)}</p>`
|
|
22
|
+
}
|
|
23
|
+
|
|
15
24
|
/** Twin of ../email/templates/invite-email.tsx. */
|
|
16
25
|
export function buildInviteEmailHtml(
|
|
17
26
|
labels: { heading: string; body: string; button: string; linkFallback: string },
|
|
@@ -105,8 +105,9 @@ export function useTours(
|
|
|
105
105
|
// Where the story is meant to be standing: captured when a step's entry script finishes, and the
|
|
106
106
|
// place "Back to the tour" returns to.
|
|
107
107
|
const stepLocationRef = useRef<string | null>(null)
|
|
108
|
-
// Bumped on every goto so a script that finishes AFTER the viewer pressed Back cannot light that
|
|
109
|
-
// abandoned step's spotlight on the screen they are now looking at
|
|
108
|
+
// Bumped on every goto and end, so a script that finishes AFTER the viewer pressed Back cannot light that
|
|
109
|
+
// abandoned step's spotlight on the screen they are now looking at, and a Next whose advance script was
|
|
110
|
+
// running when the viewer pressed Exit cannot re-open the tour they just closed.
|
|
110
111
|
const runTokenRef = useRef(0)
|
|
111
112
|
|
|
112
113
|
const tour = appTours.find((candidate) => candidate.id === activeId) ?? null
|
|
@@ -155,6 +156,7 @@ export function useTours(
|
|
|
155
156
|
}
|
|
156
157
|
|
|
157
158
|
function end(stepsRun: number) {
|
|
159
|
+
runTokenRef.current += 1
|
|
158
160
|
cancelScript()
|
|
159
161
|
hideCursor()
|
|
160
162
|
writeResumeMarker(null)
|
|
@@ -190,12 +192,14 @@ export function useTours(
|
|
|
190
192
|
async function next() {
|
|
191
193
|
if (advancing || !tour) return
|
|
192
194
|
const step = tour.steps[idx]
|
|
195
|
+
const token = runTokenRef.current
|
|
193
196
|
setAdvancing(true)
|
|
194
197
|
// Next DURING an entry script fast-forwards it to completion rather than cancelling it: a
|
|
195
198
|
// cancelled script leaves a half-typed form on screen, which reads as a bug.
|
|
196
199
|
if (isDriving()) {
|
|
197
200
|
requestFastForward()
|
|
198
201
|
while (isDriving()) await new Promise((resolve) => setTimeout(resolve, 60))
|
|
202
|
+
if (runTokenRef.current !== token) return
|
|
199
203
|
}
|
|
200
204
|
// Move the resume marker BEFORE the advance script runs. Every submission lives in `advance`,
|
|
201
205
|
// and on a server host some of them reload the page (a feature flag, a person switch) — writing
|
|
@@ -206,6 +210,8 @@ export function useTours(
|
|
|
206
210
|
setSpotlight(null) // the vignette lifts before the cursor clicks through it
|
|
207
211
|
await runScript(step.advance, addMiss)
|
|
208
212
|
}
|
|
213
|
+
// Exit (or anything else that moved the tour) while this awaited: that already settled the tour.
|
|
214
|
+
if (runTokenRef.current !== token) return
|
|
209
215
|
setAdvancing(false)
|
|
210
216
|
if (idx >= tour.steps.length - 1) end(tour.steps.length)
|
|
211
217
|
else goto(tour.id, idx + 1)
|
package/src/demo-static/world.ts
CHANGED
|
@@ -70,7 +70,7 @@ import type {
|
|
|
70
70
|
StaticPresetOperationContext,
|
|
71
71
|
StaticPresetOperationHandler,
|
|
72
72
|
} from './contracts'
|
|
73
|
-
import { buildDigestEmailHtml, buildInviteEmailHtml } from './email-html'
|
|
73
|
+
import { buildDigestEmailHtml, buildInviteEmailHtml, buildNotificationEmailHtml } from './email-html'
|
|
74
74
|
import { go, useHashRoute } from './hash-route'
|
|
75
75
|
import type {
|
|
76
76
|
DemoAcceptance,
|
|
@@ -181,12 +181,13 @@ function makeSeedAcceptances(): DemoAcceptance[] {
|
|
|
181
181
|
* meant the `file://` demo silently showed a different schedule list from `pnpm dev` the moment the
|
|
182
182
|
* app seeded a second one.
|
|
183
183
|
*/
|
|
184
|
-
|
|
184
|
+
/** The seeded schedules, each due at its first boundary after `worldNow` (the world clock's now, not real now). */
|
|
185
|
+
function makeSeedSchedules(worldNow: Date): ScheduleRowLike[] {
|
|
185
186
|
return seedJobSchedules.map((schedule, index) => ({
|
|
186
187
|
id: `seed-schedule-${index}`,
|
|
187
188
|
kind: schedule.kind,
|
|
188
189
|
spec: schedule.spec,
|
|
189
|
-
nextRunAt: computeNextRunAt(schedule.spec,
|
|
190
|
+
nextRunAt: computeNextRunAt(schedule.spec, worldNow).toISOString(),
|
|
190
191
|
enabled: true,
|
|
191
192
|
tenantSlug: schedule.tenantSlug,
|
|
192
193
|
orgSlug: schedule.orgSlug,
|
|
@@ -270,7 +271,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
270
271
|
const [smsMessages, setSmsMessages] = useState<SmsMessageRow[]>([])
|
|
271
272
|
const [notifPrefs, setNotifPrefs] = useState<Record<string, NotificationPrefRow[]>>({})
|
|
272
273
|
// Twin of the job_schedules table — seeded with the weekly research digest.
|
|
273
|
-
const [schedules, setSchedules] = useState<ScheduleRowLike[]>(() => makeSeedSchedules())
|
|
274
|
+
const [schedules, setSchedules] = useState<ScheduleRowLike[]>(() => makeSeedSchedules(new Date()))
|
|
274
275
|
// Twins of the agreements + agreement_acceptances tables — the access-gate worked example.
|
|
275
276
|
const [agreements, setAgreements] = useState<DemoAgreement[]>(() => makeSeedAgreements())
|
|
276
277
|
const [acceptances, setAcceptances] = useState<DemoAcceptance[]>(() => makeSeedAcceptances())
|
|
@@ -433,10 +434,11 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
433
434
|
const c = (key: string, values?: Record<string, string>) =>
|
|
434
435
|
tRoot(`${copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE}.${key}`, values)
|
|
435
436
|
if (channels.includes('email')) {
|
|
436
|
-
const html =
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
437
|
+
const html = buildNotificationEmailHtml({
|
|
438
|
+
title: c(copy.titleKey, copy.values),
|
|
439
|
+
body: c(copy.bodyKey, copy.values),
|
|
440
|
+
footer: tNotifications('emailFooter'),
|
|
441
|
+
})
|
|
440
442
|
setEmails((prev) => [
|
|
441
443
|
{
|
|
442
444
|
id: `email-${prev.length}`,
|
|
@@ -519,12 +521,19 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
519
521
|
// ── Outbound webhooks ─────────────────────────────────────────────────────────────────────────
|
|
520
522
|
|
|
521
523
|
/** Twin of enqueueWebhookEvent: fan an event to a pending delivery per matching enabled endpoint in
|
|
522
|
-
*
|
|
523
|
-
function
|
|
524
|
+
* `scope`'s org (endpoints are org-scoped). next_attempt is world-now, so a drain fires it at once. */
|
|
525
|
+
function enqueueWebhookFor(
|
|
526
|
+
scope: { tenantSlug: string; orgSlug: string },
|
|
527
|
+
kind: WebhookEventKind,
|
|
528
|
+
payload: WebhookEventPayload,
|
|
529
|
+
) {
|
|
524
530
|
const worldNowMs = mountedAtMs + clockOffsetMs
|
|
525
531
|
const matching = endpoints.filter(
|
|
526
532
|
(e) =>
|
|
527
|
-
e.tenantSlug ===
|
|
533
|
+
e.tenantSlug === scope.tenantSlug &&
|
|
534
|
+
e.orgSlug === scope.orgSlug &&
|
|
535
|
+
e.enabled &&
|
|
536
|
+
e.eventKinds.includes(kind),
|
|
528
537
|
)
|
|
529
538
|
if (matching.length === 0) return
|
|
530
539
|
const created: DemoDelivery[] = matching.map((endpoint) => ({
|
|
@@ -546,6 +555,35 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
546
555
|
setDeliveries((prev) => [...created, ...prev])
|
|
547
556
|
}
|
|
548
557
|
|
|
558
|
+
/** An app's own mutation emits for the org it is acting in: the active one, as the real routes' session is. */
|
|
559
|
+
function enqueueWebhook(kind: WebhookEventKind, payload: WebhookEventPayload) {
|
|
560
|
+
enqueueWebhookFor({ tenantSlug: tenant.slug, orgSlug: activeOrgSlug }, kind, payload)
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* The webhook half of a job's terminal hop, the twin of what the server's recordJobStatus emits: the
|
|
565
|
+
* job.status_changed webhook to the JOB's org (not the viewer's); an org-less job emits none. A service actor's
|
|
566
|
+
* completion takes only this half, as its server route calls recordJobStatus alone.
|
|
567
|
+
*/
|
|
568
|
+
function emitJobWebhook(job: { id: string; kind: string; tenantSlug: string; orgSlug: string | null }) {
|
|
569
|
+
if (job.orgSlug === null) return
|
|
570
|
+
enqueueWebhookFor({ tenantSlug: job.tenantSlug, orgSlug: job.orgSlug }, 'job.status_changed', {
|
|
571
|
+
jobId: job.id,
|
|
572
|
+
jobKind: job.kind,
|
|
573
|
+
status: 'completed',
|
|
574
|
+
orgId: job.orgSlug,
|
|
575
|
+
})
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* A job's whole terminal hop: the webhook, then the admin notification, as the in-process runner, the fake jobs
|
|
580
|
+
* adapter and the builder's completion webhook do. startJob, Run pending and the builder actor take it.
|
|
581
|
+
*/
|
|
582
|
+
function emitJobTerminal(job: { id: string; kind: string; tenantSlug: string; orgSlug: string | null }) {
|
|
583
|
+
emitJobWebhook(job)
|
|
584
|
+
notifyJobTerminal(job)
|
|
585
|
+
}
|
|
586
|
+
|
|
549
587
|
/** Twin of runDueDeliveries: attempt each due pending/failed delivery, signing the envelope with the
|
|
550
588
|
* REAL core signer; a toggled-failing endpoint fails and re-arms on the SAME backoff the server
|
|
551
589
|
* uses, marking 'dead' at MAX_DELIVERY_ATTEMPTS. Reads current state from the closure (the house
|
|
@@ -633,15 +671,9 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
633
671
|
}
|
|
634
672
|
setJobs((prev) => [job, ...prev])
|
|
635
673
|
// Held jobs stay queued (no terminal transition), so they emit later — from the Run-pending
|
|
636
|
-
// step below, or from an actor
|
|
674
|
+
// step below, or from an actor completing them.
|
|
637
675
|
if (held) return
|
|
638
|
-
|
|
639
|
-
jobId: base.id,
|
|
640
|
-
jobKind: kind,
|
|
641
|
-
status: 'completed',
|
|
642
|
-
orgId: activeOrgSlug,
|
|
643
|
-
})
|
|
644
|
-
notifyJobTerminal(job)
|
|
676
|
+
emitJobTerminal(job)
|
|
645
677
|
}
|
|
646
678
|
|
|
647
679
|
/**
|
|
@@ -666,20 +698,8 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
666
698
|
}
|
|
667
699
|
}),
|
|
668
700
|
)
|
|
669
|
-
for
|
|
670
|
-
|
|
671
|
-
// server's recordJobStatus does: the webhook first, then the admin notification (both
|
|
672
|
-
// skip an org-less job, as notifyJobTerminal already does).
|
|
673
|
-
if (job.orgSlug !== null) {
|
|
674
|
-
enqueueWebhook('job.status_changed', {
|
|
675
|
-
jobId: job.id,
|
|
676
|
-
jobKind: job.kind,
|
|
677
|
-
status: 'completed',
|
|
678
|
-
orgId: job.orgSlug,
|
|
679
|
-
})
|
|
680
|
-
}
|
|
681
|
-
notifyJobTerminal(job)
|
|
682
|
-
}
|
|
701
|
+
// The same terminal hop startJob's non-held branch takes, for each job's own org.
|
|
702
|
+
for (const job of completing) emitJobTerminal(job)
|
|
683
703
|
pushNotice(tSimulator('noticeJobsRan', { count: completing.length }))
|
|
684
704
|
}
|
|
685
705
|
|
|
@@ -777,13 +797,27 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
777
797
|
|
|
778
798
|
// The actor drivers read/write jobs through the stable ref + setter, so these factories never need
|
|
779
799
|
// to change identity — an actor's tick closure can be rebuilt freely without restarting its loop.
|
|
800
|
+
// A completed job's terminal hop reads the CURRENT endpoints and preferences, so the drivers reach it through a
|
|
801
|
+
// ref that every render points at this render's emitters.
|
|
802
|
+
const jobCompletedRef = useRef({ webhook: emitJobWebhook, terminal: emitJobTerminal })
|
|
803
|
+
useEffect(() => {
|
|
804
|
+
jobCompletedRef.current = { webhook: emitJobWebhook, terminal: emitJobTerminal }
|
|
805
|
+
})
|
|
780
806
|
const serviceDriver = useCallback(
|
|
781
|
-
(scope: DemoServiceScope, log: ActorLog) =>
|
|
807
|
+
(scope: DemoServiceScope, log: ActorLog) =>
|
|
808
|
+
// The service route (POST /api/service/jobs/[id]/status) emits the webhook and notifies no one.
|
|
809
|
+
createDemoServiceDriver(
|
|
810
|
+
{ jobsRef, setJobs, log, onCompleted: (job) => jobCompletedRef.current.webhook(job) },
|
|
811
|
+
scope,
|
|
812
|
+
),
|
|
782
813
|
[],
|
|
783
814
|
)
|
|
784
815
|
const builderDriver = useCallback(
|
|
785
816
|
(serviceManagedOrgSlugs: readonly string[], log: ActorLog) =>
|
|
786
|
-
createDemoBuilderDriver(
|
|
817
|
+
createDemoBuilderDriver(
|
|
818
|
+
{ jobsRef, setJobs, log, onCompleted: (job) => jobCompletedRef.current.terminal(job) },
|
|
819
|
+
serviceManagedOrgSlugs,
|
|
820
|
+
),
|
|
787
821
|
[],
|
|
788
822
|
)
|
|
789
823
|
|
|
@@ -1104,7 +1138,10 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
1104
1138
|
|
|
1105
1139
|
function markMailSeen() {
|
|
1106
1140
|
if (!viewpoint) return
|
|
1107
|
-
|
|
1141
|
+
// World time, never behind real time: a digest the clock's Advance made is dated ahead, and an email stamped
|
|
1142
|
+
// with real now must still count as seen after the clock is reset.
|
|
1143
|
+
const seenAt = new Date(Date.now() + Math.max(0, clockOffsetMs)).toISOString()
|
|
1144
|
+
setMailSeenAt((prev) => ({ ...prev, [viewpoint]: seenAt }))
|
|
1108
1145
|
}
|
|
1109
1146
|
|
|
1110
1147
|
function openMailLink(href: string) {
|
|
@@ -1158,7 +1195,9 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
|
1158
1195
|
setNotifications([])
|
|
1159
1196
|
setSmsMessages([])
|
|
1160
1197
|
setNotifPrefs({})
|
|
1161
|
-
|
|
1198
|
+
// The clock goes back to its mount time below, so the schedules are reseeded from there: from real now, a
|
|
1199
|
+
// boundary between mount and reset would be skipped by the next Advance.
|
|
1200
|
+
setSchedules(makeSeedSchedules(new Date(mountedAtMs)))
|
|
1162
1201
|
setAgreements(makeSeedAgreements())
|
|
1163
1202
|
setAcceptances(makeSeedAcceptances())
|
|
1164
1203
|
setClockOffsetMs(0)
|
package/src/email/send.ts
CHANGED
|
@@ -2,11 +2,15 @@ import { render } from '@react-email/render'
|
|
|
2
2
|
import type { ReactElement } from 'react'
|
|
3
3
|
import type { EmailPort } from '../ports/email'
|
|
4
4
|
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Renders a react-email template to html+text and hands it to whichever email adapter is wired. A subject is often
|
|
7
|
+
* composed from data (an org's name), so each run of line breaks in it becomes one space here: the message is sent
|
|
8
|
+
* rather than refused by the port, which refuses a subject with a line break from a direct caller.
|
|
9
|
+
*/
|
|
6
10
|
export async function sendTemplate(
|
|
7
11
|
port: EmailPort,
|
|
8
12
|
options: { to: string; subject: string; template: ReactElement },
|
|
9
13
|
): Promise<void> {
|
|
10
14
|
const [html, text] = await Promise.all([render(options.template), render(options.template, { plainText: true })])
|
|
11
|
-
await port.send({ to: options.to, subject: options.subject, html, text })
|
|
15
|
+
await port.send({ to: options.to, subject: options.subject.replace(/[\r\n]+/g, ' '), html, text })
|
|
12
16
|
}
|
package/src/guide.md
CHANGED
|
@@ -10,8 +10,8 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
10
10
|
- The app extends the framework only through the `@sssb/app-config/*` seam, the modules in `src/app-config/`.
|
|
11
11
|
Register new subjects, jobs, event kinds, tables and migrations there. Never edit or patch a framework base union or
|
|
12
12
|
registry.
|
|
13
|
-
- Import `@sssb/kit` only by a published subpath, a key of its `exports` map
|
|
14
|
-
internal.
|
|
13
|
+
- Import `@sssb/kit` only by a published subpath, a key of its `exports` map, never by a path into the package
|
|
14
|
+
(`sssb/no-path-into-kit`). Everything else in the package is internal.
|
|
15
15
|
|
|
16
16
|
## Vendors, environment and parameters
|
|
17
17
|
|
|
@@ -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
|
|
|
@@ -87,8 +92,17 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
87
92
|
release). The conformance suite's `authz-mutations` check reads each handler: a string, a
|
|
88
93
|
comment, a dead branch or a helper in another module does not count. Neither does a call whose denial cannot stop
|
|
89
94
|
the handler: in an `async` helper or a callback whose promise the handler neither awaits nor returns, in a callback
|
|
90
|
-
handed to a function the route file defines,
|
|
91
|
-
authorizes, and let `withPortErrors`
|
|
95
|
+
handed to a function the route file defines, in a callback a timer, a listener, `after()` or a `.catch`/`.finally`
|
|
96
|
+
runs, or in a `try` whose `catch` does not rethrow. `await` the helper that authorizes, and let `withPortErrors`
|
|
97
|
+
answer the 403. Over many items, `await Promise.all(items.map(...))`; `Promise.allSettled` does not count, and
|
|
98
|
+
neither does a `.then(...)` chained after it.
|
|
99
|
+
- The check proves that a handler can reach `authorize(...)`, not that every path through it does, nor that it
|
|
100
|
+
comes before the mutation. Call it before the mutation and before any `try`, on a path every request takes: after
|
|
101
|
+
`auth.requireUser()` and the lookups that give it the org, never inside a condition or a loop.
|
|
102
|
+
- A Server Action is a POST endpoint: every export of a `'use server'` file, and every function whose body opens
|
|
103
|
+
with `'use server'`, calls `authorize(...)` by the same rules, lives under `src`, and can match no exemption. The
|
|
104
|
+
app serves routes from `src/app` alone: a root-level `app/` directory, a `pages/api` directory, or a file named
|
|
105
|
+
`route.<ext>` the check does not read (`route.mts`, a custom `pageExtensions`) fails it.
|
|
92
106
|
- An exemption is an entry in the app's `authz-exemptions.mjs` (`{ files, prefixes }`, keys relative to
|
|
93
107
|
`src/app/api`), with a reason and a `mustMatch` gate. A mutating route outside `src/app/api` can match no
|
|
94
108
|
exemption.
|
|
@@ -106,7 +120,9 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
106
120
|
|
|
107
121
|
- Keep `src/sssb.conformance.test.ts` (SSSB's conformance suite) and `tests/contract/rls-contract.test.ts` (the
|
|
108
122
|
contract runner on real Postgres). Leave a check out only by a named opt-out with its reason,
|
|
109
|
-
`optOut: { '<check id>': '<why>' }`. `sssb doctor` fails when the Vitest config does not run them.
|
|
123
|
+
`optOut: { '<check id>': '<why>' }`. `sssb doctor` fails when the Vitest config does not run them. The suite's
|
|
124
|
+
`appDir` is the app's own directory: it refuses, while the file is collected, one that is not the package the suite
|
|
125
|
+
file sits in.
|
|
110
126
|
- A test that needs a scratch directory calls `makeTestTmpDir()` or `makeTestTmpDirAsync()` from
|
|
111
127
|
`@sssb/tools/testing/tmp-dir`, never `mkdtemp` directly. A script that runs Vitest as a gate goes through
|
|
112
128
|
`sssb check-tmpdir-leak`.
|
|
@@ -122,7 +138,10 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
122
138
|
bypass for the ticker.
|
|
123
139
|
- The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
|
|
124
140
|
layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
|
|
125
|
-
imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
|
|
141
|
+
imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`. A simulated-only
|
|
142
|
+
POST route of your own (a dev sign-in, a Simulator route you add) also refuses a request that is not
|
|
143
|
+
`application/json`, right after that first line, as SSSB's handler does: a page on another site can send a form or
|
|
144
|
+
plain-text POST to a developer's machine without a preflight.
|
|
126
145
|
- In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
|
|
127
146
|
server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
|
|
128
147
|
`"sssb": { "port": { "name": "ledger", "default": 3800 } }`, and reads its override from `LEDGER_PORT`; its scripts and
|
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
"nameLabel": "Display name",
|
|
24
24
|
"localeLabel": "Language",
|
|
25
25
|
"saveButton": "Save",
|
|
26
|
+
"nameRequired": "Enter a display name.",
|
|
27
|
+
"nameTooLong": "A display name can be at most {max} characters.",
|
|
28
|
+
"saveError": "Your profile could not be saved. Your changes are still here: try again.",
|
|
26
29
|
"saved": "Saved.",
|
|
27
30
|
"profileSection": "Profile",
|
|
28
31
|
"securitySection": "Security",
|
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
"nameLabel": "Nombre para mostrar",
|
|
24
24
|
"localeLabel": "Idioma",
|
|
25
25
|
"saveButton": "Guardar",
|
|
26
|
+
"nameRequired": "Escribe un nombre para mostrar.",
|
|
27
|
+
"nameTooLong": "Un nombre para mostrar puede tener como máximo {max} caracteres.",
|
|
28
|
+
"saveError": "No se pudo guardar el perfil. Tus cambios siguen aquí: inténtalo de nuevo.",
|
|
26
29
|
"saved": "Guardado.",
|
|
27
30
|
"profileSection": "Perfil",
|
|
28
31
|
"securitySection": "Seguridad",
|
package/src/i18n/messages.ts
CHANGED
|
@@ -13,8 +13,9 @@ export type MessageTree = { [key: string]: string | MessageTree }
|
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* Deep-merge catalogs, later trees winning per leaf. The framework/app namespaces are disjoint at the
|
|
16
|
-
* top level
|
|
17
|
-
*
|
|
16
|
+
* top level, and the conformance suite's `i18n-partition` check fails an app catalog that holds a framework
|
|
17
|
+
* namespace, so an app cannot override a framework string and nothing here ever overwrites. The merge is deep only
|
|
18
|
+
* so that it would stay correct if two trees ever shared a namespace.
|
|
18
19
|
*/
|
|
19
20
|
export function mergeMessages(...trees: MessageTree[]): MessageTree {
|
|
20
21
|
const out: MessageTree = {}
|
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. */
|