saaslayer 0.4.2 → 0.5.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.
Files changed (62) hide show
  1. package/bin/saaslayer.js +23 -11
  2. package/package.json +7 -7
  3. package/src/cdn-aws.js +67 -0
  4. package/src/cdn-publication.js +146 -0
  5. package/src/cdn-publisher.js +166 -0
  6. package/src/commands/cdn.js +66 -0
  7. package/src/commands/deploy.js +4 -3
  8. package/src/commands/lifecycle.js +20 -2
  9. package/src/commands/operations.js +8 -3
  10. package/src/commands/stacks.js +2 -0
  11. package/src/commands/users-management.js +2 -2
  12. package/src/deployments.js +5 -2
  13. package/src/module-catalog.js +15 -5
  14. package/src/sms/scope.js +4 -2
  15. package/src/source-branch.js +36 -0
  16. package/src/users-import/ids.js +1 -1
  17. package/templates/saaslayer-foundation.yml +215 -281
  18. package/vendor/config/login-domain.js +213 -0
  19. package/vendor/discovery/index.d.mts +109 -0
  20. package/vendor/discovery/index.mjs +409 -0
  21. package/vendor/ids/index.d.ts +21 -0
  22. package/vendor/ids/index.js +237 -0
  23. package/vendor/migrations/backups.js +118 -0
  24. package/vendor/migrations/child.js +78 -0
  25. package/vendor/migrations/credentials.js +103 -0
  26. package/vendor/migrations/errors.js +30 -0
  27. package/vendor/migrations/exec-child.js +78 -0
  28. package/vendor/migrations/gate.js +51 -0
  29. package/vendor/migrations/index.js +30 -0
  30. package/vendor/migrations/inventory.js +92 -0
  31. package/vendor/migrations/log.js +14 -0
  32. package/vendor/migrations/release.js +45 -0
  33. package/vendor/migrations/report.js +129 -0
  34. package/vendor/migrations/rules.js +104 -0
  35. package/vendor/migrations/run.js +311 -0
  36. package/vendor/migrations/session-policy.js +37 -0
  37. package/vendor/migrations/step-guard.js +82 -0
  38. package/vendor/operations/activity.d.ts +21 -0
  39. package/vendor/operations/activity.js +126 -0
  40. package/vendor/operations/index.d.ts +72 -0
  41. package/vendor/operations/index.js +510 -0
  42. package/vendor/permissions-engine-core/account-status.js +270 -0
  43. package/vendor/permissions-engine-core/delegation.js +174 -0
  44. package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
  45. package/vendor/permissions-engine-core/sso-claims.js +206 -0
  46. package/vendor/user-management/cognito/emails/token-registry.js +48 -0
  47. package/vendor/user-management/email/validate.js +207 -0
  48. package/vendor/user-management/extensibility/hook-contract.js +720 -0
  49. package/vendor/user-management/extensibility/safe-webhook.js +85 -0
  50. package/vendor/user-management/identity/admission.js +215 -0
  51. package/vendor/user-management/identity/attr.js +27 -0
  52. package/vendor/user-management/identity/attribute-registry.js +115 -0
  53. package/vendor/user-management/identity/email.js +25 -0
  54. package/vendor/user-management/identity/ensure-suid.js +74 -0
  55. package/vendor/user-management/identity/pointers.js +192 -0
  56. package/vendor/user-management/identity/stitch-provider.js +275 -0
  57. package/vendor/user-management/management/apply-request.js +227 -0
  58. package/vendor/user-management/management/core-profile.js +110 -0
  59. package/vendor/user-management/management/index.js +23 -0
  60. package/vendor/user-management/management/purposes.js +94 -0
  61. package/vendor/user-management/management/registry.js +569 -0
  62. package/vendor/user-management/store/table.js +332 -0
