@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.
Files changed (45) 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 +18 -2
  6. package/src/adapters/fake/data-dir.ts +32 -2
  7. package/src/adapters/fake/email.ts +2 -0
  8. package/src/adapters/real/accept-invite-form.tsx +32 -14
  9. package/src/adapters/real/analytics.ts +29 -2
  10. package/src/adapters/real/auth.ts +54 -18
  11. package/src/adapters/real/contract-postgres.ts +15 -11
  12. package/src/adapters/real/email.ts +2 -0
  13. package/src/adapters/real/jobs-in-process.ts +32 -14
  14. package/src/adapters/real/jobs.ts +6 -3
  15. package/src/adapters/real/migrate-handler.ts +3 -1
  16. package/src/adapters/real/rds-data-codec.ts +88 -4
  17. package/src/adapters/real/rds-data-emulator.ts +12 -4
  18. package/src/adapters/real/sign-in-form.tsx +29 -13
  19. package/src/authz/app-exemptions.ts +79 -9
  20. package/src/authz/route-scan.ts +626 -55
  21. package/src/components/auth/accept-invite-screen.tsx +5 -1
  22. package/src/components/auth/people-picker.tsx +20 -2
  23. package/src/components/profile-screen.tsx +27 -2
  24. package/src/core/inbound-email.ts +41 -6
  25. package/src/db/jobs.ts +15 -6
  26. package/src/db/keyset.ts +8 -6
  27. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  28. package/src/db/rls-coverage.ts +51 -17
  29. package/src/db/schedules.ts +9 -3
  30. package/src/demo-static/actor-drivers.ts +8 -2
  31. package/src/demo-static/email-html.ts +9 -0
  32. package/src/demo-static/tour/use-tours.tsx +8 -2
  33. package/src/demo-static/world.ts +76 -37
  34. package/src/email/send.ts +6 -2
  35. package/src/guide.md +20 -6
  36. package/src/i18n/messages/en.json +3 -0
  37. package/src/i18n/messages/es.json +3 -0
  38. package/src/i18n/messages.ts +3 -2
  39. package/src/server-lib/scheduled-tick.ts +5 -1
  40. package/src/server-lib/webhook-dispatch.ts +3 -0
  41. package/src/service-auth/mailgun.ts +19 -4
  42. package/src/testing/conformance/auth-provider.ts +17 -5
  43. package/src/testing/conformance/authz.ts +6 -2
  44. package/src/testing/conformance/i18n.ts +99 -5
  45. package/src/testing/conformance/suite.ts +63 -3
