@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/index.js ADDED
@@ -0,0 +1,977 @@
1
+ /**
2
+ * `@rathnasgala2/adapter-github-pages`: the managed GitHub Pages deployment
3
+ * adapter (S4-T04; DEC-097 section 6.2 and section 7's `github-pages` row).
4
+ *
5
+ * What it does: builds one deterministic gzip/ustar Pages carrier from the
6
+ * frozen artifact plus the reserved public generation marker, hands that
7
+ * carrier to the caller-supplied Actions-artifact publisher, creates exactly
8
+ * one Pages deployment through the raw REST API using a caller-supplied
9
+ * installation token, polls the deployment API to a terminal status, and
10
+ * verifies the result through credential-free public reads of the activated
11
+ * origin.
12
+ *
13
+ * What it deliberately does not do, because DEC-097 forbids it: it never
14
+ * invokes the opaque `actions/deploy-pages` action, never mutates a branch,
15
+ * never assumes a source commit, never mints or refreshes a token, never
16
+ * follows a provider-supplied `status_url`, and never claims complete
17
+ * deployed inventory. Its declared `concurrency` is `none` and its declared
18
+ * `rollback` is `reupload`, because that is what GitHub Pages actually
19
+ * offers; see `README.md` for the full boundary list.
20
+ *
21
+ * @module
22
+ */
23
+
24
+ import {
25
+ fenceDisagrees,
26
+ fenceFor,
27
+ requireGenerationFence,
28
+ sha256Hex,
29
+ } from '@rathnasgala2/adapter-protocol';
30
+
31
+ import {
32
+ computeArtifactDigest,
33
+ digestEntries,
34
+ projectEntry,
35
+ } from './artifact-projection.js';
36
+ import { describeCapabilities as buildCapabilities } from './capability.js';
37
+ import {
38
+ AUTHORITY_MODES,
39
+ GENERATION_MARKER_PATH,
40
+ MAXIMUM_PAGES_CARRIER_BYTES,
41
+ NORMAL_MODE,
42
+ RECOVERY_MODE,
43
+ } from './constants.js';
44
+ import {
45
+ createDeployment,
46
+ derivePagesBuildVersion,
47
+ pollDeployment,
48
+ } from './deployment.js';
49
+ import { decodeCarrier, encodeCarrier } from './carrier.js';
50
+ import { buildValidatedMarker, parsePublicMarker } from './marker.js';
51
+ import { readPublic } from './public-read.js';
52
+ import { requireOidcExpectation } from './oidc.js';
53
+ import {
54
+ resolvePriorAttempt,
55
+ validateReconciliationRecovery,
56
+ } from './recovery.js';
57
+ import { GITHUB_API_ORIGIN, buildRequestTemplates } from './request-catalog.js';
58
+ import { bindIdentity, callProvider } from './rest.js';
59
+ import { destinationKey, stateFor } from './store.js';
60
+
61
+ export {
62
+ EXPECT_NOTHING_SERVED,
63
+ fenceFor,
64
+ generateUuidV7,
65
+ } from '@rathnasgala2/adapter-protocol';
66
+ export { computeArtifactDigest } from './artifact-projection.js';
67
+ export { decodeCarrier, encodeCarrier } from './carrier.js';
68
+ export { GENERATION_MARKER_PATH } from './constants.js';
69
+ export { forgetDestination } from './store.js';
70
+ export { ADAPTER_VERSION, NORMAL_MODE, RECOVERY_MODE } from './constants.js';
71
+ export {
72
+ PAGES_OIDC_ENVIRONMENT,
73
+ PAGES_OIDC_ISSUER,
74
+ PAGES_OIDC_PROFILE,
75
+ buildSubjectForms,
76
+ verifyPagesOidcToken,
77
+ } from './oidc.js';
78
+ export {
79
+ GAP_PROOF_PROFILE,
80
+ NO_AUTHORITY_STATE,
81
+ RECOVERY_RECORD_PROFILE,
82
+ buildInterveningAttempts,
83
+ buildRunAttemptGapProof,
84
+ computeGapProofDigest,
85
+ computeInterveningAttemptDigest,
86
+ computeRecoveryDigest,
87
+ sealRecoveryRecord,
88
+ validateReconciliationRecovery,
89
+ validateRunAttemptGapProof,
90
+ } from './recovery.js';
91
+ export {
92
+ CALL_CLASS_BINDING,
93
+ GITHUB_API_ORIGIN,
94
+ PAGES_CALL_PLAN,
95
+ REQUEST_TEMPLATE_PROFILE,
96
+ buildRequestTemplates,
97
+ callClassIdBinding,
98
+ requireTemplate,
99
+ } from './request-catalog.js';
100
+
101
+ /**
102
+ * @typedef {Readonly<{
103
+ * owner: string,
104
+ * repository: string,
105
+ * repositoryId?: string | number,
106
+ * repositoryOwnerId?: string | number,
107
+ * apiOrigin?: string,
108
+ * oidcToken?: string,
109
+ * oidcClaims?: import('./oidc.js').PagesOidcExpectation,
110
+ * publicBaseUrl: string,
111
+ * token: string,
112
+ * publishCarrier: (input: {bytes: Buffer, generationId: string, carrierDigest: string}) => Promise<{pagesArtifactId: string | number, artifactDigest?: string, byteCount?: number}>,
113
+ * fetch?: typeof globalThis.fetch,
114
+ * publicFetch?: typeof globalThis.fetch,
115
+ * sleep?: (seconds: number) => Promise<void>,
116
+ * runId?: string,
117
+ * runAttempt?: number
118
+ * }>} PagesDestination
119
+ */
120
+
121
+ /**
122
+ * @typedef {Readonly<{path: string, bytes: Buffer}>} StagedFile
123
+ */
124
+
125
+ const DEFAULT_API_ORIGIN = GITHUB_API_ORIGIN;
126
+
127
+ /**
128
+ * Validate a destination and derive the bound REST context.
129
+ *
130
+ * @param {PagesDestination} destination the caller-supplied destination
131
+ * @returns {import('./rest.js').RestContext} the bound REST context
132
+ */
133
+ function restContextFor(destination) {
134
+ for (const field of /** @type {const} */ ([
135
+ 'owner',
136
+ 'repository',
137
+ 'publicBaseUrl',
138
+ 'token',
139
+ ])) {
140
+ if (typeof destination?.[field] !== 'string' || destination[field] === '') {
141
+ throw new TypeError(
142
+ `destination.${field} (non-empty string) is required by adapter-github-pages`,
143
+ );
144
+ }
145
+ }
146
+ const apiOrigin = destination.apiOrigin ?? DEFAULT_API_ORIGIN;
147
+ if (!apiOrigin.startsWith('https://')) {
148
+ throw new TypeError(
149
+ 'destination.apiOrigin must be an https origin; adapter-github-pages refuses a cleartext control plane',
150
+ );
151
+ }
152
+ if (!destination.publicBaseUrl.startsWith('https://')) {
153
+ throw new TypeError('destination.publicBaseUrl must be an https origin');
154
+ }
155
+ if (typeof destination.publishCarrier !== 'function') {
156
+ throw new TypeError(
157
+ 'destination.publishCarrier is required: adapter-github-pages never uploads an Actions artifact itself (DEC-097 section 2.3 makes direct carrier upload workflow-owned)',
158
+ );
159
+ }
160
+ return Object.freeze({
161
+ apiOrigin,
162
+ owner: destination.owner,
163
+ repository: destination.repository,
164
+ token: destination.token,
165
+ ...(destination.fetch === undefined ? {} : { fetch: destination.fetch }),
166
+ requestTemplates: buildRequestTemplates(apiOrigin),
167
+ });
168
+ }
169
+
170
+ /**
171
+ * @param {PagesDestination} destination the destination
172
+ * @returns {import('./public-read.js').PublicContext} the public context
173
+ */
174
+ function publicContextFor(destination) {
175
+ const injected = destination.publicFetch ?? destination.fetch;
176
+ return Object.freeze({
177
+ publicBaseUrl: destination.publicBaseUrl,
178
+ ...(injected === undefined ? {} : { fetch: injected }),
179
+ });
180
+ }
181
+
182
+ /**
183
+ * `describeCapabilities`: the exact `github-pages` capability row.
184
+ *
185
+ * @param {PagesDestination} destination the bound destination
186
+ * @returns {Promise<Readonly<Record<string, unknown>>>} the declaration
187
+ */
188
+ export async function describeCapabilities(destination) {
189
+ const context = restContextFor(destination);
190
+ return Promise.resolve(buildCapabilities({ apiOrigin: context.apiOrigin }));
191
+ }
192
+
193
+ /**
194
+ * Read the generation identity the public origin currently serves, or
195
+ * `null` when nothing has ever been activated.
196
+ *
197
+ * @param {PagesDestination} destination the bound destination
198
+ * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[]}>}
199
+ * the observed public generation
200
+ */
201
+ async function readServedGeneration(destination) {
202
+ const observation = await readPublic(
203
+ publicContextFor(destination),
204
+ GENERATION_MARKER_PATH,
205
+ );
206
+ if (observation.status === 404) {
207
+ return { generationId: null, artifactDigest: null, findings: [] };
208
+ }
209
+ if (observation.status !== 200 || observation.bytes === null) {
210
+ return {
211
+ generationId: null,
212
+ artifactDigest: null,
213
+ findings: [
214
+ `public generation marker read returned HTTP ${observation.status}; the served generation is unknown, not absent`,
215
+ ],
216
+ };
217
+ }
218
+ const parsed = parsePublicMarker(observation.bytes);
219
+ if (parsed.marker === null) {
220
+ return {
221
+ generationId: null,
222
+ artifactDigest: null,
223
+ findings: parsed.findings,
224
+ };
225
+ }
226
+ return {
227
+ generationId: String(parsed.marker.generationId),
228
+ artifactDigest: String(parsed.marker.artifactDigest),
229
+ findings: [],
230
+ };
231
+ }
232
+
233
+ /**
234
+ * `inspectDestination`: report the currently served generation from a live
235
+ * public read plus the provider's own site state, never from memory.
236
+ *
237
+ * @param {PagesDestination} destination the bound destination
238
+ * @returns {Promise<Readonly<{
239
+ * currentGenerationId: string | null,
240
+ * retainedHistory: readonly Readonly<Record<string, unknown>>[],
241
+ * releaseGenerationsOnDisk: readonly string[],
242
+ * providerSiteObserved: boolean,
243
+ * findings: readonly string[]
244
+ * }>>} the inspection result
245
+ */
246
+ export async function inspectDestination(destination) {
247
+ const context = restContextFor(destination);
248
+ const served = await readServedGeneration(destination);
249
+
250
+ let providerSiteObserved = false;
251
+ /** @type {string[]} */
252
+ const findings = [...served.findings];
253
+ try {
254
+ const site = await callProvider(context, 'inspect', 'pages-site', {
255
+ acceptStatuses: [200, 404],
256
+ });
257
+ providerSiteObserved = site.status === 200;
258
+ if (site.status === 404) {
259
+ findings.push('GitHub Pages is not enabled for this repository');
260
+ }
261
+ } catch (error) {
262
+ findings.push(
263
+ `provider site read failed: ${/** @type {Error} */ (error).message}`,
264
+ );
265
+ }
266
+
267
+ const state = stateFor(destination);
268
+ return Object.freeze({
269
+ currentGenerationId: served.generationId,
270
+ retainedHistory: Object.freeze([...state.activations.values()]),
271
+ releaseGenerationsOnDisk: Object.freeze(
272
+ served.generationId === null ? [] : [served.generationId],
273
+ ),
274
+ providerSiteObserved,
275
+ findings: Object.freeze(findings),
276
+ });
277
+ }
278
+
279
+ /**
280
+ * `preflight`: check every declared route against the portable path rules
281
+ * and the reserved marker coordinate, and report the currently served
282
+ * generation for fencing. No provider mutation of any kind occurs here.
283
+ *
284
+ * @param {{
285
+ * destination: PagesDestination,
286
+ * entries: readonly {path: string}[],
287
+ * expectedGenerationId?: string
288
+ * }} input the preflight input
289
+ * @returns {Promise<Readonly<{
290
+ * verdict: 'proceed' | 'refuse',
291
+ * observedGenerationId: string | null,
292
+ * findings: readonly string[]
293
+ * }>>} the preflight result
294
+ */
295
+ export async function preflight(input) {
296
+ restContextFor(input.destination);
297
+ /** @type {string[]} */
298
+ const findings = [];
299
+ const seen = new Set();
300
+ for (const entry of input.entries) {
301
+ if (entry.path === GENERATION_MARKER_PATH) {
302
+ findings.push(
303
+ `${entry.path}: collides with the reserved public-generation-marker coordinate`,
304
+ );
305
+ }
306
+ if (entry.path.startsWith('/') || entry.path.includes('\\')) {
307
+ findings.push(`${entry.path}: is not a portable relative POSIX path`);
308
+ }
309
+ if (
310
+ entry.path
311
+ .split('/')
312
+ .some(
313
+ (segment) => segment === '..' || segment === '.' || segment === '',
314
+ )
315
+ ) {
316
+ findings.push(`${entry.path}: contains an empty or dot path segment`);
317
+ }
318
+ if (Buffer.byteLength(entry.path, 'utf8') > 255) {
319
+ findings.push(`${entry.path}: exceeds the 255-byte path ceiling`);
320
+ }
321
+ if (seen.has(entry.path)) {
322
+ findings.push(`${entry.path}: is declared more than once`);
323
+ }
324
+ seen.add(entry.path);
325
+ }
326
+
327
+ const served = await readServedGeneration(input.destination);
328
+ findings.push(...served.findings);
329
+ if (
330
+ input.expectedGenerationId !== undefined &&
331
+ served.generationId !== null &&
332
+ input.expectedGenerationId !== served.generationId
333
+ ) {
334
+ findings.push(
335
+ `expected generation ${JSON.stringify(input.expectedGenerationId)} disagrees with the served generation ${JSON.stringify(served.generationId)}`,
336
+ );
337
+ }
338
+
339
+ return Object.freeze({
340
+ verdict: findings.length === 0 ? 'proceed' : 'refuse',
341
+ observedGenerationId: served.generationId,
342
+ findings: Object.freeze(findings),
343
+ });
344
+ }
345
+
346
+ /**
347
+ * `stage`: build the deterministic Pages carrier and publish it through the
348
+ * caller-supplied Actions-artifact publisher. Nothing public changes here —
349
+ * `staging: private` is literal: the carrier is an Actions artifact that no
350
+ * public origin serves.
351
+ *
352
+ * @param {{
353
+ * destination: PagesDestination,
354
+ * operationId: string,
355
+ * attemptId: string,
356
+ * idempotencyKey: string,
357
+ * generationId: string,
358
+ * artifactId: string,
359
+ * artifactDigest: string,
360
+ * files: readonly StagedFile[]
361
+ * }} input the stage input
362
+ * @returns {Promise<Readonly<{
363
+ * stageToken: string,
364
+ * stagedPath: string,
365
+ * fileCount: number,
366
+ * byteCount: string,
367
+ * carrierDigest: string,
368
+ * pagesArtifactId: string,
369
+ * idempotent: boolean
370
+ * }>>} the stage result
371
+ */
372
+ export async function stage(input) {
373
+ restContextFor(input.destination);
374
+ const state = stateFor(input.destination);
375
+
376
+ for (const existing of state.stages.values()) {
377
+ if (existing.idempotencyKey !== input.idempotencyKey) {
378
+ continue;
379
+ }
380
+ if (existing.artifactDigest !== input.artifactDigest) {
381
+ throw new Error(
382
+ `IDEMPOTENCY_KEY_REUSE_CONFLICT: idempotency key ${JSON.stringify(input.idempotencyKey)} was already used for a different artifact digest`,
383
+ );
384
+ }
385
+ return Object.freeze({
386
+ stageToken: existing.stageToken,
387
+ stagedPath: `actions-artifact:${existing.pagesArtifactId}`,
388
+ fileCount: existing.entryPaths.length,
389
+ byteCount: String(existing.carrierByteCount),
390
+ carrierDigest: existing.carrierDigest,
391
+ pagesArtifactId: existing.pagesArtifactId,
392
+ idempotent: true,
393
+ });
394
+ }
395
+
396
+ const marker = buildValidatedMarker({
397
+ artifactId: input.artifactId,
398
+ artifactDigest: input.artifactDigest,
399
+ generationId: input.generationId,
400
+ });
401
+ const carrierFiles = [
402
+ ...input.files.map((file) => ({ path: file.path, bytes: file.bytes })),
403
+ {
404
+ path: GENERATION_MARKER_PATH,
405
+ bytes: Buffer.from(JSON.stringify(marker), 'utf8'),
406
+ },
407
+ ];
408
+ const carrierBytes = encodeCarrier(carrierFiles);
409
+ if (carrierBytes.byteLength > MAXIMUM_PAGES_CARRIER_BYTES) {
410
+ throw new Error(
411
+ `PAGES_CARRIER_TOO_LARGE: ${carrierBytes.byteLength} bytes exceed the ${MAXIMUM_PAGES_CARRIER_BYTES}-byte Pages artifact ceiling`,
412
+ );
413
+ }
414
+ const carrierDigest = sha256Hex(carrierBytes);
415
+
416
+ const published = await input.destination.publishCarrier({
417
+ bytes: carrierBytes,
418
+ generationId: input.generationId,
419
+ carrierDigest,
420
+ });
421
+ const pagesArtifactId = String(published.pagesArtifactId);
422
+ if (
423
+ published.artifactDigest !== undefined &&
424
+ published.artifactDigest !== carrierDigest
425
+ ) {
426
+ throw new Error(
427
+ `PAGES_CARRIER_HANDOFF_MISMATCH: the artifact publisher reported digest ${published.artifactDigest} for a carrier whose bytes digest to ${carrierDigest}`,
428
+ );
429
+ }
430
+
431
+ const stageToken = carrierDigest.slice(
432
+ 'sha256:'.length,
433
+ 'sha256:'.length + 32,
434
+ );
435
+ state.stages.set(stageToken, {
436
+ stageToken,
437
+ operationId: input.operationId,
438
+ attemptId: input.attemptId,
439
+ idempotencyKey: input.idempotencyKey,
440
+ generationId: input.generationId,
441
+ artifactId: input.artifactId,
442
+ artifactDigest: input.artifactDigest,
443
+ entryPaths: Object.freeze(input.files.map((file) => file.path)),
444
+ carrierBytes,
445
+ carrierDigest,
446
+ pagesArtifactId,
447
+ pagesArtifactDigest: carrierDigest,
448
+ carrierByteCount: carrierBytes.byteLength,
449
+ });
450
+
451
+ return Object.freeze({
452
+ stageToken,
453
+ stagedPath: `actions-artifact:${pagesArtifactId}`,
454
+ fileCount: input.files.length,
455
+ byteCount: String(carrierBytes.byteLength),
456
+ carrierDigest,
457
+ pagesArtifactId,
458
+ idempotent: false,
459
+ });
460
+ }
461
+
462
+ /**
463
+ * Resolve the prior attempt of an unresolved Pages fence before any current
464
+ * carrier is uploaded or created. Exposed separately so the deploy script
465
+ * can run the DEC-097 section 6.2 precheck *before* it calls `stage` (this
466
+ * package's carrier upload happens in `stage`); `activate` runs it again,
467
+ * ahead of any current create, when it is given recovery inputs.
468
+ *
469
+ * @param {{
470
+ * destination: PagesDestination,
471
+ * pagesRecovery: Readonly<Record<string, unknown>>
472
+ * }} input the recovery input
473
+ * @returns {Promise<import('./recovery.js').PriorAttemptObservation>} the
474
+ * truthful prior-attempt observation
475
+ */
476
+ export async function recoverPriorAttempt(input) {
477
+ const context = restContextFor(input.destination);
478
+ const recovery = validateReconciliationRecovery(input.pagesRecovery, {
479
+ repositoryId: input.destination.repositoryId ?? '0',
480
+ });
481
+ return resolvePriorAttempt(
482
+ bindIdentity(context, {
483
+ mode: RECOVERY_MODE,
484
+ priorPagesBuildVersion: String(recovery.priorPagesBuildVersion),
485
+ }),
486
+ input.destination.sleep === undefined
487
+ ? {}
488
+ : { sleep: input.destination.sleep },
489
+ );
490
+ }
491
+
492
+ /**
493
+ * Resolve and validate the mandatory Pages OIDC credential inputs.
494
+ *
495
+ * This adapter never mints the token: DEC-097 section 7 places the one
496
+ * acquisition in the workflow's `deploy-github-pages` job, which reads it
497
+ * from `ACTIONS_ID_TOKEN_REQUEST_URL` and passes it in here.
498
+ *
499
+ * @param {PagesDestination} destination the bound destination
500
+ * @param {{pagesOidcToken?: string, pagesOidcClaims?: unknown}} input the
501
+ * activate input
502
+ * @returns {{
503
+ * token: string,
504
+ * expectation: import('./oidc.js').PagesOidcExpectation
505
+ * }} the validated credential inputs
506
+ */
507
+ function requirePagesOidc(destination, input) {
508
+ const token = input.pagesOidcToken ?? destination.oidcToken;
509
+ if (typeof token !== 'string' || token === '') {
510
+ throw new Error(
511
+ 'PAGES_OIDC_TOKEN_REQUIRED: oidc_token is a mandatory member of the create request entity (DEC-097 section 7). Supply it as input.pagesOidcToken or destination.oidcToken; this repository never mints a credential.',
512
+ );
513
+ }
514
+ const claims = requireOidcExpectation(
515
+ input.pagesOidcClaims ?? destination.oidcClaims,
516
+ );
517
+ if (
518
+ destination.repositoryId === undefined ||
519
+ destination.repositoryOwnerId === undefined
520
+ ) {
521
+ throw new Error(
522
+ 'PAGES_OIDC_EXPECTATION_INVALID: destination.repositoryId and destination.repositoryOwnerId are required so the two admitted subject forms can be recomputed from the verified claims',
523
+ );
524
+ }
525
+ return {
526
+ token,
527
+ expectation: /** @type {import('./oidc.js').PagesOidcExpectation} */ (
528
+ Object.freeze({
529
+ ...claims,
530
+ owner: destination.owner,
531
+ repository: destination.repository,
532
+ repositoryId: destination.repositoryId,
533
+ repositoryOwnerId: destination.repositoryOwnerId,
534
+ })
535
+ ),
536
+ };
537
+ }
538
+
539
+ /**
540
+ * `activate`: create exactly one Pages deployment for a staged carrier and
541
+ * poll it to a terminal status (`activation: provider-promotion`).
542
+ *
543
+ * `expectedCurrentGenerationId` is the adapter-protocol `2.1.0` fence:
544
+ * either a generation identity or the explicit `EXPECT_NOTHING_SERVED`
545
+ * sentinel. `null` and `undefined` are refused with
546
+ * `EXPECTED_GENERATION_FENCE_INVALID` (LOCAL-47) — there is no unfenced
547
+ * activation. The check itself is a read-then-compare performed immediately
548
+ * before the create call: honest best effort, not a provider fence, because
549
+ * GitHub Pages exposes no compare-and-set on activation, which is exactly
550
+ * why this adapter declares `concurrency: none`.
551
+ *
552
+ * In `pages-reconciliation-recovery` mode the prior attempt is resolved
553
+ * first, before any current create, per DEC-097 section 6.2.
554
+ *
555
+ * @param {{
556
+ * destination: PagesDestination,
557
+ * stageToken: string,
558
+ * generationId: string,
559
+ * expectedCurrentGenerationId: string,
560
+ * expectedArtifactDigest?: string,
561
+ * pagesOidcToken?: string,
562
+ * pagesOidcClaims?: import('./oidc.js').PagesOidcExpectation,
563
+ * mode?: string,
564
+ * pagesRecovery?: Readonly<Record<string, unknown>>,
565
+ * crashInjectionHook?: () => void | Promise<void>
566
+ * }} input the activate input; `crashInjectionHook`, when supplied (only
567
+ * ever by a conformance fixture), is awaited after the carrier is durably
568
+ * published but strictly before the create-deployment call
569
+ * @returns {Promise<Readonly<Record<string, unknown>>>} the decision
570
+ */
571
+ export async function activate(input) {
572
+ const baseContext = restContextFor(input.destination);
573
+ const state = stateFor(input.destination);
574
+ const fence = requireGenerationFence(
575
+ input.expectedCurrentGenerationId,
576
+ 'github-pages',
577
+ );
578
+ const mode = input.mode ?? NORMAL_MODE;
579
+ if (!AUTHORITY_MODES.includes(mode)) {
580
+ throw new Error(
581
+ `PAGES_AUTHORITY_MODE_INVALID: ${JSON.stringify(mode)} is not one of ${AUTHORITY_MODES.join(', ')}`,
582
+ );
583
+ }
584
+ if (mode === NORMAL_MODE && input.pagesRecovery !== undefined) {
585
+ throw new Error(
586
+ 'PAGES_RECOVERY_RECORD_FORBIDDEN: normal mode forbids pagesRecovery and every recovery-prior call',
587
+ );
588
+ }
589
+ const oidc = requirePagesOidc(input.destination, input);
590
+
591
+ const served = await readServedGeneration(input.destination);
592
+
593
+ /** @type {import('./recovery.js').PriorAttemptObservation | undefined} */
594
+ let priorObservation;
595
+ /** @type {Readonly<Record<string, unknown>> | undefined} */
596
+ let recovery;
597
+ if (mode === RECOVERY_MODE) {
598
+ recovery = validateReconciliationRecovery(input.pagesRecovery, {
599
+ repositoryId: input.destination.repositoryId ?? '0',
600
+ });
601
+ priorObservation = await resolvePriorAttempt(
602
+ bindIdentity(baseContext, {
603
+ mode: RECOVERY_MODE,
604
+ priorPagesBuildVersion: String(recovery.priorPagesBuildVersion),
605
+ }),
606
+ input.destination.sleep === undefined
607
+ ? {}
608
+ : { sleep: input.destination.sleep },
609
+ );
610
+ if (priorObservation.outcome === 'prior-succeeded') {
611
+ // The same operation's proposed generation was already selected: no
612
+ // new create is performed and the current fence terminalizes.
613
+ state.activations.set(input.generationId, {
614
+ generationId: input.generationId,
615
+ pagesDeploymentId: priorObservation.priorPagesBuildVersion,
616
+ certifiedAt: new Date().toISOString(),
617
+ entryPaths:
618
+ state.stages.get(input.stageToken)?.entryPaths ?? Object.freeze([]),
619
+ });
620
+ return Object.freeze({
621
+ decision: /** @type {'activate'} */ ('activate'),
622
+ mode,
623
+ generationId: input.generationId,
624
+ previousGenerationId: served.generationId,
625
+ idempotent: true,
626
+ terminalState: 'terminal-candidate',
627
+ pagesDeploymentId: priorObservation.priorPagesBuildVersion,
628
+ pagesRecoveryObservation: priorObservation,
629
+ });
630
+ }
631
+ if (priorObservation.outcome === 'reconciliation-required') {
632
+ return Object.freeze({
633
+ decision: /** @type {'reconcile'} */ ('reconcile'),
634
+ mode,
635
+ generationId: input.generationId,
636
+ previousGenerationId: served.generationId,
637
+ idempotent: false,
638
+ destinationChanged: /** @type {false} */ (false),
639
+ authorityState: 'reconciliation-required',
640
+ terminalState: 'reconciliation-required',
641
+ pagesRecoveryObservation: priorObservation,
642
+ });
643
+ }
644
+ }
645
+
646
+ if (served.generationId === input.generationId) {
647
+ return Object.freeze({
648
+ decision: /** @type {'activate'} */ ('activate'),
649
+ mode,
650
+ generationId: input.generationId,
651
+ previousGenerationId: served.generationId,
652
+ idempotent: true,
653
+ ...(priorObservation === undefined
654
+ ? {}
655
+ : { pagesRecoveryObservation: priorObservation }),
656
+ });
657
+ }
658
+ if (fenceDisagrees(fence, served.generationId)) {
659
+ // The create call has not been made, so this is the one reconcile
660
+ // decision that can honestly claim an unchanged destination.
661
+ return Object.freeze({
662
+ decision: /** @type {'reconcile'} */ ('reconcile'),
663
+ mode,
664
+ generationId: input.generationId,
665
+ previousGenerationId: served.generationId,
666
+ idempotent: false,
667
+ destinationChanged: /** @type {false} */ (false),
668
+ ...(priorObservation === undefined
669
+ ? {}
670
+ : { pagesRecoveryObservation: priorObservation }),
671
+ });
672
+ }
673
+
674
+ const record = state.stages.get(input.stageToken);
675
+ if (record === undefined) {
676
+ throw new Error(
677
+ `PAGES_STAGE_NOT_FOUND: stage token ${JSON.stringify(input.stageToken)} has no staged carrier in this run`,
678
+ );
679
+ }
680
+
681
+ if (input.expectedArtifactDigest !== undefined) {
682
+ // Recompute the digest from the carrier bytes that will actually be
683
+ // deployed, not from the file list the caller handed `stage`: a torn
684
+ // or tampered carrier must be caught here, before promotion.
685
+ const decoded = decodeCarrier(record.carrierBytes);
686
+ const recomputed = digestEntries(
687
+ decoded
688
+ .filter((file) => file.path !== GENERATION_MARKER_PATH)
689
+ .map((file) => projectEntry(file.path, file.bytes)),
690
+ );
691
+ if (recomputed !== input.expectedArtifactDigest) {
692
+ throw new Error(
693
+ `STAGE_INTEGRITY_MISMATCH: staged carrier digests to ${recomputed}, which disagrees with the expected artifact digest ${input.expectedArtifactDigest}; refusing to promote a partial or tampered stage`,
694
+ );
695
+ }
696
+ }
697
+
698
+ if (input.crashInjectionHook !== undefined) {
699
+ // The carrier is durably published to the provider's artifact store but
700
+ // no deployment has been created: exactly the boundary a real crash
701
+ // could land on. Only a conformance test ever reaches this branch.
702
+ await input.crashInjectionHook();
703
+ }
704
+
705
+ const pagesBuildVersion = derivePagesBuildVersion({
706
+ destinationKey: destinationKey(input.destination),
707
+ operationId: record.operationId,
708
+ attemptId: record.attemptId,
709
+ ...(input.destination.runId === undefined
710
+ ? {}
711
+ : { runId: input.destination.runId }),
712
+ ...(input.destination.runAttempt === undefined
713
+ ? {}
714
+ : { runAttempt: input.destination.runAttempt }),
715
+ artifactId: record.artifactId,
716
+ artifactDigest: record.artifactDigest,
717
+ generationId: input.generationId,
718
+ });
719
+
720
+ const context = bindIdentity(baseContext, {
721
+ mode,
722
+ pagesBuildVersion,
723
+ ...(recovery === undefined
724
+ ? {}
725
+ : { priorPagesBuildVersion: String(recovery.priorPagesBuildVersion) }),
726
+ });
727
+
728
+ state.inFlight.set(input.generationId, pagesBuildVersion);
729
+ const created = await createDeployment(context, {
730
+ pagesArtifactId: record.pagesArtifactId,
731
+ pagesBuildVersion,
732
+ oidcToken: oidc.token,
733
+ oidcExpectation: oidc.expectation,
734
+ });
735
+ const polled = await pollDeployment(context, pagesBuildVersion, {
736
+ ...(input.destination.sleep === undefined
737
+ ? {}
738
+ : { sleep: input.destination.sleep }),
739
+ });
740
+ state.inFlight.delete(input.generationId);
741
+
742
+ if (!polled.succeeded) {
743
+ throw new Error(
744
+ `PAGES_DEPLOYMENT_FAILED: deployment ${pagesBuildVersion} reached terminal status ${polled.status}`,
745
+ );
746
+ }
747
+
748
+ state.activations.set(input.generationId, {
749
+ generationId: input.generationId,
750
+ pagesDeploymentId: String(created.pagesDeploymentId),
751
+ certifiedAt: new Date().toISOString(),
752
+ // The route inventory this run deployed, retained independently of the
753
+ // staged carrier so `cleanupStaged` can discard the carrier without
754
+ // taking `observe`'s ability to verify the live generation with it.
755
+ entryPaths: record.entryPaths,
756
+ });
757
+
758
+ return Object.freeze({
759
+ decision: /** @type {'activate'} */ ('activate'),
760
+ mode,
761
+ generationId: input.generationId,
762
+ previousGenerationId: served.generationId,
763
+ idempotent: false,
764
+ pagesDeploymentId: String(created.pagesDeploymentId),
765
+ observedStatuses: Object.freeze(polled.observedStatuses),
766
+ providerIdentity: created,
767
+ ...(priorObservation === undefined
768
+ ? {}
769
+ : { pagesRecoveryObservation: priorObservation }),
770
+ });
771
+ }
772
+
773
+ /**
774
+ * `observe`: verify the activated generation through credential-free public
775
+ * reads. `providerInventoryAssurance` is `none`, so this verifies exactly
776
+ * the routes this run staged plus the marker; it never claims the deployed
777
+ * inventory is complete.
778
+ *
779
+ * @param {{
780
+ * destination: PagesDestination,
781
+ * generationId: string,
782
+ * expectedArtifactDigest: string
783
+ * }} input the observe input
784
+ * @returns {Promise<Readonly<{
785
+ * verified: boolean,
786
+ * observedArtifactDigest: string | null,
787
+ * currentGenerationId: string | null,
788
+ * markerValid: boolean,
789
+ * claimsCompleteInventory: false,
790
+ * findings: readonly string[]
791
+ * }>>} the observation result
792
+ */
793
+ export async function observe(input) {
794
+ restContextFor(input.destination);
795
+ const state = stateFor(input.destination);
796
+ const served = await readServedGeneration(input.destination);
797
+
798
+ /** @type {string[]} */
799
+ const findings = [...served.findings];
800
+ if (served.generationId !== input.generationId) {
801
+ findings.push(
802
+ `the public marker names generation ${JSON.stringify(served.generationId)}, not the observed generation ${JSON.stringify(input.generationId)}`,
803
+ );
804
+ }
805
+ const markerValid =
806
+ served.generationId === input.generationId &&
807
+ served.artifactDigest === input.expectedArtifactDigest;
808
+ if (!markerValid) {
809
+ findings.push(
810
+ 'the public generation marker is missing, invalid or disagrees with the expected identity',
811
+ );
812
+ }
813
+
814
+ const activation = state.activations.get(input.generationId);
815
+ const entryPaths =
816
+ activation?.entryPaths ??
817
+ [...state.stages.values()].find(
818
+ (candidate) => candidate.generationId === input.generationId,
819
+ )?.entryPaths;
820
+ /** @type {string | null} */
821
+ let observedArtifactDigest = null;
822
+ if (entryPaths === undefined) {
823
+ findings.push(
824
+ 'this run did not stage the observed generation, so its route inventory cannot be verified here',
825
+ );
826
+ } else {
827
+ const publicContext = publicContextFor(input.destination);
828
+ /** @type {import('./artifact-projection.js').ArtifactEntry[]} */
829
+ const entries = [];
830
+ for (const entryPath of entryPaths) {
831
+ const read = await readPublic(publicContext, entryPath);
832
+ if (read.status !== 200 || read.bytes === null) {
833
+ findings.push(`${entryPath}: public read returned HTTP ${read.status}`);
834
+ continue;
835
+ }
836
+ entries.push(projectEntry(entryPath, read.bytes));
837
+ }
838
+ observedArtifactDigest = digestEntries(entries);
839
+ if (observedArtifactDigest !== input.expectedArtifactDigest) {
840
+ findings.push(
841
+ `the publicly observed artifact digest ${observedArtifactDigest} disagrees with the expected ${input.expectedArtifactDigest}`,
842
+ );
843
+ }
844
+ }
845
+
846
+ return Object.freeze({
847
+ verified: findings.length === 0,
848
+ observedArtifactDigest,
849
+ currentGenerationId: served.generationId,
850
+ markerValid,
851
+ claimsCompleteInventory: /** @type {false} */ (false),
852
+ findings: Object.freeze(findings),
853
+ });
854
+ }
855
+
856
+ /**
857
+ * `cleanupStaged`: drop this operation's staged carrier from run-scoped
858
+ * memory and, when an abandoned generation is named, cancel its in-flight
859
+ * deployment through the cataloged cancel call. It never cancels or
860
+ * disturbs a generation that is currently served or retained.
861
+ *
862
+ * @param {{
863
+ * destination: PagesDestination,
864
+ * stageToken: string,
865
+ * generationId?: string
866
+ * }} input the cleanup input
867
+ * @returns {Promise<Readonly<{removed: boolean, cancelled: boolean}>>} whether
868
+ * staged state was removed and whether a deployment was cancelled
869
+ */
870
+ export async function cleanupStaged(input) {
871
+ const context = restContextFor(input.destination);
872
+ const state = stateFor(input.destination);
873
+ const removed = state.stages.delete(input.stageToken);
874
+
875
+ let cancelled = false;
876
+ if (input.generationId !== undefined) {
877
+ const served = await readServedGeneration(input.destination);
878
+ const isLive =
879
+ served.generationId === input.generationId ||
880
+ state.activations.has(input.generationId);
881
+ const pending = state.inFlight.get(input.generationId);
882
+ if (!isLive && pending !== undefined) {
883
+ await callProvider(
884
+ bindIdentity(context, { pagesBuildVersion: pending }),
885
+ 'cleanup-staged',
886
+ 'pages-cancel-deployment',
887
+ { acceptStatuses: [200, 202, 204, 404] },
888
+ );
889
+ state.inFlight.delete(input.generationId);
890
+ cancelled = true;
891
+ }
892
+ }
893
+
894
+ return Object.freeze({ removed: removed || cancelled, cancelled });
895
+ }
896
+
897
+ /**
898
+ * `rollback`: `rollback: reupload` semantics. GitHub Pages cannot natively
899
+ * re-promote a historical deployment, so a rollback stages a fresh carrier
900
+ * for the selected historical content under a *new* generation identity and
901
+ * activates it through the ordinary create/poll path.
902
+ *
903
+ * The historical bytes are not recoverable from the provider (Pages exposes
904
+ * no artifact read-back), so the caller supplies them through `files`. The
905
+ * run-scoped stage memory is used only when the target generation was
906
+ * staged by this same run.
907
+ *
908
+ * @param {{
909
+ * destination: PagesDestination,
910
+ * targetGenerationId: string,
911
+ * newGenerationId: string,
912
+ * newArtifactId: string,
913
+ * operationId: string,
914
+ * attemptId: string,
915
+ * idempotencyKey: string,
916
+ * files?: readonly StagedFile[],
917
+ * artifactDigest?: string,
918
+ * pagesOidcToken?: string,
919
+ * pagesOidcClaims?: import('./oidc.js').PagesOidcExpectation
920
+ * }} input the rollback input
921
+ * @returns {Promise<Readonly<Record<string, unknown>>>} the activation decision
922
+ */
923
+ export async function rollback(input) {
924
+ restContextFor(input.destination);
925
+ const state = stateFor(input.destination);
926
+
927
+ /** @type {readonly StagedFile[] | undefined} */
928
+ let files = input.files;
929
+ if (files === undefined) {
930
+ const record = [...state.stages.values()].find(
931
+ (candidate) => candidate.generationId === input.targetGenerationId,
932
+ );
933
+ if (record === undefined) {
934
+ throw new Error(
935
+ `ROLLBACK_INPUT_UNAVAILABLE: generation ${JSON.stringify(input.targetGenerationId)} was not staged by this run and GitHub Pages cannot read a historical artifact back; supply its bytes through "files"`,
936
+ );
937
+ }
938
+ files = decodeCarrier(record.carrierBytes).filter(
939
+ (file) => file.path !== GENERATION_MARKER_PATH,
940
+ );
941
+ }
942
+
943
+ const artifactDigest = input.artifactDigest ?? computeArtifactDigest(files);
944
+ const staged = await stage({
945
+ destination: input.destination,
946
+ operationId: input.operationId,
947
+ attemptId: input.attemptId,
948
+ idempotencyKey: input.idempotencyKey,
949
+ generationId: input.newGenerationId,
950
+ artifactId: input.newArtifactId,
951
+ artifactDigest,
952
+ files,
953
+ });
954
+ const served = await readServedGeneration(input.destination);
955
+ return activate({
956
+ destination: input.destination,
957
+ stageToken: staged.stageToken,
958
+ generationId: input.newGenerationId,
959
+ // `fenceFor` turns an observed "nothing is served" into the explicit
960
+ // EXPECT_NOTHING_SERVED sentinel rather than the ambiguous `null` that
961
+ // LOCAL-47 removed.
962
+ expectedCurrentGenerationId: fenceFor(served.generationId),
963
+ ...(input.pagesOidcToken === undefined
964
+ ? {}
965
+ : { pagesOidcToken: input.pagesOidcToken }),
966
+ ...(input.pagesOidcClaims === undefined
967
+ ? {}
968
+ : { pagesOidcClaims: input.pagesOidcClaims }),
969
+ });
970
+ }
971
+
972
+ /** This package's runtime status: fully implemented per S4-T04 (W4-11). */
973
+ export const PACKAGE_STATUS = Object.freeze({
974
+ name: '@rathnasgala2/adapter-github-pages',
975
+ implemented: true,
976
+ implementingTask: 'S4-T04',
977
+ });