@@ -0,0 +1,409 @@
1
+ // Deployment configuration discovery: maps a deployment's stable, public module outputs (user-service + permissions-service) to
2
+ // one versioned discovery document, decodes it when fetched from the public discovery route, and selects deployments.
3
+ // Only allowlisted public configuration is ever produced: pool/client ids, region, issuer/audience, public URLs.
4
+
5
+ /**
6
+ * The version the control plane writes. Bumped (with a new route revision) whenever a field is added, removed or renamed,
7
+ * once every supported reader decodes the new version (it is always the oldest supported version).
8
+ */
9
+ export const DISCOVERY_CONTRACT_VERSION = 2
10
+
11
+ /**
12
+ * The contract versions this reader decodes, oldest first, ending at DISCOVERY_CONTRACT_VERSION. Readers that accept a
13
+ * version ship before any document of that version is published (readers before writers).
14
+ * @type {ReadonlyArray<number>}
15
+ */
16
+ export const SUPPORTED_DISCOVERY_VERSIONS = Object.freeze([2])
17
+
18
+ /** The deployer's default service-instance label (one instance of a module per deployment unless named). */
19
+ const DEFAULT_INSTANCE = '_'
20
+
21
+ /**
22
+ * Which stable module output each discovery field reads. Output names are part of the public contract: each one must
23
+ * be a declared `stable` output of its module (the control-plane API test checks this against the module catalog).
24
+ * @type {ReadonlyArray<{ field: string, module: 'user-service'|'permissions-service', output: string, required: boolean }>}
25
+ */
26
+ export const DISCOVERY_OUTPUTS = Object.freeze([
27
+ { field: 'userPoolId', module: 'user-service', output: 'UserPoolId', required: true },
28
+ { field: 'clientId', module: 'user-service', output: 'UserPoolClientId', required: true },
29
+ { field: 'hostedLoginUrl', module: 'user-service', output: 'UserPoolDomainName', required: true },
30
+ { field: 'usersApiBase', module: 'user-service', output: 'ServiceEndpoint', required: true },
31
+ { field: 'jwksUrl', module: 'user-service', output: 'JsonWebKeyUrl', required: true },
32
+ { field: 'passwordlessApiBase', module: 'user-service', output: 'PasswordlessApiBaseUrl', required: false },
33
+ { field: 'permissionsApiBase', module: 'permissions-service', output: 'ServiceEndpoint', required: true },
34
+ ])
35
+
36
+ /** Every field of a discovery document, in order. Nothing else is ever discoverable. */
37
+ export const DISCOVERY_FIELDS = Object.freeze([
38
+ 'contractVersion', 'deploymentId', 'revision', 'region', 'userPoolId', 'clientId', 'issuer', 'audience', 'jwksUrl',
39
+ 'hostedLoginUrl', 'usersApiBase', 'permissionsApiBase', 'passwordlessApiBase',
40
+ ])
41
+
42
+ /**
43
+ * The environment variables a consumer configures statically from a discovery document (`saaslayer env export` and the
44
+ * console's env block), in print order, each naming the document field it carries. Nothing else is exported as env.
45
+ * @type {ReadonlyArray<{ name: string, field: 'userPoolId'|'clientId'|'region'|'issuer'|'jwksUrl'|'usersApiBase'|'permissionsApiBase'|'hostedLoginUrl' }>}
46
+ */
47
+ export const DISCOVERY_ENV_VARS = Object.freeze([
48
+ { name: 'SAASLAYER_USER_POOL_ID', field: 'userPoolId' },
49
+ { name: 'SAASLAYER_CLIENT_ID', field: 'clientId' },
50
+ { name: 'SAASLAYER_REGION', field: 'region' },
51
+ { name: 'SAASLAYER_ISSUER', field: 'issuer' },
52
+ { name: 'SAASLAYER_JWKS_URL', field: 'jwksUrl' },
53
+ { name: 'SAASLAYER_USERS_API_BASE', field: 'usersApiBase' },
54
+ { name: 'SAASLAYER_PERMISSIONS_API_BASE', field: 'permissionsApiBase' },
55
+ { name: 'SAASLAYER_HOSTED_LOGIN_URL', field: 'hostedLoginUrl' },
56
+ ])
57
+
58
+ const URL_FIELDS = ['issuer', 'jwksUrl', 'hostedLoginUrl', 'usersApiBase', 'permissionsApiBase', 'passwordlessApiBase']
59
+ const NULLABLE_FIELDS = new Set(['revision', 'passwordlessApiBase'])
60
+ const POOL_ID = /^([a-z]{2}(?:-[a-z]+)+-\d)_[A-Za-z0-9]+$/
61
+ // Values that must never appear in public configuration: secret ARNs, SaaSLayer secret/service keys, JWTs, PEM keys.
62
+ const SECRET_SHAPES = [/arn:aws:secretsmanager:/i, /arn:aws:ssm:.*parameter/i, /\bsl(?:sk|ak)_/i, /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/, /-----BEGIN [A-Z ]*PRIVATE KEY/]
63
+
64
+ /**
65
+ * @typedef {object} DeploymentDiscovery
66
+ * @property {number} contractVersion
67
+ * @property {string} deploymentId
68
+ * @property {string|null} revision - the release revision (commit) the deployment runs
69
+ * @property {string} region
70
+ * @property {string} userPoolId
71
+ * @property {string} clientId
72
+ * @property {string} issuer - the `iss` of the deployment's ID tokens
73
+ * @property {string[]} audience - accepted `aud` values (the deployment's app clients)
74
+ * @property {string} jwksUrl
75
+ * @property {string} hostedLoginUrl - hosted sign-in (OAuth2 authorization server) base URL
76
+ * @property {string} usersApiBase
77
+ * @property {string} permissionsApiBase
78
+ * @property {string|null} passwordlessApiBase - null when passwordless is off
79
+ */
80
+
81
+ /**
82
+ * @typedef {object} ModuleOutputsRecord
83
+ * @property {string|null} moduleName
84
+ * @property {string|null} [serviceInstance]
85
+ * @property {Record<string, unknown>} [outputs] - raw stack outputs
86
+ * @property {Record<string, unknown>} [publicOutputs] - public hostnames; win per output over `outputs`
87
+ */
88
+
89
+ /** @typedef {{ 'user-service'?: string, 'permissions-service'?: string }} DiscoveryInstances */
90
+
91
+ export class DeploymentDiscoveryError extends Error {
92
+ /**
93
+ * @param {string} code - MODULE_NOT_DEPLOYED | OUTPUT_MISSING | INVALID_OUTPUT | NOT_PUBLIC | INVALID_DOCUMENT |
94
+ * UNSUPPORTED_CONTRACT | NOT_FOUND | AMBIGUOUS | UNAVAILABLE
95
+ * @param {string} message
96
+ * @param {{ output?: string, status?: number }} [extra]
97
+ */
98
+ constructor(code, message, extra = {}) {
99
+ super(message)
100
+ this.name = 'DeploymentDiscoveryError'
101
+ this.code = code
102
+ if (extra.output) this.output = extra.output
103
+ if (extra.status) this.status = extra.status
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @param {string} module
109
+ * @param {string} instance
110
+ */
111
+ function moduleRef(module, instance) {
112
+ return instance === DEFAULT_INSTANCE ? module : `${module}@${instance}`
113
+ }
114
+
115
+ /**
116
+ * One module's outputs, public hostnames winning per output.
117
+ * @param {ModuleOutputsRecord[]} modules
118
+ * @param {string} module
119
+ * @param {string} instance
120
+ * @returns {Record<string, unknown>}
121
+ */
122
+ function moduleOutputs(modules, module, instance) {
123
+ const record = modules.find((m) => m.moduleName === module && (m.serviceInstance || DEFAULT_INSTANCE) === instance)
124
+ if (!record) throw new DeploymentDiscoveryError('MODULE_NOT_DEPLOYED', `module ${moduleRef(module, instance)} is not deployed in this deployment`)
125
+ return { ...(record.outputs || {}), ...(record.publicOutputs || {}) }
126
+ }
127
+
128
+ /**
129
+ * A declared output's value, or a clear error naming it (and the outputs the module does have — names only).
130
+ * @param {Record<string, unknown>} outputs
131
+ * @param {{ module: string, output: string, required: boolean }} spec
132
+ * @param {string} instance
133
+ * @returns {string|null}
134
+ */
135
+ function readOutput(outputs, spec, instance) {
136
+ const value = outputs[spec.output]
137
+ if (typeof value === 'string' && value.trim()) return value.trim()
138
+ if (!spec.required) return null
139
+ const name = `${moduleRef(spec.module, instance)}.${spec.output}`
140
+ const present = Object.keys(outputs).sort().join(', ') || 'none'
141
+ throw new DeploymentDiscoveryError('OUTPUT_MISSING', `deployment output ${name} is missing (${moduleRef(spec.module, instance)} has: ${present})`, { output: name })
142
+ }
143
+
144
+ /**
145
+ * The hosted sign-in base URL: a custom domain is used as-is, a Cognito prefix domain becomes its amazoncognito.com host.
146
+ * @param {string} domain
147
+ * @param {string} region
148
+ */
149
+ function hostedLoginUrl(domain, region) {
150
+ const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '')
151
+ return host.includes('.') ? `https://${host}` : `https://${host}.auth.${region}.amazoncognito.com`
152
+ }
153
+
154
+ /**
155
+ * Build the discovery document from a deployment's module records.
156
+ * @param {{ deploymentId: string, region?: string|null, revision?: string|null, modules: ModuleOutputsRecord[], instances?: DiscoveryInstances }} input
157
+ * @returns {DeploymentDiscovery}
158
+ */
159
+ export function deploymentDiscoveryFromModules(input) {
160
+ const instances = input.instances || {}
161
+ /** @type {Record<string, string|null>} */
162
+ const values = {}
163
+ /** @type {Record<string, Record<string, unknown>>} */
164
+ const byModule = {}
165
+ for (const spec of DISCOVERY_OUTPUTS) {
166
+ const instance = instances[spec.module] || DEFAULT_INSTANCE
167
+ byModule[spec.module] = byModule[spec.module] || moduleOutputs(input.modules, spec.module, instance)
168
+ values[spec.field] = readOutput(byModule[spec.module], spec, instance)
169
+ }
170
+ const userPoolId = /** @type {string} */ (values.userPoolId)
171
+ const poolRegion = POOL_ID.exec(userPoolId)?.[1]
172
+ const poolOutput = `${moduleRef('user-service', instances['user-service'] || DEFAULT_INSTANCE)}.UserPoolId`
173
+ if (!poolRegion) throw new DeploymentDiscoveryError('INVALID_OUTPUT', `deployment output ${poolOutput} is not a user pool id`, { output: poolOutput })
174
+ if (input.region && input.region !== poolRegion) {
175
+ throw new DeploymentDiscoveryError('INVALID_OUTPUT', `deployment output ${poolOutput} is in ${poolRegion}, not the deployment region ${input.region}`, { output: poolOutput })
176
+ }
177
+ const clientId = /** @type {string} */ (values.clientId)
178
+ /** @type {DeploymentDiscovery} */
179
+ const doc = {
180
+ contractVersion: DISCOVERY_CONTRACT_VERSION,
181
+ deploymentId: input.deploymentId,
182
+ revision: input.revision || null,
183
+ region: poolRegion,
184
+ userPoolId,
185
+ clientId,
186
+ issuer: `https://cognito-idp.${poolRegion}.amazonaws.com/${userPoolId}`,
187
+ audience: [clientId],
188
+ jwksUrl: /** @type {string} */ (values.jwksUrl),
189
+ hostedLoginUrl: hostedLoginUrl(/** @type {string} */ (values.hostedLoginUrl), poolRegion),
190
+ usersApiBase: /** @type {string} */ (values.usersApiBase),
191
+ permissionsApiBase: /** @type {string} */ (values.permissionsApiBase),
192
+ passwordlessApiBase: values.passwordlessApiBase,
193
+ }
194
+ return assertPublicDiscovery(doc)
195
+ }
196
+
197
+ /**
198
+ * Guard: a discovery document holds exactly the public fields, URL fields are https URLs, and no value has a secret's
199
+ * shape. Errors name the field, never its value.
200
+ * @template {Record<string, unknown>} T
201
+ * @param {T} doc
202
+ * @returns {T}
203
+ */
204
+ export function assertPublicDiscovery(doc) {
205
+ const allowed = new Set(DISCOVERY_FIELDS)
206
+ for (const key of Object.keys(doc)) {
207
+ if (!allowed.has(key)) throw new DeploymentDiscoveryError('NOT_PUBLIC', `discovery field "${key}" is not public configuration`)
208
+ }
209
+ for (const [key, value] of Object.entries(doc)) {
210
+ const strings = Array.isArray(value) ? value : [value]
211
+ if (strings.some((v) => typeof v === 'string' && SECRET_SHAPES.some((re) => re.test(v)))) {
212
+ throw new DeploymentDiscoveryError('NOT_PUBLIC', `discovery field "${key}" holds a secret-shaped value`)
213
+ }
214
+ if (URL_FIELDS.includes(key) && value !== null && !(typeof value === 'string' && value.startsWith('https://'))) {
215
+ throw new DeploymentDiscoveryError('NOT_PUBLIC', `discovery field "${key}" must be an https URL`)
216
+ }
217
+ }
218
+ return doc
219
+ }
220
+
221
+ /**
222
+ * Validate a fetched discovery document (JSON:API `data.attributes`), keeping only the contract's fields.
223
+ * @param {unknown} raw
224
+ * @returns {DeploymentDiscovery}
225
+ */
226
+ export function decodeDeploymentDiscovery(raw) {
227
+ const attributes = /** @type {{ data?: { attributes?: unknown } }} */ (raw || {}).data?.attributes
228
+ if (!attributes || typeof attributes !== 'object') throw new DeploymentDiscoveryError('INVALID_DOCUMENT', 'discovery response is not a JSON:API document with data.attributes')
229
+ const a = /** @type {Record<string, unknown>} */ (attributes)
230
+ if (!SUPPORTED_DISCOVERY_VERSIONS.includes(/** @type {number} */ (a.contractVersion))) {
231
+ throw new DeploymentDiscoveryError('UNSUPPORTED_CONTRACT', `discovery contract version ${String(a.contractVersion)} is not supported (this client reads versions ${SUPPORTED_DISCOVERY_VERSIONS.join(', ')}); upgrade the SDK`)
232
+ }
233
+ /** @type {Record<string, unknown>} */
234
+ const doc = {}
235
+ for (const field of DISCOVERY_FIELDS) {
236
+ const value = a[field]
237
+ const ok = field === 'contractVersion' ? true
238
+ : field === 'audience' ? Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === 'string' && v)
239
+ : (typeof value === 'string' && value !== '') || (NULLABLE_FIELDS.has(field) && (value === null || value === undefined))
240
+ if (!ok) throw new DeploymentDiscoveryError('INVALID_DOCUMENT', `discovery document field "${field}" is missing or invalid`)
241
+ doc[field] = value === undefined ? null : value
242
+ }
243
+ return /** @type {DeploymentDiscovery} */ (assertPublicDiscovery(doc))
244
+ }
245
+
246
+ /**
247
+ * Guard before serving a discovery document: it must decode under the oldest supported reader, so no reader still in
248
+ * support is handed a document it refuses. Returns the document unchanged; throws instead of publishing part of it.
249
+ * @template T
250
+ * @param {T} raw - the JSON:API document about to be published
251
+ * @returns {T}
252
+ */
253
+ export function assertPublishableDiscovery(raw) {
254
+ const doc = decodeDeploymentDiscovery(raw)
255
+ const oldest = SUPPORTED_DISCOVERY_VERSIONS[0]
256
+ if (doc.contractVersion !== oldest) {
257
+ throw new DeploymentDiscoveryError('UNSUPPORTED_CONTRACT', `discovery contract version ${doc.contractVersion} is not read by the oldest supported reader (version ${oldest}); ship readers first`)
258
+ }
259
+ return raw
260
+ }
261
+
262
+ /**
263
+ * The public discovery URL for a deployment (or the given URL as-is).
264
+ * @param {{ url: string } | { apiBase: string, deploymentId: string, instances?: DiscoveryInstances }} target
265
+ * @returns {string}
266
+ */
267
+ export function deploymentDiscoveryUrl(target) {
268
+ if ('url' in target && target.url) return target.url
269
+ const t = /** @type {{ apiBase: string, deploymentId: string, instances?: DiscoveryInstances }} */ (target)
270
+ if (!t.apiBase || !t.deploymentId) throw new DeploymentDiscoveryError('INVALID_DOCUMENT', 'discovery needs a url, or an apiBase and a deploymentId')
271
+ const params = new URLSearchParams()
272
+ if (t.instances?.['user-service']) params.set('userService', t.instances['user-service'])
273
+ if (t.instances?.['permissions-service']) params.set('permissions', t.instances['permissions-service'])
274
+ const query = params.toString()
275
+ return `${t.apiBase.replace(/\/+$/, '')}/api/discovery/${encodeURIComponent(t.deploymentId)}${query ? `?${query}` : ''}`
276
+ }
277
+
278
+ /**
279
+ * Fetch a deployment's discovery document from the public (unauthenticated) discovery route.
280
+ * @param {{ url: string } | { apiBase: string, deploymentId: string, instances?: DiscoveryInstances }} target
281
+ * @param {{ fetch?: typeof fetch }} [options]
282
+ * @returns {Promise<DeploymentDiscovery>}
283
+ */
284
+ export async function fetchDeploymentDiscovery(target, options = {}) {
285
+ const doFetch = options.fetch || globalThis.fetch
286
+ if (!doFetch) throw new DeploymentDiscoveryError('UNAVAILABLE', 'no fetch available; pass options.fetch')
287
+ const url = deploymentDiscoveryUrl(target)
288
+ /** @type {Response} */
289
+ let res
290
+ try {
291
+ res = await doFetch(url, { method: 'GET', headers: { Accept: 'application/vnd.api+json, application/json' } })
292
+ } catch (err) {
293
+ throw new DeploymentDiscoveryError('UNAVAILABLE', `discovery request to ${url} failed: ${err && /** @type {Error} */ (err).message}`)
294
+ }
295
+ /** @type {any} */
296
+ let body = null
297
+ try { body = await res.json() } catch { body = null }
298
+ if (!res.ok) {
299
+ const problem = Array.isArray(body?.errors) ? body.errors[0] : null
300
+ const code = res.status === 404 ? 'NOT_FOUND' : (typeof problem?.code === 'string' ? problem.code : 'UNAVAILABLE')
301
+ const detail = problem?.detail || problem?.title || `HTTP ${res.status}`
302
+ throw new DeploymentDiscoveryError(code, `discovery failed: ${detail}`, { status: res.status })
303
+ }
304
+ return decodeDeploymentDiscovery(body)
305
+ }
306
+
307
+ /**
308
+ * A deployment's discovery document, looked up at first use and kept. With `target.refreshSeconds`, a lookup older than
309
+ * that many seconds starts one background refresh (concurrent callers share it) while callers keep the current document;
310
+ * there is never a lookup per call and no timer holds the process open. A failed refresh keeps the last-known-good
311
+ * document, warns once per outage and waits a full interval before trying again. A refresh with unchanged content keeps
312
+ * the same document object, so callers rebuild what they derive from it only when it changed.
313
+ * @param {{ url: string, refreshSeconds?: number } | { apiBase: string, deploymentId: string, instances?: DiscoveryInstances }} target
314
+ * @param {{ fetch?: typeof fetch, now?: () => number }} [options] - now: the clock in milliseconds (default Date.now)
315
+ * @returns {{ get: () => Promise<DeploymentDiscovery> }}
316
+ */
317
+ export function createDiscoverySource(target, options = {}) {
318
+ const refreshSeconds = /** @type {{ refreshSeconds?: number }} */ (target).refreshSeconds
319
+ if (refreshSeconds !== undefined && !(typeof refreshSeconds === 'number' && Number.isFinite(refreshSeconds) && refreshSeconds > 0)) {
320
+ throw new TypeError('discovery refreshSeconds must be a positive number of seconds')
321
+ }
322
+ const now = options.now || (() => Date.now())
323
+ /** @type {DeploymentDiscovery|null} */
324
+ let current = null
325
+ let fetchedAt = 0
326
+ /** @type {Promise<DeploymentDiscovery>|null} */
327
+ let inFlight = null
328
+ let warned = false
329
+
330
+ /** @param {DeploymentDiscovery} doc */
331
+ const adopt = (doc) => {
332
+ if (!current || JSON.stringify(current) !== JSON.stringify(doc)) current = doc
333
+ fetchedAt = now()
334
+ warned = false
335
+ return current
336
+ }
337
+ const lookup = () => {
338
+ inFlight = inFlight || fetchDeploymentDiscovery(target, { fetch: options.fetch }).finally(() => { inFlight = null })
339
+ return inFlight
340
+ }
341
+
342
+ return {
343
+ async get() {
344
+ if (!current) {
345
+ try {
346
+ return adopt(await lookup())
347
+ } catch (err) {
348
+ if (current) return current
349
+ const e = /** @type {DeploymentDiscoveryError} */ (err)
350
+ throw new DeploymentDiscoveryError('UNAVAILABLE', `discovery has no configuration yet: ${e.code ? `${e.code}: ` : ''}${e.message}`, e.status ? { status: e.status } : {})
351
+ }
352
+ }
353
+ if (refreshSeconds !== undefined && !inFlight && now() - fetchedAt >= refreshSeconds * 1000) {
354
+ lookup().then(adopt, (err) => {
355
+ fetchedAt = now()
356
+ if (warned) return
357
+ warned = true
358
+ console.warn('discovery refresh failed', err && err.code, err && err.message)
359
+ })
360
+ }
361
+ return /** @type {DeploymentDiscovery} */ (current)
362
+ },
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Pick one deployment by project (slug or customer id) + environment (+ region) from a deployment list.
368
+ * @template {{ deploymentId: string, customerSlug?: string|null, customerId?: string|null, environment?: string|null, region?: string|null }} T
369
+ * @param {T[]} rows
370
+ * @param {{ project: string, environment: string, region?: string }} query
371
+ * @returns {T}
372
+ */
373
+ export function selectDeployment(rows, query) {
374
+ const matches = rows.filter((r) =>
375
+ (r.customerSlug === query.project || r.customerId === query.project)
376
+ && r.environment === query.environment
377
+ && (!query.region || r.region === query.region))
378
+ const where = `${query.project}/${query.environment}${query.region ? `/${query.region}` : ''}`
379
+ if (matches.length === 0) throw new DeploymentDiscoveryError('NOT_FOUND', `no deployment for ${where}`)
380
+ if (matches.length > 1) {
381
+ const list = matches.map((r) => `${r.deploymentId} (${r.region})`).join(', ')
382
+ throw new DeploymentDiscoveryError('AMBIGUOUS', `${matches.length} deployments match ${where}: ${list}; pass a region to choose one`)
383
+ }
384
+ return /** @type {T} */ (matches[0])
385
+ }
386
+
387
+ /**
388
+ * A discovery document as environment variables (DISCOVERY_ENV_VARS, in order).
389
+ * @param {DeploymentDiscovery} doc
390
+ * @returns {Record<string, string>}
391
+ */
392
+ export function discoveryEnv(doc) {
393
+ /** @type {Record<string, string>} */
394
+ const env = {}
395
+ for (const { name, field } of DISCOVERY_ENV_VARS) if (doc[field] != null) env[name] = doc[field]
396
+ return env
397
+ }
398
+
399
+ /**
400
+ * A discovery document as dotenv `KEY=value` lines (DISCOVERY_ENV_VARS, in order); a value is double-quoted only when it
401
+ * is empty or holds characters outside a plain id or URL.
402
+ * @param {DeploymentDiscovery} doc
403
+ * @returns {string}
404
+ */
405
+ export function discoveryDotenv(doc) {
406
+ return Object.entries(discoveryEnv(doc))
407
+ .map(([name, value]) => `${name}=${/^[\w.:/@%+=,?&~-]+$/.test(value) ? value : `"${value.replace(/[\\"]/g, '\\$&')}"`}`)
408
+ .join('\n')
409
+ }
@@ -0,0 +1,21 @@
1
+ // Kept in lockstep with @revenue-engine/typeid — same API, same byte format.
2
+ export const TYPEID_ALPHABET: string
3
+ export const TYPEID_SUFFIX_LENGTH: 26
4
+ export const MAX_CALLER_ID_LENGTH: 255
5
+
6
+ export type ParsedTypeId = {
7
+ prefix: string
8
+ suffix: string
9
+ }
10
+
11
+ export function uuidV7BytesFromEntropy(timestampMs: number, entropy: Uint8Array): Buffer
12
+ export function encodeTypeIdSuffix(bytes: Uint8Array): string
13
+ export function isValidTypeIdSuffix(value: unknown): boolean
14
+ export function generateTypeId(prefix: string, approvedPrefixes?: Iterable<string> | Set<string>): string
15
+ export function generateTypeIdSuffix(): string
16
+ export function typeIdFromBytes(prefix: string, bytes: Uint8Array, approvedPrefixes?: Iterable<string> | Set<string>): string
17
+ export function parseTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): ParsedTypeId | null
18
+ export function isTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): boolean
19
+ export function assertTypeIdPrefix(id: string, expectedPrefix: string, approvedPrefixes?: Iterable<string> | Set<string>): void
20
+ export function validateCallerId(id: unknown): string
21
+ export function validateRefId(fieldName: string, value: unknown): unknown
@@ -0,0 +1,237 @@
1
+ // The platform's single id generator — a verbatim port of @revenue-engine/typeid (byte-identical ids:
2
+ // monotonic UUIDv7 encoded as a 26-char TypeID base32 suffix, lowercase). CommonJS for the saaslayer
3
+ // service runtime. generateTypeIdSuffix() -> the BARE k-sortable body (custom:suid); generateTypeId(prefix,
4
+ // approvedPrefixes) -> "<prefix>_<body>". Keep this in lockstep with @revenue-engine/typeid.
5
+ const { randomBytes } = require('node:crypto')
6
+
7
+ const TYPEID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'
8
+ const TYPEID_SUFFIX_LENGTH = 26
9
+ const MAX_CALLER_ID_LENGTH = 255
10
+
11
+ const TYPEID_ALPHABET_SET = new Set(TYPEID_ALPHABET)
12
+ const PREFIX_PATTERN = /^[a-z][a-z0-9_]{0,62}$/
13
+
14
+ let lastTs = 0
15
+ let seq = 0
16
+
17
+ function assertPrefix(prefix) {
18
+ if (typeof prefix !== 'string' || !PREFIX_PATTERN.test(prefix)) {
19
+ throw new Error(`Invalid TypeID prefix: "${prefix}"`)
20
+ }
21
+ }
22
+
23
+ function normalizeApprovedPrefixes(prefixes) {
24
+ if (!prefixes) return null
25
+ return prefixes instanceof Set ? prefixes : new Set(prefixes)
26
+ }
27
+
28
+ function assertApprovedPrefix(prefix, approvedPrefixes) {
29
+ const set = normalizeApprovedPrefixes(approvedPrefixes)
30
+ assertPrefix(prefix)
31
+ if (set && !set.has(prefix)) {
32
+ throw new Error(`Unknown TypeID prefix: "${prefix}"`)
33
+ }
34
+ }
35
+
36
+ function uuidV7Bytes() {
37
+ const now = Date.now()
38
+ if (now > lastTs) {
39
+ lastTs = now
40
+ seq = 0
41
+ } else {
42
+ seq += 1
43
+ if (seq > 0xfff) {
44
+ while (Date.now() <= lastTs) { /* spin to the next ms */ }
45
+ lastTs = Date.now()
46
+ seq = 0
47
+ }
48
+ }
49
+
50
+ const buf = Buffer.alloc(16)
51
+ writeTimestamp(buf, lastTs)
52
+ buf[6] = 0x70 | ((seq >> 8) & 0x0f)
53
+ buf[7] = seq & 0xff
54
+
55
+ const rand = randomBytes(8)
56
+ buf[8] = 0x80 | (rand[0] & 0x3f)
57
+ buf[9] = rand[1]
58
+ buf[10] = rand[2]
59
+ buf[11] = rand[3]
60
+ buf[12] = rand[4]
61
+ buf[13] = rand[5]
62
+ buf[14] = rand[6]
63
+ buf[15] = rand[7]
64
+ return buf
65
+ }
66
+
67
+ function writeTimestamp(buf, timestampMs) {
68
+ const hi = Math.floor(timestampMs / 0x100000000)
69
+ const lo = timestampMs - hi * 0x100000000
70
+ buf.writeUInt16BE(hi, 0)
71
+ buf.writeUInt32BE(lo, 2)
72
+ }
73
+
74
+ function uuidV7BytesFromEntropy(timestampMs, entropy) {
75
+ if (!Number.isSafeInteger(timestampMs) || timestampMs < 0 || timestampMs > 0xffffffffffff) {
76
+ throw new Error(`Invalid UUIDv7 timestamp: ${timestampMs}`)
77
+ }
78
+ if (!(entropy instanceof Uint8Array) || entropy.length < 10) {
79
+ throw new Error('UUIDv7 entropy must be at least 10 bytes')
80
+ }
81
+
82
+ const buf = Buffer.alloc(16)
83
+ writeTimestamp(buf, timestampMs)
84
+ buf[6] = 0x70 | (entropy[0] & 0x0f)
85
+ buf[7] = entropy[1]
86
+ buf[8] = 0x80 | (entropy[2] & 0x3f)
87
+ buf[9] = entropy[3]
88
+ buf[10] = entropy[4]
89
+ buf[11] = entropy[5]
90
+ buf[12] = entropy[6]
91
+ buf[13] = entropy[7]
92
+ buf[14] = entropy[8]
93
+ buf[15] = entropy[9]
94
+ return buf
95
+ }
96
+
97
+ function encodeTypeIdSuffix(bytes) {
98
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 16) {
99
+ throw new Error('TypeID suffix encoding requires exactly 16 bytes')
100
+ }
101
+
102
+ let n = 0n
103
+ for (let i = 0; i < 16; i += 1) {
104
+ n = (n << 8n) | BigInt(bytes[i])
105
+ }
106
+
107
+ const chars = new Array(TYPEID_SUFFIX_LENGTH)
108
+ for (let i = TYPEID_SUFFIX_LENGTH - 1; i >= 0; i -= 1) {
109
+ chars[i] = TYPEID_ALPHABET[Number(n & 0x1fn)]
110
+ n >>= 5n
111
+ }
112
+ return chars.join('')
113
+ }
114
+
115
+ function isValidTypeIdSuffix(value) {
116
+ if (typeof value !== 'string' || value.length !== TYPEID_SUFFIX_LENGTH) return false
117
+ if (!'01234567'.includes(value[0].toLowerCase())) return false
118
+ for (let i = 0; i < value.length; i += 1) {
119
+ if (!TYPEID_ALPHABET_SET.has(value[i].toLowerCase())) return false
120
+ }
121
+ return true
122
+ }
123
+
124
+ function generateTypeId(prefix, approvedPrefixes) {
125
+ assertApprovedPrefix(prefix, approvedPrefixes)
126
+ return `${prefix}_${encodeTypeIdSuffix(uuidV7Bytes())}`
127
+ }
128
+
129
+ function generateTypeIdSuffix() {
130
+ return encodeTypeIdSuffix(uuidV7Bytes())
131
+ }
132
+
133
+ function typeIdFromBytes(prefix, bytes, approvedPrefixes) {
134
+ assertApprovedPrefix(prefix, approvedPrefixes)
135
+ return `${prefix}_${encodeTypeIdSuffix(bytes)}`
136
+ }
137
+
138
+ function parseTypeId(id, approvedPrefixes) {
139
+ if (typeof id !== 'string' || id.length === 0) return null
140
+ const idx = id.lastIndexOf('_')
141
+ if (idx < 1) return null
142
+
143
+ const prefix = id.slice(0, idx).toLowerCase()
144
+ const suffix = id.slice(idx + 1).toLowerCase()
145
+ if (!PREFIX_PATTERN.test(prefix)) return null
146
+ const set = normalizeApprovedPrefixes(approvedPrefixes)
147
+ if (set && !set.has(prefix)) return null
148
+ if (!isValidTypeIdSuffix(suffix)) return null
149
+ return { prefix, suffix }
150
+ }
151
+
152
+ function isTypeId(id, approvedPrefixes) {
153
+ return parseTypeId(id, approvedPrefixes) !== null
154
+ }
155
+
156
+ function assertTypeIdPrefix(id, expectedPrefix, approvedPrefixes) {
157
+ const parsed = parseTypeId(id, approvedPrefixes)
158
+ if (!parsed) {
159
+ throw new Error(`Value is not a TypeID: "${id}"`)
160
+ }
161
+ if (parsed.prefix !== expectedPrefix) {
162
+ throw new Error(`Expected TypeID prefix "${expectedPrefix}" but got "${parsed.prefix}"`)
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Shape checks shared by caller-chosen ids and references: string, non-empty after trim, bounded, no control
168
+ * characters, no "#" key delimiter.
169
+ * @param {unknown} id
170
+ * @returns {string} trimmed id
171
+ */
172
+ function validateIdShape(id) {
173
+ if (typeof id !== 'string') {
174
+ throw new TypeError('Caller ID must be a string')
175
+ }
176
+
177
+ const trimmed = id.trim()
178
+ if (!trimmed) {
179
+ throw new Error('Caller ID must not be empty after trimming')
180
+ }
181
+ if (trimmed.length > MAX_CALLER_ID_LENGTH) {
182
+ throw new Error(`Caller ID exceeds max length of ${MAX_CALLER_ID_LENGTH}`)
183
+ }
184
+ if (/[\x00-\x1f\x7f]/.test(trimmed)) {
185
+ throw new Error('Caller ID must not contain ASCII control characters')
186
+ }
187
+ if (trimmed.includes('#')) {
188
+ throw new Error('Caller ID must not contain "#" (DynamoDB key delimiter)')
189
+ }
190
+ return trimmed
191
+ }
192
+
193
+ /**
194
+ * Validate a caller-chosen id for a new entity. Rejects "*" so an id can never act as a wildcard when substituted
195
+ * into a pattern (F18: `like` + `${subject.id}`).
196
+ * @param {unknown} id
197
+ * @returns {string} trimmed id
198
+ */
199
+ function validateCallerId(id) {
200
+ const trimmed = validateIdShape(id)
201
+ if (trimmed.includes('*')) {
202
+ throw new Error('Caller ID must not contain "*" (pattern wildcard)')
203
+ }
204
+ return trimmed
205
+ }
206
+
207
+ /**
208
+ * Validate a reference field (an existing id, or a scope where "*" keeps its catch-all meaning).
209
+ * @param {string} fieldName
210
+ * @param {unknown} value
211
+ */
212
+ function validateRefId(fieldName, value) {
213
+ if (value == null) return value
214
+ try {
215
+ return validateIdShape(value)
216
+ } catch (err) {
217
+ const message = err instanceof Error ? err.message : String(err)
218
+ throw new Error(`${fieldName}: ${message}`)
219
+ }
220
+ }
221
+
222
+ module.exports = {
223
+ TYPEID_ALPHABET,
224
+ TYPEID_SUFFIX_LENGTH,
225
+ MAX_CALLER_ID_LENGTH,
226
+ uuidV7BytesFromEntropy,
227
+ encodeTypeIdSuffix,
228
+ isValidTypeIdSuffix,
229
+ generateTypeId,
230
+ generateTypeIdSuffix,
231
+ typeIdFromBytes,
232
+ parseTypeId,
233
+ isTypeId,
234
+ assertTypeIdPrefix,
235
+ validateCallerId,
236
+ validateRefId,
237
+ }