@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,77 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { useSignUp } from '@clerk/nextjs'
|
|
4
|
+
import { Stack, Text } from '@mantine/core'
|
|
5
|
+
import { useEffect, useState } from 'react'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Clerk ticket-strategy sign-up (ADR-0003): at cutover, Clerk organization invitations carry a
|
|
9
|
+
* `__clerk_ticket` query param onto this page's URL instead of the fake email's plain
|
|
10
|
+
* `/accept-invite?invite=<id>` link. sign-in-form.tsx is the reference for the v7 signals API
|
|
11
|
+
* (signIn.password() → status → finalize()) — the sign-up equivalent used here is
|
|
12
|
+
* signUp.ticket() → status → finalize(), per @clerk/shared's SignUpFutureResource.
|
|
13
|
+
*
|
|
14
|
+
* AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance. Verify the full
|
|
15
|
+
* ticket round-trip once a dev Clerk instance issues real invitation tickets (see
|
|
16
|
+
* docs/cutover-checklist.md, `auth-dev` row).
|
|
17
|
+
*
|
|
18
|
+
* Lives in packages/kit/src/adapters because it imports the vendor SDK; the AcceptInviteShell renders it as a
|
|
19
|
+
* slot, and all copy arrives via `labels` from the page's next-intl lookup (same contract as
|
|
20
|
+
* RealSignInForm — one auth UI, no vendor-side strings).
|
|
21
|
+
*/
|
|
22
|
+
export function RealAcceptInviteForm({
|
|
23
|
+
ticket,
|
|
24
|
+
redirectTo,
|
|
25
|
+
labels,
|
|
26
|
+
}: {
|
|
27
|
+
ticket: string | null
|
|
28
|
+
redirectTo: string
|
|
29
|
+
labels: AcceptInviteTicketLabels
|
|
30
|
+
}) {
|
|
31
|
+
const { signUp, fetchStatus } = useSignUp()
|
|
32
|
+
const [error, setError] = useState<string | null>(null)
|
|
33
|
+
const [accepted, setAccepted] = useState(false)
|
|
34
|
+
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (!ticket) return
|
|
37
|
+
// Driving an external SDK call on mount (Clerk's ticket-strategy sign-up) is the
|
|
38
|
+
// legitimate "sync with an external system" case the set-state-in-effect rule guards —
|
|
39
|
+
// same as the Simulator glue's fetch-on-mount effects.
|
|
40
|
+
void (async () => {
|
|
41
|
+
const { error: ticketError } = await signUp.ticket({ ticket })
|
|
42
|
+
if (ticketError) {
|
|
43
|
+
setError(labels.genericError)
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
if (signUp.status === 'complete') {
|
|
47
|
+
const finalized = await signUp.finalize()
|
|
48
|
+
if (finalized.error) {
|
|
49
|
+
setError(labels.genericError)
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
setAccepted(true)
|
|
53
|
+
window.location.assign(redirectTo)
|
|
54
|
+
} else {
|
|
55
|
+
setError(labels.genericError)
|
|
56
|
+
}
|
|
57
|
+
})()
|
|
58
|
+
}, [ticket, signUp, redirectTo, labels.genericError])
|
|
59
|
+
|
|
60
|
+
if (!ticket) return <Text c="gray.7">{labels.missingTicket}</Text>
|
|
61
|
+
|
|
62
|
+
return (
|
|
63
|
+
<Stack gap="sm">
|
|
64
|
+
{!accepted && !error ? (
|
|
65
|
+
<Text c="gray.7">{fetchStatus === 'fetching' ? labels.accepting : labels.oneMoment}</Text>
|
|
66
|
+
) : null}
|
|
67
|
+
{error ? <Text c="red.8">{error}</Text> : null}
|
|
68
|
+
</Stack>
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface AcceptInviteTicketLabels {
|
|
73
|
+
missingTicket: string
|
|
74
|
+
accepting: string
|
|
75
|
+
oneMoment: string
|
|
76
|
+
genericError: string
|
|
77
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { PostHog } from 'posthog-node'
|
|
2
|
+
import type { AnalyticsPort } from '../../ports/analytics'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
|
|
6
|
+
* staging/prod only (ADR-0010); everywhere else the no-op fake is wired even in real mode.
|
|
7
|
+
*/
|
|
8
|
+
export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
|
|
9
|
+
const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
|
|
10
|
+
|
|
11
|
+
return {
|
|
12
|
+
async capture(event, properties, distinctId = 'server') {
|
|
13
|
+
client.capture({ distinctId, event, ...(properties === undefined ? {} : { properties }) })
|
|
14
|
+
},
|
|
15
|
+
|
|
16
|
+
async isFlagEnabled(flag, defaultValue = false) {
|
|
17
|
+
// A flag read is never load-bearing: a PostHog outage degrades to the default rather
|
|
18
|
+
// than throwing into whatever screen asked (the protected layout reads flags on every
|
|
19
|
+
// authenticated render).
|
|
20
|
+
try {
|
|
21
|
+
const enabled = await client.isFeatureEnabled(flag, 'server')
|
|
22
|
+
return enabled ?? defaultValue
|
|
23
|
+
} catch {
|
|
24
|
+
return defaultValue
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { isClerkAPIResponseError } from '@clerk/nextjs/errors'
|
|
2
|
+
import { auth, clerkClient, currentUser } from '@clerk/nextjs/server'
|
|
3
|
+
import { DEFAULT_LOCALE, LOCALES, type Locale } from '../../core/locale'
|
|
4
|
+
import { isRestricted, isRole, type Role } from '../../core/roles'
|
|
5
|
+
import type {
|
|
6
|
+
AuthPort,
|
|
7
|
+
AuthUser,
|
|
8
|
+
InviteInput,
|
|
9
|
+
Membership,
|
|
10
|
+
MemberStanding,
|
|
11
|
+
OrgRef,
|
|
12
|
+
ProfileUpdate,
|
|
13
|
+
} from '../../ports/auth'
|
|
14
|
+
import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Clerk headless adapter (ADR-0003). Clerk organizations ARE our orgs
|
|
18
|
+
* (product copy: "teams"); our org slug === Clerk org slug (no mapping layer). The tenant (site) is
|
|
19
|
+
* ambient and lives in user publicMetadata.tenantSlug — one Clerk instance per tenant in prod, so
|
|
20
|
+
* every org a user sees belongs to their tenant. The ACTIVE org rides in unsafeMetadata.currentOrgSlug,
|
|
21
|
+
* and the request-time role comes from that org membership's publicMetadata.role (role is per-org).
|
|
22
|
+
*
|
|
23
|
+
* AUTHORED — CUTOVER (`auth-dev`): typechecked against @clerk/nextjs, never run against a real
|
|
24
|
+
* Clerk instance. Verify the full port contract suite against the dev instance at cutover.
|
|
25
|
+
* Cutover perf checkpoint: getCurrentUser now issues an extra getOrganizationMembershipList per
|
|
26
|
+
* request to resolve the active-org role — measure and cache if hot.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
interface AppPublicMetadata {
|
|
30
|
+
role?: string
|
|
31
|
+
locale?: string
|
|
32
|
+
restricted?: boolean
|
|
33
|
+
tenantSlug?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function roleFrom(metadata: unknown, fallback: Role): Role {
|
|
37
|
+
const role = (metadata as AppPublicMetadata)?.role
|
|
38
|
+
return role && isRole(role) ? role : fallback
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function organizationIdForSlug(slug: string): Promise<string> {
|
|
42
|
+
const client = await clerkClient()
|
|
43
|
+
const org = await client.organizations.getOrganization({ slug })
|
|
44
|
+
return org.id
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const realAuth: AuthPort = {
|
|
48
|
+
async getCurrentUser(): Promise<AuthUser | null> {
|
|
49
|
+
const { userId } = await auth()
|
|
50
|
+
if (!userId) return null
|
|
51
|
+
const user = await currentUser()
|
|
52
|
+
if (!user) return null
|
|
53
|
+
const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
|
|
54
|
+
const locale = LOCALES.includes(metadata.locale as Locale) ? (metadata.locale as Locale) : DEFAULT_LOCALE
|
|
55
|
+
|
|
56
|
+
// Resolve the active org membership: the remembered currentOrgSlug if still a membership,
|
|
57
|
+
// else the first one. Role comes from that membership (per-org), not the user object.
|
|
58
|
+
const client = await clerkClient()
|
|
59
|
+
const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
|
|
60
|
+
const currentOrgSlug = (user.unsafeMetadata as { currentOrgSlug?: string })?.currentOrgSlug
|
|
61
|
+
const active =
|
|
62
|
+
memberships.data.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ??
|
|
63
|
+
memberships.data[0]
|
|
64
|
+
|
|
65
|
+
const role = roleFrom(active?.publicMetadata, 'guest')
|
|
66
|
+
return {
|
|
67
|
+
id: userId,
|
|
68
|
+
name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
|
|
69
|
+
email: user.primaryEmailAddress?.emailAddress ?? '',
|
|
70
|
+
role,
|
|
71
|
+
locale,
|
|
72
|
+
// Ambient site claim — never the active org's business.
|
|
73
|
+
tenantSlug: metadata.tenantSlug ?? '',
|
|
74
|
+
orgSlug: active ? (active.organization.slug ?? active.organization.id) : '',
|
|
75
|
+
restricted: isRestricted(metadata.restricted, role),
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
async requireUser(): Promise<AuthUser> {
|
|
80
|
+
const user = await this.getCurrentUser()
|
|
81
|
+
if (!user) throw new AuthRequiredError()
|
|
82
|
+
return user
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
async requireRole(...roles: Role[]): Promise<AuthUser> {
|
|
86
|
+
const user = await this.requireUser()
|
|
87
|
+
if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
|
|
88
|
+
return user
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
signInPath(returnTo?: string): string {
|
|
92
|
+
return returnTo ? `/signin?returnTo=${encodeURIComponent(returnTo)}` : '/signin'
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
async signOut(): Promise<void> {
|
|
96
|
+
// Server-side revocation; the client additionally calls Clerk's signOut for local state.
|
|
97
|
+
const { sessionId } = await auth()
|
|
98
|
+
if (!sessionId) return
|
|
99
|
+
const client = await clerkClient()
|
|
100
|
+
await client.sessions.revokeSession(sessionId)
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
|
|
104
|
+
const { userId } = await auth()
|
|
105
|
+
if (!userId) throw new AuthRequiredError()
|
|
106
|
+
const client = await clerkClient()
|
|
107
|
+
if (update.name !== undefined) {
|
|
108
|
+
const [firstName = '', ...rest] = update.name.split(' ')
|
|
109
|
+
await client.users.updateUser(userId, { firstName, lastName: rest.join(' ') })
|
|
110
|
+
}
|
|
111
|
+
if (update.locale !== undefined) {
|
|
112
|
+
// Same guard the fake adapter enforces — the two adapters must reject alike.
|
|
113
|
+
if (!LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
114
|
+
await client.users.updateUserMetadata(userId, { publicMetadata: { locale: update.locale } })
|
|
115
|
+
}
|
|
116
|
+
const user = await this.getCurrentUser()
|
|
117
|
+
if (!user) throw new AuthRequiredError()
|
|
118
|
+
return user
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
|
|
122
|
+
// The two facts getCurrentUser reads, for a user who is not the caller: the role from the org
|
|
123
|
+
// membership, and `restricted` from the user's metadata and that role (isRestricted). The
|
|
124
|
+
// membership is looked up on the ORG, filtered to this user, so a person in many orgs is never cut
|
|
125
|
+
// off by a page size. No such org, or no membership, means no standing: null, as the port says,
|
|
126
|
+
// never a 404 thrown through to the caller.
|
|
127
|
+
const client = await clerkClient()
|
|
128
|
+
let memberships
|
|
129
|
+
try {
|
|
130
|
+
const organizationId = await organizationIdForSlug(orgSlug)
|
|
131
|
+
memberships = await client.organizations.getOrganizationMembershipList({ organizationId, userId: [userId] })
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (isClerkAPIResponseError(error) && error.status === 404) return null
|
|
134
|
+
throw error
|
|
135
|
+
}
|
|
136
|
+
// Matched on the user, not taken as the first row: if the filter were ever ignored, the first row
|
|
137
|
+
// would be someone else's membership, and their role.
|
|
138
|
+
const membership = memberships.data.find((m) => m.publicUserData?.userId === userId)
|
|
139
|
+
if (!membership) return null
|
|
140
|
+
const user = await client.users.getUser(userId)
|
|
141
|
+
// A BANNED user has no standing: banning ends their sessions, but their memberships survive it,
|
|
142
|
+
// so without this check their tokens and their email would keep the role. `locked` is
|
|
143
|
+
// deliberately NOT checked: anyone can lock an account by failing its sign-ins, and treating that
|
|
144
|
+
// as "no standing" would hand an attacker a way to kill a victim's tokens.
|
|
145
|
+
if (user.banned) return null
|
|
146
|
+
const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
|
|
147
|
+
const role = roleFrom(membership.publicMetadata, 'guest')
|
|
148
|
+
return { role, restricted: isRestricted(metadata.restricted, role) }
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
async listMembers(orgSlug: string): Promise<Membership[]> {
|
|
152
|
+
const client = await clerkClient()
|
|
153
|
+
const organizationId = await organizationIdForSlug(orgSlug)
|
|
154
|
+
const [members, invitations] = await Promise.all([
|
|
155
|
+
client.organizations.getOrganizationMembershipList({ organizationId, limit: 100 }),
|
|
156
|
+
client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], limit: 100 }),
|
|
157
|
+
])
|
|
158
|
+
const active: Membership[] = members.data.map((m) => {
|
|
159
|
+
const data = m.publicUserData
|
|
160
|
+
return {
|
|
161
|
+
// The USER id, never the membership resource id: Membership.id must share
|
|
162
|
+
// AuthUser.id's namespace (notify exclusion, notification recipients, assignee ids
|
|
163
|
+
// all compare the two) — the fake adapter's person ids already do.
|
|
164
|
+
id: data?.userId ?? m.id,
|
|
165
|
+
name: data ? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim() || null : null,
|
|
166
|
+
email: data?.identifier ?? '',
|
|
167
|
+
role: roleFrom(m.publicMetadata, 'member'),
|
|
168
|
+
status: 'active' as const,
|
|
169
|
+
}
|
|
170
|
+
})
|
|
171
|
+
const invited: Membership[] = invitations.data.map((i) => ({
|
|
172
|
+
id: i.id,
|
|
173
|
+
name: null,
|
|
174
|
+
email: i.emailAddress,
|
|
175
|
+
role: roleFrom(i.publicMetadata, 'member'),
|
|
176
|
+
status: 'invited' as const,
|
|
177
|
+
}))
|
|
178
|
+
return [...active, ...invited]
|
|
179
|
+
},
|
|
180
|
+
|
|
181
|
+
async createInvite(invite: InviteInput): Promise<Membership> {
|
|
182
|
+
const { userId } = await auth()
|
|
183
|
+
if (!userId) throw new AuthRequiredError()
|
|
184
|
+
const client = await clerkClient()
|
|
185
|
+
const organizationId = await organizationIdForSlug(invite.orgSlug)
|
|
186
|
+
const created = await client.organizations.createOrganizationInvitation({
|
|
187
|
+
organizationId,
|
|
188
|
+
emailAddress: invite.email,
|
|
189
|
+
inviterUserId: userId,
|
|
190
|
+
role: 'org:member',
|
|
191
|
+
publicMetadata: { role: invite.role },
|
|
192
|
+
})
|
|
193
|
+
return { id: created.id, name: null, email: created.emailAddress, role: invite.role, status: 'invited' }
|
|
194
|
+
},
|
|
195
|
+
|
|
196
|
+
async listMyOrgs(): Promise<OrgRef[]> {
|
|
197
|
+
const { userId } = await auth()
|
|
198
|
+
if (!userId) return []
|
|
199
|
+
const client = await clerkClient()
|
|
200
|
+
const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
|
|
201
|
+
return memberships.data.map((m) => ({
|
|
202
|
+
slug: m.organization.slug ?? m.organization.id,
|
|
203
|
+
name: m.organization.name,
|
|
204
|
+
role: roleFrom(m.publicMetadata, 'member'),
|
|
205
|
+
}))
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
async setActiveOrg(orgSlug: string): Promise<void> {
|
|
209
|
+
const { userId } = await auth()
|
|
210
|
+
if (!userId) throw new AuthRequiredError()
|
|
211
|
+
const mine = await this.listMyOrgs()
|
|
212
|
+
if (!mine.some((o) => o.slug === orgSlug)) throw new ForbiddenError(`no membership in org: ${orgSlug}`)
|
|
213
|
+
const client = await clerkClient()
|
|
214
|
+
await client.users.updateUserMetadata(userId, { unsafeMetadata: { currentOrgSlug: orgSlug } })
|
|
215
|
+
},
|
|
216
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createPublicKey } from 'node:crypto'
|
|
2
|
+
import { clerkMiddleware } from '@clerk/nextjs/server'
|
|
3
|
+
import { NextRequest, type NextFetchEvent, type NextProxy } from 'next/server'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Real mode's half of `withAuthProxy` (../proxy.ts): the app's proxy run inside Clerk's `clerkMiddleware`, which the
|
|
7
|
+
* Clerk auth adapter (./auth.ts) needs. Clerk's `auth()` and `currentUser()` refuse to run in a request its middleware
|
|
8
|
+
* did not see, in a page or an API route alike, so without this every real sign-in fails. Clerk runs on every request
|
|
9
|
+
* the proxy sees, and on every one that goes on to a route of this app it writes its own `x-clerk-auth-*` request
|
|
10
|
+
* headers over any a client sent (`decorateRequest` in @clerk/nextjs; a redirect or a rewrite to another origin it
|
|
11
|
+
* leaves alone).
|
|
12
|
+
*
|
|
13
|
+
* It protects no route itself: each route's own `authorize()` does. Clerk reads `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`
|
|
14
|
+
* and `CLERK_SECRET_KEY` from the environment itself, the same ones the auth adapter needs. Clerk may answer a request
|
|
15
|
+
* itself (its handshake redirect) without calling the app's proxy.
|
|
16
|
+
*
|
|
17
|
+
* Two kinds of request would make Clerk's middleware call Clerk's API before the app's proxy runs, at a caller's
|
|
18
|
+
* choosing:
|
|
19
|
+
* - A token in `Authorization`. Clerk accepts any kind of token there and verifies its machine tokens (`ak_`, `mt_`,
|
|
20
|
+
* `oat_`) through its API on every request. SSSB signs its users in by Clerk's session cookie and never sends a Clerk
|
|
21
|
+
* token in a header; its machine credentials are its own (the webhook secret, service callers' JWTs), checked by the route.
|
|
22
|
+
* So Clerk is shown the request without its `Authorization` header (`withoutAuthorization`), and the app's proxy and
|
|
23
|
+
* the route still get it (`keepAuthorization`).
|
|
24
|
+
* - A session token whose key id Clerk has not cached, which makes Clerk fetch its signing keys. `CLERK_JWT_KEY` stops
|
|
25
|
+
* that: Clerk does not read it from the environment, so it is passed on here as `jwtKey`, and Clerk then verifies
|
|
26
|
+
* every session token locally.
|
|
27
|
+
*/
|
|
28
|
+
export function withClerk(
|
|
29
|
+
proxy: NextProxy,
|
|
30
|
+
): (request: NextRequest, event: NextFetchEvent) => Promise<Response | null | undefined | void> {
|
|
31
|
+
const jwtKey = clerkJwtKey(process.env['CLERK_JWT_KEY'])
|
|
32
|
+
// Clerk hands its handler the request it was given, which may be the copy: the app's proxy gets the original. What
|
|
33
|
+
// the handler learns (whether the app's proxy listed the headers to forward) decides whether Authorization is put
|
|
34
|
+
// back.
|
|
35
|
+
const requests = new WeakMap<NextRequest, { original: NextRequest; proxyListed: boolean }>()
|
|
36
|
+
const clerk = clerkMiddleware(
|
|
37
|
+
async (_auth, request, event) => {
|
|
38
|
+
const state = requests.get(request)
|
|
39
|
+
if (!state) throw new Error("Clerk's middleware handed its handler a request it was not given")
|
|
40
|
+
const response = await proxy(state.original, event)
|
|
41
|
+
state.proxyListed = Boolean(response?.headers.get(OVERRIDE))
|
|
42
|
+
return response
|
|
43
|
+
},
|
|
44
|
+
jwtKey ? { jwtKey } : {},
|
|
45
|
+
)
|
|
46
|
+
return async (request, event) => {
|
|
47
|
+
const authorization = request.headers.get('authorization')
|
|
48
|
+
const shown = authorization === null ? request : withoutAuthorization(request)
|
|
49
|
+
const state = { original: request, proxyListed: false }
|
|
50
|
+
requests.set(shown, state)
|
|
51
|
+
const response = await clerk(shown, event)
|
|
52
|
+
return authorization === null || state.proxyListed ? response : keepAuthorization(response, authorization)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The request as Clerk is shown it: no `Authorization` header, and no body. Clerk reads a body only in its Frontend API
|
|
58
|
+
* proxy (`frontendApiProxy`, or a production key on a `.vercel.app` host), which SSSB does not use.
|
|
59
|
+
*/
|
|
60
|
+
function withoutAuthorization(request: NextRequest): NextRequest {
|
|
61
|
+
const headers = new Headers(request.headers)
|
|
62
|
+
headers.delete('authorization')
|
|
63
|
+
return new NextRequest(request.url, { method: request.method, headers })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const OVERRIDE = 'x-middleware-override-headers'
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Next forwards a request with the headers a proxy's response lists in `x-middleware-override-headers` (each value in
|
|
70
|
+
* `x-middleware-request-<name>`), when there is that list. Clerk builds it from the request it was shown when the app's
|
|
71
|
+
* proxy did not (the caller checks that), which would drop `Authorization` on its way to the route: put it back. A
|
|
72
|
+
* list the app's proxy built is its own, `Authorization` left out on purpose included.
|
|
73
|
+
*/
|
|
74
|
+
function keepAuthorization<T extends Response | null | undefined | void>(response: T, authorization: string): T {
|
|
75
|
+
const listed = response?.headers.get(OVERRIDE)
|
|
76
|
+
if (response && listed && !listed.split(',').includes('authorization')) {
|
|
77
|
+
response.headers.set(OVERRIDE, `${listed},authorization`)
|
|
78
|
+
response.headers.set('x-middleware-request-authorization', authorization)
|
|
79
|
+
}
|
|
80
|
+
return response
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The PEM public key, as a secret store or a one-line environment value often holds it (`\n` escapes, surrounding
|
|
85
|
+
* space) made into the PEM Clerk parses; and refused at once if it is not the kind Clerk can read (a 2048-bit RSA
|
|
86
|
+
* public key in SPKI PEM, whose fixed prefix Clerk strips as text), since Clerk would otherwise fail every session check
|
|
87
|
+
* with it and sign everyone out.
|
|
88
|
+
*/
|
|
89
|
+
function clerkJwtKey(value: string | undefined): string | undefined {
|
|
90
|
+
const pem = value?.replace(/\\n/g, '\n').trim()
|
|
91
|
+
if (!pem) return undefined
|
|
92
|
+
if (!isClerkReadableKey(pem)) {
|
|
93
|
+
throw new Error(
|
|
94
|
+
'CLERK_JWT_KEY is not a 2048-bit RSA public key in PEM: set it to the JWT public key from Clerk, or unset it',
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
return pem
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isClerkReadableKey(pem: string): boolean {
|
|
101
|
+
try {
|
|
102
|
+
const key = createPublicKey(pem)
|
|
103
|
+
return (
|
|
104
|
+
pem.startsWith('-----BEGIN PUBLIC KEY-----') &&
|
|
105
|
+
key.asymmetricKeyType === 'rsa' &&
|
|
106
|
+
key.asymmetricKeyDetails?.modulusLength === 2048
|
|
107
|
+
)
|
|
108
|
+
} catch {
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Kysely } from 'kysely'
|
|
2
|
+
import { expect } from 'vitest'
|
|
3
|
+
import { runOwnerPass, type Login } from '../../db/owner-pass'
|
|
4
|
+
import { runRlsProofs } from '../../db/rls-proof-runner'
|
|
5
|
+
import type { DB } from '../../db/schema'
|
|
6
|
+
import type { DbPort } from '../../ports/db'
|
|
7
|
+
import type { ContractServer } from './contract-postgres'
|
|
8
|
+
import { createRealDb } from './db'
|
|
9
|
+
import { createRealDataApiDb } from './db-data-api'
|
|
10
|
+
import { RdsDataEmulator, type EmulatedCall } from './rds-data-emulator'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* TEST ONLY: the contract passes over the RDS Data API transport (ADR-0002, addendum 2026-11-16), through
|
|
14
|
+
* ./rds-data-emulator.ts on a real Postgres. Shared by the contract runner (`@sssb/kit/testing/contract`, which runs
|
|
15
|
+
* them over each app's own tables) and the framework's own Data API contract test (./rds-data.contract.test.ts, which
|
|
16
|
+
* adds the transport's framework-specific cases). Nothing in an app's request path or a deployment imports it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** ARNs the emulator accepts and ignores: on Aurora they name the cluster and the secret, here nothing. */
|
|
20
|
+
export const EMULATED_ARNS = {
|
|
21
|
+
resourceArn: 'arn:aws:rds:us-east-1:000000000000:cluster:emulated',
|
|
22
|
+
secretArn: 'arn:aws:secretsmanager:us-east-1:000000000000:secret:emulated',
|
|
23
|
+
} as const
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The full RLS proof suite through the Data API, in `database`, made EMPTY first so the migrations run through the
|
|
27
|
+
* dialect (in its one transaction) rather than finding a database an earlier run already migrated.
|
|
28
|
+
*/
|
|
29
|
+
export async function proveRlsThroughDataApi(server: ContractServer, database: string): Promise<void> {
|
|
30
|
+
await server.recreateDatabase(database)
|
|
31
|
+
const emulator = new RdsDataEmulator(server.urlFor(database))
|
|
32
|
+
const port = createRealDataApiDb({ ...EMULATED_ARNS, database, client: emulator })
|
|
33
|
+
try {
|
|
34
|
+
await port.migrateToLatest()
|
|
35
|
+
await runRlsProofs(port.getDb(), expect)
|
|
36
|
+
} finally {
|
|
37
|
+
await port.getDb().destroy()
|
|
38
|
+
await emulator.close()
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The owner pass (../../db/owner-pass.ts), with every connection it opens made through the dialect, to an emulator
|
|
44
|
+
* logged in as that login: on Aurora the secret IS the login. Only `admin` is plain `pg`: it creates the owner, grants
|
|
45
|
+
* it the creator's membership where `app_user` (and any role the app names in `appRoles`) already exists, and tears
|
|
46
|
+
* everything down. None of that is what is
|
|
47
|
+
* being proven. Then: the owner's migrations went the Data API's way (ONE transaction, opening with the
|
|
48
|
+
* transaction-scoped lock, every statement on that one id, ending in a commit, all through the owner's emulator), and
|
|
49
|
+
* its role switch inside withTenant did too (the one-statement setup, inside a transaction).
|
|
50
|
+
*/
|
|
51
|
+
export async function runDataApiOwnerPass(server: ContractServer): Promise<void> {
|
|
52
|
+
const admin = createRealDb(server.urlFor(server.maintenanceDatabase)).getDb()
|
|
53
|
+
const opened = new Map<Kysely<DB>, { port: DbPort; emulator: RdsDataEmulator; login: Login }>()
|
|
54
|
+
const closing: Promise<void>[] = []
|
|
55
|
+
const connect = (login: Login): Kysely<DB> => {
|
|
56
|
+
const asLogin = new RdsDataEmulator(server.urlFor(login.database, login))
|
|
57
|
+
const port = createRealDataApiDb({
|
|
58
|
+
...EMULATED_ARNS,
|
|
59
|
+
database: login.database,
|
|
60
|
+
client: { send: (command) => asLogin.send(command), destroy: () => void closing.push(asLogin.close()) },
|
|
61
|
+
})
|
|
62
|
+
opened.set(port.getDb(), { port, emulator: asLogin, login })
|
|
63
|
+
return port.getDb()
|
|
64
|
+
}
|
|
65
|
+
// The calls the owner's emulator received WHILE the migrations ran: the migration itself, alone.
|
|
66
|
+
let migration: EmulatedCall[] = []
|
|
67
|
+
let migratedAs: Login | undefined
|
|
68
|
+
try {
|
|
69
|
+
await runOwnerPass(
|
|
70
|
+
{
|
|
71
|
+
admin,
|
|
72
|
+
superuser: server.superuser,
|
|
73
|
+
maintenanceDatabase: server.maintenanceDatabase,
|
|
74
|
+
connect,
|
|
75
|
+
migrate: async (ownerDb) => {
|
|
76
|
+
const { port, emulator: asOwner, login } = opened.get(ownerDb)!
|
|
77
|
+
const from = asOwner.calls.length
|
|
78
|
+
await port.migrateToLatest()
|
|
79
|
+
migration = asOwner.calls.slice(from)
|
|
80
|
+
migratedAs = login
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
expect,
|
|
84
|
+
)
|
|
85
|
+
} finally {
|
|
86
|
+
await Promise.all(closing)
|
|
87
|
+
await admin.destroy()
|
|
88
|
+
}
|
|
89
|
+
expect(migratedAs?.user).toMatch(/^sssb_owner_\d+$/)
|
|
90
|
+
expect(migration.filter((call) => call.operation === 'BeginTransaction')).toHaveLength(1)
|
|
91
|
+
expect(migration[0]?.operation).toBe('BeginTransaction')
|
|
92
|
+
expect(migration[1]?.sql).toMatch(/pg_advisory_xact_lock/)
|
|
93
|
+
expect(new Set(migration.slice(1).map((call) => call.transactionId)).size).toBe(1)
|
|
94
|
+
expect(migration.at(-1)?.operation).toBe('CommitTransaction')
|
|
95
|
+
const owner = [...opened.values()].find(({ login }) => login === migratedAs)!.emulator.calls
|
|
96
|
+
expect(
|
|
97
|
+
owner.some(
|
|
98
|
+
(call) =>
|
|
99
|
+
call.operation === 'ExecuteStatement' &&
|
|
100
|
+
call.transactionId !== undefined &&
|
|
101
|
+
/set_config\('role', 'app_user', true\)/.test(call.sql ?? ''),
|
|
102
|
+
),
|
|
103
|
+
).toBe(true)
|
|
104
|
+
}
|