@sssb/kit 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/auth-tenancy.ts +157 -0
  4. package/src/adapters/configured-auth.ts +203 -0
  5. package/src/adapters/fake/atomic-write.ts +1 -1
  6. package/src/adapters/fake/auth.ts +35 -1
  7. package/src/adapters/fake/jobs.ts +5 -4
  8. package/src/adapters/fake/simulated-auth.ts +30 -0
  9. package/src/adapters/index.ts +3 -2
  10. package/src/adapters/real/account-refused-form.tsx +32 -0
  11. package/src/adapters/real/auth.ts +76 -7
  12. package/src/adapters/real/index.ts +23 -3
  13. package/src/adapters/real/rds-data-dialect.ts +118 -1
  14. package/src/adapters/real/rds-data-emulator.ts +35 -1
  15. package/src/authz/authorize.ts +4 -1
  16. package/src/components/auth/account-refused.tsx +53 -0
  17. package/src/core/abilities.ts +22 -6
  18. package/src/core/jobs.ts +17 -0
  19. package/src/core/roles.ts +17 -2
  20. package/src/cutover/rows.json +4 -0
  21. package/src/db/family.ts +1 -1
  22. package/src/db/jobs.ts +17 -5
  23. package/src/db/migrations/0017_job_requester.ts +20 -0
  24. package/src/db/migrations/index.ts +2 -0
  25. package/src/db/org-lookup.ts +18 -0
  26. package/src/db/schema.ts +2 -0
  27. package/src/demo-static/contracts.ts +9 -0
  28. package/src/demo-static/rows.ts +2 -0
  29. package/src/demo-static/world.ts +22 -4
  30. package/src/guide.md +26 -0
  31. package/src/i18n/messages/en.json +5 -1
  32. package/src/i18n/messages/es.json +5 -1
  33. package/src/ports/auth.ts +26 -1
  34. package/src/server-lib/notify.ts +51 -9
  35. package/src/testing/conformance/auth-provider.ts +1 -0
  36. package/src/testing/conformance/demo-presets.ts +4 -4
