@sssb/cdk 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/cdk",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,11 +26,11 @@
26
26
  "peerDependencies": {
27
27
  "aws-cdk-lib": "^2.274.0",
28
28
  "constructs": "^10.8.1",
29
- "@sssb/tools": "0.5.0"
29
+ "@sssb/tools": "0.6.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "aws-cdk-lib": "^2.274.0",
33
33
  "constructs": "^10.8.1",
34
- "@sssb/tools": "0.5.0"
34
+ "@sssb/tools": "0.6.1"
35
35
  }
36
36
  }
@@ -0,0 +1,131 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * The app's auth settings, as its `params.auth` declares them, and the settings they set in the server's environment
5
+ * (@sssb/kit's `adapters/auth-tenancy.ts`, which the framework reads at boot; this package's test checks the choices
6
+ * agree, through the framework each app resolves). Left out, it sets nothing, and the framework takes its defaults:
7
+ * multi tenancy with the `tenantSlug` metadata key, and the identity provider's organizations.
8
+ *
9
+ * Two choices, one pairing refused:
10
+ * - `tenancy`, where the tenant comes from: `'multi'` (the default), each user's claim in their identity provider's
11
+ * metadata, under `tenantMetadataKey` when given; or `'single'`, the deployment's `tenantSlug`. A single tenancy
12
+ * changes nothing else.
13
+ * - `orgSource`, where organizations and roles come from: `'provider'` (the default), the identity provider's
14
+ * organizations and per-membership roles; or `'fixed'`, for an app that uses the provider without its organizations:
15
+ * every user it signs in is placed in `homeOrgSlug` with `defaultRole` (`'none'` when left out, or `'restricted'`).
16
+ * On a provider instance shared with another product, that product's users all sign in.
17
+ *
18
+ * Validated here, at synth, so a deployment never ships a setting the framework would refuse at boot: an unknown key or
19
+ * choice, a slug that is not one, a choice without its slug, a slug or role its choice does not use, or a default role
20
+ * outside the safe set. One check is the framework's alone, at boot: a fixed home org that is the app's staff org with
21
+ * a role other than `'none'`, since only the app's seam names its staff org.
22
+ */
23
+ export const AUTH_TENANCY_CHOICES = ['multi', 'single']
24
+ export const AUTH_ORG_SOURCE_CHOICES = ['provider', 'fixed']
25
+ export const FIXED_ORG_ROLES = ['none', 'restricted']
26
+
27
+ const KEYS = ['tenancy', 'tenantSlug', 'tenantMetadataKey', 'orgSource', 'homeOrgSlug', 'defaultRole']
28
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
29
+ const METADATA_KEY = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_][A-Za-z0-9_]*$/
30
+
31
+ /**
32
+ * @param {Record<string, unknown>} given
33
+ * @param {string} name
34
+ * @param {string[]} choices
35
+ * @returns {string}
36
+ */
37
+ function choiceOf(given, name, choices) {
38
+ const value = given[name] ?? choices[0]
39
+ if (typeof value !== 'string' || !choices.includes(value)) {
40
+ throw new Error(`SssbApp: params.auth.${name} must be ${choices.join(' or ')} (got ${JSON.stringify(value)})`)
41
+ }
42
+ return value
43
+ }
44
+
45
+ /**
46
+ * @param {Record<string, unknown>} given
47
+ * @param {string[]} names
48
+ * @param {string} setting
49
+ * @param {string} needed
50
+ * @param {string} chosen
51
+ */
52
+ function refuseStrays(given, names, setting, needed, chosen) {
53
+ const stray = names.filter((name) => given[name] !== undefined)
54
+ if (stray.length > 0) {
55
+ throw new Error(
56
+ `SssbApp: params.auth.${stray.join(' and ')} need ${setting} '${needed}' (${setting} is '${chosen}')`,
57
+ )
58
+ }
59
+ }
60
+
61
+ /**
62
+ * @param {Record<string, unknown>} given
63
+ * @param {string} name
64
+ * @param {string} needer
65
+ * @returns {string}
66
+ */
67
+ function slugOf(given, name, needer) {
68
+ const value = given[name]
69
+ if (typeof value !== 'string' || !SLUG.test(value)) {
70
+ throw new Error(`SssbApp: ${needer} needs params.auth.${name}, a slug (got ${JSON.stringify(value)})`)
71
+ }
72
+ return value
73
+ }
74
+
75
+ /**
76
+ * The server's settings for an app's `params.auth`, or a thrown error naming what is wrong.
77
+ * @param {unknown} auth
78
+ * @returns {Record<string, string>}
79
+ */
80
+ export function authEnvironment(auth) {
81
+ if (auth === undefined) return {}
82
+ if (typeof auth !== 'object' || auth === null || Array.isArray(auth)) {
83
+ throw new Error(`SssbApp: params.auth must be an object (got ${JSON.stringify(auth)})`)
84
+ }
85
+ const given = /** @type {Record<string, unknown>} */ (auth)
86
+ const unknown = Object.keys(given).filter((key) => !KEYS.includes(key))
87
+ if (unknown.length > 0) {
88
+ throw new Error(`SssbApp: params.auth has no ${unknown.join(', ')} (it takes ${KEYS.join(', ')})`)
89
+ }
90
+ const tenancy = choiceOf(given, 'tenancy', AUTH_TENANCY_CHOICES)
91
+ const orgSource = choiceOf(given, 'orgSource', AUTH_ORG_SOURCE_CHOICES)
92
+ /** @type {Record<string, string>} */
93
+ const env = { AUTH_TENANCY: tenancy, AUTH_ORG_SOURCE: orgSource }
94
+
95
+ const key = given['tenantMetadataKey']
96
+ if (key !== undefined) {
97
+ if (typeof key !== 'string' || !METADATA_KEY.test(key)) {
98
+ throw new Error(
99
+ `SssbApp: params.auth.tenantMetadataKey must be a plain identifier (got ${JSON.stringify(key)})`,
100
+ )
101
+ }
102
+ env['AUTH_TENANT_METADATA_KEY'] = key
103
+ }
104
+
105
+ if (tenancy === 'multi') refuseStrays(given, ['tenantSlug'], 'tenancy', 'single', 'multi')
106
+ else env['AUTH_TENANT_SLUG'] = slugOf(given, 'tenantSlug', "tenancy 'single'")
107
+
108
+ if (orgSource === 'provider') {
109
+ refuseStrays(given, ['homeOrgSlug', 'defaultRole'], 'orgSource', 'fixed', 'provider')
110
+ } else {
111
+ if (tenancy !== 'single') {
112
+ throw new Error(
113
+ "SssbApp: params.auth.orgSource 'fixed' needs tenancy 'single': with a multi tenancy the tenant claim in " +
114
+ "the identity provider's metadata would be all that places a person",
115
+ )
116
+ }
117
+ env['AUTH_HOME_ORG_SLUG'] = slugOf(given, 'homeOrgSlug', "orgSource 'fixed'")
118
+ const role = given['defaultRole']
119
+ if (role !== undefined) {
120
+ if (typeof role !== 'string' || !FIXED_ORG_ROLES.includes(role)) {
121
+ throw new Error(
122
+ `SssbApp: params.auth.defaultRole must be ${FIXED_ORG_ROLES.join(' or ')} (got ` +
123
+ `${JSON.stringify(role)}): everyone the identity provider signs in gets it, so no role that ` +
124
+ 'writes is offered',
125
+ )
126
+ }
127
+ env['AUTH_DEFAULT_ROLE'] = role
128
+ }
129
+ }
130
+ return env
131
+ }
package/src/index.d.ts CHANGED
@@ -29,6 +29,27 @@ export interface OptionalPorts {
29
29
  readonly storage?: 's3' | 's3-compatible' | 'none'
30
30
  }
