@rathnasgala2/adapter-github-pages 0.1.0 → 0.1.2

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/marker.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * @module
11
11
  */
12
12
 
13
+ import { PagesAdapterError } from './errors.js';
13
14
  import { validateGalaDocument } from '@rathnasgala2/schemas';
14
15
 
15
16
  /** The exact schema identity every marker is validated against. */
@@ -34,8 +35,9 @@ export function buildValidatedMarker(identity) {
34
35
  });
35
36
  const validation = validateGalaDocument(MARKER_SCHEMA_ID, marker);
36
37
  if (!validation.valid) {
37
- throw new Error(
38
- `PAGES_MARKER_INVALID: ${JSON.stringify(validation.diagnostics)}`,
38
+ throw new PagesAdapterError(
39
+ `PAGES_MARKER_INVALID`,
40
+ `${JSON.stringify(validation.diagnostics)}`,
39
41
  );
40
42
  }
41
43
  return marker;
package/src/oidc.js CHANGED
@@ -10,8 +10,9 @@
10
10
  * environment job, which calls the GitHub-hosted runner URL from
11
11
  * `ACTIONS_ID_TOKEN_REQUEST_URL` exactly once with
12
12
  * `ACTIONS_ID_TOKEN_REQUEST_TOKEN` (that is what the job's `id-token: write`
13
- * permission is for), against an origin that must byte-equal one member of
14
- * the capability-authorized `githubActionsOidcOriginCatalog`.
13
+ * permission is for), against an origin that must match the closed
14
+ * capability-authorized `githubActionsOidcOriginCatalog` grammar (one
15
+ * lowercase label under `.actions.githubusercontent.com`).
15
16
  *
16
17
  * For this in-job, single-use credential the trust boundary is therefore
17
18
  * that exact catalog-authorized, DNS/TLS-authenticated runner token endpoint
@@ -36,13 +37,18 @@
36
37
  * from the separately verified `repository`, `repository_owner`,
37
38
  * `repository_id` and `repository_owner_id` claims, `environment`, and the
38
39
  * caller-supplied ref/SHA/run id/run attempt/`job_workflow_ref`/
39
- * `job_workflow_sha` expectations.
40
+ * `job_workflow_sha` expectations; and (PUB-L5, belt-and-braces) `exp`,
41
+ * `iat` and, when present, `nbf`, each within
42
+ * {@link PAGES_OIDC_CLOCK_SKEW_SECONDS} of the check's own clock -- Pages
43
+ * remains the authoritative check for token staleness, per the trust
44
+ * boundary above.
40
45
  *
41
46
  * No error raised here ever contains a token byte.
42
47
  *
43
48
  * @module
44
49
  */
45
50
 
51
+ import { PagesAdapterError } from './errors.js';
46
52
  /** The closed credential-source profile this module implements. */
47
53
  export const PAGES_OIDC_PROFILE = 'gala-pages-oidc-v2';
48
54
 
@@ -54,8 +60,22 @@ export const PAGES_OIDC_ENVIRONMENT = 'github-pages';
54
60
 
55
61
  /** Inclusive byte bounds on the compact JWT (DEC-097 section 7). */
56
62
  export const PAGES_OIDC_MINIMUM_BYTES = 1;
57
- /** Inclusive upper byte bound on the compact JWT. */
58
- export const PAGES_OIDC_MAXIMUM_BYTES = 8000;
63
+ /**
64
+ * Inclusive upper byte bound on the compact JWT: a memory bound with headroom,
65
+ * not an expected size. GitHub controls the actual token size.
66
+ */
67
+ export const PAGES_OIDC_MAXIMUM_BYTES = 32768;
68
+
69
+ /**
70
+ * PUB-L5: clock-skew tolerance, in seconds, for the belt-and-braces
71
+ * `exp`/`iat`/`nbf` checks below. GitHub Pages is the relying party that
72
+ * authoritatively rejects a stale or not-yet-valid token (this module's own
73
+ * header explains why that is the real trust boundary); this check exists
74
+ * only to fail closed earlier, with a clearer diagnostic, when it costs
75
+ * nothing to do so. 300 seconds is generous enough to absorb ordinary
76
+ * runner/host clock drift without weakening the check.
77
+ */
78
+ export const PAGES_OIDC_CLOCK_SKEW_SECONDS = 300;
59
79
 
60
80
  const BASE64URL_SEGMENT = /^[A-Za-z0-9_-]+$/u;
