@sssb/kit 0.4.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 +18 -2
- package/src/adapters/fake/data-dir.ts +32 -2
- package/src/adapters/fake/email.ts +2 -0
- package/src/adapters/real/accept-invite-form.tsx +32 -14
- package/src/adapters/real/analytics.ts +29 -2
- package/src/adapters/real/auth.ts +54 -18
- package/src/adapters/real/contract-postgres.ts +15 -11
- package/src/adapters/real/email.ts +2 -0
- 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/rds-data-codec.ts +88 -4
- package/src/adapters/real/rds-data-emulator.ts +12 -4
- package/src/adapters/real/sign-in-form.tsx +29 -13
- 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/db/jobs.ts +15 -6
- package/src/db/keyset.ts +8 -6
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/rls-coverage.ts +51 -17
- package/src/db/schedules.ts +9 -3
- 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 +20 -6
- 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/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/conformance/auth-provider.ts +17 -5
- package/src/testing/conformance/authz.ts +6 -2
- package/src/testing/conformance/i18n.ts +99 -5
- package/src/testing/conformance/suite.ts +63 -3
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
|
|
|
@@ -92,8 +92,17 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
92
92
|
release). The conformance suite's `authz-mutations` check reads each handler: a string, a
|
|
93
93
|
comment, a dead branch or a helper in another module does not count. Neither does a call whose denial cannot stop
|
|
94
94
|
the handler: in an `async` helper or a callback whose promise the handler neither awaits nor returns, in a callback
|
|
95
|
-
handed to a function the route file defines,
|
|
96
|
-
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.
|
|
97
106
|
- An exemption is an entry in the app's `authz-exemptions.mjs` (`{ files, prefixes }`, keys relative to
|
|
98
107
|
`src/app/api`), with a reason and a `mustMatch` gate. A mutating route outside `src/app/api` can match no
|
|
99
108
|
exemption.
|
|
@@ -111,7 +120,9 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
111
120
|
|
|
112
121
|
- Keep `src/sssb.conformance.test.ts` (SSSB's conformance suite) and `tests/contract/rls-contract.test.ts` (the
|
|
113
122
|
contract runner on real Postgres). Leave a check out only by a named opt-out with its reason,
|
|
114
|
-
`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.
|
|
115
126
|
- A test that needs a scratch directory calls `makeTestTmpDir()` or `makeTestTmpDirAsync()` from
|
|
116
127
|
`@sssb/tools/testing/tmp-dir`, never `mkdtemp` directly. A script that runs Vitest as a gate goes through
|
|
117
128
|
`sssb check-tmpdir-leak`.
|
|
@@ -127,7 +138,10 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
127
138
|
bypass for the ticker.
|
|
128
139
|
- The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
|
|
129
140
|
layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
|
|
130
|
-
imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
|
|
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.
|
|
131
145
|
- In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
|
|
132
146
|
server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
|
|
133
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 = {}
|
|
@@ -24,7 +24,11 @@ import { dispatchWebhook } from './webhook-dispatch'
|
|
|
24
24
|
export interface ScheduledTickResult {
|
|
25
25
|
/** Jobs spawned from due schedules. */
|
|
26
26
|
spawned: number
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Due schedules whose spawn failed. One that failed inside the spawn transaction is retried on the next tick (its
|
|
29
|
+
* next_run_at never advanced); one that failed after it committed (the audit write, the runner's start) is not:
|
|
30
|
+
* its job is already queued and the schedule has moved to its next slot (../db/schedules.ts, "Fault isolation").
|
|
31
|
+
*/
|
|
28
32
|
failed: number
|
|
29
33
|
/** What the delivery drain did (`runDueDeliveries`'s own result). */
|
|
30
34
|
deliveries: Awaited<ReturnType<typeof runDueDeliveries>>
|
|
@@ -65,6 +65,9 @@ export async function dispatchWebhook(input: WebhookDispatchInput): Promise<Webh
|
|
|
65
65
|
body: input.body,
|
|
66
66
|
signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
|
|
67
67
|
})
|
|
68
|
+
// The outcome is the status alone, so the body is never read: cancel it rather than leave the
|
|
69
|
+
// connection held open until garbage collection reclaims the unread stream (undici's behaviour).
|
|
70
|
+
await response.body?.cancel().catch(() => undefined)
|
|
68
71
|
return response.ok
|
|
69
72
|
? { delivered: true, status: response.status }
|
|
70
73
|
: { delivered: false, status: response.status, error: `HTTP ${response.status}` }
|
|
@@ -39,16 +39,21 @@ function signingKey(): string | null {
|
|
|
39
39
|
return isSimulated ? devWebhookSecret() : (process.env['MAILGUN_WEBHOOK_SIGNING_KEY'] ?? null)
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* token -> expiry epoch ms; a token is a replay if seen while still within the window. The expiry is
|
|
44
|
+
* the moment its SIGNATURE stops being fresh, not "tolerance from now": the timestamp may run up to the
|
|
45
|
+
* tolerance AHEAD of our clock (verifyMailgunSignature checks both directions), so a token remembered
|
|
46
|
+
* for only `now + tolerance` would be forgotten while a replay of it still verified.
|
|
47
|
+
*/
|
|
43
48
|
const seenTokens = new Map<string, number>()
|
|
44
49
|
|
|
45
|
-
function rememberToken(token: string, nowMs: number): boolean {
|
|
50
|
+
function rememberToken(token: string, nowMs: number, timestampMs: number): boolean {
|
|
46
51
|
// Prune expired entries first so the map can't grow unbounded across a long-lived process.
|
|
47
52
|
for (const [seen, expiry] of seenTokens) {
|
|
48
53
|
if (expiry <= nowMs) seenTokens.delete(seen)
|
|
49
54
|
}
|
|
50
55
|
if (seenTokens.has(token)) return false
|
|
51
|
-
seenTokens.set(token, nowMs + WEBHOOK_REPLAY_TOLERANCE_MS)
|
|
56
|
+
seenTokens.set(token, Math.max(nowMs, timestampMs) + WEBHOOK_REPLAY_TOLERANCE_MS)
|
|
52
57
|
return true
|
|
53
58
|
}
|
|
54
59
|
|
|
@@ -61,7 +66,17 @@ export function verifyMailgunWebhook(fields: MailgunSignatureFields, now: Date =
|
|
|
61
66
|
if (!key) throw new AuthRequiredError()
|
|
62
67
|
const result = verifyMailgunSignature({ ...fields, signingKey: key, toleranceMs: WEBHOOK_REPLAY_TOLERANCE_MS, now })
|
|
63
68
|
if (!result.ok) throw new AuthRequiredError()
|
|
64
|
-
if (!rememberToken(fields.token, now.getTime())) throw new AuthRequiredError()
|
|
69
|
+
if (!rememberToken(fields.token, now.getTime(), Number(fields.timestamp) * 1000)) throw new AuthRequiredError()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Forget a token whose request was verified but NOT processed: the route's handler threw or answered 5xx.
|
|
74
|
+
* The sender's retry of that message carries the same token, and refusing it as a replay would lose the
|
|
75
|
+
* message. A replay of an unprocessed message is a retry, not a second delivery, so forgetting it opens
|
|
76
|
+
* nothing the timestamp window does not already bound.
|
|
77
|
+
*/
|
|
78
|
+
export function forgetMailgunToken(token: string): void {
|
|
79
|
+
seenTokens.delete(token)
|
|
65
80
|
}
|
|
66
81
|
|
|
67
82
|
/** Test-only: clear the replay set between cases so a reused fixture token doesn't leak across tests. */
|
|
@@ -14,7 +14,7 @@ import type { CheckImpl } from './types'
|
|
|
14
14
|
* How it reads the app: from each of Next's rendering files under `src/app` (`page`, `layout`, `template`, `default`,
|
|
15
15
|
* `not-found`, `error`, `global-error`, `loading`, `forbidden`, `unauthorized`), it follows the app's own imports
|
|
16
16
|
* (a relative path, `@/` for the app's `src/`, `@sssb/app-config/` for its seam) through import and export
|
|
17
|
-
* declarations and `import()` of a literal, and notes whether each file reaches a form or the provider. An import that
|
|
17
|
+
* declarations, `import x = require()`, and `import()` or `require()` of a literal, and notes whether each file reaches a form or the provider. An import that
|
|
18
18
|
* loads nothing (`import type`, or every name marked `type`) is not followed, nor is a specifier it cannot resolve to
|
|
19
19
|
* a file; a comment or a string naming a module does not count. A rendering file that reaches a form passes when it
|
|
20
20
|
* is wrapped by one that reaches the provider: a layout or template that is itself that file, or one in a directory
|
|
@@ -22,8 +22,9 @@ import type { CheckImpl } from './types'
|
|
|
22
22
|
* inside neither. `global-error` replaces the root layout, so only it can wrap itself.
|
|
23
23
|
*
|
|
24
24
|
* What it does not read: whether an import runs (an `isSimulated` branch is how it should be written, and a dead one
|
|
25
|
-
* would pass), a path alias other than those two,
|
|
26
|
-
* authorization scan does not
|
|
25
|
+
* would pass), a path alias other than those two, anything behind a symbolic link, which it does not follow, as the
|
|
26
|
+
* authorization scan does not, and a rendering file named for a custom `pageExtensions` (`page.page.tsx`), which it
|
|
27
|
+
* does not find. It parses each file once and settles what every file reaches in one pass over the
|
|
27
28
|
* graph, so its cost grows with the app's size, not with its pages times its modules.
|
|
28
29
|
*/
|
|
29
30
|
|
|
@@ -100,7 +101,10 @@ function typeOnly(node: ts.ImportDeclaration | ts.ExportDeclaration): boolean {
|
|
|
100
101
|
)
|
|
101
102
|
}
|
|
102
103
|
|
|
103
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* The specifiers `file` loads at run time: value import and export declarations, `import x = require()` (not
|
|
106
|
+
* `import type`), and `import()` or `require()` of a literal.
|
|
107
|
+
*/
|
|
104
108
|
function loadedSpecifiers(file: string): string[] {
|
|
105
109
|
const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true)
|
|
106
110
|
const found: string[] = []
|
|
@@ -108,9 +112,17 @@ function loadedSpecifiers(file: string): string[] {
|
|
|
108
112
|
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
|
109
113
|
const specifier = node.moduleSpecifier
|
|
110
114
|
if (specifier && ts.isStringLiteral(specifier) && !typeOnly(node)) found.push(specifier.text)
|
|
115
|
+
} else if (
|
|
116
|
+
ts.isImportEqualsDeclaration(node) &&
|
|
117
|
+
!node.isTypeOnly &&
|
|
118
|
+
ts.isExternalModuleReference(node.moduleReference) &&
|
|
119
|
+
ts.isStringLiteralLike(node.moduleReference.expression)
|
|
120
|
+
) {
|
|
121
|
+
found.push(node.moduleReference.expression.text)
|
|
111
122
|
} else if (
|
|
112
123
|
ts.isCallExpression(node) &&
|
|
113
|
-
node.expression.kind === ts.SyntaxKind.ImportKeyword
|
|
124
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
125
|
+
(ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
|
|
114
126
|
node.arguments[0] &&
|
|
115
127
|
ts.isStringLiteralLike(node.arguments[0])
|
|
116
128
|
) {
|
|
@@ -9,10 +9,14 @@ import type { CheckContext, CheckImpl } from './types'
|
|
|
9
9
|
* `route.ts` from anywhere there), and judges each exported mutating handler, read with the TypeScript parser, never
|
|
10
10
|
* the file's text: the handler must reach `authorize` on its own path, or its route must have a justified exemption
|
|
11
11
|
* (the framework's, ../../authz/route-policy.ts, or the app's own `authz-exemptions.mjs`) and the handler must pass
|
|
12
|
-
* that exemption's gate.
|
|
12
|
+
* that exemption's gate. The same scan judges every Server Action under the app's `src` (each export of a
|
|
13
|
+
* `'use server'` file, each function whose body opens with `'use server'`) like a POST, with no exemption, and fails
|
|
14
|
+
* what Next serves and it cannot read: a `pages/api` or root-level `app/` directory, a `route.<ext>` it does not
|
|
15
|
+
* parse, a `'use server'` file outside `src`.
|
|
13
16
|
*
|
|
14
17
|
* The test names are fixed (doctor computes them), so every failing handler is reported in ONE assertion, one line
|
|
15
|
-
* each
|
|
18
|
+
* each: `<app>: <rel> <VERB> …why` for a handler, `<app>: <rel> Server Action \`name\` …why` for an action, and a
|
|
19
|
+
* plain sentence for a directory or file the scan cannot read.
|
|
16
20
|
*/
|
|
17
21
|
const scans = new Map<string, Promise<AppScan>>()
|
|
18
22
|
const scanOf = ({ appDir }: CheckContext): Promise<AppScan> => {
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isDateElement,
|
|
3
|
+
isLiteralElement,
|
|
4
|
+
isNumberElement,
|
|
5
|
+
isPluralElement,
|
|
6
|
+
isPoundElement,
|
|
7
|
+
isSelectElement,
|
|
8
|
+
isTagElement,
|
|
9
|
+
isTimeElement,
|
|
10
|
+
type MessageFormatElement,
|
|
11
|
+
parse,
|
|
12
|
+
} from '@formatjs/icu-messageformat-parser'
|
|
1
13
|
import { expect } from 'vitest'
|
|
2
14
|
import enFramework from '../../i18n/messages/en.json'
|
|
3
15
|
import esFramework from '../../i18n/messages/es.json'
|
|
@@ -46,22 +58,104 @@ function flatten(tree: MessageTree, prefix = ''): Map<string, string> {
|
|
|
46
58
|
return out
|
|
47
59
|
}
|
|
48
60
|
|
|
49
|
-
|
|
61
|
+
/**
|
|
62
|
+
* What a translation of `message` must keep, as sorted strings: each argument with its type (`count:plural`,
|
|
63
|
+
* `name:argument`, `d:date`), including arguments nested inside a plural or select branch, and each tag (`<b>`).
|
|
64
|
+
* Branch text is text, a quoted `'{literal}'` is text, and branch keys are not compared (Spanish and English need
|
|
65
|
+
* different plural categories). It is a set: an argument used in one branch of one side and in every branch of the
|
|
66
|
+
* other matches. Throws when `message` is not ICU.
|
|
67
|
+
*/
|
|
68
|
+
export function icuSignature(message: string): string[] {
|
|
69
|
+
const found = new Set<string>()
|
|
70
|
+
const visit = (elements: MessageFormatElement[]): void => {
|
|
71
|
+
for (const element of elements) {
|
|
72
|
+
if (isLiteralElement(element) || isPoundElement(element)) continue
|
|
73
|
+
if (isTagElement(element)) {
|
|
74
|
+
found.add(`<${element.value}>`)
|
|
75
|
+
visit(element.children)
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
const type = isPluralElement(element)
|
|
79
|
+
? element.pluralType === 'ordinal'
|
|
80
|
+
? 'selectordinal'
|
|
81
|
+
: 'plural'
|
|
82
|
+
: isSelectElement(element)
|
|
83
|
+
? 'select'
|
|
84
|
+
: isNumberElement(element)
|
|
85
|
+
? 'number'
|
|
86
|
+
: isDateElement(element)
|
|
87
|
+
? 'date'
|
|
88
|
+
: isTimeElement(element)
|
|
89
|
+
? 'time'
|
|
90
|
+
: 'argument'
|
|
91
|
+
found.add(`${element.value}:${type}`)
|
|
92
|
+
if (isPluralElement(element) || isSelectElement(element)) {
|
|
93
|
+
for (const option of Object.values(element.options)) visit(option.value)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
visit(parse(message))
|
|
98
|
+
return [...found].sort()
|
|
99
|
+
}
|
|
50
100
|
|
|
51
|
-
function
|
|
101
|
+
function signatureOrError(message: string): string[] | string {
|
|
102
|
+
try {
|
|
103
|
+
return icuSignature(message)
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return `does not parse as ICU (${(error as Error).message})`
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The `{name}` placeholder names in a value that is not ICU, sorted: what a raw pair (a value read with next-intl's
|
|
111
|
+
* `t.raw()`, such as markup, JSON or a template) must still agree on.
|
|
112
|
+
*/
|
|
113
|
+
const rawPlaceholderNames = (value: string) => [...new Set([...value.matchAll(/\{(\w+)/g)].map((m) => m[1]!))].sort()
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Every way `es` is not a faithful counterpart of `en`: a key on one side only, or a message whose signature differs.
|
|
117
|
+
* A pair that parses as ICU on NEITHER side is a raw value (`t.raw()`), compared by its `{name}` placeholder names
|
|
118
|
+
* only; a pair that parses on exactly one side fails, naming the side that does not.
|
|
119
|
+
*/
|
|
120
|
+
export function parityProblems(en: MessageTree, es: MessageTree): string[] {
|
|
52
121
|
const enFlat = flatten(en)
|
|
53
122
|
const esFlat = flatten(es)
|
|
54
|
-
|
|
123
|
+
const problems: string[] = []
|
|
124
|
+
for (const key of enFlat.keys()) if (!esFlat.has(key)) problems.push(`${key}: missing from es`)
|
|
125
|
+
for (const key of esFlat.keys()) if (!enFlat.has(key)) problems.push(`${key}: missing from en`)
|
|
55
126
|
for (const [key, enMsg] of enFlat) {
|
|
56
127
|
const esMsg = esFlat.get(key)
|
|
57
|
-
if (esMsg
|
|
128
|
+
if (esMsg === undefined) continue
|
|
129
|
+
const enSig = signatureOrError(enMsg)
|
|
130
|
+
const esSig = signatureOrError(esMsg)
|
|
131
|
+
if (typeof enSig === 'string' && typeof esSig === 'string') {
|
|
132
|
+
const enRaw = rawPlaceholderNames(enMsg)
|
|
133
|
+
const esRaw = rawPlaceholderNames(esMsg)
|
|
134
|
+
if (enRaw.join() !== esRaw.join()) {
|
|
135
|
+
problems.push(
|
|
136
|
+
`${key}: a raw value (ICU on neither side) with en {${enRaw.join(', ')}}, es {${esRaw.join(', ')}}`,
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
} else if (typeof enSig === 'string') {
|
|
140
|
+
problems.push(`${key}: en ${enSig}, while es parses`)
|
|
141
|
+
} else if (typeof esSig === 'string') {
|
|
142
|
+
problems.push(`${key}: es ${esSig}, while en parses`)
|
|
143
|
+
} else if (enSig.join() !== esSig.join()) {
|
|
144
|
+
problems.push(`${key}: en has [${enSig.join(', ')}], es has [${esSig.join(', ')}]`)
|
|
145
|
+
}
|
|
58
146
|
}
|
|
147
|
+
return problems
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function expectParity(en: MessageTree, es: MessageTree): void {
|
|
151
|
+
expect(parityProblems(en, es)).toEqual([])
|
|
59
152
|
}
|
|
60
153
|
|
|
61
154
|
/**
|
|
62
155
|
* `i18n-parity`: en/es parity over the MERGED catalog (the framework half + the app half, which arrives through the
|
|
63
156
|
* ADR-0012 seam). The catalogs are physically split, but what ships to the user is the merge — so that is what must
|
|
64
|
-
* stay key- and placeholder-identical
|
|
157
|
+
* stay key- and placeholder-identical: the same arguments, each of the same type (inside plural and select
|
|
158
|
+
* branches too), and the same tags (`icuSignature`). A raw value, ICU on neither side, keeps its `{name}` placeholders. The framework half is checked on its own too, so the package carries a
|
|
65
159
|
* truthful guarantee independent of whatever app consumes it.
|
|
66
160
|
*/
|
|
67
161
|
export const i18nParity: CheckImpl = {
|