@sssb/kit 0.7.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/edge-headers.ts +171 -0
- package/src/adapters/fake/simulator-admin.ts +7 -3
- package/src/adapters/fake/storage.ts +60 -8
- package/src/adapters/origin-form.ts +24 -0
- package/src/adapters/real/auth.ts +3 -2
- package/src/adapters/real/clerk-authorized-parties.ts +43 -0
- package/src/adapters/real/clerk-proxy.ts +9 -1
- package/src/adapters/real/index.ts +16 -0
- package/src/adapters/real/optional-ports.ts +3 -2
- package/src/adapters/real/s3-storage.ts +66 -5
- package/src/adapters/real/sign-in-form.tsx +206 -23
- package/src/adapters/real/storage-settings.ts +7 -4
- package/src/adapters/real/storage.ts +9 -7
- package/src/authz/route-policy.ts +7 -4
- package/src/components/auth/second-factor-step.tsx +254 -0
- package/src/components/simulator/actors-app.tsx +1 -1
- package/src/components/simulator/errors-app.tsx +4 -1
- package/src/components/simulator/inbound-app.tsx +1 -1
- package/src/components/simulator/jobs-app.tsx +3 -3
- package/src/components/simulator/mail-app.tsx +1 -1
- package/src/components/simulator/mail-link.ts +27 -0
- package/src/components/simulator/simulator-host.tsx +556 -82
- package/src/components/simulator/simulator-panel.tsx +1 -1
- package/src/db/inbound-email.ts +7 -5
- package/src/db/migrations/0018_organizations_write.ts +87 -0
- package/src/db/migrations/index.ts +2 -0
- package/src/db/org-lookup.ts +4 -4
- package/src/db/rls-coverage.ts +140 -24
- package/src/db/rls-proofs.ts +147 -0
- package/src/demo-static/world.ts +2 -2
- package/src/guide.md +6 -0
- package/src/i18n/messages/en.json +20 -1
- package/src/i18n/messages/es.json +20 -1
- package/src/ports/storage.ts +50 -9
- package/src/server-lib/invite.ts +5 -1
- package/src/server-lib/simulator-api.ts +320 -3
- package/src/service-auth/secret-env.ts +19 -0
- package/src/service-auth/standard-webhooks.ts +358 -0
- package/src/service-auth/webhook.ts +39 -12
|
@@ -1,20 +1,72 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
|
+
import { presets } from '@sssb/app-config/presets'
|
|
3
4
|
import { useTranslations } from 'next-intl'
|
|
4
5
|
import type { ReactNode } from 'react'
|
|
5
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
6
|
-
import type {
|
|
6
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
|
7
|
+
import type {
|
|
8
|
+
SimulatorAgreements,
|
|
9
|
+
SimulatorAudit,
|
|
10
|
+
SimulatorEvents,
|
|
11
|
+
SimulatorFlags,
|
|
12
|
+
SimulatorHooks,
|
|
13
|
+
SimulatorInbound,
|
|
14
|
+
SimulatorJobs,
|
|
15
|
+
SimulatorMail,
|
|
16
|
+
SimulatorMessages,
|
|
17
|
+
SimulatorSchedules,
|
|
18
|
+
SimulatorSnapshots,
|
|
19
|
+
SimulatorSummary,
|
|
20
|
+
} from '../../server-lib/simulator-api'
|
|
21
|
+
import { resolveWorldStart } from '../../core/presets'
|
|
7
22
|
import { sameOriginPath } from '../../core/same-origin-path'
|
|
8
|
-
import {
|
|
23
|
+
import { useTours } from '../../demo-static/tour/use-tours'
|
|
24
|
+
import type { ScrubResult } from './errors-app'
|
|
25
|
+
import type { InboundComposeInput } from './inbound-app'
|
|
26
|
+
import type { DevTickerLike } from './jobs-app'
|
|
27
|
+
import { mailLinkTarget } from './mail-link'
|
|
28
|
+
import { SimulatorPanel, type SimulatorExtraTab, type SimulatorNotice } from './simulator-panel'
|
|
9
29
|
|
|
10
30
|
const EMPTY_SUMMARY: SimulatorSummary = { viewpoint: null, signedIn: false, people: [] }
|
|
11
31
|
const EMPTY_MAIL: SimulatorMail = { emails: [], mailSeenAt: null, allCount: 0 }
|
|
12
32
|
const EMPTY_JOBS: SimulatorJobs = { jobs: [], held: false }
|
|
13
33
|
const EMPTY_SCHEDULES: SimulatorSchedules = { schedules: [], clockOffsetMs: 0, worldNow: new Date(0).toISOString() }
|
|
34
|
+
const EMPTY_SNAPSHOTS: SimulatorSnapshots = { snapshots: [] }
|
|
35
|
+
const EMPTY_FLAGS: SimulatorFlags = { flags: [] }
|
|
36
|
+
const EMPTY_AGREEMENTS: SimulatorAgreements = { agreements: [] }
|
|
37
|
+
const EMPTY_INBOUND: SimulatorInbound = { inbound: [], orgs: [], people: [], handlers: [], domain: '' }
|
|
38
|
+
const EMPTY_MESSAGES: SimulatorMessages = { messages: [] }
|
|
39
|
+
const EMPTY_EVENTS: SimulatorEvents = { events: [] }
|
|
40
|
+
const EMPTY_AUDIT: SimulatorAudit = { audit: [] }
|
|
41
|
+
const EMPTY_HOOKS: SimulatorHooks = { endpoints: [], deliveries: [], failingEndpointIds: [] }
|
|
42
|
+
/** What the app's own `api/simulator/ticker` route answers: the dev ticker's status, which the control shows as it is. */
|
|
43
|
+
type TickerStatus = Omit<DevTickerLike, 'onStart' | 'onStop'>
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What the host shares with an app's own Simulator tab (`extraTabs`): the world's jobs, as the Jobs tab shows them,
|
|
47
|
+
* refreshed while that tab is open. Provisional, as `extraTabs` is, until safeinsights/sssb#152 decides how an app's
|
|
48
|
+
* tabs reach the host.
|
|
49
|
+
*/
|
|
50
|
+
export interface SimulatorWorld {
|
|
51
|
+
jobs: SimulatorJobs
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const SimulatorWorldContext = createContext<SimulatorWorld>({ jobs: EMPTY_JOBS })
|
|
55
|
+
|
|
56
|
+
/** The host's world, for an app's own tab rendered through `SimulatorHost`'s `extraTabs`. */
|
|
57
|
+
export function useSimulatorWorld(): SimulatorWorld {
|
|
58
|
+
return useContext(SimulatorWorldContext)
|
|
59
|
+
}
|
|
60
|
+
|
|
14
61
|
const EXPANDED_POLL_MS = 4_000
|
|
15
62
|
const COLLAPSED_POLL_MS = 15_000
|
|
16
63
|
const NOTICE_MS = 6_000
|
|
17
64
|
const MAIL_SCOPE_KEY = 'app-simulator-mail-scope'
|
|
65
|
+
/**
|
|
66
|
+
* Left right before a reset, a restore or a preset load reloads the page, so the next mount can say what happened:
|
|
67
|
+
* the panel's own notice, surviving exactly one navigation.
|
|
68
|
+
*/
|
|
69
|
+
const POST_NOTICE_KEY = 'app-simulator-post-notice'
|
|
18
70
|
const API = '/api/simulator'
|
|
19
71
|
|
|
20
72
|
/** A POST to the server host. Always JSON, even with no body: the server refuses any other content type. */
|
|
@@ -51,6 +103,38 @@ function useTickets() {
|
|
|
51
103
|
)
|
|
52
104
|
}
|
|
53
105
|
|
|
106
|
+
/** What a world-start handler answers once it has started a full reload: nothing runs after it on that document. */
|
|
107
|
+
function untilReload(): Promise<never> {
|
|
108
|
+
return new Promise<never>(() => {})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
type PostNotice = { kind: 'reset' } | { kind: 'restore' | 'preset'; name: string }
|
|
112
|
+
|
|
113
|
+
function writePostNotice(notice: PostNotice) {
|
|
114
|
+
try {
|
|
115
|
+
window.sessionStorage.setItem(POST_NOTICE_KEY, JSON.stringify(notice))
|
|
116
|
+
} catch {
|
|
117
|
+
// No storage: the reload happens all the same, unannounced.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The marker a reload left, read once and removed. */
|
|
122
|
+
function takePostNotice(): PostNotice | null {
|
|
123
|
+
try {
|
|
124
|
+
const stored = window.sessionStorage.getItem(POST_NOTICE_KEY)
|
|
125
|
+
if (!stored) return null
|
|
126
|
+
window.sessionStorage.removeItem(POST_NOTICE_KEY)
|
|
127
|
+
const parsed = JSON.parse(stored) as { kind?: unknown; name?: unknown }
|
|
128
|
+
if (parsed.kind === 'reset') return { kind: 'reset' }
|
|
129
|
+
if ((parsed.kind === 'restore' || parsed.kind === 'preset') && typeof parsed.name === 'string') {
|
|
130
|
+
return { kind: parsed.kind, name: parsed.name }
|
|
131
|
+
}
|
|
132
|
+
return null
|
|
133
|
+
} catch {
|
|
134
|
+
return null
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
54
138
|
function readStoredScope(): 'person' | 'all' | null {
|
|
55
139
|
try {
|
|
56
140
|
const stored = window.localStorage.getItem(MAIL_SCOPE_KEY)
|
|
@@ -67,16 +151,37 @@ function readStoredScope(): 'person' | 'all' | null {
|
|
|
67
151
|
* build loads it.
|
|
68
152
|
*
|
|
69
153
|
* It wires the tabs that host serves: People (switch to anyone, signed in or not), Mail (each person's inbox, or all
|
|
70
|
-
* of it
|
|
71
|
-
*
|
|
72
|
-
*
|
|
154
|
+
* of it, with the inbound mail the world sent the app and a form to send more), Messages (every SMS), Events (analytics
|
|
155
|
+
* events, with the audit trail beneath), Jobs with the world clock (run what is queued, move the clock, run what is
|
|
156
|
+
* due), Hooks (every webhook endpoint and delivery, an endpoint made to fail, due deliveries run), Errors (an error's
|
|
157
|
+
* event before and after scrubbing), Snapshots (reset the world, save, restore and delete snapshots, flip a feature
|
|
158
|
+
* flag, bump an agreement, load a demo preset) and, when the app registers any, Tours. A reset, a restore and a preset load each reload the page, since every page shows the world
|
|
159
|
+
* they replaced; a tour that starts from one of them resumes itself after the reload. The panel leaves out every tab it
|
|
160
|
+
* is not given.
|
|
161
|
+
*
|
|
162
|
+
* Two parts of the Simulator stay the app's until safeinsights/sssb#152 decides them, and the host only renders what the
|
|
163
|
+
* app hands it. An app's own tabs (the Actors tab) come in as `extraTabs`, the panel's own type; their content reads the
|
|
164
|
+
* world's jobs with `useSimulatorWorld()`. The Jobs tab's dev ticker shows only where the app's own route,
|
|
165
|
+
* `src/app/api/simulator/ticker/route.ts`, answers `ticker` (a static segment, so it wins over the catch-all, which
|
|
166
|
+
* answers 404 there): once it answers 404, the host asks no more while it is mounted. Both are provisional.
|
|
73
167
|
*
|
|
74
168
|
* Polling, never a stream: the summary (the pill's unread badge) on a slow beat while the panel is collapsed, and
|
|
75
169
|
* the open tab's data on a faster one while it is expanded. Every acknowledgement is a notice inside the panel,
|
|
76
170
|
* never the app's own toast.
|
|
77
171
|
*/
|
|
78
|
-
export function SimulatorHost({
|
|
172
|
+
export function SimulatorHost({
|
|
173
|
+
locale,
|
|
174
|
+
extraTabs,
|
|
175
|
+
children,
|
|
176
|
+
}: {
|
|
177
|
+
locale: string
|
|
178
|
+
/** An app's own Simulator tabs, built by the app (ADR-0006). Provisional until safeinsights/sssb#152. */
|
|
179
|
+
extraTabs?: SimulatorExtraTab[] | undefined
|
|
180
|
+
children: ReactNode
|
|
181
|
+
}) {
|
|
79
182
|
const t = useTranslations('simulator')
|
|
183
|
+
// A demo preset's title is a key into the app's catalog, from its root.
|
|
184
|
+
const tRoot = useTranslations()
|
|
80
185
|
const [summary, setSummary] = useState<SimulatorSummary>(EMPTY_SUMMARY)
|
|
81
186
|
const [expanded, setExpanded] = useState(false)
|
|
82
187
|
const [activeTab, setActiveTab] = useState('people')
|
|
@@ -84,12 +189,52 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
84
189
|
const [mail, setMail] = useState<SimulatorMail>(EMPTY_MAIL)
|
|
85
190
|
const [jobsData, setJobsData] = useState<SimulatorJobs>(EMPTY_JOBS)
|
|
86
191
|
const [schedulesData, setSchedulesData] = useState<SimulatorSchedules>(EMPTY_SCHEDULES)
|
|
192
|
+
const [snapshotsData, setSnapshotsData] = useState<SimulatorSnapshots>(EMPTY_SNAPSHOTS)
|
|
193
|
+
const [flagsData, setFlagsData] = useState<SimulatorFlags>(EMPTY_FLAGS)
|
|
194
|
+
const [agreementsData, setAgreementsData] = useState<SimulatorAgreements>(EMPTY_AGREEMENTS)
|
|
195
|
+
const [snapshotsBusy, setSnapshotsBusy] = useState(false)
|
|
196
|
+
const [busySnapshot, setBusySnapshot] = useState<string | null>(null)
|
|
197
|
+
const [busyPreset, setBusyPreset] = useState<string | null>(null)
|
|
198
|
+
const [busyAgreement, setBusyAgreement] = useState<string | null>(null)
|
|
199
|
+
const [inboundData, setInboundData] = useState<SimulatorInbound>(EMPTY_INBOUND)
|
|
200
|
+
const [messagesData, setMessagesData] = useState<SimulatorMessages>(EMPTY_MESSAGES)
|
|
201
|
+
const [eventsData, setEventsData] = useState<SimulatorEvents>(EMPTY_EVENTS)
|
|
202
|
+
const [auditData, setAuditData] = useState<SimulatorAudit>(EMPTY_AUDIT)
|
|
203
|
+
const [hooksData, setHooksData] = useState<SimulatorHooks>(EMPTY_HOOKS)
|
|
204
|
+
// Null until the app's ticker route answers, and never asked again once it answers 404 (no such route).
|
|
205
|
+
const [tickerData, setTickerData] = useState<TickerStatus | null>(null)
|
|
206
|
+
const tickerOffered = useRef(true)
|
|
87
207
|
const [notices, setNotices] = useState<SimulatorNotice[]>([])
|
|
88
208
|
const noticeSeq = useRef(0)
|
|
89
209
|
const prevUnread = useRef<Map<string, number> | null>(null)
|
|
90
210
|
const summaryTickets = useTickets()
|
|
91
211
|
const mailTickets = useTickets()
|
|
92
212
|
const jobsTickets = useTickets()
|
|
213
|
+
const schedulesTickets = useTickets()
|
|
214
|
+
// A poll's answer must not overwrite a start or stop's: a start or stop takes its ticket once its POST has been
|
|
215
|
+
// answered, so a poll sent before or during it is older and is dropped.
|
|
216
|
+
const tickerTickets = useTickets()
|
|
217
|
+
const inboundTickets = useTickets()
|
|
218
|
+
const messagesTickets = useTickets()
|
|
219
|
+
const eventsTickets = useTickets()
|
|
220
|
+
const auditTickets = useTickets()
|
|
221
|
+
const hooksTickets = useTickets()
|
|
222
|
+
// The Snapshots tab's feeds: two of its actions can be in flight at once (bump one agreement, then another), and
|
|
223
|
+
// the refresh one triggers must not land over the next one's.
|
|
224
|
+
const snapshotsTickets = useTickets()
|
|
225
|
+
const flagsTickets = useTickets()
|
|
226
|
+
const agreementsTickets = useTickets()
|
|
227
|
+
// The app's tours (`@sssb/app-config/tours`, read by the engine itself). A tour's starting world resolves the same
|
|
228
|
+
// way on every host (`resolveWorldStart`): a reset, a registered demo preset, or here a saved snapshot. Each reloads
|
|
229
|
+
// the page, and the engine's resume marker carries the tour across it.
|
|
230
|
+
const tours = useTours({
|
|
231
|
+
onSnapshot: (snapshot) => {
|
|
232
|
+
const start = resolveWorldStart(snapshot, presets)
|
|
233
|
+
if (start.kind === 'reset') return handleReset()
|
|
234
|
+
if (start.kind === 'preset') return handleLoadPreset(start.preset.id)
|
|
235
|
+
return handleRestoreSnapshot(start.name)
|
|
236
|
+
},
|
|
237
|
+
})
|
|
93
238
|
|
|
94
239
|
const personEmail = summary.people.find((person) => person.key === summary.viewpoint)?.email ?? null
|
|
95
240
|
// Signed out, or no viewpoint yet: there is no one's own inbox to show, so the scope is every inbox.
|
|
@@ -130,23 +275,120 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
130
275
|
if (next && mailQuery === shownMailQuery.current && mailTickets.fresh(ticket)) setMail(next)
|
|
131
276
|
}, [mailQuery, mailTickets])
|
|
132
277
|
|
|
278
|
+
// Jobs and the schedules beside them, each landing on its own: an app's tab that reads the jobs keeps them fresh
|
|
279
|
+
// even when the schedules cannot answer.
|
|
133
280
|
const refreshJobs = useCallback(async () => {
|
|
134
|
-
const
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
getJson<
|
|
281
|
+
const jobsTicket = jobsTickets.take()
|
|
282
|
+
const schedulesTicket = schedulesTickets.take()
|
|
283
|
+
await Promise.all([
|
|
284
|
+
getJson<SimulatorJobs>('jobs').then((next) => {
|
|
285
|
+
if (next && jobsTickets.fresh(jobsTicket)) setJobsData(next)
|
|
286
|
+
}),
|
|
287
|
+
getJson<SimulatorSchedules>('schedules').then((next) => {
|
|
288
|
+
if (next && schedulesTickets.fresh(schedulesTicket)) setSchedulesData(next)
|
|
289
|
+
}),
|
|
290
|
+
])
|
|
291
|
+
}, [jobsTickets, schedulesTickets])
|
|
292
|
+
|
|
293
|
+
// The Snapshots tab is fetched when it opens and after each of its own actions, never polled: its own actions
|
|
294
|
+
// refetch or reload, and a change made elsewhere (an agreement edited on an app page) shows when it next opens.
|
|
295
|
+
const refreshSnapshots = useCallback(async () => {
|
|
296
|
+
const ticket = snapshotsTickets.take()
|
|
297
|
+
const next = await getJson<SimulatorSnapshots>('snapshots')
|
|
298
|
+
if (next && snapshotsTickets.fresh(ticket)) setSnapshotsData(next)
|
|
299
|
+
}, [snapshotsTickets])
|
|
300
|
+
|
|
301
|
+
const refreshFlags = useCallback(async () => {
|
|
302
|
+
const ticket = flagsTickets.take()
|
|
303
|
+
const next = await getJson<SimulatorFlags>('flags')
|
|
304
|
+
if (next && flagsTickets.fresh(ticket)) setFlagsData(next)
|
|
305
|
+
}, [flagsTickets])
|
|
306
|
+
|
|
307
|
+
const refreshAgreements = useCallback(async () => {
|
|
308
|
+
const ticket = agreementsTickets.take()
|
|
309
|
+
const next = await getJson<SimulatorAgreements>('agreements')
|
|
310
|
+
if (next && agreementsTickets.fresh(ticket)) setAgreementsData(next)
|
|
311
|
+
}, [agreementsTickets])
|
|
312
|
+
|
|
313
|
+
const refreshInbound = useCallback(async () => {
|
|
314
|
+
const ticket = inboundTickets.take()
|
|
315
|
+
const next = await getJson<SimulatorInbound>('inbound')
|
|
316
|
+
if (next && inboundTickets.fresh(ticket)) setInboundData(next)
|
|
317
|
+
}, [inboundTickets])
|
|
318
|
+
|
|
319
|
+
const refreshMessages = useCallback(async () => {
|
|
320
|
+
const ticket = messagesTickets.take()
|
|
321
|
+
const next = await getJson<SimulatorMessages>('messages')
|
|
322
|
+
if (next && messagesTickets.fresh(ticket)) setMessagesData(next)
|
|
323
|
+
}, [messagesTickets])
|
|
324
|
+
|
|
325
|
+
// The audit trail renders on the Events tab, beneath the events, so the two are fetched together; each lands on its
|
|
326
|
+
// own, so one that fails never holds the other back.
|
|
327
|
+
const refreshEvents = useCallback(async () => {
|
|
328
|
+
const eventsTicket = eventsTickets.take()
|
|
329
|
+
const auditTicket = auditTickets.take()
|
|
330
|
+
await Promise.all([
|
|
331
|
+
getJson<SimulatorEvents>('events').then((next) => {
|
|
332
|
+
if (next && eventsTickets.fresh(eventsTicket)) setEventsData(next)
|
|
333
|
+
}),
|
|
334
|
+
getJson<SimulatorAudit>('audit').then((next) => {
|
|
335
|
+
if (next && auditTickets.fresh(auditTicket)) setAuditData(next)
|
|
336
|
+
}),
|
|
138
337
|
])
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
338
|
+
}, [eventsTickets, auditTickets])
|
|
339
|
+
|
|
340
|
+
const refreshTicker = useCallback(async () => {
|
|
341
|
+
if (!tickerOffered.current) return
|
|
342
|
+
const ticket = tickerTickets.take()
|
|
343
|
+
const response = await fetch(`${API}/ticker`)
|
|
344
|
+
if (response.status === 404) {
|
|
345
|
+
tickerOffered.current = false
|
|
346
|
+
setTickerData(null)
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
if (!response.ok) return
|
|
350
|
+
const next = (await response.json()) as TickerStatus
|
|
351
|
+
if (tickerTickets.fresh(ticket)) setTickerData(next)
|
|
352
|
+
}, [tickerTickets])
|
|
353
|
+
|
|
354
|
+
const refreshHooks = useCallback(async () => {
|
|
355
|
+
const ticket = hooksTickets.take()
|
|
356
|
+
const next = await getJson<SimulatorHooks>('webhooks')
|
|
357
|
+
if (next && hooksTickets.fresh(ticket)) setHooksData(next)
|
|
358
|
+
}, [hooksTickets])
|
|
359
|
+
|
|
360
|
+
// A boolean, not the array: an app that builds `extraTabs` afresh on each render must not restart the poll.
|
|
361
|
+
const appTabOpen = extraTabs?.some((tab) => tab.id === activeTab) ?? false
|
|
143
362
|
|
|
144
363
|
/** The open tab's own data, when the panel is expanded. */
|
|
145
364
|
const refreshOpenTab = useCallback(() => {
|
|
146
365
|
if (!expanded) return
|
|
147
|
-
if (activeTab === 'mail')
|
|
148
|
-
|
|
149
|
-
|
|
366
|
+
if (activeTab === 'mail') {
|
|
367
|
+
void refreshMail()
|
|
368
|
+
// Inbound mail is on the Mail tab, beside the outbound catch-store.
|
|
369
|
+
void refreshInbound()
|
|
370
|
+
}
|
|
371
|
+
if (activeTab === 'messages') void refreshMessages()
|
|
372
|
+
if (activeTab === 'events') void refreshEvents()
|
|
373
|
+
if (activeTab === 'jobs') {
|
|
374
|
+
void refreshJobs()
|
|
375
|
+
void refreshTicker()
|
|
376
|
+
}
|
|
377
|
+
// An app's own tab reads the world's jobs (`useSimulatorWorld`), so they are polled while it is open too.
|
|
378
|
+
if (appTabOpen) void refreshJobs()
|
|
379
|
+
if (activeTab === 'hooks') void refreshHooks()
|
|
380
|
+
}, [
|
|
381
|
+
expanded,
|
|
382
|
+
activeTab,
|
|
383
|
+
appTabOpen,
|
|
384
|
+
refreshMail,
|
|
385
|
+
refreshInbound,
|
|
386
|
+
refreshMessages,
|
|
387
|
+
refreshEvents,
|
|
388
|
+
refreshJobs,
|
|
389
|
+
refreshTicker,
|
|
390
|
+
refreshHooks,
|
|
391
|
+
])
|
|
150
392
|
|
|
151
393
|
useEffect(() => {
|
|
152
394
|
// Fetch on mount, and restore the remembered mail scope: syncing with external systems (the server, the
|
|
@@ -155,6 +397,12 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
155
397
|
void refresh()
|
|
156
398
|
const storedScope = readStoredScope()
|
|
157
399
|
if (storedScope) setMailScope(storedScope)
|
|
400
|
+
// What the reload before this mount did, if a reset, a restore or a preset load started it.
|
|
401
|
+
const posted = takePostNotice()
|
|
402
|
+
if (posted?.kind === 'reset') pushNotice(t('noticeWorldReset'))
|
|
403
|
+
if (posted?.kind === 'restore') pushNotice(t('noticeSnapshotRestored', { name: posted.name }))
|
|
404
|
+
const preset = posted?.kind === 'preset' ? presets.find((candidate) => candidate.id === posted.name) : undefined
|
|
405
|
+
if (preset) pushNotice(t('noticePresetLoaded', { name: tRoot(preset.titleKey) }))
|
|
158
406
|
// Mount-only.
|
|
159
407
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
160
408
|
}, [])
|
|
@@ -177,6 +425,15 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
177
425
|
refreshOpenTab()
|
|
178
426
|
}, [refreshOpenTab])
|
|
179
427
|
|
|
428
|
+
useEffect(() => {
|
|
429
|
+
if (!expanded || activeTab !== 'snapshots') return
|
|
430
|
+
// Fetched when the tab opens: the same external-system sync as the mount effect.
|
|
431
|
+
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
432
|
+
void refreshSnapshots()
|
|
433
|
+
void refreshFlags()
|
|
434
|
+
void refreshAgreements()
|
|
435
|
+
}, [expanded, activeTab, refreshSnapshots, refreshFlags, refreshAgreements])
|
|
436
|
+
|
|
180
437
|
function handleSelect(person: string) {
|
|
181
438
|
void post('viewpoint', { person, locale }).then(async (response) => {
|
|
182
439
|
if (!response.ok) return
|
|
@@ -205,31 +462,11 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
205
462
|
}
|
|
206
463
|
|
|
207
464
|
function handleOpenLink(href: string) {
|
|
208
|
-
// Same origin only, and never silently
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (path) {
|
|
214
|
-
window.location.assign(path)
|
|
215
|
-
return
|
|
216
|
-
}
|
|
217
|
-
try {
|
|
218
|
-
const url = href.startsWith('//') ? new URL(href, window.location.href) : new URL(href)
|
|
219
|
-
const local =
|
|
220
|
-
url.origin === window.location.origin ? sameOriginPath(url.pathname + url.search + url.hash) : null
|
|
221
|
-
if (local) {
|
|
222
|
-
window.location.assign(local)
|
|
223
|
-
return
|
|
224
|
-
}
|
|
225
|
-
if (url.origin === window.location.origin || url.origin === 'null') {
|
|
226
|
-
pushNotice(t('noticeLinkUnusable', { href }))
|
|
227
|
-
} else {
|
|
228
|
-
pushNotice(t('noticeLinkOrigin', { origin: url.origin }))
|
|
229
|
-
}
|
|
230
|
-
} catch {
|
|
231
|
-
pushNotice(t('noticeLinkUnusable', { href }))
|
|
232
|
-
}
|
|
465
|
+
// Same origin only, and never silently: `mailLinkTarget` says where to go, or why not.
|
|
466
|
+
const target = mailLinkTarget(href, window.location.href)
|
|
467
|
+
if ('path' in target) window.location.assign(target.path)
|
|
468
|
+
else if (target.refused === 'origin') pushNotice(t('noticeLinkOrigin', { origin: target.origin }))
|
|
469
|
+
else pushNotice(t('noticeLinkUnusable', { href }))
|
|
233
470
|
}
|
|
234
471
|
|
|
235
472
|
function handleCopyLink(href: string) {
|
|
@@ -248,6 +485,82 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
248
485
|
})
|
|
249
486
|
}
|
|
250
487
|
|
|
488
|
+
/**
|
|
489
|
+
* The ticker's route answers its status on every outcome (with `error` on a refusal), so the control always shows
|
|
490
|
+
* what the server holds, and the notice says what happened to the click. A 404 means the app has no such route.
|
|
491
|
+
*/
|
|
492
|
+
async function postTicker(request: { action: 'start'; seconds: number } | { action: 'stop' }) {
|
|
493
|
+
const response = await post('ticker', request).catch(() => null)
|
|
494
|
+
// Taken once the server has answered, so every poll sent before or during this POST is older than it.
|
|
495
|
+
const ticket = tickerTickets.take()
|
|
496
|
+
if (!response) return null
|
|
497
|
+
if (response.status === 404) {
|
|
498
|
+
tickerOffered.current = false
|
|
499
|
+
setTickerData(null)
|
|
500
|
+
return null
|
|
501
|
+
}
|
|
502
|
+
const body = (await response.json().catch(() => null)) as (TickerStatus & { error?: string }) | null
|
|
503
|
+
// A body without the status (a 500 while the route compiles, say) leaves the control as it was.
|
|
504
|
+
if (typeof body?.running !== 'boolean') return null
|
|
505
|
+
// Stored whole, `error` and all (the control ignores it, and the next GET replaces it).
|
|
506
|
+
if (tickerTickets.fresh(ticket)) setTickerData(body)
|
|
507
|
+
return { error: body.error, status: body }
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function handleStartTicker(seconds: number) {
|
|
511
|
+
const result = await postTicker({ action: 'start', seconds })
|
|
512
|
+
if (!result) return
|
|
513
|
+
if (result.error === 'invalid-interval') {
|
|
514
|
+
pushNotice(t('noticeTickerInvalid', { min: result.status.minSeconds, max: result.status.maxSeconds }))
|
|
515
|
+
} else if (result.error === 'running-elsewhere') {
|
|
516
|
+
pushNotice(t('noticeTickerElsewhere'))
|
|
517
|
+
} else if (result.status.running && result.status.seconds !== null) {
|
|
518
|
+
pushNotice(t('noticeTickerStarted', { seconds: result.status.seconds }))
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
async function handleStopTicker() {
|
|
523
|
+
const result = await postTicker({ action: 'stop' })
|
|
524
|
+
if (result && !result.status.running) pushNotice(t('noticeTickerStopped'))
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function handleComposeInbound(input: InboundComposeInput) {
|
|
528
|
+
void post('inbound/compose', input)
|
|
529
|
+
.then(async (response) => {
|
|
530
|
+
if (!response.ok) return
|
|
531
|
+
const { outcome } = (await response.json()) as { outcome: { status: string } }
|
|
532
|
+
// The new row, and any mail a handler sent in reply (a person's unread badge too).
|
|
533
|
+
await Promise.all([refreshInbound(), refreshMail(), refresh()])
|
|
534
|
+
pushNotice(
|
|
535
|
+
t('noticeInboundSent', {
|
|
536
|
+
status: t(`inboundStatus_${outcome.status}` as 'inboundStatus_handled'),
|
|
537
|
+
}),
|
|
538
|
+
)
|
|
539
|
+
})
|
|
540
|
+
.catch(() => undefined)
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function handleToggleFail(endpointId: string, failing: boolean) {
|
|
544
|
+
const response = await post('webhooks/fail', { endpointId, failing })
|
|
545
|
+
if (!response.ok) return
|
|
546
|
+
await refreshHooks()
|
|
547
|
+
pushNotice(failing ? t('noticeHookFailOn') : t('noticeHookFailOff'))
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async function handleRunDueDeliveries() {
|
|
551
|
+
const response = await post('webhooks/run-due')
|
|
552
|
+
if (!response.ok) return
|
|
553
|
+
const { deliveries } = (await response.json()) as { deliveries: { delivered: number } }
|
|
554
|
+
await refreshHooks()
|
|
555
|
+
pushNotice(t('noticeHooksDelivered', { count: deliveries.delivered }))
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async function handleServerErrorScenario(): Promise<ScrubResult> {
|
|
559
|
+
const response = await fetch(`${API}/error-scenario`)
|
|
560
|
+
if (!response.ok) throw new Error(`error-scenario answered ${response.status}`)
|
|
561
|
+
return (await response.json()) as ScrubResult
|
|
562
|
+
}
|
|
563
|
+
|
|
251
564
|
async function handleRunPending() {
|
|
252
565
|
const response = await post('jobs/run-pending')
|
|
253
566
|
if (!response.ok) return
|
|
@@ -279,6 +592,116 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
279
592
|
await afterSchedulesChanged(await post('schedules/run-due'), null)
|
|
280
593
|
}
|
|
281
594
|
|
|
595
|
+
// The three world-start handlers (reset, restore, preset) answer a promise a tour's start can await: false when the
|
|
596
|
+
// server refused, and on success one that never settles, because the page is reloading. Awaiting it keeps a tour
|
|
597
|
+
// from showing its first step on a document about to be replaced.
|
|
598
|
+
function handleReset(): Promise<boolean> {
|
|
599
|
+
setSnapshotsBusy(true)
|
|
600
|
+
const failed = () => {
|
|
601
|
+
setSnapshotsBusy(false)
|
|
602
|
+
return false
|
|
603
|
+
}
|
|
604
|
+
return post('reset').then((response) => {
|
|
605
|
+
if (!response.ok) return failed()
|
|
606
|
+
writePostNotice({ kind: 'reset' })
|
|
607
|
+
window.location.assign(`/${locale}`)
|
|
608
|
+
return untilReload()
|
|
609
|
+
}, failed)
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function handleRestoreSnapshot(name: string): Promise<boolean> {
|
|
613
|
+
setBusySnapshot(name)
|
|
614
|
+
const failed = () => {
|
|
615
|
+
setBusySnapshot(null)
|
|
616
|
+
return false
|
|
617
|
+
}
|
|
618
|
+
return post('snapshots/restore', { name }).then((response) => {
|
|
619
|
+
if (!response.ok) return failed()
|
|
620
|
+
writePostNotice({ kind: 'restore', name })
|
|
621
|
+
window.location.assign(`/${locale}`)
|
|
622
|
+
return untilReload()
|
|
623
|
+
}, failed)
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* The server resets the world, replays the preset and signs this browser in as its viewpoint, then answers where
|
|
628
|
+
* to land: a full reload, as after a restore. A refused or failed load is said, never only un-busied: the server
|
|
629
|
+
* may have reset the world before the step that failed, so this page no longer shows what the world holds. No
|
|
630
|
+
* reload then, so a tour that asked for the preset can still record the miss.
|
|
631
|
+
*/
|
|
632
|
+
function handleLoadPreset(id: string): Promise<boolean> {
|
|
633
|
+
setBusyPreset(id)
|
|
634
|
+
const failed = (): false => {
|
|
635
|
+
setBusyPreset(null)
|
|
636
|
+
const preset = presets.find((candidate) => candidate.id === id)
|
|
637
|
+
pushNotice(t('noticePresetFailedStale', { name: preset ? tRoot(preset.titleKey) : id }))
|
|
638
|
+
return false
|
|
639
|
+
}
|
|
640
|
+
return (
|
|
641
|
+
post('presets', { name: id, locale })
|
|
642
|
+
.then(async (response) => {
|
|
643
|
+
// Only ever to a path on this origin: the server answers no other, and this is the client's own check.
|
|
644
|
+
const path = response.ok
|
|
645
|
+
? sameOriginPath(((await response.json()) as { redirectTo?: unknown }).redirectTo)
|
|
646
|
+
: null
|
|
647
|
+
if (!path) return failed()
|
|
648
|
+
writePostNotice({ kind: 'preset', name: id })
|
|
649
|
+
window.location.assign(path)
|
|
650
|
+
return untilReload()
|
|
651
|
+
})
|
|
652
|
+
// A rejected fetch, or an answer that is not JSON (a proxy's error page), is a failed load too.
|
|
653
|
+
.catch(failed)
|
|
654
|
+
)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function handleSaveSnapshot(name: string) {
|
|
658
|
+
setSnapshotsBusy(true)
|
|
659
|
+
void post('snapshots', { name })
|
|
660
|
+
.then((response) => {
|
|
661
|
+
if (!response.ok) return
|
|
662
|
+
pushNotice(t('noticeSnapshotSaved', { name }))
|
|
663
|
+
void refreshSnapshots()
|
|
664
|
+
})
|
|
665
|
+
// A rejected fetch (the dev server stopped) must not leave the controls disabled until a reload.
|
|
666
|
+
.catch(() => undefined)
|
|
667
|
+
.finally(() => setSnapshotsBusy(false))
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function handleDeleteSnapshot(name: string) {
|
|
671
|
+
setBusySnapshot(name)
|
|
672
|
+
void post('snapshots/delete', { name })
|
|
673
|
+
.then((response) => {
|
|
674
|
+
if (!response.ok) return
|
|
675
|
+
pushNotice(t('noticeSnapshotDeleted', { name }))
|
|
676
|
+
void refreshSnapshots()
|
|
677
|
+
})
|
|
678
|
+
.catch(() => undefined)
|
|
679
|
+
.finally(() => setBusySnapshot(null))
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function handleToggleFlag(flag: string, enabled: boolean) {
|
|
683
|
+
// A full reload: what a flag changes (the demo banner, say) is server output, read again only on a new request.
|
|
684
|
+
void post('flags', { flag, enabled })
|
|
685
|
+
.then((response) => {
|
|
686
|
+
if (response.ok) window.location.reload()
|
|
687
|
+
})
|
|
688
|
+
// The dev server stopped: the switch stays where the server has it.
|
|
689
|
+
.catch(() => undefined)
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function handleBumpAgreement(id: string) {
|
|
693
|
+
setBusyAgreement(id)
|
|
694
|
+
void post('agreements/bump', { agreementId: id })
|
|
695
|
+
.then(async (response) => {
|
|
696
|
+
if (!response.ok) return
|
|
697
|
+
const { version } = (await response.json()) as { version: number }
|
|
698
|
+
pushNotice(t('noticeAgreementBumped', { version }))
|
|
699
|
+
void refreshAgreements()
|
|
700
|
+
})
|
|
701
|
+
.catch(() => undefined)
|
|
702
|
+
.finally(() => setBusyAgreement(null))
|
|
703
|
+
}
|
|
704
|
+
|
|
282
705
|
function handleLocaleChange(next: string) {
|
|
283
706
|
if (next === locale) return
|
|
284
707
|
// Swap the leading /<locale> segment and reload the same page: the theme and the header are per-request
|
|
@@ -288,48 +711,99 @@ export function SimulatorHost({ locale, children }: { locale: string; children:
|
|
|
288
711
|
window.location.assign(sameOriginPath(swapped) ?? `/${next}`)
|
|
289
712
|
}
|
|
290
713
|
|
|
714
|
+
const world = useMemo<SimulatorWorld>(() => ({ jobs: jobsData }), [jobsData])
|
|
715
|
+
|
|
291
716
|
return (
|
|
292
717
|
<div style={{ display: 'flex', minHeight: '100vh', alignItems: 'stretch' }}>
|
|
293
718
|
<div style={{ flex: 1, minWidth: 0 }}>{children}</div>
|
|
294
|
-
<
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
719
|
+
<SimulatorWorldContext.Provider value={world}>
|
|
720
|
+
<SimulatorPanel
|
|
721
|
+
people={summary.people}
|
|
722
|
+
viewpoint={summary.viewpoint}
|
|
723
|
+
signedIn={summary.signedIn}
|
|
724
|
+
onSelect={handleSelect}
|
|
725
|
+
onRefresh={refresh}
|
|
726
|
+
onExpandedChange={(value) => {
|
|
727
|
+
setExpanded(value)
|
|
728
|
+
if (value) void refresh()
|
|
729
|
+
}}
|
|
730
|
+
onTabChange={setActiveTab}
|
|
731
|
+
onLocaleChange={handleLocaleChange}
|
|
732
|
+
notices={notices}
|
|
733
|
+
mail={{
|
|
734
|
+
emails: mail.emails,
|
|
735
|
+
scope: effectiveMailScope,
|
|
736
|
+
onScopeChange: handleScopeChange,
|
|
737
|
+
personEmail,
|
|
738
|
+
mailSeenAt: mail.mailSeenAt,
|
|
739
|
+
allCount: mail.allCount,
|
|
740
|
+
onOpenLink: handleOpenLink,
|
|
741
|
+
onSeen: handleMailSeen,
|
|
742
|
+
onClear: handleClearMail,
|
|
743
|
+
onCopyLink: handleCopyLink,
|
|
744
|
+
}}
|
|
745
|
+
// Inbound mail is for an app that registers a handler (`@sssb/app-config/inbound-email`): with none,
|
|
746
|
+
// nothing the form sends could reach the app, so the Mail tab shows no compose form.
|
|
747
|
+
inbound={
|
|
748
|
+
inboundData.handlers.length > 0
|
|
749
|
+
? {
|
|
750
|
+
inbound: inboundData.inbound,
|
|
751
|
+
orgs: inboundData.orgs,
|
|
752
|
+
people: inboundData.people,
|
|
753
|
+
handlers: inboundData.handlers,
|
|
754
|
+
domain: inboundData.domain,
|
|
755
|
+
onCompose: handleComposeInbound,
|
|
756
|
+
}
|
|
757
|
+
: undefined
|
|
758
|
+
}
|
|
759
|
+
messages={messagesData.messages}
|
|
760
|
+
events={eventsData.events}
|
|
761
|
+
audit={auditData.audit}
|
|
762
|
+
hooks={{
|
|
763
|
+
endpoints: hooksData.endpoints,
|
|
764
|
+
deliveries: hooksData.deliveries,
|
|
765
|
+
failingEndpointIds: hooksData.failingEndpointIds,
|
|
766
|
+
onToggleFail: handleToggleFail,
|
|
767
|
+
onRunDue: handleRunDueDeliveries,
|
|
768
|
+
}}
|
|
769
|
+
runServerErrorScenario={handleServerErrorScenario}
|
|
770
|
+
jobs={{
|
|
771
|
+
jobs: jobsData.jobs,
|
|
772
|
+
held: jobsData.held,
|
|
773
|
+
onRunPending: handleRunPending,
|
|
774
|
+
schedules: schedulesData.schedules,
|
|
775
|
+
clock: {
|
|
776
|
+
offsetMs: schedulesData.clockOffsetMs,
|
|
777
|
+
worldNow: schedulesData.worldNow,
|
|
778
|
+
onAdvance: handleAdvanceClock,
|
|
779
|
+
onReset: handleResetClock,
|
|
780
|
+
onRunDue: handleRunDue,
|
|
781
|
+
},
|
|
782
|
+
ticker: tickerData
|
|
783
|
+
? { ...tickerData, onStart: handleStartTicker, onStop: handleStopTicker }
|
|
784
|
+
: undefined,
|
|
785
|
+
}}
|
|
786
|
+
extraTabs={extraTabs}
|
|
787
|
+
snapshots={{
|
|
788
|
+
snapshots: snapshotsData.snapshots,
|
|
789
|
+
onReset: () => void handleReset(),
|
|
790
|
+
onSave: handleSaveSnapshot,
|
|
791
|
+
onRestore: (name) => void handleRestoreSnapshot(name),
|
|
792
|
+
onDelete: handleDeleteSnapshot,
|
|
793
|
+
busy: snapshotsBusy,
|
|
794
|
+
busySnapshot,
|
|
795
|
+
flags: flagsData.flags,
|
|
796
|
+
onToggleFlag: handleToggleFlag,
|
|
797
|
+
agreements: agreementsData.agreements,
|
|
798
|
+
onBumpAgreement: handleBumpAgreement,
|
|
799
|
+
busyAgreement,
|
|
800
|
+
onLoadPreset: (id) => void handleLoadPreset(id),
|
|
801
|
+
busyPreset,
|
|
802
|
+
}}
|
|
803
|
+
tours={tours.tab}
|
|
804
|
+
/>
|
|
805
|
+
</SimulatorWorldContext.Provider>
|
|
806
|
+
{tours.overlay}
|
|
333
807
|
</div>
|
|
334
808
|
)
|
|
335
809
|
}
|