@@ -117,7 +117,11 @@ export function AcceptInviteScreen({
117
117
  <Text size="xs" c="gray.7" data-testid="accept-agreements-notice">
118
118
  {t('agreementsNotice')}
119
119
  </Text>
120
- {error ? <Text c="red.8">{error}</Text> : null}
120
+ {error ? (
121
+ <Text c="red.8" role="alert">
122
+ {error}
123
+ </Text>
124
+ ) : null}
121
125
  </Stack>
122
126
  </form>
123
127
  }
@@ -14,8 +14,18 @@ export interface PickerPerson {
14
14
  /**
15
15
  * Simulated-mode sign-in: the same card layout the real credential form uses, listing seeded
16
16
  * people. One auth UI in every mode (ADR-0003).
17
+ *
18
+ * `onPick` may answer a promise: one that resolves `false` or rejects (the sign-in was refused, the dev server is
19
+ * down) clears the spinner so the person can pick again; anything else (`true`, or nothing, as an `async` handler
20
+ * that returns no value resolves) keeps it while the page navigates.
17
21
  */
18
- export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPick: (id: string) => void }) {
22
+ export function PeoplePicker({
23
+ people,
24
+ onPick,
25
+ }: {
26
+ people: PickerPerson[]
27
+ onPick: (id: string) => void | Promise<boolean | void>
28
+ }) {
19
29
  const t = useTranslations('auth')
20
30
  const [busy, setBusy] = useState<string | null>(null)
21
31
 
@@ -39,7 +49,15 @@ export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPic
39
49
  }
40
50
  onClick={() => {
41
51
  setBusy(person.id)
42
- onPick(person.id)
52
+ const result = onPick(person.id)
53
+ if (result) {
54
+ result.then(
55
+ (outcome) => {
56
+ if (outcome === false) setBusy(null)
57
+ },
58
+ () => setBusy(null),
59
+ )
60
+ }
43
61
  }}
44
62
  >
45
63
  {person.name}
@@ -10,6 +10,9 @@ export interface ProfileValues {
10
10
  locale: string
11
11
  }
12
12
 
13
+ /** The longest display name SSSB's auth adapters accept; a blank one is refused too. */
14
+ const PROFILE_NAME_MAX_LENGTH = 256
15
+
13
16
  /**
14
17
  * Lean take on Clerk's UserProfile (ADR-0003): a sectioned account page. The Profile section is live;
15
18
  * the Security section is a named seam so MFA / password / connected accounts have a home when those
@@ -27,13 +30,25 @@ export function ProfileScreen({
27
30
  initial: ProfileValues
28
31
  email: string
29
32
  locales: string[]
33
+ /** Rejects when the profile was not saved: the screen then keeps the form and says so. */
30
34
  onSave: (values: ProfileValues) => Promise<void>
31
35
  extraSection?: ReactNode
32
36
  }) {
33
37
  const t = useTranslations('profile')
34
38
  const [saved, setSaved] = useState(false)
35
39
  const [busy, setBusy] = useState(false)
36
- const form = useForm({ initialValues: initial })
40
+ const [saveFailed, setSaveFailed] = useState(false)
41
+ const form = useForm({
42
+ initialValues: initial,
43
+ validate: {
44
+ name: (value) =>
45
+ !value.trim()
46
+ ? t('nameRequired')
47
+ : value.length > PROFILE_NAME_MAX_LENGTH
48
+ ? t('nameTooLong', { max: PROFILE_NAME_MAX_LENGTH })
49
+ : null,
50
+ },
51
+ })
37
52
 
38
53
  return (
39
54
  <Container component="main" size="sm" py="xl">
@@ -48,8 +63,12 @@ export function ProfileScreen({
48
63
  onSubmit={form.onSubmit((values) => {
49
64
  setBusy(true)
50
65
  setSaved(false)
66
+ setSaveFailed(false)
51
67
  onSave(values)
52
- .then(() => setSaved(true))
68
+ .then(
69
+ () => setSaved(true),
70
+ () => setSaveFailed(true),
71
+ )
53
72
  .finally(() => setBusy(false))
54
73
  })}
55
74
  >
@@ -58,6 +77,7 @@ export function ProfileScreen({
58
77
  <TextInput
59
78
  label={t('nameLabel')}
60
79
  data-testid="profile-name"
80
+ withAsterisk
61
81
  {...form.getInputProps('name')}
62
82
  />
63
83
  <Select
@@ -75,6 +95,11 @@ export function ProfileScreen({
75
95
  >
76
96
  {t('saveButton')}
77
97
  </Button>
98
+ {saveFailed ? (
99
+ <Text c="red.8" size="sm" role="alert" data-testid="profile-save-error">
100
+ {t('saveError')}
101
+ </Text>
102
+ ) : null}
78
103
  {saved ? (
79
104
  <Text c="green.8" size="sm" data-testid="profile-saved">
80
105
  {t('saved')}
@@ -42,14 +42,49 @@ export interface InboundRecipient {
42
42
  const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
43
43
 
44
44
  /**
45
- * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`,
46
- * a bare `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local
47
- * parts are case-insensitive in every practical mail system — we normalize so a sender/member match is
48
- * not defeated by case). Returns '' for anything without an addr-spec.
45
+ * `raw` with each double-quoted string taken out, a backslash escaping the character after it. A quote that never
46
+ * closes is left where it is, with everything after it. One pass by hand: the regular expression for this
47
+ * (`"(?:[^"\\]|\\.)*"`) rescans from every opening quote, which is quadratic on a header an attacker writes.
48
+ */
49
+ function withoutQuotedStrings(raw: string): string {
50
+ let out = ''
51
+ let at = 0
52
+ while (at < raw.length) {
53
+ if (raw[at] !== '"') {
54
+ out += raw[at]
55
+ at += 1
56
+ continue
57
+ }
58
+ let end = at + 1
59
+ while (end < raw.length && raw[end] !== '"') end += raw[end] === '\\' ? 2 : 1
60
+ if (end >= raw.length) return out + raw.slice(at)
61
+ at = end + 1
62
+ }
63
+ return out
64
+ }
65
+
66
+ /**
67
+ * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`, a bare
68
+ * `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local parts are
69
+ * case-insensitive in every practical mail system — we normalize so a sender/member match is not defeated by case).
70
+ *
71
+ * It fails closed: anything it cannot read one way only returns '' ("no address"), never a guess. Double-quoted
72
+ * strings (a display name) are dropped first, so `"<victim@org.test>" <attacker@evil.test>` is the attacker's own
73
+ * address. Then a value with angle brackets must hold exactly one `<...>` with nothing but whitespace after its `>`:
74
+ * a comment after the address (`<a@x> (<b@y>)`), a second address (`<a@x>, <b@y>`) or text after the brackets
75
+ * (`x<b@y>a@x`) each name another address, so they return ''. Returns '' for anything without an addr-spec too.
49
76
  */
50
77
  export function normalizeEmailAddress(raw: string): string {
51
- const angle = raw.match(/<([^>]+)>/)
52
- const candidate = (angle ? angle[1]! : raw).trim().toLowerCase()
78
+ const unquoted = withoutQuotedStrings(raw)
79
+ let candidate: string
80
+ if (/[<>]/.test(unquoted)) {
81
+ const only = /^[^<>]*<([^<>]*)>\s*$/.exec(unquoted)
82
+ if (!only) return ''
83
+ candidate = only[1]!
84
+ } else {
85
+ candidate = unquoted
86
+ }
87
+ candidate = candidate.trim().toLowerCase()
53
88
  // A single '@' with non-empty both sides, else not a usable address.
54
89
  const at = candidate.indexOf('@')
55
90
  if (at <= 0 || at !== candidate.lastIndexOf('@') || at === candidate.length - 1) return ''
package/src/db/jobs.ts CHANGED
@@ -98,13 +98,22 @@ export async function recordJobStatus(
98
98
  // Outbound webhooks: a job status change is an emitted event. Enqueue only — cheap; the
99
99
  // drain delivers async. Deliberately AFTER the status transaction commits (the audit precedent),
100
100
  // and skipped when the job has no org (RLS-proof / legacy rows can't have subscribed endpoints).
101
+ // The status is durable by now, so a failed enqueue must not fail the caller: a runner that saw
102
+ // `running` throw would never run the handler, and one that saw `completed` throw would answer an
103
+ // error for a job that finished. The event is lost and logged (console.warn reaches CloudWatch in
104
+ // Lambda; SSSB has no logger port, as ../adapters/real/db.ts says).
101
105
  if (job.orgId) {
102
- await enqueueWebhookEvent(db, {
103
- tenantId,
104
- orgId: job.orgId,
105
- kind: 'job.status_changed',
106
- payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
107
- })
106
+ try {
107
+ await enqueueWebhookEvent(db, {
108
+ tenantId,
109
+ orgId: job.orgId,
110
+ kind: 'job.status_changed',
111
+ payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
112
+ })
113
+ } catch (error) {
114
+ const message = error instanceof Error ? error.message : String(error)
115
+ console.warn(`SSSB jobs: job ${jobId} is ${next}, but enqueueing its webhook event failed: ${message}`)
116
+ }
108
117
  }
109
118
  }
110
119
 
package/src/db/keyset.ts CHANGED
@@ -101,15 +101,17 @@ export interface KeysetPage<TRow> {
101
101
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
102
102
 
103
103
  /**
104
- * `parseKeysetCursor` plus the one constraint only this layer knows about: the id half is bound to a
105
- * `uuid`, so an id that is not one can never be a real row here and is rejected at the boundary
106
- * rather than becoming a cast error (a 500, and a probe signal) inside the query. Routes over SQL
107
- * tables should use THIS, not the core parser; an in-memory twin uses the core one, whose row handles
108
- * are not uuids.
104
+ * `parseKeysetCursor` plus the constraints only this layer knows about, each a cast error (a 500, and a
105
+ * probe signal) inside the query if it were let through: the id half is bound to a `uuid`, so an id
106
+ * that is not one can never be a real row here; and the `at` half is bound to a `timestamptz`, which
107
+ * has no year 0000 (JavaScript's calendar does, so the core parser accepts it). Both are rejected at
108
+ * the boundary. Routes over SQL tables should use THIS, not the core parser; an in-memory twin uses
109
+ * the core one, whose row handles are not uuids.
109
110
  */
110
111
  export function parseDbKeysetCursor(raw: string | null | undefined): KeysetCursorParse {
111
112
  const parsed = parseKeysetCursor(raw)
112
- if (parsed.kind === 'after' && !UUID_PATTERN.test(parsed.position.id)) return { kind: 'invalid' }
113
+ if (parsed.kind !== 'after') return parsed
114
+ if (!UUID_PATTERN.test(parsed.position.id) || parsed.position.at.startsWith('0000-')) return { kind: 'invalid' }
113
115
  return parsed
114
116
  }
115
117
 
@@ -55,7 +55,7 @@ export async function up(db: Kysely<any>): Promise<void> {
55
55
  END IF;
56
56
  EXCEPTION WHEN insufficient_privilege THEN
57
57
  -- The statement is printed with the role QUOTED, so copying it runs as-is for any role name.
58
- RAISE EXCEPTION 'keel: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
58
+ RAISE EXCEPTION 'SSSB: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
59
59
  END $$
60
60
  `.execute(db)
61
61
  }
@@ -112,8 +112,15 @@ interface RelationRow {
112
112
  enabled: boolean
113
113
  forced: boolean
114
114
  is_partition: boolean
115
- policies: number
116
- policy_src: string
115
+ }
116
+
117
+ interface PolicyRow {
118
+ schema_name: string
119
+ table_name: string
120
+ policy_name: string
121
+ permissive: boolean
122
+ using_src: string | null
123
+ check_src: string | null
117
124
  }
118
125
 
119
126
  interface PrivilegeRow {
@@ -153,14 +160,7 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
153
160
  c.relkind::text AS kind,
154
161
  c.relrowsecurity AS enabled,
155
162
  c.relforcerowsecurity AS forced,
156
- c.relispartition AS is_partition,
157
- (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid)::int AS policies,
158
- COALESCE((
159
- SELECT string_agg(
160
- COALESCE(pg_get_expr(p.polqual, p.polrelid), '') || ' ' ||
161
- COALESCE(pg_get_expr(p.polwithcheck, p.polrelid), ''), ' ')
162
- FROM pg_policy p WHERE p.polrelid = c.oid
163
- ), '') AS policy_src
163
+ c.relispartition AS is_partition
164
164
  FROM reachable r
165
165
  JOIN pg_class c ON c.oid = r.oid
166
166
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -168,6 +168,26 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
168
168
  ORDER BY n.nspname, c.relname
169
169
  `.execute(db)
170
170
 
171
+ // Policies one row each. They used to be read as one string per table, and since PERMISSIVE policies
172
+ // are OR-ed, one isolating policy hid a `USING (true)` beside it: the table leaked with the gate green.
173
+ const { rows: policyRows } = await sql<PolicyRow>`
174
+ SELECT n.nspname AS schema_name,
175
+ c.relname AS table_name,
176
+ p.polname AS policy_name,
177
+ p.polpermissive AS permissive,
178
+ pg_get_expr(p.polqual, p.polrelid) AS using_src,
179
+ pg_get_expr(p.polwithcheck, p.polrelid) AS check_src
180
+ FROM pg_policy p
181
+ JOIN pg_class c ON c.oid = p.polrelid
182
+ JOIN pg_namespace n ON n.oid = c.relnamespace
183
+ ORDER BY n.nspname, c.relname, p.polname
184
+ `.execute(db)
185
+ const policiesOf = new Map<string, PolicyRow[]>()
186
+ for (const policy of policyRows) {
187
+ const key = `${policy.schema_name}.${policy.table_name}`
188
+ policiesOf.set(key, [...(policiesOf.get(key) ?? []), policy])
189
+ }
190
+
171
191
  const failures: string[] = []
172
192
  const name = (row: RelationRow) => `${row.schema_name}.${row.table_name}`
173
193
  const present = new Set(rows.map(name))
@@ -213,17 +233,31 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
213
233
  continue
214
234
  }
215
235
 
236
+ const policies = policiesOf.get(key) ?? []
216
237
  if (!row.enabled) failures.push(`${key} is reachable by app_user but has no ROW LEVEL SECURITY`)
217
238
  else if (!row.forced) failures.push(`${key} has RLS but not FORCE ROW LEVEL SECURITY`)
218
- else if (row.policies === 0) failures.push(`${key} has RLS enabled but no policy`)
219
- else if (!row.policy_src.includes(TENANT_SETTING)) {
239
+ else if (policies.length === 0) failures.push(`${key} has RLS enabled but no policy`)
240
+ else {
220
241
  // Coverage used to accept any policy at all, so `USING (true)` — a policy that exists and
221
242
  // isolates nothing — passed. Reading the expression is what distinguishes a policy from a
222
- // policy that does something.
223
- failures.push(
224
- `${key} has a policy that never reads ${TENANT_SETTING}, so it does not isolate tenants: ` +
225
- `${row.policy_src.trim()}`,
226
- )
243
+ // policy that does something. Each PERMISSIVE policy is read on its own (they are OR-ed, so
244
+ // one tenant-blind policy opens the table whatever the others say), and each expression it
245
+ // has on its own: a USING that isolates beside a `WITH CHECK (true)` still lets a write land
246
+ // in another tenant. A missing expression is fine (an INSERT policy has no USING; an absent
247
+ // WITH CHECK falls back to USING). RESTRICTIVE policies are AND-ed on top and can only narrow
248
+ // access, so they are not read here (a table with only restrictive policies shows app_user nothing).
249
+ for (const policy of policies) {
250
+ if (!policy.permissive) continue
251
+ const blind = [policy.using_src, policy.check_src].filter(
252
+ (expression): expression is string => expression !== null && !expression.includes(TENANT_SETTING),
253
+ )
254
+ if (blind.length > 0) {
255
+ failures.push(
256
+ `${key} has a permissive policy \`${policy.policy_name}\` that never reads ${TENANT_SETTING}, ` +
257
+ `so it does not isolate tenants (permissive policies are OR-ed): ${blind.join(' / ')}`,
258
+ )
259
+ }
260
+ }
227
261
  }
228
262
  }
229
263
 
@@ -38,9 +38,15 @@ const MAX_COALESCE = 100_000
38
38
  * skipped period. jobs.start() runs only AFTER that transaction commits, exactly as submitJob does, so
39
39
  * a handler never observes a job — or a schedule state — that isn't durable yet.
40
40
  *
41
- * FAULT ISOLATION. One bad row (a malformed spec that parseScheduleSpec rejects, a start() failure)
42
- * must not stall every other schedule: each schedule drains inside its own try/catch, counted in
43
- * `failed` and retried naturally on the next tick because its next_run_at never advanced.
41
+ * FAULT ISOLATION. One bad row must not stall every other schedule: each schedule drains inside its
42
+ * own try/catch, counted in `failed`. What a failure leaves depends on where it happens. A failure
43
+ * INSIDE the transaction (a malformed spec that parseScheduleSpec rejects, a failed insert) rolls it
44
+ * back, so next_run_at never advanced and the next tick tries the row again. A failure AFTER it
45
+ * commits (the audit insert, or jobs.start()) is NOT retried: the job row is already `queued` and the
46
+ * schedule has already moved on to its next slot, so that period's run is not started by this code.
47
+ * Retrying would make the spawn at-least-once for handlers written to run at most once. The job left
48
+ * `queued` is the runner's to deal with: the in-process runner's sweep fails a job left queued too
49
+ * long; under any other runner it stays queued.
44
50
  */
45
51
  export async function runDueSchedules(
46
52
  db: DbPort,
@@ -32,6 +32,10 @@ interface DemoDriverDeps {
32
32
  jobsRef: RefObject<DemoJob[]>
33
33
  setJobs: Dispatch<SetStateAction<DemoJob[]>>
34
34
  log: ActorLog
35
+ /** What the world emits once a job this driver completed is completed, as the server route this driver stands
36
+ * in for does: the service actor's, the job.status_changed webhook; the builder's, the webhook and the admin
37
+ * notification. */
38
+ onCompleted: (job: DemoJob) => void
35
39
  }
36
40
 
37
41
  /** The one team a service actor is scoped to — the twin of its minted token's tenant/org claims. */
@@ -41,7 +45,7 @@ export interface DemoServiceScope {
41
45
  }
42
46
 
43
47
  export function createDemoServiceDriver(
44
- { jobsRef, setJobs, log }: DemoDriverDeps,
48
+ { jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
45
49
  scope: DemoServiceScope,
46
50
  ): ServiceDriver {
47
51
  return {
@@ -95,13 +99,14 @@ export function createDemoServiceDriver(
95
99
  : j,
96
100
  ),
97
101
  )
102
+ onCompleted(job)
98
103
  return 'applied'
99
104
  },
100
105
  }
101
106
  }
102
107
 
103
108
  export function createDemoBuilderDriver(
104
- { jobsRef, setJobs, log }: DemoDriverDeps,
109
+ { jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
105
110
  /** Teams already served by a dedicated service actor (@sssb/app-config/jobs' serviceManagedOrgSlugs) —
106
111
  * excluded so the two actors' job pools stay disjoint, exactly like listPendingBuilds. */
107
112
  serviceManagedOrgSlugs: readonly string[],
@@ -155,6 +160,7 @@ export function createDemoBuilderDriver(
155
160
  return { ...j, status: 'completed', timeline }
156
161
  }),
157
162
  )
163
+ onCompleted(job)
158
164
  return 'applied'
159
165
  },
160
166
  }
@@ -12,6 +12,15 @@ function escapeHtml(value: string): string {
12
12
  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
13
13
  }
14
14
 
15
+ /**
16
+ * Twin of the server's notification email (../server-lib/notify.ts): a heading, a body line and the footer. The
17
+ * values are already-translated copy, and that copy interpolates what people typed (an invited address, an app's
18
+ * subject line), so each is escaped.
19
+ */
20
+ export function buildNotificationEmailHtml(labels: { title: string; body: string; footer: string }): string {
21
+ return `<h2>${escapeHtml(labels.title)}</h2><p>${escapeHtml(labels.body)}</p><p>${escapeHtml(labels.footer)}</p>`
22
+ }
23
+
15
24
  /** Twin of ../email/templates/invite-email.tsx. */
16
25
  export function buildInviteEmailHtml(
17
26
  labels: { heading: string; body: string; button: string; linkFallback: string },
@@ -105,8 +105,9 @@ export function useTours(
105
105
  // Where the story is meant to be standing: captured when a step's entry script finishes, and the
106
106
  // place "Back to the tour" returns to.
107
107
  const stepLocationRef = useRef<string | null>(null)
108
- // Bumped on every goto so a script that finishes AFTER the viewer pressed Back cannot light that
109
- // abandoned step's spotlight on the screen they are now looking at.
108
+ // Bumped on every goto and end, so a script that finishes AFTER the viewer pressed Back cannot light that
109
+ // abandoned step's spotlight on the screen they are now looking at, and a Next whose advance script was
110
+ // running when the viewer pressed Exit cannot re-open the tour they just closed.
110
111
  const runTokenRef = useRef(0)
111
112
 
112
113
  const tour = appTours.find((candidate) => candidate.id === activeId) ?? null
@@ -155,6 +156,7 @@ export function useTours(
155
156
  }
156
157
 
157
158
  function end(stepsRun: number) {
159
+ runTokenRef.current += 1
158
160
  cancelScript()
159
161
  hideCursor()
160
162
  writeResumeMarker(null)
@@ -190,12 +192,14 @@ export function useTours(
190
192
  async function next() {
191
193
  if (advancing || !tour) return
192
194
  const step = tour.steps[idx]
195
+ const token = runTokenRef.current
193
196
  setAdvancing(true)
194
197
  // Next DURING an entry script fast-forwards it to completion rather than cancelling it: a
195
198
  // cancelled script leaves a half-typed form on screen, which reads as a bug.
196
199
  if (isDriving()) {
197
200
  requestFastForward()
198
201
  while (isDriving()) await new Promise((resolve) => setTimeout(resolve, 60))
202
+ if (runTokenRef.current !== token) return
199
203
  }
200
204
  // Move the resume marker BEFORE the advance script runs. Every submission lives in `advance`,
201
205
  // and on a server host some of them reload the page (a feature flag, a person switch) — writing
@@ -206,6 +210,8 @@ export function useTours(
206
210
  setSpotlight(null) // the vignette lifts before the cursor clicks through it
207
211
  await runScript(step.advance, addMiss)
208
212
  }
213
+ // Exit (or anything else that moved the tour) while this awaited: that already settled the tour.
214
+ if (runTokenRef.current !== token) return
209
215
  setAdvancing(false)
210
216
  if (idx >= tour.steps.length - 1) end(tour.steps.length)
211
217
  else goto(tour.id, idx + 1)