@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.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/auth-tenancy.ts +157 -0
- package/src/adapters/configured-auth.ts +203 -0
- package/src/adapters/fake/atomic-write.ts +1 -1
- package/src/adapters/fake/auth.ts +35 -1
- package/src/adapters/fake/jobs.ts +5 -4
- package/src/adapters/fake/simulated-auth.ts +30 -0
- package/src/adapters/index.ts +3 -2
- package/src/adapters/real/account-refused-form.tsx +32 -0
- package/src/adapters/real/auth.ts +76 -7
- package/src/adapters/real/index.ts +23 -3
- package/src/adapters/real/rds-data-dialect.ts +118 -1
- package/src/adapters/real/rds-data-emulator.ts +35 -1
- package/src/authz/authorize.ts +4 -1
- package/src/components/auth/account-refused.tsx +53 -0
- package/src/core/abilities.ts +22 -6
- package/src/core/jobs.ts +17 -0
- package/src/core/roles.ts +17 -2
- package/src/cutover/rows.json +4 -0
- package/src/db/family.ts +1 -1
- package/src/db/jobs.ts +17 -5
- package/src/db/migrations/0017_job_requester.ts +20 -0
- package/src/db/migrations/index.ts +2 -0
- package/src/db/org-lookup.ts +18 -0
- package/src/db/schema.ts +2 -0
- package/src/demo-static/contracts.ts +9 -0
- package/src/demo-static/rows.ts +2 -0
- package/src/demo-static/world.ts +22 -4
- package/src/guide.md +26 -0
- package/src/i18n/messages/en.json +5 -1
- package/src/i18n/messages/es.json +5 -1
- package/src/ports/auth.ts +26 -1
- package/src/server-lib/notify.ts +51 -9
- package/src/testing/conformance/auth-provider.ts +1 -0
- package/src/testing/conformance/demo-presets.ts +4 -4
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({
|
|
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
|
|
285
|
-
|
|
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/org-lookup.ts
CHANGED
|
@@ -102,3 +102,21 @@ export async function listOrgsInTenant(
|
|
|
102
102
|
.orderBy('name', 'asc')
|
|
103
103
|
.execute()
|
|
104
104
|
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* An org's display name, by its tenant's slug and its own: the same RLS-free raw read of the `organizations` infra
|
|
108
|
+
* table as the lookups above. The auth port's fixed org source names its home org with it (`listMyOrgs`), since the
|
|
109
|
+
* port knows the org only by slug. Null when the tenant has no such org.
|
|
110
|
+
*/
|
|
111
|
+
export async function orgNameForSlugs(db: DbPort, tenantSlug: string, orgSlug: string): Promise<string | null> {
|
|
112
|
+
await db.ready()
|
|
113
|
+
const row = await db
|
|
114
|
+
.getDb()
|
|
115
|
+
.selectFrom('organizations')
|
|
116
|
+
.innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
|
|
117
|
+
.select('organizations.name as name')
|
|
118
|
+
.where('tenants.slug', '=', tenantSlug)
|
|
119
|
+
.where('organizations.slug', '=', orgSlug)
|
|
120
|
+
.executeTakeFirst()
|
|
121
|
+
return row?.name ?? null
|
|
122
|
+
}
|
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:
|
package/src/demo-static/rows.ts
CHANGED
|
@@ -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
|
package/src/demo-static/world.ts
CHANGED
|
@@ -226,7 +226,13 @@ function seededMail(initial: DemoWorldOptions['initialMail']): MailItem[] {
|
|
|
226
226
|
}
|
|
227
227
|
|
|
228
228
|
export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
|
|
229
|
-
const {
|
|
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
|
|
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
|
-
|
|
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,22 @@ 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.
|
|
126
|
+
- Under a fixed org source (`params.auth.orgSource` `'fixed'`) everyone has the role `none` or `restricted`, and both
|
|
127
|
+
are restricted (`AuthUser.restricted` and the actor's `restricted`), so `restricted` cannot tell your own admins from
|
|
128
|
+
anyone else. Grant your own people from your own data (a field on the subject, such as its publishers; your own table
|
|
129
|
+
in a route or screen) BEFORE any denial on `restricted`, in `appAbilityRules` and wherever a route or screen reads
|
|
130
|
+
`user.restricted`: a check that denies on `restricted` first locks out everyone, your own admins included. Key that
|
|
131
|
+
grant on `actor.userId`, never an email, which another product on a shared instance may let anyone claim. Every
|
|
132
|
+
person credential reaches your rules (a token, an inbound email: the same `userId`), so a grant meant for the person
|
|
133
|
+
at the keyboard also checks `actor.credential?.kind === 'session'`. Your rules see `none` in no org (`sameOrg` is
|
|
134
|
+
false), so a grant that must be scoped to the home org needs `defaultRole: 'restricted'`.
|
|
109
135
|
|
|
110
136
|
## UI
|
|
111
137
|
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
"mfaNotImplemented": "This account requires MFA, which arrives with a later slice.",
|
|
16
16
|
"userMenuLabel": "{name}, account menu",
|
|
17
17
|
"profileLink": "Profile",
|
|
18
|
-
"signOut": "Sign out"
|
|
18
|
+
"signOut": "Sign out",
|
|
19
|
+
"refusedTitle": "This account belongs to another site",
|
|
20
|
+
"refusedBody": "You are signed in, but your account is registered with another site that uses the same sign-in, so it cannot be used here.",
|
|
21
|
+
"refusedSignOutNote": "Signing out here also signs you out of any other site that shares this sign-in.",
|
|
22
|
+
"refusedSignOutError": "You could not be signed out. Try again."
|
|
19
23
|
},
|
|
20
24
|
"profile": {
|
|
21
25
|
"title": "Your profile",
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
"mfaNotImplemented": "Esta cuenta requiere MFA, que llegará en una fase posterior.",
|
|
16
16
|
"userMenuLabel": "{name}, menú de la cuenta",
|
|
17
17
|
"profileLink": "Perfil",
|
|
18
|
-
"signOut": "Cerrar sesión"
|
|
18
|
+
"signOut": "Cerrar sesión",
|
|
19
|
+
"refusedTitle": "Esta cuenta pertenece a otro sitio",
|
|
20
|
+
"refusedBody": "Has iniciado sesión, pero tu cuenta está registrada en otro sitio que usa el mismo inicio de sesión, así que no se puede usar aquí.",
|
|
21
|
+
"refusedSignOutNote": "Al cerrar sesión aquí también la cierras en cualquier otro sitio que comparta este inicio de sesión.",
|
|
22
|
+
"refusedSignOutError": "No se pudo cerrar la sesión. Inténtalo de nuevo."
|
|
19
23
|
},
|
|
20
24
|
"profile": {
|
|
21
25
|
"title": "Tu perfil",
|
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). */
|
|
@@ -70,6 +79,15 @@ export interface CreatedInvite extends Membership {
|
|
|
70
79
|
acceptUrl: string | null
|
|
71
80
|
}
|
|
72
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Why a person the identity provider has signed in is not a user here. `other-tenant`: their account names another
|
|
84
|
+
* tenant under the deployment's metadata key, or holds there something that is not a slug (a single tenancy's guard),
|
|
85
|
+
* so it is taken to belong to another site.
|
|
86
|
+
*/
|
|
87
|
+
export interface AuthRefusal {
|
|
88
|
+
reason: 'other-tenant'
|
|
89
|
+
}
|
|
90
|
+
|
|
73
91
|
/**
|
|
74
92
|
* Server-side auth port (ADR-0003). Sized to what the app needs — never to Clerk's API.
|
|
75
93
|
* The custom Mantine auth UI is the ONLY auth UI; both adapters sit behind it.
|
|
@@ -103,4 +121,11 @@ export interface AuthPort {
|
|
|
103
121
|
listMyOrgs(): Promise<OrgRef[]>
|
|
104
122
|
/** @throws ForbiddenError when the user has no membership in that org */
|
|
105
123
|
setActiveOrg(orgSlug: string): Promise<void>
|
|
124
|
+
/**
|
|
125
|
+
* Why the person signed in to the identity provider on this request is refused here, or null when nobody is
|
|
126
|
+
* signed in or nobody is refused: what tells a refused person apart from a signed-out one, which `getCurrentUser`
|
|
127
|
+
* answers alike (null). Optional: only a port that refuses people has it (a single tenancy's guard). The sign-in
|
|
128
|
+
* page reads it to say why, and to offer an explicit sign-out (`@sssb/kit/components/auth/account-refused`).
|
|
129
|
+
*/
|
|
130
|
+
refusal?(): Promise<AuthRefusal | null>
|
|
106
131
|
}
|
package/src/server-lib/notify.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import
|
|
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
|
|
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
|
-
*
|
|
221
|
-
*
|
|
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,
|
|
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
|
-
|
|
243
|
-
|
|
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
|
|
289
|
+
payload,
|
|
248
290
|
})
|
|
249
291
|
} catch {
|
|
250
292
|
// Swallowed by design — see above.
|
|
@@ -31,6 +31,7 @@ import type { CheckImpl } from './types'
|
|
|
31
31
|
const FORMS: ReadonlySet<string> = new Set([
|
|
32
32
|
'@sssb/kit/adapters/real/sign-in-form',
|
|
33
33
|
'@sssb/kit/adapters/real/accept-invite-form',
|
|
34
|
+
'@sssb/kit/adapters/real/account-refused-form',
|
|
34
35
|
])
|
|
35
36
|
const PROVIDER = '@sssb/kit/adapters/real/providers'
|
|
36
37
|
/**
|
|
@@ -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')).
|
|
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
|
|
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
|
|
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
|
|
292
|
+
expect((await auth.getCurrentUser())?.id, preset.id).toBe(expanded.viewpoint)
|
|
293
293
|
}
|
|
294
294
|
}
|
|
295
295
|
}
|