@sssb/kit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/email-message.ts +30 -0
  4. package/src/adapters/fake/analytics.ts +1 -1
  5. package/src/adapters/fake/auth.ts +31 -4
  6. package/src/adapters/fake/data-dir.ts +32 -2
  7. package/src/adapters/fake/db.ts +4 -2
  8. package/src/adapters/fake/email.ts +2 -0
  9. package/src/adapters/real/absent.ts +13 -0
  10. package/src/adapters/real/accept-invite-form.tsx +86 -21
  11. package/src/adapters/real/analytics.ts +30 -3
  12. package/src/adapters/real/auth.ts +82 -20
  13. package/src/adapters/real/contract-postgres.ts +15 -11
  14. package/src/adapters/real/db-port.ts +3 -2
  15. package/src/adapters/real/email.ts +2 -0
  16. package/src/adapters/real/index.ts +49 -12
  17. package/src/adapters/real/jobs-in-process.ts +32 -14
  18. package/src/adapters/real/jobs.ts +6 -3
  19. package/src/adapters/real/migrate-handler.ts +3 -1
  20. package/src/adapters/real/no-analytics.ts +17 -0
  21. package/src/adapters/real/optional-ports.ts +35 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/s3-storage.ts +7 -1
  25. package/src/adapters/real/sign-in-form.tsx +29 -13
  26. package/src/adapters/real/storage-settings.ts +37 -0
  27. package/src/adapters/real/storage.ts +65 -0
  28. package/src/authz/app-exemptions.ts +79 -9
  29. package/src/authz/route-scan.ts +626 -55
  30. package/src/components/auth/accept-invite-screen.tsx +5 -1
  31. package/src/components/auth/people-picker.tsx +20 -2
  32. package/src/components/profile-screen.tsx +27 -2
  33. package/src/core/inbound-email.ts +41 -6
  34. package/src/cutover/rows.json +13 -1
  35. package/src/db/audit.ts +2 -2
  36. package/src/db/family-suite.ts +42 -0
  37. package/src/db/family.ts +91 -0
  38. package/src/db/jobs.ts +19 -9
  39. package/src/db/keyset.ts +19 -30
  40. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  41. package/src/db/notifications.ts +2 -2
  42. package/src/db/rls-coverage.ts +51 -17
  43. package/src/db/rls-proof-runner.ts +3 -2
  44. package/src/db/schedules.ts +11 -4
  45. package/src/db/webhooks.ts +4 -4
  46. package/src/demo-static/actor-drivers.ts +8 -2
  47. package/src/demo-static/email-html.ts +9 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +76 -37
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +26 -7
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +21 -2
  56. package/src/ports/db.ts +19 -0
  57. package/src/server-lib/invite.ts +34 -26
  58. package/src/server-lib/scheduled-tick.ts +5 -1
  59. package/src/server-lib/webhook-dispatch.ts +3 -0
  60. package/src/service-auth/mailgun.ts +19 -4
  61. package/src/testing/checks.json +9 -0
  62. package/src/testing/conformance/auth-provider.ts +308 -0
  63. package/src/testing/conformance/authz.ts +6 -2
  64. package/src/testing/conformance/db.ts +6 -5
  65. package/src/testing/conformance/i18n.ts +99 -5
  66. package/src/testing/conformance/suite.ts +65 -3
  67. package/src/testing/contract.ts +6 -4
