@sssb/kit 0.5.0 → 0.6.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 CHANGED
@@ -1 +1 @@
1
- {"commit":"1f7bc710b87ea12442ba8f1505aaf2245c58fbec"}
1
+ {"commit":"d70d56db1537eee2bcfe9c8c72bb4c784b131117"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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,183 @@
1
+ import { isRestricted } from '../core/roles'
2
+ import type { Locale } from '../core/locale'
3
+ import type { AuthPort, 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. Over the provider's organizations, every method is
46
+ * otherwise the adapter's, with its organizations, roles, members and invitations; the ones that act for the signed-in
47
+ * person (`updateProfile`, `createInvite`, `listMyOrgs`, `setActiveOrg`) run the tenant guard first, and `getMember`
48
+ * runs it after the provider's membership.
49
+ *
50
+ * **A fixed org source places everyone in one org with one role**, and what each method means follows from it:
51
+ * - `getCurrentUser`: the home org and the configured role, whatever the provider's metadata says. No role is read from
52
+ * the provider: on an instance shared with another product, that product may write the same metadata for its own
53
+ * reasons.
54
+ * - `getMember`: the same standing, with the account's name and email, for an account the provider still has, in the
55
+ * home org; null for any other org, and for an unknown or banned account.
56
+ * - `listMembers`: empty. Membership is implicit, and listing the provider's users would enumerate everyone on the
57
+ * instance, another product's users included, and mail them. So no one is an org admin: the end of a job submitted
58
+ * with a requester goes to that person instead (../server-lib/notify.ts `notifyJobTerminal`), and an app addresses
59
+ * its own notifications to the people it knows. SSSB's own rules let neither offered role submit a `Job` (create
60
+ * needs a non-restricted member), so such a job is one the app's own rules let the person start.
61
+ * - `createInvite`: refused. Anyone the provider signs in is already placed in the home org; an app adds people through
62
+ * its provider's own sign-up.
63
+ * - `listMyOrgs`: the home org alone, named by its slug (this module reads no database). `setActiveOrg`: the home org
64
+ * is accepted and changes nothing; any other is refused.
65
+ *
66
+ * `signInPath` and `signOut` are always the adapter's, and `updateProfile` writes through it after the guard.
67
+ */
68
+ export function configuredAuth(
69
+ base: AuthPort,
70
+ settings: AuthSettings,
71
+ source: ProviderIdentitySource,
72
+ staffOrgSlug: string,
73
+ ): AuthPort {
74
+ const { tenancy, orgSource } = settings
75
+ if (tenancy.kind === 'multi' && orgSource.kind === 'provider') return base
76
+ const problem = fixedOrgProblem(orgSource, staffOrgSlug)
77
+ if (problem) throw new Error(problem)
78
+ // authSettings refuses this pairing; refused again here, for a caller that builds the settings itself.
79
+ if (orgSource.kind === 'fixed' && tenancy.kind !== 'single')
80
+ throw new Error('a fixed org source needs a single tenancy')
81
+
82
+ const admitted = (claim: string | null | undefined) =>
83
+ tenancy.kind === 'multi' || claim === undefined || claim === tenancy.tenantSlug
84
+ const fixed = orgSource.kind === 'fixed' ? orgSource : null
85
+ const fixedRestricted = fixed ? isRestricted(undefined, fixed.role) : false
86
+
87
+ const port: AuthPort = {
88
+ async getCurrentUser(): Promise<AuthUser | null> {
89
+ const identity = await source.current()
90
+ if (!identity || !admitted(identity.tenantClaim)) return null
91
+ if (fixed) {
92
+ return {
93
+ id: identity.id,
94
+ name: identity.name,
95
+ email: identity.email,
96
+ locale: identity.locale,
97
+ role: fixed.role,
98
+ // A fixed org source needs a single tenancy (refused above otherwise).
99
+ tenantSlug: tenancy.kind === 'single' ? tenancy.tenantSlug : '',
100
+ orgSlug: fixed.homeOrgSlug,
101
+ restricted: fixedRestricted,
102
+ }
103
+ }
104
+ // Single tenancy over the provider's organizations: the adapter's user, in the configured tenant. The
105
+ // adapter reads the signed-in account again, so on Clerk this may be a second user request per call (the
106
+ // cutover row `auth-tenancy` says to measure it).
107
+ const user = await base.getCurrentUser()
108
+ if (!user || user.id !== identity.id) return null
109
+ return tenancy.kind === 'single' ? { ...user, tenantSlug: tenancy.tenantSlug } : user
110
+ },
111
+
112
+ async requireUser(): Promise<AuthUser> {
113
+ const user = await port.getCurrentUser()
114
+ if (!user) throw new AuthRequiredError()
115
+ return user
116
+ },
117
+
118
+ async requireRole(...roles): Promise<AuthUser> {
119
+ const user = await port.requireUser()
120
+ if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
121
+ return user
122
+ },
123
+
124
+ signInPath(returnTo?: string): string {
125
+ return base.signInPath(returnTo)
126
+ },
127
+
128
+ async signOut(): Promise<void> {
129
+ await base.signOut()
130
+ },
131
+
132
+ async updateProfile(update): Promise<AuthUser> {
133
+ await port.requireUser()
134
+ await base.updateProfile(update)
135
+ return port.requireUser()
136
+ },
137
+
138
+ async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
139
+ if (!fixed) {
140
+ // The provider's organizations: its own membership first, so a non-member costs what it always did,
141
+ // then the tenant guard.
142
+ const standing = await base.getMember(orgSlug, userId)
143
+ if (!standing) return null
144
+ const account = await source.account(userId)
145
+ return account && admitted(account.tenantClaim) ? standing : null
146
+ }
147
+ if (orgSlug !== fixed.homeOrgSlug) return null
148
+ const account = await source.account(userId)
149
+ if (!account || !admitted(account.tenantClaim)) return null
150
+ return { role: fixed.role, restricted: fixedRestricted, name: account.name, email: account.email }
151
+ },
152
+
153
+ async listMembers(orgSlug: string): Promise<Membership[]> {
154
+ return fixed ? [] : base.listMembers(orgSlug)
155
+ },
156
+
157
+ async createInvite(invite): Promise<CreatedInvite> {
158
+ if (fixed) {
159
+ throw new ForbiddenError(
160
+ 'a fixed org source places everyone the identity provider signs in in the home org, so there is ' +
161
+ 'no one to invite (AUTH_ORG_SOURCE=fixed)',
162
+ )
163
+ }
164
+ // The adapter checks only that someone is signed in; the tenant guard is this port's.
165
+ await port.requireUser()
166
+ return base.createInvite(invite)
167
+ },
168
+
169
+ async listMyOrgs(): Promise<OrgRef[]> {
170
+ const user = await port.getCurrentUser()
171
+ if (!user) return []
172
+ if (fixed) return [{ slug: fixed.homeOrgSlug, name: fixed.homeOrgSlug, role: fixed.role }]
173
+ return base.listMyOrgs()
174
+ },
175
+
176
+ async setActiveOrg(orgSlug: string): Promise<void> {
177
+ await port.requireUser()
178
+ if (!fixed) return base.setActiveOrg(orgSlug)
179
+ if (orgSlug !== fixed.homeOrgSlug) throw new ForbiddenError(`no membership in org: ${orgSlug}`)
180
+ },
181
+ }
182
+ return port
183
+ }
@@ -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,24 @@
1
+ import { staffOrgSlug } from '@sssb/app-config/abilities'
2
+ import type { AuthPort } from '../../ports/auth'
3
+ import { authSettings } from '../auth-tenancy'
4
+ import { configuredAuth } from '../configured-auth'
5
+ import { fakeAuth, fakeIdentitySource } from './auth'
6
+
7
+ let cached: AuthPort | undefined
8
+
9
+ /**
10
+ * The simulated world's auth port: the fake, placed as the environment's auth settings say (`AUTH_TENANCY`,
11
+ * `AUTH_ORG_SOURCE`: ../auth-tenancy.ts), and the bare fake on the defaults. Every simulated consumer takes it from
12
+ * here, the registry (../index.ts), the fake job runner's handlers and notifications (./jobs.ts) and the conformance
13
+ * suite's preset replay, so an app's `pnpm dev` places people as its deployment does everywhere, not only on the
14
+ * request path. Read on first use, so only in simulated mode: the registry imports the fakes in real mode too, where
15
+ * a misconfigured setting is the boot check's to report.
16
+ *
17
+ * The conformance suite's preset replay takes this too, deliberately: a preset that invites someone under a fixed org
18
+ * source, or signs in a person of another tenant under a single tenancy, describes a world the deployment cannot
19
+ * reach, and the replay says so.
20
+ */
21
+ export function simulatedAuth(): AuthPort {
22
+ if (cached === undefined) cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug)
23
+ return cached
24
+ }
@@ -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
@@ -13,13 +13,19 @@ import type {
13
13
  ProfileUpdate,
14
14
  } from '../../ports/auth'
