@sssb/kit 0.0.0-stage → 0.2.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 +209 -3
- 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 +312 -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 +270 -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 +94 -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 +115 -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/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.ts +88 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +89 -0
- package/src/adapters/real/jobs.ts +32 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -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/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-panel.tsx +716 -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 +459 -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/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 +1479 -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 +118 -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 +97 -0
- package/src/observability/scrub.ts +42 -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 +48 -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 +53 -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 +38 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +73 -0
- package/src/service-auth/webhook.ts +60 -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,93 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { appendFile } from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { flags as appSimulatorFlags } from '@sssb/app-config/simulator'
|
|
5
|
+
import type { AnalyticsPort } from '../../ports/analytics'
|
|
6
|
+
import { writeJsonAtomicSync } from './atomic-write'
|
|
7
|
+
import { recordLastPath } from './simulator'
|
|
8
|
+
import { dataDir } from './data-dir'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Persists every capture() into .data/analytics/events.jsonl (append-only — an event log is
|
|
12
|
+
* high-volume, unlike the one-file-per-item email catch store) and flags into
|
|
13
|
+
* .data/analytics/flags.json. The Simulator panel's Events tab (GET /api/simulator/events)
|
|
14
|
+
* renders both; Playwright asserts against them.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface CapturedEvent {
|
|
18
|
+
id: string
|
|
19
|
+
at: string
|
|
20
|
+
event: string
|
|
21
|
+
properties?: Record<string, unknown> | undefined
|
|
22
|
+
distinctId?: string | undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The framework's own feature flags: 'demo-banner' gates the demo banner; 'jobs-held' keeps submitted
|
|
27
|
+
* jobs 'queued' for the operator to step forward. Both are framework flags and stay HERE (ADR-0012).
|
|
28
|
+
*/
|
|
29
|
+
const frameworkFlags = ['demo-banner', 'jobs-held']
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The feature flags the Simulator Snapshots tab can toggle — the ONE list both simulator routes read
|
|
33
|
+
* (events feeds the toggle list, flags validates writes) so they can never drift. Composed from the
|
|
34
|
+
* framework flags and any app-registered ones (the app's `@sssb/app-config/simulator` `flags`).
|
|
35
|
+
*/
|
|
36
|
+
export const KNOWN_FLAGS = [...frameworkFlags, ...appSimulatorFlags.map((flag) => flag.id)]
|
|
37
|
+
|
|
38
|
+
let counter = 0
|
|
39
|
+
|
|
40
|
+
function eventsFile(): string {
|
|
41
|
+
return path.join(dataDir('analytics'), 'events.jsonl')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function flagsFile(): string {
|
|
45
|
+
return path.join(dataDir('analytics'), 'flags.json')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const fakeAnalytics: AnalyticsPort = {
|
|
49
|
+
async capture(event, properties, distinctId) {
|
|
50
|
+
const captured: CapturedEvent = {
|
|
51
|
+
id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
|
|
52
|
+
at: new Date().toISOString(),
|
|
53
|
+
event,
|
|
54
|
+
properties,
|
|
55
|
+
distinctId,
|
|
56
|
+
}
|
|
57
|
+
await appendFile(eventsFile(), `${JSON.stringify(captured)}\n`)
|
|
58
|
+
// Simulator continuity piggyback: a signed-in page_view is exactly "where this person
|
|
59
|
+
// last was", so the fake adapter records it here — keeping the beacon route port-pure
|
|
60
|
+
// instead of importing simulator internals from product code.
|
|
61
|
+
if (event === 'page_view' && typeof distinctId === 'string' && typeof properties?.['path'] === 'string') {
|
|
62
|
+
recordLastPath(distinctId, properties['path'])
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
async isFlagEnabled(flag, defaultValue = false) {
|
|
66
|
+
const flags = readFlags()
|
|
67
|
+
return flag in flags ? flags[flag]! : defaultValue
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Simulated-mode-only surface for the Simulator Events tab (NOT part of AnalyticsPort). */
|
|
72
|
+
export function listCapturedEvents(): CapturedEvent[] {
|
|
73
|
+
const file = eventsFile()
|
|
74
|
+
if (!existsSync(file)) return []
|
|
75
|
+
return readFileSync(file, 'utf8')
|
|
76
|
+
.split('\n')
|
|
77
|
+
.filter((line) => line.trim().length > 0)
|
|
78
|
+
.map((line) => JSON.parse(line) as CapturedEvent)
|
|
79
|
+
.sort((a, b) => (a.id < b.id ? 1 : -1))
|
|
80
|
+
.slice(0, 500)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function readFlags(): Record<string, boolean> {
|
|
84
|
+
const file = flagsFile()
|
|
85
|
+
if (!existsSync(file)) return {}
|
|
86
|
+
return JSON.parse(readFileSync(file, 'utf8')) as Record<string, boolean>
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function setFlag(flag: string, enabled: boolean): void {
|
|
90
|
+
const flags = readFlags()
|
|
91
|
+
flags[flag] = enabled
|
|
92
|
+
writeJsonAtomicSync(flagsFile(), flags)
|
|
93
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { renameSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { copyFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Atomic file writes for the fake adapters (packages/kit/src/adapters/fake/*.ts). Internal helper —
|
|
6
|
+
* NOT part of SSSB's public surface (packages/kit/package.json `exports`); every fake adapter
|
|
7
|
+
* reaches it by relative import, same as any other module-private file in this directory.
|
|
8
|
+
*
|
|
9
|
+
* WHY this exists: every fake adapter persists its state as a flat file, and under concurrent
|
|
10
|
+
* requests two writers can land on the SAME file at once (see
|
|
11
|
+
* .claude/future-tasks/e2e-shared-world-blocks-parallelism.md). Plain `writeFileSync`/`writeFile`
|
|
12
|
+
* TRUNCATE the file and then stream the new bytes in — so if writer A (shorter payload) and writer
|
|
13
|
+
* B (longer payload) interleave, a reader can observe B's truncate landing after A has already
|
|
14
|
+
* written, leaving A's shorter content followed by the tail of B's longer content: neither writer's
|
|
15
|
+
* value, and not even valid JSON. That splice is exactly what produced
|
|
16
|
+
* `SyntaxError: Unexpected non-whitespace character after JSON at position 751` on an 821-byte
|
|
17
|
+
* invites.json.
|
|
18
|
+
*
|
|
19
|
+
* POSIX `rename()` is atomic WITHIN one filesystem: a concurrent reader of the TARGET path always
|
|
20
|
+
* sees either the whole old file or the whole new file, never a partial one. So every write here
|
|
21
|
+
* goes to a fresh temp file colocated with the target (same directory ⇒ guaranteed same filesystem
|
|
22
|
+
* ⇒ the rename below is actually atomic — renaming across filesystems silently falls back to
|
|
23
|
+
* copy+delete, which reintroduces the exact race this module exists to remove) and is published
|
|
24
|
+
* with a rename.
|
|
25
|
+
*
|
|
26
|
+
* This removes CORRUPTION, not lost updates: two concurrent read-modify-write cycles on the same
|
|
27
|
+
* file can still race each other to "last write wins" (the second rename simply clobbers the
|
|
28
|
+
* first's content with its own). That's a known, separate problem — see the future-task doc's
|
|
29
|
+
* "world per worker" follow-up fix.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
interface WriteAtomicOptions {
|
|
33
|
+
/** chmod applied to the temp file before it's published. Rename preserves the SOURCE file's
|
|
34
|
+
* mode (the temp file's), so setting it here — rather than on the target after the fact — is
|
|
35
|
+
* what makes a call site's `{ mode: 0o600 }` survive the swap atomically; a separate post-
|
|
36
|
+
* rename chmod would itself be a window where the file briefly has the wrong permissions. */
|
|
37
|
+
mode?: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Temp path colocated with `file` — same directory, so same filesystem, so the rename below is
|
|
42
|
+
* actually atomic (see module doc). Suffixed with this process's pid AND a random UUID so two
|
|
43
|
+
* concurrent writers — even two requests handled by the same process — never share a temp path:
|
|
44
|
+
* sharing one would just move the truncate/write race from the target file onto the temp file.
|
|
45
|
+
*/
|
|
46
|
+
function tempFileFor(file: string): string {
|
|
47
|
+
return `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** True for the expected cleanup outcome (rename already moved the temp file away, or it was never
|
|
51
|
+
* created because the write itself failed first). Anything else is a real problem — e.g. a
|
|
52
|
+
* permissions error — and must not be swallowed alongside it. */
|
|
53
|
+
function isEnoent(err: unknown): boolean {
|
|
54
|
+
return err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Removes a leftover temp file after a failed write/rename, swallowing the expected ENOENT (the
|
|
58
|
+
* write itself never got far enough to create it) but surfacing anything else. Not called on the
|
|
59
|
+
* success path: a successful rename has already made `tmp` not exist, so there's nothing to do. */
|
|
60
|
+
function cleanupTempSync(tmp: string): void {
|
|
61
|
+
try {
|
|
62
|
+
unlinkSync(tmp)
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (!isEnoent(err)) throw err
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Async twin of cleanupTempSync. */
|
|
69
|
+
async function cleanupTemp(tmp: string): Promise<void> {
|
|
70
|
+
try {
|
|
71
|
+
await unlink(tmp)
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (!isEnoent(err)) throw err
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Synchronous atomic write of raw bytes/text. Reserved for the call sites that are themselves
|
|
79
|
+
* synchronous (session/dev-secret provisioning, guarded by `existsSync` in the same sync function)
|
|
80
|
+
* and can't become async without rippling into their callers.
|
|
81
|
+
*/
|
|
82
|
+
export function writeFileAtomicSync(file: string, data: string | Uint8Array, opts?: WriteAtomicOptions): void {
|
|
83
|
+
const tmp = tempFileFor(file)
|
|
84
|
+
try {
|
|
85
|
+
writeFileSync(tmp, data, opts?.mode !== undefined ? { mode: opts.mode } : undefined)
|
|
86
|
+
renameSync(tmp, file)
|
|
87
|
+
} catch (err) {
|
|
88
|
+
cleanupTempSync(tmp)
|
|
89
|
+
throw err
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Async atomic write of raw bytes/text — the default for the fake adapters' async ports (email,
|
|
94
|
+
* sms, storage, webhooks-as-async-callers, etc). See writeFileAtomicSync for the sync twin. */
|
|
95
|
+
export async function writeFileAtomic(
|
|
96
|
+
file: string,
|
|
97
|
+
data: string | Uint8Array,
|
|
98
|
+
opts?: WriteAtomicOptions,
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
const tmp = tempFileFor(file)
|
|
101
|
+
try {
|
|
102
|
+
await writeFile(tmp, data, opts?.mode !== undefined ? { mode: opts.mode } : undefined)
|
|
103
|
+
await rename(tmp, file)
|
|
104
|
+
} catch (err) {
|
|
105
|
+
await cleanupTemp(tmp)
|
|
106
|
+
throw err
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A copy that has been made beside its target but not yet put there. */
|
|
111
|
+
export interface StagedCopy {
|
|
112
|
+
/** The temp file holding the copy, which exists until `publish` or `discard`: what a caller inspects to
|
|
113
|
+
* decide whether to publish. */
|
|
114
|
+
readonly file: string
|
|
115
|
+
/** Puts the copy at the target with one rename. On failure the temp file is removed and the error thrown. */
|
|
116
|
+
publish(): Promise<void>
|
|
117
|
+
/** Removes the temp file. Safe after `publish` (it has nothing left to remove) and safe to call twice. */
|
|
118
|
+
discard(): Promise<void>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The first half of an atomic file COPY: the bytes go to a temp file colocated with `to`, and nothing is
|
|
123
|
+
* visible at `to` until `publish` renames it into place. Two phases because a caller copying SEVERAL files
|
|
124
|
+
* that belong together (an object and its sidecar) can stage them all, and publish only once every one of
|
|
125
|
+
* them exists whole: a failure or a vanished source while staging then leaves nothing behind. A failed
|
|
126
|
+
* stage removes its own temp file and throws. Not `copyFile(from, to)` directly: that writes into `to`
|
|
127
|
+
* in place, so a reader sees it half-written.
|
|
128
|
+
*/
|
|
129
|
+
export async function stageCopy(from: string, to: string): Promise<StagedCopy> {
|
|
130
|
+
const tmp = tempFileFor(to)
|
|
131
|
+
try {
|
|
132
|
+
await copyFile(from, tmp)
|
|
133
|
+
} catch (err) {
|
|
134
|
+
await cleanupTemp(tmp)
|
|
135
|
+
throw err
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
file: tmp,
|
|
139
|
+
async publish() {
|
|
140
|
+
try {
|
|
141
|
+
await rename(tmp, to)
|
|
142
|
+
} catch (err) {
|
|
143
|
+
await cleanupTemp(tmp)
|
|
144
|
+
throw err
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
discard: () => cleanupTemp(tmp),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Synchronous atomic JSON write. `JSON.stringify(value, null, 2)` matches every existing
|
|
152
|
+
* fake-adapter JSON call site's formatting exactly, so swapping this in is byte-identical for a
|
|
153
|
+
* single writer. */
|
|
154
|
+
export function writeJsonAtomicSync(file: string, value: unknown, opts?: WriteAtomicOptions): void {
|
|
155
|
+
writeFileAtomicSync(file, JSON.stringify(value, null, 2), opts)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Async atomic JSON write — see writeJsonAtomicSync. */
|
|
159
|
+
export async function writeJsonAtomic(file: string, value: unknown, opts?: WriteAtomicOptions): Promise<void> {
|
|
160
|
+
await writeFileAtomic(file, JSON.stringify(value, null, 2), opts)
|
|
161
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { AuditDetail } from '../../db/audit'
|
|
2
|
+
import { toIso } from '../../db/jobs'
|
|
3
|
+
import { fakeDb } from './db'
|
|
4
|
+
|
|
5
|
+
/** One row of the simulated-mode cross-tenant audit god view (NOT part of any port). */
|
|
6
|
+
export interface WorldAuditEvent {
|
|
7
|
+
id: string
|
|
8
|
+
action: string
|
|
9
|
+
subjectType: string
|
|
10
|
+
subjectId: string | null
|
|
11
|
+
actorUserId: string
|
|
12
|
+
tenantSlug: string
|
|
13
|
+
orgSlug: string
|
|
14
|
+
at: string
|
|
15
|
+
/** Why, as codes and counts (0016); null when the writer recorded none. Shown as escaped text. */
|
|
16
|
+
detail: AuditDetail | null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Every audit event across ALL tenants, joined to tenant/org slugs, newest first (cap 100) — the
|
|
21
|
+
* Simulator Events tab's read-only "product record" section. A raw getDb() read on purpose: this is
|
|
22
|
+
* the simulated-world god view, deliberately reaching past the tenant RLS scope (simulated-mode-only), the
|
|
23
|
+
* exact same justification as listWorldJobs, beside which this lives conceptually. org_id is NOT NULL
|
|
24
|
+
* on audit_events, so the organizations join is inner (every event has an org).
|
|
25
|
+
*/
|
|
26
|
+
export async function listWorldAuditEvents(): Promise<WorldAuditEvent[]> {
|
|
27
|
+
await fakeDb.ready()
|
|
28
|
+
const rows = await fakeDb
|
|
29
|
+
.getDb()
|
|
30
|
+
.selectFrom('audit_events')
|
|
31
|
+
.innerJoin('tenants', 'tenants.id', 'audit_events.tenant_id')
|
|
32
|
+
.innerJoin('organizations', 'organizations.id', 'audit_events.org_id')
|
|
33
|
+
.select([
|
|
34
|
+
'audit_events.id as id',
|
|
35
|
+
'audit_events.action as action',
|
|
36
|
+
'audit_events.subject_type as subject_type',
|
|
37
|
+
'audit_events.subject_id as subject_id',
|
|
38
|
+
'audit_events.actor_user_id as actor_user_id',
|
|
39
|
+
'audit_events.at as at',
|
|
40
|
+
'audit_events.detail as detail',
|
|
41
|
+
'tenants.slug as tenant_slug',
|
|
42
|
+
'organizations.slug as org_slug',
|
|
43
|
+
])
|
|
44
|
+
.orderBy('audit_events.at', 'desc')
|
|
45
|
+
.limit(100)
|
|
46
|
+
.execute()
|
|
47
|
+
return rows.map((r) => ({
|
|
48
|
+
id: r.id,
|
|
49
|
+
action: r.action,
|
|
50
|
+
subjectType: r.subject_type,
|
|
51
|
+
subjectId: r.subject_id,
|
|
52
|
+
actorUserId: r.actor_user_id,
|
|
53
|
+
tenantSlug: r.tenant_slug,
|
|
54
|
+
orgSlug: r.org_slug,
|
|
55
|
+
at: toIso(r.at),
|
|
56
|
+
detail: r.detail,
|
|
57
|
+
}))
|
|
58
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { APP_SLUG } from '@sssb/app-config/identity'
|
|
5
|
+
import { findOrg, people, type SeedPerson } from '@sssb/app-config/seed'
|
|
6
|
+
import { jwtVerify, SignJWT } from 'jose'
|
|
7
|
+
import { cookies } from 'next/headers'
|
|
8
|
+
import { LOCALES, type Locale } from '../../core/locale'
|
|
9
|
+
import { isRestricted, isRole, type Role } from '../../core/roles'
|
|
10
|
+
import type {
|
|
11
|
+
AuthPort,
|
|
12
|
+
AuthUser,
|
|
13
|
+
InviteInput,
|
|
14
|
+
Membership,
|
|
15
|
+
MemberStanding,
|
|
16
|
+
OrgRef,
|
|
17
|
+
ProfileUpdate,
|
|
18
|
+
} from '../../ports/auth'
|
|
19
|
+
import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
|
|
20
|
+
import { writeFileAtomicSync, writeJsonAtomic } from './atomic-write'
|
|
21
|
+
import { readSimulatorState, updatePersonState, writeViewpointCookie } from './simulator'
|
|
22
|
+
import { dataDir } from './data-dir'
|
|
23
|
+
|
|
24
|
+
const COOKIE_NAME = `${APP_SLUG}_session`
|
|
25
|
+
const ISSUER = `${APP_SLUG}-fake-auth`
|
|
26
|
+
|
|
27
|
+
/** Stable per-checkout signing secret so dev sessions survive restarts. Never used in real mode. */
|
|
28
|
+
function secret(): Uint8Array {
|
|
29
|
+
const file = path.join(dataDir('auth'), 'dev-secret')
|
|
30
|
+
if (!existsSync(file)) writeFileAtomicSync(file, randomBytes(32).toString('hex'), { mode: 0o600 })
|
|
31
|
+
return new TextEncoder().encode(readFileSync(file, 'utf8'))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface ProfileOverride {
|
|
35
|
+
name?: string
|
|
36
|
+
locale?: Locale
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function overridesFile(): string {
|
|
40
|
+
return path.join(dataDir('auth'), 'profile-overrides.json')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readOverrides(): Record<string, ProfileOverride> {
|
|
44
|
+
const file = overridesFile()
|
|
45
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, ProfileOverride>) : {}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface StoredInvite {
|
|
49
|
+
id: string
|
|
50
|
+
email: string
|
|
51
|
+
role: Role
|
|
52
|
+
orgSlug: string
|
|
53
|
+
invitedAt: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function invitesFile(): string {
|
|
57
|
+
return path.join(dataDir('auth'), 'invites.json')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function readInvites(): StoredInvite[] {
|
|
61
|
+
const file = invitesFile()
|
|
62
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as StoredInvite[]) : []
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Simulated-mode-only lookup used by the Simulator APIs and the accept-invite page (NOT part of AuthPort). */
|
|
66
|
+
export function findInvite(id: string): StoredInvite | undefined {
|
|
67
|
+
return readInvites().find((invite) => invite.id === id)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function peopleFile(): string {
|
|
71
|
+
return path.join(dataDir('auth'), 'people.json')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Overlay of people created by acceptInvite (simulated-mode-only, NOT part of AuthPort): every seed
|
|
76
|
+
* person is static, but an accepted invite needs somewhere durable to live across restarts, so
|
|
77
|
+
* this is the same read-a-JSON-array-or-default-empty pattern as invites.json.
|
|
78
|
+
*/
|
|
79
|
+
function listDynamicPeople(): SeedPerson[] {
|
|
80
|
+
const file = peopleFile()
|
|
81
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as SeedPerson[]) : []
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Seed + dynamic people as one list — the sign-in picker, Simulator People, and every person
|
|
85
|
+
* lookup below all need "everyone who can sign in", not just the static seed. */
|
|
86
|
+
export function listAllPeople(): SeedPerson[] {
|
|
87
|
+
return [...people, ...listDynamicPeople()]
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function findPerson(id: string | undefined): SeedPerson | undefined {
|
|
91
|
+
return id ? listAllPeople().find((p) => p.id === id) : undefined
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Simulated-mode-only locale lookup (NOT part of AuthPort) — the notification fan-out's `resolveLocale`
|
|
96
|
+
* enrichment, so a recipient's email/SMS render in their language (the digest-email locale precedent).
|
|
97
|
+
* Honours a profile-override locale first, then the person's seed locale; undefined for an unknown id
|
|
98
|
+
* (the fan-out then falls back to the app default). Real mode has no analog (Clerk memberships carry no
|
|
99
|
+
* locale), so this stays fake-only and behind the fan-out's optional dependency.
|
|
100
|
+
*/
|
|
101
|
+
export function personLocale(userId: string): Locale | undefined {
|
|
102
|
+
const person = findPerson(userId)
|
|
103
|
+
if (!person) return undefined
|
|
104
|
+
return readOverrides()[person.id]?.locale ?? person.locale
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Resolve the person's membership for `activeOrgSlug`, falling back to their first membership when
|
|
109
|
+
* the slug isn't (or is no longer) one they belong to. People always have ≥1 membership, so this
|
|
110
|
+
* never returns undefined for a valid person.
|
|
111
|
+
*/
|
|
112
|
+
function resolveMembership(person: SeedPerson, activeOrgSlug: string) {
|
|
113
|
+
const membership = person.memberships.find((m) => m.orgSlug === activeOrgSlug) ?? person.memberships[0]
|
|
114
|
+
if (!membership) throw new Error(`person ${person.id} has no memberships`)
|
|
115
|
+
return membership
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function toUser(person: SeedPerson, activeOrgSlug: string): AuthUser {
|
|
119
|
+
const override = readOverrides()[person.id] ?? {}
|
|
120
|
+
const membership = resolveMembership(person, activeOrgSlug)
|
|
121
|
+
return {
|
|
122
|
+
id: person.id,
|
|
123
|
+
name: override.name ?? person.name,
|
|
124
|
+
email: person.email,
|
|
125
|
+
role: membership.role,
|
|
126
|
+
locale: override.locale ?? person.locale,
|
|
127
|
+
// Ambient site: a person's tenant is fixed, never the active org's business.
|
|
128
|
+
tenantSlug: person.tenantSlug,
|
|
129
|
+
orgSlug: membership.orgSlug,
|
|
130
|
+
restricted: isRestricted(person.restricted, membership.role),
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The orgs a person belongs to, each with its per-org role — drives the OrgSwitcher. */
|
|
135
|
+
function orgsForPerson(person: SeedPerson): OrgRef[] {
|
|
136
|
+
return person.memberships.flatMap((m) => {
|
|
137
|
+
const org = findOrg(m.orgSlug)
|
|
138
|
+
return org ? [{ slug: org.slug, name: org.name, role: m.role }] : []
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function readSession(): Promise<{ person: SeedPerson; orgSlug: string } | null> {
|
|
143
|
+
const jar = await cookies()
|
|
144
|
+
const token = jar.get(COOKIE_NAME)?.value
|
|
145
|
+
if (!token) return null
|
|
146
|
+
try {
|
|
147
|
+
const { payload } = await jwtVerify(token, secret(), { issuer: ISSUER })
|
|
148
|
+
const person = findPerson(payload.sub)
|
|
149
|
+
if (!person) return null
|
|
150
|
+
const claimed = typeof payload['org'] === 'string' ? payload['org'] : undefined
|
|
151
|
+
// A stale/foreign org claim must not stick — fall back to the first membership.
|
|
152
|
+
const orgSlug = resolveMembership(person, claimed ?? '').orgSlug
|
|
153
|
+
return { person, orgSlug }
|
|
154
|
+
} catch {
|
|
155
|
+
return null
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function writeSession(personId: string, orgSlug: string): Promise<void> {
|
|
160
|
+
const token = await new SignJWT({ org: orgSlug })
|
|
161
|
+
.setProtectedHeader({ alg: 'HS256' })
|
|
162
|
+
.setSubject(personId)
|
|
163
|
+
.setIssuer(ISSUER)
|
|
164
|
+
.setIssuedAt()
|
|
165
|
+
.setExpirationTime('7d')
|
|
166
|
+
.sign(secret())
|
|
167
|
+
const jar = await cookies()
|
|
168
|
+
jar.set(COOKIE_NAME, token, { httpOnly: true, sameSite: 'lax', path: '/' })
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Simulated-mode-only surface used by /api/auth/dev-signin AND /api/simulator/viewpoint (NOT part of
|
|
173
|
+
* AuthPort). Restores the person's remembered active org (Simulator continuity) when it's still
|
|
174
|
+
* one they belong to, else falls back to their first membership; also sets the viewpoint cookie so
|
|
175
|
+
* the Simulator panel's "whose world am I looking at" follows this sign-in. (Cross-tenant hopping
|
|
176
|
+
* is picking a person whose home tenant differs — the person IS the site you're inhabiting.)
|
|
177
|
+
*/
|
|
178
|
+
export async function devSignIn(personId: string): Promise<void> {
|
|
179
|
+
const person = findPerson(personId)
|
|
180
|
+
if (!person) throw new ForbiddenError(`unknown person: ${personId}`)
|
|
181
|
+
const remembered = readSimulatorState().people[`person:${personId}`]?.activeOrgSlug
|
|
182
|
+
const orgSlug = resolveMembership(person, remembered ?? '').orgSlug
|
|
183
|
+
await writeSession(person.id, orgSlug)
|
|
184
|
+
await writeViewpointCookie(`person:${personId}`)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Simulated-mode-only surface used by /api/auth/accept-invite (NOT part of AuthPort — same doc-comment
|
|
189
|
+
* convention as devSignIn). The real analog is Clerk's client-side ticket-strategy sign-up
|
|
190
|
+
* (packages/kit/src/adapters/real/accept-invite-form.tsx), which isn't expressible as a server port method:
|
|
191
|
+
* there's no session yet to call it against. Turns a pending invite into a full person, appends
|
|
192
|
+
* it to the people.json overlay, removes the invite, signs the new person in, and points the
|
|
193
|
+
* Simulator viewpoint cookie at them so the panel follows the switch.
|
|
194
|
+
*/
|
|
195
|
+
export async function acceptInvite(
|
|
196
|
+
inviteId: string,
|
|
197
|
+
profile: { name: string; locale?: string },
|
|
198
|
+
): Promise<{ id: string; tenantSlug: string }> {
|
|
199
|
+
const invite = findInvite(inviteId)
|
|
200
|
+
if (!invite) throw new ForbiddenError(`unknown invite: ${inviteId}`)
|
|
201
|
+
const name = profile.name.trim()
|
|
202
|
+
if (!name) throw new ForbiddenError('name is required')
|
|
203
|
+
|
|
204
|
+
const person: SeedPerson = {
|
|
205
|
+
id: `person-invited-${inviteId.slice(0, 8)}`,
|
|
206
|
+
name,
|
|
207
|
+
email: invite.email,
|
|
208
|
+
// The new person starts life in the language they accepted the invite in.
|
|
209
|
+
locale: LOCALES.includes(profile.locale as Locale) ? (profile.locale as Locale) : 'en',
|
|
210
|
+
// Ambient site is the tenant that owns the org they were invited into.
|
|
211
|
+
tenantSlug: findOrg(invite.orgSlug)?.tenantSlug ?? '',
|
|
212
|
+
memberships: [{ orgSlug: invite.orgSlug, role: invite.role }],
|
|
213
|
+
restricted: invite.role === 'restricted',
|
|
214
|
+
}
|
|
215
|
+
await writeJsonAtomic(peopleFile(), [...listDynamicPeople(), person])
|
|
216
|
+
await writeJsonAtomic(
|
|
217
|
+
invitesFile(),
|
|
218
|
+
readInvites().filter((i) => i.id !== inviteId),
|
|
219
|
+
)
|
|
220
|
+
await writeSession(person.id, invite.orgSlug)
|
|
221
|
+
await writeViewpointCookie(`person:${person.id}`)
|
|
222
|
+
return { id: person.id, tenantSlug: person.tenantSlug }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export const fakeAuth: AuthPort = {
|
|
226
|
+
async getCurrentUser(): Promise<AuthUser | null> {
|
|
227
|
+
const session = await readSession()
|
|
228
|
+
return session ? toUser(session.person, session.orgSlug) : null
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
async requireUser(): Promise<AuthUser> {
|
|
232
|
+
const user = await this.getCurrentUser()
|
|
233
|
+
if (!user) throw new AuthRequiredError()
|
|
234
|
+
return user
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
async requireRole(...roles: Role[]): Promise<AuthUser> {
|
|
238
|
+
const user = await this.requireUser()
|
|
239
|
+
if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
|
|
240
|
+
return user
|
|
241
|
+
},
|
|
242
|
+
|
|
243
|
+
signInPath(returnTo?: string): string {
|
|
244
|
+
return returnTo ? `/signin?returnTo=${encodeURIComponent(returnTo)}` : '/signin'
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
async signOut(): Promise<void> {
|
|
248
|
+
const jar = await cookies()
|
|
249
|
+
jar.delete(COOKIE_NAME)
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
|
|
253
|
+
const session = await readSession()
|
|
254
|
+
if (!session) throw new AuthRequiredError()
|
|
255
|
+
if (update.locale && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
256
|
+
const overrides = readOverrides()
|
|
257
|
+
overrides[session.person.id] = { ...overrides[session.person.id], ...update }
|
|
258
|
+
await writeJsonAtomic(overridesFile(), overrides)
|
|
259
|
+
return toUser(session.person, session.orgSlug)
|
|
260
|
+
},
|
|
261
|
+
|
|
262
|
+
async listMembers(orgSlug: string): Promise<Membership[]> {
|
|
263
|
+
const members: Membership[] = listAllPeople()
|
|
264
|
+
.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
|
|
265
|
+
.map((p) => {
|
|
266
|
+
const user = toUser(p, orgSlug)
|
|
267
|
+
return { id: p.id, name: user.name, email: p.email, role: user.role, status: 'active' as const }
|
|
268
|
+
})
|
|
269
|
+
const invited: Membership[] = readInvites()
|
|
270
|
+
.filter((i) => i.orgSlug === orgSlug)
|
|
271
|
+
.map((i) => ({ id: i.id, name: null, email: i.email, role: i.role, status: 'invited' as const }))
|
|
272
|
+
return [...members, ...invited]
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
|
|
276
|
+
// Read afresh from the world on every call (seed + accepted invites): nothing is cached, so a
|
|
277
|
+
// person who leaves the org is a non-member on the very next call.
|
|
278
|
+
const person = findPerson(userId)
|
|
279
|
+
const membership = person?.memberships.find((m) => m.orgSlug === orgSlug)
|
|
280
|
+
if (!person || !membership) return null
|
|
281
|
+
return { role: membership.role, restricted: isRestricted(person.restricted, membership.role) }
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
async createInvite(invite: InviteInput): Promise<Membership> {
|
|
285
|
+
if (!isRole(invite.role)) throw new ForbiddenError('unknown role')
|
|
286
|
+
const stored: StoredInvite = {
|
|
287
|
+
id: crypto.randomUUID(),
|
|
288
|
+
email: invite.email,
|
|
289
|
+
role: invite.role,
|
|
290
|
+
orgSlug: invite.orgSlug,
|
|
291
|
+
invitedAt: new Date().toISOString(),
|
|
292
|
+
}
|
|
293
|
+
await writeJsonAtomic(invitesFile(), [...readInvites(), stored])
|
|
294
|
+
return { id: stored.id, name: null, email: stored.email, role: stored.role, status: 'invited' }
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
async listMyOrgs(): Promise<OrgRef[]> {
|
|
298
|
+
const session = await readSession()
|
|
299
|
+
if (!session) return []
|
|
300
|
+
return orgsForPerson(session.person)
|
|
301
|
+
},
|
|
302
|
+
|
|
303
|
+
async setActiveOrg(orgSlug: string): Promise<void> {
|
|
304
|
+
const session = await readSession()
|
|
305
|
+
if (!session) throw new AuthRequiredError()
|
|
306
|
+
if (!session.person.memberships.some((m) => m.orgSlug === orgSlug)) {
|
|
307
|
+
throw new ForbiddenError(`no membership in org: ${orgSlug}`)
|
|
308
|
+
}
|
|
309
|
+
await writeSession(session.person.id, orgSlug)
|
|
310
|
+
updatePersonState(`person:${session.person.id}`, { activeOrgSlug: orgSlug })
|
|
311
|
+
},
|
|
312
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { writeJsonAtomicSync } from './atomic-write'
|
|
4
|
+
import { dataDir } from './data-dir'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The simulated world's CLOCK OFFSET (simulated-mode only, NOT a port) — the "time control" the backlog
|
|
8
|
+
* left open until a feature needed elapsed time (scheduled work is that feature). It is
|
|
9
|
+
* a single signed millisecond offset added to real wall-clock time to compute the world's "now" for
|
|
10
|
+
* the scheduled-jobs due-scan, so a demo can advance the clock past a schedule's next_run_at and watch
|
|
11
|
+
* it fire without waiting real hours.
|
|
12
|
+
*
|
|
13
|
+
* Stored as `.data/simulator/clock.json`. `simulator` is a LIVE_DIR (packages/kit/src/adapters/fake/simulator-admin.ts),
|
|
14
|
+
* so a Snapshots RESET wipes this file back to zero and save/restore snapshot it with the rest of the
|
|
15
|
+
* world — the "Snapshots reset clears the offset" requirement is satisfied structurally, no extra wiring.
|
|
16
|
+
*
|
|
17
|
+
* REAL MODE NEVER TOUCHES THIS. worldNow() is only reached behind simulated mode: `runScheduledTick` calls it
|
|
18
|
+
* behind an `isSimulated` guard, the Simulator routes are simulated-mode-gated, and `fakeDb.now` (which dates
|
|
19
|
+
* audit rows) is a member of the FAKE database, which a real build never selects. So the offset is structurally
|
|
20
|
+
* unreachable in a real build — real time is always real time. Same containment shape as the fake-only webhook
|
|
21
|
+
* secret helper pulled into shared glue behind isSimulated (packages/kit/src/service-auth/webhook.ts).
|
|
22
|
+
*/
|
|
23
|
+
function clockFile(): string {
|
|
24
|
+
return path.join(dataDir('simulator'), 'clock.json')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function readClockOffsetMs(): number {
|
|
28
|
+
const file = clockFile()
|
|
29
|
+
if (!existsSync(file)) return 0
|
|
30
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as { offsetMs?: unknown }
|
|
31
|
+
return typeof parsed.offsetMs === 'number' && Number.isFinite(parsed.offsetMs) ? parsed.offsetMs : 0
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeClockOffsetMs(offsetMs: number): void {
|
|
35
|
+
writeJsonAtomicSync(clockFile(), { offsetMs })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Adds delta ms to the stored offset (advance only ever moves forward in the UI) and returns the new
|
|
39
|
+
* total. Clamped to non-negative — the world clock never runs behind real time. */
|
|
40
|
+
export function advanceClockMs(deltaMs: number): number {
|
|
41
|
+
const next = Math.max(0, readClockOffsetMs() + deltaMs)
|
|
42
|
+
writeClockOffsetMs(next)
|
|
43
|
+
return next
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Back to real time. */
|
|
47
|
+
export function resetClock(): void {
|
|
48
|
+
writeClockOffsetMs(0)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The world's current instant: real time plus the stored offset. Simulated-mode use only. */
|
|
52
|
+
export function worldNow(): Date {
|
|
53
|
+
return new Date(Date.now() + readClockOffsetMs())
|
|
54
|
+
}
|