61
81
  const CANONICAL_DECIMAL = /^(?:0|[1-9][0-9]*)$/u;
@@ -83,7 +103,7 @@ const CANONICAL_DECIMAL = /^(?:0|[1-9][0-9]*)$/u;
83
103
  * @returns {never} never returns
84
104
  */
85
105
  function refuse(code, detail) {
86
- throw new Error(`${code}: ${detail}`);
106
+ throw new PagesAdapterError(code, detail);
87
107
  }
88
108
 
89
109
  /**
@@ -269,6 +289,66 @@ function requireCanonicalDecimal(value, name) {
269
289
  return /** @type {string} */ (text);
270
290
  }
271
291
 
292
+ /**
293
+ * Read one required numeric claim (a JWT `NumericDate`: seconds since the
294
+ * epoch, per RFC 7519 section 2).
295
+ *
296
+ * @param {Record<string, unknown>} payload the parsed payload
297
+ * @param {string} name the claim name
298
+ * @returns {number} the claim value
299
+ */
300
+ function requireNumericClaim(payload, name) {
301
+ const value = payload[name];
302
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
303
+ refuse(
304
+ 'PAGES_OIDC_CLAIM_MISSING',
305
+ `the ${JSON.stringify(name)} claim is absent or not a finite number`,
306
+ );
307
+ }
308
+ return /** @type {number} */ (value);
309
+ }
310
+
311
+ /**
312
+ * Belt-and-braces temporal validity: `exp` and `iat` are required and
313
+ * checked with a {@link PAGES_OIDC_CLOCK_SKEW_SECONDS} tolerance; `nbf` is
314
+ * checked the same way when present, since RFC 7519 makes it optional.
315
+ * Failing here is never the last word -- Pages independently rejects a
316
+ * stale token when it validates the signature -- but it produces a far
317
+ * clearer diagnostic than a Pages-side rejection, at zero verification cost.
318
+ *
319
+ * @param {Record<string, unknown>} payload the parsed payload
320
+ * @param {() => number} now the clock source, in epoch milliseconds
321
+ * (injectable so a test can pin "now" instead of racing the wall clock at
322
+ * the 300-second skew boundary; defaults to the real `Date.now`)
323
+ * @returns {void}
324
+ */
325
+ function requireTemporalValidity(payload, now) {
326
+ const nowSeconds = now() / 1000;
327
+ const expiresAt = requireNumericClaim(payload, 'exp');
328
+ if (nowSeconds > expiresAt + PAGES_OIDC_CLOCK_SKEW_SECONDS) {
329
+ refuse(
330
+ 'PAGES_OIDC_TOKEN_EXPIRED',
331
+ `the token's "exp" claim (${expiresAt}) is in the past beyond the ${PAGES_OIDC_CLOCK_SKEW_SECONDS}s skew tolerance`,
332
+ );
333
+ }
334
+ const issuedAt = requireNumericClaim(payload, 'iat');
335
+ if (issuedAt > nowSeconds + PAGES_OIDC_CLOCK_SKEW_SECONDS) {
336
+ refuse(
337
+ 'PAGES_OIDC_TOKEN_NOT_YET_VALID',
338
+ `the token's "iat" claim (${issuedAt}) is in the future beyond the ${PAGES_OIDC_CLOCK_SKEW_SECONDS}s skew tolerance`,
339
+ );
340
+ }
341
+ if (payload.nbf !== undefined) {
342
+ const notBefore = requireNumericClaim(payload, 'nbf');
343
+ if (notBefore > nowSeconds + PAGES_OIDC_CLOCK_SKEW_SECONDS) {
344
+ refuse(
345
+ 'PAGES_OIDC_TOKEN_NOT_YET_VALID',
346
+ `the token's "nbf" claim (${notBefore}) is in the future beyond the ${PAGES_OIDC_CLOCK_SKEW_SECONDS}s skew tolerance`,
347
+ );
348
+ }
349
+ }
350
+ }
351
+
272
352
  /**
273
353
  * Compare one claim against its expectation without echoing either value's
274
354
  * observed bytes where the claim could carry caller content.
@@ -281,9 +361,12 @@ function requireCanonicalDecimal(value, name) {
281
361
  */