15
15
  import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
16
+ import { authSettings } from '../auth-tenancy'
17
+ import type { ProviderIdentitySource } from '../configured-auth'
16
18
 
17
19
  /**
18
20
  * Clerk headless adapter (ADR-0003). Clerk organizations ARE our orgs
19
21
  * (product copy: "teams"); our org slug === Clerk org slug (no mapping layer). The tenant (site) is
20
- * ambient and lives in user publicMetadata.tenantSlug — one Clerk instance per tenant in prod, so
22
+ * ambient and lives in the user's publicMetadata, under the deployment's key (`tenantSlug` unless
23
+ * AUTH_TENANT_METADATA_KEY says otherwise) — one Clerk instance per tenant in prod, so
21
24
  * every org a user sees belongs to their tenant. The ACTIVE org rides in unsafeMetadata.currentOrgSlug,
22
25
  * and the request-time role comes from that org membership's publicMetadata.role (role is per-org).
26
+ * These are the default auth settings (multi tenancy, the provider's organizations); a single tenancy or a fixed
27
+ * org source (../auth-tenancy.ts) wraps this adapter with ../configured-auth.ts, which reads Clerk's accounts
28
+ * through `clerkIdentitySource` below.
23
29
  *
24
30
  * AUTHORED — CUTOVER (`auth-dev`): typechecked against @clerk/nextjs, never run against a real
25
31
  * Clerk instance. Verify the full port contract suite against the dev instance at cutover.
@@ -31,7 +37,27 @@ interface AppPublicMetadata {
31
37
  role?: string
32
38
  locale?: string
33
39
  restricted?: boolean
34
- tenantSlug?: string
40
+ }
41
+
42
+ /**
43
+ * The tenant a user's public metadata claims, under the deployment's key (`AUTH_TENANT_METADATA_KEY`, default
44
+ * `tenantSlug`: ../auth-tenancy.ts): the string it holds; `undefined` when it holds none (absent, null or empty); or
45
+ * `null` when it holds something else, which a single tenancy refuses and a multi tenancy reads as no tenant.
46
+ */
47
+ function tenantClaim(metadata: unknown): string | null | undefined {
48
+ const key = authSettings().tenantMetadataKey
49
+ // Its own property only: a key such as `toString` names something every object inherits.
50
+ const value =
51
+ metadata !== null && typeof metadata === 'object' && Object.hasOwn(metadata, key)
52
+ ? (metadata as Record<string, unknown>)[key]
53
+ : undefined
54
+ if (value === undefined || value === null || value === '') return undefined
55
+ return typeof value === 'string' ? value : null
56
+ }
57
+
58
+ function localeFrom(metadata: unknown): Locale {
59
+ const locale = (metadata as AppPublicMetadata | null | undefined)?.locale
60
+ return LOCALES.includes(locale as Locale) ? (locale as Locale) : DEFAULT_LOCALE
35
61
  }
36
62
 
