@sssb/kit 0.0.0 → 0.3.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/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +212 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +313 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +248 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +93 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +464 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/same-origin-path.ts +20 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1480 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +132 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +69 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +57 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import type { AppPresetOperation } from '@sssb/app-config/presets'
|
|
2
|
+
import * as v from 'valibot'
|
|
3
|
+
import { canManageOrg, isRole, ORG_ASSIGNABLE_ROLES, ROLES, type Role } from './roles'
|
|
4
|
+
import type { StandardSchemaV1, StandardSchemaV1Issue } from './standard-schema'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* DEMO PRESETS — named starting points for the simulated world that EVERY host can restore.
|
|
8
|
+
*
|
|
9
|
+
* A saved snapshot is a directory copy of `.data/` (@sssb/kit/adapters/fake/simulator-admin.ts), pglite's
|
|
10
|
+
* binary state included, so only a server host can restore one: a `file://` static demo has no
|
|
11
|
+
* filesystem to copy it into. A preset is the other representation — **the seed plus a script of world
|
|
12
|
+
* operations** — which each host replays its own way: the server through the fake adapters
|
|
13
|
+
* (@sssb/kit/server-lib/demo-presets.ts), the static twin through its in-memory world
|
|
14
|
+
* (@sssb/kit/demo-static/world.ts). The two never share bytes, only this vocabulary, which is why it is
|
|
15
|
+
* pure TypeScript and lives in core.
|
|
16
|
+
*
|
|
17
|
+
* Preset CONTENT is app vocabulary (whose desk, which team, what the email says), so an app registers
|
|
18
|
+
* presets on the ADR-0012 seam (`@sssb/app-config/presets`), with copy in its own catalog. A preset may
|
|
19
|
+
* `extends` another (single inheritance, `expandPreset`), so "mid-demo, signed in as someone else" is a
|
|
20
|
+
* line, not a copy.
|
|
21
|
+
*
|
|
22
|
+
* **An operation is something the product itself could have done.** Every one that acts AS someone or IN a
|
|
23
|
+
* team names them explicitly — never "whoever is signed in" — and the world-wide ones (`flag`,
|
|
24
|
+
* `actor.hold`) name no one, so a replay is deterministic, and `presetProblems`
|
|
25
|
+
* below holds each one to the same rules the product enforces (an invite comes from someone who may
|
|
26
|
+
* invite, into a role that may be granted). A preset can therefore only describe a world someone could
|
|
27
|
+
* have clicked together; it is a shortcut to that world, never a back door into a different one.
|
|
28
|
+
*
|
|
29
|
+
* **The operation KINDS are a registry, not a closed list.** SSSB contributes `invite`, `inbound`, `flag`
|
|
30
|
+
* and `actor.hold` (`frameworkPresetOperations` below); an app contributes its own on the same seam module
|
|
31
|
+
* (`appPresetOperations`, typed by its `AppPresetOperation` union), and an app entry with SSSB's kind name
|
|
32
|
+
* REPLACES SSSB's (`composePresetOperations`). Each kind is three parts that never share a module: this
|
|
33
|
+
* pure DEFINITION (the argument schema, the product rules, the named results it consumes), a SERVER half
|
|
34
|
+
* (@sssb/kit/server-lib/preset-operations.ts, the app's `@sssb/app-config/preset-operations`), and a STATIC half
|
|
35
|
+
* (@sssb/kit/demo-static/world.ts, the app's `DemoWorldOptions.presetOperations`). The split is physical: the
|
|
36
|
+
* server half reaches pglite and `server-only` modules, and the static demo is one browser bundle that
|
|
37
|
+
* would fail to load with either inside it.
|
|
38
|
+
*
|
|
39
|
+
* **Named results.** An operation may say `as: 'refund'`; the id of the thing it created is then bound to
|
|
40
|
+
* that name for the rest of the replay, and a later operation names it in an argument its kind
|
|
41
|
+
* `consumes`. Each host keeps its own name → id map (a real uuid on the server, the twin's id in the
|
|
42
|
+
* static world), so a script can say "assign THAT ticket" without either host's ids leaking into it.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* One step of a preset's script, as written: `op` names the kind, `as` optionally names its result for
|
|
47
|
+
* later steps, and every other field is the kind's argument object. Objects, not tuples (contrast tour
|
|
48
|
+
* actions): an operation carries four or five named fields, and a positional list of strings would make
|
|
49
|
+
* `from` and `org` easy to swap. An app spells its kinds with this too:
|
|
50
|
+
* `export type AppPresetOperation = PresetOperationOf<'ticket.assign', TicketAssignArgs>`.
|
|
51
|
+
*/
|
|
52
|
+
export type PresetOperationOf<Kind extends string, Args> = { op: Kind; as?: string } & Args
|
|
53
|
+
|
|
54
|
+
/** `by` (a seed person who manages `org`) invites `email` into `org` as `role` — the invite, its email in
|
|
55
|
+
* the invitee's inbox, the audit row and the admins' notification, as the org screen does. `role` is any
|
|
56
|
+
* role, so a preset CAN ask for one no invite may grant; `presetProblems` is what says no. */
|
|
57
|
+
export interface InviteArgs {
|
|
58
|
+
by: string
|
|
59
|
+
org: string
|
|
60
|
+
email: string
|
|
61
|
+
role: Role
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The world emails `<org>+<handler>@…` — the Simulator's compose-inbound, through the same intake and
|
|
65
|
+
* the same registered handler a real message would reach. With `as`, names the row the handler opened. */
|
|
66
|
+
export interface InboundArgs {
|
|
67
|
+
org: string
|
|
68
|
+
handler: string
|
|
69
|
+
from: string
|
|
70
|
+
subject: string
|
|
71
|
+
body: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A Snapshots-tab feature flag, framework (`demo-banner`, `jobs-held`) or app-registered. */
|
|
75
|
+
export interface FlagArgs {
|
|
76
|
+
flag: string
|
|
77
|
+
enabled: boolean
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Holds (or releases) ONE registered Simulator actor — the per-actor counterpart of an app's world-wide
|
|
81
|
+
* hold flag. A held actor keeps its schedule but does nothing on its own (a manual Step still works),
|
|
82
|
+
* so a preset can start a world where one counterparty has gone quiet while the others keep working. */
|
|
83
|
+
export interface ActorHoldArgs {
|
|
84
|
+
/** A registered Simulator actor id (`@sssb/app-config/actors`). */
|
|
85
|
+
actor: string
|
|
86
|
+
held: boolean
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** SSSB's own operation kinds, as preset authors write them. */
|
|
90
|
+
export type FrameworkPresetOperation =
|
|
91
|
+
| PresetOperationOf<'invite', InviteArgs>
|
|
92
|
+
| PresetOperationOf<'inbound', InboundArgs>
|
|
93
|
+
| PresetOperationOf<'flag', FlagArgs>
|
|
94
|
+
| PresetOperationOf<'actor.hold', ActorHoldArgs>
|
|
95
|
+
|
|
96
|
+
/** Every operation a preset may contain: SSSB's kinds plus the app's, composed like job kinds (ADR-0012).
|
|
97
|
+
* The app half is a TYPE on its seam module, `never` when it registers none. */
|
|
98
|
+
export type PresetOperation = FrameworkPresetOperation | AppPresetOperation
|
|
99
|
+
|
|
100
|
+
/** A registered preset — what the Snapshots tab lists, and what a tour may name as its `snapshot`. */
|
|
101
|
+
export interface DemoPreset {
|
|
102
|
+
/** Stable id: the tab's testids, and the name a tour's `snapshot` resolves. Same shape as a saved
|
|
103
|
+
* snapshot's name, and never `'reset'`. */
|
|
104
|
+
id: string
|
|
105
|
+
/** Fully-qualified keys into the APP's catalog (`namespace.key`), like a tour's. */
|
|
106
|
+
titleKey: string
|
|
107
|
+
summaryKey: string
|
|
108
|
+
/**
|
|
109
|
+
* The seed person the RESTORING browser is signed in as once the world is ready. Omit to leave the
|
|
110
|
+
* viewpoint wherever the host's reset leaves it.
|
|
111
|
+
*
|
|
112
|
+
* The viewpoint is per-browser and the world is shared, so this is deliberately NOT "the viewpoint
|
|
113
|
+
* captured in the preset" — it is "who the person restoring it sits down as". A second browser
|
|
114
|
+
* watching the same server keeps its own viewpoint across a restore.
|
|
115
|
+
*/
|
|
116
|
+
viewpoint?: string
|
|
117
|
+
/**
|
|
118
|
+
* The id of another registered preset, replayed FIRST: this preset's world is the base's world plus
|
|
119
|
+
* its own operations, and its viewpoint overrides the base's when it names one. Single inheritance —
|
|
120
|
+
* one base, which may itself extend another (`expandPreset` walks the chain).
|
|
121
|
+
*/
|
|
122
|
+
extends?: string
|
|
123
|
+
/** The script, in order. Absent = none, so a preset can differ from its base by viewpoint alone. */
|
|
124
|
+
operations?: PresetOperation[]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The one world start every host has: the seeded world, with no script on top. */
|
|
128
|
+
const RESET_WORLD_START = 'reset'
|
|
129
|
+
|
|
130
|
+
/** The name pattern a saved snapshot uses (simulator-admin.ts) — presets share the namespace a tour's
|
|
131
|
+
* `snapshot` field resolves in, so they share its shape too. */
|
|
132
|
+
export const WORLD_START_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/
|
|
133
|
+
|
|
134
|
+
/** What a world-start name (a tour's `snapshot`, a Snapshots-tab click) means on a host. */
|
|
135
|
+
export type WorldStart =
|
|
136
|
+
| { kind: 'reset' }
|
|
137
|
+
| { kind: 'preset'; preset: DemoPreset }
|
|
138
|
+
/** A saved directory snapshot — something only a server host can restore. */
|
|
139
|
+
| { kind: 'snapshot'; name: string }
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Resolves a world-start name in a fixed order: `'reset'`, then a registered preset, then a saved
|
|
143
|
+
* snapshot. Saving a snapshot under a reserved name is refused (`isReservedWorldStartName`), so the
|
|
144
|
+
* order never has to break a tie.
|
|
145
|
+
*/
|
|
146
|
+
export function resolveWorldStart(name: string, presets: readonly DemoPreset[]): WorldStart {
|
|
147
|
+
if (name === RESET_WORLD_START) return { kind: 'reset' }
|
|
148
|
+
const preset = presets.find((candidate) => candidate.id === name)
|
|
149
|
+
if (preset) return { kind: 'preset', preset }
|
|
150
|
+
return { kind: 'snapshot', name }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** True when a saved snapshot may not take this name: it would shadow `'reset'` or a registered preset. */
|
|
154
|
+
export function isReservedWorldStartName(name: string, presets: readonly DemoPreset[]): boolean {
|
|
155
|
+
return name === RESET_WORLD_START || presets.some((preset) => preset.id === name)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A preset with its `extends` chain flattened: the operations to replay (the base chain's, oldest base
|
|
160
|
+
* first, then the preset's own) and the viewpoint to sit down as. The shape both replays run.
|
|
161
|
+
*/
|
|
162
|
+
export interface ExpandedPreset {
|
|
163
|
+
operations: PresetOperation[]
|
|
164
|
+
viewpoint?: string
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Where an `extends` walk stopped: at a root (no base), at an id nothing registers, or back on a
|
|
168
|
+
* preset it had already visited (a cycle). */
|
|
169
|
+
type ChainEnd = { kind: 'root' } | { kind: 'unknown'; id: string } | { kind: 'cycle'; at: string }
|
|
170
|
+
|
|
171
|
+
/** The presets from `id` toward its root (the preset itself first), and why the walk stopped. A visited
|
|
172
|
+
* set bounds it, so a malformed registry can never loop it. An unregistered `id` yields an empty chain. */
|
|
173
|
+
function walkExtends(id: string, presets: readonly DemoPreset[]): { chain: DemoPreset[]; end: ChainEnd } {
|
|
174
|
+
const chain: DemoPreset[] = []
|
|
175
|
+
const visited = new Set<string>()
|
|
176
|
+
let currentId: string | undefined = id
|
|
177
|
+
while (currentId !== undefined) {
|
|
178
|
+
if (visited.has(currentId)) return { chain, end: { kind: 'cycle', at: currentId } }
|
|
179
|
+
visited.add(currentId)
|
|
180
|
+
const preset = presets.find((candidate) => candidate.id === currentId)
|
|
181
|
+
if (!preset) return { chain, end: { kind: 'unknown', id: currentId } }
|
|
182
|
+
chain.push(preset)
|
|
183
|
+
currentId = preset.extends
|
|
184
|
+
}
|
|
185
|
+
return { chain, end: { kind: 'root' } }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Flattens a walked chain (preset first, root last): operations root-first, viewpoint nearest the preset. */
|
|
189
|
+
function flattenChain(chain: readonly DemoPreset[]): ExpandedPreset {
|
|
190
|
+
const operations = [...chain].reverse().flatMap((preset) => preset.operations ?? [])
|
|
191
|
+
const viewpoint = chain.find((preset) => preset.viewpoint !== undefined)?.viewpoint
|
|
192
|
+
return viewpoint === undefined ? { operations } : { operations, viewpoint }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Flattens a preset's `extends` chain, base first. Operations are the chain's in order — the root's,
|
|
197
|
+
* then each descendant's, the named preset's own last — and the viewpoint is the nearest one defined
|
|
198
|
+
* walking from the preset toward its root, so a child overrides its base and otherwise inherits.
|
|
199
|
+
*
|
|
200
|
+
* Returns null for an id no preset has, a chain that names an unknown base, or a cycle: a preset that
|
|
201
|
+
* cannot be fully expanded is never replayed half-way. Pure and total (the walk is bounded by a visited
|
|
202
|
+
* set). `presetProblems` is what says WHICH of those it was; the replays only need to know.
|
|
203
|
+
*/
|
|
204
|
+
export function expandPreset(id: string, presets: readonly DemoPreset[]): ExpandedPreset | null {
|
|
205
|
+
const { chain, end } = walkExtends(id, presets)
|
|
206
|
+
return end.kind === 'root' ? flattenChain(chain) : null
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The world a preset is checked against — derived from the seed and the registries, never hand-listed. */
|
|
210
|
+
export interface PresetWorld {
|
|
211
|
+
people: {
|
|
212
|
+
id: string
|
|
213
|
+
email: string
|
|
214
|
+
memberships: { orgSlug: string; role: string }[]
|
|
215
|
+
/** The seed person's limited-access flag — what the ability model reads, so an app kind's check
|
|
216
|
+
* can ask the same question its route's `authorize` would. */
|
|
217
|
+
restricted: boolean
|
|
218
|
+
}[]
|
|
219
|
+
orgSlugs: string[]
|
|
220
|
+
/** Registered inbound-email handler slugs. */
|
|
221
|
+
handlers: string[]
|
|
222
|
+
/** Known Snapshots feature flags. */
|
|
223
|
+
flags: string[]
|
|
224
|
+
/** Registered Simulator actor ids. */
|
|
225
|
+
actors: string[]
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* One operation KIND: what its arguments look like, what the product would refuse, and which named
|
|
230
|
+
* results it reads. Pure, and read only by `presetProblems` (the seam-conformance gate, in tests) — never by
|
|
231
|
+
* a replay — so it never holds the kind's behaviour; that is the server and static halves (see the module
|
|
232
|
+
* comment).
|
|
233
|
+
*
|
|
234
|
+
* `check` and `consumes` are METHOD signatures on purpose: method parameters are compared bivariantly, so
|
|
235
|
+
* a definition typed for its own arguments still fits a `PresetOperationDefinition[]` registry.
|
|
236
|
+
*/
|
|
237
|
+
export interface PresetOperationDefinition<Kind extends string = string, Args = unknown> {
|
|
238
|
+
kind: Kind
|
|
239
|
+
/** Shape of the operation's arguments (everything except `op` and `as`). Any Standard Schema library;
|
|
240
|
+
* it must validate SYNCHRONOUSLY, because presetProblems is synchronous. */
|
|
241
|
+
args: StandardSchemaV1<unknown, Args>
|
|
242
|
+
/**
|
|
243
|
+
* Rules a shape cannot express (the inviter manages the team, the sender is a seed person), as
|
|
244
|
+
* sentences without the "preset … operation N" prefix. Pure. Runs only once the arguments pass the
|
|
245
|
+
* schema. `earlier` is the script's earlier operations whose arguments passed theirs — what a rule
|
|
246
|
+
* that spans steps needs (an address invited twice is a duplicate, whichever step did it first).
|
|
247
|
+
*/
|
|
248
|
+
check?(args: Args, world: PresetWorld, earlier: readonly PresetOperation[]): string[]
|
|
249
|
+
/** Named results this operation CONSUMES — the names it reads from earlier operations' `as`. */
|
|
250
|
+
consumes?(args: Args): string[]
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const EMAIL_SHAPE = /.+@.+\..+/
|
|
254
|
+
|
|
255
|
+
// SSSB's own definitions are built BY FUNCTION, never at module scope, and that is load-bearing. The static
|
|
256
|
+
// demo imports this module for `expandPreset` and `resolveWorldStart` and never validates a preset, but a
|
|
257
|
+
// module-level `v.strictObject(...)` is a call the bundler must keep, so it carried valibot and every schema
|
|
258
|
+
// into each app's `file://` bundle (3.2 KB on the starter, which registers no preset at all).
|
|
259
|
+
// tests/tooling/static-demo-bundle.test.ts holds this. An app's own definitions are not covered: they sit on the seam module the
|
|
260
|
+
// demo imports for `presets`, so a module-level schema call in one stays in the demo (~2.8 KB for the
|
|
261
|
+
// showcase's `ticket.assign`, once).
|
|
262
|
+
|
|
263
|
+
const inviteOperation = (): PresetOperationDefinition<'invite', InviteArgs> => ({
|
|
264
|
+
kind: 'invite',
|
|
265
|
+
args: v.strictObject({ by: v.string(), org: v.string(), email: v.string(), role: v.picklist(ROLES) }),
|
|
266
|
+
check(args, world, earlier) {
|
|
267
|
+
const problems: string[] = []
|
|
268
|
+
if (!world.orgSlugs.includes(args.org)) problems.push(`unknown org "${args.org}"`)
|
|
269
|
+
const inviter = world.people.find((person) => person.id === args.by)
|
|
270
|
+
const membership = inviter?.memberships.find((m) => m.orgSlug === args.org)
|
|
271
|
+
if (!inviter) problems.push(`inviter "${args.by}" is not a seed person`)
|
|
272
|
+
else if (!membership || !isRole(membership.role) || !canManageOrg(membership.role)) {
|
|
273
|
+
problems.push(`"${args.by}" may not invite into "${args.org}"`)
|
|
274
|
+
}
|
|
275
|
+
// Grantable-by-invite is a product RULE, not the shape: the schema accepts any role, so a preset
|
|
276
|
+
// asking for `admin` gets the org screen's own sentence back rather than a type error.
|
|
277
|
+
if (!ORG_ASSIGNABLE_ROLES.includes(args.role)) problems.push(`role "${args.role}" cannot be granted by invite`)
|
|
278
|
+
const address = args.email.toLowerCase()
|
|
279
|
+
if (!EMAIL_SHAPE.test(address)) problems.push(`"${args.email}" is not an email address`)
|
|
280
|
+
// Inviting the same address twice is the duplicate the org screen refuses with a 409, whichever
|
|
281
|
+
// step in the expanded script did the first. `earlier` passed its schemas, but an app may have
|
|
282
|
+
// replaced `invite` with a differently-shaped kind, hence the typeof.
|
|
283
|
+
const invitedEarlier = earlier.some(
|
|
284
|
+
(operation) =>
|
|
285
|
+
operation.op === 'invite' &&
|
|
286
|
+
typeof operation.email === 'string' &&
|
|
287
|
+
operation.email.toLowerCase() === address,
|
|
288
|
+
)
|
|
289
|
+
if (invitedEarlier || world.people.some((person) => person.email.toLowerCase() === address)) {
|
|
290
|
+
problems.push(`"${args.email}" is already a person or an invite`)
|
|
291
|
+
}
|
|
292
|
+
return problems
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
const inboundOperation = (): PresetOperationDefinition<'inbound', InboundArgs> => ({
|
|
297
|
+
kind: 'inbound',
|
|
298
|
+
args: v.strictObject({
|
|
299
|
+
org: v.string(),
|
|
300
|
+
handler: v.string(),
|
|
301
|
+
from: v.string(),
|
|
302
|
+
subject: v.string(),
|
|
303
|
+
body: v.string(),
|
|
304
|
+
}),
|
|
305
|
+
check(args, world) {
|
|
306
|
+
const problems: string[] = []
|
|
307
|
+
if (!world.orgSlugs.includes(args.org)) problems.push(`unknown org "${args.org}"`)
|
|
308
|
+
if (!world.handlers.includes(args.handler)) problems.push(`no inbound handler "${args.handler}"`)
|
|
309
|
+
// A seed person, so a typo cannot quietly turn an intended ticket into an 'unmatched' filing.
|
|
310
|
+
// Whether that person may author into the team stays the HANDLER's call — a refused email is a
|
|
311
|
+
// legitimate thing for a preset to show.
|
|
312
|
+
const sender = args.from.toLowerCase()
|
|
313
|
+
if (!world.people.some((person) => person.email.toLowerCase() === sender)) {
|
|
314
|
+
problems.push(`sender "${args.from}" is not a seed person`)
|
|
315
|
+
}
|
|
316
|
+
return problems
|
|
317
|
+
},
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
const flagOperation = (): PresetOperationDefinition<'flag', FlagArgs> => ({
|
|
321
|
+
kind: 'flag',
|
|
322
|
+
args: v.strictObject({ flag: v.string(), enabled: v.boolean() }),
|
|
323
|
+
check: (args, world) => (world.flags.includes(args.flag) ? [] : [`unknown flag "${args.flag}"`]),
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
const actorHoldOperation = (): PresetOperationDefinition<'actor.hold', ActorHoldArgs> => ({
|
|
327
|
+
kind: 'actor.hold',
|
|
328
|
+
args: v.strictObject({ actor: v.string(), held: v.boolean() }),
|
|
329
|
+
check: (args, world) => (world.actors.includes(args.actor) ? [] : [`unknown actor "${args.actor}"`]),
|
|
330
|
+
})
|
|
331
|
+
|
|
332
|
+
/** SSSB's own operation kinds. An app may replace any of them by registering a definition of the same
|
|
333
|
+
* `kind` in its `appPresetOperations` (`/sssb:new-preset-operation --from <kind>` copies one to start from;
|
|
334
|
+
* `composePresetOperations([])[kind]` reaches SSSB's to wrap). */
|
|
335
|
+
const frameworkPresetOperations = (): readonly PresetOperationDefinition[] => [
|
|
336
|
+
inviteOperation(),
|
|
337
|
+
inboundOperation(),
|
|
338
|
+
flagOperation(),
|
|
339
|
+
actorHoldOperation(),
|
|
340
|
+
]
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* The operation registry a preset is checked against: SSSB's kinds, then the app's, keyed by kind — so an
|
|
344
|
+
* app definition with SSSB's kind name REPLACES SSSB's, the same `{ ...framework, ...app }` composition
|
|
345
|
+
* every other registry on the seam uses.
|
|
346
|
+
*/
|
|
347
|
+
export function composePresetOperations(
|
|
348
|
+
appDefinitions: readonly PresetOperationDefinition[],
|
|
349
|
+
): Readonly<Record<string, PresetOperationDefinition>> {
|
|
350
|
+
const composed: Record<string, PresetOperationDefinition> = {}
|
|
351
|
+
for (const definition of [...frameworkPresetOperations(), ...appDefinitions]) composed[definition.kind] = definition
|
|
352
|
+
return composed
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** "email" for a top-level key, "items.0.name" for a nested one, "" for the value itself. */
|
|
356
|
+
function issuePath(issue: StandardSchemaV1Issue): string {
|
|
357
|
+
return (issue.path ?? []).map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Everything wrong with a preset list, as readable sentences (empty = valid). A preset that replays on
|
|
362
|
+
* one host and silently does nothing on the other is the failure this exists to stop, so the checks
|
|
363
|
+
* mirror what each operation's server path would refuse — run in every app's seam-conformance suite,
|
|
364
|
+
* not at replay time, so a broken preset fails the build rather than a demo.
|
|
365
|
+
*
|
|
366
|
+
* `definitions` is the composed registry (`composePresetOperations(appPresetOperations)`). Each
|
|
367
|
+
* operation is held, in order, to: a registered kind (`no operation kind "X"`); its kind's argument
|
|
368
|
+
* schema, one sentence per issue naming the path; then its kind's `check`. Named results are checked
|
|
369
|
+
* across the script: an `as` names one operation only, and every name a kind `consumes` must be bound by
|
|
370
|
+
* an EARLIER operation's `as` — replay is in order, so a name bound later is as missing as one never bound.
|
|
371
|
+
*
|
|
372
|
+
* Operations and the viewpoint are checked on the EXPANDED preset (`expandPreset`): what actually
|
|
373
|
+
* replays, so a duplicate invite split across a base and its child is caught, and a child that
|
|
374
|
+
* overrides a bad viewpoint is not blamed for it. Consequences, both deliberate: an operation's number
|
|
375
|
+
* (`operation 3`) counts in the expanded list, base operations first; and a base's own problem repeats
|
|
376
|
+
* under every preset that extends it, because each of them replays it. A cycle is reported once on each
|
|
377
|
+
* preset that is IN it (a preset merely leading into one is not), and an unknown base on the preset that
|
|
378
|
+
* names it; either way the operations reachable before the chain broke are still checked.
|
|
379
|
+
*/
|
|
380
|
+
export function presetProblems(
|
|
381
|
+
presets: readonly DemoPreset[],
|
|
382
|
+
world: PresetWorld,
|
|
383
|
+
definitions: Readonly<Record<string, PresetOperationDefinition>>,
|
|
384
|
+
): string[] {
|
|
385
|
+
const problems: string[] = []
|
|
386
|
+
const seen = new Set<string>()
|
|
387
|
+
|
|
388
|
+
for (const preset of presets) {
|
|
389
|
+
const where = `preset "${preset.id}"`
|
|
390
|
+
if (!WORLD_START_NAME_PATTERN.test(preset.id)) problems.push(`${where}: id is not a valid world-start name`)
|
|
391
|
+
if (preset.id === RESET_WORLD_START) problems.push(`${where}: "reset" is reserved for the seeded world`)
|
|
392
|
+
if (seen.has(preset.id)) problems.push(`${where}: registered twice`)
|
|
393
|
+
seen.add(preset.id)
|
|
394
|
+
|
|
395
|
+
const { chain, end } = walkExtends(preset.id, presets)
|
|
396
|
+
if (end.kind === 'unknown' && chain.length === 1) problems.push(`${where}: extends unknown preset "${end.id}"`)
|
|
397
|
+
if (end.kind === 'cycle' && end.at === preset.id) problems.push(`${where}: extends chain has a cycle`)
|
|
398
|
+
const { operations, viewpoint } = flattenChain(chain)
|
|
399
|
+
|
|
400
|
+
if (viewpoint !== undefined && !world.people.some((person) => person.id === viewpoint)) {
|
|
401
|
+
problems.push(`${where}: viewpoint "${viewpoint}" is not a seed person`)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Earlier operations whose arguments passed their schema — what a kind's `check` may look back at.
|
|
405
|
+
const passed: PresetOperation[] = []
|
|
406
|
+
// Each `as` name → the (1-based) operation that bound it first.
|
|
407
|
+
const boundAt = new Map<string, number>()
|
|
408
|
+
for (const [index, operation] of operations.entries()) {
|
|
409
|
+
const number = index + 1
|
|
410
|
+
const at = `${where} operation ${number} (${operation.op})`
|
|
411
|
+
const { op, as, ...args } = operation
|
|
412
|
+
|
|
413
|
+
if (as !== undefined) {
|
|
414
|
+
const first = boundAt.get(as)
|
|
415
|
+
if (first !== undefined) problems.push(`${at}: "${as}" is already the name of operation ${first}`)
|
|
416
|
+
else boundAt.set(as, number)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// An own-property lookup, so a kind named like an Object.prototype member is just unknown.
|
|
420
|
+
const definition = Object.hasOwn(definitions, op) ? definitions[op] : undefined
|
|
421
|
+
if (!definition) {
|
|
422
|
+
problems.push(`${at}: no operation kind "${op}"`)
|
|
423
|
+
continue
|
|
424
|
+
}
|
|
425
|
+
const result = definition.args['~standard'].validate(args)
|
|
426
|
+
if (result instanceof Promise) {
|
|
427
|
+
problems.push(
|
|
428
|
+
`${at}: schema for kind "${op}" validated asynchronously; preset schemas must be synchronous`,
|
|
429
|
+
)
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
if (result.issues) {
|
|
433
|
+
for (const issue of result.issues) {
|
|
434
|
+
const path = issuePath(issue)
|
|
435
|
+
problems.push(`${at}: ${path ? `${path}: ` : ''}${issue.message}`)
|
|
436
|
+
}
|
|
437
|
+
continue
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
for (const problem of definition.check?.(result.value, world, passed) ?? [])
|
|
441
|
+
problems.push(`${at}: ${problem}`)
|
|
442
|
+
for (const name of definition.consumes?.(result.value) ?? []) {
|
|
443
|
+
const bound = boundAt.get(name)
|
|
444
|
+
if (bound !== undefined && bound < number) continue
|
|
445
|
+
const later = operations.findIndex((candidate, i) => i > index && candidate.as === name)
|
|
446
|
+
problems.push(
|
|
447
|
+
later === -1
|
|
448
|
+
? `${at}: no earlier operation is named "${name}"`
|
|
449
|
+
: `${at}: "${name}" is not named until operation ${later + 1}, after this one`,
|
|
450
|
+
)
|
|
451
|
+
}
|
|
452
|
+
passed.push(operation)
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return problems
|
|
456
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const ROLES = ['admin', 'staff', 'member', 'guest', 'restricted'] as const
|
|
2
|
+
export type Role = (typeof ROLES)[number]
|
|
3
|
+
|
|
4
|
+
// The designated staff/operator org slug is an app/deployment choice, so it lives on the
|
|
5
|
+
// seam as `staffOrgSlug` (src/app-config/abilities.ts) — NOT here. DISAMBIGUATION: the operator ORG is
|
|
6
|
+
// NOT the rank-ladder role `'staff'` below; the role is an org-manager RANK, the org is the operator
|
|
7
|
+
// org whose active membership activates cross-org manage-all. See the seam for the doctrine + slug.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Roles allowed to manage an organization (member list, invites). Module-private: the ability layer
|
|
11
|
+
* (packages/kit/src/core/abilities.ts) and callers consume the `canManageOrg` predicate below, not the raw list —
|
|
12
|
+
* the last external use (org/invite's requireRole) is now authorize('Membership').
|
|
13
|
+
*/
|
|
14
|
+
const ORG_MANAGER_ROLES: readonly Role[] = ['admin', 'staff']
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Roles an org manager may GRANT via invite. Excludes admin — managers must never mint a role
|
|
18
|
+
* above their own; the API never accepts a role the caller cannot grant.
|
|
19
|
+
*/
|
|
20
|
+
export const ORG_ASSIGNABLE_ROLES: readonly Role[] = ['staff', 'member', 'guest', 'restricted']
|
|
21
|
+
|
|
22
|
+
export function isRole(value: string): value is Role {
|
|
23
|
+
return (ROLES as readonly string[]).includes(value)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The invite-path check: is `value` a role an org manager may grant? Narrower than `isRole`, which
|
|
28
|
+
* accepts `'admin'`. One predicate shared by the real invite route and the static demo's invite twin,
|
|
29
|
+
* so the two cannot disagree about who may be minted.
|
|
30
|
+
*/
|
|
31
|
+
export function isAssignableRole(value: string): value is Role {
|
|
32
|
+
return (ORG_ASSIGNABLE_ROLES as readonly string[]).includes(value)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function canManageOrg(role: Role): boolean {
|
|
36
|
+
return ORG_MANAGER_ROLES.includes(role)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether a member is RESTRICTED: by their own `restricted` flag, or by holding the `restricted` role in
|
|
41
|
+
* the org in question. This template has both readings. The seed sets both, while a real-mode invite
|
|
42
|
+
* writes only the role, so reading the flag alone left a `restricted` invitee unrestricted. Both auth
|
|
43
|
+
* adapters derive `AuthUser.restricted` and `getMember`'s standing through this one function.
|
|
44
|
+
*/
|
|
45
|
+
export function isRestricted(flag: boolean | undefined, role: Role): boolean {
|
|
46
|
+
return flag === true || role === 'restricted'
|
|
47
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const BASE = 'http://same-origin.invalid'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `value` as a path on the current origin (path, query and fragment, normalised), or null when a browser given it
|
|
5
|
+
* would leave the origin, run a script, or land on a path that reads as another origin.
|
|
6
|
+
*
|
|
7
|
+
* The Simulator navigates to strings it does not write: a remembered `lastPath` (recorded from a page-view beacon's
|
|
8
|
+
* body), a link in a caught email. A prefix check is not enough, because a browser reads `/\host` as `//host`, drops a
|
|
9
|
+
* tab or newline anywhere (`/<tab>/host` is `//host`), and resolves dot segments (`/.//host` is the path `//host`,
|
|
10
|
+
* which a later relative use turns into another origin). So the string must start with one `/`, hold no control
|
|
11
|
+
* character, and no backslash or whitespace in its path (the query and fragment may: they cannot change the origin),
|
|
12
|
+
* resolve against a fixed origin to that same origin, and resolve to a path that does not itself start with `//`.
|
|
13
|
+
* What it returns is the parser's serialisation, never the input.
|
|
14
|
+
*/
|
|
15
|
+
export function sameOriginPath(value: unknown): string | null {
|
|
16
|
+
if (typeof value !== 'string' || !/^\/(?![/\\])[^\s\\\p{Cc}?#]*(?:[?#][^\p{Cc}]*)?$/u.test(value)) return null
|
|
17
|
+
const url = new URL(value, BASE)
|
|
18
|
+
if (url.origin !== BASE || url.pathname.startsWith('//')) return null
|
|
19
|
+
return url.pathname + url.search + url.hash
|
|
20
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recurring-schedule timing. PURE TypeScript — no framework imports (ADR-0006,
|
|
3
|
+
* lint-enforced). This is the single source of truth for "when does a schedule next fire", shared
|
|
4
|
+
* verbatim by the server due-scan (packages/kit/src/db/schedules.ts) and the static-demo twin.
|
|
5
|
+
*
|
|
6
|
+
* DELIBERATELY NOT a cron/RRULE engine. Three closed spec shapes cover the reminder/digest/SLA/dunning
|
|
7
|
+
* loop the round-2 sweep found (docs/app-coverage-gaps.md); arbitrary cron expressions and
|
|
8
|
+
* calendar recurrence stay a recipe, not template code. Everything here is UTC — there is no timezone
|
|
9
|
+
* library and no local-time interpretation, so results are identical on every host and DST can never
|
|
10
|
+
* shift a fire time (a UTC day is always exactly 86_400_000 ms). An instance that needs per-user
|
|
11
|
+
* local times layers a tz conversion above this, at the edge; the core stays UTC-only on purpose.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A recurring interval, anchored to the schedule's own origin (see computeNextRunAt drift note). */
|
|
15
|
+
interface IntervalSpec {
|
|
16
|
+
type: 'interval'
|
|
17
|
+
/** Fire every N minutes. Integer, 1..MAX_INTERVAL_MINUTES (a year), so next-run math stays bounded. */
|
|
18
|
+
everyMinutes: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Fire once a day at a fixed UTC wall-clock time. */
|
|
22
|
+
interface DailySpec {
|
|
23
|
+
type: 'daily'
|
|
24
|
+
/** 0..23 */
|
|
25
|
+
atUtcHour: number
|
|
26
|
+
/** 0..59 */
|
|
27
|
+
atUtcMinute: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Fire once a week on a fixed UTC weekday at a fixed UTC time. */
|
|
31
|
+
interface WeeklySpec {
|
|
32
|
+
type: 'weekly'
|
|
33
|
+
/** 0 = Sunday … 6 = Saturday (matches Date.prototype.getUTCDay). */
|
|
34
|
+
utcDay: number
|
|
35
|
+
/** 0..23 */
|
|
36
|
+
atUtcHour: number
|
|
37
|
+
/** 0..59 */
|
|
38
|
+
atUtcMinute: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type ScheduleSpec = IntervalSpec | DailySpec | WeeklySpec
|
|
42
|
+
|
|
43
|
+
const MS_PER_MINUTE = 60_000
|
|
44
|
+
const MS_PER_DAY = 86_400_000
|
|
45
|
+
/** A year in minutes — the interval cap. Keeps the coalescing loop in the due-scan bounded. */
|
|
46
|
+
export const MAX_INTERVAL_MINUTES = 366 * 24 * 60
|
|
47
|
+
|
|
48
|
+
function isInt(value: unknown, min: number, max: number): value is number {
|
|
49
|
+
return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validates an untrusted value (a jsonb column, a seed literal, a request body) into a typed
|
|
54
|
+
* ScheduleSpec, throwing a descriptive Error on anything malformed. Hand-rolled, no zod — validation
|
|
55
|
+
* stays explicit at the boundary, the same discipline the webhook route uses. Callers that persist a
|
|
56
|
+
* spec MUST run it through here first so a bad row can never reach computeNextRunAt.
|
|
57
|
+
*/
|
|
58
|
+
export function parseScheduleSpec(value: unknown): ScheduleSpec {
|
|
59
|
+
if (typeof value !== 'object' || value === null) throw new Error('schedule spec must be an object')
|
|
60
|
+
const spec = value as Record<string, unknown>
|
|
61
|
+
switch (spec['type']) {
|
|
62
|
+
case 'interval':
|
|
63
|
+
if (!isInt(spec['everyMinutes'], 1, MAX_INTERVAL_MINUTES)) {
|
|
64
|
+
throw new Error(`interval everyMinutes must be an integer 1..${MAX_INTERVAL_MINUTES}`)
|
|
65
|
+
}
|
|
66
|
+
return { type: 'interval', everyMinutes: spec['everyMinutes'] }
|
|
67
|
+
case 'daily':
|
|
68
|
+
if (!isInt(spec['atUtcHour'], 0, 23) || !isInt(spec['atUtcMinute'], 0, 59)) {
|
|
69
|
+
throw new Error('daily atUtcHour must be 0..23 and atUtcMinute 0..59')
|
|
70
|
+
}
|
|
71
|
+
return { type: 'daily', atUtcHour: spec['atUtcHour'], atUtcMinute: spec['atUtcMinute'] }
|
|
72
|
+
case 'weekly':
|
|
73
|
+
if (
|
|
74
|
+
!isInt(spec['utcDay'], 0, 6) ||
|
|
75
|
+
!isInt(spec['atUtcHour'], 0, 23) ||
|
|
76
|
+
!isInt(spec['atUtcMinute'], 0, 59)
|
|
77
|
+
) {
|
|
78
|
+
throw new Error('weekly utcDay must be 0..6, atUtcHour 0..23, atUtcMinute 0..59')
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
type: 'weekly',
|
|
82
|
+
utcDay: spec['utcDay'],
|
|
83
|
+
atUtcHour: spec['atUtcHour'],
|
|
84
|
+
atUtcMinute: spec['atUtcMinute'],
|
|
85
|
+
}
|
|
86
|
+
default:
|
|
87
|
+
throw new Error(`unknown schedule spec type: ${String(spec['type'])}`)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Non-throwing predicate — a `parse` that returns a boolean, for guards that don't want the message. */
|
|
92
|
+
export function isScheduleSpec(value: unknown): value is ScheduleSpec {
|
|
93
|
+
try {
|
|
94
|
+
parseScheduleSpec(value)
|
|
95
|
+
return true
|
|
96
|
+
} catch {
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The single next fire time STRICTLY AFTER `from`, in UTC.
|
|
103
|
+
*
|
|
104
|
+
* Drift policy (the decision the slice records): a schedule advances by feeding its OWN scheduled
|
|
105
|
+
* next_run_at back in as `from` — never `now`, never the handler's completion time. So an interval
|
|
106
|
+
* series is `origin, origin+I, origin+2I, …`, anchored to its origin and immune to tick latency or
|
|
107
|
+
* handler duration; "scheduled-time anchoring", not "completion-time anchoring". Because every step is
|
|
108
|
+
* exact epoch-ms arithmetic on a UTC instant, month/year rollovers and DST are non-events.
|
|
109
|
+
*
|
|
110
|
+
* This is a SINGLE step. When a tick is late or the demo world-clock jumps across several missed
|
|
111
|
+
* slots, the due-scan coalesces by stepping from the scheduled anchor until the result passes `now`
|
|
112
|
+
* (packages/kit/src/db/schedules.ts) — firing once and skipping the gap rather than dogpiling one job per missed
|
|
113
|
+
* slot. Anchoring is preserved through the coalesce because each step still lands on an origin-aligned
|
|
114
|
+
* slot.
|
|
115
|
+
*/
|
|
116
|
+
export function computeNextRunAt(spec: ScheduleSpec, from: Date): Date {
|
|
117
|
+
const fromMs = from.getTime()
|
|
118
|
+
switch (spec.type) {
|
|
119
|
+
case 'interval':
|
|
120
|
+
return new Date(fromMs + spec.everyMinutes * MS_PER_MINUTE)
|
|
121
|
+
case 'daily': {
|
|
122
|
+
const todayAt = Date.UTC(
|
|
123
|
+
from.getUTCFullYear(),
|
|
124
|
+
from.getUTCMonth(),
|
|
125
|
+
from.getUTCDate(),
|
|
126
|
+
spec.atUtcHour,
|
|
127
|
+
spec.atUtcMinute,
|
|
128
|
+
)
|
|
129
|
+
// A UTC day is exactly MS_PER_DAY, so "tomorrow at the same wall time" is just +1 day of ms.
|
|
130
|
+
return new Date(todayAt > fromMs ? todayAt : todayAt + MS_PER_DAY)
|
|
131
|
+
}
|
|
132
|
+
case 'weekly': {
|
|
133
|
+
const todayAt = Date.UTC(
|
|
134
|
+
from.getUTCFullYear(),
|
|
135
|
+
from.getUTCMonth(),
|
|
136
|
+
from.getUTCDate(),
|
|
137
|
+
spec.atUtcHour,
|
|
138
|
+
spec.atUtcMinute,
|
|
139
|
+
)
|
|
140
|
+
const dayDiff = (spec.utcDay - from.getUTCDay() + 7) % 7
|
|
141
|
+
const candidate = todayAt + dayDiff * MS_PER_DAY
|
|
142
|
+
// dayDiff 0 with the time already past today rolls to next week; a future weekday is always
|
|
143
|
+
// strictly after `from` already.
|
|
144
|
+
return new Date(candidate > fromMs ? candidate : candidate + 7 * MS_PER_DAY)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|