saaslayer 0.4.1 → 0.4.3

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 (68) hide show
  1. package/bin/saaslayer.js +91 -6
  2. package/package.json +5 -6
  3. package/src/api-client.js +3 -2
  4. package/src/commands/foundation.js +5 -3
  5. package/src/commands/hooks.js +4 -9
  6. package/src/commands/operations.js +1 -1
  7. package/src/commands/release-manifest.js +3 -1
  8. package/src/commands/settings.js +2 -0
  9. package/src/commands/sms.js +35 -4
  10. package/src/commands/sso.js +913 -0
  11. package/src/commands/users-management.js +2 -2
  12. package/src/commands/users.js +7 -3
  13. package/src/commands/verifier-keys.js +105 -0
  14. package/src/login-domain.js +1 -0
  15. package/src/release-manifest.js +30 -7
  16. package/src/secret-sink.js +77 -0
  17. package/src/sms/registration-fields.js +1 -1
  18. package/src/sso-plan.js +21 -0
  19. package/src/user-service-instance.js +30 -1
  20. package/src/users-api.js +3 -2
  21. package/src/users-import/ids.js +1 -1
  22. package/templates/saaslayer-foundation-region.yml +10 -2
  23. package/templates/saaslayer-foundation.yml +33 -5
  24. package/vendor/config/login-domain.js +213 -0
  25. package/vendor/discovery/index.d.mts +109 -0
  26. package/vendor/discovery/index.mjs +409 -0
  27. package/vendor/ids/index.d.ts +21 -0
  28. package/vendor/ids/index.js +237 -0
  29. package/vendor/migrations/backups.js +118 -0
  30. package/vendor/migrations/child.js +78 -0
  31. package/vendor/migrations/credentials.js +103 -0
  32. package/vendor/migrations/errors.js +30 -0
  33. package/vendor/migrations/exec-child.js +78 -0
  34. package/vendor/migrations/gate.js +51 -0
  35. package/vendor/migrations/index.js +30 -0
  36. package/vendor/migrations/inventory.js +92 -0
  37. package/vendor/migrations/log.js +14 -0
  38. package/vendor/migrations/release.js +45 -0
  39. package/vendor/migrations/report.js +129 -0
  40. package/vendor/migrations/rules.js +104 -0
  41. package/vendor/migrations/run.js +311 -0
  42. package/vendor/migrations/session-policy.js +37 -0
  43. package/vendor/migrations/step-guard.js +82 -0
  44. package/vendor/operations/activity.d.ts +21 -0
  45. package/vendor/operations/activity.js +126 -0
  46. package/vendor/operations/index.d.ts +60 -0
  47. package/vendor/operations/index.js +471 -0
  48. package/vendor/permissions-engine-core/account-status.js +270 -0
  49. package/vendor/permissions-engine-core/delegation.js +174 -0
  50. package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
  51. package/vendor/permissions-engine-core/sso-claims.js +206 -0
  52. package/vendor/user-management/cognito/emails/token-registry.js +48 -0
  53. package/vendor/user-management/email/validate.js +207 -0
  54. package/vendor/user-management/extensibility/hook-contract.js +720 -0
  55. package/vendor/user-management/extensibility/safe-webhook.js +85 -0
  56. package/vendor/user-management/identity/admission.js +215 -0
  57. package/vendor/user-management/identity/attr.js +27 -0
  58. package/vendor/user-management/identity/attribute-registry.js +115 -0
  59. package/vendor/user-management/identity/email.js +25 -0
  60. package/vendor/user-management/identity/ensure-suid.js +74 -0
  61. package/vendor/user-management/identity/pointers.js +192 -0
  62. package/vendor/user-management/identity/stitch-provider.js +275 -0
  63. package/vendor/user-management/management/apply-request.js +227 -0
  64. package/vendor/user-management/management/core-profile.js +110 -0
  65. package/vendor/user-management/management/index.js +23 -0
  66. package/vendor/user-management/management/purposes.js +94 -0
  67. package/vendor/user-management/management/registry.js +569 -0
  68. package/vendor/user-management/store/table.js +332 -0