37
63
  /**
@@ -92,7 +118,7 @@ export const realAuth: AuthPort = {
92
118
  const user = await currentUser()
93
119
  if (!user) return null
94
120
  const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
95
- const locale = LOCALES.includes(metadata.locale as Locale) ? (metadata.locale as Locale) : DEFAULT_LOCALE
121
+ const locale = localeFrom(metadata)
96
122
 
97
123
  // Resolve the active org membership: the remembered currentOrgSlug if still a membership,
98
124
  // else the first one. Role comes from that membership (per-org), not the user object.
@@ -110,7 +136,7 @@ export const realAuth: AuthPort = {
110
136
  role,
111
137
  locale,
112
138
  // Ambient site claim — never the active org's business.
113
- tenantSlug: metadata.tenantSlug ?? '',
139
+ tenantSlug: tenantClaim(user.publicMetadata) ?? '',
114
140
  orgSlug: active ? (active.organization.slug ?? active.organization.id) : '',
115
141
  restricted: isRestricted(metadata.restricted, role),
116
142
  }
@@ -186,7 +212,12 @@ export const realAuth: AuthPort = {
186
212
  if (user.banned) return null
187
213
  const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
188
214
  const role = roleFrom(membership.publicMetadata)
189
- return { role, restricted: isRestricted(metadata.restricted, role) }
215
+ return {
216
+ role,
217
+ restricted: isRestricted(metadata.restricted, role),
218
+ name: user.fullName ?? null,
219
+ email: user.primaryEmailAddress?.emailAddress ?? '',
220
+ }
190
221
  },
191
222
 
192
223
  async listMembers(orgSlug: string): Promise<Membership[]> {
@@ -276,3 +307,40 @@ export const realAuth: AuthPort = {
276
307
  await client.users.updateUserMetadata(userId, { unsafeMetadata: { currentOrgSlug: orgSlug } })
277
308
  },
278
309
  }
310
+
311
+ /**
312
+ * Clerk's accounts as the auth settings see them (../configured-auth.ts): who is signed in and whether an account may
313
+ * still act, with no organization or role in it, so a fixed org source makes no membership call per request. A banned
314
+ * account may not act, as `getMember` says above; a locked one may, for the reason given there.
315
+ */
316
+ export const clerkIdentitySource: ProviderIdentitySource = {
317
+ async current() {
318
+ const { userId } = await auth()
319
+ if (!userId) return null
320
+ const user = await currentUser()
321
+ if (!user) return null
322
+ return {
323
+ id: userId,
324
+ name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
325
+ email: user.primaryEmailAddress?.emailAddress ?? '',
326
+ locale: localeFrom(user.publicMetadata),
327
+ tenantClaim: tenantClaim(user.publicMetadata),
328
+ }
329
+ },
330
+ async account(userId) {
331
+ const client = await clerkClient()
332
+ let user
333
+ try {
334
+ user = await client.users.getUser(userId)
335
+ } catch (error) {
336
+ if (isClerkAPIResponseError(error) && error.status === 404) return null
337
+ throw error
338
+ }
339
+ if (user.banned) return null
340
+ return {
341
+ tenantClaim: tenantClaim(user.publicMetadata),
342
+ name: user.fullName ?? null,
343
+ email: user.primaryEmailAddress?.emailAddress ?? '',
344
+ }
345
+ },
346
+ }
@@ -1,3 +1,4 @@
1
+ import { staffOrgSlug } from '@sssb/app-config/abilities'
1
2
  import type { AnalyticsPort } from '../../ports/analytics'
2
3
  import type { AuthPort } from '../../ports/auth'
3
4
  import type { DbPort } from '../../ports/db'
@@ -7,7 +8,9 @@ import type { JobsPort } from '../../ports/jobs'
7
8
  import type { LlmPort } from '../../ports/llm'
8
9
  import type { StoragePort } from '../../ports/storage'
9
10
  import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
10
- import { realAuth } from './auth'
11
+ import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
+ import { configuredAuth } from '../configured-auth'
13
+ import { clerkIdentitySource, realAuth } from './auth'
11
14
  import { DATABASE_ENV, databaseTransport } from './database-transport'
12
15
  import { noAnalytics } from './no-analytics'
13
16
  import { optionalPortsEnv, portChoice } from './optional-ports'
@@ -49,6 +52,7 @@ export function assertRealEnv(): void {
49
52
  ...DATABASE_ENV[transport],
50
53
  ...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
51
54
  ...optionalPortsEnv(),
55
+ ...authRequiredEnv(),
52
56
  }
53
57
  const missing = Object.keys(required).filter((name) => !process.env[name])
54
58
  if (missing.length > 0) {
@@ -69,6 +73,15 @@ export function assertRealEnv(): void {
69
73
  throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
70
74
  }
71
75
  }
76
+ // The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
77
+ // org source that would hand everyone the staff org's manage-all.
78
+ let problem: string | null
79
+ try {
80
+ problem = fixedOrgProblem(authSettings().orgSource, staffOrgSlug)
81
+ } catch (error) {
82
+ problem = (error as Error).message
83
+ }
84
+ if (problem) throw new CutoverPendingError(['auth-tenancy'], problem)
72
85
  }
73
86
 
