@sssb/kit 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/email-message.ts +30 -0
- package/src/adapters/fake/analytics.ts +1 -1
- package/src/adapters/fake/auth.ts +31 -4
- package/src/adapters/fake/data-dir.ts +32 -2
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/fake/email.ts +2 -0
- package/src/adapters/real/absent.ts +13 -0
- package/src/adapters/real/accept-invite-form.tsx +86 -21
- package/src/adapters/real/analytics.ts +30 -3
- package/src/adapters/real/auth.ts +82 -20
- package/src/adapters/real/contract-postgres.ts +15 -11
- package/src/adapters/real/db-port.ts +3 -2
- package/src/adapters/real/email.ts +2 -0
- package/src/adapters/real/index.ts +49 -12
- package/src/adapters/real/jobs-in-process.ts +32 -14
- package/src/adapters/real/jobs.ts +6 -3
- package/src/adapters/real/migrate-handler.ts +3 -1
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +35 -1
- package/src/adapters/real/rds-data-codec.ts +88 -4
- package/src/adapters/real/rds-data-emulator.ts +12 -4
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/sign-in-form.tsx +29 -13
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/authz/app-exemptions.ts +79 -9
- package/src/authz/route-scan.ts +626 -55
- package/src/components/auth/accept-invite-screen.tsx +5 -1
- package/src/components/auth/people-picker.tsx +20 -2
- package/src/components/profile-screen.tsx +27 -2
- package/src/core/inbound-email.ts +41 -6
- 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 +19 -9
- package/src/db/keyset.ts +19 -30
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/notifications.ts +2 -2
- package/src/db/rls-coverage.ts +51 -17
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +11 -4
- package/src/db/webhooks.ts +4 -4
- package/src/demo-static/actor-drivers.ts +8 -2
- package/src/demo-static/email-html.ts +9 -0
- package/src/demo-static/tour/use-tours.tsx +8 -2
- package/src/demo-static/world.ts +76 -37
- package/src/email/send.ts +6 -2
- package/src/guide.md +26 -7
- package/src/i18n/messages/en.json +3 -0
- package/src/i18n/messages/es.json +3 -0
- package/src/i18n/messages.ts +3 -2
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/server-lib/scheduled-tick.ts +5 -1
- package/src/server-lib/webhook-dispatch.ts +3 -0
- package/src/service-auth/mailgun.ts +19 -4
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +308 -0
- package/src/testing/conformance/authz.ts +6 -2
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/i18n.ts +99 -5
- package/src/testing/conformance/suite.ts +65 -3
- package/src/testing/contract.ts +6 -4
package/dist/release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"commit":"
|
|
1
|
+
{"commit":"1f7bc710b87ea12442ba8f1505aaf2245c58fbec"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sssb/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -90,6 +90,7 @@
|
|
|
90
90
|
"./core/notifications": "./src/core/notifications.ts",
|
|
91
91
|
"./core/presets": "./src/core/presets.ts",
|
|
92
92
|
"./core/roles": "./src/core/roles.ts",
|
|
93
|
+
"./core/same-origin-path": "./src/core/same-origin-path.ts",
|
|
93
94
|
"./core/schedules": "./src/core/schedules.ts",
|
|
94
95
|
"./core/state-machine": "./src/core/state-machine.ts",
|
|
95
96
|
"./core/webhook-events": "./src/core/webhook-events.ts",
|
|
@@ -170,6 +171,7 @@
|
|
|
170
171
|
"@aws-sdk/s3-request-presigner": "^3.1155.0",
|
|
171
172
|
"@clerk/nextjs": "^7.9.19",
|
|
172
173
|
"@electric-sql/pglite": "^0.5.11",
|
|
174
|
+
"@formatjs/icu-messageformat-parser": "^3.5.15",
|
|
173
175
|
"@mantine/form": "^9.7.3",
|
|
174
176
|
"@react-email/components": "^1.0.12",
|
|
175
177
|
"@react-email/render": "^2.1.1",
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { EmailMessage } from '../ports/email'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Refuses a message the email port must never send, before any adapter hands it on: a `to` that is not exactly one
|
|
5
|
+
* address, and a `subject` that could break a header. Mailgun's `to` takes a comma-separated list, so a `to` built from
|
|
6
|
+
* user input (`a@x.test, b@evil.test`) would otherwise mail everyone in it. Both the real adapter and the fake call this,
|
|
7
|
+
* so a test on the simulated world fails where a deployment would have sent to a list. Neither value is echoed in the
|
|
8
|
+
* error: both may be personal data, and the error may reach a log.
|
|
9
|
+
*/
|
|
10
|
+
export function assertSendableMessage(message: EmailMessage): void {
|
|
11
|
+
const { to, subject } = message
|
|
12
|
+
if (typeof to !== 'string' || /[,;\p{Cc}]/u.test(to) || (to.match(/@/g) ?? []).length !== 1 || !isOneAddress(to)) {
|
|
13
|
+
throw new Error('email: `to` must be exactly one address')
|
|
14
|
+
}
|
|
15
|
+
if (/[\r\n]/.test(subject)) throw new Error('email: `subject` must not contain a line break')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** An addr-spec with nothing a mailer could read as a display name, a comment or a second address around it. */
|
|
19
|
+
const BARE_ADDRESS = /^[^\s<>"()@]+@[^\s<>"()@]+$/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `to` is either a bare address (`ada@example.test`) or a display name and then one bracketed bare address at its very
|
|
23
|
+
* end (`Ada Lovelace <ada@example.test>`). Anything else lets the address a vendor mails differ from the one the caller
|
|
24
|
+
* recorded: in `a<b@c.d>` a mailer reads the display name `a` and mails `b@c.d`, and a trailing `(…)` is a comment.
|
|
25
|
+
*/
|
|
26
|
+
function isOneAddress(to: string): boolean {
|
|
27
|
+
if (BARE_ADDRESS.test(to)) return true
|
|
28
|
+
const named = /^([^<>"()]*[^\s<>"()])\s+<([^<>]*)>$/.exec(to)
|
|
29
|
+
return named !== null && named[1]!.trim() !== '' && BARE_ADDRESS.test(named[2]!)
|
|
30
|
+
}
|
|
@@ -64,7 +64,7 @@ export const fakeAnalytics: AnalyticsPort = {
|
|
|
64
64
|
},
|
|
65
65
|
async isFlagEnabled(flag, defaultValue = false) {
|
|
66
66
|
const flags = readFlags()
|
|
67
|
-
return flag
|
|
67
|
+
return Object.hasOwn(flags, flag) ? flags[flag]! : defaultValue
|
|
68
68
|
},
|
|
69
69
|
}
|
|
70
70
|
|
|
@@ -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,
|
|
@@ -199,8 +200,11 @@ export async function acceptInvite(
|
|
|
199
200
|
): Promise<{ id: string; tenantSlug: string }> {
|
|
200
201
|
const invite = findInvite(inviteId)
|
|
201
202
|
if (!invite) throw new ForbiddenError(`unknown invite: ${inviteId}`)
|
|
203
|
+
if (typeof profile.name !== 'string') throw new ForbiddenError('invalid name')
|
|
202
204
|
const name = profile.name.trim()
|
|
203
205
|
if (!name) throw new ForbiddenError('name is required')
|
|
206
|
+
// The same bound updateProfile keeps, so a person cannot get a name at sign-up that they could not set later.
|
|
207
|
+
if (!isProfileName(name)) throw new ForbiddenError('invalid name')
|
|
204
208
|
|
|
205
209
|
const person: SeedPerson = {
|
|
206
210
|
id: `person-invited-${inviteId.slice(0, 8)}`,
|
|
@@ -253,9 +257,17 @@ export const fakeAuth: AuthPort = {
|
|
|
253
257
|
async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
|
|
254
258
|
const session = await readSession()
|
|
255
259
|
if (!session) throw new AuthRequiredError()
|
|
256
|
-
|
|
260
|
+
// Refused as the real adapter refuses (./../real/auth.ts), before anything is stored: a name that is not a
|
|
261
|
+
// non-blank string of at most 256 characters, a locale this app does not ship. Only the two known fields are
|
|
262
|
+
// stored, so a body with anything else in it cannot reach every page that renders this person.
|
|
263
|
+
if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
|
|
264
|
+
if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
257
265
|
const overrides = readOverrides()
|
|
258
|
-
overrides[session.person.id] = {
|
|
266
|
+
overrides[session.person.id] = {
|
|
267
|
+
...overrides[session.person.id],
|
|
268
|
+
...(update.name === undefined ? {} : { name: update.name }),
|
|
269
|
+
...(update.locale === undefined ? {} : { locale: update.locale }),
|
|
270
|
+
}
|
|
259
271
|
await writeJsonAtomic(overridesFile(), overrides)
|
|
260
272
|
return toUser(session.person, session.orgSlug)
|
|
261
273
|
},
|
|
@@ -282,7 +294,7 @@ export const fakeAuth: AuthPort = {
|
|
|
282
294
|
return { role: membership.role, restricted: isRestricted(person.restricted, membership.role) }
|
|
283
295
|
},
|
|
284
296
|
|
|
285
|
-
async createInvite(invite: InviteInput): Promise<
|
|
297
|
+
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
286
298
|
if (!isRole(invite.role)) throw new ForbiddenError('unknown role')
|
|
287
299
|
const stored: StoredInvite = {
|
|
288
300
|
id: crypto.randomUUID(),
|
|
@@ -292,7 +304,17 @@ export const fakeAuth: AuthPort = {
|
|
|
292
304
|
invitedAt: new Date().toISOString(),
|
|
293
305
|
}
|
|
294
306
|
await writeJsonAtomic(invitesFile(), [...readInvites(), stored])
|
|
295
|
-
|
|
307
|
+
// The accept page finds the invitation by its id (`findInvite`).
|
|
308
|
+
const acceptUrl = new URL(invite.acceptPageUrl)
|
|
309
|
+
acceptUrl.searchParams.set('invite', stored.id)
|
|
310
|
+
return {
|
|
311
|
+
id: stored.id,
|
|
312
|
+
name: null,
|
|
313
|
+
email: stored.email,
|
|
314
|
+
role: stored.role,
|
|
315
|
+
status: 'invited',
|
|
316
|
+
acceptUrl: acceptUrl.toString(),
|
|
317
|
+
}
|
|
296
318
|
},
|
|
297
319
|
|
|
298
320
|
async listMyOrgs(): Promise<OrgRef[]> {
|
|
@@ -311,3 +333,8 @@ export const fakeAuth: AuthPort = {
|
|
|
311
333
|
updatePersonState(`person:${session.person.id}`, { activeOrgSlug: orgSlug })
|
|
312
334
|
},
|
|
313
335
|
}
|
|
336
|
+
|
|
337
|
+
/** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
|
|
338
|
+
function isProfileName(name: unknown): name is string {
|
|
339
|
+
return typeof name === 'string' && name.trim() !== '' && name.length <= 256
|
|
340
|
+
}
|
|
@@ -1,9 +1,39 @@
|
|
|
1
1
|
import { mkdirSync } from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* The directory all fake-adapter state lives under: APP_DATA_DIR, else `.data/` (gitignored), as an absolute path (a
|
|
6
|
+
* relative APP_DATA_DIR is read against the working directory). Absolute because fake storage keeps a key inside its
|
|
7
|
+
* directory by comparing resolved paths. Creates nothing.
|
|
8
|
+
*/
|
|
5
9
|
export function dataRoot(): string {
|
|
6
|
-
|
|
10
|
+
const dir = process.env['APP_DATA_DIR']
|
|
11
|
+
if (dir === undefined) return path.join(process.cwd(), '.data')
|
|
12
|
+
return absolute(dir)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `dir` as a normalised absolute path, against the working directory when it is relative. Written out by hand, because
|
|
17
|
+
* of what a build showed: with `path.resolve(<APP_DATA_DIR>)` here, and again with `path.join(process.cwd(), <it>)` or
|
|
18
|
+
* `path.normalize(<it>)`, Next's file tracer copied this whole directory's TypeScript source into the standalone
|
|
19
|
+
* server (pack and consume fails on it); with this function it copies none. Other path calls on runtime values in
|
|
20
|
+
* this directory do not trip it, so the trigger is narrower than "any path call": keep the environment value out of
|
|
21
|
+
* one. On Windows a UNC root and a drive-relative value (`D:rel`) are not supported.
|
|
22
|
+
*/
|
|
23
|
+
function absolute(dir: string): string {
|
|
24
|
+
const from = path.isAbsolute(dir) ? dir : `${process.cwd()}${path.sep}${dir}`
|
|
25
|
+
// A backslash separates only where it is the platform's separator: on POSIX it is a legal file-name character.
|
|
26
|
+
const separators = path.sep === '\\' ? /[\\/]+/ : /\/+/
|
|
27
|
+
const parts: string[] = []
|
|
28
|
+
for (const part of from.split(separators)) {
|
|
29
|
+
if (part === '.' || (part === '' && parts.length > 0)) continue
|
|
30
|
+
if (part === '..') {
|
|
31
|
+
if (parts.length > 1) parts.pop()
|
|
32
|
+
continue
|
|
33
|
+
}
|
|
34
|
+
parts.push(part)
|
|
35
|
+
}
|
|
36
|
+
return parts.length === 1 ? `${parts[0]}${path.sep}` : parts.join(path.sep)
|
|
7
37
|
}
|
|
8
38
|
|
|
9
39
|
/** A directory under the fake adapters' data root, created if missing. Tests point APP_DATA_DIR at a tmp dir. */
|
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,6 +1,7 @@
|
|
|
1
1
|
import { readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import type { EmailMessage, EmailPort } from '../../ports/email'
|
|
4
|
+
import { assertSendableMessage } from '../email-message'
|
|
4
5
|
import { writeJsonAtomic } from './atomic-write'
|
|
5
6
|
import { dataDir } from './data-dir'
|
|
6
7
|
|
|
@@ -19,6 +20,7 @@ let counter = 0
|
|
|
19
20
|
|
|
20
21
|
export const fakeEmail: EmailPort = {
|
|
21
22
|
async send(message) {
|
|
23
|
+
assertSendableMessage(message) // as the real adapter does, so a test on fakes catches a list in `to`
|
|
22
24
|
const caught: CaughtEmail = {
|
|
23
25
|
id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
|
|
24
26
|
at: new Date().toISOString(),
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { EmailPort } from '../../ports/email'
|
|
2
2
|
import type { JobsPort } from '../../ports/jobs'
|
|
3
3
|
import type { LlmPort } from '../../ports/llm'
|
|
4
|
+
import type { StoragePort } from '../../ports/storage'
|
|
4
5
|
import { OPTIONAL_PORTS, type OptionalPort } from './optional-ports'
|
|
5
6
|
|
|
6
7
|
/**
|
|
@@ -39,3 +40,15 @@ export const absentEmail: EmailPort = {
|
|
|
39
40
|
export const absentJobs: JobsPort = {
|
|
40
41
|
start: async () => absent('jobs'),
|
|
41
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,74 +1,139 @@
|
|
|
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
|
+
|
|
7
|
+
import { sameOriginPath } from '../../core/same-origin-path'
|
|
6
8
|
|
|
7
9
|
/**
|
|
8
|
-
* Clerk ticket-strategy
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* Clerk ticket-strategy acceptance (ADR-0003): the invitation mail carries Clerk's invitation URL (./auth.ts
|
|
11
|
+
* `createInvite`), and Clerk sends the invitee on to this page with `__clerk_ticket` and `__clerk_status` query
|
|
12
|
+
* params, where the fake's link carries `?invite=<id>`. Clerk's guide to accepting organization invitations: a status
|
|
13
|
+
* of `sign_in` means the invitee already has an account, and takes a ticket sign-in; `sign_up` (or none), a ticket
|
|
14
|
+
* sign-up; `complete`, that Clerk accepted it already, so the form only redirects; any other is shown as the error.
|
|
15
|
+
* sign-in-form.tsx is the reference for the v7 signals API (signIn.password() → status → finalize()); here it is
|
|
16
|
+
* signIn.ticket() or signUp.ticket() → status → finalize(), per @clerk/shared's SignInFutureResource and
|
|
17
|
+
* SignUpFutureResource.
|
|
13
18
|
*
|
|
14
19
|
* AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance. Verify the full
|
|
15
20
|
* ticket round-trip once a dev Clerk instance issues real invitation tickets (see
|
|
16
21
|
* docs/cutover-checklist.md, `auth-dev` row).
|
|
17
22
|
*
|
|
23
|
+
* `redirectTo` is followed only when `sameOriginPath` accepts it, and `/` otherwise, as RealSignInForm does with its
|
|
24
|
+
* `returnTo`: the form trusts no caller to have checked it.
|
|
25
|
+
*
|
|
18
26
|
* Lives in packages/kit/src/adapters because it imports the vendor SDK; the AcceptInviteShell renders it as a
|
|
19
27
|
* slot, and all copy arrives via `labels` from the page's next-intl lookup (same contract as
|
|
20
28
|
* RealSignInForm — one auth UI, no vendor-side strings).
|
|
21
29
|
*/
|
|
22
30
|
export function RealAcceptInviteForm({
|
|
23
31
|
ticket,
|
|
32
|
+
status = null,
|
|
24
33
|
redirectTo,
|
|
25
34
|
labels,
|
|
26
35
|
}: {
|
|
27
36
|
ticket: string | null
|
|
37
|
+
/**
|
|
38
|
+
* Clerk's `__clerk_status` from the page's URL: `sign_in` for an invitee who already has an account, `sign_up` for
|
|
39
|
+
* one who has none, `complete` when Clerk accepted the invitation itself (the invitee was already signed in).
|
|
40
|
+
*/
|
|
41
|
+
status?: string | null
|
|
28
42
|
redirectTo: string
|
|
29
43
|
labels: AcceptInviteTicketLabels
|
|
30
44
|
}) {
|
|
31
|
-
const {
|
|
45
|
+
const { isLoaded } = useAuth()
|
|
46
|
+
const { signUp, fetchStatus: signUpFetch } = useSignUp()
|
|
47
|
+
const { signIn, fetchStatus: signInFetch } = useSignIn()
|
|
32
48
|
const [error, setError] = useState<string | null>(null)
|
|
33
49
|
const [accepted, setAccepted] = useState(false)
|
|
50
|
+
const plan = planFor(status)
|
|
51
|
+
const fetchStatus = plan === 'sign-in' ? signInFetch : signUpFetch
|
|
52
|
+
|
|
53
|
+
// A ticket is single-use, so it is submitted once. The resources change identity as Clerk loads, so the effect
|
|
54
|
+
// reads the current ones through a ref rather than depending on them (a dependency would run it again), starts
|
|
55
|
+
// only once Clerk has loaded, and remembers what it started.
|
|
56
|
+
const flows = useRef({ signIn, signUp })
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
flows.current = { signIn, signUp }
|
|
59
|
+
})
|
|
60
|
+
const started = useRef<string | null>(null)
|
|
34
61
|
|
|
35
62
|
useEffect(() => {
|
|
36
|
-
if (!ticket) return
|
|
37
|
-
|
|
63
|
+
if (!isLoaded || (plan !== 'accepted' && !ticket)) return
|
|
64
|
+
const key = `${plan}:${ticket ?? ''}`
|
|
65
|
+
if (started.current === key) return
|
|
66
|
+
started.current = key
|
|
67
|
+
// Driving an external SDK call on mount (Clerk's ticket strategy) is the
|
|
38
68
|
// legitimate "sync with an external system" case the set-state-in-effect rule guards —
|
|
39
69
|
// same as the Simulator glue's fetch-on-mount effects.
|
|
40
70
|
void (async () => {
|
|
41
|
-
|
|
42
|
-
|
|
71
|
+
if (plan === 'accepted') {
|
|
72
|
+
setAccepted(true)
|
|
73
|
+
window.location.assign(sameOriginPath(redirectTo) ?? '/')
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
if (plan === 'unknown' || !ticket) {
|
|
43
77
|
setError(labels.genericError)
|
|
44
78
|
return
|
|
45
79
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
80
|
+
const { signIn: currentSignIn, signUp: currentSignUp } = flows.current
|
|
81
|
+
const flow = plan === 'sign-in' ? currentSignIn : currentSignUp
|
|
82
|
+
setError(null) // a retry after a thrown call starts with no error on screen
|
|
83
|
+
try {
|
|
84
|
+
const { error: ticketError } =
|
|
85
|
+
plan === 'sign-in' ? await currentSignIn.ticket({ ticket }) : await currentSignUp.ticket({ ticket })
|
|
86
|
+
if (ticketError) {
|
|
49
87
|
setError(labels.genericError)
|
|
50
88
|
return
|
|
51
89
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
90
|
+
if (flow.status === 'complete') {
|
|
91
|
+
const finalized = await flow.finalize()
|
|
92
|
+
if (finalized.error) {
|
|
93
|
+
setError(labels.genericError)
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
setAccepted(true)
|
|
97
|
+
window.location.assign(sameOriginPath(redirectTo) ?? '/')
|
|
98
|
+
} else {
|
|
99
|
+
setError(labels.genericError)
|
|
100
|
+
}
|
|
101
|
+
} catch {
|
|
102
|
+
// A call that THREW (the network) is not Clerk refusing the ticket: show the error, and forget that this
|
|
103
|
+
// ticket was started, so the effect's next run (Clerk reloading, the page remounting) submits it again.
|
|
104
|
+
// A refusal above is not retried: Clerk has answered, and a ticket is single-use.
|
|
105
|
+
started.current = null
|
|
55
106
|
setError(labels.genericError)
|
|
56
107
|
}
|
|
57
108
|
})()
|
|
58
|
-
}, [
|
|
109
|
+
}, [isLoaded, plan, ticket, redirectTo, labels.genericError])
|
|
59
110
|
|
|
60
|
-
if (!ticket) return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
111
|
+
if (!ticket && plan !== 'accepted') return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
61
112
|
|
|
62
113
|
return (
|
|
63
114
|
<Stack gap="sm">
|
|
64
115
|
{!accepted && !error ? (
|
|
65
116
|
<Text c="gray.7">{fetchStatus === 'fetching' ? labels.accepting : labels.oneMoment}</Text>
|
|
66
117
|
) : null}
|
|
67
|
-
{error ?
|
|
118
|
+
{error ? (
|
|
119
|
+
<Text c="red.8" role="alert">
|
|
120
|
+
{error}
|
|
121
|
+
</Text>
|
|
122
|
+
) : null}
|
|
68
123
|
</Stack>
|
|
69
124
|
)
|
|
70
125
|
}
|
|
71
126
|
|
|
127
|
+
type Plan = 'sign-in' | 'sign-up' | 'accepted' | 'unknown'
|
|
128
|
+
|
|
129
|
+
/** What Clerk's `__clerk_status` asks of the form. A missing status is a sign-up, as before the status was read. */
|
|
130
|
+
function planFor(status: string | null): Plan {
|
|
131
|
+
if (status === 'complete') return 'accepted'
|
|
132
|
+
if (status === 'sign_in') return 'sign-in'
|
|
133
|
+
if (status === null || status === 'sign_up') return 'sign-up'
|
|
134
|
+
return 'unknown'
|
|
135
|
+
}
|
|
136
|
+
|
|
72
137
|
export interface AcceptInviteTicketLabels {
|
|
73
138
|
missingTicket: string
|
|
74
139
|
accepting: string
|
|
@@ -1,16 +1,43 @@
|
|
|
1
1
|
import { PostHog } from 'posthog-node'
|
|
2
2
|
import type { AnalyticsPort } from '../../ports/analytics'
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* How long `capture` waits for PostHog before it gives up on the event. The server is a Lambda, frozen once its
|
|
6
|
+
* response is sent, so an event still in the client's queue then may never leave: `capture` therefore sends each event
|
|
7
|
+
* itself and waits for it, but never longer than this, so a PostHog outage costs a response at most this much.
|
|
8
|
+
*/
|
|
9
|
+
export const CAPTURE_TIMEOUT_MS = 2_000
|
|
10
|
+
|
|
4
11
|
/**
|
|
5
12
|
* AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
|
|
6
|
-
* staging/prod only (ADR-0010)
|
|
13
|
+
* staging/prod only (ADR-0010): a real deployment without a key gets the no-op (./no-analytics.ts).
|
|
7
14
|
*/
|
|
8
15
|
export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
|
|
9
|
-
const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
|
|
16
|
+
const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000, requestTimeout: CAPTURE_TIMEOUT_MS })
|
|
10
17
|
|
|
11
18
|
return {
|
|
19
|
+
// An event is never load-bearing either: a send that fails or outruns CAPTURE_TIMEOUT_MS is logged and dropped.
|
|
12
20
|
async capture(event, properties, distinctId = 'server') {
|
|
13
|
-
|
|
21
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
22
|
+
const timedOut = new Promise<'timed out'>((resolve) => {
|
|
23
|
+
timer = setTimeout(() => resolve('timed out'), CAPTURE_TIMEOUT_MS)
|
|
24
|
+
})
|
|
25
|
+
try {
|
|
26
|
+
const sent = client.captureImmediate({
|
|
27
|
+
distinctId,
|
|
28
|
+
event,
|
|
29
|
+
...(properties === undefined ? {} : { properties }),
|
|
30
|
+
})
|
|
31
|
+
if ((await Promise.race([sent.then(() => 'sent' as const), timedOut])) === 'timed out') {
|
|
32
|
+
console.warn(`SSSB analytics: dropped event ${event}: PostHog did not answer in time`)
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
console.warn(
|
|
36
|
+
`SSSB analytics: dropped event ${event}: ${error instanceof Error ? error.message : String(error)}`,
|
|
37
|
+
)
|
|
38
|
+
} finally {
|
|
39
|
+
clearTimeout(timer)
|
|
40
|
+
}
|
|
14
41
|
},
|
|
15
42
|
|
|
16
43
|
async isFlagEnabled(flag, defaultValue = false) {
|
|
@@ -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,
|
|
@@ -33,9 +34,49 @@ interface AppPublicMetadata {
|
|
|
33
34
|
tenantSlug?: string
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The role a membership or invitation records, or `guest` when it records none (or one this app does not know): the
|
|
39
|
+
* least privilege, and the same answer everywhere, so the switcher and the member list never show a role the session
|
|
40
|
+
* does not have.
|
|
41
|
+
*/
|
|
42
|
+
function roleFrom(metadata: unknown): Role {
|
|
37
43
|
const role = (metadata as AppPublicMetadata)?.role
|
|
38
|
-
return role && isRole(role) ? role :
|
|
44
|
+
return role && isRole(role) ? role : 'guest'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The accept page as a path (with any query), for Clerk to resolve against the instance's own domain. */
|
|
48
|
+
function acceptPagePath(acceptPageUrl: string): string {
|
|
49
|
+
const url = new URL(acceptPageUrl)
|
|
50
|
+
return `${url.pathname}${url.search}`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Clerk's list calls answer a page at a time; this is the page size the adapter asks for. */
|
|
54
|
+
const PAGE_SIZE = 100
|
|
55
|
+
|
|
56
|
+
/** The most pages `allPages` reads before it gives up: 100,000 rows at PAGE_SIZE, far past any team or person. */
|
|
57
|
+
const MAX_PAGES = 1_000
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Every row of a Clerk list, read a page at a time. A list read as one page would silently drop whoever is past it: a
|
|
61
|
+
* team's 101st member from its notifications, or a person's 101st org from their switcher. It stops on an empty page
|
|
62
|
+
* or once it holds `totalCount` rows, never on a page shorter than asked for, since a server may serve fewer rows per
|
|
63
|
+
* page than the limit; and it throws rather than loop without end on a list that never reaches its count.
|
|
64
|
+
*/
|
|
65
|
+
async function allPages<T>(
|
|
66
|
+
page: (params: { limit: number; offset: number }) => Promise<{ data: T[]; totalCount: number }>,
|
|
67
|
+
): Promise<T[]> {
|
|
68
|
+
const rows: T[] = []
|
|
69
|
+
for (let read = 0; read < MAX_PAGES; read += 1) {
|
|
70
|
+
const { data, totalCount } = await page({ limit: PAGE_SIZE, offset: rows.length })
|
|
71
|
+
rows.push(...data)
|
|
72
|
+
if (data.length === 0 || rows.length >= totalCount) return rows
|
|
73
|
+
}
|
|
74
|
+
throw new Error(`a Clerk list ran past ${MAX_PAGES} pages without reaching its count`)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
|
|
78
|
+
function isProfileName(name: unknown): name is string {
|
|
79
|
+
return typeof name === 'string' && name.trim() !== '' && name.length <= 256
|
|
39
80
|
}
|
|
40
81
|
|
|
41
82
|
async function organizationIdForSlug(slug: string): Promise<string> {
|
|
@@ -56,13 +97,12 @@ export const realAuth: AuthPort = {
|
|
|
56
97
|
// Resolve the active org membership: the remembered currentOrgSlug if still a membership,
|
|
57
98
|
// else the first one. Role comes from that membership (per-org), not the user object.
|
|
58
99
|
const client = await clerkClient()
|
|
59
|
-
const memberships = await client.users.getOrganizationMembershipList({ userId,
|
|
100
|
+
const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
|
|
60
101
|
const currentOrgSlug = (user.unsafeMetadata as { currentOrgSlug?: string })?.currentOrgSlug
|
|
61
102
|
const active =
|
|
62
|
-
memberships.
|
|
63
|
-
memberships.data[0]
|
|
103
|
+
memberships.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ?? memberships[0]
|
|
64
104
|
|
|
65
|
-
const role = roleFrom(active?.publicMetadata
|
|
105
|
+
const role = roleFrom(active?.publicMetadata)
|
|
66
106
|
return {
|
|
67
107
|
id: userId,
|
|
68
108
|
name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
|
|
@@ -103,14 +143,15 @@ export const realAuth: AuthPort = {
|
|
|
103
143
|
async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
|
|
104
144
|
const { userId } = await auth()
|
|
105
145
|
if (!userId) throw new AuthRequiredError()
|
|
146
|
+
// Same guards the fake adapter enforces, and as early: before any write, so a refused update changes nothing.
|
|
147
|
+
if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
|
|
148
|
+
if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
106
149
|
const client = await clerkClient()
|
|
107
150
|
if (update.name !== undefined) {
|
|
108
151
|
const [firstName = '', ...rest] = update.name.split(' ')
|
|
109
152
|
await client.users.updateUser(userId, { firstName, lastName: rest.join(' ') })
|
|
110
153
|
}
|
|
111
154
|
if (update.locale !== undefined) {
|
|
112
|
-
// Same guard the fake adapter enforces — the two adapters must reject alike.
|
|
113
|
-
if (!LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
114
155
|
await client.users.updateUserMetadata(userId, { publicMetadata: { locale: update.locale } })
|
|
115
156
|
}
|
|
116
157
|
const user = await this.getCurrentUser()
|
|
@@ -144,7 +185,7 @@ export const realAuth: AuthPort = {
|
|
|
144
185
|
// as "no standing" would hand an attacker a way to kill a victim's tokens.
|
|
145
186
|
if (user.banned) return null
|
|
146
187
|
const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
|
|
147
|
-
const role = roleFrom(membership.publicMetadata
|
|
188
|
+
const role = roleFrom(membership.publicMetadata)
|
|
148
189
|
return { role, restricted: isRestricted(metadata.restricted, role) }
|
|
149
190
|
},
|
|
150
191
|
|
|
@@ -152,10 +193,12 @@ export const realAuth: AuthPort = {
|
|
|
152
193
|
const client = await clerkClient()
|
|
153
194
|
const organizationId = await organizationIdForSlug(orgSlug)
|
|
154
195
|
const [members, invitations] = await Promise.all([
|
|
155
|
-
client.organizations.getOrganizationMembershipList({ organizationId,
|
|
156
|
-
|
|
196
|
+
allPages((page) => client.organizations.getOrganizationMembershipList({ organizationId, ...page })),
|
|
197
|
+
allPages((page) =>
|
|
198
|
+
client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], ...page }),
|
|
199
|
+
),
|
|
157
200
|
])
|
|
158
|
-
const active: Membership[] = members.
|
|
201
|
+
const active: Membership[] = members.map((m) => {
|
|
159
202
|
const data = m.publicUserData
|
|
160
203
|
return {
|
|
161
204
|
// The USER id, never the membership resource id: Membership.id must share
|
|
@@ -164,21 +207,32 @@ export const realAuth: AuthPort = {
|
|
|
164
207
|
id: data?.userId ?? m.id,
|
|
165
208
|
name: data ? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim() || null : null,
|
|
166
209
|
email: data?.identifier ?? '',
|
|
167
|
-
role: roleFrom(m.publicMetadata
|
|
210
|
+
role: roleFrom(m.publicMetadata),
|
|
168
211
|
status: 'active' as const,
|
|
169
212
|
}
|
|
170
213
|
})
|
|
171
|
-
const invited: Membership[] = invitations.
|
|
214
|
+
const invited: Membership[] = invitations.map((i) => ({
|
|
172
215
|
id: i.id,
|
|
173
216
|
name: null,
|
|
174
217
|
email: i.emailAddress,
|
|
175
|
-
role: roleFrom(i.publicMetadata
|
|
218
|
+
role: roleFrom(i.publicMetadata),
|
|
176
219
|
status: 'invited' as const,
|
|
177
220
|
}))
|
|
178
221
|
return [...active, ...invited]
|
|
179
222
|
},
|
|
180
223
|
|
|
181
|
-
|
|
224
|
+
/**
|
|
225
|
+
* Clerk's organization invitation. `redirectUrl` sends the invitee to the app's accept page, which reads the
|
|
226
|
+
* `__clerk_ticket` and `__clerk_status` Clerk adds to the URL (./accept-invite-form.tsx); the invitation's own
|
|
227
|
+
* `url` is the link to mail, which Clerk documents as "The URL that the user can use to accept the invitation" and
|
|
228
|
+
* types as nullable. Clerk can also deliver the invitation email itself; which of the two an invitee gets is the
|
|
229
|
+
* `auth-dev` cutover row's to settle.
|
|
230
|
+
*
|
|
231
|
+
* The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
|
|
232
|
+
* absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
|
|
233
|
+
* (`localhost`), not the app's (.claude/future-tasks/request-url-is-not-the-public-url.md in SSSB's repository).
|
|
234
|
+
*/
|
|
235
|
+
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
182
236
|
const { userId } = await auth()
|
|
183
237
|
if (!userId) throw new AuthRequiredError()
|
|
184
238
|
const client = await clerkClient()
|
|
@@ -189,19 +243,27 @@ export const realAuth: AuthPort = {
|
|
|
189
243
|
inviterUserId: userId,
|
|
190
244
|
role: 'org:member',
|
|
191
245
|
publicMetadata: { role: invite.role },
|
|
246
|
+
redirectUrl: acceptPagePath(invite.acceptPageUrl),
|
|
192
247
|
})
|
|
193
|
-
return {
|
|
248
|
+
return {
|
|
249
|
+
id: created.id,
|
|
250
|
+
name: null,
|
|
251
|
+
email: created.emailAddress,
|
|
252
|
+
role: invite.role,
|
|
253
|
+
status: 'invited',
|
|
254
|
+
acceptUrl: created.url,
|
|
255
|
+
}
|
|
194
256
|
},
|
|
195
257
|
|
|
196
258
|
async listMyOrgs(): Promise<OrgRef[]> {
|
|
197
259
|
const { userId } = await auth()
|
|
198
260
|
if (!userId) return []
|
|
199
261
|
const client = await clerkClient()
|
|
200
|
-
const memberships = await client.users.getOrganizationMembershipList({ userId,
|
|
201
|
-
return memberships.
|
|
262
|
+
const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
|
|
263
|
+
return memberships.map((m) => ({
|
|
202
264
|
slug: m.organization.slug ?? m.organization.id,
|
|
203
265
|
name: m.organization.name,
|
|
204
|
-
role: roleFrom(m.publicMetadata
|
|
266
|
+
role: roleFrom(m.publicMetadata),
|
|
205
267
|
}))
|
|
206
268
|
},
|
|
207
269
|
|