@@ -0,0 +1,126 @@
1
+ // A deployment's activity feed: every change, who made it (customer or operator), the action, the reason and the
2
+ // operation it started. Entries come from deployer runs (a run is an operation) and from recorded non-run actions.
3
+ 'use strict'
4
+ const { operationFromRun, redactText } = require('./index')
5
+
6
+ /** @typedef {'customer'|'operator'} ActorKind */
7
+ /** @typedef {{ kind: ActorKind, id: string }} Actor */
8
+ /**
9
+ * @typedef {object} ActivityEntry
10
+ * @property {string} id the run id, or the recorded action's id
11
+ * @property {string|null} at
12
+ * @property {Actor|null} actor null when the change predates actor recording
13
+ * @property {string} action
14
+ * @property {string|null} subject the service or setting names the change touched (never values)
15
+ * @property {string|null} reason
16
+ * @property {string|null} operationId
17
+ * @property {string} [status] the operation status, for run entries
18
+ */
19
+
20
+ const ACTOR_KINDS = ['customer', 'operator']
21
+
22
+ /** @param {unknown} v @returns {string|null} */
23
+ function str(v) {
24
+ return typeof v === 'string' && v ? v : null
25
+ }
26
+
27
+ /** @param {unknown} v @returns {string[]} */
28
+ function strList(v) {
29
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []
30
+ }
31
+
32
+ /**
33
+ * A recorded actor, or null when it is missing or not a known kind.
34
+ * @param {unknown} value
35
+ * @returns {Actor|null}
36
+ */
37
+ function actorOf(value) {
38
+ const a = /** @type {{ kind?: unknown, id?: unknown }} */ (value && typeof value === 'object' ? value : {})
39
+ return ACTOR_KINDS.includes(String(a.kind)) && str(a.id) ? { kind: /** @type {ActorKind} */ (a.kind), id: /** @type {string} */ (a.id) } : null
40
+ }
41
+
42
+ /** @param {unknown} v @returns {string|null} */
43
+ function reasonOf(v) {
44
+ return str(v) ? redactText(/** @type {string} */ (v)) : null
45
+ }
46
+
47
+ /**
48
+ * The setting names a run writes, as `service.Setting` (requestedSettings holds names only).
49
+ * @param {unknown} requestedSettings
50
+ * @returns {string[]}
51
+ */
52
+ function settingNames(requestedSettings) {
53
+ const bySvc = requestedSettings && typeof requestedSettings === 'object' ? /** @type {Record<string, unknown>} */ (requestedSettings) : {}
54
+ return Object.entries(bySvc).flatMap(([svc, names]) => strList(names).map((n) => `${svc}.${n}`))
55
+ }
56
+
57
+ /**
58
+ * Project one deployer run as an activity entry. The run id is the operation id.
59
+ * @param {Record<string, unknown>} run
60
+ * @returns {ActivityEntry}
61
+ */
62
+ function activityFromRun(run) {
63
+ const op = operationFromRun({ run })
64
+ const settings = settingNames(run.requestedSettings)
65
+ const isSettingsWrite = op.kind === 'deployment.update' && settings.length > 0
66
+ const isServiceChange = op.kind === 'service.add' || op.kind === 'service.remove'
67
+ const service = str(run.service) || strList(run.requestedServices)[0] || null
68
+ return {
69
+ id: op.id,
70
+ at: str(run.createdAt),
71
+ actor: actorOf(run.actor),
72
+ action: isSettingsWrite ? 'settings.update' : op.kind,
73
+ subject: isSettingsWrite ? settings.join(', ') : isServiceChange ? service : null,
74
+ reason: reasonOf(run.reason),
75
+ operationId: op.id,
76
+ status: op.status,
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Project a recorded non-run action (force unlock, cancel, transfer, ...) as an activity entry.
82
+ * @param {Record<string, unknown>} record
83
+ * @returns {ActivityEntry}
84
+ */
85
+ function activityFromRecord(record) {
86
+ return {
87
+ id: String(record.activityId),
88
+ at: str(record.at),
89
+ actor: actorOf(record.actor),
90
+ action: String(record.action),
91
+ subject: str(record.subject),
92
+ reason: reasonOf(record.reason),
93
+ operationId: str(record.operationId),
94
+ }
95
+ }
96
+
97
+ /**
98
+ * A deployment's activity, newest first.
99
+ * @param {{ runs?: Array<Record<string, unknown>>, records?: Array<Record<string, unknown>>, limit?: number }} input
100
+ * @returns {ActivityEntry[]}
101
+ */
102
+ function activityFeed({ runs = [], records = [], limit }) {
103
+ const entries = [...runs.map(activityFromRun), ...records.map(activityFromRecord)]
104
+ entries.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')))
105
+ return typeof limit === 'number' && limit >= 0 ? entries.slice(0, limit) : entries
106
+ }
107
+
108
+ /**
109
+ * One line per entry: time, actor, action, subject, status, operation and reason.
110
+ * @param {ActivityEntry[]} entries
111
+ * @returns {string[]}
112
+ */
113
+ function formatActivity(entries) {
114
+ if (entries.length === 0) return ['no activity']
115
+ return entries.map((e) => [
116
+ e.at || '-',
117
+ e.actor ? `${e.actor.kind}:${e.actor.id}` : 'unattributed',
118
+ e.action,
119
+ e.subject,
120
+ e.status,
121
+ e.operationId ? `op ${e.operationId}` : null,
122
+ e.reason ? JSON.stringify(e.reason) : null,
123
+ ].filter(Boolean).join(' '))
124
+ }
125
+
126
+ module.exports = { ACTOR_KINDS, actorOf, activityFromRun, activityFromRecord, activityFeed, formatActivity }
@@ -0,0 +1,60 @@
1
+ // Types for @saaslayer/operations — the operation resource shared by control plane, services, CLI and console.
2
+ // Mirrors src/index.js (CommonJS, JSDoc-typed).
3
+ export type OperationStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'partial'
4
+ export type ComponentStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'skipped' | 'unknown'
5
+ export interface OperationError { code?: string | null; message?: string | null }
6
+ export interface OperationComponent {
7
+ name: string
8
+ status: ComponentStatus
9
+ delivery?: 'external'
10
+ error?: OperationError
11
+ nextAction?: string
12
+ detail?: Record<string, unknown>
13
+ }
14
+ export interface Operation {
15
+ id: string
16
+ kind: string
17
+ status: OperationStatus
18
+ components: OperationComponent[]
19
+ createdAt: string | null
20
+ updatedAt: string | null
21
+ requestKey: string | null
22
+ deploymentId?: string
23
+ error?: OperationError
24
+ nextAction?: string
25
+ /** A delete destroy's or purge's report (ADR 0006 §5): complete, pending or incomplete, with what it removed and what remains. */
26
+ purgeResult?: Record<string, unknown>
27
+ }
28
+ export type IdempotencyDecision =
29
+ | { action: 'new' }
30
+ | { action: 'replay'; operationId: string | null }
31
+ | { action: 'conflict'; statusCode: 409; code: 'IDEMPOTENCY_KEY_REUSED'; error: string }
32
+
33
+ export const OPERATION_STATUSES: OperationStatus[]
34
+ export const COMPONENT_STATUSES: ComponentStatus[]
35
+ export const TERMINAL_STATUSES: OperationStatus[]
36
+ export const IDEMPOTENCY_RETENTION_SECONDS: number
37
+ export function isTerminal(status: string): boolean
38
+ export function createOperation(input: { id: string; kind: string; requestKey?: string | null; components?: Array<string | { name: string; delivery?: 'external' }>; now: string }): Operation
39
+ export function transition(op: Operation, next: string, now: string): Operation
40
+ export function rollupStatus(components: OperationComponent[]): OperationStatus
41
+ export function updateComponent(op: Operation, name: string, patch: { status: string; error?: OperationError; nextAction?: string }, now: string): Operation
42
+ export function fingerprint(payload: unknown): string
43
+ export function idempotencyScopeKey(input: { scope: string; kind: string; requestKey: string }): string
44
+ export function idempotencyExpiry(nowMs: number): number
45
+ export function resolveIdempotency(input: { record: Record<string, unknown> | null | undefined; fingerprint: string; nowMs: number }): IdempotencyDecision
46
+ export function operationFromRun(input: { deploymentId?: string; run: Record<string, unknown>; moduleResults?: Array<Record<string, unknown>> }): Operation
47
+ export function syncWriteResult<T>(input: { result: T; requestId: string; revision: number | string }): { result: T; requestId: string; revision: number | string }
48
+ export function redact<T>(value: T): T
49
+ export function redactText(text: string): string
50
+ export function operationLogLine(op: Operation, componentName?: string): string
51
+ export function formatOperation(op: Operation): string[]
52
+ export function watchOperation(input: {
53
+ id: string
54
+ fetchOperation: () => Promise<Operation>
55
+ sleep?: (ms: number) => Promise<void>
56
+ intervalMs?: number
57
+ maxConsecutiveErrors?: number
58
+ onUpdate?: (op: Operation) => void
59
+ resumeCommand?: string
60
+ }): Promise<Operation>
@@ -0,0 +1,471 @@
1
+ // The operation resource shared by the control plane, deployed services, CLI and console: durable id, kind,
2
+ // status (pending|running|succeeded|failed|partial), per-component outcomes, idempotency, redaction and watch.
3
+ 'use strict'
4
+
5
+ /** @typedef {'pending'|'running'|'succeeded'|'failed'|'partial'} OperationStatus */
6
+ /** @typedef {'pending'|'running'|'succeeded'|'failed'|'skipped'|'unknown'} ComponentStatus */
7
+ /** @typedef {{ code?: string|null, message?: string|null }} OperationError */
8
+ /**
9
+ * @typedef {object} OperationComponent
10
+ * @property {string} name
11
+ * @property {ComponentStatus} status
12
+ * @property {'external'} [delivery] an external delivery (email, webhook) whose outcome may stay unknown
13
+ * @property {OperationError} [error]
14
+ * @property {string} [nextAction] the next supported command for this component
15
+ * @property {Record<string, unknown>} [detail] the component's own reported state (redacted), e.g. a bootstrap's step
16
+ */
17
+ /**
18
+ * @typedef {object} Operation
19
+ * @property {string} id
20
+ * @property {string} kind
21
+ * @property {OperationStatus} status
22
+ * @property {OperationComponent[]} components
23
+ * @property {string|null} createdAt
24
+ * @property {string|null} updatedAt
25
+ * @property {string|null} requestKey
26
+ * @property {string} [deploymentId]
27
+ * @property {OperationError} [error]
28
+ * @property {string} [nextAction]
29
+ * @property {Record<string, unknown>} [purgeResult] a delete destroy's or purge's report: complete, pending or incomplete
30
+ */
31
+
32
+ const OPERATION_STATUSES = ['pending', 'running', 'succeeded', 'failed', 'partial']
33
+ const COMPONENT_STATUSES = ['pending', 'running', 'succeeded', 'failed', 'skipped', 'unknown']
34
+ const EXTERNAL_DELIVERY_STATUSES = ['pending', 'running', 'succeeded', 'failed', 'unknown']
35
+ const TERMINAL_STATUSES = ['succeeded', 'failed', 'partial']
36
+
37
+ // How long a request key (and the operation it names) is replayable: 7 days. After that the key may be reused.
38
+ const IDEMPOTENCY_RETENTION_SECONDS = 7 * 24 * 60 * 60
39
+
40
+ /** @type {Record<string, OperationStatus[]>} */
41
+ const ALLOWED_TRANSITIONS = {
42
+ pending: ['running', 'succeeded', 'failed', 'partial'],
43
+ running: ['succeeded', 'failed', 'partial'],
44
+ succeeded: [],
45
+ failed: [],
46
+ partial: [],
47
+ }
48
+
49
+ /** @param {string} status */
50
+ function isTerminal(status) {
51
+ return TERMINAL_STATUSES.includes(status)
52
+ }
53
+
54
+ /**
55
+ * @param {{ id: string, kind: string, requestKey?: string|null, components?: Array<string|{ name: string, delivery?: 'external' }>, now: string }} input
56
+ * @returns {Operation}
57
+ */
58
+ function createOperation({ id, kind, requestKey = null, components = [], now }) {
59
+ if (!id || !kind) throw new Error('createOperation: id and kind are required')
60
+ return {
61
+ id,
62
+ kind,
63
+ status: 'pending',
64
+ components: components.map((c) => {
65
+ const spec = typeof c === 'string' ? { name: c } : c
66
+ return { name: spec.name, status: 'pending', ...(spec.delivery === 'external' ? { delivery: 'external' } : {}) }
67
+ }),
68
+ createdAt: now,
69
+ updatedAt: now,
70
+ requestKey,
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Move an operation to a new status. Same-state is a no-op; leaving a terminal state throws.
76
+ * @param {Operation} op
77
+ * @param {string} next
78
+ * @param {string} now
79
+ * @returns {Operation}
80
+ */
81
+ function transition(op, next, now) {
82
+ if (!OPERATION_STATUSES.includes(next)) throw new Error(`unknown operation status "${next}"`)
83
+ if (op.status === next) return op
84
+ if (!ALLOWED_TRANSITIONS[op.status].includes(/** @type {OperationStatus} */ (next))) {
85
+ throw new Error(`illegal operation transition ${op.status} -> ${next}`)
86
+ }
87
+ return { ...op, status: /** @type {OperationStatus} */ (next), updatedAt: now }
88
+ }
89
+
90
+ /**
91
+ * The operation status implied by its components: all pending = pending; any pending/running = running; else
92
+ * no failure = succeeded (an external delivery's unknown is not a failure), failures plus successes = partial,
93
+ * only failures = failed.
94
+ * @param {OperationComponent[]} components
95
+ * @returns {OperationStatus}
96
+ */
97
+ function rollupStatus(components) {
98
+ if (components.length === 0) return 'pending'
99
+ if (components.every((c) => c.status === 'pending')) return 'pending'
100
+ if (components.some((c) => c.status === 'pending' || c.status === 'running')) return 'running'
101
+ const failed = components.filter((c) => c.status === 'failed').length
102
+ if (failed === 0) return 'succeeded'
103
+ return components.some((c) => c.status === 'succeeded' || c.status === 'unknown') ? 'partial' : 'failed'
104
+ }
105
+
106
+ /**
107
+ * Record one component's outcome and roll the operation status up from its components.
108
+ * @param {Operation} op
109
+ * @param {string} name
110
+ * @param {{ status: string, error?: OperationError, nextAction?: string }} patch
111
+ * @param {string} now
112
+ * @returns {Operation}
113
+ */
114
+ function updateComponent(op, name, patch, now) {
115
+ const index = op.components.findIndex((c) => c.name === name)
116
+ if (index < 0) throw new Error(`no component "${name}" on operation ${op.id}`)
117
+ if (!COMPONENT_STATUSES.includes(patch.status)) throw new Error(`unknown component status "${patch.status}"`)
118
+ const current = op.components[index]
119
+ if (current.delivery === 'external' && !EXTERNAL_DELIVERY_STATUSES.includes(patch.status)) {
120
+ throw new Error(`external delivery component "${name}" reports succeeded|failed|unknown`)
121
+ }
122
+ const component = {
123
+ ...current,
124
+ status: /** @type {ComponentStatus} */ (patch.status),
125
+ ...(patch.error ? { error: redact(patch.error) } : {}),
126
+ ...(patch.nextAction ? { nextAction: patch.nextAction } : {}),
127
+ }
128
+ const components = op.components.map((c, i) => (i === index ? component : c))
129
+ return transition({ ...op, components, updatedAt: now }, rollupStatus(components), now)
130
+ }
131
+
132
+ // ---- Idempotency -------------------------------------------------------------------------------------
133
+
134
+ /** @param {unknown} value @returns {unknown} */
135
+ function canonical(value) {
136
+ if (Array.isArray(value)) return value.map(canonical)
137
+ if (value && typeof value === 'object') {
138
+ return Object.keys(value).sort().reduce((acc, key) => {
139
+ acc[key] = canonical(/** @type {Record<string, unknown>} */ (value)[key])
140
+ return acc
141
+ }, /** @type {Record<string, unknown>} */ ({}))
142
+ }
143
+ return value
144
+ }
145
+
146
+ /**
147
+ * The payload fingerprint a request key is bound to (sha256 of the key-sorted JSON).
148
+ * @param {unknown} payload
149
+ */
150
+ function fingerprint(payload) {
151
+ // Required here, not at module load: browser bundles import this module for redaction and rendering only.
152
+ const { createHash } = require('node:crypto')
153
+ return createHash('sha256').update(JSON.stringify(canonical(payload === undefined ? null : payload))).digest('hex')
154
+ }
155
+
156
+ /**
157
+ * A request key scoped by its scope (a deployment id) and operation kind, so one key can't collide across them.
158
+ * @param {{ scope: string, kind: string, requestKey: string }} input
159
+ */
160
+ function idempotencyScopeKey({ scope, kind, requestKey }) {
161
+ if (!scope || !kind || !requestKey) throw new Error('idempotencyScopeKey: scope, kind and requestKey are required')
162
+ return `${scope}#${kind}#${requestKey}`
163
+ }
164
+
165
+ /**
166
+ * The DynamoDB ttl (epoch seconds) for a request key recorded at nowMs.
167
+ * @param {number} nowMs
168
+ */
169
+ function idempotencyExpiry(nowMs) {
170
+ return Math.floor(nowMs / 1000) + IDEMPOTENCY_RETENTION_SECONDS
171
+ }
172
+
173
+ /**
174
+ * Decide what a request with this key + payload does against the stored key record: 'new' (no live record),
175
+ * 'replay' (same payload — return the same operation) or 'conflict' (different payload — 409). A record past
176
+ * its ttl (or, without one, past createdAt + retention) is expired and treated as absent.
177
+ * @param {{ record: { requestHash?: unknown, runId?: unknown, operationId?: unknown, ttl?: unknown, createdAt?: unknown } | null | undefined, fingerprint: string, nowMs: number }} input
178
+ * @returns {{ action: 'new' } | { action: 'replay', operationId: string|null } | { action: 'conflict', statusCode: 409, code: 'IDEMPOTENCY_KEY_REUSED', error: string }}
179
+ */
180
+ function resolveIdempotency({ record, fingerprint: requestFingerprint, nowMs }) {
181
+ if (!record) return { action: 'new' }
182
+ const expiresAtSeconds = typeof record.ttl === 'number'
183
+ ? record.ttl
184
+ : typeof record.createdAt === 'string' ? Math.floor(Date.parse(record.createdAt) / 1000) + IDEMPOTENCY_RETENTION_SECONDS : null
185
+ if (expiresAtSeconds !== null && expiresAtSeconds * 1000 < nowMs) return { action: 'new' }
186
+ if (record.requestHash !== requestFingerprint) {
187
+ return { action: 'conflict', statusCode: 409, code: 'IDEMPOTENCY_KEY_REUSED', error: 'Idempotency-Key was already used with a different request body' }
188
+ }
189
+ const operationId = record.operationId || record.runId
190
+ return { action: 'replay', operationId: typeof operationId === 'string' ? operationId : null }
191
+ }
192
+
193
+ // ---- Deployer runs as operations ---------------------------------------------------------------------
194
+
195
+ /** @type {Record<string, string>} */
196
+ const KIND_BY_RUN_TYPE = {
197
+ CREATE: 'deployment.create',
198
+ UPDATE: 'deployment.update',
199
+ DESTROY: 'deployment.destroy',
200
+ PURGE: 'deployment.purge',
201
+ MIGRATE: 'deployment.migrate',
202
+ ADD_SERVICE: 'service.add',
203
+ REMOVE_SERVICE: 'service.remove',
204
+ }
205
+
206
+ /** @param {unknown} customDomain the custom domain a run carries @returns {string|null} its operation kind */
207
+ function customDomainKind(customDomain) {
208
+ const action = customDomain && typeof customDomain === 'object' ? /** @type {{ action?: unknown }} */ (customDomain).action : null
209
+ return action === 'attach' || action === 'remove' ? `service.custom-domain.${action}` : null
210
+ }
211
+
212
+ // The login-domain actions a dedicated UPDATE run carries (run.loginDomain.action): kind service.login-domain.<action>.
213
+ const LOGIN_DOMAIN_ACTIONS = ['provision', 'activate', 'deactivate', 'remove']
214
+
215
+ /**
216
+ * The login-domain action a run was started for, or null.
217
+ * @param {Record<string, unknown>} run
218
+ * @returns {string|null}
219
+ */
220
+ function loginDomainAction(run) {
221
+ const action = run.loginDomain && typeof run.loginDomain === 'object' ? /** @type {{ action?: unknown }} */ (run.loginDomain).action : null
222
+ return typeof action === 'string' && LOGIN_DOMAIN_ACTIONS.includes(action) ? action : null
223
+ }
224
+
225
+ /** @param {string|null|undefined} runStatus @returns {OperationStatus} */
226
+ function statusFromRun(runStatus) {
227
+ if (runStatus === 'QUEUED') return 'pending'
228
+ if (runStatus === 'RUNNING' || runStatus === 'CANCEL_REQUESTED') return 'running'
229
+ if (runStatus === 'SUCCEEDED') return 'succeeded'
230
+ return 'failed'
231
+ }
232
+
233
+ /**
234
+ * The CLI command that retries (or, for a blocked/non-retryable failure, inspects) a failed run.
235
+ * @param {{ kind: string, deploymentId?: string, run: Record<string, unknown>, service?: string, retryable?: unknown, blocked?: unknown }} input
236
+ */
237
+ function nextActionFor({ kind, deploymentId, run, service, retryable, blocked }) {
238
+ if (blocked === true || retryable === false) return 'saaslayer status'
239
+ switch (kind) {
240
+ case 'deployment.create': return 'saaslayer deploy'
241
+ case 'deployment.update': return run.targetCommitSha ? `saaslayer update --commit-sha ${run.targetCommitSha}` : 'saaslayer update'
242
+ case 'deployment.destroy': return 'saaslayer destroy --data-custody delete|retain'
243
+ case 'deployment.purge': return 'saaslayer destroy --purge-retained --reason TEXT'
244
+ case 'deployment.migrate': return `saaslayer migrate status --deployment ${deploymentId}`
245
+ case 'service.add': return `saaslayer service add ${service}`
246
+ case 'service.remove': return `saaslayer service remove ${service} --data-custody delete|retain`
247
+ default:
248
+ // A login-domain run's state (and the next step) is read back with status, whichever action failed.
249
+ if (kind.startsWith('service.login-domain.')) return `saaslayer login-domain status --service ${service}`
250
+ return 'saaslayer status'
251
+ }
252
+ }
253
+
254
+ /** @param {Record<string, unknown>} result @returns {ComponentStatus|null} */
255
+ function componentStatusFromResult(result) {
256
+ // A component a step reports itself (a seed's first-admin bootstrap) carries its own status.
257
+ if (typeof result.componentStatus === 'string' && COMPONENT_STATUSES.includes(result.componentStatus)) return /** @type {ComponentStatus} */ (result.componentStatus)
258
+ const outcomes = [result.deployStatus, result.removeStatus]
259
+ if (outcomes.includes('FAILED')) return 'failed'
260
+ if (outcomes.includes('SUCCEEDED')) return 'succeeded'
261
+ if (outcomes.includes('SKIPPED')) return 'skipped'
262
+ return null
263
+ }
264
+
265
+ /** @param {unknown} code @param {unknown} message @returns {OperationError|undefined} */
266
+ function errorOf(code, message) {
267
+ if (!code && !message) return undefined
268
+ return { code: typeof code === 'string' ? code : null, message: typeof message === 'string' ? redactText(message) : null }
269
+ }
270
+
271
+ /** @param {unknown} v @returns {string[]} */
272
+ function strList(v) {
273
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []
274
+ }
275
+
276
+ /**
277
+ * Project a deployer run (and its per-module results) as an operation. The run id IS the operation id.
278
+ * @param {{ deploymentId?: string, run: Record<string, unknown>, moduleResults?: Array<Record<string, unknown>> }} input
279
+ * @returns {Operation}
280
+ */
281
+ function operationFromRun({ deploymentId, run, moduleResults = [] }) {
282
+ // A run started for an explicit first-admin request (deployer action admin-bootstrap) is that operation; so is a run
283
+ // started to attach or remove a custom domain.
284
+ const kind = run.adminBootstrap ? 'deployment.admin-bootstrap'
285
+ : loginDomainAction(run) ? `service.login-domain.${loginDomainAction(run)}`
286
+ : customDomainKind(run.customDomain) || KIND_BY_RUN_TYPE[String(run.type)] || `deployment.${String(run.type || 'run').toLowerCase()}`
287
+ const runStatus = statusFromRun(/** @type {string|undefined} */ (run.status))
288
+ const requested = strList(run.requestedServices).length ? strList(run.requestedServices) : strList(run.requestedModules)
289
+ const loginDomainService = loginDomainAction(run) ? String(/** @type {{ service?: unknown }} */ (run.loginDomain).service || '') : ''
290
+ const resultByName = new Map(moduleResults.filter((r) => typeof r.moduleName === 'string').map((r) => [String(r.moduleName), r]))
291
+ const names = [...requested, ...[...resultByName.keys()].filter((n) => !requested.includes(n))]
292
+ /** @type {OperationComponent[]} */
293
+ const components = names.map((name) => {
294
+ const result = resultByName.get(name)
295
+ const reported = result ? componentStatusFromResult(result) : null
296
+ /** @type {ComponentStatus} */
297
+ const status = reported || (runStatus === 'succeeded' ? 'succeeded' : runStatus === 'failed' ? 'unknown' : 'pending')
298
+ /** @type {OperationComponent} */
299
+ const component = { name: result && typeof result.component === 'string' ? result.component : name, status }
300
+ const error = result ? errorOf(result.errorCode, result.errorMessage) : undefined
301
+ if (error) component.error = error
302
+ if (result && result.detail && typeof result.detail === 'object' && !Array.isArray(result.detail)) {
303
+ component.detail = /** @type {Record<string, unknown>} */ (redact(result.detail))
304
+ }
305
+ if (status === 'failed') {
306
+ component.nextAction = nextActionFor({ kind, deploymentId, run, service: name, retryable: result && result.retryable !== undefined ? result.retryable : run.retryable, blocked: run.blocked })
307
+ }
308
+ return component
309
+ })
310
+ const anySucceeded = components.some((c) => c.status === 'succeeded')
311
+ const anyFailed = components.some((c) => c.status === 'failed')
312
+ /** @type {OperationStatus} */
313
+ const status = (runStatus === 'failed' && anySucceeded) || (runStatus === 'succeeded' && anyFailed) ? 'partial' : runStatus
314
+ /** @type {Operation} */
315
+ const op = {
316
+ id: String(run.runId),
317
+ kind,
318
+ status,
319
+ components,
320
+ createdAt: typeof run.createdAt === 'string' ? run.createdAt : null,
321
+ updatedAt: typeof run.updatedAt === 'string' ? run.updatedAt : null,
322
+ requestKey: typeof run.idempotencyKey === 'string' ? run.idempotencyKey : typeof run.requestKey === 'string' ? run.requestKey : null,
323
+ }
324
+ if (deploymentId) op.deploymentId = deploymentId
325
+ // A delete destroy or a purge reports what it removed and what remains (ADR 0006 §5 purgeResult).
326
+ if (run.purgeResult && typeof run.purgeResult === 'object') op.purgeResult = /** @type {Record<string, unknown>} */ (run.purgeResult)
327
+ const error = errorOf(run.errorCode, run.errorMessage)
328
+ if (error) op.error = error
329
+ if (status === 'failed' || status === 'partial') {
330
+ op.nextAction = nextActionFor({ kind, deploymentId, run, service: loginDomainService || requested[0] || names[0], retryable: run.retryable, blocked: run.blocked })
331
+ }
332
+ return op
333
+ }
334
+
335
+ /**
336
+ * A simple synchronous write's response: the result, the request id and the resource's revision (no operation).
337
+ * @param {{ result: unknown, requestId: string, revision: number|string }} input
338
+ */
339
+ function syncWriteResult({ result, requestId, revision }) {
340
+ if (!requestId) throw new Error('syncWriteResult: requestId is required')
341
+ return { result: redact(result), requestId, revision }
342
+ }
343
+
344
+ // ---- Redaction ---------------------------------------------------------------------------------------
345
+
346
+ const REDACTED = '[REDACTED]'
347
+ const SECRET_KEY_RE = /pass(word|code)?$|secret|token|authorization|api[-_]?key|invitation|credential/i
348
+ const SECRET_NAMES = 'password|passcode|secret|clientSecret|token|idToken|accessToken|refreshToken|invitationToken|apiKey|api_key'
349
+
350
+ /**
351
+ * Remove bearer tokens, JWTs and `name=value` / `"name":"value"` secrets from free text.
352
+ * @param {string} text
353
+ */
354
+ function redactText(text) {
355
+ return String(text)
356
+ .replace(/Bearer\s+[^\s"',]+/gi, `Bearer ${REDACTED}`)
357
+ .replace(/eyJ[\w-]+\.[\w-]+\.[\w-]+/g, REDACTED)
358
+ .replace(new RegExp(`"(${SECRET_NAMES})"\\s*:\\s*"[^"]*"`, 'gi'), `"$1":"${REDACTED}"`)
359
+ .replace(new RegExp(`\\b(${SECRET_NAMES})=([^\\s&"',]+)`, 'gi'), `$1=${REDACTED}`)
360
+ }
361
+
362
+ /**
363
+ * Deep-copy a value with secret-named fields replaced and free-text secrets removed from strings.
364
+ * @template T
365
+ * @param {T} value
366
+ * @returns {T}
367
+ */
368
+ function redact(value) {
369
+ if (typeof value === 'string') return /** @type {T} */ (/** @type {unknown} */ (redactText(value)))
370
+ if (Array.isArray(value)) return /** @type {T} */ (/** @type {unknown} */ (value.map(redact)))
371
+ if (value && typeof value === 'object') {
372
+ /** @type {Record<string, unknown>} */
373
+ const out = {}
374
+ for (const [key, v] of Object.entries(value)) out[key] = SECRET_KEY_RE.test(key) && v != null ? REDACTED : redact(v)
375
+ return /** @type {T} */ (/** @type {unknown} */ (out))
376
+ }
377
+ return value
378
+ }
379
+
380
+ // ---- Logs + rendering --------------------------------------------------------------------------------
381
+
382
+ /**
383
+ * The structured log line for an operation (optionally focused on one component): operation {id, kind, status, component}.
384
+ * @param {Operation} op
385
+ * @param {string} [componentName]
386
+ */
387
+ function operationLogLine(op, componentName) {
388
+ /** @type {Record<string, unknown>} */
389
+ const line = { event: 'operation', id: op.id, kind: op.kind, status: op.status }
390
+ if (componentName) {
391
+ const c = op.components.find((x) => x.name === componentName)
392
+ if (c) line.component = { name: c.name, status: c.status, ...(c.error && c.error.code ? { errorCode: c.error.code } : {}) }
393
+ }
394
+ return redactText(JSON.stringify(line))
395
+ }
396
+
397
+ /**
398
+ * Human-readable lines for an operation — the one rendering the CLI and console share.
399
+ * @param {Operation} op
400
+ * @returns {string[]}
401
+ */
402
+ function formatOperation(op) {
403
+ const lines = [`operation ${op.id} (${op.kind}): ${op.status}`]
404
+ const width = Math.max(0, ...op.components.map((c) => c.name.length))
405
+ for (const c of op.components) {
406
+ const err = c.error ? ` ${[c.error.code, c.error.message].filter(Boolean).join(': ')}` : ''
407
+ lines.push(` ${c.name.padEnd(width)} ${c.status}${err}`)
408
+ }
409
+ if (op.error && !op.components.some((c) => c.error)) lines.push(` error: ${[op.error.code, op.error.message].filter(Boolean).join(': ')}`)
410
+ const next = [...new Set([op.nextAction, ...op.components.map((c) => c.nextAction)].filter(Boolean))]
411
+ for (const n of next) lines.push(` next: ${n}`)
412
+ return lines
413
+ }
414
+
415
+ /**
416
+ * Poll an operation until it is terminal. Transient fetch errors (a dropped connection) are retried; after
417
+ * maxConsecutiveErrors in a row it gives up with an OPERATION_CONNECTION_LOST error naming the resume command. An
418
+ * error marked `fatal` (a 4xx such as a missing operation) is rethrown at once.
419
+ * @param {{ id: string, fetchOperation: () => Promise<Operation>, sleep?: (ms: number) => Promise<void>, intervalMs?: number, maxConsecutiveErrors?: number, onUpdate?: (op: Operation) => void, resumeCommand?: string }} input
420
+ * @returns {Promise<Operation>}
421
+ */
422
+ async function watchOperation({ id, fetchOperation, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), intervalMs = 5000, maxConsecutiveErrors = 5, onUpdate, resumeCommand }) {
423
+ let errors = 0
424
+ let lastSignature = ''
425
+ for (;;) {
426
+ try {
427
+ const op = await fetchOperation()
428
+ errors = 0
429
+ const signature = JSON.stringify([op.status, op.components])
430
+ if (signature !== lastSignature) {
431
+ lastSignature = signature
432
+ if (onUpdate) onUpdate(op)
433
+ }
434
+ if (isTerminal(op.status)) return op
435
+ } catch (err) {
436
+ if (err && /** @type {{ fatal?: boolean }} */ (err).fatal) throw err
437
+ errors++
438
+ if (errors >= maxConsecutiveErrors) {
439
+ const reason = err && /** @type {Error} */ (err).message ? /** @type {Error} */ (err).message : String(err)
440
+ const lost = /** @type {Error & { code?: string, operationId?: string }} */ (new Error(`lost connection while watching operation ${id} (${redactText(reason)})${resumeCommand ? ` — resume with: ${resumeCommand}` : ''}`))
441
+ lost.code = 'OPERATION_CONNECTION_LOST'
442
+ lost.operationId = id
443
+ throw lost
444
+ }
445
+ }
446
+ await sleep(intervalMs)
447
+ }
448
+ }
449
+
450
+ module.exports = {
451
+ OPERATION_STATUSES,
452
+ COMPONENT_STATUSES,
453
+ TERMINAL_STATUSES,
454
+ IDEMPOTENCY_RETENTION_SECONDS,
455
+ isTerminal,
456
+ createOperation,
457
+ transition,
458
+ rollupStatus,
459
+ updateComponent,
460
+ fingerprint,
461
+ idempotencyScopeKey,
462
+ idempotencyExpiry,
463
+ resolveIdempotency,
464
+ operationFromRun,
465
+ syncWriteResult,
466
+ redact,
467
+ redactText,
468
+ operationLogLine,
469
+ formatOperation,
470
+ watchOperation,
471
+ }