74
87
  /**
@@ -95,6 +108,9 @@ interface RealPortsHooks {
95
108
  export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
96
109
  assertRealEnv()
97
110
  const env = process.env
111
+ // Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
112
+ // reaches the people (the in-process runner's job context included) is handed this one.
113
+ const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug)
98
114
  // assertRealEnv above already proved every required variable is set; this narrows the type.
99
115
  const need = (name: string): string => {
100
116
  const value = env[name]
@@ -144,7 +160,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
144
160
  runner === 'codebuild'
145
161
  ? (await import('./jobs')).createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION'))
146
162
  : runner === 'in-process'
147
- ? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
163
+ ? await inProcessJobs(hooks, { db, storage, email, llm, auth })
148
164
  : absentJobs
149
165
  // PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
150
166
  // the simulated world's fake, which writes under `.data/`.
@@ -152,7 +168,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
152
168
  ? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
153
169
  : noAnalytics
154
170
  return {
155
- auth: realAuth,
171
+ auth,
156
172
  db,
157
173
  storage,
158
174
  llm,
@@ -10,6 +10,7 @@ import {
10
10
  type SubjectType,
11
11
  defineAbilitiesFor,
12
12
  } from '../core/abilities'
13
+ import { hasStanding } from '../core/roles'
13
14
  import type { OrgIdentity } from '../db/org-lookup'
14
15
  import type { AuthPort, AuthUser } from '../ports/auth'
15
16
  import { ForbiddenError } from '../ports/errors'
@@ -48,7 +49,9 @@ export function abilityActorFromUser(user: AuthUser, activeOrgId: string): Abili
48
49
  role: user.role,
49
50
  restricted: user.restricted,
50
51
  activeOrgId,
51
- manageAll: user.orgSlug === staffOrgSlug,
52
+ // Not for a person without standing (role `none`): a fixed org source places every user of the identity
53
+ // provider in the home org, which may be the staff org. The ability layer refuses it again (defineAbilitiesFor).
54
+ manageAll: user.orgSlug === staffOrgSlug && hasStanding(user.role),
52
55
  }
53
56
  }
54
57
 
@@ -7,7 +7,7 @@ import {
7
7
  type AppSubjectFields,
8
8
  type AppSubjectType,
9
9
  } from '@sssb/app-config/abilities'
10
- import { canManageOrg, isRole, type Role } from './roles'
10
+ import { canManageOrg, hasStanding, isRole, type Role } from './roles'
11
11
 
12
12
  /**
13
13
  * The authorization model. PURE TypeScript — imports only ./roles and the app-config seam
@@ -273,6 +273,12 @@ export interface Ability {
273
273
  cannot(action: AbilityAction, subject: AbilitySubject): boolean
274
274
  }
275
275
 
276
+ /**
277
+ * An active-org id no org has: what the app's rules are shown for a person without standing (`hasStanding`). Org ids
278
+ * are database uuids, so no subject's org field can hold it.
279
+ */
280
+ const NO_STANDING_ORG = '\u0000no-standing'
281
+
276
282
  /**
277
283
  * Compile the rule table for one actor. The framework rules (deny by default):
278
284
  * - manageAll → allow everything (held by a member acting AS the app's operator org; see above).
@@ -324,16 +330,26 @@ export function defineAbilitiesFor(actor: Actor): Ability {
324
330
  // The staff superpower belongs to a SESSION acting as the operator org. Enforced here rather than
325
331
  // trusted to whoever built the actor: a person who came through any other credential (an email, a
326
332
  // token), or who states none, never wields it, even acting in the staff org. The app's rules are
327
- // handed the same effective value.
333
+ // handed the same effective value. A person without standing (role `none`, ./roles.ts `hasStanding`) never wields
334
+ // it either: a fixed org source places every user of the identity provider in the home org, which may be the staff
335
+ // org.
328
336
  const session = copy.credential?.kind === 'session'
337
+ const standing = hasStanding(copy.role)
329
338
  // Read at call time, like the app's machine rules (see the machine branch above).
330
339
  const widening: NonSessionAdministration = nonSessionAdministration
331
340
  const person: AbilityActor =
332
- copy.manageAll && session
341
+ copy.manageAll && session && standing
333
342
  ? { ...copy, manageAll: true, credential: { kind: 'session', id: copy.credential?.id ?? null } }
334
343
  : { ...copy, manageAll: false }
335
- // sameOrg for the person reads the COPY's org, like every other person rule.
336
- const personSameOrg: SameOrg = (subject) => subject.orgId != null && subject.orgId === person.activeOrgId
344
+ // sameOrg for the person reads the COPY's org, like every other person rule. A person without standing is in no
345
+ // org for any rule, the framework's or the app's (which are handed this same predicate): being placed in an org is
346
+ // not membership of it.
347
+ const personSameOrg: SameOrg = (subject) =>
348
+ standing && subject.orgId != null && subject.orgId === person.activeOrgId
349
+ // The app's rules see a person without standing as active in no org at all: its `activeOrgId` is a value no org id
350
+ // equals, so a rule that compares org ids itself rather than calling `sameOrg` (a two-sided subject's requester and
351
+ // responder sides, say) cannot grant it either.
352
+ const ruleActor: AbilityActor = standing ? person : { ...person, activeOrgId: NO_STANDING_ORG }
337
353
 
338
354
  function can(action: AbilityAction, subject: AbilitySubject): boolean {
339
355
  // The staff-org superpower. manageAll precedes
@@ -403,7 +419,7 @@ export function defineAbilitiesFor(actor: Actor): Ability {
403
419
  default:
404
420
  // App subjects register through the seam (src/app-config/abilities.ts). Deny by default:
405
421
  // appAbilityRules returns false for anything it does not explicitly allow.
406
- return appAbilityRules(person, action, subject, { sameOrg: personSameOrg })
422
+ return appAbilityRules(ruleActor, action, subject, { sameOrg: personSameOrg })
407
423
  }
408
424
  }
409
425
 
package/src/core/jobs.ts CHANGED
@@ -35,6 +35,23 @@ export function isJobKind(value: string): value is JobKind {
35
35
  )
36
36
  }
37
37
 
38
+ /**
39
+ * When a job kind's terminal state notifies the team's admins: `always` (a completion and a failure, what every app
40
+ * kind did before the setting existed, so the default), `failure` (only a failure) or `never`. An app says it per
41
+ * kind in the seam's optional `jobNotify` export (`@sssb/app-config/jobs`); the framework's own kinds never notify.
42
+ */
43
+ export const JOB_NOTIFY_MODES = ['always', 'failure', 'never'] as const
44
+ export type JobNotify = (typeof JOB_NOTIFY_MODES)[number]
45
+
46
+ export function isJobNotify(value: unknown): value is JobNotify {
47
+ return (JOB_NOTIFY_MODES as readonly unknown[]).includes(value)
48
+ }
49
+
50
+ /** Whether a job that reached `status` is notified under `mode`. */
51
+ export function notifiesOn(mode: JobNotify, status: 'completed' | 'failed'): boolean {
52
+ return mode === 'always' || (mode === 'failure' && status === 'failed')
53
+ }
54
+
38
55
  export function isJobStatus(value: string): value is JobStatus {
39
56
  return (JOB_STATUSES as readonly string[]).includes(value)
40
57
  }