@@ -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
- const membership = await auth.createInvite({ email: input.email, role: input.role, orgSlug: input.orgSlug })
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
- const acceptUrl = new URL(
51
- `/${input.inviter.locale}/accept-invite?invite=${membership.id}`,
52
- input.baseUrl,
53
- ).toString()
54
- // The invitee has no account (and so no locale) yet — the inviter's locale is the best available
55
- // signal for the email copy (ADR-0008).
56
- const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
57
- // Deferred: the notification email is a post-response side effect — a slow mail provider must never
58
- // add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
59
- // Simulator events); real mode sends it via Next's after().
60
- await deferAfterResponse('invite-email', () =>
61
- sendTemplate(email, {
62
- to: input.email,
63
- subject: t('inviteSubject', { org: input.orgName }),
64
- template: InviteEmail({
65
- labels: {
66
- preview: t('invitePreview', { org: input.orgName }),
67
- heading: t('inviteHeading', { org: input.orgName }),
68
- body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
69
- button: t('inviteButton'),
70
- linkFallback: t('inviteLinkFallback'),
71
- },
72
- acceptUrl,
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
@@ -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
- /** Due schedules whose spawn failed (retried on the next tick). */
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
- /** token -> expiry epoch ms; a token is a replay if seen while still within the window. */
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. */
@@ -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",
@@ -0,0 +1,308 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript'
4
+ import { expect } from 'vitest'
5
+ import type { CheckImpl } from './types'
6
+
7
+ /**
8
+ * `real-auth-provider`: a page that renders one of SSSB's real-mode auth forms sits under a layout that mounts their
9
+ * provider. The forms (`@sssb/kit/adapters/real/sign-in-form`, `.../accept-invite-form`) call the auth vendor's client
10
+ * hooks, which throw outside its provider (`RealAuthProviders`, `@sssb/kit/adapters/real/providers`). In simulated mode
11
+ * neither the form nor the provider loads, so nothing but real mode shows the gap: a real sign-in page that fails to
12
+ * render. SSSB's own starter once shipped without the provider, and no gate saw it.
13
+ *
14
+ * How it reads the app: from each of Next's rendering files under `src/app` (`page`, `layout`, `template`, `default`,
15
+ * `not-found`, `error`, `global-error`, `loading`, `forbidden`, `unauthorized`), it follows the app's own imports
16
+ * (a relative path, `@/` for the app's `src/`, `@sssb/app-config/` for its seam) through import and export
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
+ * loads nothing (`import type`, or every name marked `type`) is not followed, nor is a specifier it cannot resolve to
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
+ * is wrapped by one that reaches the provider: a layout or template that is itself that file, or one in a directory
21
+ * above it, or in its own directory, where a page is inside both, a template is inside the layout, and a layout is
22
+ * inside neither. `global-error` replaces the root layout, so only it can wrap itself.
23
+ *
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, 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
28
+ * graph, so its cost grows with the app's size, not with its pages times its modules.
29
+ */
30
+
31
+ const FORMS: ReadonlySet<string> = new Set([
32
+ '@sssb/kit/adapters/real/sign-in-form',
33
+ '@sssb/kit/adapters/real/accept-invite-form',
34
+ ])
35
+ const PROVIDER = '@sssb/kit/adapters/real/providers'
36
+ /**
37
+ * The seam's specifiers, as a prefix. Built from the package name because a literal spelling of a seam module path in
38
+ * shipped kit source is what `seam-specifiers.test.ts` refuses as a specifier it cannot list.
39
+ */
40
+ const SEAM_PACKAGE = '@sssb/app-config'
41
+ const SEAM_PREFIX = `${SEAM_PACKAGE}/`
42
+ const EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mts', '.cts', '.mjs', '.cjs']
43
+ /** What a written `.js`-style extension may stand for, as TypeScript's `bundler` resolution reads it. */
44
+ const SOURCE_FOR: Readonly<Record<string, readonly string[]>> = {
45
+ '.js': ['.ts', '.tsx', '.js', '.jsx'],
46
+ '.jsx': ['.tsx', '.jsx'],
47
+ '.mjs': ['.mts', '.mjs'],
48
+ '.cjs': ['.cts', '.cjs'],
49
+ }
50
+ const RENDERING =
51
+ /^(page|layout|template|default|not-found|error|global-error|loading|forbidden|unauthorized)\.(tsx?|jsx?)$/
52
+ const LAYOUT = /^layout\.(tsx?|jsx?)$/
53
+ const TEMPLATE = /^template\.(tsx?|jsx?)$/
54
+
55
+ /** Paths as the report prints them: relative to the app, with `/` on every platform. */
56
+ const relativeTo = (appDir: string, file: string) => path.relative(appDir, file).split(path.sep).join('/')
57
+
58
+ /** The entries of `dir`, or none when it cannot be read, which is then recorded. */
59
+ function entriesOf(dir: string, unreadable: Map<string, string>) {
60
+ try {
61
+ return readdirSync(dir, { withFileTypes: true })
62
+ } catch (error) {
63
+ unreadable.set(dir, (error as Error).message)
64
+ return []
65
+ }
66
+ }
67
+
68
+ /** Every rendering file under `dir`, recursively, as absolute paths. Symbolic links are not followed. */
69
+ function renderingFiles(dir: string, unreadable: Map<string, string>): string[] {
70
+ const files: string[] = []
71
+ for (const entry of entriesOf(dir, unreadable)) {
72
+ const full = path.join(dir, entry.name)
73
+ if (entry.isDirectory()) files.push(...renderingFiles(full, unreadable))
74
+ else if (entry.isFile() && RENDERING.test(entry.name)) files.push(full)
75
+ }
76
+ return files
77
+ }
78
+
79
+ /** True when an import or export declaration loads nothing at run time: all of it, or every name in it, is a type. */
80
+ function typeOnly(node: ts.ImportDeclaration | ts.ExportDeclaration): boolean {
81
+ if (ts.isImportDeclaration(node)) {
82
+ const clause = node.importClause
83
+ if (clause === undefined) return false // `import 'x'` runs the module
84
+ if (clause.isTypeOnly) return true
85
+ const named = clause.namedBindings
86
+ return (
87
+ clause.name === undefined &&
88
+ named !== undefined &&
89
+ ts.isNamedImports(named) &&
90
+ named.elements.length > 0 &&
91
+ named.elements.every((element) => element.isTypeOnly)
92
+ )
93
+ }
94
+ if (node.isTypeOnly) return true
95
+ const clause = node.exportClause
96
+ return (
97
+ clause !== undefined &&
98
+ ts.isNamedExports(clause) &&
99
+ clause.elements.length > 0 &&
100
+ clause.elements.every((element) => element.isTypeOnly)
101
+ )
102
+ }
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
+ */
108
+ function loadedSpecifiers(file: string): string[] {
109
+ const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true)
110
+ const found: string[] = []
111
+ const visit = (node: ts.Node): void => {
112
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
113
+ const specifier = node.moduleSpecifier
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)
122
+ } else if (
123
+ ts.isCallExpression(node) &&
124
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
125
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
126
+ node.arguments[0] &&
127
+ ts.isStringLiteralLike(node.arguments[0])
128
+ ) {
129
+ found.push(node.arguments[0].text)
130
+ }
131
+ ts.forEachChild(node, visit)
132
+ }
133
+ visit(source)
134
+ return found
135
+ }
136
+
137
+ const isFile = (file: string) => {
138
+ try {
139
+ return statSync(file).isFile()
140
+ } catch {
141
+ return false
142
+ }
143
+ }
144
+
145
+ const isDirectory = (dir: string) => {
146
+ try {
147
+ return statSync(dir).isDirectory()
148
+ } catch {
149
+ return false
150
+ }
151
+ }
152
+
153
+ /** The app file a specifier names, through a relative path, `@/` or `@sssb/app-config/`; undefined for anything else. */
154
+ function resolverFor(srcDir: string): (specifier: string, from: string) => string | undefined {
155
+ const cache = new Map<string, string | undefined>()
156
+ return (specifier, from) => {
157
+ let base: string
158
+ if (specifier.startsWith('@/')) base = path.join(srcDir, specifier.slice(2))
159
+ else if (specifier.startsWith(SEAM_PREFIX)) {
160
+ base = path.join(srcDir, 'app-config', specifier.slice(SEAM_PREFIX.length))
161
+ } else if (specifier === '.' || specifier === '..' || /^\.\.?\//.test(specifier)) {
162
+ base = path.resolve(path.dirname(from), specifier)
163
+ } else return undefined
164
+ if (cache.has(base)) return cache.get(base)
165
+ const written = path.extname(base)
166
+ const stem = base.slice(0, base.length - written.length)
167
+ const candidates = [
168
+ base,
169
+ ...(SOURCE_FOR[written] ?? []).map((ext) => stem + ext),
170
+ ...EXTENSIONS.map((ext) => base + ext),
171
+ ...EXTENSIONS.map((ext) => path.join(base, `index${ext}`)),
172
+ ]
173
+ const found = candidates.find(isFile)
174
+ cache.set(base, found)
175
+ return found
176
+ }
177
+ }
178
+
179
+ interface Reach {
180
+ form: boolean
181
+ provider: boolean
182
+ }
183
+
184
+ /**
185
+ * What every file reachable from `roots` reaches, settled in one pass: each file is parsed once to learn what it
186
+ * loads directly and which app files it imports, and then each flag is carried backwards along the imports from the
187
+ * files that set it. Cycles need nothing special: a file is visited at most once per flag.
188
+ */
189
+ function reachOf(roots: readonly string[], srcDir: string, unreadable: Map<string, string>): Map<string, Reach> {
190
+ const resolve = resolverFor(srcDir)
191
+ const direct = new Map<string, Reach>()
192
+ const importers = new Map<string, string[]>()
193
+ const queue = [...roots]
194
+ const seen = new Set(roots)
195
+ while (queue.length > 0) {
196
+ const file = queue.shift() as string
197
+ const reach: Reach = { form: false, provider: false }
198
+ let specifiers: string[] = []
199
+ try {
200
+ specifiers = loadedSpecifiers(file)
201
+ } catch (error) {
202
+ unreadable.set(file, (error as Error).message)
203
+ }
204
+ for (const specifier of specifiers) {
205
+ if (FORMS.has(specifier)) reach.form = true
206
+ if (specifier === PROVIDER) reach.provider = true
207
+ const local = resolve(specifier, file)
208
+ if (local === undefined) continue
209
+ const list = importers.get(local) ?? []
210
+ list.push(file)
211
+ importers.set(local, list)
212
+ if (!seen.has(local)) {
213
+ seen.add(local)
214
+ queue.push(local)
215
+ }
216
+ }
217
+ direct.set(file, reach)
218
+ }
219
+ const result = new Map<string, Reach>([...seen].map((file) => [file, { form: false, provider: false }]))
220
+ for (const flag of ['form', 'provider'] as const) {
221
+ const pending = [...direct].filter(([, reach]) => reach[flag]).map(([file]) => file)
222
+ for (const file of pending) (result.get(file) as Reach)[flag] = true
223
+ while (pending.length > 0) {
224
+ for (const importer of importers.get(pending.pop() as string) ?? []) {
225
+ const reach = result.get(importer) as Reach
226
+ if (!reach[flag]) {
227
+ reach[flag] = true
228
+ pending.push(importer)
229
+ }
230
+ }
231
+ }
232
+ }
233
+ return result
234
+ }
235
+
236
+ /**
237
+ * The layouts and templates that wrap `file`, itself included when it is one: in its own directory, a page (or any
238
+ * other rendering file) is inside both, a template is inside the layout, and a layout is inside neither; every layout
239
+ * and template in each directory above wraps it, up to `appRoot`. A `global-error` replaces the root layout, so it
240
+ * wraps itself and nothing else does.
241
+ */
242
+ function wrappersOf(file: string, appRoot: string, unreadable: Map<string, string>): string[] {
243
+ const name = path.basename(file)
244
+ if (/^global-error\./.test(name)) return [file]
245
+ const wrappers = LAYOUT.test(name) || TEMPLATE.test(name) ? [file] : []
246
+ const own = path.dirname(file)
247
+ for (let current = own; ; current = path.dirname(current)) {
248
+ for (const entry of entriesOf(current, unreadable)) {
249
+ if (!entry.isFile()) continue
250
+ const isLayout = LAYOUT.test(entry.name)
251
+ const isTemplate = TEMPLATE.test(entry.name)
252
+ if (!isLayout && !isTemplate) continue
253
+ if (current === own) {
254
+ if (LAYOUT.test(name)) continue // a layout is inside neither of its own directory's wrappers
255
+ if (TEMPLATE.test(name) && isTemplate) continue // a template is inside its layout, not itself again
256
+ }
257
+ wrappers.push(path.join(current, entry.name))
258
+ }
259
+ if (current === appRoot || path.dirname(current) === current) break
260
+ }
261
+ return wrappers
262
+ }
263
+
264
+ /** What the check finds: how many rendering files it walked, those that reach a form, those no provider wraps. */
265
+ export function realAuthProviderGaps(appDir: string): {
266
+ walked: number
267
+ withForms: string[]
268
+ gaps: string[]
269
+ unreadable: string[]
270
+ } {
271
+ const srcDir = path.join(appDir, 'src')
272
+ const appRoot = path.join(srcDir, 'app')
273
+ const unreadableFiles = new Map<string, string>()
274
+ if (!isDirectory(appRoot)) return { walked: 0, withForms: [], gaps: [], unreadable: [] }
275
+ const files = renderingFiles(appRoot, unreadableFiles)
276
+ const reach = reachOf(files, srcDir, unreadableFiles)
277
+ const reaches = (file: string, flag: keyof Reach) => reach.get(file)?.[flag] ?? false
278
+ const withForms = files.filter((file) => reaches(file, 'form'))
279
+ const gaps = withForms.filter(
280
+ (file) => !wrappersOf(file, appRoot, unreadableFiles).some((wrapper) => reaches(wrapper, 'provider')),
281
+ )
282
+ const rel = (file: string) => relativeTo(appDir, file)
283
+ return {
284
+ walked: files.length,
285
+ withForms: withForms.map(rel),
286
+ gaps: gaps.map(rel),
287
+ unreadable: [...unreadableFiles].map(([file, why]) => `${rel(file)}: ${why}`),
288
+ }
289
+ }
290
+
291
+ export const realAuthProvider: CheckImpl = {
292
+ tests: {
293
+ "the app's src/app is really walked": ({ appDir }) => {
294
+ const { walked, unreadable } = realAuthProviderGaps(appDir)
295
+ expect(walked, `no page or layout found under ${path.join(appDir, 'src', 'app')}`).toBeGreaterThan(0)
296
+ expect(unreadable, 'these files or directories could not be read').toEqual([])
297
+ },
298
+ 'every page that reaches a real auth form sits under a layout that reaches RealAuthProviders': ({ appDir }) => {
299
+ const { gaps } = realAuthProviderGaps(appDir)
300
+ expect(
301
+ gaps,
302
+ `these reach ${[...FORMS].join(' or ')}, but no layout above them reaches ${PROVIDER}, so the form ` +
303
+ 'throws in real mode. Mount RealAuthProviders in a layout above them, loaded with import() when ' +
304
+ '!isSimulated',
305
+ ).toEqual([])
306
+ },
307
+ },
308
+ }
@@ -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, `<app>: <rel> <VERB> …why`.
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> => {
@@ -3,13 +3,14 @@ import { type Migration, Migrator } from 'kysely/migration'
3
3
  import { expect } from 'vitest'
4
4
  import { openPglite, PGliteDialect } from '../../adapters/fake/pglite-dialect'
5
5
  import type { FoundRole } from '../../db/app-roles'
6
+ import { familySuite } from '../../db/family-suite'
6
7
  import type { DB } from '../../db/schema'
7
8
  import type { CheckImpl } from './types'
8
9
 
9
- // Everything that composes the framework's migrations with the app's reaches the seam, so it is imported when a
10
- // test runs, not when the suite is collected.
11
- const migrate = () => import('../../db/migrate')
12
- const registry = () => import('../../db/migrations/index')
10
+ // Everything that composes the framework's migrations with the app's reaches the seam, so the database family hands
11
+ // it over as loaders (../../db/family-suite.ts), run when a test runs, not when the suite is collected.
12
+ const migrate = () => familySuite.migrator()
13
+ const registry = () => familySuite.migrations()
13
14
 
14
15
  const pglite = () => new Kysely<DB>({ dialect: new PGliteDialect(openPglite()) })
15
16
 
@@ -197,7 +198,7 @@ export const rlsPglite: CheckImpl = {
197
198
  tests: {
198
199
  'the full RLS proof suite passes': async () => {
199
200
  const { migrateToLatest } = await migrate()
200
- const { runRlsProofs } = await import('../../db/rls-proof-runner')
201
+ const { runRlsProofs } = await familySuite.proofs()
201
202
  const db = pglite()
202
203
  try {
203
204
  await migrateToLatest(db)
@@ -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
- const icuArgs = (msg: string) => [...msg.matchAll(/\{(\w+)/g)].map((m) => m[1]).sort()
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 expectParity(en: MessageTree, es: MessageTree): void {
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
- expect([...esFlat.keys()].sort()).toEqual([...enFlat.keys()].sort())
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 !== undefined) expect.soft(icuArgs(esMsg), key).toEqual(icuArgs(enMsg))
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. The framework half is checked on its own too, so the package carries a
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 = {