@sssb/kit 0.2.0 → 0.4.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/dist/release.json +1 -1
- package/package.json +4 -1
- package/src/adapters/fake/auth.ts +18 -6
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/fake/jobs.ts +17 -39
- package/src/adapters/fake/simulator.ts +2 -3
- package/src/adapters/index.ts +33 -6
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +54 -0
- package/src/adapters/real/accept-invite-form.tsx +62 -15
- package/src/adapters/real/analytics.ts +1 -1
- package/src/adapters/real/auth.ts +28 -2
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/db-data-api.ts +1 -1
- package/src/adapters/real/db-port.ts +27 -0
- package/src/adapters/real/db.ts +2 -21
- package/src/adapters/real/index.ts +117 -30
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +2 -1
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +112 -0
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/components/app-header.tsx +1 -1
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +45 -57
- package/src/core/abilities.ts +6 -1
- package/src/core/same-origin-path.ts +20 -0
- package/src/cutover/rows.json +13 -1
- package/src/db/audit.ts +2 -2
- package/src/db/family-suite.ts +42 -0
- package/src/db/family.ts +91 -0
- package/src/db/jobs.ts +4 -3
- package/src/db/keyset.ts +12 -25
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/notifications.ts +2 -2
- package/src/db/org-lookup.ts +1 -1
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +2 -1
- package/src/db/webhooks.ts +4 -4
- package/src/demo-static/world.ts +5 -4
- package/src/guide.md +23 -4
- package/src/jobs/digest-email.ts +32 -17
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +3 -1
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/ports/jobs.ts +25 -4
- package/src/server-lib/defer.ts +4 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/server-lib/scheduled-tick.ts +13 -3
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +2 -2
- package/src/service-auth/verify.ts +10 -3
- package/src/service-auth/webhook.ts +14 -5
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +296 -0
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/suite.ts +2 -0
- package/src/testing/contract.ts +6 -4
package/dist/release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"commit":"
|
|
1
|
+
{"commit":"dfc5cdde3b3fa3043efc03891ee5db574179f740"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sssb/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"./adapters/fake/storage": "./src/adapters/fake/storage.ts",
|
|
36
36
|
"./adapters/fake/webhooks": "./src/adapters/fake/webhooks.ts",
|
|
37
37
|
"./adapters/index": "./src/adapters/index.ts",
|
|
38
|
+
"./adapters/proxy": "./src/adapters/proxy.ts",
|
|
38
39
|
"./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
|
|
39
40
|
"./adapters/real/index": "./src/adapters/real/index.ts",
|
|
40
41
|
"./adapters/real/llm": "./src/adapters/real/llm.ts",
|
|
@@ -57,6 +58,7 @@
|
|
|
57
58
|
"./components/simulator/actor-runtime": "./src/components/simulator/actor-runtime.ts",
|
|
58
59
|
"./components/simulator/actor-shell": "./src/components/simulator/actor-shell.tsx",
|
|
59
60
|
"./components/simulator/actors-app": "./src/components/simulator/actors-app.tsx",
|
|
61
|
+
"./components/simulator/simulator-host": "./src/components/simulator/simulator-host.tsx",
|
|
60
62
|
"./components/simulator/simulator-panel": "./src/components/simulator/simulator-panel.tsx",
|
|
61
63
|
"./components/simulator/people-app": "./src/components/simulator/people-app.tsx",
|
|
62
64
|
"./components/simulator/errors-app": "./src/components/simulator/errors-app.tsx",
|
|
@@ -146,6 +148,7 @@
|
|
|
146
148
|
"./server-lib/notify-deps": "./src/server-lib/notify-deps.ts",
|
|
147
149
|
"./server-lib/preset-operations": "./src/server-lib/preset-operations.ts",
|
|
148
150
|
"./server-lib/scheduled-tick": "./src/server-lib/scheduled-tick.ts",
|
|
151
|
+
"./server-lib/simulator-api": "./src/server-lib/simulator-api.ts",
|
|
149
152
|
"./server-lib/sms": "./src/server-lib/sms.ts",
|
|
150
153
|
"./server-lib/webhook-dispatch": "./src/server-lib/webhook-dispatch.ts",
|
|
151
154
|
"./service-auth/mailgun": "./src/service-auth/mailgun.ts",
|
|
@@ -10,6 +10,7 @@ import { isRestricted, isRole, type Role } from '../../core/roles'
|
|
|
10
10
|
import type {
|
|
11
11
|
AuthPort,
|
|
12
12
|
AuthUser,
|
|
13
|
+
CreatedInvite,
|
|
13
14
|
InviteInput,
|
|
14
15
|
Membership,
|
|
15
16
|
MemberStanding,
|
|
@@ -93,10 +94,11 @@ function findPerson(id: string | undefined): SeedPerson | undefined {
|
|
|
93
94
|
|
|
94
95
|
/**
|
|
95
96
|
* Simulated-mode-only locale lookup (NOT part of AuthPort) — the notification fan-out's `resolveLocale`
|
|
96
|
-
* enrichment,
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
97
|
+
* enrichment, and the job context's (`JobContext.resolveLocale`, which the simulated runner fills, so the
|
|
98
|
+
* digest email follows it too), so a recipient's email/SMS render in their language. Honours a
|
|
99
|
+
* profile-override locale first, then the person's seed locale; undefined for an unknown id (callers then
|
|
100
|
+
* fall back to the app default). Real mode has no analog (Clerk memberships carry no locale), so this
|
|
101
|
+
* stays fake-only and behind those optional dependencies.
|
|
100
102
|
*/
|
|
101
103
|
export function personLocale(userId: string): Locale | undefined {
|
|
102
104
|
const person = findPerson(userId)
|
|
@@ -281,7 +283,7 @@ export const fakeAuth: AuthPort = {
|
|
|
281
283
|
return { role: membership.role, restricted: isRestricted(person.restricted, membership.role) }
|
|
282
284
|
},
|
|
283
285
|
|
|
284
|
-
async createInvite(invite: InviteInput): Promise<
|
|
286
|
+
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
285
287
|
if (!isRole(invite.role)) throw new ForbiddenError('unknown role')
|
|
286
288
|
const stored: StoredInvite = {
|
|
287
289
|
id: crypto.randomUUID(),
|
|
@@ -291,7 +293,17 @@ export const fakeAuth: AuthPort = {
|
|
|
291
293
|
invitedAt: new Date().toISOString(),
|
|
292
294
|
}
|
|
293
295
|
await writeJsonAtomic(invitesFile(), [...readInvites(), stored])
|
|
294
|
-
|
|
296
|
+
// The accept page finds the invitation by its id (`findInvite`).
|
|
297
|
+
const acceptUrl = new URL(invite.acceptPageUrl)
|
|
298
|
+
acceptUrl.searchParams.set('invite', stored.id)
|
|
299
|
+
return {
|
|
300
|
+
id: stored.id,
|
|
301
|
+
name: null,
|
|
302
|
+
email: stored.email,
|
|
303
|
+
role: stored.role,
|
|
304
|
+
status: 'invited',
|
|
305
|
+
acceptUrl: acceptUrl.toString(),
|
|
306
|
+
}
|
|
295
307
|
},
|
|
296
308
|
|
|
297
309
|
async listMyOrgs(): Promise<OrgRef[]> {
|
package/src/adapters/fake/db.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Kysely, type Transaction } from 'kysely'
|
|
|
3
3
|
import { migrateToLatest } from '../../db/migrate'
|
|
4
4
|
import type { DB } from '../../db/schema'
|
|
5
5
|
import { seedDb } from '../../db/seed'
|
|
6
|
-
import {
|
|
6
|
+
import { family } from '../../db/family'
|
|
7
7
|
import type { DbPort } from '../../ports/db'
|
|
8
8
|
import { worldNow } from './clock'
|
|
9
9
|
import { dataDir } from './data-dir'
|
|
@@ -53,6 +53,8 @@ export async function closeFakeDb(): Promise<void> {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
export const fakeDb: DbPort = {
|
|
56
|
+
// pglite is a Postgres transport: the family's isolation and the family's tenant scope.
|
|
57
|
+
isolation: family.isolation,
|
|
56
58
|
getDb() {
|
|
57
59
|
return instance().db
|
|
58
60
|
},
|
|
@@ -62,7 +64,7 @@ export const fakeDb: DbPort = {
|
|
|
62
64
|
async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
|
|
63
65
|
const { db, ready } = instance()
|
|
64
66
|
await ready
|
|
65
|
-
return runWithTenant(db, tenantId, fn)
|
|
67
|
+
return family.runWithTenant(db, tenantId, fn)
|
|
66
68
|
},
|
|
67
69
|
async migrateToLatest() {
|
|
68
70
|
await instance().ready
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jobHandlers, serviceManagedOrgSlugs } from '@sssb/app-config/jobs'
|
|
2
2
|
import { isJobKind, type JobStatus } from '../../core/jobs'
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { type JobTimelineEntry, loadTimelines, toIso } from '../../db/jobs'
|
|
4
|
+
import { runJobInProcess } from '../../jobs/run-in-process'
|
|
5
5
|
import { NotFoundError } from '../../ports/errors'
|
|
6
6
|
import type { JobsPort, SubmittedJob } from '../../ports/jobs'
|
|
7
7
|
import { readFlags } from './analytics'
|
|
@@ -40,47 +40,23 @@ async function notifyTerminal(job: SubmittedJob, status: 'completed' | 'failed')
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
|
-
* Runs a submitted job to completion in-process
|
|
44
|
-
* instant fake still records queued -> running -> completed (or -> failed)
|
|
45
|
-
* the
|
|
46
|
-
* the held flag itself: holding only gates
|
|
47
|
-
* forward deliberately.
|
|
43
|
+
* Runs a submitted job to completion in-process (`runJobInProcess`, shared with the real in-process runner). An
|
|
44
|
+
* instant fake still records queued -> running -> completed (or -> failed), the transitions a CodeBuild run reports
|
|
45
|
+
* through the service-authenticated jobs webhook. A concurrent runner (a second run-pending click racing an instant
|
|
46
|
+
* start) that already claimed the job makes this return false. Never checks the held flag itself: holding only gates
|
|
47
|
+
* fakeJobs.start(); runPendingJobs() steps held jobs forward deliberately.
|
|
48
48
|
*/
|
|
49
49
|
async function executeJob(job: SubmittedJob): Promise<boolean> {
|
|
50
50
|
await fakeDb.ready()
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
if (!isJobKind(job.kind)) {
|
|
60
|
-
await recordJobStatus(fakeDb, job.tenantId, job.id, 'failed', { error: `unknown job kind: ${job.kind}` })
|
|
61
|
-
return true
|
|
62
|
-
}
|
|
63
|
-
try {
|
|
64
|
-
const handler = jobHandlers[job.kind]
|
|
65
|
-
if (!handler) throw new Error(`no job handler registered for kind: ${job.kind}`)
|
|
66
|
-
const { resultKey } = await handler(job.payload, {
|
|
67
|
-
db: fakeDb,
|
|
68
|
-
storage: fakeStorage,
|
|
69
|
-
email: fakeEmail,
|
|
70
|
-
llm: fakeLlm,
|
|
71
|
-
tenantId: job.tenantId,
|
|
72
|
-
orgId: job.orgId,
|
|
73
|
-
jobId: job.id,
|
|
74
|
-
})
|
|
75
|
-
await recordJobStatus(fakeDb, job.tenantId, job.id, 'completed', { resultKey })
|
|
76
|
-
await notifyTerminal(job, 'completed')
|
|
77
|
-
} catch (error) {
|
|
78
|
-
await recordJobStatus(fakeDb, job.tenantId, job.id, 'failed', {
|
|
79
|
-
error: error instanceof Error ? error.message : String(error),
|
|
80
|
-
})
|
|
81
|
-
await notifyTerminal(job, 'failed')
|
|
51
|
+
const ports = {
|
|
52
|
+
db: fakeDb,
|
|
53
|
+
storage: fakeStorage,
|
|
54
|
+
email: fakeEmail,
|
|
55
|
+
llm: fakeLlm,
|
|
56
|
+
auth: fakeAuth,
|
|
57
|
+
resolveLocale: personLocale,
|
|
82
58
|
}
|
|
83
|
-
return
|
|
59
|
+
return runJobInProcess(job, ports, (status) => notifyTerminal(job, status))
|
|
84
60
|
}
|
|
85
61
|
|
|
86
62
|
export const fakeJobs: JobsPort = {
|
|
@@ -258,6 +234,8 @@ export async function produceJobArtifact(
|
|
|
258
234
|
storage: fakeStorage,
|
|
259
235
|
email: fakeEmail,
|
|
260
236
|
llm: fakeLlm,
|
|
237
|
+
auth: fakeAuth,
|
|
238
|
+
resolveLocale: personLocale,
|
|
261
239
|
tenantId: row.tenant_id,
|
|
262
240
|
orgId: row.org_id,
|
|
263
241
|
jobId: row.id,
|
|
@@ -8,9 +8,8 @@ import { dataDir } from './data-dir'
|
|
|
8
8
|
/**
|
|
9
9
|
* Simulator continuity (simulated-mode-only, NOT a port): who's who is a session (`${APP_SLUG}_session`);
|
|
10
10
|
* whose WORLD you're looking at is the viewpoint. A signed-in session's viewpoint always follows
|
|
11
|
-
* it; the cookie only matters when there's no session (
|
|
12
|
-
*
|
|
13
|
-
* is reserved for that later slice.
|
|
11
|
+
* it; the cookie only matters when there's no session (an invited-but-unregistered viewer).
|
|
12
|
+
* `person:<id>` covers seeded/dynamic people; `invited:<inviteId>` is a pending invite (`readInvites`, ./auth.ts).
|
|
14
13
|
*/
|
|
15
14
|
export type PersonKey = `person:${string}` | `invited:${string}`
|
|
16
15
|
|
package/src/adapters/index.ts
CHANGED
|
@@ -15,6 +15,8 @@ import { fakeEmail } from './fake/email'
|
|
|
15
15
|
import { fakeJobs } from './fake/jobs'
|
|
16
16
|
import { fakeLlm } from './fake/llm'
|
|
17
17
|
import { fakeStorage } from './fake/storage'
|
|
18
|
+
import { lazyJobs } from './lazy-jobs'
|
|
19
|
+
import { appMode, isSimulated } from './run-mode'
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
22
|
* The adapter registry: the ONE place run mode selects implementations. Simulated is the default —
|
|
@@ -27,12 +29,10 @@ import { fakeStorage } from './fake/storage'
|
|
|
27
29
|
* is for Postgres and `.data/` is for S3. So `if (isSimulated) -> fakeDb` reads correctly: in a
|
|
28
30
|
* simulated world, the DB port is served by a fake.
|
|
29
31
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
+
* The mode itself is read in ./run-mode.ts, which loads nothing else, so the request proxy (./proxy.ts) can ask it
|
|
33
|
+
* without loading this registry; it is re-exported here, where everything else imports it from.
|
|
32
34
|
*/
|
|
33
|
-
export type AppMode
|
|
34
|
-
export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
|
|
35
|
-
export const isSimulated = appMode === 'simulated'
|
|
35
|
+
export { appMode, isSimulated, type AppMode } from './run-mode'
|
|
36
36
|
|
|
37
37
|
/**
|
|
38
38
|
* Demo build flag. packages/kit/src/adapters is where process.env is read (lint-enforced), so run-mode
|
|
@@ -104,7 +104,10 @@ if (isSimulated && process.env.NODE_ENV === 'production') {
|
|
|
104
104
|
)
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
const real =
|
|
107
|
+
const real =
|
|
108
|
+
appMode === 'real'
|
|
109
|
+
? await (await import('./real/index')).createRealPorts({ inProcessJobs: buildInProcessJobs })
|
|
110
|
+
: null
|
|
108
111
|
|
|
109
112
|
export const auth: AuthPort = real?.auth ?? fakeAuth
|
|
110
113
|
export const db: DbPort = real?.db ?? fakeDb
|
|
@@ -113,3 +116,27 @@ export const llm: LlmPort = real?.llm ?? fakeLlm
|
|
|
113
116
|
export const email: EmailPort = real?.email ?? fakeEmail
|
|
114
117
|
export const analytics: AnalyticsPort = real?.analytics ?? fakeAnalytics
|
|
115
118
|
export const jobs: JobsPort = real?.jobs ?? fakeJobs
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The in-process job runner (real mode, `JOBS_RUNNER=in-process`), built here rather than by the real ports
|
|
122
|
+
* (./real/index.ts says why), and loaded on its first use (./lazy-jobs.ts): never while this module is evaluated, which
|
|
123
|
+
* would deadlock on a job handler that imports it. Its notification is the jobs webhook route's, with the request
|
|
124
|
+
* path's deps; the notification modules import this registry, so they too are imported when a job ends.
|
|
125
|
+
*/
|
|
126
|
+
async function buildInProcessJobs(
|
|
127
|
+
ports: Parameters<typeof import('./real/jobs-in-process').createInProcessJobs>[0],
|
|
128
|
+
): Promise<JobsPort> {
|
|
129
|
+
return lazyJobs(async () =>
|
|
130
|
+
(await import('./real/jobs-in-process')).createInProcessJobs(ports, notifyJobTerminalFromRegistry),
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function notifyJobTerminalFromRegistry(input: {
|
|
135
|
+
tenantId: string
|
|
136
|
+
jobId: string
|
|
137
|
+
status: 'completed' | 'failed'
|
|
138
|
+
}): Promise<void> {
|
|
139
|
+
const { notifyJobTerminal } = await import('../server-lib/notify')
|
|
140
|
+
const { makeNotifyDeps } = await import('../server-lib/notify-deps')
|
|
141
|
+
await notifyJobTerminal(await makeNotifyDeps(), auth, input)
|
|
142
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { JobsPort } from '../ports/jobs'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A jobs port that loads its runner on first use, not when it is made. The adapter registry builds the in-process
|
|
5
|
+
* runner with this (./index.ts): loading it means loading the app's job handlers (`@sssb/app-config/jobs`), and a handler
|
|
6
|
+
* that imports the registry (for `isSimulated`, say) would make the registry's top-level await wait on a module that
|
|
7
|
+
* waits on the registry, so the server would never finish loading. By the first `start` or `sweep` the registry has.
|
|
8
|
+
* A failed load is not kept: the next call tries again.
|
|
9
|
+
*/
|
|
10
|
+
export function lazyJobs(load: () => Promise<JobsPort>): JobsPort {
|
|
11
|
+
let runner: Promise<JobsPort> | undefined
|
|
12
|
+
const get = () =>
|
|
13
|
+
(runner ??= load().catch((error: unknown) => {
|
|
14
|
+
runner = undefined
|
|
15
|
+
throw error
|
|
16
|
+
}))
|
|
17
|
+
return {
|
|
18
|
+
async start(job) {
|
|
19
|
+
await (await get()).start(job)
|
|
20
|
+
},
|
|
21
|
+
async sweep(now) {
|
|
22
|
+
return (await (await get()).sweep?.(now)) ?? 0
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { NextFetchEvent, NextProxy, NextRequest } from 'next/server'
|
|
2
|
+
import { isSimulated } from './run-mode'
|
|
3
|
+
|
|
4
|
+
type ProxyResult = Awaited<ReturnType<NextProxy>>
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The app's request proxy (`src/proxy.ts`, Next's `proxy` file convention) with what SSSB's auth adapter needs around
|
|
8
|
+
* it. In real mode that is Clerk's middleware, without which the Clerk adapter's `auth()` refuses every request: the
|
|
9
|
+
* app's proxy runs inside it (./real/clerk-proxy.ts). In simulated mode the app's proxy runs as it is, and no Clerk
|
|
10
|
+
* code is loaded: the real half is reached only by `import()`, on the first request in real mode.
|
|
11
|
+
*
|
|
12
|
+
* The app's proxy still decides what each path gets (locale routing on pages, nothing on an API route); the app's
|
|
13
|
+
* `config.matcher` must send it every page AND every `/api/...` route, since Clerk needs to see both. (The starter's
|
|
14
|
+
* matcher leaves out a page path with a dot in it, so a page path has none.) Next runs a
|
|
15
|
+
* proxy on the Node.js runtime, so the `import()` here is an ordinary one.
|
|
16
|
+
*
|
|
17
|
+
* Use it as the default export of `src/proxy.ts`:
|
|
18
|
+
*
|
|
19
|
+
* export default withAuthProxy((request) => locales(request))
|
|
20
|
+
*/
|
|
21
|
+
export function withAuthProxy(proxy: NextProxy): (request: NextRequest, event: NextFetchEvent) => Promise<ProxyResult> {
|
|
22
|
+
if (isSimulated) return async (request, event) => proxy(request, event)
|
|
23
|
+
let real: Promise<(request: NextRequest, event: NextFetchEvent) => Promise<ProxyResult>> | undefined
|
|
24
|
+
return async (request, event) => {
|
|
25
|
+
// A failed load is forgotten, so the next request tries again rather than failing until a restart.
|
|
26
|
+
real ??= import('./real/clerk-proxy')
|
|
27
|
+
.then(({ withClerk }) => withClerk(proxy))
|
|
28
|
+
.catch((error: unknown) => {
|
|
29
|
+
real = undefined
|
|
30
|
+
throw error
|
|
31
|
+
})
|
|
32
|
+
return (await real)(request, event)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { EmailPort } from '../../ports/email'
|
|
2
|
+
import type { JobsPort } from '../../ports/jobs'
|
|
3
|
+
import type { LlmPort } from '../../ports/llm'
|
|
4
|
+
import type { StoragePort } from '../../ports/storage'
|
|
5
|
+
import { OPTIONAL_PORTS, type OptionalPort } from './optional-ports'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A call through a port the deployment declared unused (`<SWITCH>=none`, ./optional-ports.ts). Thrown at the call,
|
|
9
|
+
* never at boot: the app boots without the port, and only code that reaches for it fails, saying which switch to
|
|
10
|
+
* change (the framework's deferred mail catches it and logs it: ../../server-lib/defer.ts). Not one of the port
|
|
11
|
+
* errors routes map (`withPortErrors`), so a route that reaches it answers 500.
|
|
12
|
+
*/
|
|
13
|
+
export class AbsentPortError extends Error {
|
|
14
|
+
constructor(port: OptionalPort) {
|
|
15
|
+
const { variable } = OPTIONAL_PORTS[port]
|
|
16
|
+
const rows = [...new Set(Object.values(OPTIONAL_PORTS[port].env).flatMap((env) => Object.values(env)))]
|
|
17
|
+
super(
|
|
18
|
+
`the ${port} port is absent: this deployment sets ${variable}=none, declaring that the app does not use ` +
|
|
19
|
+
`it. To use it, set ${variable} and the settings it names (cutover row ${rows.join(', ')}).`,
|
|
20
|
+
)
|
|
21
|
+
this.name = 'AbsentPortError'
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function absent(port: OptionalPort): never {
|
|
26
|
+
throw new AbsentPortError(port)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const absentLlm: LlmPort = {
|
|
30
|
+
complete: async () => absent('llm'),
|
|
31
|
+
// Throws when called, not when iterated: the caller learns at once, before it streams anything to a client.
|
|
32
|
+
stream: () => absent('llm'),
|
|
33
|
+
runToolLoop: async () => absent('llm'),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const absentEmail: EmailPort = {
|
|
37
|
+
send: async () => absent('email'),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const absentJobs: JobsPort = {
|
|
41
|
+
start: async () => absent('jobs'),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Every method throws: an app that stores nothing never calls it, and one that does learns which switch to change. */
|
|
45
|
+
export const absentStorage: StoragePort = {
|
|
46
|
+
put: async () => absent('storage'),
|
|
47
|
+
get: async () => absent('storage'),
|
|
48
|
+
getSignedDownloadUrl: async () => absent('storage'),
|
|
49
|
+
createUploadTarget: async () => absent('storage'),
|
|
50
|
+
list: async () => absent('storage'),
|
|
51
|
+
delete: async () => absent('storage'),
|
|
52
|
+
copy: async () => absent('storage'),
|
|
53
|
+
head: async () => absent('storage'),
|
|
54
|
+
}
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
|
-
import { useSignUp } from '@clerk/nextjs'
|
|
3
|
+
import { useAuth, useSignIn, useSignUp } from '@clerk/nextjs'
|
|
4
4
|
import { Stack, Text } from '@mantine/core'
|
|
5
|
-
import { useEffect, useState } from 'react'
|
|
5
|
+
import { useEffect, useRef, useState } from 'react'
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* Clerk ticket-strategy
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* Clerk ticket-strategy acceptance (ADR-0003): the invitation mail carries Clerk's invitation URL (./auth.ts
|
|
9
|
+
* `createInvite`), and Clerk sends the invitee on to this page with `__clerk_ticket` and `__clerk_status` query
|
|
10
|
+
* params, where the fake's link carries `?invite=<id>`. Clerk's guide to accepting organization invitations: a status
|
|
11
|
+
* of `sign_in` means the invitee already has an account, and takes a ticket sign-in; `sign_up` (or none), a ticket
|
|
12
|
+
* sign-up; `complete`, that Clerk accepted it already, so the form only redirects; any other is shown as the error.
|
|
13
|
+
* sign-in-form.tsx is the reference for the v7 signals API (signIn.password() → status → finalize()); here it is
|
|
14
|
+
* signIn.ticket() or signUp.ticket() → status → finalize(), per @clerk/shared's SignInFutureResource and
|
|
15
|
+
* SignUpFutureResource.
|
|
13
16
|
*
|
|
14
17
|
* AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance. Verify the full
|
|
15
18
|
* ticket round-trip once a dev Clerk instance issues real invitation tickets (see
|
|
@@ -21,30 +24,64 @@ import { useEffect, useState } from 'react'
|
|
|
21
24
|
*/
|
|
22
25
|
export function RealAcceptInviteForm({
|
|
23
26
|
ticket,
|
|
27
|
+
status = null,
|
|
24
28
|
redirectTo,
|
|
25
29
|
labels,
|
|
26
30
|
}: {
|
|
27
31
|
ticket: string | null
|
|
32
|
+
/**
|
|
33
|
+
* Clerk's `__clerk_status` from the page's URL: `sign_in` for an invitee who already has an account, `sign_up` for
|
|
34
|
+
* one who has none, `complete` when Clerk accepted the invitation itself (the invitee was already signed in).
|
|
35
|
+
*/
|
|
36
|
+
status?: string | null
|
|
28
37
|
redirectTo: string
|
|
29
38
|
labels: AcceptInviteTicketLabels
|
|
30
39
|
}) {
|
|
31
|
-
const {
|
|
40
|
+
const { isLoaded } = useAuth()
|
|
41
|
+
const { signUp, fetchStatus: signUpFetch } = useSignUp()
|
|
42
|
+
const { signIn, fetchStatus: signInFetch } = useSignIn()
|
|
32
43
|
const [error, setError] = useState<string | null>(null)
|
|
33
44
|
const [accepted, setAccepted] = useState(false)
|
|
45
|
+
const plan = planFor(status)
|
|
46
|
+
const fetchStatus = plan === 'sign-in' ? signInFetch : signUpFetch
|
|
34
47
|
|
|
48
|
+
// A ticket is single-use, so it is submitted once. The resources change identity as Clerk loads, so the effect
|
|
49
|
+
// reads the current ones through a ref rather than depending on them (a dependency would run it again), starts
|
|
50
|
+
// only once Clerk has loaded, and remembers what it started.
|
|
51
|
+
const flows = useRef({ signIn, signUp })
|
|
35
52
|
useEffect(() => {
|
|
36
|
-
|
|
37
|
-
|
|
53
|
+
flows.current = { signIn, signUp }
|
|
54
|
+
})
|
|
55
|
+
const started = useRef<string | null>(null)
|
|
56
|
+
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (!isLoaded || (plan !== 'accepted' && !ticket)) return
|
|
59
|
+
const key = `${plan}:${ticket ?? ''}`
|
|
60
|
+
if (started.current === key) return
|
|
61
|
+
started.current = key
|
|
62
|
+
// Driving an external SDK call on mount (Clerk's ticket strategy) is the
|
|
38
63
|
// legitimate "sync with an external system" case the set-state-in-effect rule guards —
|
|
39
64
|
// same as the Simulator glue's fetch-on-mount effects.
|
|
40
65
|
void (async () => {
|
|
41
|
-
|
|
66
|
+
if (plan === 'accepted') {
|
|
67
|
+
setAccepted(true)
|
|
68
|
+
window.location.assign(redirectTo)
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
if (plan === 'unknown' || !ticket) {
|
|
72
|
+
setError(labels.genericError)
|
|
73
|
+
return
|
|
74
|
+
}
|
|
75
|
+
const { signIn: currentSignIn, signUp: currentSignUp } = flows.current
|
|
76
|
+
const flow = plan === 'sign-in' ? currentSignIn : currentSignUp
|
|
77
|
+
const { error: ticketError } =
|
|
78
|
+
plan === 'sign-in' ? await currentSignIn.ticket({ ticket }) : await currentSignUp.ticket({ ticket })
|
|
42
79
|
if (ticketError) {
|
|
43
80
|
setError(labels.genericError)
|
|
44
81
|
return
|
|
45
82
|
}
|
|
46
|
-
if (
|
|
47
|
-
const finalized = await
|
|
83
|
+
if (flow.status === 'complete') {
|
|
84
|
+
const finalized = await flow.finalize()
|
|
48
85
|
if (finalized.error) {
|
|
49
86
|
setError(labels.genericError)
|
|
50
87
|
return
|
|
@@ -55,9 +92,9 @@ export function RealAcceptInviteForm({
|
|
|
55
92
|
setError(labels.genericError)
|
|
56
93
|
}
|
|
57
94
|
})()
|
|
58
|
-
}, [
|
|
95
|
+
}, [isLoaded, plan, ticket, redirectTo, labels.genericError])
|
|
59
96
|
|
|
60
|
-
if (!ticket) return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
97
|
+
if (!ticket && plan !== 'accepted') return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
61
98
|
|
|
62
99
|
return (
|
|
63
100
|
<Stack gap="sm">
|
|
@@ -69,6 +106,16 @@ export function RealAcceptInviteForm({
|
|
|
69
106
|
)
|
|
70
107
|
}
|
|
71
108
|
|
|
109
|
+
type Plan = 'sign-in' | 'sign-up' | 'accepted' | 'unknown'
|
|
110
|
+
|
|
111
|
+
/** What Clerk's `__clerk_status` asks of the form. A missing status is a sign-up, as before the status was read. */
|
|
112
|
+
function planFor(status: string | null): Plan {
|
|
113
|
+
if (status === 'complete') return 'accepted'
|
|
114
|
+
if (status === 'sign_in') return 'sign-in'
|
|
115
|
+
if (status === null || status === 'sign_up') return 'sign-up'
|
|
116
|
+
return 'unknown'
|
|
117
|
+
}
|
|
118
|
+
|
|
72
119
|
export interface AcceptInviteTicketLabels {
|
|
73
120
|
missingTicket: string
|
|
74
121
|
accepting: string
|
|
@@ -3,7 +3,7 @@ import type { AnalyticsPort } from '../../ports/analytics'
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
|
|
6
|
-
* staging/prod only (ADR-0010)
|
|
6
|
+
* staging/prod only (ADR-0010): a real deployment without a key gets the no-op (./no-analytics.ts).
|
|
7
7
|
*/
|
|
8
8
|
export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
|
|
9
9
|
const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
|
|
@@ -5,6 +5,7 @@ import { isRestricted, isRole, type Role } from '../../core/roles'
|
|
|
5
5
|
import type {
|
|
6
6
|
AuthPort,
|
|
7
7
|
AuthUser,
|
|
8
|
+
CreatedInvite,
|
|
8
9
|
InviteInput,
|
|
9
10
|
Membership,
|
|
10
11
|
MemberStanding,
|
|
@@ -38,6 +39,12 @@ function roleFrom(metadata: unknown, fallback: Role): Role {
|
|
|
38
39
|
return role && isRole(role) ? role : fallback
|
|
39
40
|
}
|
|
40
41
|
|
|
42
|
+
/** The accept page as a path (with any query), for Clerk to resolve against the instance's own domain. */
|
|
43
|
+
function acceptPagePath(acceptPageUrl: string): string {
|
|
44
|
+
const url = new URL(acceptPageUrl)
|
|
45
|
+
return `${url.pathname}${url.search}`
|
|
46
|
+
}
|
|
47
|
+
|
|
41
48
|
async function organizationIdForSlug(slug: string): Promise<string> {
|
|
42
49
|
const client = await clerkClient()
|
|
43
50
|
const org = await client.organizations.getOrganization({ slug })
|
|
@@ -178,7 +185,18 @@ export const realAuth: AuthPort = {
|
|
|
178
185
|
return [...active, ...invited]
|
|
179
186
|
},
|
|
180
187
|
|
|
181
|
-
|
|
188
|
+
/**
|
|
189
|
+
* Clerk's organization invitation. `redirectUrl` sends the invitee to the app's accept page, which reads the
|
|
190
|
+
* `__clerk_ticket` and `__clerk_status` Clerk adds to the URL (./accept-invite-form.tsx); the invitation's own
|
|
191
|
+
* `url` is the link to mail, which Clerk documents as "The URL that the user can use to accept the invitation" and
|
|
192
|
+
* types as nullable. Clerk can also deliver the invitation email itself; which of the two an invitee gets is the
|
|
193
|
+
* `auth-dev` cutover row's to settle.
|
|
194
|
+
*
|
|
195
|
+
* The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
|
|
196
|
+
* absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
|
|
197
|
+
* (`localhost`), not the app's (.claude/future-tasks/request-url-is-not-the-public-url.md in SSSB's repository).
|
|
198
|
+
*/
|
|
199
|
+
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
182
200
|
const { userId } = await auth()
|
|
183
201
|
if (!userId) throw new AuthRequiredError()
|
|
184
202
|
const client = await clerkClient()
|
|
@@ -189,8 +207,16 @@ export const realAuth: AuthPort = {
|
|
|
189
207
|
inviterUserId: userId,
|
|
190
208
|
role: 'org:member',
|
|
191
209
|
publicMetadata: { role: invite.role },
|
|
210
|
+
redirectUrl: acceptPagePath(invite.acceptPageUrl),
|
|
192
211
|
})
|
|
193
|
-
return {
|
|
212
|
+
return {
|
|
213
|
+
id: created.id,
|
|
214
|
+
name: null,
|
|
215
|
+
email: created.emailAddress,
|
|
216
|
+
role: invite.role,
|
|
217
|
+
status: 'invited',
|
|
218
|
+
acceptUrl: created.url,
|
|
219
|
+
}
|
|
194
220
|
},
|
|
195
221
|
|
|
196
222
|
async listMyOrgs(): Promise<OrgRef[]> {
|