velocious 1.0.571 → 1.0.573

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 (80) hide show
  1. package/README.md +2 -0
  2. package/build/background-jobs/web/authorization.js +2 -33
  3. package/build/background-jobs/web/path-matcher.js +5 -30
  4. package/build/database/drivers/base.js +17 -0
  5. package/build/database/drivers/mssql/index.js +30 -0
  6. package/build/database/record/index.js +22 -10
  7. package/build/deployment-api/controller.js +437 -0
  8. package/build/deployment-api/index.js +210 -0
  9. package/build/deployment-api/path-matcher.js +45 -0
  10. package/build/deployment-api/registry.js +84 -0
  11. package/build/deployment-api/run-store.js +798 -0
  12. package/build/deployment-api/sanitize.js +114 -0
  13. package/build/http-client/request.js +3 -1
  14. package/build/src/background-jobs/web/authorization.d.ts.map +1 -1
  15. package/build/src/background-jobs/web/authorization.js +3 -29
  16. package/build/src/background-jobs/web/path-matcher.d.ts +2 -12
  17. package/build/src/background-jobs/web/path-matcher.d.ts.map +1 -1
  18. package/build/src/background-jobs/web/path-matcher.js +5 -30
  19. package/build/src/database/drivers/base.d.ts +16 -0
  20. package/build/src/database/drivers/base.d.ts.map +1 -1
  21. package/build/src/database/drivers/base.js +16 -1
  22. package/build/src/database/drivers/mssql/index.d.ts.map +1 -1
  23. package/build/src/database/drivers/mssql/index.js +29 -1
  24. package/build/src/database/record/index.d.ts +3 -2
  25. package/build/src/database/record/index.d.ts.map +1 -1
  26. package/build/src/database/record/index.js +21 -10
  27. package/build/src/deployment-api/controller.d.ts +117 -0
  28. package/build/src/deployment-api/controller.d.ts.map +1 -0
  29. package/build/src/deployment-api/controller.js +384 -0
  30. package/build/src/deployment-api/index.d.ts +46 -0
  31. package/build/src/deployment-api/index.d.ts.map +1 -0
  32. package/build/src/deployment-api/index.js +178 -0
  33. package/build/src/deployment-api/path-matcher.d.ts +31 -0
  34. package/build/src/deployment-api/path-matcher.d.ts.map +1 -0
  35. package/build/src/deployment-api/path-matcher.js +39 -0
  36. package/build/src/deployment-api/registry.d.ts +106 -0
  37. package/build/src/deployment-api/registry.d.ts.map +1 -0
  38. package/build/src/deployment-api/registry.js +74 -0
  39. package/build/src/deployment-api/run-store.d.ts +402 -0
  40. package/build/src/deployment-api/run-store.d.ts.map +1 -0
  41. package/build/src/deployment-api/run-store.js +711 -0
  42. package/build/src/deployment-api/sanitize.d.ts +27 -0
  43. package/build/src/deployment-api/sanitize.d.ts.map +1 -0
  44. package/build/src/deployment-api/sanitize.js +100 -0
  45. package/build/src/http-client/request.d.ts.map +1 -1
  46. package/build/src/http-client/request.js +4 -2
  47. package/build/src/sync/signed-sync-envelope-replay-service.d.ts +154 -0
  48. package/build/src/sync/signed-sync-envelope-replay-service.d.ts.map +1 -0
  49. package/build/src/sync/signed-sync-envelope-replay-service.js +294 -0
  50. package/build/src/sync/sync-envelope-replay-service.d.ts +84 -15
  51. package/build/src/sync/sync-envelope-replay-service.d.ts.map +1 -1
  52. package/build/src/sync/sync-envelope-replay-service.js +98 -16
  53. package/build/src/utils/bearer-token.d.ts +15 -0
  54. package/build/src/utils/bearer-token.d.ts.map +1 -0
  55. package/build/src/utils/bearer-token.js +29 -0
  56. package/build/src/utils/mount-prefix.d.ts +21 -0
  57. package/build/src/utils/mount-prefix.d.ts.map +1 -0
  58. package/build/src/utils/mount-prefix.js +35 -0
  59. package/build/sync/signed-sync-envelope-replay-service.js +342 -0
  60. package/build/sync/sync-envelope-replay-service.js +110 -15
  61. package/build/tsconfig.tsbuildinfo +1 -1
  62. package/build/utils/bearer-token.js +34 -0
  63. package/build/utils/mount-prefix.js +36 -0
  64. package/package.json +2 -1
  65. package/src/background-jobs/web/authorization.js +2 -33
  66. package/src/background-jobs/web/path-matcher.js +5 -30
  67. package/src/database/drivers/base.js +17 -0
  68. package/src/database/drivers/mssql/index.js +30 -0
  69. package/src/database/record/index.js +22 -10
  70. package/src/deployment-api/controller.js +437 -0
  71. package/src/deployment-api/index.js +210 -0
  72. package/src/deployment-api/path-matcher.js +45 -0
  73. package/src/deployment-api/registry.js +84 -0
  74. package/src/deployment-api/run-store.js +798 -0
  75. package/src/deployment-api/sanitize.js +114 -0
  76. package/src/http-client/request.js +3 -1
  77. package/src/sync/signed-sync-envelope-replay-service.js +342 -0
  78. package/src/sync/sync-envelope-replay-service.js +110 -15
  79. package/src/utils/bearer-token.js +34 -0
  80. package/src/utils/mount-prefix.js +36 -0