282
362
  function requireClaimEquals(observed, expected, name, code) {
283
363
  if (observed !== expected) {
364
+ // Every claim compared here is a public identity string (ref, sha, run id,
365
+ // workflow path), never a credential, so the observed value is named: a
366
+ // production refusal that hides it costs a full publish cycle to diagnose.
284
367
  refuse(
285
368
  code,
286
- `the ${JSON.stringify(name)} claim does not byte-equal the expected ${JSON.stringify(expected)}`,
369
+ `the ${JSON.stringify(name)} claim ${JSON.stringify(String(observed))} does not byte-equal the expected ${JSON.stringify(expected)}`,
287
370
  );
288
371
  }
289
372
  }
@@ -315,6 +398,10 @@ export function buildSubjectForms(identity) {
315
398
  *
316
399
  * @param {unknown} token the caller-supplied compact JWT
317
400
  * @param {PagesOidcExpectation} expected the expected bindings
401
+ * @param {() => number} [now] the clock source used for the `exp`/`iat`/`nbf`
402
+ * checks, in epoch milliseconds. Defaults to `Date.now`; a test supplies a
403
+ * fixed function to check the {@link PAGES_OIDC_CLOCK_SKEW_SECONDS}
404
+ * boundary deterministically instead of racing the real clock.
318
405
  * @returns {Readonly<{
319
406
  * profile: string,
320
407
  * subjectForm: 'name' | 'identifier',
@@ -322,7 +409,7 @@ export function buildSubjectForms(identity) {
322
409
  * tokenByteCount: number
323
410
  * }>} non-secret evidence about the accepted token
324
411
  */
325
- export function verifyPagesOidcToken(token, expected) {
412
+ export function verifyPagesOidcToken(token, expected, now = Date.now) {
326
413
  if (typeof token !== 'string' || token === '') {
327
414
  refuse(
328
415
  'PAGES_OIDC_TOKEN_REQUIRED',
@@ -363,6 +450,8 @@ export function verifyPagesOidcToken(token, expected) {
363
450
  'JWT payload',
364
451
  );
365
452
 
453
+ requireTemporalValidity(payload, now);
454
+
366
455
  const repositoryOwner = requireStringClaim(payload, 'repository_owner');
367
456
  const repositoryClaim = requireStringClaim(payload, 'repository');
368
457
  const repositoryId = requireCanonicalDecimal(
@@ -6,9 +6,17 @@
6
6
  * profile declares zero credentials on the public origin), follow no
7
7
  * redirect, and read a bounded body.
8
8
  *
9
+ * A redirect is an answer, not a crash: the public base URL a site carries
10
+ * can name a host the site has since moved away from (a custom domain on the
11
+ * Pages site, a base URL still on `github.io`), and the origin then answers
12
+ * 301/302/307/308. The read classifies that as `status: 'redirect'` with the
13
+ * target host, so the adapter can refuse with `PAGES_PUBLIC_REDIRECT` instead
14
+ * of throwing out of the lifecycle.
15
+ *
9
16
  * @module
10
17
  */
11
18
 
19
+ import { PagesAdapterError } from './errors.js';
12
20
  /** Maximum bytes any single public read will accept. */
13
21
  export const MAXIMUM_PUBLIC_BODY_BYTES = 33554432;
14
22
 
@@ -33,29 +41,118 @@ export function publicUrlFor(publicBaseUrl, artifactRelativePath) {
33
41
  return `${base}/${artifactRelativePath}`;
34
42
  }
35
43
 
44
+ /**
45
+ * The `max-age` a `Cache-Control` header declares, in seconds.
46
+ *
47
+ * @param {string | null | undefined} cacheControl the header value
48
+ * @returns {number | null} the lifetime, `null` when none is declared
49
+ */
50
+ export function maxAgeSeconds(cacheControl) {
51
+ const match = /(?:^|[\s,])max-age=(\d+)/iu.exec(cacheControl ?? '');
52
+ return match === null ? null : Number(match[1]);
53
+ }
54
+
55
+ /** How long the redirect-target probe may take before the target is unknown. */
56
+ const REDIRECT_PROBE_TIMEOUT_MS = 10_000;
57
+
58
+ /**
59
+ * Whether a failed fetch failed because the origin answered with a redirect
60
+ * the fetch was told not to follow (`redirect: 'error'`). Undici reports it
61
+ * as a `TypeError('fetch failed')` whose `cause` is an `Error` with the exact
62
+ * message `unexpected redirect` (it carries no `code`); no other failure
63
+ * matches.
64
+ *
65
+ * @param {unknown} error the thrown value
66
+ * @returns {boolean} whether it is the refused-redirect failure
67
+ */
68
+ function isRefusedRedirect(error) {
69
+ return (
70
+ error instanceof TypeError &&
71
+ /** @type {{message?: unknown} | undefined} */ (error.cause)?.message ===
72
+ 'unexpected redirect'
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Learn where a refused redirect pointed. A fetch that refused to follow
78
+ * exposes no `Location`, so the same credential-free URL is asked once more
79
+ * with `redirect: 'manual'`, which hands back the 3xx response itself and
80
+ * still follows nothing. The probe is bounded to ten seconds and its body is
81
+ * cancelled unread. Any failure here, and any `Location` that is not an
82
+ * absolute-or-relative http(s) URL, leaves the target unknown; it never hides
83
+ * the redirect.
84
+ *
85
+ * @param {typeof globalThis.fetch} doFetch the fetch implementation
86
+ * @param {string} url the requested public URL
87
+ * @returns {Promise<{toHost: string | null, location: string | null}>} the
88
+ * redirect target, `null` where it could not be read
89
+ */
90
+ async function redirectTarget(doFetch, url) {
91
+ const unknown = { toHost: null, location: null };
92
+ try {
93
+ const response = await doFetch(url, {
94
+ method: 'GET',
95
+ redirect: 'manual',
96
+ cache: 'no-store',
97
+ signal: AbortSignal.timeout(REDIRECT_PROBE_TIMEOUT_MS),
98
+ });
99
+ await response.body?.cancel().catch(() => undefined);
100
+ const header = response.headers.get('location');
101
+ if (header === null) {
102
+ return unknown;
103
+ }
104
+ const target = new URL(header, url);
105
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') {
106
+ return unknown;
107
+ }
108
+ return { toHost: target.host, location: target.href };
109
+ } catch {
110
+ return unknown;
111
+ }
112
+ }
113
+
36
114
  /**
37
115
  * Read one public route.
38
116
  *
39
117
  * @param {PublicContext} context the public-origin context
40
118
  * @param {string} artifactRelativePath the artifact-relative POSIX path
41
- * @returns {Promise<{status: number, bytes: Buffer | null, etag: string | null}>}
42
- * the bounded observation; `bytes` is `null` for any non-`200` status
119
+ * @returns {Promise<{status: number | 'redirect', bytes: Buffer | null, etag: string | null, cacheControl?: string | null | undefined, toHost?: string | null, location?: string | null}>}
120
+ * the bounded observation; `bytes` is `null` for any non-`200` status. A
121
+ * `'redirect'` status carries the `toHost` and absolute `location` the
122
+ * origin named (`null` when it named none that could be read).
43
123
  */
44
124
  export async function readPublic(context, artifactRelativePath) {
45
125
  const doFetch = context.fetch ?? globalThis.fetch;
46
- const response = await doFetch(
47
- publicUrlFor(context.publicBaseUrl, artifactRelativePath),
48
- { method: 'GET', redirect: 'error', cache: 'no-store' },
49
- );
126
+ const url = publicUrlFor(context.publicBaseUrl, artifactRelativePath);
127
+ let response;
128
+ try {
129
+ response = await doFetch(url, {
130
+ method: 'GET',
131
+ redirect: 'error',
132
+ cache: 'no-store',
133
+ });
134
+ } catch (error) {
135
+ if (!isRefusedRedirect(error)) {
136
+ throw error;
137
+ }
138
+ return {
139
+ status: 'redirect',
140
+ bytes: null,
141
+ etag: null,
142
+ ...(await redirectTarget(doFetch, url)),
143
+ };
144
+ }
50
145
  const etag = response.headers.get('etag');
146
+ const cacheControl = response.headers.get('cache-control');
51
147
  if (response.status !== 200) {
52
- return { status: response.status, bytes: null, etag };
148
+ return { status: response.status, bytes: null, etag, cacheControl };
53
149
  }
54
150
  const bytes = Buffer.from(await response.arrayBuffer());
55
151
  if (bytes.byteLength > MAXIMUM_PUBLIC_BODY_BYTES) {
56
- throw new Error(
57
- `PAGES_PUBLIC_BODY_TOO_LARGE: ${artifactRelativePath} returned ${bytes.byteLength} bytes`,
152
+ throw new PagesAdapterError(
153
+ `PAGES_PUBLIC_BODY_TOO_LARGE`,
154
+ `${artifactRelativePath} returned ${bytes.byteLength} bytes`,
58
155
  );
59
156
  }
60
- return { status: 200, bytes, etag };
157
+ return { status: 200, bytes, etag, cacheControl };
61
158
  }
package/src/recovery.js CHANGED
@@ -25,6 +25,7 @@
25
25
  * @module
26
26
  */
27
27
 
28
+ import { PagesAdapterError } from './errors.js';
28
29
  import {
29
30
  canonicalizeJson,
30
31
  domainDigest,
@@ -79,7 +80,7 @@ const RFC3339 =
79
80
  * @returns {never} never returns
80
81
  */
81
82
  function refuse(code, detail) {
82
- throw new Error(`${code}: ${detail}`);
83
+ throw new PagesAdapterError(code, detail);
83
84
  }
84
85
 
85
86
  /**
@@ -535,8 +536,9 @@ export function validateReconciliationRecovery(recovery, binding) {
535
536
  */
536
537
  export function assertRecoveryModePermitted(mode) {
537
538
  if (mode !== RECOVERY_MODE) {
538
- throw new Error(
539
- `PAGES_RECOVERY_CALL_FORBIDDEN: the recovery-prior call plan is admitted only in ${RECOVERY_MODE} mode, not ${JSON.stringify(mode)}`,
539
+ refuse(
540
+ 'PAGES_RECOVERY_CALL_FORBIDDEN',
541
+ `the recovery-prior call plan is admitted only in ${RECOVERY_MODE} mode, not ${JSON.stringify(mode)}`,
540
542
  );
541
543
  }
542
544
  }
@@ -658,7 +660,7 @@ export async function resolvePriorAttempt(context, options = {}) {
658
660
  first.status,
659
661
  observed,
660
662
  0,
661
- 'the prior attempt reported a status outside the eleven accepted values; no current create is made',
663
+ 'the prior attempt reported a status outside the twelve accepted values; no current create is made',
662
664
  );
663
665
  }
664
666
  if (first.status === SUCCESS_STATUS) {
package/src/redaction.js CHANGED
@@ -16,8 +16,11 @@
16
16
  * @module
17
17
  */
18
18
 
19
- /** The placeholder a redacted secret is replaced with. */
20
- export const REDACTION_PLACEHOLDER = '[redacted]';
19
+ import { REDACTION_PLACEHOLDER } from '@rathnasgala2/adapter-protocol';
20
+
21
+ import { PagesAdapterError } from './errors.js';
22
+
23
+ export { REDACTION_PLACEHOLDER };
21
24
 
22
25
  /**
23
26
  * Replace every occurrence of every secret in one string.
@@ -81,8 +84,9 @@ export function assertFreeOfSecrets(value, secrets, label) {
81
84
  continue;
82
85
  }
83
86
  if (strings.some((candidate) => candidate.includes(secret))) {
84
- throw new Error(
85
- `PAGES_SECRET_LEAK_DETECTED: a credential's bytes reached ${label}; DEC-097 section 7 forbids it`,
87
+ throw new PagesAdapterError(
88
+ `PAGES_SECRET_LEAK_DETECTED`,
89
+ `a credential's bytes reached ${label}; DEC-097 section 7 forbids it`,
86
90
  );
87
91
  }
88
92
  }
@@ -23,6 +23,7 @@
23
23
  * @module
24
24
  */
25
25
 
26
+ import { PagesAdapterError } from './errors.js';
26
27
  import { canonicalizeJson } from '@rathnasgala2/adapter-protocol';
27
28
 
28
29
  /** The exact request-template profile this adapter declares. */
@@ -259,8 +260,9 @@ export function callClassIdBinding(stage, callClass) {
259
260
  (entry) => entry.stage === stage && entry.callClass === callClass,
260
261
  );
261
262
  if (row === undefined) {
262
- throw new Error(
263
- `PAGES_CALL_NOT_IN_CATALOG: (${JSON.stringify(stage)}, ${JSON.stringify(callClass)}) has no declared callClassBinding row`,
263
+ throw new PagesAdapterError(
264
+ `PAGES_CALL_NOT_IN_CATALOG`,
265
+ `(${JSON.stringify(stage)}, ${JSON.stringify(callClass)}) has no declared callClassBinding row`,
264
266
  );
265
267
  }
266
268
  return row;
@@ -401,8 +403,9 @@ export function requireTemplate(templates, stage, callClass) {
401
403
  (entry) => entry.stage === stage && entry.callClass === callClass,
402
404
  );
403
405
  if (found === undefined) {
404
- throw new Error(
405
- `PAGES_CALL_NOT_IN_CATALOG: (${JSON.stringify(stage)}, ${JSON.stringify(callClass)}) is not one of the nine admitted github-pages REST calls`,
406
+ throw new PagesAdapterError(
407
+ `PAGES_CALL_NOT_IN_CATALOG`,
408
+ `(${JSON.stringify(stage)}, ${JSON.stringify(callClass)}) is not one of the nine admitted github-pages REST calls`,
406
409
  );
407
410
  }
408
411
  return found;
package/src/rest.js CHANGED
@@ -27,7 +27,9 @@
27
27
  * @module
28
28
  */
29
29
 
30
+ import { PagesAdapterError } from './errors.js';
30
31
  import { NORMAL_MODE, RECOVERY_MODE } from './constants.js';
32
+ import { REDACTION_PLACEHOLDER } from './redaction.js';
31
33
  import { callClassIdBinding, requireTemplate } from './request-catalog.js';
32
34
 
33
35
  /** Maximum response body this client will read, in bytes. */
@@ -96,8 +98,9 @@ export function renderRequestTarget(template, values) {
96
98
  return template.replace(/\{([A-Za-z]+)\}/gu, (_match, key) => {
97
99
  const value = values[key];
98
100
  if (value === undefined) {
99
- throw new Error(
100
- `PAGES_REQUEST_TARGET_PLACEHOLDER_UNBOUND: ${JSON.stringify(key)} has no value`,
101
+ throw new PagesAdapterError(
102
+ `PAGES_REQUEST_TARGET_PLACEHOLDER_UNBOUND`,
103
+ `${JSON.stringify(key)} has no value`,
101
104
  );
102
105
  }
103
106
  return encodeURIComponent(value);
@@ -129,8 +132,9 @@ export function selectDeploymentId(context, template) {
129
132
  ? 'pagesRecovery.priorPagesBuildVersion'
130
133
  : "the intent's pagesBuildVersion";
131
134
  if (typeof value !== 'string' || !BUILD_VERSION_PATTERN.test(value)) {
132
- throw new Error(
133
- `PAGES_DEPLOYMENT_ID_SOURCE_UNAVAILABLE: ${String(template.stage)}/${String(template.callClass)} statically selects ${label}, which is absent or not 40 lowercase hex characters`,
135
+ throw new PagesAdapterError(
136
+ `PAGES_DEPLOYMENT_ID_SOURCE_UNAVAILABLE`,
137
+ `${String(template.stage)}/${String(template.callClass)} statically selects ${label}, which is absent or not 40 lowercase hex characters`,
134
138
  );
135
139
  }
136
140
  return value;
@@ -150,8 +154,9 @@ export function assertModePermitsCall(context, tmpl) {
150
154
  String(tmpl.callClass),
151
155
  ).recoveryOnly;
152
156
  if (recoveryOnly && mode !== RECOVERY_MODE) {
153
- throw new Error(
154
- `PAGES_RECOVERY_CALL_FORBIDDEN: ${String(tmpl.stage)}/${String(tmpl.callClass)} is admitted only in ${RECOVERY_MODE} mode; ${JSON.stringify(mode)} forbids every recovery-prior call`,
157
+ throw new PagesAdapterError(
158
+ `PAGES_RECOVERY_CALL_FORBIDDEN`,
159
+ `${String(tmpl.stage)}/${String(tmpl.callClass)} is admitted only in ${RECOVERY_MODE} mode; ${JSON.stringify(mode)} forbids every recovery-prior call`,
155
160
  );
156
161
  }
157
162
  }
@@ -193,26 +198,30 @@ export function buildHeaders(context, tmpl) {
193
198
  */
194
199
  export function assertRequestMatchesTemplate(tmpl, request) {
195
200
  if (request.method !== tmpl.method) {
196
- throw new Error(
197
- `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: method ${request.method} is not the cataloged ${String(tmpl.method)}`,
201
+ throw new PagesAdapterError(
202
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE`,
203
+ `method ${request.method} is not the cataloged ${String(tmpl.method)}`,
198
204
  );
199
205
  }
200
206
  if (!request.url.startsWith(`${String(tmpl.origin)}/`)) {
201
- throw new Error(
202
- `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: the request URL is not on the cataloged origin ${String(tmpl.origin)}`,
207
+ throw new PagesAdapterError(
208
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE`,
209
+ `the request URL is not on the cataloged origin ${String(tmpl.origin)}`,
203
210
  );
204
211
  }
205
212
  if (new URL(request.url).search !== '') {
206
- throw new Error(
207
- 'PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: canonicalQueryProfile is "none", so no query component is representable',
213
+ throw new PagesAdapterError(
214
+ 'PAGES_REQUEST_DISAGREES_WITH_TEMPLATE',
215
+ 'canonicalQueryProfile is "none", so no query component is representable',
208
216
  );
209
217
  }
210
218
  for (const fixed of /** @type {{name: string, value: string}[]} */ (
211
219
  tmpl.fixedHeaders
212
220
  )) {
213
221
  if (request.headers[fixed.name] !== fixed.value) {
214
- throw new Error(
215
- `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: fixed header ${JSON.stringify(fixed.name)} is missing or not the cataloged value`,
222
+ throw new PagesAdapterError(
223
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE`,
224
+ `fixed header ${JSON.stringify(fixed.name)} is missing or not the cataloged value`,
216
225
  );
217
226
  }
218
227
  }
@@ -225,19 +234,46 @@ export function assertRequestMatchesTemplate(tmpl, request) {
225
234
  const permitted = new Set([...fixedNames, ...credentialNames]);
226
235
  for (const name of Object.keys(request.headers)) {
227
236
  if (!permitted.has(name)) {
228
- throw new Error(
229
- `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: header ${JSON.stringify(name)} is not declared by this template`,
237
+ throw new PagesAdapterError(
238
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE`,
239
+ `header ${JSON.stringify(name)} is not declared by this template`,
230
240
  );
231
241
  }
232
242
  }
233
243
  const expectsBody = tmpl.requestBodyProfile !== 'empty';
234
244
  if (expectsBody !== (request.body !== undefined)) {
235
- throw new Error(
236
- `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: requestBodyProfile is ${JSON.stringify(String(tmpl.requestBodyProfile))} but the request ${request.body === undefined ? 'has no' : 'has a'} body`,
245
+ throw new PagesAdapterError(
246
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE`,
247
+ `requestBodyProfile is ${JSON.stringify(String(tmpl.requestBodyProfile))} but the request ${request.body === undefined ? 'has no' : 'has a'} body`,
237
248
  );
238
249
  }
239
250
  }
240
251
 
252
+ /**
253
+ * The provider's own JSON `message`, for the unexpected-status diagnostic: a
254
+ * bounded, single-line text with every 40+ character token-like run replaced,
255
+ * so a credential echoed by a provider can never reach a message.
256
+ *
257
+ * @param {Buffer} rawBody the raw response body
258
+ * @returns {string} `: provider message: <message>` or the empty string
259
+ */
260
+ export function providerMessageSuffix(rawBody) {
261
+ try {
262
+ const parsed = JSON.parse(rawBody.toString('utf8'));
263
+ const message = parsed === null ? undefined : parsed.message;
264
+ if (typeof message !== 'string' || message === '') {
265
+ return '';
266
+ }
267
+ const redacted = message
268
+ .replace(/[A-Za-z0-9_\-.~+/=]{40,}/gu, REDACTION_PLACEHOLDER)
269
+ .replace(/\s+/gu, ' ')
270
+ .slice(0, 200);
271
+ return `: provider message: ${redacted}`;
272
+ } catch {
273
+ return '';
274
+ }
275
+ }
276
+
241
277
  /**
242
278
  * Issue one cataloged provider call.
243
279
  *
@@ -267,8 +303,9 @@ export async function callProvider(context, stage, callClass, options) {
267
303
  tmpl.maximumRequestTargetBytes
268
304
  );
269
305
  if (Buffer.byteLength(requestTarget, 'utf8') > maximumTargetBytes) {
270
- throw new Error(
271
- `PAGES_REQUEST_TARGET_TOO_LONG: ${requestTarget.length} characters exceed the cataloged ${maximumTargetBytes}-byte ceiling`,
306
+ throw new PagesAdapterError(
307
+ `PAGES_REQUEST_TARGET_TOO_LONG`,
308
+ `${requestTarget.length} characters exceed the cataloged ${maximumTargetBytes}-byte ceiling`,
272
309
  );
273
310
  }
274
311
 
@@ -292,13 +329,15 @@ export async function callProvider(context, stage, callClass, options) {
292
329
 
293
330
  const rawBody = Buffer.from(await response.arrayBuffer());
294
331
  if (rawBody.byteLength > MAXIMUM_RESPONSE_BODY_BYTES) {
295
- throw new Error(
296
- `PAGES_RESPONSE_BODY_TOO_LARGE: ${rawBody.byteLength} bytes exceed the ${MAXIMUM_RESPONSE_BODY_BYTES}-byte ceiling`,
332
+ throw new PagesAdapterError(
333
+ `PAGES_RESPONSE_BODY_TOO_LARGE`,
334
+ `${rawBody.byteLength} bytes exceed the ${MAXIMUM_RESPONSE_BODY_BYTES}-byte ceiling`,
297
335
  );
298
336
  }
299
337
  if (!options.acceptStatuses.includes(response.status)) {
300
- throw new Error(
301
- `PAGES_PROVIDER_STATUS_UNEXPECTED: ${stage}/${callClass} returned HTTP ${response.status}, expected one of ${options.acceptStatuses.join(', ')}`,
338
+ throw new PagesAdapterError(
339
+ `PAGES_PROVIDER_STATUS_UNEXPECTED`,
340
+ `${stage}/${callClass} returned HTTP ${response.status}, expected one of ${options.acceptStatuses.join(', ')}${providerMessageSuffix(rawBody)}`,
302
341
  );
303
342
  }
304
343
 
package/src/store.js CHANGED
@@ -26,6 +26,7 @@ import { DOMAIN_PAGES_DESTINATION } from './constants.js';
26
26
  * artifactId: string,
27
27
  * artifactDigest: string,
28
28
  * entryPaths: readonly string[],
29
+ * entries: readonly import('./artifact-projection.js').ArtifactEntry[],
29
30
  * carrierBytes: Buffer,
30
31
  * carrierDigest: string,
31
32
  * pagesArtifactId: string,
@@ -37,7 +38,7 @@ import { DOMAIN_PAGES_DESTINATION } from './constants.js';
37
38
  /**
38
39
  * @typedef {{
39
40
  * stages: Map<string, StageRecord>,
40
- * activations: Map<string, {generationId: string, pagesDeploymentId: string, certifiedAt: string, entryPaths: readonly string[]}>,
41
+ * activations: Map<string, {generationId: string, pagesDeploymentId: string, certifiedAt: string, entryPaths: readonly string[], entries: readonly import('./artifact-projection.js').ArtifactEntry[]}>,
41
42
  * inFlight: Map<string, string>
42
43
  * }} DestinationState
43
44
  */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @typedef {Readonly<{path: string, byteLength: string, sha256: string}>} ArtifactEntry
3
+ */
4
+ /**
5
+ * Project one `{path, bytes}` pair onto its manifest entry.
6
+ *
7
+ * @param {string} entryPath the artifact-relative POSIX path
8
+ * @param {Buffer} bytes the file bytes
9
+ * @returns {ArtifactEntry} the projected entry
10
+ */
11
+ export function projectEntry(entryPath: string, bytes: Buffer): ArtifactEntry;
12
+ /**
13
+ * Order a projected entry list by UTF-8 path.
14
+ *
15
+ * @param {readonly ArtifactEntry[]} entries the unordered entries
16
+ * @returns {ArtifactEntry[]} a new, path-ordered array
17
+ */
18
+ export function orderEntries(entries: readonly ArtifactEntry[]): ArtifactEntry[];
19
+ /**
20
+ * Digest an already-projected, marker-excluding entry list.
21
+ *
22
+ * @param {readonly ArtifactEntry[]} entries the projected entries
23
+ * @returns {string} the `GALA-ARTIFACT-V2 ` artifact digest
24
+ */
25
+ export function digestEntries(entries: readonly ArtifactEntry[]): string;
26
+ /**
27
+ * Compute the artifact digest for a complete in-memory file set, excluding
28
+ * the reserved marker coordinate. Exported so a caller (the workflow's
29
+ * composition root, or a conformance fixture) can pass `stage` a truthful
30
+ * `artifactDigest` without restating the projection.
31
+ *
32
+ * PUB-M5: excluding the marker is this package's own contribution; the
33
+ * digest formula itself delegates to `@rathnasgala2/adapter-protocol`'s
34
+ * `computeArtifactDigest`, the single implementation every S2 destination
35
+ * adapter verifies against.
36
+ *
37
+ * @param {readonly Readonly<{path: string, bytes: Buffer}>[]} files the file set
38
+ * @returns {string} the artifact digest
39
+ */
40
+ export function computeArtifactDigest(files: readonly Readonly<{
41
+ path: string;
42
+ bytes: Buffer;
43
+ }>[]): string;
44
+ export type ArtifactEntry = Readonly<{
45
+ path: string;
46
+ byteLength: string;
47
+ sha256: string;
48
+ }>;