@sssb/kit 0.0.0 → 0.3.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/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +212 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +313 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +248 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +93 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +464 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/same-origin-path.ts +20 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1480 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +132 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +69 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +57 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { getTranslations } from 'next-intl/server'
|
|
2
|
+
import { analytics, auth, db, email } from '../adapters/index'
|
|
3
|
+
import type { Locale } from '../core/locale'
|
|
4
|
+
import type { Role } from '../core/roles'
|
|
5
|
+
import { recordAuditEvent } from '../db/audit'
|
|
6
|
+
import { sendTemplate } from '../email/send'
|
|
7
|
+
import { InviteEmail } from '../email/templates/invite-email'
|
|
8
|
+
import type { Membership } from '../ports/auth'
|
|
9
|
+
import { deferAfterResponse } from './defer'
|
|
10
|
+
import { notifyAdmins } from './notify'
|
|
11
|
+
import { makeNotifyDeps } from './notify-deps'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Inviting someone to a team, AFTER the caller has decided it may happen: mint the invite, audit it,
|
|
15
|
+
* mail the invitee their accept link, record the analytics event, and tell the team's other admins.
|
|
16
|
+
*
|
|
17
|
+
* Authorization, validation and the duplicate check stay with the CALLER, because they differ by
|
|
18
|
+
* caller: the org route authorizes the signed-in session and answers 400/409, while a demo preset's
|
|
19
|
+
* replay (./demo-presets.ts) has no session at all and was held to the same rules at build time
|
|
20
|
+
* (@sssb/kit/core/presets.ts `presetProblems`). What happens once an invite is allowed does not differ, so
|
|
21
|
+
* it lives here once — a preset that re-implemented it would be a second invite flow, free to drift.
|
|
22
|
+
*/
|
|
23
|
+
export async function sendOrgInvite(input: {
|
|
24
|
+
/** Who is inviting: named in the email, excluded from the admins' notification, and the audit actor. */
|
|
25
|
+
inviter: { id: string; name: string; locale: Locale }
|
|
26
|
+
tenantSlug: string
|
|
27
|
+
tenantId: string
|
|
28
|
+
orgId: string
|
|
29
|
+
orgSlug: string
|
|
30
|
+
orgName: string
|
|
31
|
+
email: string
|
|
32
|
+
role: Role
|
|
33
|
+
/** The org's current members (the caller already fetched them for its duplicate check). */
|
|
34
|
+
members: Membership[]
|
|
35
|
+
/** Any absolute URL on this host; the accept link is built against its origin. */
|
|
36
|
+
baseUrl: string
|
|
37
|
+
}): Promise<Membership> {
|
|
38
|
+
const membership = await auth.createInvite({ email: input.email, role: input.role, orgSlug: input.orgSlug })
|
|
39
|
+
|
|
40
|
+
// Audit trail: the invite is the audited mutation — a Membership was created.
|
|
41
|
+
await recordAuditEvent(db, {
|
|
42
|
+
tenantId: input.tenantId,
|
|
43
|
+
orgId: input.orgId,
|
|
44
|
+
actorUserId: input.inviter.id,
|
|
45
|
+
action: 'membership.invited',
|
|
46
|
+
subjectType: 'Membership',
|
|
47
|
+
subjectId: membership.id,
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
const acceptUrl = new URL(
|
|
51
|
+
`/${input.inviter.locale}/accept-invite?invite=${membership.id}`,
|
|
52
|
+
input.baseUrl,
|
|
53
|
+
).toString()
|
|
54
|
+
// The invitee has no account (and so no locale) yet — the inviter's locale is the best available
|
|
55
|
+
// signal for the email copy (ADR-0008).
|
|
56
|
+
const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
|
|
57
|
+
// Deferred: the notification email is a post-response side effect — a slow mail provider must never
|
|
58
|
+
// add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
|
|
59
|
+
// Simulator events); real mode sends it via Next's after().
|
|
60
|
+
await deferAfterResponse('invite-email', () =>
|
|
61
|
+
sendTemplate(email, {
|
|
62
|
+
to: input.email,
|
|
63
|
+
subject: t('inviteSubject', { org: input.orgName }),
|
|
64
|
+
template: InviteEmail({
|
|
65
|
+
labels: {
|
|
66
|
+
preview: t('invitePreview', { org: input.orgName }),
|
|
67
|
+
heading: t('inviteHeading', { org: input.orgName }),
|
|
68
|
+
body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
|
|
69
|
+
button: t('inviteButton'),
|
|
70
|
+
linkFallback: t('inviteLinkFallback'),
|
|
71
|
+
},
|
|
72
|
+
acceptUrl,
|
|
73
|
+
}),
|
|
74
|
+
}),
|
|
75
|
+
)
|
|
76
|
+
await analytics.capture('org_invite_sent', { tenant: input.tenantSlug, org: input.orgSlug, role: input.role })
|
|
77
|
+
|
|
78
|
+
// Notification fan-out: tell the inviting team's OTHER admins that an invite went out. The invitee
|
|
79
|
+
// has no account yet, so they can't hold an in-app row — the admins are the demoable recipients
|
|
80
|
+
// (see the decision log). The inviter is excluded so they aren't notified of their own action.
|
|
81
|
+
// After-commit, like the audit.
|
|
82
|
+
await notifyAdmins(await makeNotifyDeps(), {
|
|
83
|
+
members: input.members,
|
|
84
|
+
tenantId: input.tenantId,
|
|
85
|
+
orgId: input.orgId,
|
|
86
|
+
kind: 'org.invited',
|
|
87
|
+
payload: { email: input.email, role: input.role, orgName: input.orgName },
|
|
88
|
+
excludeUserId: input.inviter.id,
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
return membership
|
|
92
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { db, email, isSimulated } from '../adapters/index'
|
|
2
|
+
import type { NotifyDeps } from './notify'
|
|
3
|
+
import { sendSms } from './sms'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build the notification fan-out's injected dependencies for a request path (routes call this; the fake
|
|
7
|
+
* job executor assembles its own deps from the fake adapters directly, to stay off the @/adapters cycle).
|
|
8
|
+
* In simulated mode it wires the person-locale resolver so demo emails/SMS render in the recipient's
|
|
9
|
+
* language; in real mode `resolveLocale` is omitted and copy falls back to the app default (the auth
|
|
10
|
+
* port exposes no per-user locale — a noted simplification, see the decision log).
|
|
11
|
+
*/
|
|
12
|
+
export async function makeNotifyDeps(): Promise<NotifyDeps> {
|
|
13
|
+
const resolveLocale = isSimulated ? (await import('../adapters/fake/auth')).personLocale : undefined
|
|
14
|
+
return { db, email, sms: sendSms, resolveLocale }
|
|
15
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { appJobKinds } from '@sssb/app-config/jobs'
|
|
2
|
+
import { getTranslations } from 'next-intl/server'
|
|
3
|
+
import { DEFAULT_LOCALE, type Locale } from '../core/locale'
|
|
4
|
+
import {
|
|
5
|
+
FRAMEWORK_NOTIFICATION_NAMESPACE,
|
|
6
|
+
type NotificationKind,
|
|
7
|
+
type NotificationPayload,
|
|
8
|
+
notificationCopy,
|
|
9
|
+
resolveEnabledChannels,
|
|
10
|
+
} from '../core/notifications'
|
|
11
|
+
import { canManageOrg, type Role } from '../core/roles'
|
|
12
|
+
import { jobKindAndOrg } from '../db/jobs'
|
|
13
|
+
import { insertNotification, readPrefRows } from '../db/notifications'
|
|
14
|
+
import { orgForId } from '../db/org-lookup'
|
|
15
|
+
import { sendTemplate } from '../email/send'
|
|
16
|
+
import { NotificationEmail } from '../email/templates/notification-email'
|
|
17
|
+
import type { AuthPort, Membership } from '../ports/auth'
|
|
18
|
+
import type { DbPort } from '../ports/db'
|
|
19
|
+
import type { EmailPort } from '../ports/email'
|
|
20
|
+
import { deferAfterResponse } from './defer'
|
|
21
|
+
import type { SmsChannel } from './sms'
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The notification FAN-OUT seam — app-owned server machinery, NOT a vendor port (the same
|
|
25
|
+
* settlement as webhook-dispatch: no vendor SDK is involved; in_app is the db, email is the existing
|
|
26
|
+
* port, sms is the app-owned channel seam). It reads the recipient's prefs, resolves the enabled
|
|
27
|
+
* channels via the PURE core resolver (shared verbatim with the twin), and fans out with PER-CHANNEL
|
|
28
|
+
* FAULT ISOLATION: in_app is written synchronously so the header bell is durable before the response,
|
|
29
|
+
* while email and sms ride deferAfterResponse (post-response in real mode, inline in simulated mode) — which
|
|
30
|
+
* already swallows-and-records failures, so a dead mail provider can never lose the in_app row or block
|
|
31
|
+
* the sms. Producers (the invite / app mutation routes, the job-terminal sites) call this AFTER their own
|
|
32
|
+
* mutation commits, the same after-commit posture as the audit and webhook emissions beside them.
|
|
33
|
+
*
|
|
34
|
+
* Dependencies are INJECTED (db/email/sms + an optional locale resolver) — the runDueSchedules(db, jobs)
|
|
35
|
+
* precedent — so the same code is exercised by unit tests with fakes; the twin re-implements the fan-out
|
|
36
|
+
* in-memory over the shared core resolver rather than importing this server module.
|
|
37
|
+
*/
|
|
38
|
+
export interface NotifyDeps {
|
|
39
|
+
db: DbPort
|
|
40
|
+
email: EmailPort
|
|
41
|
+
sms: SmsChannel
|
|
42
|
+
/**
|
|
43
|
+
* Optional simulated-mode enrichment: resolve a recipient's preferred locale so their email/SMS render
|
|
44
|
+
* in their language (the digest-email precedent). The auth port's Membership carries no
|
|
45
|
+
* locale, so real mode omits this and copy falls back to the app default — a noted simplification a
|
|
46
|
+
* real instance closes by enriching from its IdP. Never affects in_app (rendered client-side).
|
|
47
|
+
*/
|
|
48
|
+
resolveLocale?: ((userId: string) => Locale | undefined) | undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface NotifyInput {
|
|
52
|
+
tenantId: string
|
|
53
|
+
orgId: string
|
|
54
|
+
recipientUserId: string
|
|
55
|
+
/** The recipient's email — required to address the `email` channel; absent = skip email. */
|
|
56
|
+
recipientEmail?: string
|
|
57
|
+
/** A display name for the `to` line of the fake SMS (people carry no phone number). */
|
|
58
|
+
recipientName?: string
|
|
59
|
+
kind: NotificationKind
|
|
60
|
+
payload: NotificationPayload
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Fan ONE notification out to one recipient across their enabled channels (per-channel isolated).
|
|
65
|
+
* INTERNAL — producers call the higher-level `notifyAdmins` / `notifyJobTerminal` below; a
|
|
66
|
+
* single-known-recipient producer would export this then.
|
|
67
|
+
*/
|
|
68
|
+
async function notify(deps: NotifyDeps, input: NotifyInput): Promise<void> {
|
|
69
|
+
const prefs = await readPrefRows(deps.db, input.tenantId, input.orgId, input.recipientUserId)
|
|
70
|
+
const channels = resolveEnabledChannels(prefs, input.kind)
|
|
71
|
+
|
|
72
|
+
// in_app — synchronous + durable (the bell must reflect it immediately). Isolated: a failure here
|
|
73
|
+
// is swallowed so it never crashes the producer, and it never depends on email/sms succeeding.
|
|
74
|
+
if (channels.includes('in_app')) {
|
|
75
|
+
try {
|
|
76
|
+
await insertNotification(deps.db, {
|
|
77
|
+
tenantId: input.tenantId,
|
|
78
|
+
orgId: input.orgId,
|
|
79
|
+
recipientUserId: input.recipientUserId,
|
|
80
|
+
kind: input.kind,
|
|
81
|
+
payload: input.payload,
|
|
82
|
+
})
|
|
83
|
+
} catch {
|
|
84
|
+
// The durable channel failing must not lose the deferred channels or crash the request.
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const copy = notificationCopy(input.kind, input.payload)
|
|
89
|
+
const locale = deps.resolveLocale?.(input.recipientUserId) ?? DEFAULT_LOCALE
|
|
90
|
+
|
|
91
|
+
// email — deferred (a slow provider must not add request latency); deferAfterResponse isolates
|
|
92
|
+
// failures. Skipped when the recipient has no address to send to.
|
|
93
|
+
if (channels.includes('email') && input.recipientEmail) {
|
|
94
|
+
const to = input.recipientEmail
|
|
95
|
+
await deferAfterResponse(`notify-email:${input.kind}`, async () => {
|
|
96
|
+
// Root translator, not a namespace-scoped one: an APP kind's copy lives in the app's own
|
|
97
|
+
// catalog, so the namespace comes from the copy itself (core/notifications.ts).
|
|
98
|
+
const t = await getTranslations({ locale })
|
|
99
|
+
const ns = copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE
|
|
100
|
+
await sendTemplate(deps.email, {
|
|
101
|
+
to,
|
|
102
|
+
subject: t(`${ns}.${copy.subjectKey}`, copy.values),
|
|
103
|
+
template: NotificationEmail({
|
|
104
|
+
labels: {
|
|
105
|
+
preview: t(`${ns}.${copy.titleKey}`, copy.values),
|
|
106
|
+
heading: t(`${ns}.${copy.titleKey}`, copy.values),
|
|
107
|
+
body: t(`${ns}.${copy.bodyKey}`, copy.values),
|
|
108
|
+
footer: t(`${FRAMEWORK_NOTIFICATION_NAMESPACE}.emailFooter`),
|
|
109
|
+
},
|
|
110
|
+
}),
|
|
111
|
+
})
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// sms — the fake channel (a recipe adds Twilio). Deferred + isolated like email.
|
|
116
|
+
if (channels.includes('sms')) {
|
|
117
|
+
const to = input.recipientName ?? input.recipientEmail ?? input.recipientUserId
|
|
118
|
+
await deferAfterResponse(`notify-sms:${input.kind}`, async () => {
|
|
119
|
+
const t = await getTranslations({ locale })
|
|
120
|
+
const ns = copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE
|
|
121
|
+
await deps.sms({
|
|
122
|
+
to,
|
|
123
|
+
body: t(`${ns}.${copy.smsKey}`, copy.values),
|
|
124
|
+
kind: input.kind,
|
|
125
|
+
recipientUserId: input.recipientUserId,
|
|
126
|
+
})
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Fan a notification out to every ADMIN of an org (the recipient decision for org.invited / job.completed
|
|
133
|
+
* and the app's own admin-addressed kinds — see the decision log). `members` is the auth port's
|
|
134
|
+
* listMembers result for
|
|
135
|
+
* the org; admins are its ACTIVE, org-managing members (canManageOrg). `excludeUserId` drops the actor
|
|
136
|
+
* so an inviter isn't told about their own invite. Each admin is notified independently — one bad
|
|
137
|
+
* recipient never stalls the rest (the fan-out already isolates per channel).
|
|
138
|
+
*/
|
|
139
|
+
export async function notifyAdmins(
|
|
140
|
+
deps: NotifyDeps,
|
|
141
|
+
input: {
|
|
142
|
+
members: Membership[]
|
|
143
|
+
tenantId: string
|
|
144
|
+
orgId: string
|
|
145
|
+
kind: NotificationKind
|
|
146
|
+
payload: NotificationPayload
|
|
147
|
+
excludeUserId?: string
|
|
148
|
+
},
|
|
149
|
+
): Promise<number> {
|
|
150
|
+
const admins = input.members.filter(
|
|
151
|
+
(m) => m.status === 'active' && canManageOrg(m.role as Role) && m.id !== input.excludeUserId,
|
|
152
|
+
)
|
|
153
|
+
// Best-effort per recipient: producers call this AFTER their mutation committed, so a notify
|
|
154
|
+
// failure (a prefs read, even the durable insert) must neither 500 a succeeded action nor
|
|
155
|
+
// stall the remaining admins — allSettled keeps that isolation while the admins' independent
|
|
156
|
+
// prefs-read + insert pairs run concurrently instead of serially in the request path.
|
|
157
|
+
const results = await Promise.allSettled(
|
|
158
|
+
admins.map((admin) =>
|
|
159
|
+
notify(deps, {
|
|
160
|
+
tenantId: input.tenantId,
|
|
161
|
+
orgId: input.orgId,
|
|
162
|
+
recipientUserId: admin.id,
|
|
163
|
+
recipientEmail: admin.email,
|
|
164
|
+
recipientName: admin.name ?? admin.email,
|
|
165
|
+
kind: input.kind,
|
|
166
|
+
payload: input.payload,
|
|
167
|
+
}),
|
|
168
|
+
),
|
|
169
|
+
)
|
|
170
|
+
return results.filter((result) => result.status === 'fulfilled').length
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Fan a notification out to ONE named member of an org — the recipient decision for a kind that is
|
|
175
|
+
* addressed to a person rather than to whoever happens to manage the team — being handed a piece of
|
|
176
|
+
* work is news for the person it was handed to, not for the admins. `members` is the auth port's
|
|
177
|
+
* listMembers result; the recipient must be ACTIVE, and
|
|
178
|
+
* `excludeUserId` drops the actor so assigning something to yourself does not notify you about it.
|
|
179
|
+
*
|
|
180
|
+
* Returns whether anyone was reached, so a producer can tell "no such member" from "notified".
|
|
181
|
+
*/
|
|
182
|
+
export async function notifyMember(
|
|
183
|
+
deps: NotifyDeps,
|
|
184
|
+
input: {
|
|
185
|
+
members: Membership[]
|
|
186
|
+
tenantId: string
|
|
187
|
+
orgId: string
|
|
188
|
+
recipientUserId: string
|
|
189
|
+
kind: NotificationKind
|
|
190
|
+
payload: NotificationPayload
|
|
191
|
+
excludeUserId?: string
|
|
192
|
+
},
|
|
193
|
+
): Promise<boolean> {
|
|
194
|
+
if (input.recipientUserId === input.excludeUserId) return false
|
|
195
|
+
const member = input.members.find((m) => m.status === 'active' && m.id === input.recipientUserId)
|
|
196
|
+
if (!member) return false
|
|
197
|
+
try {
|
|
198
|
+
await notify(deps, {
|
|
199
|
+
tenantId: input.tenantId,
|
|
200
|
+
orgId: input.orgId,
|
|
201
|
+
recipientUserId: member.id,
|
|
202
|
+
recipientEmail: member.email,
|
|
203
|
+
recipientName: member.name ?? member.email,
|
|
204
|
+
kind: input.kind,
|
|
205
|
+
payload: input.payload,
|
|
206
|
+
})
|
|
207
|
+
return true
|
|
208
|
+
} catch {
|
|
209
|
+
// Same posture as notifyAdmins: the notification layer is never load-bearing for the request.
|
|
210
|
+
return false
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Job kinds whose terminal state notifies the team. The app's OWN job kinds (appJobKinds,
|
|
215
|
+
* the seam) are user-submitted work someone is waiting on; the framework's scheduled kinds (e.g.
|
|
216
|
+
* digest-email) are internal machinery and would just be noise (see the decision log). */
|
|
217
|
+
const NOTIFIED_JOB_KINDS = new Set<string>(appJobKinds)
|
|
218
|
+
|
|
219
|
+
/**
|
|
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
|
|
222
|
+
* kind + org itself from (tenantId, jobId) so both terminal sites — the fake in-process executor and
|
|
223
|
+
* 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
|
|
225
|
+
* emission beside it.
|
|
226
|
+
*/
|
|
227
|
+
export async function notifyJobTerminal(
|
|
228
|
+
deps: NotifyDeps,
|
|
229
|
+
authPort: AuthPort,
|
|
230
|
+
input: { tenantId: string; jobId: string; status: 'completed' | 'failed' },
|
|
231
|
+
): Promise<void> {
|
|
232
|
+
// Best-effort end to end: this path adds an EXTERNAL failure surface (listMembers is a real IdP
|
|
233
|
+
// call in real mode) after the terminal status already committed — a throw here would 500 the
|
|
234
|
+
// completion webhook into a vendor retry that then no-ops as idempotent, silently losing the
|
|
235
|
+
// notification AND lying to the vendor. Swallow instead; the job outcome itself is already durable.
|
|
236
|
+
try {
|
|
237
|
+
const job = await jobKindAndOrg(deps.db, input.tenantId, input.jobId)
|
|
238
|
+
if (!job || job.orgId === null || !NOTIFIED_JOB_KINDS.has(job.kind)) return
|
|
239
|
+
const org = await orgForId(deps.db, job.orgId)
|
|
240
|
+
if (!org) return
|
|
241
|
+
const members = await authPort.listMembers(org.slug)
|
|
242
|
+
await notifyAdmins(deps, {
|
|
243
|
+
members,
|
|
244
|
+
tenantId: input.tenantId,
|
|
245
|
+
orgId: job.orgId,
|
|
246
|
+
kind: 'job.completed',
|
|
247
|
+
payload: { jobId: input.jobId, jobKind: job.kind, status: input.status },
|
|
248
|
+
})
|
|
249
|
+
} catch {
|
|
250
|
+
// Swallowed by design — see above.
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { organizations, people } from '@sssb/app-config/seed'
|
|
2
|
+
import { auth, db } from '../adapters/index'
|
|
3
|
+
import { KNOWN_FLAGS, setFlag } from '../adapters/fake/analytics'
|
|
4
|
+
import { setActorHold } from '../adapters/fake/simulator'
|
|
5
|
+
import { DEMO_INBOUND_DOMAIN, formatInboundRecipient } from '../core/inbound-email'
|
|
6
|
+
import type { ActorHoldArgs, FlagArgs, FrameworkPresetOperation, InboundArgs, InviteArgs } from '../core/presets'
|
|
7
|
+
import { orgIdForSlug } from '../db/org-lookup'
|
|
8
|
+
import { tenantIdForSlug } from '../db/tenant-lookup'
|
|
9
|
+
import { intakeInboundEmail } from '../inbound-email/intake'
|
|
10
|
+
import { ForbiddenError, NotFoundError } from '../ports/errors'
|
|
11
|
+
import { sendOrgInvite } from './invite'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The SERVER halves of SSSB's own demo-preset operation kinds (@sssb/kit/core/presets.ts) — what `invite`,
|
|
15
|
+
* `inbound`, `flag` and `actor.hold` DO when the server replays a preset, through the same server code the product
|
|
16
|
+
* runs: `sendOrgInvite` for an invite, the framework intake (and the app's registered handler) for an
|
|
17
|
+
* inbound email, the fake analytics store for a flag, the Simulator's per-actor hold file for `actor.hold`.
|
|
18
|
+
* @sssb/kit/server-lib/demo-presets.ts composes these with
|
|
19
|
+
* the app's halves (`@sssb/app-config/preset-operations`) and dispatches each step to one.
|
|
20
|
+
*
|
|
21
|
+
* Published because an app's own server halves are written against this module: the handler and context
|
|
22
|
+
* types, `resolvePresetOrg` (a preset names a team by slug; the server works in uuids), and these halves
|
|
23
|
+
* themselves, so an app that REPLACES an SSSB kind can wrap SSSB's half rather than copy it. It never
|
|
24
|
+
* imports the seam's `@sssb/app-config/preset-operations`, so an app half importing it closes no cycle.
|
|
25
|
+
*
|
|
26
|
+
* An operation the world cannot perform (a person, team or flag the seed does not have) THROWS rather
|
|
27
|
+
* than being skipped: SSSB's seam-conformance suite already held every registered preset to these rules
|
|
28
|
+
* (`presetProblems`), so reaching one means that gate was bypassed.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** The named results bound so far in this replay (`as` → the id of what that step created). */
|
|
32
|
+
export interface PresetRefs {
|
|
33
|
+
/** The id bound to `name`; throws when no earlier step bound it. */
|
|
34
|
+
resolve(name: string): string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ServerPresetOperationContext {
|
|
38
|
+
/** The request URL the replay was asked for on — where links in emails it sends must point. */
|
|
39
|
+
baseUrl: string
|
|
40
|
+
refs: PresetRefs
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One kind's server half. Returns `{ ref }` — the id of the row it created — when it created one, so a
|
|
45
|
+
* step with `as` can name it; nothing when it did not. Gets its ports from @sssb/kit/adapters/index itself,
|
|
46
|
+
* as server code does.
|
|
47
|
+
*
|
|
48
|
+
* Written as a method type on purpose: method parameters are compared bivariantly, so a half typed for
|
|
49
|
+
* its own kind's arguments fits the `Record<string, ServerPresetOperationHandler>` registry.
|
|
50
|
+
*/
|
|
51
|
+
export type ServerPresetOperationHandler<Args = unknown> = {
|
|
52
|
+
method(args: Args, ctx: ServerPresetOperationContext): Promise<{ ref?: string | undefined } | void>
|
|
53
|
+
}['method']
|
|
54
|
+
|
|
55
|
+
/** A preset names a team by slug (seed vocabulary); the server's writes need its tenant and org uuids. */
|
|
56
|
+
export async function resolvePresetOrg(
|
|
57
|
+
orgSlug: string,
|
|
58
|
+
): Promise<{ tenantId: string; orgId: string; orgName: string; tenantSlug: string }> {
|
|
59
|
+
const org = organizations.find((candidate) => candidate.slug === orgSlug)
|
|
60
|
+
const tenantId = org ? await tenantIdForSlug(db, org.tenantSlug) : null
|
|
61
|
+
const orgId = org && tenantId ? await orgIdForSlug(db, tenantId, orgSlug) : null
|
|
62
|
+
if (!org || !tenantId || !orgId) throw new NotFoundError(`unknown org: ${orgSlug}`)
|
|
63
|
+
return { tenantId, orgId, orgName: org.name, tenantSlug: org.tenantSlug }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const invite: ServerPresetOperationHandler<InviteArgs> = async (args, ctx) => {
|
|
67
|
+
const inviter = people.find((person) => person.id === args.by)
|
|
68
|
+
const { tenantId, orgId, orgName, tenantSlug } = await resolvePresetOrg(args.org)
|
|
69
|
+
if (!inviter) throw new NotFoundError(`unknown person: ${args.by}`)
|
|
70
|
+
// The org route's 409, kept here too: the build-time gate already refuses a duplicate, and refusing it
|
|
71
|
+
// again at replay keeps a bypassed gate from minting a second membership — the static twin refuses it
|
|
72
|
+
// as well (`inviteInto` answers false).
|
|
73
|
+
const members = await auth.listMembers(args.org)
|
|
74
|
+
if (members.some((member) => member.email.toLowerCase() === args.email.toLowerCase())) {
|
|
75
|
+
throw new ForbiddenError(`already a member or invited: ${args.email}`)
|
|
76
|
+
}
|
|
77
|
+
await sendOrgInvite({
|
|
78
|
+
inviter,
|
|
79
|
+
tenantSlug,
|
|
80
|
+
tenantId,
|
|
81
|
+
orgId,
|
|
82
|
+
orgSlug: args.org,
|
|
83
|
+
orgName,
|
|
84
|
+
email: args.email,
|
|
85
|
+
role: args.role,
|
|
86
|
+
members,
|
|
87
|
+
baseUrl: ctx.baseUrl,
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const inbound: ServerPresetOperationHandler<InboundArgs> = async (args) => {
|
|
92
|
+
const outcome = await intakeInboundEmail(db, auth, {
|
|
93
|
+
to: formatInboundRecipient(args.org, args.handler, DEMO_INBOUND_DOMAIN),
|
|
94
|
+
from: args.from,
|
|
95
|
+
subject: args.subject,
|
|
96
|
+
bodyText: args.body,
|
|
97
|
+
})
|
|
98
|
+
// The row the app's handler opened, if it opened one — a declined email names nothing.
|
|
99
|
+
return { ref: outcome.subjectId ?? undefined }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const flag: ServerPresetOperationHandler<FlagArgs> = async (args) => {
|
|
103
|
+
if (!KNOWN_FLAGS.includes(args.flag)) throw new NotFoundError(`unknown flag: ${args.flag}`)
|
|
104
|
+
setFlag(args.flag, args.enabled)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// An actor id the registry lacks is not checked here (the framework does not value-import the app's actor
|
|
108
|
+
// list, ADR-0012): it would write a hold nothing reads, and the seam-conformance gate (`presetProblems`)
|
|
109
|
+
// rejects the preset that names it.
|
|
110
|
+
const actorHold: ServerPresetOperationHandler<ActorHoldArgs> = async (args) => {
|
|
111
|
+
setActorHold(args.actor, args.held)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** SSSB's server halves, by kind — one for every framework kind (`satisfies` makes that exhaustive). An
|
|
115
|
+
* app entry of the same kind replaces one (@sssb/kit/server-lib/demo-presets.ts). */
|
|
116
|
+
export const frameworkPresetOperationHandlers = {
|
|
117
|
+
invite,
|
|
118
|
+
inbound,
|
|
119
|
+
flag,
|
|
120
|
+
'actor.hold': actorHold,
|
|
121
|
+
} satisfies Record<FrameworkPresetOperation['op'], ServerPresetOperationHandler>
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { worldNow } from '../adapters/fake/clock'
|
|
2
|
+
import { db, isSimulated, jobs } from '../adapters/index'
|
|
3
|
+
import { runDueSchedules } from '../db/schedules'
|
|
4
|
+
import { runDueDeliveries } from '../db/webhooks'
|
|
5
|
+
import { dispatchWebhook } from './webhook-dispatch'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The scheduled-work tick: drains every due `job_schedules` row (spawning its job) and every due outbound
|
|
9
|
+
* webhook delivery, and says how many of each. It is the whole body of an app's `/api/webhooks/cron` route, so
|
|
10
|
+
* that route is a three-line wrapper (`withWebhookSecret(async () => Response.json({ ok: true, ...(await
|
|
11
|
+
* runScheduledTick()) }))`) and an app that takes SSSB as a package gets the same behaviour as a fork.
|
|
12
|
+
*
|
|
13
|
+
* Real world: an EventBridge rule POSTs that route on a fixed cadence with the shared secret in `x-sssb-webhook-secret`
|
|
14
|
+
* (cutover row `scheduled-tick`; @sssb/cdk's `SssbApp` does it with `scheduledTick`). Nothing else ticks the scheduler: in `pnpm dev` an app with no Simulator has no
|
|
15
|
+
* tick source until something POSTs the route (docs/adopting-reference.md, "The scheduled tick").
|
|
16
|
+
*
|
|
17
|
+
* "Now" is the trigger source's clock: real time in a real build; in a simulated world the Simulator's world clock
|
|
18
|
+
* (real time plus the offset a demo advanced), so a tick honours a clock the demo moved. `worldNow()` is called
|
|
19
|
+
* only behind `isSimulated`, so that offset is structurally unreachable in a real build.
|
|
20
|
+
*
|
|
21
|
+
* The same tick drains due webhook deliveries: a scheduled digest that spawns a job whose status change
|
|
22
|
+
* enqueues a delivery, and any retry whose backoff has elapsed, both fire from one tick.
|
|
23
|
+
*/
|
|
24
|
+
export interface ScheduledTickResult {
|
|
25
|
+
/** Jobs spawned from due schedules. */
|
|
26
|
+
spawned: number
|
|
27
|
+
/** Due schedules whose spawn failed (retried on the next tick). */
|
|
28
|
+
failed: number
|
|
29
|
+
/** What the delivery drain did (`runDueDeliveries`'s own result). */
|
|
30
|
+
deliveries: Awaited<ReturnType<typeof runDueDeliveries>>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function runScheduledTick(): Promise<ScheduledTickResult> {
|
|
34
|
+
const now = isSimulated ? worldNow() : new Date()
|
|
35
|
+
// A runner that can lose a job mid-run (JOBS_RUNNER=in-process) fails the lost ones first; its own count is not
|
|
36
|
+
// reported here, the failed jobs' errors say it.
|
|
37
|
+
try {
|
|
38
|
+
await jobs.sweep?.(now)
|
|
39
|
+
} catch (error) {
|
|
40
|
+
// A sweep that fails must not stop the schedules and deliveries behind it.
|
|
41
|
+
console.warn(
|
|
42
|
+
`SSSB tick: the jobs port's sweep failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
const { spawned, failed } = await runDueSchedules(db, jobs, now)
|
|
46
|
+
const deliveries = await runDueDeliveries(db, now, dispatchWebhook)
|
|
47
|
+
return { spawned, failed, deliveries }
|
|
48
|
+
}
|