@rathnasgala2/adapter-github-pages 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/carrier.js ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The deterministic Pages carrier codec (slice brief section 2.3: "its
3
+ * deterministic one-member gzip/POSIX.1-1988 ustar bytes"). The carrier is
4
+ * the *only* thing this adapter ever hands the provider, and it is
5
+ * byte-deterministic for a given file set: identical inputs always produce
6
+ * identical carrier bytes, so a lost create response can be recovered
7
+ * without re-deriving a different artifact identity.
8
+ *
9
+ * Determinism comes from fixing every field a tar writer would normally
10
+ * take from the ambient environment: modification time `0`, owner/group id
11
+ * `0`, empty owner/group names, a fixed file mode, no PAX or GNU extension
12
+ * records, entries emitted in ascending UTF-8 path order, and a gzip member
13
+ * written with a zeroed MTIME/OS byte.
14
+ *
15
+ * @module
16
+ */
17
+
18
+ import { gunzipSync, gzipSync } from 'node:zlib';
19
+
20
+ const BLOCK_BYTES = 512;
21
+ const NAME_FIELD_BYTES = 100;
22
+ const PREFIX_FIELD_BYTES = 155;
23
+ const FILE_MODE = '0000644';
24
+ const USTAR_MAGIC = 'ustar\0' + '00';
25
+
26
+ /**
27
+ * @typedef {Readonly<{path: string, bytes: Buffer}>} CarrierFile
28
+ */
29
+
30
+ /**
31
+ * Write one fixed-width, NUL-padded ASCII field into a header block.
32
+ *
33
+ * @param {Buffer} block the 512-byte header block
34
+ * @param {number} offset the field's byte offset
35
+ * @param {number} length the field's byte length
36
+ * @param {string} value the ASCII value (must fit in `length - 1` bytes when
37
+ * a terminating NUL is required by the caller's field choice)
38
+ * @returns {void}
39
+ */
40
+ function writeField(block, offset, length, value) {
41
+ const bytes = Buffer.from(value, 'ascii');
42
+ if (bytes.byteLength > length) {
43
+ throw new RangeError(
44
+ `PAGES_CARRIER_FIELD_OVERFLOW: value of ${bytes.byteLength} bytes does not fit a ${length}-byte ustar field`,
45
+ );
46
+ }
47
+ bytes.copy(block, offset);
48
+ }
49
+
50
+ /**
51
+ * Split one POSIX path into the ustar `prefix`/`name` pair, refusing any
52
+ * path that cannot be represented without a GNU/PAX extension record (which
53
+ * would make the carrier writer-dependent rather than deterministic).
54
+ *
55
+ * @param {string} entryPath the artifact-relative POSIX path
56
+ * @returns {{name: string, prefix: string}} the split fields
57
+ */
58
+ export function splitUstarPath(entryPath) {
59
+ const bytes = Buffer.from(entryPath, 'utf8');
60
+ if (bytes.byteLength <= NAME_FIELD_BYTES) {
61
+ return { name: entryPath, prefix: '' };
62
+ }
63
+ const segments = entryPath.split('/');
64
+ for (let cut = 1; cut < segments.length; cut += 1) {
65
+ const prefix = segments.slice(0, cut).join('/');
66
+ const name = segments.slice(cut).join('/');
67
+ if (
68
+ Buffer.byteLength(prefix, 'utf8') <= PREFIX_FIELD_BYTES &&
69
+ Buffer.byteLength(name, 'utf8') <= NAME_FIELD_BYTES
70
+ ) {
71
+ return { name, prefix };
72
+ }
73
+ }
74
+ throw new RangeError(
75
+ `PAGES_CARRIER_PATH_UNREPRESENTABLE: ${JSON.stringify(entryPath)} cannot be written as POSIX.1-1988 ustar without an extension record`,
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Refuse any member path that would not extract inside the carrier root.
81
+ *
82
+ * The carrier is extracted by the provider, not by this process, so the
83
+ * only place an escaping member can be stopped is here, at the point it is
84
+ * written. Only regular-file entries are ever emitted (typeflag `0`): this
85
+ * codec has no link, device or directory entry, so a symlink/hardlink
86
+ * member cannot exist to be followed.
87
+ *
88
+ * @param {string} entryPath the artifact-relative POSIX path
89
+ * @returns {string} the accepted path
90
+ */
91
+ export function requireContainedPath(entryPath) {
92
+ const segments = entryPath.split('/');
93
+ if (
94
+ entryPath === '' ||
95
+ entryPath.startsWith('/') ||
96
+ entryPath.includes('\\') ||
97
+ entryPath.includes('\0') ||
98
+ segments.some(
99
+ (segment) => segment === '' || segment === '.' || segment === '..',
100
+ )
101
+ ) {
102
+ throw new RangeError(
103
+ `PAGES_CARRIER_PATH_REFUSED: ${JSON.stringify(entryPath)} is not a contained relative POSIX path; the carrier never emits a member that can extract outside its own root`,
104
+ );
105
+ }
106
+ return entryPath;
107
+ }
108
+
109
+ /**
110
+ * Build one 512-byte ustar header block for a regular file.
111
+ *
112
+ * @param {string} entryPath the artifact-relative POSIX path
113
+ * @param {number} byteLength the member's byte length
114
+ * @returns {Buffer} the header block, with its checksum applied
115
+ */
116
+ function buildHeaderBlock(entryPath, byteLength) {
117
+ const block = Buffer.alloc(BLOCK_BYTES);
118
+ const { name, prefix } = splitUstarPath(requireContainedPath(entryPath));
119
+
120
+ writeField(block, 0, NAME_FIELD_BYTES, name);
121
+ writeField(block, 100, 8, FILE_MODE);
122
+ writeField(block, 108, 8, '0000000');
123
+ writeField(block, 116, 8, '0000000');
124
+ writeField(block, 124, 12, byteLength.toString(8).padStart(11, '0'));
125
+ writeField(block, 136, 12, '00000000000');
126
+ block.fill(0x20, 148, 156);
127
+ block.write('0', 156, 1, 'ascii');
128
+ writeField(block, 257, 8, USTAR_MAGIC);
129
+ writeField(block, 345, PREFIX_FIELD_BYTES, prefix);
130
+
131
+ let checksum = 0;
132
+ for (const byte of block) {
133
+ checksum += byte;
134
+ }
135
+ writeField(block, 148, 8, `${checksum.toString(8).padStart(6, '0')}\0 `);
136
+ return block;
137
+ }
138
+
139
+ /**
140
+ * Encode a complete file set as deterministic one-member gzip/ustar carrier
141
+ * bytes.
142
+ *
143
+ * @param {readonly CarrierFile[]} files the complete artifact file set,
144
+ * including the reserved public generation marker
145
+ * @returns {Buffer} the carrier bytes
146
+ */
147
+ export function encodeCarrier(files) {
148
+ const ordered = [...files].sort((left, right) =>
149
+ left.path < right.path ? -1 : left.path > right.path ? 1 : 0,
150
+ );
151
+ /** @type {Buffer[]} */
152
+ const blocks = [];
153
+ for (const file of ordered) {
154
+ blocks.push(buildHeaderBlock(file.path, file.bytes.byteLength));
155
+ blocks.push(file.bytes);
156
+ const remainder = file.bytes.byteLength % BLOCK_BYTES;
157
+ if (remainder !== 0) {
158
+ blocks.push(Buffer.alloc(BLOCK_BYTES - remainder));
159
+ }
160
+ }
161
+ blocks.push(Buffer.alloc(BLOCK_BYTES * 2));
162
+
163
+ const gzipped = gzipSync(Buffer.concat(blocks), { level: 9 });
164
+ // Zero the gzip header's MTIME (bytes 4..7) and OS (byte 9) fields, the
165
+ // only two places zlib is permitted to record ambient facts.
166
+ gzipped.writeUInt32LE(0, 4);
167
+ gzipped.writeUInt8(0xff, 9);
168
+ return gzipped;
169
+ }
170
+
171
+ /**
172
+ * Decode carrier bytes back into the exact file set they were built from.
173
+ * The adapter itself never needs this (it only ever writes a carrier); it
174
+ * exists so a caller — the Pages provider, a conformance fixture or a
175
+ * codec golden test — can prove the round trip is lossless.
176
+ *
177
+ * @param {Buffer} carrier the carrier bytes
178
+ * @returns {CarrierFile[]} the decoded file set, in carrier order
179
+ */
180
+ export function decodeCarrier(carrier) {
181
+ const tar = gunzipSync(carrier);
182
+ /** @type {CarrierFile[]} */
183
+ const files = [];
184
+ let offset = 0;
185
+ while (offset + BLOCK_BYTES <= tar.byteLength) {
186
+ const header = tar.subarray(offset, offset + BLOCK_BYTES);
187
+ if (header.every((byte) => byte === 0)) {
188
+ break;
189
+ }
190
+ const name = readAsciiField(header, 0, NAME_FIELD_BYTES);
191
+ const prefix = readAsciiField(header, 345, PREFIX_FIELD_BYTES);
192
+ const size = Number.parseInt(
193
+ readAsciiField(header, 124, 12).trim() || '0',
194
+ 8,
195
+ );
196
+ offset += BLOCK_BYTES;
197
+ files.push({
198
+ path: prefix === '' ? name : `${prefix}/${name}`,
199
+ bytes: Buffer.from(tar.subarray(offset, offset + size)),
200
+ });
201
+ offset += Math.ceil(size / BLOCK_BYTES) * BLOCK_BYTES;
202
+ }
203
+ return files;
204
+ }
205
+
206
+ /**
207
+ * @param {Buffer} block a header block
208
+ * @param {number} offset field offset
209
+ * @param {number} length field length
210
+ * @returns {string} the field value up to its first NUL
211
+ */
212
+ function readAsciiField(block, offset, length) {
213
+ const raw = block.subarray(offset, offset + length);
214
+ const end = raw.indexOf(0);
215
+ return raw.subarray(0, end === -1 ? raw.length : end).toString('utf8');
216
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Closed constants for the managed `github-pages` adapter: the reserved
3
+ * public-marker coordinate, the exact GitHub Pages deployment status
4
+ * vocabulary and its terminal/temporary partition, the exact poll schedule,
5
+ * and every domain separator this package owns (slice brief
6
+ * `S4-workflow-build-deploy-certification.md` sections 5 and 6.2; DEC-097
7
+ * section 7's `github-pages` row).
8
+ *
9
+ * @module
10
+ */
11
+
12
+ import { createRequire } from 'node:module';
13
+
14
+ /**
15
+ * This adapter's installed package version, read from its own `package.json`
16
+ * rather than restated by hand: DEC-097 section 3 requires the capability
17
+ * document's `adapter.adapterVersion` to byte-equal the locked package
18
+ * version, and the only value that can never drift from what a lock records
19
+ * for this package is the version the package manifest itself declares.
20
+ */
21
+ export const ADAPTER_VERSION = /** @type {string} */ (
22
+ /** @type {{version: string}} */ (
23
+ createRequire(import.meta.url)('../package.json')
24
+ ).version
25
+ );
26
+
27
+ /**
28
+ * The reserved artifact-relative coordinate the public generation marker is
29
+ * staged at (brief section 5). Freeze rejects an artifact route colliding
30
+ * with it; this adapter adds it to the deterministic Pages carrier.
31
+ */
32
+ export const GENERATION_MARKER_PATH = '.well-known/gala-generation.json';
33
+
34
+ /**
35
+ * The exact eleven accepted `GET /repos/{owner}/{repo}/pages/deployments/{id}`
36
+ * status values (brief section 6.2). Anything else is unknown and can never
37
+ * release the destination fence.
38
+ */
39
+ export const PAGES_DEPLOYMENT_STATUSES = Object.freeze([
40
+ 'deployment_in_progress',
41
+ 'syncing_files',
42
+ 'finished_file_sync',
43
+ 'updating_pages',
44
+ 'purging_cdn',
45
+ 'deployment_cancelled',
46
+ 'deployment_failed',
47
+ 'deployment_content_failed',
48
+ 'deployment_attempt_error',
49
+ 'deployment_lost',
50
+ 'succeed',
51
+ ]);
52
+
53
+ /**
54
+ * Temporary statuses: polling continues and the fence stays held.
55
+ * `deployment_attempt_error` is temporary because GitHub retries it
56
+ * automatically (brief section 6.2).
57
+ */
58
+ export const TEMPORARY_STATUSES = Object.freeze([
59
+ 'deployment_in_progress',
60
+ 'syncing_files',
61
+ 'finished_file_sync',
62
+ 'updating_pages',
63
+ 'purging_cdn',
64
+ 'deployment_attempt_error',
65
+ ]);
66
+
67
+ /** Terminal failure statuses: the deployment can never later succeed. */
68
+ export const TERMINAL_FAILURE_STATUSES = Object.freeze([
69
+ 'deployment_cancelled',
70
+ 'deployment_failed',
71
+ 'deployment_content_failed',
72
+ 'deployment_lost',
73
+ ]);
74
+
75
+ /** The single success status. */
76
+ export const SUCCESS_STATUS = 'succeed';
77
+
78
+ /**
79
+ * The exact poll schedule in seconds: `5, 8, 12, 18, 27, 30`, then `30`
80
+ * repeatedly while the fixed budget permits (brief section 6.2).
81
+ */
82
+ export const POLL_SCHEDULE_SECONDS = Object.freeze([5, 8, 12, 18, 27, 30]);
83
+
84
+ /** The repeated tail wait, in seconds, once the schedule is exhausted. */
85
+ export const POLL_TAIL_SECONDS = 30;
86
+
87
+ /** Fixed activation-detection polling budget, in seconds. */
88
+ export const POLL_BUDGET_SECONDS = 1500;
89
+
90
+ /** Hard ceiling on the deterministic Pages carrier, in bytes. */
91
+ export const MAXIMUM_PAGES_CARRIER_BYTES = 1073741824;
92
+
93
+ /** Domain separator: `adapter-capability:2.0.0.capabilityDigest`. */
94
+ export const DOMAIN_ADAPTER_CAPABILITY = 'GALA-ADAPTER-CAPABILITY-V2\0';
95
+
96
+ /** Domain separator shared with the template's artifact-manifest projection. */
97
+ export const DOMAIN_ARTIFACT = 'GALA-ARTIFACT-V2 ';
98
+
99
+ /** Domain separator: this adapter's own identity digest. */
100
+ export const DOMAIN_ADAPTER_IDENTITY = 'GALA-PAGES-ADAPTER-IDENTITY-V2\0';
101
+
102
+ /** Domain separator: the `pagesBuildVersion` projection (brief section 6.2). */
103
+ export const DOMAIN_PAGES_BUILD_VERSION = 'GALA-PAGES-BUILD-VERSION-V2\0';
104
+
105
+ /** Domain separator: the physical Pages destination mutation key. */
106
+ export const DOMAIN_PAGES_DESTINATION = 'GALA-PAGES-DESTINATION-V2\0';
107
+
108
+ /** Domain separator: the stage token projection. */
109
+ export const DOMAIN_PAGES_STAGE_TOKEN = 'GALA-PAGES-STAGE-TOKEN-V2\0';
110
+
111
+ /** Domain separator: the frozen provider request-template catalog. */
112
+ export const DOMAIN_PAGES_REQUEST_CATALOG = 'GALA-PAGES-REQUEST-CATALOG-V2\0';
113
+
114
+ /** Domain separator: the frozen provider response-profile catalog. */
115
+ export const DOMAIN_PAGES_RESPONSE_CATALOG = 'GALA-PAGES-RESPONSE-CATALOG-V2\0';
116
+
117
+ /** Domain separator: the provider compatibility evidence record. */
118
+ export const DOMAIN_PAGES_COMPATIBILITY = 'GALA-PAGES-COMPATIBILITY-V2\0';
119
+
120
+ /** Domain separator: the TLS profile record. */
121
+ export const DOMAIN_PAGES_TLS_PROFILE = 'GALA-PAGES-TLS-PROFILE-V2\0';
122
+
123
+ /** Domain separator: the credential-egress profile record. */
124
+ export const DOMAIN_PAGES_CREDENTIAL_EGRESS =
125
+ 'GALA-PAGES-CREDENTIAL-EGRESS-V2\0';
126
+
127
+ /** Domain separator: an intervening run attempt's no-authority tombstone. */
128
+ export const DOMAIN_PAGES_NO_AUTHORITY_RUN_ATTEMPT =
129
+ 'GALA-PAGES-NO-AUTHORITY-RUN-ATTEMPT-V2\0';
130
+
131
+ /** Domain separator: the run-attempt gap proof record. */
132
+ export const DOMAIN_PAGES_RUN_ATTEMPT_GAP_PROOF =
133
+ 'GALA-PAGES-RUN-ATTEMPT-GAP-PROOF-V2\0';
134
+
135
+ /** Domain separator: the `pagesReconciliationRecovery` record. */
136
+ export const DOMAIN_PAGES_RECONCILIATION_RECOVERY =
137
+ 'GALA-PAGES-RECONCILIATION-RECOVERY-V2\0';
138
+
139
+ /**
140
+ * The two admitted `destinationMutationAuthority.mode` values (DEC-097
141
+ * section 6.2). `normal` forbids every `pages-recovery-*` call.
142
+ */
143
+ export const NORMAL_MODE = 'normal';
144
+
145
+ /** The recovery mode that admits the two `pages-recovery-*` call classes. */
146
+ export const RECOVERY_MODE = 'pages-reconciliation-recovery';
147
+
148
+ /** The two admitted authority modes. */
149
+ export const AUTHORITY_MODES = Object.freeze([NORMAL_MODE, RECOVERY_MODE]);
150
+
151
+ /**
152
+ * Bounded budget, in seconds, for the complete recovery-prior
153
+ * status/poll/cancel/poll sequence. Recovery authorization budgets this in
154
+ * addition to the ordinary fresh carrier/create/current poll sequence.
155
+ */
156
+ export const RECOVERY_POLL_BUDGET_SECONDS = 300;
@@ -0,0 +1,333 @@
1
+ /**
2
+ * The Pages deployment call sequence: the `pagesBuildVersion` projection,
3
+ * the exact `gala-pages-create-deployment-jcs-v2` request entity, the single
4
+ * create call, and the bounded poll loop over the exact eleven accepted
5
+ * statuses (DEC-097 sections 6.2 and 7).
6
+ *
7
+ * The create body is the one place either credential is allowed to meet the
8
+ * other's destination, so both directions are enforced here: the OIDC token
9
+ * goes only into the body and never into a header, evidence, digest, output
10
+ * or thrown message, and the GitHub token goes only into the `authorization`
11
+ * header and never into the body.
12
+ *
13
+ * @module
14
+ */
15
+
16
+ import { canonicalizeJson, domainDigest } from '@rathnasgala2/adapter-protocol';
17
+
18
+ import {
19
+ DOMAIN_PAGES_BUILD_VERSION,
20
+ POLL_BUDGET_SECONDS,
21
+ POLL_SCHEDULE_SECONDS,
22
+ POLL_TAIL_SECONDS,
23
+ PAGES_DEPLOYMENT_STATUSES,
24
+ SUCCESS_STATUS,
25
+ TEMPORARY_STATUSES,
26
+ TERMINAL_FAILURE_STATUSES,
27
+ } from './constants.js';
28
+ import { verifyPagesOidcToken } from './oidc.js';
29
+ import { assertFreeOfSecrets, withRedactedFailures } from './redaction.js';
30
+ import { CREATE_BODY_PROFILE } from './request-catalog.js';
31
+ import { buildPollUrl, callProvider, expectedStatusUrl } from './rest.js';
32
+
33
+ /** The exact three member names of the create request entity, in JCS order. */
34
+ export const CREATE_BODY_MEMBERS = Object.freeze([
35
+ 'artifact_id',
36
+ 'oidc_token',
37
+ 'pages_build_version',
38
+ ]);
39
+
40
+ /** The inclusive upper bound on `artifact_id` (exact JSON/JCS identity). */
41
+ export const MAXIMUM_ARTIFACT_ID = 9007199254740991;
42
+
43
+ const BUILD_VERSION_PATTERN = /^[0-9a-f]{40}$/u;
44
+
45
+ /**
46
+ * Derive the `pagesBuildVersion`: the first 40 lowercase hex characters of
47
+ * the domain-separated repository/operation/attempt/run/artifact/generation
48
+ * projection (DEC-097 section 6.2). `pagesDeploymentId` must equal it
49
+ * exactly.
50
+ *
51
+ * @param {{
52
+ * destinationKey: string,
53
+ * operationId: string,
54
+ * attemptId: string,
55
+ * runId?: string,
56
+ * runAttempt?: number,
57
+ * artifactId: string,
58
+ * artifactDigest: string,
59
+ * generationId: string
60
+ * }} projection the closed projection inputs
61
+ * @returns {string} the 40-character lowercase hexadecimal build version
62
+ */
63
+ export function derivePagesBuildVersion(projection) {
64
+ return domainDigest(DOMAIN_PAGES_BUILD_VERSION, {
65
+ destinationKey: projection.destinationKey,
66
+ operationId: projection.operationId,
67
+ attemptId: projection.attemptId,
68
+ runId: projection.runId ?? null,
69
+ runAttempt: projection.runAttempt ?? null,
70
+ artifactId: projection.artifactId,
71
+ artifactDigest: projection.artifactDigest,
72
+ generationId: projection.generationId,
73
+ })
74
+ .slice('sha256:'.length)
75
+ .slice(0, 40);
76
+ }
77
+
78
+ /**
79
+ * Refuse a create-body text that is not the exact compact JCS of the three
80
+ * admitted members. Exported so a fixture can prove a duplicated, extra,
81
+ * missing or reordered member is refused without reaching a provider.
82
+ *
83
+ * @param {string} bodyText the serialized request entity
84
+ * @returns {void}
85
+ */
86
+ export function assertCanonicalCreateBody(bodyText) {
87
+ /** @type {unknown} */
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(bodyText);
91
+ } catch {
92
+ throw new Error(
93
+ 'PAGES_CREATE_BODY_NONCANONICAL: the create request entity is not JSON',
94
+ );
95
+ }
96
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
97
+ throw new Error(
98
+ 'PAGES_CREATE_BODY_NONCANONICAL: the create request entity is not a JSON object',
99
+ );
100
+ }
101
+ const keys = Object.keys(/** @type {Record<string, unknown>} */ (parsed));
102
+ if (
103
+ keys.length !== CREATE_BODY_MEMBERS.length ||
104
+ !CREATE_BODY_MEMBERS.every((name, index) => keys[index] === name)
105
+ ) {
106
+ throw new Error(
107
+ `PAGES_CREATE_BODY_NONCANONICAL: the create request entity must have exactly the three members ${CREATE_BODY_MEMBERS.join(', ')} in JCS order`,
108
+ );
109
+ }
110
+ if (canonicalizeJson(parsed) !== bodyText) {
111
+ throw new Error(
112
+ 'PAGES_CREATE_BODY_NONCANONICAL: the create request entity is not compact RFC 8785 JCS',
113
+ );
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Build the exact `gala-pages-create-deployment-jcs-v2` request entity.
119
+ *
120
+ * @param {{
121
+ * pagesArtifactId: string | number,
122
+ * pagesBuildVersion: string,
123
+ * oidcToken: string,
124
+ * githubToken: string
125
+ * }} input the body inputs
126
+ * @returns {Readonly<{bodyText: string, byteCount: number, artifactId: number}>}
127
+ * the canonical body text and its non-secret measurements
128
+ */
129
+ export function buildCreateDeploymentBody(input) {
130
+ const artifactId = Number(input.pagesArtifactId);
131
+ if (
132
+ !Number.isSafeInteger(artifactId) ||
133
+ artifactId < 1 ||
134
+ artifactId > MAXIMUM_ARTIFACT_ID ||
135
+ String(artifactId) !== String(input.pagesArtifactId)
136
+ ) {
137
+ throw new Error(
138
+ `PAGES_ARTIFACT_ID_INVALID: ${JSON.stringify(String(input.pagesArtifactId))} is not a JSON integer in 1..${MAXIMUM_ARTIFACT_ID}; a string artifact id, a non-integer and an unsafe integer are all refused`,
139
+ );
140
+ }
141
+ if (!BUILD_VERSION_PATTERN.test(input.pagesBuildVersion)) {
142
+ throw new Error(
143
+ 'PAGES_BUILD_VERSION_INVALID: pages_build_version must be exactly 40 lowercase hexadecimal characters',
144
+ );
145
+ }
146
+ if (typeof input.oidcToken !== 'string' || input.oidcToken === '') {
147
+ throw new Error(
148
+ 'PAGES_OIDC_TOKEN_REQUIRED: oidc_token is a mandatory member of the create request entity',
149
+ );
150
+ }
151
+ const bodyText = canonicalizeJson({
152
+ artifact_id: artifactId,
153
+ oidc_token: input.oidcToken,
154
+ pages_build_version: input.pagesBuildVersion,
155
+ });
156
+ assertCanonicalCreateBody(bodyText);
157
+ if (bodyText.includes(input.githubToken)) {
158
+ throw new Error(
159
+ 'PAGES_SECRET_LEAK_DETECTED: the GitHub token reached the create request body; DEC-097 section 7 forbids it',
160
+ );
161
+ }
162
+ return Object.freeze({
163
+ bodyText,
164
+ byteCount: Buffer.byteLength(bodyText, 'utf8'),
165
+ artifactId,
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Issue the single create-deployment call and return the closed provider
171
+ * identity projection. `createResponseStatusUrl` is carried only on the
172
+ * `createResponseObserved: true` branch and only when it equals the exact
173
+ * expected shape; it is evidence, never a URL this adapter follows.
174
+ *
175
+ * The OIDC token is verified against its expected bindings and then placed
176
+ * only in the body. Neither credential can reach the returned evidence: the
177
+ * whole projection is scanned before it is returned, and every failure
178
+ * message is scrubbed.
179
+ *
180
+ * @param {import('./rest.js').RestContext} context the bound REST context
181
+ * @param {{
182
+ * pagesArtifactId: string | number,
183
+ * pagesBuildVersion: string,
184
+ * oidcToken: string,
185
+ * oidcExpectation: import('./oidc.js').PagesOidcExpectation,
186
+ * stage?: string
187
+ * }} input the create inputs
188
+ * @returns {Promise<Readonly<Record<string, unknown>>>} the provider identity
189
+ */
190
+ export async function createDeployment(context, input) {
191
+ const secrets = [input.oidcToken, context.token];
192
+ return withRedactedFailures(secrets, async () => {
193
+ const oidcEvidence = verifyPagesOidcToken(
194
+ input.oidcToken,
195
+ input.oidcExpectation,
196
+ );
197
+ const body = buildCreateDeploymentBody({
198
+ pagesArtifactId: input.pagesArtifactId,
199
+ pagesBuildVersion: input.pagesBuildVersion,
200
+ oidcToken: input.oidcToken,
201
+ githubToken: context.token,
202
+ });
203
+
204
+ const response = await callProvider(
205
+ context,
206
+ input.stage ?? 'activate',
207
+ 'pages-create-deployment',
208
+ { bodyText: body.bodyText, acceptStatuses: [200, 201] },
209
+ );
210
+
211
+ const parsed = /** @type {Record<string, unknown>} */ (response.body ?? {});
212
+ const observedId = parsed.id === undefined ? undefined : String(parsed.id);
213
+ if (observedId !== input.pagesBuildVersion) {
214
+ throw new Error(
215
+ `PAGES_DEPLOYMENT_ID_MISMATCH: provider returned deployment id ${JSON.stringify(observedId)} for requested pages_build_version ${JSON.stringify(input.pagesBuildVersion)}`,
216
+ );
217
+ }
218
+
219
+ const expected = expectedStatusUrl(context, input.pagesBuildVersion);
220
+ const observedStatusUrl =
221
+ typeof parsed.status_url === 'string' && parsed.status_url === expected
222
+ ? expected
223
+ : undefined;
224
+ const pollUrl = buildPollUrl(context, input.pagesBuildVersion);
225
+ if (observedStatusUrl === pollUrl) {
226
+ throw new Error(
227
+ 'PAGES_STATUS_URL_EQUALS_POLL_URL: DEC-097 section 7 forbids equality between the create response status_url and the independently constructed poll URL',
228
+ );
229
+ }
230
+
231
+ // Retained evidence records only the body profile, its byte count and
232
+ // the non-secret artifact ID and build version (DEC-097 section 7).
233
+ const identity = Object.freeze({
234
+ createResponseObserved: true,
235
+ pagesDeploymentId: input.pagesBuildVersion,
236
+ ...(observedStatusUrl === undefined
237
+ ? {}
238
+ : { createResponseStatusUrl: observedStatusUrl }),
239
+ pollUrl,
240
+ requestBodyProfile: CREATE_BODY_PROFILE,
241
+ requestBodyByteCount: body.byteCount,
242
+ pagesArtifactId: String(body.artifactId),
243
+ pagesBuildVersion: input.pagesBuildVersion,
244
+ oidcCredentialSourceProfile: oidcEvidence.profile,
245
+ oidcSubjectForm: oidcEvidence.subjectForm,
246
+ oidcIssuerSignatureVerified: oidcEvidence.issuerSignatureVerified,
247
+ });
248
+ assertFreeOfSecrets(identity, secrets, 'create-deployment evidence');
249
+ return identity;
250
+ });
251
+ }
252
+
253
+ /**
254
+ * Poll one deployment to a terminal state under the fixed budget, waiting
255
+ * exactly `5, 8, 12, 18, 27, 30` seconds and then repeating `30`.
256
+ *
257
+ * @param {import('./rest.js').RestContext} context the bound REST context
258
+ * @param {string} pagesDeploymentId the deployment identity, used only to
259
+ * name the deployment in diagnostics; the request target's segment is
260
+ * selected statically by the call class from the bound context
261
+ * @param {{
262
+ * sleep?: (seconds: number) => Promise<void>,
263
+ * budgetSeconds?: number,
264
+ * stage?: string
265
+ * }} options polling controls; `sleep` is injectable so a test proves the
266
+ * schedule without spending it in wall-clock time
267
+ * @returns {Promise<{
268
+ * status: string,
269
+ * succeeded: boolean,
270
+ * observedStatuses: string[],
271
+ * waitedSeconds: number[]
272
+ * }>} the terminal observation
273
+ */
274
+ export async function pollDeployment(context, pagesDeploymentId, options) {
275
+ const sleep = options.sleep ?? defaultSleep;
276
+ const budget = options.budgetSeconds ?? POLL_BUDGET_SECONDS;
277
+ const stage = options.stage ?? 'activate';
278
+ /** @type {string[]} */
279
+ const observedStatuses = [];
280
+ /** @type {number[]} */
281
+ const waitedSeconds = [];
282
+ let spent = 0;
283
+
284
+ for (let attempt = 0; ; attempt += 1) {
285
+ const response = await callProvider(
286
+ context,
287
+ stage,
288
+ 'pages-deployment-status',
289
+ { acceptStatuses: [200] },
290
+ );
291
+ const status = String(
292
+ /** @type {Record<string, unknown>} */ (response.body ?? {}).status,
293
+ );
294
+ observedStatuses.push(status);
295
+
296
+ if (!PAGES_DEPLOYMENT_STATUSES.includes(status)) {
297
+ throw new Error(
298
+ `PAGES_DEPLOYMENT_STATUS_UNKNOWN: ${JSON.stringify(status)} is outside the eleven accepted statuses; the destination fence stays held`,
299
+ );
300
+ }
301
+ if (status === SUCCESS_STATUS) {
302
+ return { status, succeeded: true, observedStatuses, waitedSeconds };
303
+ }
304
+ if (TERMINAL_FAILURE_STATUSES.includes(status)) {
305
+ return { status, succeeded: false, observedStatuses, waitedSeconds };
306
+ }
307
+ if (!TEMPORARY_STATUSES.includes(status)) {
308
+ throw new Error(
309
+ `PAGES_DEPLOYMENT_STATUS_UNPARTITIONED: ${JSON.stringify(status)} is neither temporary nor terminal`,
310
+ );
311
+ }
312
+
313
+ const wait = POLL_SCHEDULE_SECONDS[attempt] ?? POLL_TAIL_SECONDS;
314
+ if (spent + wait > budget) {
315
+ throw new Error(
316
+ `PAGES_DEPLOYMENT_POLL_BUDGET_EXHAUSTED: ${pagesDeploymentId} was still ${status} after ${spent} seconds; the outcome is ambiguous and the destination fence stays held`,
317
+ );
318
+ }
319
+ spent += wait;
320
+ waitedSeconds.push(wait);
321
+ await sleep(wait);
322
+ }
323
+ }
324
+
325
+ /**
326
+ * @param {number} seconds seconds to wait
327
+ * @returns {Promise<void>} resolves after the wait
328
+ */
329
+ function defaultSleep(seconds) {
330
+ return new Promise((resolve) => {
331
+ setTimeout(resolve, seconds * 1000).unref();
332
+ });
333
+ }