package/src/core/roles.ts CHANGED
@@ -1,6 +1,21 @@
1
- export const ROLES = ['admin', 'staff', 'member', 'guest', 'restricted'] as const
1
+ /**
2
+ * `none` is the lowest: a signed-in person with no standing in the org they are placed in. A fixed org source
3
+ * (`AUTH_ORG_SOURCE=fixed`, the app's `params.auth`) gives it to every user of the deployment's identity provider by
4
+ * default (its other choice is `restricted`). It grants nothing a membership would: no org-scoped access in the
5
+ * framework's rules or the app's, and never manage-all (`hasStanding`). It is not grantable by invite.
6
+ */
7
+ export const ROLES = ['admin', 'staff', 'member', 'guest', 'restricted', 'none'] as const
2
8
  export type Role = (typeof ROLES)[number]
3
9
 
10
+ /**
11
+ * Whether a role carries standing in the org its holder is placed in: every role but `none`. The ability layer
12
+ * treats a holder without standing as outside every org (`sameOrg` is false, framework rules and app rules alike) and
13
+ * never lets it wield the staff org's manage-all.
14
+ */
15
+ export function hasStanding(role: Role): boolean {
16
+ return role !== 'none'
17
+ }
18
+
4
19
  // The designated staff/operator org slug is an app/deployment choice, so it lives on the
5
20
  // seam as `staffOrgSlug` (src/app-config/abilities.ts) — NOT here. DISAMBIGUATION: the operator ORG is
6
21
  // NOT the rank-ladder role `'staff'` below; the role is an org-manager RANK, the org is the operator
@@ -43,5 +58,5 @@ export function canManageOrg(role: Role): boolean {
43
58
  * adapters derive `AuthUser.restricted` and `getMember`'s standing through this one function.
44
59
  */
45
60
  export function isRestricted(flag: boolean | undefined, role: Role): boolean {
46
- return flag === true || role === 'restricted'
61
+ return flag === true || role === 'restricted' || role === 'none'
47
62
  }
@@ -4,6 +4,10 @@
4
4
  "id": "auth-dev",
5
5
  "what": "Managed-auth **development** instance + keys"
6
6
  },
