@sssb/kit 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/auth-tenancy.ts +157 -0
- package/src/adapters/configured-auth.ts +183 -0
- package/src/adapters/email-message.ts +30 -0
- package/src/adapters/fake/analytics.ts +1 -1
- package/src/adapters/fake/auth.ts +53 -3
- package/src/adapters/fake/data-dir.ts +32 -2
- package/src/adapters/fake/email.ts +2 -0
- package/src/adapters/fake/jobs.ts +5 -4
- package/src/adapters/fake/simulated-auth.ts +24 -0
- package/src/adapters/index.ts +3 -2
- package/src/adapters/real/accept-invite-form.tsx +32 -14
- package/src/adapters/real/analytics.ts +29 -2
- package/src/adapters/real/auth.ts +127 -23
- package/src/adapters/real/contract-postgres.ts +15 -11
- package/src/adapters/real/email.ts +2 -0
- package/src/adapters/real/index.ts +19 -3
- package/src/adapters/real/jobs-in-process.ts +32 -14
- package/src/adapters/real/jobs.ts +6 -3
- package/src/adapters/real/migrate-handler.ts +3 -1
- package/src/adapters/real/rds-data-codec.ts +88 -4
- package/src/adapters/real/rds-data-emulator.ts +12 -4
- package/src/adapters/real/sign-in-form.tsx +29 -13
- package/src/authz/app-exemptions.ts +79 -9
- package/src/authz/authorize.ts +4 -1
- package/src/authz/route-scan.ts +626 -55
- package/src/components/auth/accept-invite-screen.tsx +5 -1
- package/src/components/auth/people-picker.tsx +20 -2
- package/src/components/profile-screen.tsx +27 -2
- package/src/core/abilities.ts +22 -6
- package/src/core/inbound-email.ts +41 -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/jobs.ts +32 -11
- package/src/db/keyset.ts +8 -6
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/migrations/0017_job_requester.ts +20 -0
- package/src/db/migrations/index.ts +2 -0
- package/src/db/rls-coverage.ts +51 -17
- package/src/db/schedules.ts +9 -3
- package/src/db/schema.ts +2 -0
- package/src/demo-static/actor-drivers.ts +8 -2
- package/src/demo-static/contracts.ts +9 -0
- package/src/demo-static/email-html.ts +9 -0
- package/src/demo-static/rows.ts +2 -0
- package/src/demo-static/tour/use-tours.tsx +8 -2
- package/src/demo-static/world.ts +98 -41
- package/src/email/send.ts +6 -2
- package/src/guide.md +37 -6
- package/src/i18n/messages/en.json +3 -0
- package/src/i18n/messages/es.json +3 -0
- package/src/i18n/messages.ts +3 -2
- package/src/ports/auth.ts +10 -1
- package/src/server-lib/notify.ts +51 -9
- package/src/server-lib/scheduled-tick.ts +5 -1
- package/src/server-lib/webhook-dispatch.ts +3 -0
- package/src/service-auth/mailgun.ts +19 -4
- package/src/testing/conformance/auth-provider.ts +17 -5
- package/src/testing/conformance/authz.ts +6 -2
- package/src/testing/conformance/demo-presets.ts +4 -4
- package/src/testing/conformance/i18n.ts +99 -5
- package/src/testing/conformance/suite.ts +63 -3
package/dist/release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"commit":"
|
|
1
|
+
{"commit":"d70d56db1537eee2bcfe9c8c72bb4c784b131117"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sssb/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -90,6 +90,7 @@
|
|
|
90
90
|
"./core/notifications": "./src/core/notifications.ts",
|
|
91
91
|
"./core/presets": "./src/core/presets.ts",
|
|
92
92
|
"./core/roles": "./src/core/roles.ts",
|
|
93
|
+
"./core/same-origin-path": "./src/core/same-origin-path.ts",
|
|
93
94
|
"./core/schedules": "./src/core/schedules.ts",
|
|
94
95
|
"./core/state-machine": "./src/core/state-machine.ts",
|
|
95
96
|
"./core/webhook-events": "./src/core/webhook-events.ts",
|
|
@@ -170,6 +171,7 @@
|
|
|
170
171
|
"@aws-sdk/s3-request-presigner": "^3.1155.0",
|
|
171
172
|
"@clerk/nextjs": "^7.9.19",
|
|
172
173
|
"@electric-sql/pglite": "^0.5.11",
|
|
174
|
+
"@formatjs/icu-messageformat-parser": "^3.5.15",
|
|
173
175
|
"@mantine/form": "^9.7.3",
|
|
174
176
|
"@react-email/components": "^1.0.12",
|
|
175
177
|
"@react-email/render": "^2.1.1",
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the auth adapters place a signed-in person: the deployment's two choices, read here from the environment, which
|
|
3
|
+
* `SssbApp` sets from the app's `params.auth` (an app's own infra sets it itself). Both adapters read them, the fake as
|
|
4
|
+
* well as Clerk, so a simulated world runs the same placement as the deployment when its environment says so. Each
|
|
5
|
+
* answers its own question, and one pairing is refused (below).
|
|
6
|
+
*
|
|
7
|
+
* **Where the tenant comes from, `AUTH_TENANCY`:**
|
|
8
|
+
* - `multi` (the default, what every deployment did before the switch existed): the tenant is the user's own claim, in
|
|
9
|
+
* their identity provider's public metadata under `AUTH_TENANT_METADATA_KEY` (default `tenantSlug`).
|
|
10
|
+
* - `single`: `AUTH_TENANT_SLUG` fixes it. No tenant metadata is needed. A user whose metadata names a DIFFERENT tenant
|
|
11
|
+
* under the key, or holds there something that is not a slug, is refused, so a multi-tenant instance switched to this
|
|
12
|
+
* mode by mistake cannot pour every tenant's users into one. Nothing else changes: the person's organizations, roles,
|
|
13
|
+
* invitations and notifications are whatever the org source says.
|
|
14
|
+
*
|
|
15
|
+
* **Where organizations and roles come from, `AUTH_ORG_SOURCE`:**
|
|
16
|
+
* - `provider` (the default, ADR-0003): the identity provider's organizations, and the role on each membership.
|
|
17
|
+
* - `fixed`: for an app that uses the identity provider without its organizations. Every person it signs in is placed
|
|
18
|
+
* in one org, `AUTH_HOME_ORG_SLUG`, with one role, `AUTH_DEFAULT_ROLE`: `none` (the default), which grants nothing a
|
|
19
|
+
* membership would (../core/roles.ts `hasStanding`), or `restricted`, which reads what a restricted member reads and
|
|
20
|
+
* writes nothing org-scoped through SSSB's rules. No role that writes is offered: on an identity-provider instance
|
|
21
|
+
* shared with another product, everyone that product signs in gets it. The app's own rules grant the rest.
|
|
22
|
+
*
|
|
23
|
+
* One pairing is refused: a fixed org source needs a single tenancy. It reads nothing from the provider about orgs or
|
|
24
|
+
* roles, so with a multi tenancy the tenant claim in the provider's metadata would be the only thing deciding whose
|
|
25
|
+
* data a person reaches, and a credential (`getMember`) could not be checked against the tenant its org belongs to.
|
|
26
|
+
* On an instance shared with another product, that product's operator writes that metadata.
|
|
27
|
+
*
|
|
28
|
+
* Each is an explicit switch, never inferred from which settings happen to be set, so a deployment that
|
|
29
|
+
* half-configures one fails at boot instead of quietly changing who sees what.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export const AUTH_TENANCY_CHOICES = ['multi', 'single'] as const
|
|
33
|
+
export const AUTH_ORG_SOURCE_CHOICES = ['provider', 'fixed'] as const
|
|
34
|
+
/** The roles a fixed org source may give everyone, lowest first: neither writes anything org-scoped in SSSB's rules. */
|
|
35
|
+
export const FIXED_ORG_ROLES = ['none', 'restricted'] as const
|
|
36
|
+
export type FixedOrgRole = (typeof FIXED_ORG_ROLES)[number]
|
|
37
|
+
|
|
38
|
+
export type AuthTenancy = { kind: 'multi' } | { kind: 'single'; tenantSlug: string }
|
|
39
|
+
export type AuthOrgSource = { kind: 'provider' } | { kind: 'fixed'; homeOrgSlug: string; role: FixedOrgRole }
|
|
40
|
+
|
|
41
|
+
export interface AuthSettings {
|
|
42
|
+
tenancy: AuthTenancy
|
|
43
|
+
orgSource: AuthOrgSource
|
|
44
|
+
/** The public-metadata key holding a user's tenant claim: read in multi tenancy, checked in single. */
|
|
45
|
+
tenantMetadataKey: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const DEFAULT_TENANT_METADATA_KEY = 'tenantSlug'
|
|
49
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
50
|
+
const METADATA_KEY = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_][A-Za-z0-9_]*$/
|
|
51
|
+
|
|
52
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
53
|
+
|
|
54
|
+
/** Every setting either choice reads, each mapped to its cutover row. */
|
|
55
|
+
const SINGLE_TENANCY_ENV: Readonly<Record<string, string>> = { AUTH_TENANT_SLUG: 'auth-tenancy' }
|
|
56
|
+
const FIXED_ORG_ENV: Readonly<Record<string, string>> = { AUTH_HOME_ORG_SLUG: 'auth-tenancy' }
|
|
57
|
+
/** Optional in a fixed org source (it defaults to `none`), so required nowhere, and refused elsewhere. */
|
|
58
|
+
const FIXED_ORG_OPTIONAL = ['AUTH_DEFAULT_ROLE']
|
|
59
|
+
|
|
60
|
+
function choice<T extends string>(env: Env, name: string, choices: readonly T[]): T {
|
|
61
|
+
const value = env[name] || choices[0]
|
|
62
|
+
if (!(choices as readonly string[]).includes(value as string)) {
|
|
63
|
+
throw new Error(`${name} must be one of ${choices.join(', ')} (got "${value}")`)
|
|
64
|
+
}
|
|
65
|
+
return value as T
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function strays(env: Env, names: readonly string[], setting: string, needs: string): void {
|
|
69
|
+
const set = names.filter((name) => env[name])
|
|
70
|
+
if (set.length > 0) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`${set.join(' and ')} ${set.length > 1 ? 'are' : 'is'} set but ${setting}: set ${needs} to use ` +
|
|
73
|
+
`${set.length > 1 ? 'them' : 'it'}, or remove ${set.length > 1 ? 'them' : 'it'}`,
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function slug(env: Env, name: string, needer: string): string {
|
|
79
|
+
const value = env[name] ?? ''
|
|
80
|
+
if (!SLUG.test(value)) throw new Error(`${needer} needs ${name}, a slug (got "${value}")`)
|
|
81
|
+
return value
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The deployment's auth settings, from `env` (the process's own by default). Throws on an unknown choice, a malformed
|
|
86
|
+
* slug, key or role, or a setting its choice does not use; a missing setting a choice needs is the boot check's to
|
|
87
|
+
* report (`assertRealEnv`), and throws here only when the settings are read without it.
|
|
88
|
+
*/
|
|
89
|
+
export function authSettings(env: Env = process.env): AuthSettings {
|
|
90
|
+
const tenancyKind = choice(env, 'AUTH_TENANCY', AUTH_TENANCY_CHOICES)
|
|
91
|
+
const orgSourceKind = choice(env, 'AUTH_ORG_SOURCE', AUTH_ORG_SOURCE_CHOICES)
|
|
92
|
+
const tenantMetadataKey = env['AUTH_TENANT_METADATA_KEY'] || DEFAULT_TENANT_METADATA_KEY
|
|
93
|
+
if (!METADATA_KEY.test(tenantMetadataKey)) {
|
|
94
|
+
throw new Error(`AUTH_TENANT_METADATA_KEY must be a plain identifier (got "${tenantMetadataKey}")`)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let tenancy: AuthTenancy
|
|
98
|
+
if (tenancyKind === 'multi') {
|
|
99
|
+
strays(env, Object.keys(SINGLE_TENANCY_ENV), 'AUTH_TENANCY is multi', 'AUTH_TENANCY=single')
|
|
100
|
+
tenancy = { kind: 'multi' }
|
|
101
|
+
} else {
|
|
102
|
+
tenancy = { kind: 'single', tenantSlug: slug(env, 'AUTH_TENANT_SLUG', 'AUTH_TENANCY=single') }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let orgSource: AuthOrgSource
|
|
106
|
+
if (orgSourceKind === 'provider') {
|
|
107
|
+
strays(
|
|
108
|
+
env,
|
|
109
|
+
[...Object.keys(FIXED_ORG_ENV), ...FIXED_ORG_OPTIONAL],
|
|
110
|
+
'AUTH_ORG_SOURCE is provider',
|
|
111
|
+
'AUTH_ORG_SOURCE=fixed',
|
|
112
|
+
)
|
|
113
|
+
orgSource = { kind: 'provider' }
|
|
114
|
+
} else {
|
|
115
|
+
const homeOrgSlug = slug(env, 'AUTH_HOME_ORG_SLUG', 'AUTH_ORG_SOURCE=fixed')
|
|
116
|
+
const role = env['AUTH_DEFAULT_ROLE'] || FIXED_ORG_ROLES[0]
|
|
117
|
+
if (!(FIXED_ORG_ROLES as readonly string[]).includes(role)) {
|
|
118
|
+
throw new Error(
|
|
119
|
+
`AUTH_DEFAULT_ROLE must be one of ${FIXED_ORG_ROLES.join(', ')} (got "${role}"): everyone the ` +
|
|
120
|
+
'identity provider signs in gets it, so no role that writes is offered',
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
orgSource = { kind: 'fixed', homeOrgSlug, role: role as FixedOrgRole }
|
|
124
|
+
if (tenancy.kind === 'multi') {
|
|
125
|
+
throw new Error(
|
|
126
|
+
'AUTH_ORG_SOURCE=fixed needs AUTH_TENANCY=single: with a multi tenancy the tenant claim in the identity ' +
|
|
127
|
+
"provider's metadata would be all that places a person",
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { tenancy, orgSource, tenantMetadataKey }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The settings the deployment's choices require, each mapped to its cutover row: a single tenancy's tenant slug, a
|
|
136
|
+
* fixed org source's home org slug, or none.
|
|
137
|
+
*/
|
|
138
|
+
export function authRequiredEnv(env: Env = process.env): Record<string, string> {
|
|
139
|
+
return {
|
|
140
|
+
...((env['AUTH_TENANCY'] || 'multi') === 'single' ? SINGLE_TENANCY_ENV : {}),
|
|
141
|
+
...((env['AUTH_ORG_SOURCE'] || 'provider') === 'fixed' ? FIXED_ORG_ENV : {}),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Why a fixed org source cannot run with this app's staff org, or null. The staff org's members wield manage-all
|
|
147
|
+
* (../core/abilities.ts), and every role a fixed org source offers but `none` has standing, so placing everyone the
|
|
148
|
+
* identity provider signs in in the staff org with one would hand them all manage-all. Checked where the auth port is
|
|
149
|
+
* built, with the seam's `staffOrgSlug`, since only the app knows it (`SssbApp` cannot, at synth).
|
|
150
|
+
*/
|
|
151
|
+
export function fixedOrgProblem(orgSource: AuthOrgSource, staffOrgSlug: string): string | null {
|
|
152
|
+
if (orgSource.kind !== 'fixed' || orgSource.role === 'none' || orgSource.homeOrgSlug !== staffOrgSlug) return null
|
|
153
|
+
return (
|
|
154
|
+
`AUTH_HOME_ORG_SLUG is the staff org ("${staffOrgSlug}") and AUTH_DEFAULT_ROLE is "${orgSource.role}": ` +
|
|
155
|
+
'everyone the identity provider signs in would wield manage-all. Use another home org, or the role none'
|
|
156
|
+
)
|
|
157
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { isRestricted } from '../core/roles'
|
|
2
|
+
import type { Locale } from '../core/locale'
|
|
3
|
+
import type { AuthPort, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
|
|
4
|
+
import { AuthRequiredError, ForbiddenError } from '../ports/errors'
|
|
5
|
+
import { type AuthSettings, fixedOrgProblem } from './auth-tenancy'
|
|
6
|
+
|
|
7
|
+
/** A signed-in person as the identity provider knows them: who they are, and any tenant they claim. */
|
|
8
|
+
export interface ProviderIdentity {
|
|
9
|
+
id: string
|
|
10
|
+
name: string
|
|
11
|
+
email: string
|
|
12
|
+
locale: Locale
|
|
13
|
+
/**
|
|
14
|
+
* The account's tenant claim under the metadata key: the slug it names, `undefined` when it names none (the key is
|
|
15
|
+
* absent, null or empty), or `null` when it holds something that is not a slug at all, which single tenancy
|
|
16
|
+
* refuses.
|
|
17
|
+
*/
|
|
18
|
+
tenantClaim: string | null | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Another account, as `getMember` needs it: its tenant claim, and how to reach it. */
|
|
22
|
+
export type ProviderAccount = Pick<ProviderIdentity, 'tenantClaim' | 'email'> & { name: string | null }
|
|
23
|
+
|
|
24
|
+
/** What the auth settings need from an adapter beyond its port: the provider's facts, with no org or role in them. */
|
|
25
|
+
export interface ProviderIdentitySource {
|
|
26
|
+
/** The person signed in on this request, or null. */
|
|
27
|
+
current(): Promise<ProviderIdentity | null>
|
|
28
|
+
/**
|
|
29
|
+
* Another account by id: null when the provider has none, or would not let it act (a banned account). For a
|
|
30
|
+
* person who arrived without a session (an API token, an inbound email), so they are judged as now.
|
|
31
|
+
*/
|
|
32
|
+
account(userId: string): Promise<ProviderAccount | null>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The auth port as the deployment's settings place people (./auth-tenancy.ts), over either adapter, the fake or Clerk,
|
|
37
|
+
* so the settings mean the same in a simulated world as in a deployment. On the defaults (multi tenancy, the provider's
|
|
38
|
+
* organizations) it is the adapter itself, untouched.
|
|
39
|
+
*
|
|
40
|
+
* **Single tenancy changes where the tenant comes from, and nothing else.** The person's tenant is the configured one,
|
|
41
|
+
* and a person whose account names a different tenant under the metadata key, or holds there something that is not a
|
|
42
|
+
* slug, is no user at all, and has no standing anywhere as a credential (`getMember`): that is a multi-tenant instance
|
|
43
|
+
* switched to this mode by mistake, and admitting them would put another tenant's people in this one. Refused without
|
|
44
|
+
* signing out: this runs while server components render, where a session cookie cannot be changed, and on a shared
|
|
45
|
+
* instance it would end their session in the other product. Over the provider's organizations, every method is
|
|
46
|
+
* otherwise the adapter's, with its organizations, roles, members and invitations; the ones that act for the signed-in
|
|
47
|
+
* person (`updateProfile`, `createInvite`, `listMyOrgs`, `setActiveOrg`) run the tenant guard first, and `getMember`
|
|
48
|
+
* runs it after the provider's membership.
|
|
49
|
+
*
|
|
50
|
+
* **A fixed org source places everyone in one org with one role**, and what each method means follows from it:
|
|
51
|
+
* - `getCurrentUser`: the home org and the configured role, whatever the provider's metadata says. No role is read from
|
|
52
|
+
* the provider: on an instance shared with another product, that product may write the same metadata for its own
|
|
53
|
+
* reasons.
|
|
54
|
+
* - `getMember`: the same standing, with the account's name and email, for an account the provider still has, in the
|
|
55
|
+
* home org; null for any other org, and for an unknown or banned account.
|
|
56
|
+
* - `listMembers`: empty. Membership is implicit, and listing the provider's users would enumerate everyone on the
|
|
57
|
+
* instance, another product's users included, and mail them. So no one is an org admin: the end of a job submitted
|
|
58
|
+
* with a requester goes to that person instead (../server-lib/notify.ts `notifyJobTerminal`), and an app addresses
|
|
59
|
+
* its own notifications to the people it knows. SSSB's own rules let neither offered role submit a `Job` (create
|
|
60
|
+
* needs a non-restricted member), so such a job is one the app's own rules let the person start.
|
|
61
|
+
* - `createInvite`: refused. Anyone the provider signs in is already placed in the home org; an app adds people through
|
|
62
|
+
* its provider's own sign-up.
|
|
63
|
+
* - `listMyOrgs`: the home org alone, named by its slug (this module reads no database). `setActiveOrg`: the home org
|
|
64
|
+
* is accepted and changes nothing; any other is refused.
|
|
65
|
+
*
|
|
66
|
+
* `signInPath` and `signOut` are always the adapter's, and `updateProfile` writes through it after the guard.
|
|
67
|
+
*/
|
|
68
|
+
export function configuredAuth(
|
|
69
|
+
base: AuthPort,
|
|
70
|
+
settings: AuthSettings,
|
|
71
|
+
source: ProviderIdentitySource,
|
|
72
|
+
staffOrgSlug: string,
|
|
73
|
+
): AuthPort {
|
|
74
|
+
const { tenancy, orgSource } = settings
|
|
75
|
+
if (tenancy.kind === 'multi' && orgSource.kind === 'provider') return base
|
|
76
|
+
const problem = fixedOrgProblem(orgSource, staffOrgSlug)
|
|
77
|
+
if (problem) throw new Error(problem)
|
|
78
|
+
// authSettings refuses this pairing; refused again here, for a caller that builds the settings itself.
|
|
79
|
+
if (orgSource.kind === 'fixed' && tenancy.kind !== 'single')
|
|
80
|
+
throw new Error('a fixed org source needs a single tenancy')
|
|
81
|
+
|
|
82
|
+
const admitted = (claim: string | null | undefined) =>
|
|
83
|
+
tenancy.kind === 'multi' || claim === undefined || claim === tenancy.tenantSlug
|
|
84
|
+
const fixed = orgSource.kind === 'fixed' ? orgSource : null
|
|
85
|
+
const fixedRestricted = fixed ? isRestricted(undefined, fixed.role) : false
|
|
86
|
+
|
|
87
|
+
const port: AuthPort = {
|
|
88
|
+
async getCurrentUser(): Promise<AuthUser | null> {
|
|
89
|
+
const identity = await source.current()
|
|
90
|
+
if (!identity || !admitted(identity.tenantClaim)) return null
|
|
91
|
+
if (fixed) {
|
|
92
|
+
return {
|
|
93
|
+
id: identity.id,
|
|
94
|
+
name: identity.name,
|
|
95
|
+
email: identity.email,
|
|
96
|
+
locale: identity.locale,
|
|
97
|
+
role: fixed.role,
|
|
98
|
+
// A fixed org source needs a single tenancy (refused above otherwise).
|
|
99
|
+
tenantSlug: tenancy.kind === 'single' ? tenancy.tenantSlug : '',
|
|
100
|
+
orgSlug: fixed.homeOrgSlug,
|
|
101
|
+
restricted: fixedRestricted,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Single tenancy over the provider's organizations: the adapter's user, in the configured tenant. The
|
|
105
|
+
// adapter reads the signed-in account again, so on Clerk this may be a second user request per call (the
|
|
106
|
+
// cutover row `auth-tenancy` says to measure it).
|
|
107
|
+
const user = await base.getCurrentUser()
|
|
108
|
+
if (!user || user.id !== identity.id) return null
|
|
109
|
+
return tenancy.kind === 'single' ? { ...user, tenantSlug: tenancy.tenantSlug } : user
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
async requireUser(): Promise<AuthUser> {
|
|
113
|
+
const user = await port.getCurrentUser()
|
|
114
|
+
if (!user) throw new AuthRequiredError()
|
|
115
|
+
return user
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
async requireRole(...roles): Promise<AuthUser> {
|
|
119
|
+
const user = await port.requireUser()
|
|
120
|
+
if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
|
|
121
|
+
return user
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
signInPath(returnTo?: string): string {
|
|
125
|
+
return base.signInPath(returnTo)
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
async signOut(): Promise<void> {
|
|
129
|
+
await base.signOut()
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
async updateProfile(update): Promise<AuthUser> {
|
|
133
|
+
await port.requireUser()
|
|
134
|
+
await base.updateProfile(update)
|
|
135
|
+
return port.requireUser()
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
|
|
139
|
+
if (!fixed) {
|
|
140
|
+
// The provider's organizations: its own membership first, so a non-member costs what it always did,
|
|
141
|
+
// then the tenant guard.
|
|
142
|
+
const standing = await base.getMember(orgSlug, userId)
|
|
143
|
+
if (!standing) return null
|
|
144
|
+
const account = await source.account(userId)
|
|
145
|
+
return account && admitted(account.tenantClaim) ? standing : null
|
|
146
|
+
}
|
|
147
|
+
if (orgSlug !== fixed.homeOrgSlug) return null
|
|
148
|
+
const account = await source.account(userId)
|
|
149
|
+
if (!account || !admitted(account.tenantClaim)) return null
|
|
150
|
+
return { role: fixed.role, restricted: fixedRestricted, name: account.name, email: account.email }
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
async listMembers(orgSlug: string): Promise<Membership[]> {
|
|
154
|
+
return fixed ? [] : base.listMembers(orgSlug)
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
async createInvite(invite): Promise<CreatedInvite> {
|
|
158
|
+
if (fixed) {
|
|
159
|
+
throw new ForbiddenError(
|
|
160
|
+
'a fixed org source places everyone the identity provider signs in in the home org, so there is ' +
|
|
161
|
+
'no one to invite (AUTH_ORG_SOURCE=fixed)',
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
// The adapter checks only that someone is signed in; the tenant guard is this port's.
|
|
165
|
+
await port.requireUser()
|
|
166
|
+
return base.createInvite(invite)
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
async listMyOrgs(): Promise<OrgRef[]> {
|
|
170
|
+
const user = await port.getCurrentUser()
|
|
171
|
+
if (!user) return []
|
|
172
|
+
if (fixed) return [{ slug: fixed.homeOrgSlug, name: fixed.homeOrgSlug, role: fixed.role }]
|
|
173
|
+
return base.listMyOrgs()
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
async setActiveOrg(orgSlug: string): Promise<void> {
|
|
177
|
+
await port.requireUser()
|
|
178
|
+
if (!fixed) return base.setActiveOrg(orgSlug)
|
|
179
|
+
if (orgSlug !== fixed.homeOrgSlug) throw new ForbiddenError(`no membership in org: ${orgSlug}`)
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
return port
|
|
183
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { EmailMessage } from '../ports/email'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Refuses a message the email port must never send, before any adapter hands it on: a `to` that is not exactly one
|
|
5
|
+
* address, and a `subject` that could break a header. Mailgun's `to` takes a comma-separated list, so a `to` built from
|
|
6
|
+
* user input (`a@x.test, b@evil.test`) would otherwise mail everyone in it. Both the real adapter and the fake call this,
|
|
7
|
+
* so a test on the simulated world fails where a deployment would have sent to a list. Neither value is echoed in the
|
|
8
|
+
* error: both may be personal data, and the error may reach a log.
|
|
9
|
+
*/
|
|
10
|
+
export function assertSendableMessage(message: EmailMessage): void {
|
|
11
|
+
const { to, subject } = message
|
|
12
|
+
if (typeof to !== 'string' || /[,;\p{Cc}]/u.test(to) || (to.match(/@/g) ?? []).length !== 1 || !isOneAddress(to)) {
|
|
13
|
+
throw new Error('email: `to` must be exactly one address')
|
|
14
|
+
}
|
|
15
|
+
if (/[\r\n]/.test(subject)) throw new Error('email: `subject` must not contain a line break')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** An addr-spec with nothing a mailer could read as a display name, a comment or a second address around it. */
|
|
19
|
+
const BARE_ADDRESS = /^[^\s<>"()@]+@[^\s<>"()@]+$/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `to` is either a bare address (`ada@example.test`) or a display name and then one bracketed bare address at its very
|
|
23
|
+
* end (`Ada Lovelace <ada@example.test>`). Anything else lets the address a vendor mails differ from the one the caller
|
|
24
|
+
* recorded: in `a<b@c.d>` a mailer reads the display name `a` and mails `b@c.d`, and a trailing `(…)` is a comment.
|
|
25
|
+
*/
|
|
26
|
+
function isOneAddress(to: string): boolean {
|
|
27
|
+
if (BARE_ADDRESS.test(to)) return true
|
|
28
|
+
const named = /^([^<>"()]*[^\s<>"()])\s+<([^<>]*)>$/.exec(to)
|
|
29
|
+
return named !== null && named[1]!.trim() !== '' && BARE_ADDRESS.test(named[2]!)
|
|
30
|
+
}
|
|
@@ -64,7 +64,7 @@ export const fakeAnalytics: AnalyticsPort = {
|
|
|
64
64
|
},
|
|
65
65
|
async isFlagEnabled(flag, defaultValue = false) {
|
|
66
66
|
const flags = readFlags()
|
|
67
|
-
return flag
|
|
67
|
+
return Object.hasOwn(flags, flag) ? flags[flag]! : defaultValue
|
|
68
68
|
},
|
|
69
69
|
}
|
|
70
70
|
|
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
ProfileUpdate,
|
|
19
19
|
} from '../../ports/auth'
|
|
20
20
|
import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
|
|
21
|
+
import type { ProviderIdentitySource } from '../configured-auth'
|
|
21
22
|
import { writeFileAtomicSync, writeJsonAtomic } from './atomic-write'
|
|
22
23
|
import { readSimulatorState, updatePersonState, writeViewpointCookie } from './simulator'
|
|
23
24
|
import { dataDir } from './data-dir'
|
|
@@ -200,8 +201,11 @@ export async function acceptInvite(
|
|
|
200
201
|
): Promise<{ id: string; tenantSlug: string }> {
|
|
201
202
|
const invite = findInvite(inviteId)
|
|
202
203
|
if (!invite) throw new ForbiddenError(`unknown invite: ${inviteId}`)
|
|
204
|
+
if (typeof profile.name !== 'string') throw new ForbiddenError('invalid name')
|
|
203
205
|
const name = profile.name.trim()
|
|
204
206
|
if (!name) throw new ForbiddenError('name is required')
|
|
207
|
+
// The same bound updateProfile keeps, so a person cannot get a name at sign-up that they could not set later.
|
|
208
|
+
if (!isProfileName(name)) throw new ForbiddenError('invalid name')
|
|
205
209
|
|
|
206
210
|
const person: SeedPerson = {
|
|
207
211
|
id: `person-invited-${inviteId.slice(0, 8)}`,
|
|
@@ -254,9 +258,17 @@ export const fakeAuth: AuthPort = {
|
|
|
254
258
|
async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
|
|
255
259
|
const session = await readSession()
|
|
256
260
|
if (!session) throw new AuthRequiredError()
|
|
257
|
-
|
|
261
|
+
// Refused as the real adapter refuses (./../real/auth.ts), before anything is stored: a name that is not a
|
|
262
|
+
// non-blank string of at most 256 characters, a locale this app does not ship. Only the two known fields are
|
|
263
|
+
// stored, so a body with anything else in it cannot reach every page that renders this person.
|
|
264
|
+
if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
|
|
265
|
+
if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
|
|
258
266
|
const overrides = readOverrides()
|
|
259
|
-
overrides[session.person.id] = {
|
|
267
|
+
overrides[session.person.id] = {
|
|
268
|
+
...overrides[session.person.id],
|
|
269
|
+
...(update.name === undefined ? {} : { name: update.name }),
|
|
270
|
+
...(update.locale === undefined ? {} : { locale: update.locale }),
|
|
271
|
+
}
|
|
260
272
|
await writeJsonAtomic(overridesFile(), overrides)
|
|
261
273
|
return toUser(session.person, session.orgSlug)
|
|
262
274
|
},
|
|
@@ -280,7 +292,12 @@ export const fakeAuth: AuthPort = {
|
|
|
280
292
|
const person = findPerson(userId)
|
|
281
293
|
const membership = person?.memberships.find((m) => m.orgSlug === orgSlug)
|
|
282
294
|
if (!person || !membership) return null
|
|
283
|
-
return {
|
|
295
|
+
return {
|
|
296
|
+
role: membership.role,
|
|
297
|
+
restricted: isRestricted(person.restricted, membership.role),
|
|
298
|
+
name: readOverrides()[person.id]?.name ?? person.name,
|
|
299
|
+
email: person.email,
|
|
300
|
+
}
|
|
284
301
|
},
|
|
285
302
|
|
|
286
303
|
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
@@ -322,3 +339,36 @@ export const fakeAuth: AuthPort = {
|
|
|
322
339
|
updatePersonState(`person:${session.person.id}`, { activeOrgSlug: orgSlug })
|
|
323
340
|
},
|
|
324
341
|
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The simulated world's people as the auth settings see them (../configured-auth.ts): who is signed in and whether an
|
|
345
|
+
* account exists, with no org or role in it. A person's seeded tenant is their tenant claim, so a world run in single
|
|
346
|
+
* tenancy must seed its people in the configured tenant, as a deployment's accounts must not claim another. The
|
|
347
|
+
* simulated sign-in resolves a membership, so a world run with a fixed org source still seeds each person one.
|
|
348
|
+
*/
|
|
349
|
+
export const fakeIdentitySource: ProviderIdentitySource = {
|
|
350
|
+
async current() {
|
|
351
|
+
const session = await readSession()
|
|
352
|
+
if (!session) return null
|
|
353
|
+
const user = toUser(session.person, session.orgSlug)
|
|
354
|
+
return {
|
|
355
|
+
id: user.id,
|
|
356
|
+
name: user.name,
|
|
357
|
+
email: user.email,
|
|
358
|
+
locale: user.locale,
|
|
359
|
+
// An empty claim is no claim, as Clerk's adapter reads it.
|
|
360
|
+
tenantClaim: session.person.tenantSlug || undefined,
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
async account(userId) {
|
|
364
|
+
const person = findPerson(userId)
|
|
365
|
+
if (!person) return null
|
|
366
|
+
const name = readOverrides()[person.id]?.name ?? person.name
|
|
367
|
+
return { tenantClaim: person.tenantSlug || undefined, name, email: person.email }
|
|
368
|
+
},
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
|
|
372
|
+
function isProfileName(name: unknown): name is string {
|
|
373
|
+
return typeof name === 'string' && name.trim() !== '' && name.length <= 256
|
|
374
|
+
}
|
|
@@ -1,9 +1,39 @@
|
|
|
1
1
|
import { mkdirSync } from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* The directory all fake-adapter state lives under: APP_DATA_DIR, else `.data/` (gitignored), as an absolute path (a
|
|
6
|
+
* relative APP_DATA_DIR is read against the working directory). Absolute because fake storage keeps a key inside its
|
|
7
|
+
* directory by comparing resolved paths. Creates nothing.
|
|
8
|
+
*/
|
|
5
9
|
export function dataRoot(): string {
|
|
6
|
-
|
|
10
|
+
const dir = process.env['APP_DATA_DIR']
|
|
11
|
+
if (dir === undefined) return path.join(process.cwd(), '.data')
|
|
12
|
+
return absolute(dir)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `dir` as a normalised absolute path, against the working directory when it is relative. Written out by hand, because
|
|
17
|
+
* of what a build showed: with `path.resolve(<APP_DATA_DIR>)` here, and again with `path.join(process.cwd(), <it>)` or
|
|
18
|
+
* `path.normalize(<it>)`, Next's file tracer copied this whole directory's TypeScript source into the standalone
|
|
19
|
+
* server (pack and consume fails on it); with this function it copies none. Other path calls on runtime values in
|
|
20
|
+
* this directory do not trip it, so the trigger is narrower than "any path call": keep the environment value out of
|
|
21
|
+
* one. On Windows a UNC root and a drive-relative value (`D:rel`) are not supported.
|
|
22
|
+
*/
|
|
23
|
+
function absolute(dir: string): string {
|
|
24
|
+
const from = path.isAbsolute(dir) ? dir : `${process.cwd()}${path.sep}${dir}`
|
|
25
|
+
// A backslash separates only where it is the platform's separator: on POSIX it is a legal file-name character.
|
|
26
|
+
const separators = path.sep === '\\' ? /[\\/]+/ : /\/+/
|
|
27
|
+
const parts: string[] = []
|
|
28
|
+
for (const part of from.split(separators)) {
|
|
29
|
+
if (part === '.' || (part === '' && parts.length > 0)) continue
|
|
30
|
+
if (part === '..') {
|
|
31
|
+
if (parts.length > 1) parts.pop()
|
|
32
|
+
continue
|
|
33
|
+
}
|
|
34
|
+
parts.push(part)
|
|
35
|
+
}
|
|
36
|
+
return parts.length === 1 ? `${parts[0]}${path.sep}` : parts.join(path.sep)
|
|
7
37
|
}
|
|
8
38
|
|
|
9
39
|
/** A directory under the fake adapters' data root, created if missing. Tests point APP_DATA_DIR at a tmp dir. */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import type { EmailMessage, EmailPort } from '../../ports/email'
|
|
4
|
+
import { assertSendableMessage } from '../email-message'
|
|
4
5
|
import { writeJsonAtomic } from './atomic-write'
|
|
5
6
|
import { dataDir } from './data-dir'
|
|
6
7
|
|
|
@@ -19,6 +20,7 @@ let counter = 0
|
|
|
19
20
|
|
|
20
21
|
export const fakeEmail: EmailPort = {
|
|
21
22
|
async send(message) {
|
|
23
|
+
assertSendableMessage(message) // as the real adapter does, so a test on fakes catches a list in `to`
|
|
22
24
|
const caught: CaughtEmail = {
|
|
23
25
|
id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
|
|
24
26
|
at: new Date().toISOString(),
|
|
@@ -5,11 +5,12 @@ import { runJobInProcess } from '../../jobs/run-in-process'
|
|
|
5
5
|
import { NotFoundError } from '../../ports/errors'
|
|
6
6
|
import type { JobsPort, SubmittedJob } from '../../ports/jobs'
|
|
7
7
|
import { readFlags } from './analytics'
|
|
8
|
-
import {
|
|
8
|
+
import { personLocale } from './auth'
|
|
9
9
|
import { fakeDb } from './db'
|
|
10
10
|
import { fakeEmail } from './email'
|
|
11
11
|
import { fakeLlm } from './llm'
|
|
12
12
|
import { fakeSendSms } from './sms'
|
|
13
|
+
import { simulatedAuth } from './simulated-auth'
|
|
13
14
|
import { fakeStorage } from './storage'
|
|
14
15
|
|
|
15
16
|
/** Simulator flag: when set, submitted jobs stay 'queued' so an operator can step them forward. */
|
|
@@ -31,7 +32,7 @@ async function notifyTerminal(job: SubmittedJob, status: 'completed' | 'failed')
|
|
|
31
32
|
const { notifyJobTerminal } = await import('../../server-lib/notify')
|
|
32
33
|
await notifyJobTerminal(
|
|
33
34
|
{ db: fakeDb, email: fakeEmail, sms: fakeSendSms, resolveLocale: personLocale },
|
|
34
|
-
|
|
35
|
+
simulatedAuth(),
|
|
35
36
|
{ tenantId: job.tenantId, jobId: job.id, status },
|
|
36
37
|
)
|
|
37
38
|
} catch {
|
|
@@ -53,7 +54,7 @@ async function executeJob(job: SubmittedJob): Promise<boolean> {
|
|
|
53
54
|
storage: fakeStorage,
|
|
54
55
|
email: fakeEmail,
|
|
55
56
|
llm: fakeLlm,
|
|
56
|
-
auth:
|
|
57
|
+
auth: simulatedAuth(),
|
|
57
58
|
resolveLocale: personLocale,
|
|
58
59
|
}
|
|
59
60
|
return runJobInProcess(job, ports, (status) => notifyTerminal(job, status))
|
|
@@ -234,7 +235,7 @@ export async function produceJobArtifact(
|
|
|
234
235
|
storage: fakeStorage,
|
|
235
236
|
email: fakeEmail,
|
|
236
237
|
llm: fakeLlm,
|
|
237
|
-
auth:
|
|
238
|
+
auth: simulatedAuth(),
|
|
238
239
|
resolveLocale: personLocale,
|
|
239
240
|
tenantId: row.tenant_id,
|
|
240
241
|
orgId: row.org_id,
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { staffOrgSlug } from '@sssb/app-config/abilities'
|
|
2
|
+
import type { AuthPort } from '../../ports/auth'
|
|
3
|
+
import { authSettings } from '../auth-tenancy'
|
|
4
|
+
import { configuredAuth } from '../configured-auth'
|
|
5
|
+
import { fakeAuth, fakeIdentitySource } from './auth'
|
|
6
|
+
|
|
7
|
+
let cached: AuthPort | undefined
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The simulated world's auth port: the fake, placed as the environment's auth settings say (`AUTH_TENANCY`,
|
|
11
|
+
* `AUTH_ORG_SOURCE`: ../auth-tenancy.ts), and the bare fake on the defaults. Every simulated consumer takes it from
|
|
12
|
+
* here, the registry (../index.ts), the fake job runner's handlers and notifications (./jobs.ts) and the conformance
|
|
13
|
+
* suite's preset replay, so an app's `pnpm dev` places people as its deployment does everywhere, not only on the
|
|
14
|
+
* request path. Read on first use, so only in simulated mode: the registry imports the fakes in real mode too, where
|
|
15
|
+
* a misconfigured setting is the boot check's to report.
|
|
16
|
+
*
|
|
17
|
+
* The conformance suite's preset replay takes this too, deliberately: a preset that invites someone under a fixed org
|
|
18
|
+
* source, or signs in a person of another tenant under a single tenancy, describes a world the deployment cannot
|
|
19
|
+
* reach, and the replay says so.
|
|
20
|
+
*/
|
|
21
|
+
export function simulatedAuth(): AuthPort {
|
|
22
|
+
if (cached === undefined) cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug)
|
|
23
|
+
return cached
|
|
24
|
+
}
|
package/src/adapters/index.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type { LlmPort } from '../ports/llm'
|
|
|
9
9
|
import type { StoragePort } from '../ports/storage'
|
|
10
10
|
import { simulatedDevServer } from './dev-server'
|
|
11
11
|
import { fakeAnalytics } from './fake/analytics'
|
|
12
|
-
import {
|
|
12
|
+
import { simulatedAuth } from './fake/simulated-auth'
|
|
13
13
|
import { fakeDb } from './fake/db'
|
|
14
14
|
import { fakeEmail } from './fake/email'
|
|
15
15
|
import { fakeJobs } from './fake/jobs'
|
|
@@ -109,7 +109,8 @@ const real =
|
|
|
109
109
|
? await (await import('./real/index')).createRealPorts({ inProcessJobs: buildInProcessJobs })
|
|
110
110
|
: null
|
|
111
111
|
|
|
112
|
-
|
|
112
|
+
// The simulated world runs the deployment's auth tenancy when its environment sets one (./fake/simulated-auth.ts).
|
|
113
|
+
export const auth: AuthPort = real?.auth ?? simulatedAuth()
|
|
113
114
|
export const db: DbPort = real?.db ?? fakeDb
|
|
114
115
|
export const storage: StoragePort = real?.storage ?? fakeStorage
|
|
115
116
|
export const llm: LlmPort = real?.llm ?? fakeLlm
|