31
31
 
32
+ /**
33
+ * How the auth adapter places a signed-in person: the app's `params.auth`, two choices. The construct sets
34
+ * `AUTH_TENANCY`, `AUTH_ORG_SOURCE` and the settings each choice reads; left out, the framework takes multi tenancy
35
+ * with the `tenantSlug` metadata key, and the identity provider's organizations.
36
+ * - `tenancy: 'single'` fixes the tenant at `tenantSlug` and changes nothing else.
37
+ * - `orgSource: 'fixed'`, which needs `tenancy: 'single'`, is for an app that uses the identity provider without its
38
+ * organizations: every user it signs in is placed in `homeOrgSlug` with `defaultRole` (`'none'` when left out, which grants nothing a membership would;
39
+ * or `'restricted'`). On a provider instance shared with another product, its users all sign in.
40
+ */
41
+ export type AuthTenancyParams = (
42
+ | { readonly tenancy?: 'multi'; readonly orgSource?: 'provider' }
43
+ | { readonly tenancy: 'single'; readonly tenantSlug: string; readonly orgSource?: 'provider' }
44
+ | {
45
+ readonly tenancy: 'single'
46
+ readonly tenantSlug: string
47
+ readonly orgSource: 'fixed'
48
+ readonly homeOrgSlug: string
49
+ readonly defaultRole?: 'none' | 'restricted'
50
+ }
51
+ ) & { readonly tenantMetadataKey?: string }
52
+
32
53
  /** The scheduled tick: what runs the app's scheduled work (its cron route) in the deployment. */