7
+ {
8
+ "id": "auth-tenancy",
9
+ "what": "Auth settings: the tenancy (multi, or single with its tenant) and the org source (the provider's, or one fixed home org and role)"
10
+ },
7
11
  {
8
12
  "id": "auth-prod",
9
13
  "what": "Managed-auth **production** instance (typically one per tenant site)"
package/src/db/jobs.ts CHANGED
@@ -33,16 +33,24 @@ export function toIso(value: unknown): string {
33
33
  * Submits a job: one tenant-scoped transaction persists the `jobs` row and its opening 'queued'
34
34
  * timeline entry together, THEN — only once that has committed — hands off to the execution seam
35
35
  * so the handler (fake: in-process; real: CodeBuild) can never observe a job that isn't durable yet.
36
+ * `requestedBy` is the user id of the person submitting it, when a person is: their job's end reaches them when
37
+ * the org has no admin to tell (../server-lib/notify.ts `notifyJobTerminal`).
36
38
  */
37
39
  export async function submitJob(
38
40
  db: DbPort,
39
41
  jobs: JobsPort,
40
- input: { tenantId: string; orgId: string | null; kind: string; payload: unknown },
42
+ input: { tenantId: string; orgId: string | null; kind: string; payload: unknown; requestedBy?: string | null },
41
43
  ): Promise<{ id: string }> {
42
44
  const { id } = await db.withTenant(input.tenantId, async (trx) => {
43
45
  const job = await trx
44
46
  .insertInto('jobs')
45
- .values({ tenant_id: input.tenantId, org_id: input.orgId, kind: input.kind, payload: input.payload })
47
+ .values({
48
+ tenant_id: input.tenantId,
49
+ org_id: input.orgId,
50
+ kind: input.kind,
51
+ payload: input.payload,
52
+ requested_by: input.requestedBy ?? null,
53
+ })
46
54
  .returning('id')
47
55
  .executeTakeFirstOrThrow()
48
56
  await trx
@@ -279,10 +287,14 @@ export async function jobKindAndOrg(
279
287
  db: DbPort,
280
288
  tenantId: string,
281
289
  jobId: string,
282
- ): Promise<{ kind: string; orgId: string | null } | null> {
290
+ ): Promise<{ kind: string; orgId: string | null; requestedBy: string | null } | null> {
283
291
  return db.withTenant(tenantId, async (trx) => {
284
- const row = await trx.selectFrom('jobs').select(['kind', 'org_id']).where('id', '=', jobId).executeTakeFirst()
285
- return row ? { kind: row.kind, orgId: row.org_id } : null
292
+ const row = await trx
293
+ .selectFrom('jobs')
294
+ .select(['kind', 'org_id', 'requested_by'])
295
+ .where('id', '=', jobId)
296
+ .executeTakeFirst()
297
+ return row ? { kind: row.kind, orgId: row.org_id, requestedBy: row.requested_by } : null
286
298
  })
287
299
  }
288
300
 
@@ -0,0 +1,20 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * WHO started a job: the user id of the person who submitted it, so the end of their job can reach them when the org
5
+ * has no admin to tell (a fixed org source places everyone in one org with one role, so it has none).
6
+ *
7
+ * - NULLABLE, no default. NULL means "no person started it": a scheduled run, a job submitted by a service, and every
8
+ * row written before this migration.
9
+ * - Plain text, no foreign key: user ids are the identity provider's, not a table here (as `audit_events`' actor).
10
+ * - The grant is unchanged: table-level grants cover columns added later (as in 0014 and 0016).
11
+ *
12
+ * It names the one table it touches (the order-independence rule in ./index.ts).
13
+ */
14
+ export async function up(db: Kysely<any>): Promise<void> {
15
+ await sql`ALTER TABLE jobs ADD COLUMN requested_by text`.execute(db)
16
+ }
17
+
18
+ export async function down(db: Kysely<any>): Promise<void> {
19
+ await sql`ALTER TABLE jobs DROP COLUMN requested_by`.execute(db)
20
+ }
@@ -13,6 +13,7 @@ import * as m0013 from './0013_agreements'
13
13
  import * as m0014 from './0014_audit_credential'
14
14
  import * as m0015 from './0015_app_user_grant'
15
15
  import * as m0016 from './0016_audit_detail'
16
+ import * as m0017 from './0017_job_requester'
16
17
 
17
18
  /**
18
19
  * Static migration registry (no filesystem scanning — bundles cleanly into the Lambda migrator and
@@ -44,6 +45,7 @@ export const frameworkMigrations: Record<string, Migration> = {
44
45
  '0014_audit_credential': m0014,
45
46
  '0015_app_user_grant': m0015,
46
47
  '0016_audit_detail': m0016,
48
+ '0017_job_requester': m0017,
47
49
  }
48
50
 
49
51
  export const migrations: Record<string, Migration> = { ...frameworkMigrations, ...appMigrations }
package/src/db/schema.ts CHANGED
@@ -30,6 +30,8 @@ interface JobsTable {
30
30
  status: Generated<string>
31
31
  result_key: string | null
32
32
  error: string | null
33
+ /** The user id of the person who submitted it; null for a scheduled or service job (0017_job_requester). */
34
+ requested_by: Generated<string | null>
33
35
  created_at: Generated<string>
34
36
  updated_at: Generated<string>
35
37
  }
@@ -10,6 +10,7 @@ import type { MailItem } from '../components/simulator/mail-app'
10
10
  import type { SmsMessageRow } from '../components/simulator/messages-app'
11
11
  import type { FeatureFlag } from '../components/simulator/snapshots-app'
12
12
  import type { PendingAgreement } from '../core/agreements'
13
+ import type { JobNotify } from '../core/jobs'
13
14
  import type {
14
15
  NotificationChannel,
15
16
  NotificationKind,
@@ -125,6 +126,14 @@ export interface DemoWorldOptions {
125
126
  initialMail?: { to: string; subject: string; html: string }[]
126
127
  /** Clears the composition root's OWN rows when the world resets — the twin of wiping `.data/`. */
127
128
  onReset?: () => void
129
+ /**
130
+ * Twin of the seam's optional `jobNotify` export (`@sssb/app-config/jobs`): when each app job kind's terminal
131
+ * state notifies its team's admins. Supplied here, as `inboundHandlers` are, because the seam module imports
132
+ * every server handler, which the static bundle cannot carry: an app that sets `jobNotify` passes the same map
133
+ * from a module of its own that both import. A world only ever completes a job, so `failure` and `never` both
134
+ * mean "no notification"; a kind the map leaves out is `always`.
135
+ */
136
+ jobNotify?: Record<string, JobNotify>
128
137
  /**
129
138
  * Static halves of the app's demo-preset operation kinds, keyed by kind — the twins of its server
130
139
  * halves (`@sssb/app-config/preset-operations`), supplied here for the same reason `inboundHandlers` are:
@@ -28,6 +28,8 @@ export interface DemoJob {
28
28
  createdAt: string
29
29
  error: string | null
30
30
  timeline: { status: string; at: string; message?: string | null }[]
31
+ /** Twin of `jobs.requested_by`: the person who started it; absent for a scheduled run. */
32
+ requestedBy?: string | null
31
33
  }
32
34
 
33
35
  /** Twin of a StoredInvite (../adapters/fake/auth.ts) — with no server an invite is just a row of
@@ -226,7 +226,13 @@ function seededMail(initial: DemoWorldOptions['initialMail']): MailItem[] {
226
226
  }
227
227
 
228
228
  export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
229
- const { inboundHandlers = {}, digestBodies, onReset, presetOperations: appPresetOperationHalves = {} } = options
229
+ const {
230
+ inboundHandlers = {},
231
+ digestBodies,
232
+ onReset,
233
+ presetOperations: appPresetOperationHalves = {},
234
+ jobNotify = {},
235
+ } = options
230
236
  const route = useHashRoute()
231
237
  const tEmail = useTranslations('email')
232
238
  const tSimulator = useTranslations('simulator')
@@ -503,7 +509,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
503
509
 
504
510
  /**
505
511
  * Twin of notifyJobTerminal: a user-facing job reaching a terminal state notifies its OWN team's
506
- * admins (jobs carry no creator column, so the team's admins are the recipients).
512
+ * admins, and when the team has none, the person who started it while they are still a member.
507
513
  *
508
514
  * The server gates this on NOTIFIED_JOB_KINDS — `appJobKinds`, i.e. "kinds the app registered are
509
515
  * work someone submitted and is waiting on; the framework's scheduled kinds are internal machinery
@@ -513,9 +519,20 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
513
519
  * sites below ARE the app-submitted kinds. Importing the seam's registry to re-derive that would
514
520
  * have dragged every server handler's db/email dependencies into a bundle that has neither.
515
521
  */
516
- function notifyJobTerminal(job: { id: string; kind: string; orgSlug: string | null }) {
522
+ function notifyJobTerminal(job: { id: string; kind: string; orgSlug: string | null; requestedBy?: string | null }) {
517
523
  if (job.orgSlug === null) return
518
- notifyAdminsOf(job.orgSlug, 'job.completed', { jobId: job.id, jobKind: job.kind, status: 'completed' })
524
+ // The twin of the server's `jobNotify` check (server-lib/notify.ts): this world only ever completes a job (the
525
+ // server's runners also fail them), so a kind that notifies only a failure, or never, is silent here. The
526
+ // server's `notifiesOn` is a value import of core/jobs, which reaches the seam's handlers, so it is not used.
527
+ const mode = jobNotify[job.kind]
528
+ if (mode === 'failure' || mode === 'never') return
529
+ const orgSlug = job.orgSlug
530
+ const payload = { jobId: job.id, jobKind: job.kind, status: 'completed' } as const
531
+ const hasAdmin = allPeople.some(
532
+ (p) => p.memberships.some((m) => m.orgSlug === orgSlug) && canManageOrg(roleInOrg(p, orgSlug)),
533
+ )
534
+ if (hasAdmin) notifyAdminsOf(orgSlug, 'job.completed', payload)
535
+ else if (job.requestedBy) notifyMemberOf(orgSlug, job.requestedBy, 'job.completed', payload)
519
536
  }
520
537
 
521
538
  // ── Outbound webhooks ─────────────────────────────────────────────────────────────────────────
@@ -657,6 +674,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
657
674
  orgSlug: activeOrgSlug,
658
675
  createdAt: iso(0),
659
676
  error: null,
677
+ requestedBy: person?.id ?? null,
660
678
  }
661
679
  const job: DemoJob = held
662
680
  ? { ...base, status: 'queued', timeline: [{ status: 'queued', at: iso(0) }] }
package/src/guide.md CHANGED
@@ -36,6 +36,16 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
36
36
  `jobs`, `storage`). A port the app does not use is `none`, never configured with placeholder values.
37
37
  - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
38
38
  `ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
39
+ - A job kind's completion notifies its team's admins, whoever runs it and whatever it ends as. A routine kind, one a
40
+ schedule runs every hour, says otherwise in the seam's optional `jobNotify` export in `src/app-config/jobs.ts`:
41
+ `export const jobNotify: Partial<Record<AppJobKind, JobNotify>> = { 'sweep-items': 'failure' }`, with `JobNotify` from
42
+ `@sssb/kit/core/jobs`. `'failure'` notifies only a failed job (one the in-process runner's sweep fails as lost included) and `'never'` nothing; a kind not
43
+ named, and an app with no export, is `'always'`, and the framework's own kinds never notify. A refused run makes no
44
+ `listMembers` call. If the static demo starts the kind, pass the same map as `useDemoWorld`'s `jobNotify`.
45
+ - A route that submits a job for a person passes `requestedBy: user.id` to `submitJob` (`@sssb/kit/db/jobs`): when the
46
+ team has no admin to tell (a fixed org source, `params.auth`, has none), the job's end reaches the person who started
47
+ it, and a job submitted without one reaches no one. Under a fixed org source SSSB's `Job` rule admits no one (its
48
+ roles are `none` and `restricted`), so authorize such a submission on a subject of your own.
39
49
  - `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
40
50
  anything that phones home.
41
51
  - Anything that needs real credentials, accounts or money is a row in the workspace's cutover checklist, never a
@@ -106,6 +116,13 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
106
116
  - An exemption is an entry in the app's `authz-exemptions.mjs` (`{ files, prefixes }`, keys relative to
107
117
  `src/app/api`), with a reason and a `mustMatch` gate. A mutating route outside `src/app/api` can match no
108
118
  exemption.
119
+ - A route or screen that reads org-scoped data authorizes the read too, as `src/app/api/items/route.ts`'s GET does
120
+ (`authorize(user, orgId, 'read', …)`): the session's org says where a person is placed, not that they may read there.
121
+ The role `none` (a fixed org source gives it to every signed-in user by default: `params.auth`) is placed in the home
122
+ org with no standing in it.
123
+ - In `appAbilityRules`, grant org-scoped access through the `sameOrg` you are handed, never by a role alone: `sameOrg` is
124
+ false for a person without standing, and a rule that grants because a role is not some other role would grant
125
+ `none` too.
109
126
 
110
127
  ## UI
111
128
 
package/src/ports/auth.ts CHANGED
@@ -19,11 +19,20 @@ export interface AuthUser {
19
19
  /**
20
20
  * A person's CURRENT standing in one org: what their session would carry if they were the caller. Read
21
21
  * for someone who reached the app WITHOUT a session (an inbound email, a personal API token), so their
22
- * role and `restricted` flag come from the same place a session's do, never from the credential.
22
+ * role and `restricted` flag come from the same place a session's do, never from the credential. It also
23
+ * says how to reach them (`name`, `email`), for a notification addressed to one known person, such as the
24
+ * end of a job they started, where no members list names them.
23
25
  */
24
26
  export interface MemberStanding {
25
27
  role: Role
26
28
  restricted: boolean
29
+ /**
30
+ * How to reach them. SSSB's adapters always say; optional so that a stand-in written before these existed (a
31
+ * test double) still type-checks, and a recipient without an address is told in-app only.
32
+ */
33
+ name?: string | null
34
+ /** The account's primary address, or `''` when it has none. */
35
+ email?: string
27
36
  }
28
37
 
29
38
  /** An org the current user belongs to; `role` is their role in THAT org (drives the OrgSwitcher). */
@@ -1,5 +1,6 @@
1
- import { appJobKinds } from '@sssb/app-config/jobs'
1
+ import * as jobsSeam from '@sssb/app-config/jobs'
2
2
  import { getTranslations } from 'next-intl/server'
3
+ import { isJobNotify, type JobNotify, notifiesOn } from '../core/jobs'
3
4
  import { DEFAULT_LOCALE, type Locale } from '../core/locale'
4
5
  import {
5
6
  FRAMEWORK_NOTIFICATION_NAMESPACE,
@@ -211,17 +212,34 @@ export async function notifyMember(
211
212
  }
212
213
  }
213
214
 
214
- /** Job kinds whose terminal state notifies the team. The app's OWN job kinds (appJobKinds,
215
+ /** Job kinds whose terminal state can notify the team. The app's OWN job kinds (appJobKinds,
215
216
  * the seam) are user-submitted work someone is waiting on; the framework's scheduled kinds (e.g.
216
217
  * digest-email) are internal machinery and would just be noise (see the decision log). */
217
- const NOTIFIED_JOB_KINDS = new Set<string>(appJobKinds)
218
+ const NOTIFIED_JOB_KINDS = new Set<string>(jobsSeam.appJobKinds)
218
219
 
219
220
  /**
220
- * Notify a job's org admins that a user-facing job reached a terminal state. Jobs carry no
221
- * creator column, so the org's admins are the recipients (the recorded decision). Resolves the job's
221
+ * When a kind's terminal state notifies: the app's `jobNotify` entry (`@sssb/app-config/jobs`, optional as an
222
+ * export and as an entry), else `always`, which every app kind did before the setting existed. Read through the
223
+ * namespace, as `db/seed.ts` reads `appSeedRows`, so an app that has not added the export still builds. A value that is
224
+ * not one of the three (an untyped seam) counts as absent: the kind notifies as it always did, and is never silenced by
225
+ * a typo.
226
+ */
227
+ function notifyModeFor(kind: string): JobNotify {
228
+ const setting = (jobsSeam as Record<string, unknown>)['jobNotify'] as Record<string, unknown> | undefined
229
+ const mode = setting?.[kind]
230
+ return isJobNotify(mode) ? mode : 'always'
231
+ }
232
+
233
+ /**
234
+ * Notify a job's org admins that a user-facing job reached a terminal state; when the org has no active admin to
235
+ * tell, the person who submitted the job (`requested_by`), while the auth port still gives them standing in the org.
236
+ * An org without admins is what a fixed org source makes (everyone in one org with one role, and an empty members
237
+ * list), and an org whose admins have all left. A job no person submitted (a scheduled run) then reaches no one, so a
238
+ * routine kind there says `jobNotify` `never` to skip the lookup. Resolves the job's
222
239
  * kind + org itself from (tenantId, jobId) so both terminal sites — the fake in-process executor and
223
240
  * the real completion webhook — call it with the same three facts. A no-op for internal job kinds, a
224
- * job with no org, or an unknown job/org. Called AFTER the terminal status commits, like the webhook
241
+ * job with no org, an unknown job/org, or a status the kind's `jobNotify` setting does not notify (checked before
242
+ * the org is read, so a kind that opts out costs no `listMembers` call, the IdP call in real mode). Called AFTER the terminal status commits, like the webhook
225
243
  * emission beside it.
226
244
  */
227
245
  export async function notifyJobTerminal(
@@ -236,15 +254,39 @@ export async function notifyJobTerminal(
236
254
  try {
237
255
  const job = await jobKindAndOrg(deps.db, input.tenantId, input.jobId)
238
256
  if (!job || job.orgId === null || !NOTIFIED_JOB_KINDS.has(job.kind)) return
257
+ if (!notifiesOn(notifyModeFor(job.kind), input.status)) return
239
258
  const org = await orgForId(deps.db, job.orgId)
240
259
  if (!org) return
241
260
  const members = await authPort.listMembers(org.slug)
242
- await notifyAdmins(deps, {
243
- members,
261
+ const payload = { jobId: input.jobId, jobKind: job.kind, status: input.status }
262
+ if (members.some((m) => m.status === 'active' && canManageOrg(m.role as Role))) {
263
+ await notifyAdmins(deps, {
264
+ members,
265
+ tenantId: input.tenantId,
266
+ orgId: job.orgId,
267
+ kind: 'job.completed',
268
+ payload,
269
+ })
270
+ return
271
+ }
272
+ if (!job.requestedBy) return
273
+ // Read afresh, like a credential: someone removed from the org, or barred, is told nothing more.
274
+ const requester = await authPort.getMember(org.slug, job.requestedBy)
275
+ if (!requester) return
276
+ const recipient: Membership = {
277
+ id: job.requestedBy,
278
+ name: requester.name ?? null,
279
+ email: requester.email ?? '',
280
+ role: requester.role,
281
+ status: 'active',
282
+ }
283
+ await notifyMember(deps, {
284
+ members: [recipient],
244
285
  tenantId: input.tenantId,
245
286
  orgId: job.orgId,
287
+ recipientUserId: recipient.id,
246
288
  kind: 'job.completed',
247
- payload: { jobId: input.jobId, jobKind: job.kind, status: input.status },
289
+ payload,
248
290
  })
249
291
  } catch {
250
292
  // Swallowed by design — see above.
@@ -53,7 +53,7 @@ function mockServerOnlyWorld(): void {
53
53
  vi.doMock('../../adapters/index', async () => ({
54
54
  [MOCK_MARK]: true,
55
55
  isSimulated: true,
56
- auth: (await import('../../adapters/fake/auth')).fakeAuth,
56
+ auth: (await import('../../adapters/fake/simulated-auth')).simulatedAuth(),
57
57
  db: (await import('../../adapters/fake/db')).fakeDb,
58
58
  email: (await import('../../adapters/fake/email')).fakeEmail,
59
59
  analytics: (await import('../../adapters/fake/analytics')).fakeAnalytics,
@@ -262,7 +262,7 @@ async function replayEveryPreset(own: ScratchWorld): Promise<void> {
262
262
  const { presets } = await registries()
263
263
  const { expandPreset } = await import('../../core/presets')
264
264
  const { applyDemoPreset } = await import('../../server-lib/demo-presets')
265
- const { fakeAuth } = await import('../../adapters/fake/auth')
265
+ const auth = (await import('../../adapters/fake/simulated-auth')).simulatedAuth()
266
266
  const { readActorHolds } = await import('../../adapters/fake/simulator')
267
267
  for (const preset of presets) {
268
268
  // What replays is the EXPANDED preset (`extends` chain flattened): a child's inherited invites
@@ -282,14 +282,14 @@ async function replayEveryPreset(own: ScratchWorld): Promise<void> {
282
282
  expect(readActorHolds(), `${preset.id}: actor holds`).toEqual(expectedHolds)
283
283
  for (const operation of expanded.operations) {
284
284
  if (operation.op !== 'invite') continue
285
- const members = await fakeAuth.listMembers(operation.org)
285
+ const members = await auth.listMembers(operation.org)
286
286
  expect(
287
287
  members.some((member) => member.status === 'invited' && member.email === operation.email),
288
288
  `${preset.id}: invite to ${operation.email}`,
289
289
  ).toBe(true)
290
290
  }
291
291
  if (expanded.viewpoint !== undefined) {
292
- expect((await fakeAuth.getCurrentUser())?.id, preset.id).toBe(expanded.viewpoint)
292
+ expect((await auth.getCurrentUser())?.id, preset.id).toBe(expanded.viewpoint)
293
293
  }
294
294
  }
295
295
  }