@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,288 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
3
|
+
import { mkdir, open, readdir, readFile, rm } from 'node:fs/promises'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { NotFoundError, PreconditionFailedError } from '../../ports/errors'
|
|
6
|
+
import type {
|
|
7
|
+
CopyOptions,
|
|
8
|
+
StoragePort,
|
|
9
|
+
StoredObject,
|
|
10
|
+
StoredObjectInfo,
|
|
11
|
+
UploadConstraints,
|
|
12
|
+
UploadTarget,
|
|
13
|
+
} from '../../ports/storage'
|
|
14
|
+
import { stageCopy, writeFileAtomic, writeFileAtomicSync, type StagedCopy } from './atomic-write'
|
|
15
|
+
import { dataDir } from './data-dir'
|
|
16
|
+
|
|
17
|
+
const META_SUFFIX = '.meta.json'
|
|
18
|
+
const UPLOAD_SECRET_FILE = 'upload-secret'
|
|
19
|
+
/** In-flight temp file from writeFileAtomic (`<target>.<pid>.<uuid>.tmp`). */
|
|
20
|
+
const TEMP_FILE = /\.\d+\.[0-9a-f-]{36}\.tmp$/
|
|
21
|
+
|
|
22
|
+
/** Resolve a storage key inside the base dir, refusing path escapes. */
|
|
23
|
+
function resolveKey(key: string): string {
|
|
24
|
+
const base = dataDir('storage')
|
|
25
|
+
const resolved = path.resolve(base, key)
|
|
26
|
+
if (!resolved.startsWith(base + path.sep)) throw new Error(`invalid storage key: ${key}`)
|
|
27
|
+
return resolved
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The store shares one directory with the fake's own bookkeeping (a `<key>.meta.json` sidecar per
|
|
32
|
+
* object, plus the upload secret at the root), and `list` hides those by name. So a key that could BE
|
|
33
|
+
* one is never an object: `put` refuses it rather than silently overwriting the bookkeeping, `get`
|
|
34
|
+
* finds nothing, and `delete` leaves it alone. Real S3 would accept such a key; keep keys off these names.
|
|
35
|
+
*/
|
|
36
|
+
function isReserved(key: string): boolean {
|
|
37
|
+
return key.endsWith(META_SUFFIX) || resolveKey(key) === path.join(dataDir('storage'), UPLOAD_SECRET_FILE)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** True for a regular file. A directory is not an object, though `existsSync` says yes to it. */
|
|
41
|
+
function isFile(file: string): boolean {
|
|
42
|
+
return statSync(file, { throwIfNoEntry: false })?.isFile() === true
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Size, modification time and ETag of ONE version of a file. All three come from a single open handle, so a
|
|
47
|
+
* writer that renames a new file over this one (every write here does) leaves the handle on the old inode:
|
|
48
|
+
* the size and the hash are of the same bytes. The ETag is a double-quoted SHA-256 of the bytes, shaped like
|
|
49
|
+
* S3's (quotes included) so a caller that mishandles the quotes fails here too; it is opaque by contract.
|
|
50
|
+
*/
|
|
51
|
+
async function inspect(file: string): Promise<{ size: number; mtime: Date; etag: string }> {
|
|
52
|
+
const handle = await open(file, 'r')
|
|
53
|
+
try {
|
|
54
|
+
const { size, mtime } = await handle.stat()
|
|
55
|
+
const hash = createHash('sha256')
|
|
56
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk as Buffer)
|
|
57
|
+
return { size, mtime, etag: `"${hash.digest('hex')}"` }
|
|
58
|
+
} finally {
|
|
59
|
+
await handle.close()
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Every file under `dir`, as `/`-separated paths relative to `root`. A missing `dir` is empty. */
|
|
64
|
+
async function walk(root: string, dir: string): Promise<string[]> {
|
|
65
|
+
let entries
|
|
66
|
+
try {
|
|
67
|
+
entries = await readdir(dir, { withFileTypes: true })
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
|
|
70
|
+
throw error
|
|
71
|
+
}
|
|
72
|
+
const nested = await Promise.all(
|
|
73
|
+
entries.map(async (entry) => {
|
|
74
|
+
const full = path.join(dir, entry.name)
|
|
75
|
+
if (entry.isDirectory()) return walk(root, full)
|
|
76
|
+
return [path.relative(root, full).split(path.sep).join('/')]
|
|
77
|
+
}),
|
|
78
|
+
)
|
|
79
|
+
return nested.flat()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Stable per-checkout HMAC secret for signing fake upload targets, mirroring fake auth's dev-secret
|
|
84
|
+
* (packages/kit/src/adapters/fake/auth.ts): a random 32-byte hex written once, 0600, and reused across restarts.
|
|
85
|
+
* Never used in real mode (AWS signs presigned POSTs there). It exists so the fake upload endpoint can
|
|
86
|
+
* prove a target it receives was minted by THIS server and not tampered with — the same trust model as
|
|
87
|
+
* the shared webhook secret, applied to a browser-facing form.
|
|
88
|
+
*/
|
|
89
|
+
function uploadSecret(): Buffer {
|
|
90
|
+
const file = path.join(dataDir('storage'), 'upload-secret')
|
|
91
|
+
// NOTE: existsSync-then-write is still a TOCTOU (two concurrent first-callers can both see
|
|
92
|
+
// "missing" and both mint a secret) — the atomic rename below only guarantees whichever write
|
|
93
|
+
// lands last is never a torn/spliced file, not that it's the only writer. Out of scope here;
|
|
94
|
+
// this mirrors the same accepted gap in auth.ts's dev-secret and service-auth.ts's key/webhook
|
|
95
|
+
// secrets, none of which are security-sensitive in simulated mode.
|
|
96
|
+
if (!existsSync(file)) writeFileAtomicSync(file, randomBytes(32).toString('hex'), { mode: 0o600 })
|
|
97
|
+
return Buffer.from(readFileSync(file, 'utf8'), 'utf8')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Upload targets die after 15 minutes — the same window createRealStorage gives an S3 presigned
|
|
101
|
+
* POST, so fake and real agree that a minted target is short-lived, not a forever-capability to
|
|
102
|
+
* silently swap an artifact's bytes after confirm. */
|
|
103
|
+
const UPLOAD_TARGET_TTL_SECONDS = 900
|
|
104
|
+
|
|
105
|
+
/** Canonical string the signature covers — order-fixed so signer and verifier never disagree. The
|
|
106
|
+
* expiry is INSIDE the signature, so a caller can't extend a target's life by editing the field. */
|
|
107
|
+
function canonical(key: string, contentType: string, maxBytes: number, expires: number): string {
|
|
108
|
+
return `${key}\n${contentType}\n${maxBytes}\n${expires}`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** HMAC-SHA256 (hex) over the upload target's constraints — module-internal (mint signs, verify checks). */
|
|
112
|
+
function signUploadFields(key: string, contentType: string, maxBytes: number, expires: number): string {
|
|
113
|
+
return createHmac('sha256', uploadSecret())
|
|
114
|
+
.update(canonical(key, contentType, maxBytes, expires))
|
|
115
|
+
.digest('hex')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The verified constraints carried by a fake upload target's signed fields. */
|
|
119
|
+
export interface VerifiedUploadFields {
|
|
120
|
+
key: string
|
|
121
|
+
contentType: string
|
|
122
|
+
maxBytes: number
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Verify the signed fields of a fake upload POST and return the constraints they attest to, or null
|
|
127
|
+
* when anything is missing/malformed or the signature doesn't match (a timing-safe compare). The fake
|
|
128
|
+
* upload endpoint calls this FIRST — a null result is the local twin of S3 rejecting a POST whose
|
|
129
|
+
* policy signature is wrong. Simulated-mode-only (NOT part of StoragePort).
|
|
130
|
+
*/
|
|
131
|
+
export function verifyUploadFields(fields: Record<string, string | undefined>): VerifiedUploadFields | null {
|
|
132
|
+
const key = fields['key']
|
|
133
|
+
const contentType = fields['content-type']
|
|
134
|
+
const maxBytesRaw = fields['max-bytes']
|
|
135
|
+
const expiresRaw = fields['expires']
|
|
136
|
+
const signature = fields['signature']
|
|
137
|
+
if (!key || !contentType || !maxBytesRaw || !expiresRaw || !signature) return null
|
|
138
|
+
const maxBytes = Number(maxBytesRaw)
|
|
139
|
+
if (!Number.isInteger(maxBytes) || maxBytes < 0) return null
|
|
140
|
+
const expires = Number(expiresRaw)
|
|
141
|
+
if (!Number.isInteger(expires) || expires < 0) return null
|
|
142
|
+
const expected = signUploadFields(key, contentType, maxBytes, expires)
|
|
143
|
+
const got = Buffer.from(signature, 'utf8')
|
|
144
|
+
const want = Buffer.from(expected, 'utf8')
|
|
145
|
+
if (got.length !== want.length || !timingSafeEqual(got, want)) return null
|
|
146
|
+
// Expiry check AFTER the signature check, so the timestamp we trust is the one that was signed.
|
|
147
|
+
if (expires * 1000 < Date.now()) return null
|
|
148
|
+
return { key, contentType, maxBytes }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const fakeStorage: StoragePort = {
|
|
152
|
+
async put(key, body, contentType) {
|
|
153
|
+
if (isReserved(key)) throw new Error(`invalid storage key: ${key} (reserved by the fake store)`)
|
|
154
|
+
const file = resolveKey(key)
|
|
155
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
156
|
+
await writeFileAtomic(file, body)
|
|
157
|
+
// Not JSON.stringify(..., null, 2) — this sidecar has never been pretty-printed and nothing
|
|
158
|
+
// reads it by hand, so writeFileAtomic (not writeJsonAtomic) keeps the byte-for-byte format.
|
|
159
|
+
await writeFileAtomic(`${file}.meta.json`, JSON.stringify({ contentType }))
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
async get(key): Promise<StoredObject | null> {
|
|
163
|
+
if (isReserved(key)) return null
|
|
164
|
+
const file = resolveKey(key)
|
|
165
|
+
if (!existsSync(file)) return null
|
|
166
|
+
const [body, meta] = await Promise.all([readFile(file), readFile(`${file}.meta.json`, 'utf8')])
|
|
167
|
+
return { body: new Uint8Array(body), contentType: (JSON.parse(meta) as { contentType: string }).contentType }
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
async list(prefix): Promise<string[]> {
|
|
171
|
+
// dataDir creates the store, so a fresh checkout lists as empty; the ENOENT guard in walk
|
|
172
|
+
// covers the store being wiped (world reset) between that call and the read.
|
|
173
|
+
const base = dataDir('storage')
|
|
174
|
+
const files = await walk(base, base)
|
|
175
|
+
return files
|
|
176
|
+
.filter((file) => !file.endsWith(META_SUFFIX) && file !== UPLOAD_SECRET_FILE && !TEMP_FILE.test(file))
|
|
177
|
+
.filter((key) => key.startsWith(prefix))
|
|
178
|
+
.sort()
|
|
179
|
+
},
|
|
180
|
+
|
|
181
|
+
async delete(keys) {
|
|
182
|
+
for (const key of keys) {
|
|
183
|
+
if (isReserved(key)) continue
|
|
184
|
+
const file = resolveKey(key)
|
|
185
|
+
await rm(file, { force: true })
|
|
186
|
+
await rm(`${file}${META_SUFFIX}`, { force: true })
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
|
|
190
|
+
async copy(from, to, options?: CopyOptions) {
|
|
191
|
+
// Refused first, as the real adapter refuses it (see there: S3 could read an empty or `*` as no condition).
|
|
192
|
+
if (options?.ifMatch !== undefined && (options.ifMatch.trim() === '' || options.ifMatch.trim() === '*')) {
|
|
193
|
+
throw new Error('storage copy: ifMatch must be the etag head returned, not empty and not "*"')
|
|
194
|
+
}
|
|
195
|
+
// `to` is checked as `put` checks a key it writes; `from` as `get` checks one it reads (a reserved
|
|
196
|
+
// name is never an object, so it is a missing source, not an invalid one). Either can still be an
|
|
197
|
+
// escape, which resolveKey refuses with the same error as everywhere else.
|
|
198
|
+
if (isReserved(to)) throw new Error(`invalid storage key: ${to} (reserved by the fake store)`)
|
|
199
|
+
const source = resolveKey(from)
|
|
200
|
+
const target = resolveKey(to)
|
|
201
|
+
// Compared as resolved paths: `a/../a` and `a` are one file here (S3 would see two keys, which is a
|
|
202
|
+
// quirk of every method of this fake, not of copy). Before the existence check, because the real
|
|
203
|
+
// adapter refuses it before any request and so cannot know whether the key exists.
|
|
204
|
+
if (source === target) throw new Error(`storage copy: source and destination are the same key: ${from}`)
|
|
205
|
+
if (isReserved(from) || !isFile(source)) throw new NotFoundError(`storage object not found: ${from}`)
|
|
206
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
207
|
+
// STAGE both files first, then publish. Nothing is visible at the destination until both copies exist
|
|
208
|
+
// whole, so a failure while staging (a full disk, a source deleted mid-copy) leaves no orphan sidecar.
|
|
209
|
+
const staged: StagedCopy[] = []
|
|
210
|
+
try {
|
|
211
|
+
staged.push(await stageCopy(`${source}${META_SUFFIX}`, `${target}${META_SUFFIX}`))
|
|
212
|
+
staged.push(await stageCopy(source, target))
|
|
213
|
+
} catch (error) {
|
|
214
|
+
await Promise.all(staged.map((copy) => copy.discard()))
|
|
215
|
+
// The source went away while it was being copied: it is a missing source, as it was a moment ago.
|
|
216
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !isFile(source)) {
|
|
217
|
+
throw new NotFoundError(`storage object not found: ${from}`)
|
|
218
|
+
}
|
|
219
|
+
throw error
|
|
220
|
+
}
|
|
221
|
+
const [sidecar, body] = staged as [StagedCopy, StagedCopy]
|
|
222
|
+
try {
|
|
223
|
+
// The precondition is checked on the staged copy of the body, which is the very bytes about to be
|
|
224
|
+
// published: what lands is exactly the version the etag names, even if a writer replaces the source
|
|
225
|
+
// meanwhile. (S3 evaluates `CopySourceIfMatch` with the copy; this is the fake's equivalent.)
|
|
226
|
+
if (options?.ifMatch !== undefined && (await inspect(body.file)).etag !== options.ifMatch) {
|
|
227
|
+
throw new PreconditionFailedError(
|
|
228
|
+
`storage copy: ${from} is no longer the version ${options.ifMatch}; nothing was copied`,
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
// The sidecar first and the body LAST. The body is what makes a key exist (`get` and `list` both look
|
|
232
|
+
// for it), so `to` appears only once it is complete, with its content type already in place. The
|
|
233
|
+
// other order would leave a window where a new `to` has a body and no sidecar, and `get` would throw
|
|
234
|
+
// on the missing sidecar. Over an EXISTING `to` the content type changes a moment before the bytes
|
|
235
|
+
// do, and a source rewritten while it is being copied can pair one version's bytes with another's
|
|
236
|
+
// content type (S3 snapshots an object; `put` has the same gap between its own two files). A
|
|
237
|
+
// destination that is an existing DIRECTORY fails at the body, after the sidecar: the stray sidecar
|
|
238
|
+
// is invisible to `get` and `list`, and `put` fails on such a key the same way. It is a fake.
|
|
239
|
+
await sidecar.publish()
|
|
240
|
+
await body.publish()
|
|
241
|
+
} catch (error) {
|
|
242
|
+
await Promise.all(staged.map((copy) => copy.discard()))
|
|
243
|
+
throw error
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
async head(key): Promise<StoredObjectInfo | null> {
|
|
248
|
+
if (isReserved(key)) return null
|
|
249
|
+
const file = resolveKey(key)
|
|
250
|
+
if (!isFile(file)) return null
|
|
251
|
+
try {
|
|
252
|
+
const [{ size, mtime, etag }, meta] = await Promise.all([
|
|
253
|
+
inspect(file),
|
|
254
|
+
readFile(`${file}${META_SUFFIX}`, 'utf8'),
|
|
255
|
+
])
|
|
256
|
+
const { contentType } = JSON.parse(meta) as { contentType: string }
|
|
257
|
+
return { size, contentType, etag, lastModified: mtime }
|
|
258
|
+
} catch (error) {
|
|
259
|
+
// Deleted between the check and the read: it is gone, as `get` finding no file would say.
|
|
260
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !isFile(file)) return null
|
|
261
|
+
throw error
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
|
|
265
|
+
async getSignedDownloadUrl(key): Promise<string> {
|
|
266
|
+
// Served by the simulated-mode-only /api/storage route; "signing" is meaningless locally.
|
|
267
|
+
return `/api/storage/${key.split('/').map(encodeURIComponent).join('/')}`
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
async createUploadTarget(key, { contentType, maxBytes }: UploadConstraints): Promise<UploadTarget> {
|
|
271
|
+
// Point the browser at the local fake upload endpoint and hand it signed constraints. The
|
|
272
|
+
// signature ties the target to THIS key/type/size ceiling AND a 15-minute expiry, so the
|
|
273
|
+
// endpoint can trust them without a session — the local stand-in for an S3 presigned POST
|
|
274
|
+
// policy (validated there by AWS, here by verifyUploadFields). resolveKey rejects escapes
|
|
275
|
+
// when the bytes finally land.
|
|
276
|
+
const expires = Math.floor(Date.now() / 1000) + UPLOAD_TARGET_TTL_SECONDS
|
|
277
|
+
return {
|
|
278
|
+
url: '/api/storage-upload',
|
|
279
|
+
fields: {
|
|
280
|
+
key,
|
|
281
|
+
'content-type': contentType,
|
|
282
|
+
'max-bytes': String(maxBytes),
|
|
283
|
+
expires: String(expires),
|
|
284
|
+
signature: signUploadFields(key, contentType, maxBytes, expires),
|
|
285
|
+
},
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import type { WebhookDispatchInput, WebhookDispatchResult } from '../../server-lib/webhook-dispatch'
|
|
4
|
+
import { writeJsonAtomicSync } from './atomic-write'
|
|
5
|
+
import { dataDir } from './data-dir'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The fake webhook counterparty, simulated-mode-only (NOT a port — an app-owned dispatch seam;
|
|
9
|
+
* see the decision log). The Actors precedent, statically: instead of a real HTTP POST to a customer
|
|
10
|
+
* URL, it CATCHES each egress attempt into `.data/webhooks/` — the mail catch-store pattern
|
|
11
|
+
* (packages/kit/src/adapters/fake/email.ts) — so the Simulator Hooks tab can display exactly what would have been
|
|
12
|
+
* sent (the signed body and the signature header). `.data/webhooks/` is a Snapshots LIVE_DIR
|
|
13
|
+
* (simulator-admin.ts), so a reset clears the catch-store and save/restore snapshot it.
|
|
14
|
+
*
|
|
15
|
+
* To let e2e/demo exercise the retry path deterministically, it honours a per-endpoint FAILURE TOGGLE:
|
|
16
|
+
* a Simulator control writes the set of failing endpoint ids to `.data/simulator/webhook-failures.json`
|
|
17
|
+
* (a `simulator` LIVE_DIR file, so reset clears it too), and a dispatch to a toggled endpoint returns a
|
|
18
|
+
* simulated failure instead of "delivering". This is the simplest deterministic mechanism (a plain
|
|
19
|
+
* per-endpoint flag beats magic URL markers — the operator flips it live from the panel).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** One caught egress attempt, keyed in the store by delivery id (the latest attempt overwrites). */
|
|
23
|
+
export interface CaughtWebhook {
|
|
24
|
+
deliveryId: string
|
|
25
|
+
endpointId: string
|
|
26
|
+
url: string
|
|
27
|
+
headers: Record<string, string>
|
|
28
|
+
body: string
|
|
29
|
+
at: string
|
|
30
|
+
ok: boolean
|
|
31
|
+
error?: string | undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function catchFile(deliveryId: string): string {
|
|
35
|
+
return path.join(dataDir('webhooks'), `${deliveryId}.json`)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function failuresFile(): string {
|
|
39
|
+
return path.join(dataDir('simulator'), 'webhook-failures.json')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The set of endpoint ids currently toggled to fail (empty when the file is absent). */
|
|
43
|
+
export function readFailingEndpoints(): Set<string> {
|
|
44
|
+
const file = failuresFile()
|
|
45
|
+
if (!existsSync(file)) return new Set()
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as { endpointIds?: unknown }
|
|
48
|
+
return new Set(Array.isArray(parsed.endpointIds) ? parsed.endpointIds.filter((x) => typeof x === 'string') : [])
|
|
49
|
+
} catch {
|
|
50
|
+
return new Set()
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Toggle whether a given endpoint's fake dispatch simulates failure. */
|
|
55
|
+
export function setEndpointFailing(endpointId: string, failing: boolean): void {
|
|
56
|
+
const current = readFailingEndpoints()
|
|
57
|
+
if (failing) current.add(endpointId)
|
|
58
|
+
else current.delete(endpointId)
|
|
59
|
+
writeJsonAtomicSync(failuresFile(), { endpointIds: [...current] })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read one caught delivery (the latest attempt), or null. */
|
|
63
|
+
export function readCaughtWebhook(deliveryId: string): CaughtWebhook | null {
|
|
64
|
+
const file = catchFile(deliveryId)
|
|
65
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as CaughtWebhook) : null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Every caught delivery across the world — the Simulator Hooks tab merges these onto the DB rows. */
|
|
69
|
+
export function listCaughtWebhooks(): CaughtWebhook[] {
|
|
70
|
+
const dir = dataDir('webhooks')
|
|
71
|
+
return readdirSync(dir)
|
|
72
|
+
.filter((f) => f.endsWith('.json'))
|
|
73
|
+
.map((f) => JSON.parse(readFileSync(path.join(dir, f), 'utf8')) as CaughtWebhook)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The fake dispatch: record the attempt to the catch-store (always — even a "failure" is a real egress
|
|
78
|
+
* attempt worth inspecting), then report delivered unless the endpoint is toggled to fail.
|
|
79
|
+
*/
|
|
80
|
+
export function fakeDispatchWebhook(input: WebhookDispatchInput): WebhookDispatchResult {
|
|
81
|
+
const failing = readFailingEndpoints().has(input.endpointId)
|
|
82
|
+
const result: WebhookDispatchResult = failing
|
|
83
|
+
? { delivered: false, error: 'fake failure toggle' }
|
|
84
|
+
: { delivered: true, status: 200 }
|
|
85
|
+
|
|
86
|
+
const caught: CaughtWebhook = {
|
|
87
|
+
deliveryId: input.deliveryId,
|
|
88
|
+
endpointId: input.endpointId,
|
|
89
|
+
url: input.url,
|
|
90
|
+
headers: input.headers,
|
|
91
|
+
body: input.body,
|
|
92
|
+
at: new Date().toISOString(),
|
|
93
|
+
ok: result.delivered,
|
|
94
|
+
error: result.error,
|
|
95
|
+
}
|
|
96
|
+
writeJsonAtomicSync(catchFile(input.deliveryId), caught)
|
|
97
|
+
return result
|
|
98
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import 'server-only'
|
|
2
|
+
|
|
3
|
+
import type { AnalyticsPort } from '../ports/analytics'
|
|
4
|
+
import type { AuthPort } from '../ports/auth'
|
|
5
|
+
import type { DbPort } from '../ports/db'
|
|
6
|
+
import type { EmailPort } from '../ports/email'
|
|
7
|
+
import type { JobsPort } from '../ports/jobs'
|
|
8
|
+
import type { LlmPort } from '../ports/llm'
|
|
9
|
+
import type { StoragePort } from '../ports/storage'
|
|
10
|
+
import { simulatedDevServer } from './dev-server'
|
|
11
|
+
import { fakeAnalytics } from './fake/analytics'
|
|
12
|
+
import { fakeAuth } from './fake/auth'
|
|
13
|
+
import { fakeDb } from './fake/db'
|
|
14
|
+
import { fakeEmail } from './fake/email'
|
|
15
|
+
import { fakeJobs } from './fake/jobs'
|
|
16
|
+
import { fakeLlm } from './fake/llm'
|
|
17
|
+
import { fakeStorage } from './fake/storage'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The adapter registry: the ONE place run mode selects implementations. Simulated is the default —
|
|
21
|
+
* dev, demo, and E2E are first-class citizens on fakes; APP_MODE=real is for adapter work
|
|
22
|
+
* against dev cloud resources and for deployed environments.
|
|
23
|
+
*
|
|
24
|
+
* TWO WORDS, DELIBERATELY. The MODE is `simulated` (is this a simulated world? — what the Simulator
|
|
25
|
+
* panel, the fail-closed guard and every route gate ask). The ADAPTER KIND stays `fake`: in the
|
|
26
|
+
* test-double sense a fake is a working implementation with a shortcut, which is exactly what pglite
|
|
27
|
+
* is for Postgres and `.data/` is for S3. So `if (isSimulated) -> fakeDb` reads correctly: in a
|
|
28
|
+
* simulated world, the DB port is served by a fake.
|
|
29
|
+
*
|
|
30
|
+
* `APP_MODE` only ever tests for `'real'`, so an older `APP_MODE=fake` still resolves to `simulated`
|
|
31
|
+
* and no deployed config breaks.
|
|
32
|
+
*/
|
|
33
|
+
export type AppMode = 'simulated' | 'real'
|
|
34
|
+
export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
|
|
35
|
+
export const isSimulated = appMode === 'simulated'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Demo build flag. packages/kit/src/adapters is where process.env is read (lint-enforced), so run-mode
|
|
39
|
+
* signals like this live here and everything else imports the boolean — the demo badge, the fail-closed
|
|
40
|
+
* guard below, etc. A demo build is a simulated-mode build that opts in explicitly via DEMO_MODE=1.
|
|
41
|
+
* An app's own adapters (apps/<app>/src/adapters/real) may read their own configuration from process.env,
|
|
42
|
+
* but never these run-mode variables (lint-enforced). The app's registry may not read process.env at all, and
|
|
43
|
+
* takes `isSimulated` from here by convention, which also runs the guard below for it.
|
|
44
|
+
*/
|
|
45
|
+
export const isDemoMode = process.env['DEMO_MODE'] === '1'
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* E2E build flag. Lets the e2e suite run against a PRODUCTION build instead of `next dev`, which is
|
|
49
|
+
* where most of CI's e2e wall clock goes — every route otherwise pays an on-demand compile, and every
|
|
50
|
+
* timeout in the repo is sized to absorb it.
|
|
51
|
+
*
|
|
52
|
+
* This is deliberately NOT `DEMO_MODE=1`, even though that would already satisfy the guard below.
|
|
53
|
+
* A demo build renders `<DemoBadge />`, which changes the very pages the axe sweep asserts on — the
|
|
54
|
+
* suite would be testing a different product than the one that ships. Measured, not assumed: see
|
|
55
|
+
* `.claude/future-tasks/resolved/e2e-against-production-build.md`.
|
|
56
|
+
*/
|
|
57
|
+
const isE2eBuild = process.env['E2E_BUILD'] === '1'
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A developer's own `next dev` of a simulated world, and nothing else (./dev-server.ts says why each condition is
|
|
61
|
+
* there): what a dev-only Simulator affordance asks before it exists. False in real mode, in every production build
|
|
62
|
+
* (deployed, demo, e2e) and under Vitest.
|
|
63
|
+
*/
|
|
64
|
+
export const isSimulatedDevServer = simulatedDevServer({
|
|
65
|
+
isSimulated,
|
|
66
|
+
nodeEnv: process.env.NODE_ENV,
|
|
67
|
+
isDemoMode,
|
|
68
|
+
isE2eBuild,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
// Fail CLOSED: a production build must never silently serve fake auth
|
|
72
|
+
// because APP_MODE was forgotten. The guard is about ACCIDENTS, so every way past it is an explicit,
|
|
73
|
+
// deliberate opt-in: DEMO_MODE=1 for demo builds, E2E_BUILD=1 for a production-build test run.
|
|
74
|
+
// Neither can be set by forgetting something. `authorized-mutations.test.ts`'s sibling
|
|
75
|
+
// `production-guard.test.ts` proves the guard still closes when no opt-in is set. That no deployed
|
|
76
|
+
// environment carries either flag is @sssb/cdk's: the SssbApp construct fails `cdk synth` if the server's
|
|
77
|
+
// final environment sets either one or anything but APP_MODE=real.
|
|
78
|
+
if (isSimulated && process.env.NODE_ENV === 'production' && !isDemoMode && !isE2eBuild) {
|
|
79
|
+
// The message deliberately does NOT offer the bypasses as remedies. An earlier wording listed all
|
|
80
|
+
// three env vars as ways to proceed, which hands someone debugging a real deployment a menu with
|
|
81
|
+
// two wrong answers on it — and the wrong answers are the ones that make the error stop.
|
|
82
|
+
throw new Error(
|
|
83
|
+
'refusing to run fake adapters in a production build. A deployment must set APP_MODE=real. ' +
|
|
84
|
+
'If you are seeing this in a deployed environment then THAT is the bug: do not set DEMO_MODE ' +
|
|
85
|
+
'or E2E_BUILD to silence it. Those exist only for local demo builds and the e2e suite, and ' +
|
|
86
|
+
'with fake adapters sign-in is passwordless person switching — anyone who reaches the URL ' +
|
|
87
|
+
'is an admin.',
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Past the guard with fake adapters in a production build means a bypass is active. That is legitimate
|
|
92
|
+
// for a demo build or an e2e run and catastrophic anywhere else, and the two are indistinguishable from
|
|
93
|
+
// inside the process — so say so loudly rather than starting quietly. Whoever is reading logs when this
|
|
94
|
+
// turns out to be the wrong machine will see it.
|
|
95
|
+
if (isSimulated && process.env.NODE_ENV === 'production') {
|
|
96
|
+
const bypass = isDemoMode ? 'DEMO_MODE=1' : 'E2E_BUILD=1'
|
|
97
|
+
console.warn(
|
|
98
|
+
`\n${'!'.repeat(80)}\n` +
|
|
99
|
+
`FAKE ADAPTERS IN A PRODUCTION BUILD — bypass active: ${bypass}\n` +
|
|
100
|
+
`Sign-in is passwordless person switching; there is no real authentication.\n` +
|
|
101
|
+
`This is correct for a demo build or the e2e suite. If this is a real deployment,\n` +
|
|
102
|
+
`stop it now and set APP_MODE=real.\n` +
|
|
103
|
+
`${'!'.repeat(80)}\n`,
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const real = appMode === 'real' ? await (await import('./real/index')).createRealPorts() : null
|
|
108
|
+
|
|
109
|
+
export const auth: AuthPort = real?.auth ?? fakeAuth
|
|
110
|
+
export const db: DbPort = real?.db ?? fakeDb
|
|
111
|
+
export const storage: StoragePort = real?.storage ?? fakeStorage
|
|
112
|
+
export const llm: LlmPort = real?.llm ?? fakeLlm
|
|
113
|
+
export const email: EmailPort = real?.email ?? fakeEmail
|
|
114
|
+
export const analytics: AnalyticsPort = real?.analytics ?? fakeAnalytics
|
|
115
|
+
export const jobs: JobsPort = real?.jobs ?? fakeJobs
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { useSignUp } from '@clerk/nextjs'
|
|
4
|
+
import { Stack, Text } from '@mantine/core'
|
|
5
|
+
import { useEffect, useState } from 'react'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Clerk ticket-strategy sign-up (ADR-0003): at cutover, Clerk organization invitations carry a
|
|
9
|
+
* `__clerk_ticket` query param onto this page's URL instead of the fake email's plain
|
|
10
|
+
* `/accept-invite?invite=<id>` link. sign-in-form.tsx is the reference for the v7 signals API
|
|
11
|
+
* (signIn.password() → status → finalize()) — the sign-up equivalent used here is
|
|
12
|
+
* signUp.ticket() → status → finalize(), per @clerk/shared's SignUpFutureResource.
|
|
13
|
+
*
|
|
14
|
+
* AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance. Verify the full
|
|
15
|
+
* ticket round-trip once a dev Clerk instance issues real invitation tickets (see
|
|
16
|
+
* docs/cutover-checklist.md, `auth-dev` row).
|
|
17
|
+
*
|
|
18
|
+
* Lives in packages/kit/src/adapters because it imports the vendor SDK; the AcceptInviteShell renders it as a
|
|
19
|
+
* slot, and all copy arrives via `labels` from the page's next-intl lookup (same contract as
|
|
20
|
+
* RealSignInForm — one auth UI, no vendor-side strings).
|
|
21
|
+
*/
|
|
22
|
+
export function RealAcceptInviteForm({
|
|
23
|
+
ticket,
|
|
24
|
+
redirectTo,
|
|
25
|
+
labels,
|
|
26
|
+
}: {
|
|
27
|
+
ticket: string | null
|
|
28
|
+
redirectTo: string
|
|
29
|
+
labels: AcceptInviteTicketLabels
|
|
30
|
+
}) {
|
|
31
|
+
const { signUp, fetchStatus } = useSignUp()
|
|
32
|
+
const [error, setError] = useState<string | null>(null)
|
|
33
|
+
const [accepted, setAccepted] = useState(false)
|
|
34
|
+
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (!ticket) return
|
|
37
|
+
// Driving an external SDK call on mount (Clerk's ticket-strategy sign-up) is the
|
|
38
|
+
// legitimate "sync with an external system" case the set-state-in-effect rule guards —
|
|
39
|
+
// same as the Simulator glue's fetch-on-mount effects.
|
|
40
|
+
void (async () => {
|
|
41
|
+
const { error: ticketError } = await signUp.ticket({ ticket })
|
|
42
|
+
if (ticketError) {
|
|
43
|
+
setError(labels.genericError)
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
if (signUp.status === 'complete') {
|
|
47
|
+
const finalized = await signUp.finalize()
|
|
48
|
+
if (finalized.error) {
|
|
49
|
+
setError(labels.genericError)
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
setAccepted(true)
|
|
53
|
+
window.location.assign(redirectTo)
|
|
54
|
+
} else {
|
|
55
|
+
setError(labels.genericError)
|
|
56
|
+
}
|
|
57
|
+
})()
|
|
58
|
+
}, [ticket, signUp, redirectTo, labels.genericError])
|
|
59
|
+
|
|
60
|
+
if (!ticket) return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
61
|
+
|
|
62
|
+
return (
|
|
63
|
+
<Stack gap="sm">
|
|
64
|
+
{!accepted && !error ? (
|
|
65
|
+
<Text c="gray.7">{fetchStatus === 'fetching' ? labels.accepting : labels.oneMoment}</Text>
|
|
66
|
+
) : null}
|
|
67
|
+
{error ? <Text c="red.8">{error}</Text> : null}
|
|
68
|
+
</Stack>
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface AcceptInviteTicketLabels {
|
|
73
|
+
missingTicket: string
|
|
74
|
+
accepting: string
|
|
75
|
+
oneMoment: string
|
|
76
|
+
genericError: string
|
|
77
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { PostHog } from 'posthog-node'
|
|
2
|
+
import type { AnalyticsPort } from '../../ports/analytics'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
|
|
6
|
+
* staging/prod only (ADR-0010); everywhere else the no-op fake is wired even in real mode.
|
|
7
|
+
*/
|
|
8
|
+
export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
|
|
9
|
+
const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
|
|
10
|
+
|
|
11
|
+
return {
|
|
12
|
+
async capture(event, properties, distinctId = 'server') {
|
|
13
|
+
client.capture({ distinctId, event, ...(properties === undefined ? {} : { properties }) })
|
|
14
|
+
},
|
|
15
|
+
|
|
16
|
+
async isFlagEnabled(flag, defaultValue = false) {
|
|
17
|
+
// A flag read is never load-bearing: a PostHog outage degrades to the default rather
|
|
18
|
+
// than throwing into whatever screen asked (the protected layout reads flags on every
|
|
19
|
+
// authenticated render).
|
|
20
|
+
try {
|
|
21
|
+
const enabled = await client.isFeatureEnabled(flag, 'server')
|
|
22
|
+
return enabled ?? defaultValue
|
|
23
|
+
} catch {
|
|
24
|
+
return defaultValue
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
}
|