@@ -0,0 +1,437 @@
1
+ // @ts-check
2
+
3
+ import Controller from "../controller.js"
4
+ import DeploymentRunStore, {registerActiveDeploymentRun, unregisterActiveDeploymentRun} from "./run-store.js"
5
+ import {bearerToken, constantTimeEqual} from "../utils/bearer-token.js"
6
+ import {getDeploymentMount} from "./registry.js"
7
+ import {sanitizeAdapterValue, sanitizeErrorPayload} from "./sanitize.js"
8
+
9
+ const REVISION_PATTERN = /^[0-9a-f]{40}$/
10
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 255
11
+
12
+ /**
13
+ * Resolves allowlisted stage options with own-property checks only, so
14
+ * request-controlled names like "__proto__" or "constructor" can never
15
+ * resolve inherited values. The normalized maps are also null-prototype, so
16
+ * this is defense in depth.
17
+ * @param {import("./registry.js").DeploymentMountOptions} options - Mount options.
18
+ * @param {string} project - Requested project identifier.
19
+ * @param {string} stage - Requested stage identifier.
20
+ * @returns {import("./registry.js").DeploymentStageOptions | undefined} - Stage options when allowlisted.
21
+ */
22
+ function lookupStageOptions(options, project, stage) {
23
+ if (!Object.hasOwn(options.projects, project)) return undefined
24
+
25
+ const stages = options.projects[project].stages
26
+
27
+ if (!Object.hasOwn(stages, stage)) return undefined
28
+
29
+ return stages[stage]
30
+ }
31
+
32
+ /**
33
+ * Authenticated HTTP API for callable deployments. Mounted by
34
+ * {@link import("./index.js").default} as a route-resolver hook so it can ship
35
+ * inside the velocious package. Every action is gated by a bearer-token check
36
+ * against the configured access tokens; the API exposes only allowlisted
37
+ * project/stage pairs and full immutable revisions, and delegates all
38
+ * execution to the configured adapter. It never accepts commands, paths,
39
+ * arbitrary refs, environment variables, or raw log output.
40
+ */
41
+ export default class VelociousDeploymentApiController extends Controller {
42
+ /**
43
+ * Runs mount options.
44
+ * @returns {import("./registry.js").DeploymentMountOptions} - Options for the mount that matched this request.
45
+ */
46
+ _mountOptions() {
47
+ const at = /** @type {string} */ (this.params().velociousDeploymentMountAt)
48
+ const options = getDeploymentMount(this.getConfiguration(), at)
49
+
50
+ if (!options) throw new Error(`No deployment API mount registered at ${at}`)
51
+
52
+ return options
53
+ }
54
+
55
+ /**
56
+ * Runs store.
57
+ * @returns {DeploymentRunStore} - Run store scoped to the mount's database.
58
+ */
59
+ _store() {
60
+ if (!this._deploymentRunStore) {
61
+ this._deploymentRunStore = new DeploymentRunStore({
62
+ configuration: this.getConfiguration(),
63
+ databaseIdentifier: this._mountOptions().databaseIdentifier,
64
+ mountIdentifier: this._mountOptions().mountIdentifier,
65
+ staleRunTimeoutMs: this._mountOptions().staleRunTimeoutMs
66
+ })
67
+ }
68
+
69
+ return this._deploymentRunStore
70
+ }
71
+
72
+ /**
73
+ * Reports one internally consumed framework failure on both documented
74
+ * error channels so framework-specific and unified reporters see the same
75
+ * payload.
76
+ * @param {object} args - Options.
77
+ * @param {string} args.context - Deployment API failure context.
78
+ * @param {?} args.error - Consumed error.
79
+ * @returns {void} - No return value.
80
+ */
81
+ _emitFrameworkError({context, error}) {
82
+ const errorEvents = this.getConfiguration().getErrorEvents()
83
+ const payload = {context, error, request: this.getRequest()}
84
+
85
+ errorEvents.emit("framework-error", payload)
86
+ errorEvents.emit("all-error", {...payload, errorType: "framework-error"})
87
+ }
88
+
89
+ /**
90
+ * Authorizes the request with a constant-time bearer-token comparison and
91
+ * runs the action body only when authorized. Renders a 401 otherwise. The
92
+ * base controller has no before-action halting, so authorization is enforced
93
+ * here per action. Tokens are only accepted through the Authorization header
94
+ * — never through URLs — and are never rendered back.
95
+ * @param {() => Promise<void>} actionFn - Action body.
96
+ * @returns {Promise<void>} - Resolves when complete.
97
+ */
98
+ async _respond(actionFn) {
99
+ const token = bearerToken(this.request())
100
+ let authorized = false
101
+
102
+ if (token) {
103
+ for (const accessToken of this._mountOptions().accessTokens) {
104
+ if (constantTimeEqual(token, accessToken)) {
105
+ authorized = true
106
+ break
107
+ }
108
+ }
109
+ }
110
+
111
+ if (!authorized) {
112
+ await this.render({json: {error: "unauthorized"}, status: 401})
113
+ return
114
+ }
115
+
116
+ await actionFn()
117
+ }
118
+
119
+ /**
120
+ * Creates a deployment run for an allowlisted project/stage and a full
121
+ * immutable revision reachable from the approved release branch. Idempotent:
122
+ * a retried idempotency key reads the original run, a reused key with a
123
+ * different payload conflicts, and an active run for the same project/stage
124
+ * returns a bounded conflict.
125
+ * @returns {Promise<void>} - Resolves when complete.
126
+ */
127
+ async create() {
128
+ await this._respond(async () => {
129
+ const params = this.params()
130
+ const revision = typeof params.revision === "string" ? params.revision : null
131
+ const idempotencyKey = typeof params.idempotencyKey === "string" ? params.idempotencyKey : null
132
+ const invalidFields = []
133
+
134
+ if (!revision || !REVISION_PATTERN.test(revision)) invalidFields.push("revision")
135
+ if (!idempotencyKey || idempotencyKey.length === 0 || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
136
+ invalidFields.push("idempotencyKey")
137
+ }
138
+
139
+ if (invalidFields.length > 0) {
140
+ await this.render({json: {error: "invalid_params", fields: invalidFields}, status: 422})
141
+ return
142
+ }
143
+
144
+ const options = this._mountOptions()
145
+ const project = typeof params.project === "string" ? params.project : ""
146
+ const stage = typeof params.stage === "string" ? params.stage : ""
147
+ const stageOptions = lookupStageOptions(options, project, stage)
148
+
149
+ if (!stageOptions) {
150
+ await this.render({json: {error: "not_found"}, status: 404})
151
+ return
152
+ }
153
+
154
+ const store = this._store()
155
+ const validRevision = /** @type {string} */ (revision)
156
+ const validIdempotencyKey = /** @type {string} */ (idempotencyKey)
157
+
158
+ // Retries read the original run before anything else — a replay must
159
+ // never re-validate or re-deploy.
160
+ const existingRun = await store.findRunByKey(validIdempotencyKey)
161
+
162
+ if (existingRun) {
163
+ await this._renderExistingRun({existingRun, project, revision: validRevision, stage})
164
+ return
165
+ }
166
+
167
+ const reachable = await options.adapter.validateRevision({
168
+ configuration: this.getConfiguration(),
169
+ project,
170
+ releaseBranch: stageOptions.releaseBranch,
171
+ revision: validRevision,
172
+ stage
173
+ })
174
+
175
+ if (!reachable) {
176
+ await this.render({json: {error: "revision_not_reachable"}, status: 422})
177
+ return
178
+ }
179
+
180
+ const outcome = await store.createRunIfPossible({
181
+ idempotencyKey: validIdempotencyKey,
182
+ project,
183
+ revision: validRevision,
184
+ stage
185
+ })
186
+
187
+ if (outcome.outcome === "replay" || outcome.outcome === "conflict") {
188
+ const existingFromStore = outcome.run
189
+
190
+ if (!existingFromStore) throw new Error(`Deployment run store reported '${outcome.outcome}' without a run`)
191
+
192
+ await this._renderExistingRun({existingRun: existingFromStore, project, revision: validRevision, stage})
193
+ return
194
+ }
195
+
196
+ if (outcome.outcome === "in_progress") {
197
+ const activeRun = outcome.run
198
+
199
+ await this.render({json: {error: "deployment_in_progress", runId: activeRun ? activeRun.id : undefined}, status: 409})
200
+ return
201
+ }
202
+
203
+ if (outcome.outcome === "reconciliation_required") {
204
+ const blockedRun = outcome.run
205
+
206
+ if (!blockedRun) throw new Error("Deployment run store reported 'reconciliation_required' without a run")
207
+
208
+ await this.render({json: {error: "deployment_reconciliation_required", runId: blockedRun.id}, status: 409})
209
+ return
210
+ }
211
+
212
+ const run = outcome.run
213
+
214
+ if (!run) throw new Error("Deployment run store reported 'created' without a run")
215
+
216
+ await this._audit({event: "run_requested", payload: {project, revision: validRevision, stage}, runId: run.id})
217
+
218
+ // Execution is deliberately not awaited: the deploy runs under the
219
+ // integration's own lock/build/health/rollback semantics and the caller
220
+ // reads progress back through the show action.
221
+ this._executeRun({options, run}).catch((error) => {
222
+ this._emitFrameworkError({context: "deployment-api-execute-run", error})
223
+ })
224
+
225
+ await this.render({json: {run: this._serializeRun(run)}, status: 202})
226
+ })
227
+ }
228
+
229
+ /**
230
+ * Renders a previously created run for an idempotency-key hit: a replay when
231
+ * the payload matches, a bounded conflict when it doesn't.
232
+ * @param {object} args - Options.
233
+ * @param {import("./run-store.js").DeploymentRunRow} args.existingRun - The stored run.
234
+ * @param {string} args.project - Requested project.
235
+ * @param {string} args.revision - Requested revision.
236
+ * @param {string} args.stage - Requested stage.
237
+ * @returns {Promise<void>} - Resolves when complete.
238
+ */
239
+ async _renderExistingRun({existingRun, project, revision, stage}) {
240
+ const samePayload = existingRun.project === project && existingRun.stage === stage && existingRun.revision === revision
241
+
242
+ if (!samePayload) {
243
+ await this.render({json: {error: "idempotency_conflict", runId: existingRun.id}, status: 409})
244
+ return
245
+ }
246
+
247
+ await this.render({json: {replayed: true, run: this._serializeRun(existingRun)}, status: 200})
248
+ }
249
+
250
+ /**
251
+ * Returns the bounded state of a single run, enriched with the adapter's
252
+ * live status when the integration provides one.
253
+ * @returns {Promise<void>} - Resolves when complete.
254
+ */
255
+ async show() {
256
+ await this._respond(async () => {
257
+ const run = await this._store().findRunById(/** @type {string} */ (this.params().id))
258
+
259
+ if (!run) {
260
+ await this.render({json: {error: "not_found"}, status: 404})
261
+ return
262
+ }
263
+
264
+ const options = this._mountOptions()
265
+ /** @type {Record<string, ?>} */
266
+ const body = {run: this._serializeRun(run)}
267
+
268
+ if (options.adapter.readStatus) {
269
+ const liveStatus = await options.adapter.readStatus({
270
+ configuration: this.getConfiguration(),
271
+ project: run.project,
272
+ stage: run.stage
273
+ })
274
+
275
+ body.current = sanitizeAdapterValue(liveStatus, options.accessTokens) ?? null
276
+ }
277
+
278
+ await this.render({json: body, status: 200})
279
+ })
280
+ }
281
+
282
+ /**
283
+ * Executes a created run asynchronously: registers it as active in this
284
+ * process, marks it running, heartbeats its ownership lease while the
285
+ * adapter deploys, and records the sanitized outcome. A deployment failure
286
+ * is an expected operational result — it is persisted with its sanitized
287
+ * recovery information instead of being raised, so it stays visible through
288
+ * readback and audit rather than crashing the worker.
289
+ * @param {object} args - Options.
290
+ * @param {import("./registry.js").DeploymentMountOptions} args.options - Mount options.
291
+ * @param {import("./run-store.js").DeploymentRunRow} args.run - The created run.
292
+ * @returns {Promise<void>} - Resolves when the outcome is recorded.
293
+ */
294
+ async _executeRun({options, run}) {
295
+ const store = this._store()
296
+ const secrets = options.accessTokens
297
+ const stageOptions = lookupStageOptions(options, run.project, run.stage)
298
+
299
+ if (!stageOptions) throw new Error(`Deployment run ${run.id} references non-allowlisted ${run.project}/${run.stage}`)
300
+ if (!run.ownerToken) throw new Error(`Deployment run ${run.id} has no execution owner token`)
301
+
302
+ const ownerToken = run.ownerToken
303
+
304
+ registerActiveDeploymentRun(run.id)
305
+
306
+ /** @type {ReturnType<typeof setInterval> | null} */
307
+ let heartbeatTimer = null
308
+
309
+ try {
310
+ await store.markRunning({id: run.id, startedAtMs: Date.now()})
311
+
312
+ // Renew the ownership lease while the deploy runs so reconciliation
313
+ // never reclaims this genuinely active run; unref'd so the timer alone
314
+ // keeps no process alive.
315
+ const heartbeatIntervalMs = Math.max(1000, Math.floor(options.staleRunTimeoutMs / 4))
316
+
317
+ heartbeatTimer = setInterval(() => {
318
+ store.heartbeat({heartbeatAtMs: Date.now(), id: run.id}).catch((error) => {
319
+ this._emitFrameworkError({context: "deployment-api-heartbeat", error})
320
+ })
321
+ }, heartbeatIntervalMs)
322
+ heartbeatTimer.unref()
323
+
324
+ await this._audit({event: "run_started", payload: {project: run.project, revision: run.revision, stage: run.stage}, runId: run.id})
325
+
326
+ let report
327
+
328
+ try {
329
+ report = await options.adapter.deploy({
330
+ configuration: this.getConfiguration(),
331
+ project: run.project,
332
+ releaseBranch: stageOptions.releaseBranch,
333
+ revision: run.revision,
334
+ runId: run.id,
335
+ stage: run.stage
336
+ })
337
+ } catch (error) {
338
+ const errorPayload = sanitizeErrorPayload(error, secrets)
339
+
340
+ try {
341
+ await store.markFailed({error: errorPayload, finishedAtMs: Date.now(), id: run.id, ownerToken})
342
+ await this._audit({
343
+ event: "run_failed",
344
+ payload: {message: errorPayload.message, project: run.project, revision: run.revision, stage: run.stage},
345
+ runId: run.id
346
+ })
347
+ } catch (storeError) {
348
+ // Recording the failure itself failed — that is an unexpected bug
349
+ // and must surface to process-level error reporters.
350
+ this._emitFrameworkError({context: "deployment-api-record-failure", error: storeError})
351
+ }
352
+
353
+ return
354
+ }
355
+
356
+ try {
357
+ const result = sanitizeAdapterValue(report ?? {}, secrets) ?? {}
358
+
359
+ await store.markSucceeded({finishedAtMs: Date.now(), id: run.id, ownerToken, result})
360
+ await this._audit({event: "run_succeeded", payload: {project: run.project, revision: run.revision, stage: run.stage}, runId: run.id})
361
+ } catch (error) {
362
+ // The adapter already returned success. Surface the recording error,
363
+ // then fence the run in a durable non-retryable state rather than
364
+ // falsely recording an external success as a deployment failure.
365
+ this._emitFrameworkError({context: "deployment-api-record-success", error})
366
+
367
+ const reconciliationError = {
368
+ message: "Deployment activation succeeded, but its result could not be persisted; operator reconciliation is required"
369
+ }
370
+
371
+ try {
372
+ await store.markReconciliationRequired({
373
+ error: reconciliationError,
374
+ finishedAtMs: Date.now(),
375
+ id: run.id,
376
+ ownerToken
377
+ })
378
+ await this._audit({
379
+ event: "run_reconciliation_required",
380
+ payload: {message: reconciliationError.message, project: run.project, revision: run.revision, stage: run.stage},
381
+ runId: run.id
382
+ })
383
+ } catch (reconciliationErrorPersistenceError) {
384
+ this._emitFrameworkError({
385
+ context: "deployment-api-record-reconciliation-required",
386
+ error: reconciliationErrorPersistenceError
387
+ })
388
+ }
389
+ }
390
+ } finally {
391
+ if (heartbeatTimer) clearInterval(heartbeatTimer)
392
+ unregisterActiveDeploymentRun(run.id)
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Records a sanitized audit event. Audit persistence must never strand or
398
+ * suppress a deployment, so a failure here is reported on the
399
+ * framework-error and unified all-error channels (where process-level bug
400
+ * reporters capture it), and execution continues.
401
+ * @param {object} args - Options.
402
+ * @param {string} args.event - Event name.
403
+ * @param {Record<string, ?>} args.payload - Payload; sanitized and redacted before persistence.
404
+ * @param {string | null} args.runId - Owning run id.
405
+ * @returns {Promise<void>} - Resolves when recorded or reported.
406
+ */
407
+ async _audit({event, payload, runId}) {
408
+ const sanitized = sanitizeAdapterValue(payload, this._mountOptions().accessTokens) ?? {}
409
+
410
+ try {
411
+ await this._store().addAuditEvent({event, payload: sanitized, runId})
412
+ } catch (error) {
413
+ this._emitFrameworkError({context: "deployment-api-audit", error})
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Serializes a run for the API.
419
+ * @param {import("./run-store.js").DeploymentRunRow} run - Run row.
420
+ * @returns {Record<string, ?>} - Serialized run.
421
+ */
422
+ _serializeRun(run) {
423
+ return {
424
+ error: run.error,
425
+ finishedAtMs: run.finishedAtMs,
426
+ id: run.id,
427
+ idempotencyKey: run.idempotencyKey,
428
+ project: run.project,
429
+ requestedAtMs: run.requestedAtMs,
430
+ result: run.result,
431
+ revision: run.revision,
432
+ stage: run.stage,
433
+ startedAtMs: run.startedAtMs,
434
+ status: run.status
435
+ }
436
+ }
437
+ }
@@ -0,0 +1,210 @@
1
+ // @ts-check
2
+
3
+ import VelociousDeploymentApiController from "./controller.js"
4
+ import {matchDeploymentApiPath} from "./path-matcher.js"
5
+ import {normalizeMountPrefix} from "../utils/mount-prefix.js"
6
+ import {deploymentMountIdentifier, registerDeploymentMount} from "./registry.js"
7
+
8
+ const IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9_-]*$/
9
+ const MAX_IDENTIFIER_LENGTH = 64
10
+ const BRANCH_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*(\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/
11
+
12
+ /**
13
+ * Validates one allowlist identifier (project or stage). Bounded identifiers
14
+ * keep every value the API handles safe to pass to the adapter as data.
15
+ * @param {?} value - Raw identifier.
16
+ * @param {string} name - Human-readable name for error messages.
17
+ * @returns {string} - The validated identifier.
18
+ */
19
+ function validateIdentifier(value, name) {
20
+ if (typeof value !== "string" || value.length > MAX_IDENTIFIER_LENGTH || !IDENTIFIER_PATTERN.test(value)) {
21
+ throw new Error(`Invalid ${name} identifier: ${String(value)}`)
22
+ }
23
+
24
+ return value
25
+ }
26
+
27
+ /**
28
+ * Validates the projects allowlist and returns a normalized copy.
29
+ * @param {?} projects - Raw projects option.
30
+ * @returns {Record<string, import("./registry.js").DeploymentProjectOptions>} - Normalized allowlist.
31
+ */
32
+ function validateProjects(projects) {
33
+ if (!projects || typeof projects !== "object" || Array.isArray(projects)) {
34
+ throw new Error("VelociousDeploymentApi requires a 'projects' allowlist object")
35
+ }
36
+
37
+ // Null-prototype maps so request-controlled names like "__proto__" or
38
+ // "constructor" can never resolve inherited properties as allowlisted
39
+ // projects/stages.
40
+ /** @type {Record<string, import("./registry.js").DeploymentProjectOptions>} */
41
+ const normalized = Object.create(null)
42
+
43
+ for (const [project, projectOptions] of Object.entries(projects)) {
44
+ validateIdentifier(project, "project")
45
+
46
+ const stages = /** @type {Record<string, ?>} */ (projectOptions)?.stages
47
+
48
+ if (!stages || typeof stages !== "object" || Array.isArray(stages) || Object.keys(stages).length === 0) {
49
+ throw new Error(`Project ${project} must allowlist at least one stage`)
50
+ }
51
+
52
+ /** @type {Record<string, import("./registry.js").DeploymentStageOptions>} */
53
+ const normalizedStages = Object.create(null)
54
+
55
+ for (const [stage, stageOptions] of Object.entries(stages)) {
56
+ validateIdentifier(stage, "stage")
57
+
58
+ const releaseBranch = /** @type {Record<string, ?>} */ (stageOptions)?.releaseBranch
59
+
60
+ if (typeof releaseBranch !== "string" || !BRANCH_PATTERN.test(releaseBranch) || releaseBranch.includes("..")) {
61
+ throw new Error(`Invalid release branch for ${project}/${stage}: ${String(releaseBranch)}`)
62
+ }
63
+
64
+ normalizedStages[stage] = {releaseBranch}
65
+ }
66
+
67
+ normalized[project] = {stages: normalizedStages}
68
+ }
69
+
70
+ if (Object.keys(normalized).length === 0) {
71
+ throw new Error("VelociousDeploymentApi requires at least one allowlisted project")
72
+ }
73
+
74
+ return normalized
75
+ }
76
+
77
+ /**
78
+ * Validates the adapter contract so misconfiguration fails at boot rather than
79
+ * on the first request.
80
+ * @param {?} adapter - Raw adapter option.
81
+ * @returns {import("./registry.js").DeploymentAdapter} - The validated adapter.
82
+ */
83
+ function validateAdapter(adapter) {
84
+ if (!adapter || typeof adapter !== "object") {
85
+ throw new Error("VelociousDeploymentApi requires an 'adapter' object")
86
+ }
87
+
88
+ const candidate = /** @type {Record<string, ?>} */ (adapter)
89
+
90
+ for (const methodName of ["validateRevision", "deploy"]) {
91
+ if (typeof candidate[methodName] !== "function") {
92
+ throw new TypeError(`VelociousDeploymentApi adapter must respond to ${methodName}()`)
93
+ }
94
+ }
95
+
96
+ if (candidate.readStatus !== undefined && typeof candidate.readStatus !== "function") {
97
+ throw new TypeError("VelociousDeploymentApi adapter readStatus must be a function when given")
98
+ }
99
+
100
+ return /** @type {import("./registry.js").DeploymentAdapter} */ (adapter)
101
+ }
102
+
103
+ /**
104
+ * Validates the access tokens. The API fails closed: without at least one
105
+ * configured token every request is unauthorized, so mounting without tokens
106
+ * is a configuration error.
107
+ * @param {?} accessTokens - Raw access tokens option.
108
+ * @returns {string[]} - The validated tokens.
109
+ */
110
+ function validateAccessTokens(accessTokens) {
111
+ if (!Array.isArray(accessTokens)) {
112
+ throw new Error("VelociousDeploymentApi requires an 'accessTokens' array with at least one token")
113
+ }
114
+
115
+ for (const token of accessTokens) {
116
+ if (typeof token !== "string" || token.length === 0) {
117
+ throw new Error("VelociousDeploymentApi access tokens must all be non-empty strings")
118
+ }
119
+ }
120
+
121
+ if (accessTokens.length === 0) {
122
+ throw new Error("VelociousDeploymentApi requires at least one non-empty access token; the API fails closed without one")
123
+ }
124
+
125
+ return [...accessTokens]
126
+ }
127
+
128
+ const DEFAULT_STALE_RUN_TIMEOUT_MS = 60000
129
+
130
+ /**
131
+ * Validates the stale-run lease timeout: after this many milliseconds without
132
+ * an ownership heartbeat, a later request reconciles pending work as
133
+ * interrupted and running work as requiring operator reconciliation.
134
+ * @param {?} value - Raw option value.
135
+ * @returns {number} - The timeout in milliseconds.
136
+ */
137
+ function validateStaleRunTimeoutMs(value) {
138
+ if (value === undefined) return DEFAULT_STALE_RUN_TIMEOUT_MS
139
+
140
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
141
+ throw new Error(`VelociousDeploymentApi staleRunTimeoutMs must be a positive integer, got: ${String(value)}`)
142
+ }
143
+
144
+ return value
145
+ }
146
+
147
+ /**
148
+ * Mountable authenticated deployment API. A narrowly configured consumer
149
+ * mounts it in its routes file and supplies an adapter owned by the deployment
150
+ * integration (e.g. Rampway) that performs the actual lock/build/release/
151
+ * health/rollback/cleanup work:
152
+ *
153
+ * ```js
154
+ * routes.draw((route) => {
155
+ * route.mount(VelociousDeploymentApi, {
156
+ * at: "/velocious/deployments",
157
+ * accessTokens: [secrets.deploymentApiToken],
158
+ * adapter: rampwayDeploymentAdapter,
159
+ * projects: {
160
+ * "my-app": {stages: {production: {releaseBranch: "master"}}}
161
+ * }
162
+ * })
163
+ * })
164
+ * ```
165
+ */
166
+ export default class VelociousDeploymentApi {
167
+ /**
168
+ * Registers the deployment API under `at`. Implemented as a route-resolver
169
+ * hook so the controller can live inside the velocious package rather than
170
+ * the host app's `src/routes` directory. Invoked by the routing layer for
171
+ * each `route.mount(...)` registration.
172
+ * @param {object} args - Options.
173
+ * @param {import("../configuration.js").default} args.configuration - Configuration instance.
174
+ * @param {string} args.at - Mount path prefix (e.g. "/velocious/deployments").
175
+ * @param {string[]} args.accessTokens - Accepted bearer tokens; requests authenticate with `Authorization: Bearer <token>` only.
176
+ * @param {import("./registry.js").DeploymentAdapter} args.adapter - Deployment integration adapter that owns execution.
177
+ * @param {Record<string, import("./registry.js").DeploymentProjectOptions>} args.projects - Allowlisted projects/stages with their approved release branches.
178
+ * @param {string} [args.databaseIdentifier] - Database identifier the run store reads from.
179
+ * @param {number} [args.staleRunTimeoutMs] - Lease timeout after which an active run without a heartbeat is reconciled according to its execution state; defaults to 60000.
180
+ * @returns {void} - No return value.
181
+ */
182
+ static mountInto({accessTokens, adapter, at, configuration, databaseIdentifier, projects, staleRunTimeoutMs}) {
183
+ if (!configuration) throw new Error("No configuration given")
184
+
185
+ const prefix = normalizeMountPrefix(at)
186
+ const options = {
187
+ accessTokens: validateAccessTokens(accessTokens),
188
+ adapter: validateAdapter(adapter),
189
+ databaseIdentifier,
190
+ mountIdentifier: deploymentMountIdentifier(prefix),
191
+ projects: validateProjects(projects),
192
+ staleRunTimeoutMs: validateStaleRunTimeoutMs(staleRunTimeoutMs)
193
+ }
194
+
195
+ registerDeploymentMount(configuration, prefix, options)
196
+
197
+ configuration.addRouteResolverHook(({currentPath, request}) => {
198
+ const match = matchDeploymentApiPath({method: request.httpMethod(), path: currentPath, prefix})
199
+
200
+ if (!match) return null
201
+
202
+ return {
203
+ action: match.action,
204
+ controller: "velociousDeploymentApi",
205
+ controllerClass: VelociousDeploymentApiController,
206
+ params: {...match.params, velociousDeploymentMountAt: prefix}
207
+ }
208
+ })
209
+ }
210
+ }
@@ -0,0 +1,45 @@
1
+ // @ts-check
2
+
3
+ import {mountSubPath} from "../utils/mount-prefix.js"
4
+
5
+ /**
6
+ * @typedef {object} DeploymentApiMatch
7
+ * @property {string} action - Controller action to run.
8
+ * @property {Record<string, string>} params - Extra params extracted from the path.
9
+ */
10
+
11
+ /**
12
+ * Matches an incoming request against the deployment API routes that live
13
+ * under the mount prefix. Returns the controller action plus any extracted
14
+ * params, or null when the path/method isn't part of the deployment API.
15
+ * @param {object} args - Options.
16
+ * @param {string} args.prefix - Normalized mount prefix.
17
+ * @param {string} args.path - Request path without query string.
18
+ * @param {string} args.method - HTTP method.
19
+ * @returns {DeploymentApiMatch | null} - Matched action or null.
20
+ */
21
+ export function matchDeploymentApiPath({prefix, path, method}) {
22
+ const subPath = mountSubPath({prefix, path})
23
+
24
+ if (subPath === null) return null
25
+
26
+ if (method === "POST" && subPath === "/runs") return {action: "create", params: {}}
27
+
28
+ if (method === "GET") {
29
+ const runMatch = subPath.match(/^\/runs\/([^/]+)$/)
30
+
31
+ if (runMatch) {
32
+ let id
33
+
34
+ try {
35
+ id = decodeURIComponent(runMatch[1])
36
+ } catch {
37
+ return null
38
+ }
39
+
40
+ return {action: "show", params: {id}}
41
+ }
42
+ }
43
+
44
+ return null
45
+ }