33
54
  export interface ScheduledTickProps {
34
55
  /**
@@ -53,7 +74,11 @@ export interface SssbAppProps {
53
74
  */
54
75
  readonly slug: string
55
76
  /** The app's deployment params (`config/params.ts`); the construct reads `database.transport` and `ports`. */
56
- readonly params: { readonly database: { readonly transport: DatabaseTransport }; readonly ports?: OptionalPorts }
77
+ readonly params: {
78
+ readonly database: { readonly transport: DatabaseTransport }
79
+ readonly ports?: OptionalPorts
80
+ readonly auth?: AuthTenancyParams
81
+ }
57
82
  /** The deployment's name, as the app's own policy spells it (`Staging`, `Production`). */
58
83
  readonly environment: string
59
84
  /** A production deployment: the database keeps a warm writer and the data stores are retained. */
package/src/sssb-app.js CHANGED
@@ -12,6 +12,7 @@ import { failClosedEnvironmentProblems, migratorBundleProblems } from '@sssb/too
12
12
  import { kitDirOf, kitVersionOf, resolveAppsKit } from '@sssb/tools/kit'
13
13
  import { databaseNameFor, SLUG } from './database-name.js'
14
14
  import { FORWARDED_HOST_SOURCE } from './forwarded-host.js'
15
+ import { authEnvironment } from './auth-tenancy.js'
15
16
  import { portsEnvironment } from './optional-ports.js'
16
17
  import { addScheduledTick } from './scheduled-tick.js'
17
18
 
@@ -244,6 +245,13 @@ export const HSTS_MAX_AGE_SECONDS = 31_536_000
244
245
  /** AWS's managed SecurityHeadersPolicy (CloudFront's guide, "Use managed response headers policies"). */
245
246
  export const MANAGED_SECURITY_HEADERS_POLICY_ID = '67f7725c-6f97-4210-82d7-5512b31e9d03'
246
247
 
248
+ /**
249
+ * The first line of the Migrator's ESM bundle: a `require` for the CommonJS code esbuild inlines. Under its own name, so
250
+ * a bundled module's `createRequire` import cannot collide with it.
251
+ */
252
+ const MIGRATOR_REQUIRE_BANNER =
253
+ "import { createRequire as __sssbCreateRequire } from 'node:module'; const require = __sssbCreateRequire(import.meta.url);"
254
+
247
255
  /** After every tag aspect: CDK's own run at `AspectPriority.MUTATING` (200) or the default (500). */
248
256
  const MIRROR_PRIORITY = 900
249
257
 
@@ -369,6 +377,8 @@ export class SssbApp extends Construct {
369
377
  }
370
378
  // The optional ports' switches (LLM_PROVIDER, …), from `params.ports`: validated here, before anything is built.
371
379
  const portsEnv = portsEnvironment(props.params?.ports)
380
+ // The auth settings (AUTH_TENANCY, AUTH_ORG_SOURCE, …), from `params.auth`: validated here too.
381
+ const authEnv = authEnvironment(props.params?.auth)
372
382
  // Storage left out is the framework's default, `s3`: the bucket below exists for `s3` alone. `s3-compatible`
373
383
  // keeps its objects in a store this stack does not own (R2, MinIO, B2), and `none` stores nothing.
374
384
  const storesObjects = (portsEnv['STORAGE_PROVIDER'] ?? 's3') === 's3'
@@ -530,8 +540,8 @@ export class SssbApp extends Construct {
530
540
  // (next/dist/build/utils.js). Pinned to that default: the Web Adapter calls the server on 127.0.0.1,
531
541
  // so an inherited HOSTNAME naming another address would leave it nothing to call, and with 127.0.0.1
532
542
  // itself Next names itself `localhost` to the proxy but `127.0.0.1` when it routes, so a rewrite the
533
- // proxy makes (Clerk's, on every request) looks external and Next fetches it over the network (pages,
534
- // 2026-11-18). No wider than that: on pg the server's security group admits nothing, and on data-api
543
+ // proxy makes (Clerk's, on every request) looks external and Next fetches it over the network (an adopter's
544
+ // finding, 2026-11-18). No wider than that: on pg the server's security group admits nothing, and on data-api
535
545
  // it is in no VPC. A run.sh that exports HOSTNAME overrides this; the deploy pipeline's must not.
536
546
  HOSTNAME: '0.0.0.0',
537
547
  APP_MODE: 'real',
@@ -539,6 +549,7 @@ export class SssbApp extends Construct {
539
549
  ...databaseEnv,
540
550
  ...(storageBucket && { STORAGE_BUCKET: storageBucket.bucketName }),
541
551
  ...portsEnv,
552
+ ...authEnv,
542
553
  },
543
554
  })
544
555
  grantDatabase(server)
@@ -573,6 +584,10 @@ export class SssbApp extends Construct {
573
584
  : { DATABASE_TRANSPORT: 'pg', DB_SECRET_ARN: secret.secretArn, DATABASE_NAME: databaseName },
574
585
  bundling: {
575
586
  format: aws_lambda_nodejs.OutputFormat.ESM,
587
+ // An ESM bundle has no `require`, and esbuild's stand-in for the CommonJS packages it inlines (`pg`,
588
+ // whose `require('events')` runs when the handler module loads, on either transport) throws "Dynamic
589
+ // require of ... is not supported". So the bundle defines one, Node's own, for its own path.
590
+ banner: MIGRATOR_REQUIRE_BANNER,
576
591
  // pg's optional native/cloudflare shims must stay external or esbuild chokes
577
592
  externalModules: ['@aws-sdk/*', 'pg-native', 'cloudflare:sockets'],
578
593
  esbuildArgs: { '--alias:@sssb/app-config': migratorSource.seamDir },