package/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"1f7bc710b87ea12442ba8f1505aaf2245c58fbec"}
1
+ {"commit":"993193893bda13fc98aaaeba0ad004092482c039"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -37,6 +37,7 @@
37
37
  "./adapters/index": "./src/adapters/index.ts",
38
38
  "./adapters/proxy": "./src/adapters/proxy.ts",
39
39
  "./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
40
+ "./adapters/real/account-refused-form": "./src/adapters/real/account-refused-form.tsx",
40
41
  "./adapters/real/index": "./src/adapters/real/index.ts",
41
42
  "./adapters/real/llm": "./src/adapters/real/llm.ts",
42
43
  "./adapters/real/migrate-handler": "./src/adapters/real/migrate-handler.ts",
@@ -51,6 +52,7 @@
51
52
  "./components/agreements/agreement-gate": "./src/components/agreements/agreement-gate.tsx",
52
53
  "./components/app-header": "./src/components/app-header.tsx",
53
54
  "./components/auth/accept-invite-screen": "./src/components/auth/accept-invite-screen.tsx",
55
+ "./components/auth/account-refused": "./src/components/auth/account-refused.tsx",
54
56
  "./components/auth/org-switcher": "./src/components/auth/org-switcher.tsx",
55
57
  "./components/auth/people-picker": "./src/components/auth/people-picker.tsx",
56
58
  "./components/auth/sign-in-screen": "./src/components/auth/sign-in-screen.tsx",
@@ -0,0 +1,157 @@
1
+ /**
2
+ * How the auth adapters place a signed-in person: the deployment's two choices, read here from the environment, which
3
+ * `SssbApp` sets from the app's `params.auth` (an app's own infra sets it itself). Both adapters read them, the fake as
4
+ * well as Clerk, so a simulated world runs the same placement as the deployment when its environment says so. Each
5
+ * answers its own question, and one pairing is refused (below).
6
+ *
7
+ * **Where the tenant comes from, `AUTH_TENANCY`:**
8
+ * - `multi` (the default, what every deployment did before the switch existed): the tenant is the user's own claim, in
9
+ * their identity provider's public metadata under `AUTH_TENANT_METADATA_KEY` (default `tenantSlug`).
10
+ * - `single`: `AUTH_TENANT_SLUG` fixes it. No tenant metadata is needed. A user whose metadata names a DIFFERENT tenant
11
+ * under the key, or holds there something that is not a slug, is refused, so a multi-tenant instance switched to this
12
+ * mode by mistake cannot pour every tenant's users into one. Nothing else changes: the person's organizations, roles,
13
+ * invitations and notifications are whatever the org source says.
14
+ *
15
+ * **Where organizations and roles come from, `AUTH_ORG_SOURCE`:**
16
+ * - `provider` (the default, ADR-0003): the identity provider's organizations, and the role on each membership.
17
+ * - `fixed`: for an app that uses the identity provider without its organizations. Every person it signs in is placed
18
+ * in one org, `AUTH_HOME_ORG_SLUG`, with one role, `AUTH_DEFAULT_ROLE`: `none` (the default), which grants nothing a
19
+ * membership would (../core/roles.ts `hasStanding`), or `restricted`, which reads what a restricted member reads and
20
+ * writes nothing org-scoped through SSSB's rules. No role that writes is offered: on an identity-provider instance
21
+ * shared with another product, everyone that product signs in gets it. The app's own rules grant the rest.
22
+ *
23
+ * One pairing is refused: a fixed org source needs a single tenancy. It reads nothing from the provider about orgs or
24
+ * roles, so with a multi tenancy the tenant claim in the provider's metadata would be the only thing deciding whose
25
+ * data a person reaches, and a credential (`getMember`) could not be checked against the tenant its org belongs to.
26
+ * On an instance shared with another product, that product's operator writes that metadata.
27
+ *
28
+ * Each is an explicit switch, never inferred from which settings happen to be set, so a deployment that
29
+ * half-configures one fails at boot instead of quietly changing who sees what.
30
+ */
31
+
32
+ export const AUTH_TENANCY_CHOICES = ['multi', 'single'] as const
33
+ export const AUTH_ORG_SOURCE_CHOICES = ['provider', 'fixed'] as const
34
+ /** The roles a fixed org source may give everyone, lowest first: neither writes anything org-scoped in SSSB's rules. */
35
+ export const FIXED_ORG_ROLES = ['none', 'restricted'] as const
36
+ export type FixedOrgRole = (typeof FIXED_ORG_ROLES)[number]
37
+
38
+ export type AuthTenancy = { kind: 'multi' } | { kind: 'single'; tenantSlug: string }
39
+ export type AuthOrgSource = { kind: 'provider' } | { kind: 'fixed'; homeOrgSlug: string; role: FixedOrgRole }
40
+
41
+ export interface AuthSettings {
42
+ tenancy: AuthTenancy
43
+ orgSource: AuthOrgSource
44
+ /** The public-metadata key holding a user's tenant claim: read in multi tenancy, checked in single. */
45
+ tenantMetadataKey: string
46
+ }
47
+
48
+ const DEFAULT_TENANT_METADATA_KEY = 'tenantSlug'
49
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
50
+ const METADATA_KEY = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_][A-Za-z0-9_]*$/
51
+
52
+ type Env = Readonly<Record<string, string | undefined>>
53
+
54
+ /** Every setting either choice reads, each mapped to its cutover row. */
55
+ const SINGLE_TENANCY_ENV: Readonly<Record<string, string>> = { AUTH_TENANT_SLUG: 'auth-tenancy' }
56
+ const FIXED_ORG_ENV: Readonly<Record<string, string>> = { AUTH_HOME_ORG_SLUG: 'auth-tenancy' }
57
+ /** Optional in a fixed org source (it defaults to `none`), so required nowhere, and refused elsewhere. */
58
+ const FIXED_ORG_OPTIONAL = ['AUTH_DEFAULT_ROLE']
59
+
60
+ function choice<T extends string>(env: Env, name: string, choices: readonly T[]): T {
61
+ const value = env[name] || choices[0]
62
+ if (!(choices as readonly string[]).includes(value as string)) {
63
+ throw new Error(`${name} must be one of ${choices.join(', ')} (got "${value}")`)
64
+ }
65
+ return value as T
66
+ }
67
+
68
+ function strays(env: Env, names: readonly string[], setting: string, needs: string): void {
69
+ const set = names.filter((name) => env[name])
70
+ if (set.length > 0) {
71
+ throw new Error(
72
+ `${set.join(' and ')} ${set.length > 1 ? 'are' : 'is'} set but ${setting}: set ${needs} to use ` +
73
+ `${set.length > 1 ? 'them' : 'it'}, or remove ${set.length > 1 ? 'them' : 'it'}`,
74
+ )
75
+ }
76
+ }
77
+
78
+ function slug(env: Env, name: string, needer: string): string {
79
+ const value = env[name] ?? ''
80
+ if (!SLUG.test(value)) throw new Error(`${needer} needs ${name}, a slug (got "${value}")`)
81
+ return value
82
+ }
83
+
84
+ /**
85
+ * The deployment's auth settings, from `env` (the process's own by default). Throws on an unknown choice, a malformed
86
+ * slug, key or role, or a setting its choice does not use; a missing setting a choice needs is the boot check's to
87
+ * report (`assertRealEnv`), and throws here only when the settings are read without it.
88
+ */
89
+ export function authSettings(env: Env = process.env): AuthSettings {
90
+ const tenancyKind = choice(env, 'AUTH_TENANCY', AUTH_TENANCY_CHOICES)
91
+ const orgSourceKind = choice(env, 'AUTH_ORG_SOURCE', AUTH_ORG_SOURCE_CHOICES)
92
+ const tenantMetadataKey = env['AUTH_TENANT_METADATA_KEY'] || DEFAULT_TENANT_METADATA_KEY
93
+ if (!METADATA_KEY.test(tenantMetadataKey)) {
94
+ throw new Error(`AUTH_TENANT_METADATA_KEY must be a plain identifier (got "${tenantMetadataKey}")`)
95
+ }
96
+
97
+ let tenancy: AuthTenancy
98
+ if (tenancyKind === 'multi') {
99
+ strays(env, Object.keys(SINGLE_TENANCY_ENV), 'AUTH_TENANCY is multi', 'AUTH_TENANCY=single')
100
+ tenancy = { kind: 'multi' }
101
+ } else {
102
+ tenancy = { kind: 'single', tenantSlug: slug(env, 'AUTH_TENANT_SLUG', 'AUTH_TENANCY=single') }
103
+ }
104
+
105
+ let orgSource: AuthOrgSource
106
+ if (orgSourceKind === 'provider') {
107
+ strays(
108
+ env,
109
+ [...Object.keys(FIXED_ORG_ENV), ...FIXED_ORG_OPTIONAL],
110
+ 'AUTH_ORG_SOURCE is provider',
111
+ 'AUTH_ORG_SOURCE=fixed',
112
+ )
113
+ orgSource = { kind: 'provider' }
114
+ } else {
115
+ const homeOrgSlug = slug(env, 'AUTH_HOME_ORG_SLUG', 'AUTH_ORG_SOURCE=fixed')
116
+ const role = env['AUTH_DEFAULT_ROLE'] || FIXED_ORG_ROLES[0]
117
+ if (!(FIXED_ORG_ROLES as readonly string[]).includes(role)) {
118
+ throw new Error(
119
+ `AUTH_DEFAULT_ROLE must be one of ${FIXED_ORG_ROLES.join(', ')} (got "${role}"): everyone the ` +
120
+ 'identity provider signs in gets it, so no role that writes is offered',
121
+ )
122
+ }
123
+ orgSource = { kind: 'fixed', homeOrgSlug, role: role as FixedOrgRole }
124
+ if (tenancy.kind === 'multi') {
125
+ throw new Error(
126
+ 'AUTH_ORG_SOURCE=fixed needs AUTH_TENANCY=single: with a multi tenancy the tenant claim in the identity ' +
127
+ "provider's metadata would be all that places a person",
128
+ )
129
+ }
130
+ }
131
+ return { tenancy, orgSource, tenantMetadataKey }
132
+ }
133
+
134
+ /**
135
+ * The settings the deployment's choices require, each mapped to its cutover row: a single tenancy's tenant slug, a
136
+ * fixed org source's home org slug, or none.
137
+ */
138
+ export function authRequiredEnv(env: Env = process.env): Record<string, string> {
139
+ return {
140
+ ...((env['AUTH_TENANCY'] || 'multi') === 'single' ? SINGLE_TENANCY_ENV : {}),
141
+ ...((env['AUTH_ORG_SOURCE'] || 'provider') === 'fixed' ? FIXED_ORG_ENV : {}),
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Why a fixed org source cannot run with this app's staff org, or null. The staff org's members wield manage-all
147
+ * (../core/abilities.ts), and every role a fixed org source offers but `none` has standing, so placing everyone the
148
+ * identity provider signs in in the staff org with one would hand them all manage-all. Checked where the auth port is
149
+ * built, with the seam's `staffOrgSlug`, since only the app knows it (`SssbApp` cannot, at synth).
150
+ */
151
+ export function fixedOrgProblem(orgSource: AuthOrgSource, staffOrgSlug: string): string | null {
152
+ if (orgSource.kind !== 'fixed' || orgSource.role === 'none' || orgSource.homeOrgSlug !== staffOrgSlug) return null
153
+ return (
154
+ `AUTH_HOME_ORG_SLUG is the staff org ("${staffOrgSlug}") and AUTH_DEFAULT_ROLE is "${orgSource.role}": ` +
155
+ 'everyone the identity provider signs in would wield manage-all. Use another home org, or the role none'
156
+ )
157
+ }
@@ -0,0 +1,203 @@
1
+ import { isRestricted } from '../core/roles'
2
+ import type { Locale } from '../core/locale'
3
+ import type { AuthPort, AuthRefusal, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
4
+ import { AuthRequiredError, ForbiddenError } from '../ports/errors'
5
+ import { type AuthSettings, fixedOrgProblem } from './auth-tenancy'
6
+
7
+ /** A signed-in person as the identity provider knows them: who they are, and any tenant they claim. */
8
+ export interface ProviderIdentity {
9
+ id: string
10
+ name: string
11
+ email: string
12
+ locale: Locale
13
+ /**
14
+ * The account's tenant claim under the metadata key: the slug it names, `undefined` when it names none (the key is
15
+ * absent, null or empty), or `null` when it holds something that is not a slug at all, which single tenancy
16
+ * refuses.
17
+ */
18
+ tenantClaim: string | null | undefined
19
+ }
20
+
21
+ /** Another account, as `getMember` needs it: its tenant claim, and how to reach it. */
22
+ export type ProviderAccount = Pick<ProviderIdentity, 'tenantClaim' | 'email'> & { name: string | null }
23
+
24
+ /** What the auth settings need from an adapter beyond its port: the provider's facts, with no org or role in them. */
25
+ export interface ProviderIdentitySource {
26
+ /** The person signed in on this request, or null. */
27
+ current(): Promise<ProviderIdentity | null>
28
+ /**
29
+ * Another account by id: null when the provider has none, or would not let it act (a banned account). For a
30
+ * person who arrived without a session (an API token, an inbound email), so they are judged as now.
31
+ */
32
+ account(userId: string): Promise<ProviderAccount | null>
33
+ }
34
+
35
+ /**
36
+ * The auth port as the deployment's settings place people (./auth-tenancy.ts), over either adapter, the fake or Clerk,
37
+ * so the settings mean the same in a simulated world as in a deployment. On the defaults (multi tenancy, the provider's
38
+ * organizations) it is the adapter itself, untouched.
39
+ *
40
+ * **Single tenancy changes where the tenant comes from, and nothing else.** The person's tenant is the configured one,
41
+ * and a person whose account names a different tenant under the metadata key, or holds there something that is not a
42
+ * slug, is no user at all, and has no standing anywhere as a credential (`getMember`): that is a multi-tenant instance
43
+ * switched to this mode by mistake, and admitting them would put another tenant's people in this one. Refused without
44
+ * signing out: this runs while server components render, where a session cookie cannot be changed, and on a shared
45
+ * instance it would end their session in the other product. `refusal` says why to the sign-in page, which offers the
46
+ * person an explicit sign-out (`@sssb/kit/components/auth/account-refused`). Over the provider's organizations, every method is
47
+ * otherwise the adapter's, with its organizations, roles, members and invitations; the ones that act for the signed-in
48
+ * person (`updateProfile`, `createInvite`, `listMyOrgs`, `setActiveOrg`) run the tenant guard first, and `getMember`
49
+ * runs it after the provider's membership.
50
+ *
51
+ * **A fixed org source places everyone in one org with one role**, and what each method means follows from it:
52
+ * - `getCurrentUser`: the home org and the configured role, whatever the provider's metadata says. No role is read from
53
+ * the provider: on an instance shared with another product, that product may write the same metadata for its own
54
+ * reasons.
55
+ * - `getMember`: the same standing, with the account's name and email, for an account the provider still has, in the
56
+ * home org; null for any other org, and for an unknown or banned account.
57
+ * - `listMembers`: empty. Membership is implicit, and listing the provider's users would enumerate everyone on the
58
+ * instance, another product's users included, and mail them. So no one is an org admin: the end of a job submitted
59
+ * with a requester goes to that person instead (../server-lib/notify.ts `notifyJobTerminal`), and an app addresses
60
+ * its own notifications to the people it knows. SSSB's own rules let neither offered role submit a `Job` (create
61
+ * needs a non-restricted member), so such a job is one the app's own rules let the person start.
62
+ * - `createInvite`: refused. Anyone the provider signs in is already placed in the home org; an app adds people through
63
+ * its provider's own sign-up.
64
+ * - `listMyOrgs`: the home org alone, named by its org row's name, which the caller supplies a lookup for (`orgName`;
65
+ * the slug when the row is missing). `setActiveOrg`: the home org
66
+ * is accepted and changes nothing; any other is refused.
67
+ *
68
+ * `signInPath` and `signOut` are always the adapter's, and `updateProfile` writes through it after the guard.
69
+ */
70
+ export function configuredAuth(
71
+ base: AuthPort,
72
+ settings: AuthSettings,
73
+ source: ProviderIdentitySource,
74
+ staffOrgSlug: string,
75
+ /**
76
+ * The display name of an org, by its tenant's slug and its own, or null when there is no such row: how a fixed org
77
+ * source names its home org, since this module knows it only by slug. Left out (a test), the slug is the name.
78
+ */
79
+ orgName?: (tenantSlug: string, orgSlug: string) => Promise<string | null>,
80
+ ): AuthPort {
81
+ const { tenancy, orgSource } = settings
82
+ if (tenancy.kind === 'multi' && orgSource.kind === 'provider') return base
83
+ const problem = fixedOrgProblem(orgSource, staffOrgSlug)
84
+ if (problem) throw new Error(problem)
85
+ // authSettings refuses this pairing; refused again here, for a caller that builds the settings itself.
86
+ if (orgSource.kind === 'fixed' && tenancy.kind !== 'single')
87
+ throw new Error('a fixed org source needs a single tenancy')
88
+
89
+ const admitted = (claim: string | null | undefined) =>
90
+ tenancy.kind === 'multi' || claim === undefined || claim === tenancy.tenantSlug
91
+ const fixed = orgSource.kind === 'fixed' ? orgSource : null
92
+ const fixedRestricted = fixed ? isRestricted(undefined, fixed.role) : false
93
+
94
+ const port: AuthPort = {
95
+ async getCurrentUser(): Promise<AuthUser | null> {
96
+ const identity = await source.current()
97
+ if (!identity || !admitted(identity.tenantClaim)) return null
98
+ if (fixed) {
99
+ return {
100
+ id: identity.id,
101
+ name: identity.name,
102
+ email: identity.email,
103
+ locale: identity.locale,
104
+ role: fixed.role,
105
+ // A fixed org source needs a single tenancy (refused above otherwise).
106
+ tenantSlug: tenancy.kind === 'single' ? tenancy.tenantSlug : '',
107
+ orgSlug: fixed.homeOrgSlug,
108
+ restricted: fixedRestricted,
109
+ }
110
+ }
111
+ // Single tenancy over the provider's organizations: the adapter's user, in the configured tenant. The
112
+ // adapter reads the signed-in account again, so on Clerk this may be a second user request per call (the
113
+ // cutover row `auth-tenancy` says to measure it).
114
+ const user = await base.getCurrentUser()
115
+ if (!user || user.id !== identity.id) return null
116
+ return tenancy.kind === 'single' ? { ...user, tenantSlug: tenancy.tenantSlug } : user
117
+ },
118
+
119
+ async requireUser(): Promise<AuthUser> {
120
+ const user = await port.getCurrentUser()
121
+ if (!user) throw new AuthRequiredError()
122
+ return user
123
+ },
124
+
125
+ async requireRole(...roles): Promise<AuthUser> {
126
+ const user = await port.requireUser()
127
+ if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
128
+ return user
129
+ },
130
+
131
+ signInPath(returnTo?: string): string {
132
+ return base.signInPath(returnTo)
133
+ },
134
+
135
+ async signOut(): Promise<void> {
136
+ await base.signOut()
137
+ },
138
+
139
+ async updateProfile(update): Promise<AuthUser> {
140
+ await port.requireUser()
141
+ await base.updateProfile(update)
142
+ return port.requireUser()
143
+ },
144
+
145
+ async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
146
+ if (!fixed) {
147
+ // The provider's organizations: its own membership first, so a non-member costs what it always did,
148
+ // then the tenant guard.
149
+ const standing = await base.getMember(orgSlug, userId)
150
+ if (!standing) return null
151
+ const account = await source.account(userId)
152
+ return account && admitted(account.tenantClaim) ? standing : null
153
+ }
154
+ if (orgSlug !== fixed.homeOrgSlug) return null
155
+ const account = await source.account(userId)
156
+ if (!account || !admitted(account.tenantClaim)) return null
157
+ return { role: fixed.role, restricted: fixedRestricted, name: account.name, email: account.email }
158
+ },
159
+
160
+ async listMembers(orgSlug: string): Promise<Membership[]> {
161
+ return fixed ? [] : base.listMembers(orgSlug)
162
+ },
163
+
164
+ async createInvite(invite): Promise<CreatedInvite> {
165
+ if (fixed) {
166
+ throw new ForbiddenError(
167
+ 'a fixed org source places everyone the identity provider signs in in the home org, so there is ' +
168
+ 'no one to invite (AUTH_ORG_SOURCE=fixed)',
169
+ )
170
+ }
171
+ // The adapter checks only that someone is signed in; the tenant guard is this port's.
172
+ await port.requireUser()
173
+ return base.createInvite(invite)
174
+ },
175
+
176
+ async listMyOrgs(): Promise<OrgRef[]> {
177
+ const user = await port.getCurrentUser()
178
+ if (!user) return []
179
+ if (fixed) {
180
+ // The org row's name, read per call (a rename shows at once); the slug when the row is missing,
181
+ // which the cutover row `auth-tenancy` says to create.
182
+ // A failed read falls back too: a display name never takes the page down.
183
+ const name =
184
+ (await orgName?.(user.tenantSlug, fixed.homeOrgSlug).catch(() => null)) ?? fixed.homeOrgSlug
185
+ return [{ slug: fixed.homeOrgSlug, name, role: fixed.role }]
186
+ }
187
+ return base.listMyOrgs()
188
+ },
189
+
190
+ async refusal(): Promise<AuthRefusal | null> {
191
+ // The guard's own reason, from the same identity read. Its callers are the sign-in pages, not every request.
192
+ const identity = await source.current()
193
+ return identity && !admitted(identity.tenantClaim) ? { reason: 'other-tenant' } : null
194
+ },
195
+
196
+ async setActiveOrg(orgSlug: string): Promise<void> {
197
+ await port.requireUser()
198
+ if (!fixed) return base.setActiveOrg(orgSlug)
199
+ if (orgSlug !== fixed.homeOrgSlug) throw new ForbiddenError(`no membership in org: ${orgSlug}`)
200
+ },
201
+ }
202
+ return port
203
+ }
@@ -8,7 +8,7 @@ import { copyFile, rename, unlink, writeFile } from 'node:fs/promises'
8
8
  *
9
9
  * WHY this exists: every fake adapter persists its state as a flat file, and under concurrent
10
10
  * requests two writers can land on the SAME file at once (see
11
- * .claude/future-tasks/e2e-shared-world-blocks-parallelism.md). Plain `writeFileSync`/`writeFile`
11
+ * safeinsights/sssb#99). Plain `writeFileSync`/`writeFile`
12
12
  * TRUNCATE the file and then stream the new bytes in — so if writer A (shorter payload) and writer
13
13
  * B (longer payload) interleave, a reader can observe B's truncate landing after A has already
14
14
  * written, leaving A's shorter content followed by the tail of B's longer content: neither writer's
@@ -18,6 +18,7 @@ import type {
18
18
  ProfileUpdate,
19
19
  } from '../../ports/auth'
20
20
  import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
21
+ import type { ProviderIdentitySource } from '../configured-auth'
21
22
  import { writeFileAtomicSync, writeJsonAtomic } from './atomic-write'
22
23
  import { readSimulatorState, updatePersonState, writeViewpointCookie } from './simulator'
23
24
  import { dataDir } from './data-dir'
@@ -291,7 +292,12 @@ export const fakeAuth: AuthPort = {
291
292
  const person = findPerson(userId)
292
293
  const membership = person?.memberships.find((m) => m.orgSlug === orgSlug)
293
294
  if (!person || !membership) return null
294
- return { role: membership.role, restricted: isRestricted(person.restricted, membership.role) }
295
+ return {
296
+ role: membership.role,
297
+ restricted: isRestricted(person.restricted, membership.role),
298
+ name: readOverrides()[person.id]?.name ?? person.name,
299
+ email: person.email,
300
+ }
295
301
  },
296
302
 
297
303
  async createInvite(invite: InviteInput): Promise<CreatedInvite> {
@@ -334,6 +340,34 @@ export const fakeAuth: AuthPort = {
334
340
  },
335
341
  }
336
342
 
343
+ /**
344
+ * The simulated world's people as the auth settings see them (../configured-auth.ts): who is signed in and whether an
345
+ * account exists, with no org or role in it. A person's seeded tenant is their tenant claim, so a world run in single
346
+ * tenancy must seed its people in the configured tenant, as a deployment's accounts must not claim another. The
347
+ * simulated sign-in resolves a membership, so a world run with a fixed org source still seeds each person one.
348
+ */
349
+ export const fakeIdentitySource: ProviderIdentitySource = {
350
+ async current() {
351
+ const session = await readSession()
352
+ if (!session) return null
353
+ const user = toUser(session.person, session.orgSlug)
354
+ return {
355
+ id: user.id,
356
+ name: user.name,
357
+ email: user.email,
358
+ locale: user.locale,
359
+ // An empty claim is no claim, as Clerk's adapter reads it.
360
+ tenantClaim: session.person.tenantSlug || undefined,
361
+ }
362
+ },
363
+ async account(userId) {
364
+ const person = findPerson(userId)
365
+ if (!person) return null
366
+ const name = readOverrides()[person.id]?.name ?? person.name
367
+ return { tenantClaim: person.tenantSlug || undefined, name, email: person.email }
368
+ },
369
+ }
370
+
337
371
  /** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
338
372
  function isProfileName(name: unknown): name is string {
339
373
  return typeof name === 'string' && name.trim() !== '' && name.length <= 256
@@ -5,11 +5,12 @@ 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'
8
- import { fakeAuth, personLocale } from './auth'
8
+ import { personLocale } from './auth'
9
9
  import { fakeDb } from './db'
10
10
  import { fakeEmail } from './email'
11
11
  import { fakeLlm } from './llm'
12
12
  import { fakeSendSms } from './sms'
13
+ import { simulatedAuth } from './simulated-auth'
13
14
  import { fakeStorage } from './storage'
14
15
 
15
16
  /** Simulator flag: when set, submitted jobs stay 'queued' so an operator can step them forward. */
@@ -31,7 +32,7 @@ async function notifyTerminal(job: SubmittedJob, status: 'completed' | 'failed')
31
32
  const { notifyJobTerminal } = await import('../../server-lib/notify')
32
33
  await notifyJobTerminal(
33
34
  { db: fakeDb, email: fakeEmail, sms: fakeSendSms, resolveLocale: personLocale },
34
- fakeAuth,
35
+ simulatedAuth(),
35
36
  { tenantId: job.tenantId, jobId: job.id, status },
36
37
  )
37
38
  } catch {
@@ -53,7 +54,7 @@ async function executeJob(job: SubmittedJob): Promise<boolean> {
53
54
  storage: fakeStorage,
54
55
  email: fakeEmail,
55
56
  llm: fakeLlm,
56
- auth: fakeAuth,
57
+ auth: simulatedAuth(),
57
58
  resolveLocale: personLocale,
58
59
  }
59
60
  return runJobInProcess(job, ports, (status) => notifyTerminal(job, status))
@@ -234,7 +235,7 @@ export async function produceJobArtifact(
234
235
  storage: fakeStorage,
235
236
  email: fakeEmail,
236
237
  llm: fakeLlm,
237
- auth: fakeAuth,
238
+ auth: simulatedAuth(),
238
239
  resolveLocale: personLocale,
239
240
  tenantId: row.tenant_id,
240
241
  orgId: row.org_id,
@@ -0,0 +1,30 @@
1
+ import { staffOrgSlug } from '@sssb/app-config/abilities'
2
+ import type { AuthPort } from '../../ports/auth'
3
+ import { authSettings } from '../auth-tenancy'
4
+ import { orgNameForSlugs } from '../../db/org-lookup'
5
+ import { configuredAuth } from '../configured-auth'
6
+ import { fakeAuth, fakeIdentitySource } from './auth'
7
+ import { fakeDb } from './db'
8
+
9
+ let cached: AuthPort | undefined
10
+
11
+ /**
12
+ * The simulated world's auth port: the fake, placed as the environment's auth settings say (`AUTH_TENANCY`,
13
+ * `AUTH_ORG_SOURCE`: ../auth-tenancy.ts), and the bare fake on the defaults. Every simulated consumer takes it from
14
+ * here, the registry (../index.ts), the fake job runner's handlers and notifications (./jobs.ts) and the conformance
15
+ * suite's preset replay, so an app's `pnpm dev` places people as its deployment does everywhere, not only on the
16
+ * request path. Read on first use, so only in simulated mode: the registry imports the fakes in real mode too, where
17
+ * a misconfigured setting is the boot check's to report.
18
+ *
19
+ * The conformance suite's preset replay takes this too, deliberately: a preset that invites someone under a fixed org
20
+ * source, or signs in a person of another tenant under a single tenancy, describes a world the deployment cannot
21
+ * reach, and the replay says so.
22
+ */
23
+ export function simulatedAuth(): AuthPort {
24
+ if (cached === undefined) {
25
+ cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug, (tenant, org) =>
26
+ orgNameForSlugs(fakeDb, tenant, org),
27
+ )
28
+ }
29
+ return cached
30
+ }
@@ -9,7 +9,7 @@ import type { LlmPort } from '../ports/llm'
9
9
  import type { StoragePort } from '../ports/storage'
10
10
  import { simulatedDevServer } from './dev-server'
11
11
  import { fakeAnalytics } from './fake/analytics'
12
- import { fakeAuth } from './fake/auth'
12
+ import { simulatedAuth } from './fake/simulated-auth'
13
13
  import { fakeDb } from './fake/db'
14
14
  import { fakeEmail } from './fake/email'
15
15
  import { fakeJobs } from './fake/jobs'
@@ -109,7 +109,8 @@ const real =
109
109
  ? await (await import('./real/index')).createRealPorts({ inProcessJobs: buildInProcessJobs })
110
110
  : null
111
111
 
112
- export const auth: AuthPort = real?.auth ?? fakeAuth
112
+ // The simulated world runs the deployment's auth tenancy when its environment sets one (./fake/simulated-auth.ts).
113
+ export const auth: AuthPort = real?.auth ?? simulatedAuth()
113
114
  export const db: DbPort = real?.db ?? fakeDb
114
115
  export const storage: StoragePort = real?.storage ?? fakeStorage
115
116
  export const llm: LlmPort = real?.llm ?? fakeLlm
@@ -0,0 +1,32 @@
1
+ 'use client'
2
+
3
+ import { useAuth, useClerk } from '@clerk/nextjs'
4
+ import { AccountRefused } from '../../components/auth/account-refused'
5
+
6
+ /**
7
+ * The refused-account screen in real mode (`@sssb/kit/components/auth/account-refused`), signing out through Clerk's
8
+ * client. Revoking the session on the server alone leaves the browser's short-lived session token in place, which the
9
+ * middleware still verifies until it lapses, so the page would come back refused. Clerk's client sign-out ends this one
10
+ * session (`sessionId`), clears its cookies, and then sends the browser back to this page (`redirectUrl`), which now
11
+ * shows the sign-in form.
12
+ *
13
+ * Only on the person's click, as the screen says: on an identity-provider instance shared with another product, this
14
+ * session may be that product's too. Until Clerk has loaded and knows the session, a click signs nobody out and says
15
+ * so: before then Clerk only queues the call, and with no session id it would end every session on the device.
16
+ *
17
+ * AUTHORED — CUTOVER (`auth-tenancy`): never run against a real Clerk instance. Lives in packages/kit/src/adapters
18
+ * because it imports the vendor SDK; mount it under `RealAuthProviders`.
19
+ */
20
+ export function RealAccountRefused() {
21
+ const { signOut } = useClerk()
22
+ const { isLoaded, sessionId } = useAuth()
23
+ return (
24
+ <AccountRefused
25
+ onSignOut={async () => {
26
+ if (!isLoaded || !sessionId) return false
27
+ await signOut({ sessionId, redirectUrl: window.location.href })
28
+ return true
29
+ }}
30
+ />
31
+ )
32
+ }