@rightkit/release 0.6.40 → 0.6.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +110 -11
  2. package/admission-files.mjs +40 -0
  3. package/admission-host.mjs +2 -1
  4. package/app-check.mjs +303 -16
  5. package/app-closure.mjs +6 -4
  6. package/bin/rightkit-gate.mjs +177 -32
  7. package/cargo-contract.mjs +17 -31
  8. package/cargo-license-notices.mjs +129 -19
  9. package/cargo-target-shim.mjs +14 -0
  10. package/carried-cargo.mjs +2 -4
  11. package/cli/right-release.mjs +24 -2
  12. package/cross-targets.mjs +24 -0
  13. package/deterministic-scans.mjs +150 -58
  14. package/development-signing.mjs +25 -2
  15. package/development.mjs +34 -1
  16. package/direct-release-command.mjs +154 -0
  17. package/disk-policy.mjs +16 -0
  18. package/feature-coverage.mjs +134 -0
  19. package/gate-coverage.mjs +38 -0
  20. package/gate-stages.mjs +1 -0
  21. package/ghsa-audit.mjs +95 -0
  22. package/install-app.mjs +33 -5
  23. package/install-channels.mjs +301 -0
  24. package/interactive-session-run.mjs +105 -0
  25. package/legal-contract.mjs +10 -1
  26. package/legion-freeze-consumer.mjs +241 -0
  27. package/linux-publish.mjs +136 -0
  28. package/local-publish.mjs +31 -8
  29. package/nsis-pack.mjs +95 -0
  30. package/nsis-upgrade-template.mjs +93 -0
  31. package/outdated-command.mjs +19 -0
  32. package/ownership-class-rules.mjs +32 -10
  33. package/ownership-mandatory-set.json +23 -0
  34. package/ownership-mandatory-set.mjs +66 -8
  35. package/package-recipe-targets.mjs +54 -19
  36. package/package.json +1 -1
  37. package/payload-root-install.mjs +123 -0
  38. package/plugin-delivery.mjs +141 -0
  39. package/prebuild-gates.mjs +8 -4
  40. package/preflight.mjs +6 -1
  41. package/provision-model-bundle.mjs +172 -0
  42. package/pub-upload.mjs +1 -1
  43. package/publish-local-npm.mjs +34 -9
  44. package/publish-retention.mjs +106 -0
  45. package/publish-update.mjs +15 -8
  46. package/qa-build-features.mjs +24 -15
  47. package/qa-contract.mjs +5 -6
  48. package/qa-control-scan.mjs +14 -0
  49. package/qa-web-pairing.mjs +76 -0
  50. package/r2-s3-multipart.mjs +190 -0
  51. package/r2-verified-upload.mjs +28 -16
  52. package/recipe-build.mjs +53 -3
  53. package/release-checks.mjs +53 -2
  54. package/release-config.mjs +8 -3
  55. package/release-invocation.mjs +12 -2
  56. package/release-pin-floor.mjs +44 -0
  57. package/release-qa-audit.mjs +18 -2
  58. package/release-qa-command.mjs +17 -1
  59. package/release-qa-policy.mjs +30 -3
  60. package/release-switch-cfg.mjs +271 -0
  61. package/release-switch-registry.json +60 -1
  62. package/release-switch-scan.mjs +398 -23
  63. package/release.mjs +97 -6
  64. package/render-views.mjs +141 -0
  65. package/rightkit-registry-resolver.mjs +1 -1
  66. package/rightkit-versions.json +140 -103
  67. package/runtime-artifact-manifest.mjs +9 -0
  68. package/runtime-manifest-refresh.mjs +88 -0
  69. package/rustright-stage.mjs +197 -0
  70. package/scan-digest.mjs +15 -9
  71. package/scan-tool-enrolment.mjs +1 -1
  72. package/security-policy.mjs +196 -0
  73. package/shell-contract.mjs +32 -0
  74. package/snapshot-broker.mjs +8 -1
  75. package/snapshot-check.mjs +58 -0
  76. package/snapshot-request.mjs +25 -2
  77. package/stage-commands.mjs +33 -4
  78. package/stage-receipt.mjs +115 -0
  79. package/stage-sidecar.mjs +188 -17
  80. package/stage-xcframework.mjs +118 -0
  81. package/suite-api.generated.mjs +16 -1
  82. package/unit-gate.mjs +14 -2
  83. package/upload-large.mjs +4 -4
  84. package/upload-release.mjs +6 -0
  85. package/win-package-recipe.mjs +26 -4
@@ -0,0 +1,106 @@
1
+ // Publishing leaves no copies behind (rightkit#763). Adrian, 2026-10-18: "trash them but we also need rightkit to not make those copies in the first place,
2
+ // kill the problem at the source". After a publish whose remote bytes were verified, `retainAfterPublish` reduces what right-release keeps under
3
+ // `<repo>/.right-release/{sealed,state}` to a bounded set, and refuses loudly when what is left is still too big:
4
+ //
5
+ // the published release kept whole (a release is published once per tier, patch and update, from the same sealed folder, so the second tier still needs
6
+ // its bytes); with `reducePublished: true` (a release known to be fully published) its sealed folder keeps only small evidence
7
+ // (every file at or under SMALL_FILE_BYTES) and every large file (installers, DMGs, zips, bundles) is deleted, because the verified
8
+ // remote objects are the copy of record. Its state folder (the verified marker, the receipts) is always kept whole.
9
+ // other releases the newest `maxReleases - 1` others (by modification time) are kept, and nothing older than `maxAgeDays`; the rest are deleted whole.
10
+ // a repository copy a `.git` anywhere in the first two levels of a release folder means a copy of a whole repository was made per release (the retired
11
+ // v*/w* flow, ~72 GB): that is refused, never cleaned silently.
12
+ // size if, after all of that, the two folders hold more than `maxBytes`, the run fails and names the largest entries.
13
+ // Nothing here copies, moves or uploads anything; it only deletes under the two folders. Defaults: 3 releases, 14 days, 2 GiB; the environment
14
+ // (RIGHT_RELEASE_RETAIN_RELEASES, RIGHT_RELEASE_RETAIN_DAYS, RIGHT_RELEASE_RETAIN_MAX_BYTES) can only TIGHTEN them (a larger value is refused).
15
+ import { existsSync, lstatSync, readdirSync, rmSync, statSync } from "node:fs";
16
+ import path from "node:path";
17
+
18
+ export const RETENTION_DEFAULTS = Object.freeze({ maxReleases: 3, maxAgeDays: 14, maxBytes: 2 * 1024 ** 3 });
19
+ export const SMALL_FILE_BYTES = 1024 * 1024;
20
+ const DAY_MS = 24 * 60 * 60 * 1000;
21
+ const FOLDERS = ["sealed", "state"];
22
+
23
+ export class RetentionError extends Error {
24
+ constructor(message, details = {}) { super(message); this.name = "RetentionError"; this.code = "RK_PUBLISH_RETENTION"; Object.assign(this, details); }
25
+ }
26
+ const fail = (message, details) => { throw new RetentionError(message, details); };
27
+
28
+ /** The limits in force: the defaults, tightened (never loosened) by the environment. */
29
+ export function retentionLimits(env = process.env) {
30
+ const read = (name, fallback) => {
31
+ const raw = env[name];
32
+ if (raw === undefined || raw === "") return fallback;
33
+ const value = Number(raw);
34
+ if (!Number.isInteger(value) || value < 1) fail(`${name} must be a positive integer`);
35
+ if (value > fallback) fail(`${name}=${value} is above the limit ${fallback}: the environment can tighten the retention bound, never loosen it`);
36
+ return value;
37
+ };
38
+ return {
39
+ maxReleases: read("RIGHT_RELEASE_RETAIN_RELEASES", RETENTION_DEFAULTS.maxReleases),
40
+ maxAgeDays: read("RIGHT_RELEASE_RETAIN_DAYS", RETENTION_DEFAULTS.maxAgeDays),
41
+ maxBytes: read("RIGHT_RELEASE_RETAIN_MAX_BYTES", RETENTION_DEFAULTS.maxBytes),
42
+ };
43
+ }
44
+
45
+ /** Total bytes of regular files under `target` (symlinks are counted as their own size and never followed). */
46
+ export function treeBytes(target, fs = { lstatSync, readdirSync }) {
47
+ const info = fs.lstatSync(target);
48
+ if (!info.isDirectory()) return info.size;
49
+ return fs.readdirSync(target).reduce((sum, name) => sum + treeBytes(path.join(target, name), fs), 0);
50
+ }
51
+
52
+ function filesUnder(dir, fs, prefix = "") {
53
+ return fs.readdirSync(path.join(dir, prefix)).flatMap((name) => {
54
+ const relative = prefix ? `${prefix}/${name}` : name;
55
+ const info = fs.lstatSync(path.join(dir, relative));
56
+ return info.isDirectory() ? filesUnder(dir, fs, relative) : [{ relative, size: info.size }];
57
+ });
58
+ }
59
+
60
+ function assertNoRepositoryCopy(dir, fs, depth = 2) {
61
+ if (depth < 0) return;
62
+ for (const name of fs.readdirSync(dir)) {
63
+ if (name === ".git") fail(`${dir} holds a .git: a copy of a whole repository was made for this release. That is the retired per-release copy flow; remove it by hand and find what made it (rightkit#763)`, { dir });
64
+ const full = path.join(dir, name);
65
+ if (fs.lstatSync(full).isDirectory()) assertNoRepositoryCopy(full, fs, depth - 1);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Apply the retention. `keep` is { releaseId } of the release just published (its folders are reduced, never removed whole).
71
+ * Returns { removed: [paths], keptReleases: [ids], bytes }. `dryRun` deletes nothing and returns what it would. Throws RetentionError on a repository copy or on size.
72
+ */
73
+ export function retainAfterPublish({ root, keep, limits = retentionLimits(), dryRun = false, reducePublished = false, now = Date.now(), fs = { existsSync, lstatSync, readdirSync, rmSync, statSync }, log = () => {} }) {
74
+ if (typeof keep?.releaseId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,159}$/.test(keep.releaseId)) fail("retainAfterPublish needs the id of the release just published");
75
+ const base = path.join(path.resolve(root), ".right-release");
76
+ const removed = [];
77
+ const drop = (target) => { removed.push(target); if (!dryRun) fs.rmSync(target, { recursive: true, force: true }); };
78
+ const releasesOf = (folder) => (fs.existsSync(path.join(base, folder)) ? fs.readdirSync(path.join(base, folder)).filter((name) => fs.lstatSync(path.join(base, folder, name)).isDirectory()) : []);
79
+ for (const folder of FOLDERS) for (const id of releasesOf(folder)) assertNoRepositoryCopy(path.join(base, folder, id), fs);
80
+
81
+ // The published release: sealed keeps small evidence only.
82
+ const sealedKeep = path.join(base, "sealed", keep.releaseId);
83
+ if (reducePublished && fs.existsSync(sealedKeep)) {
84
+ for (const file of filesUnder(sealedKeep, fs)) if (file.size > SMALL_FILE_BYTES) drop(path.join(sealedKeep, ...file.relative.split("/")));
85
+ }
86
+
87
+ // Every other release: newest (maxReleases - 1) and younger than maxAgeDays survive.
88
+ const ids = [...new Set(FOLDERS.flatMap(releasesOf))].filter((id) => id !== keep.releaseId);
89
+ const modified = (id) => Math.max(...FOLDERS.filter((folder) => fs.existsSync(path.join(base, folder, id))).map((folder) => fs.statSync(path.join(base, folder, id)).mtimeMs));
90
+ const ordered = ids.map((id) => ({ id, at: modified(id) })).sort((a, b) => b.at - a.at);
91
+ const kept = [];
92
+ for (const [index, item] of ordered.entries()) {
93
+ const old = now - item.at > limits.maxAgeDays * DAY_MS;
94
+ if (index >= limits.maxReleases - 1 || old) for (const folder of FOLDERS) { const target = path.join(base, folder, item.id); if (fs.existsSync(target)) drop(target); }
95
+ else kept.push(item.id);
96
+ }
97
+
98
+ // Size of what is left (a dry run subtracts what it would have removed only by not counting it: it measures the tree as it is, then says so).
99
+ const bytes = FOLDERS.reduce((sum, folder) => (fs.existsSync(path.join(base, folder)) ? sum + treeBytes(path.join(base, folder), fs) : sum), 0);
100
+ if (!dryRun && bytes > limits.maxBytes) {
101
+ const largest = FOLDERS.flatMap((folder) => releasesOf(folder).map((id) => ({ path: path.join(base, folder, id), bytes: treeBytes(path.join(base, folder, id), fs) }))).sort((a, b) => b.bytes - a.bytes).slice(0, 5);
102
+ fail(`after publishing ${keep.releaseId}, ${base} still holds ${bytes} bytes (limit ${limits.maxBytes}). Largest: ${largest.map((item) => `${item.path} (${item.bytes})`).join(", ")}`, { bytes, largest });
103
+ }
104
+ log(`right-release: retention ${dryRun ? "would remove" : "removed"} ${removed.length} path(s); ${kept.length + 1} release(s) kept; ${bytes} bytes left under ${base}`);
105
+ return { removed, keptReleases: [keep.releaseId, ...kept], bytes };
106
+ }
@@ -8,6 +8,7 @@ import { pruneReleaseObjects } from "./prune-r2.mjs";
8
8
  import { loadReleaseToken } from "./release-token.mjs";
9
9
  import { registerRightAppsRelease } from "./rightapps-register.mjs";
10
10
  import { recordPublishedVersion } from "./artifact-storage.mjs";
11
+ import { retainAfterPublish } from "./publish-retention.mjs";
11
12
  import { defaultReleaseConfigFile, importReleaseConfig } from "./release-config.mjs";
12
13
  import { assertPrimaryReleaseCheckout } from "./release-invocation.mjs";
13
14
  import { assertCleanSource } from "./source-gate.mjs";
@@ -188,8 +189,8 @@ if (githubLane) {
188
189
  } catch (error) {
189
190
  fail(error.message);
190
191
  }
191
- if (!dryRun) recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId });
192
- process.exit(0);
192
+ if (!dryRun) { recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId }); retainPublished(); }
193
+ process.exit(process.exitCode ?? 0);
193
194
  }
194
195
 
195
196
  if (tier === "patch") {
@@ -252,7 +253,7 @@ if (tier === "patch") {
252
253
  }
253
254
  }
254
255
  if (!artifacts.length) {
255
- console.log(`${dryRun ? "[dry-run] " : ""}NO patch updater artifacts; skipping patch manifest registration`);
256
+ console.log(`${dryRun ? "[dry-run] " : ""}NO patch updater artifacts; installers uploaded, patch manifest NOT registered: the registration route needs exactly one updater artifact and non-empty platforms, so an installer-only app has no client feed yet (README "Client update feed for private (R2) apps", #854)`);
256
257
  await pruneReleaseObjects({
257
258
  app: config.app,
258
259
  platform: platform === "mac" ? "mac" : "windows",
@@ -263,8 +264,8 @@ if (tier === "patch") {
263
264
  },
264
265
  retainPreviousVersions: installers.some((artifact) => artifact.versionedKey) ? 1 : 0,
265
266
  });
266
- if (!dryRun) recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId });
267
- process.exit(0);
267
+ if (!dryRun) { recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId }); retainPublished(); }
268
+ process.exit(process.exitCode ?? 0);
268
269
  }
269
270
  const version = config.version || target.updater.version;
270
271
  if (!version) fail(`${config.app} config must expose version or targets.${platform}.updater.version`);
@@ -302,8 +303,8 @@ if (tier === "patch") {
302
303
  },
303
304
  retainPreviousVersions: installers.some((artifact) => artifact.versionedKey) ? 1 : 0,
304
305
  });
305
- if (!dryRun) recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId });
306
- process.exit(0);
306
+ if (!dryRun) { recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId }); retainPublished(); }
307
+ process.exit(process.exitCode ?? 0);
307
308
  }
308
309
 
309
310
  const platforms = {};
@@ -372,7 +373,7 @@ await pruneReleaseObjects({
372
373
  private: [...registrations.keys()],
373
374
  },
374
375
  });
375
- if (!dryRun) recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId });
376
+ if (!dryRun) { recordPublishedVersion({ app: config.app, version: versionForStorage, platform, configPath, releaseId }); retainPublished(); }
376
377
 
377
378
  function fileMetadata(file) {
378
379
  const artifact = verifiedArtifact(file);
@@ -429,6 +430,12 @@ async function register(route, body) {
429
430
  }
430
431
  }
431
432
 
433
+ // After the remote bytes were verified and the version recorded: bound the sealed and state folders by count and age, loudly (rightkit#763).
434
+ function retainPublished() {
435
+ try { retainAfterPublish({ root: git(["rev-parse", "--show-toplevel"]), keep: { releaseId }, log: (line) => console.log(line) }); }
436
+ catch (error) { console.error(`publish-update: published, but ${error.message}`); process.exitCode = 1; }
437
+ }
438
+
432
439
  function fail(message) {
433
440
  console.error(`publish-update: ${message}`);
434
441
  process.exit(1);
@@ -17,6 +17,10 @@ const DEVTOOLS_FEATURES = Object.freeze(featureRegistry.conditionalForbiddenFeat
17
17
  export const FORBIDDEN_FEATURES = Object.freeze([...featureRegistry.forbiddenFeatures.filter((name) => !name.includes("/")), ...DEVTOOLS_FEATURES]);
18
18
  export const QUALIFIED_FORBIDDEN_FEATURES = Object.freeze(featureRegistry.forbiddenFeatures.filter((name) => name.includes("/")));
19
19
  const FORBIDDEN_DEPENDENCY = "tauri-plugin-wdio-webdriver";
20
+ // GATE-CONTRACT GC-A07 (rightkit#1433): the dev copy is the release build plus exactly one feature, `qa-native`. The named `dev` tier allows
21
+ // that one feature and nothing else (`test-mode`, every other QA or inspect feature and `--all-features` stay refused); the release and
22
+ // update tiers refuse `qa-native` too.
23
+ export const DEV_TIER_FEATURES = Object.freeze(["qa-native"]);
20
24
  const MANAGERS = new Set(["pnpm", "npm", "yarn", "bun", "npx"]);
21
25
 
22
26
  // "dep:foo" -> "foo"; "tauri/devtools" and "tauri?/devtools" -> "devtools".
@@ -24,10 +28,11 @@ function featureName(item) {
24
28
  const bare = String(item).trim().replace(/^dep:/, "");
25
29
  return bare.includes("/") ? bare.slice(bare.lastIndexOf("/") + 1) : bare;
26
30
  }
27
- export function isForbiddenFeature(item, { allowDevtools = false } = {}) {
31
+ export function isForbiddenFeature(item, { allowDevtools = false, tier = "release" } = {}) {
28
32
  const text = String(item).trim();
29
33
  const name = featureName(text);
30
34
  if (allowDevtools && DEVTOOLS_FEATURES.includes(name)) return false;
35
+ if (tier === "dev" && DEV_TIER_FEATURES.includes(name)) return false;
31
36
  // `control` is too generic to forbid by bare name; rightkit-qa's dev-only server feature is refused when qualified.
32
37
  if (QUALIFIED_FORBIDDEN_FEATURES.includes(text.replace(/\s+/g, "").replace("?/", "/"))) return true;
33
38
  return text === `dep:${FORBIDDEN_DEPENDENCY}` || FORBIDDEN_FEATURES.includes(name);
@@ -61,7 +66,7 @@ export function scriptTarget(tokens) {
61
66
  }
62
67
 
63
68
  // Issues (strings) for one command object { cmd, args, env? } or a shell string.
64
- export function commandFeatureIssues(command, { label = "command", scripts = {}, depth = 0, seen = new Set(), allowDevtools = false } = {}) {
69
+ export function commandFeatureIssues(command, { label = "command", scripts = {}, depth = 0, seen = new Set(), allowDevtools = false, tier = "release" } = {}) {
65
70
  const parts = typeof command === "string" ? [command] : [command?.cmd, ...(command?.args ?? [])].filter((v) => v !== undefined).map(String);
66
71
  // Two views: every argument whole (`--features` followed by "a b qa-native"), and every argument re-tokenised as
67
72
  // shell text (`sh -c "cargo build --features qa-native"`).
@@ -70,16 +75,16 @@ export function commandFeatureIssues(command, { label = "command", scripts = {},
70
75
  for (const tokens of views) {
71
76
  const { enabled, allFeatures } = featuresInTokens(tokens);
72
77
  if (allFeatures) issues.add(`${label}: --all-features enables every feature including ${FORBIDDEN_FEATURES.join(", ")}`);
73
- for (const feature of enabled) if (isForbiddenFeature(feature, { allowDevtools })) issues.add(`${label}: enables feature \`${feature}\``);
78
+ for (const feature of enabled) if (isForbiddenFeature(feature, { allowDevtools, tier })) issues.add(`${label}: enables feature \`${feature}\``);
74
79
  }
75
80
  if (command && typeof command === "object") {
76
81
  for (const [key, value] of Object.entries(command.env ?? {})) {
77
- if (/FEATURES$/i.test(key)) for (const feature of String(value).split(/[,\s]+/)) if (feature && isForbiddenFeature(feature, { allowDevtools })) issues.add(`${label}: env ${key} enables feature \`${feature}\``);
82
+ if (/FEATURES$/i.test(key)) for (const feature of String(value).split(/[,\s]+/)) if (feature && isForbiddenFeature(feature, { allowDevtools, tier })) issues.add(`${label}: env ${key} enables feature \`${feature}\``);
78
83
  }
79
84
  }
80
85
  const script = views.map(scriptTarget).find(Boolean);
81
86
  if (script && depth < 3 && Object.hasOwn(scripts, script) && !seen.has(script)) {
82
- for (const issue of commandFeatureIssues(String(scripts[script]), { label: `${label} -> package script \`${script}\``, scripts, depth: depth + 1, seen: new Set([...seen, script]), allowDevtools })) issues.add(issue);
87
+ for (const issue of commandFeatureIssues(String(scripts[script]), { label: `${label} -> package script \`${script}\``, scripts, depth: depth + 1, seen: new Set([...seen, script]), allowDevtools, tier })) issues.add(issue);
83
88
  }
84
89
  return [...issues];
85
90
  }
@@ -153,7 +158,7 @@ function dependencyInfo(spec) {
153
158
  };
154
159
  }
155
160
 
156
- export function cargoManifestIssues(manifestText, label = "Cargo.toml", { allowDevtools = false } = {}) {
161
+ export function cargoManifestIssues(manifestText, label = "Cargo.toml", { allowDevtools = false, tier = "release" } = {}) {
157
162
  const { features, dependencies } = parseCargoFeaturesAndDependencies(manifestText);
158
163
  const issues = [];
159
164
  const canonicalFeature = (item) => {
@@ -162,7 +167,7 @@ export function cargoManifestIssues(manifestText, label = "Cargo.toml", { allowD
162
167
  };
163
168
  for (const [alias, dep] of dependencies) {
164
169
  if (dep.package && dep.package !== alias && !dep.optional) for (const feature of dep.features) {
165
- if (isForbiddenFeature(`${dep.package ?? alias}/${feature}`, { allowDevtools })) issues.push(`${label}: dependency \`${alias}\` enables forbidden feature \`${dep.package ?? alias}/${feature}\``);
170
+ if (isForbiddenFeature(`${dep.package ?? alias}/${feature}`, { allowDevtools, tier })) issues.push(`${label}: dependency \`${alias}\` enables forbidden feature \`${dep.package ?? alias}/${feature}\``);
166
171
  }
167
172
  }
168
173
  const tauri = dependencies.get("tauri");
@@ -180,14 +185,14 @@ export function cargoManifestIssues(manifestText, label = "Cargo.toml", { allowD
180
185
  if (shell && !shell.optional && shell.features.includes("dev-inspect")) issues.push(`${label}: dependency \`${name}\` lists \`dev-inspect\` unconditionally (developer inspection ships in release builds)`);
181
186
  }
182
187
  // GC-A09: no `test-mode` feature exists anywhere (own `[features]` table or any dependency, optional or not,
183
- // `<crate>/test-mode` forwards included): tests are isolated by injection (a temp data root, a MemoryBackend).
188
+ // `<crate>/test-mode` forwards included): tests are isolated by injection of a temp data root; journeys run on the real data under the rightkit-qa snapshot and restore (GC-A10, rightkit#1437).
184
189
  const isTestModeName = (name) => name === "test-mode" || name.endsWith("-test-mode");
185
190
  for (const name of features.keys()) {
186
- if (isTestModeName(name)) issues.push(`${label}: declares feature \`${name}\` (no test-mode feature may exist: inject a temp data root and a MemoryBackend instead)`);
191
+ if (isTestModeName(name)) issues.push(`${label}: declares feature \`${name}\` (no test-mode feature may exist: tests inject a temp data root, journeys run on the real data under the rightkit-qa [snapshot] and restore)`);
187
192
  }
188
193
  for (const [alias, dep] of dependencies) {
189
194
  for (const feature of dep.features) {
190
- if (isTestModeName(feature)) issues.push(`${label}: dependency \`${alias}\` enables feature \`${feature}\` (no test-mode feature may exist: inject a temp data root and a MemoryBackend instead)`);
195
+ if (isTestModeName(feature)) issues.push(`${label}: dependency \`${alias}\` enables feature \`${feature}\` (no test-mode feature may exist: tests inject a temp data root, journeys run on the real data under the rightkit-qa [snapshot] and restore)`);
191
196
  }
192
197
  }
193
198
  const wdio = dependencies.get(FORBIDDEN_DEPENDENCY);
@@ -197,7 +202,7 @@ export function cargoManifestIssues(manifestText, label = "Cargo.toml", { allowD
197
202
  const item = stack.pop();
198
203
  if (reached.has(item)) continue;
199
204
  reached.add(item);
200
- if (isForbiddenFeature(canonicalFeature(item), { allowDevtools })) issues.push(`${label}: default feature set reaches \`${item}\``);
205
+ if (isForbiddenFeature(canonicalFeature(item), { allowDevtools, tier })) issues.push(`${label}: default feature set reaches \`${item}\``);
201
206
  if (features.has(item)) stack.push(...features.get(item));
202
207
  }
203
208
  return issues;
@@ -214,7 +219,7 @@ export function resolveCargoManifestPath({ root, cargoManifest, manifest } = {})
214
219
  return { rel: candidates.find((c) => existsSync(path.join(root, c))), declared, candidates };
215
220
  }
216
221
 
217
- export function buildFeatureIssues({ root, commands, devtools, cargoManifest, manifest }) {
222
+ export function buildFeatureIssues({ root, commands, devtools, cargoManifest, manifest, tier = "release" }) {
218
223
  const allowDevtools = devtools?.mode === "content-only";
219
224
  let scripts = {};
220
225
  try { scripts = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).scripts ?? {}; } catch { /* no package.json */ }
@@ -223,16 +228,20 @@ export function buildFeatureIssues({ root, commands, devtools, cargoManifest, ma
223
228
  if (!command) continue;
224
229
  // A `node recipe-build.mjs --plan <JSON>` wrapper hides every step's flags in one argument: scan each step too.
225
230
  const expanded = expandRecipeBuildCommands(command, { root });
226
- expanded.forEach((part, index) => issues.push(...commandFeatureIssues(part, { label: index === 0 ? label : `${label} -> recipe-build step ${index}`, scripts, allowDevtools })));
231
+ expanded.forEach((part, index) => issues.push(...commandFeatureIssues(part, { label: index === 0 ? label : `${label} -> recipe-build step ${index}`, scripts, allowDevtools, tier })));
227
232
  }
228
233
  const { rel } = resolveCargoManifestPath({ root, cargoManifest, manifest });
229
- if (rel) issues.push(...cargoManifestIssues(readFileSync(path.join(root, rel), "utf8"), rel, { allowDevtools }));
234
+ if (rel) issues.push(...cargoManifestIssues(readFileSync(path.join(root, rel), "utf8"), rel, { allowDevtools, tier }));
230
235
  return issues;
231
236
  }
232
237
 
233
238
  export function assertNoForbiddenBuildFeatures({ root, commands, tier = "release", devtools, cargoManifest, manifest }) {
234
- const issues = buildFeatureIssues({ root, commands, devtools, cargoManifest, manifest });
239
+ // The named `dev` tier (GC-A07) allows `qa-native` only; every other tier name (release, update, release/update) refuses it as well.
240
+ const issues = buildFeatureIssues({ root, commands, devtools, cargoManifest, manifest, tier: tier === "dev" ? "dev" : "release" });
235
241
  if (issues.length === 0) return;
242
+ if (tier === "dev") {
243
+ throw new Error(`dev build refused: it enables a feature other than ${DEV_TIER_FEATURES.join(", ")} (the dev copy is the release build plus exactly that feature, GATE-CONTRACT GC-A07):\n- ${issues.join("\n- ")}\n`);
244
+ }
236
245
  throw new Error(
237
246
  `${tier} build refused: it enables a test-automation or debugging feature (${FORBIDDEN_FEATURES.join(", ")}); none may ship:\n- ${issues.join("\n- ")}\n`
238
247
  + "Remove the feature from the release build command, the app's default features and its tauri dependency; dev builds (`right-release dev`) may keep it. "
package/qa-contract.mjs CHANGED
@@ -21,13 +21,12 @@ export function validateQaBackdoorContract(root, packageScripts = {}) {
21
21
  }
22
22
 
23
23
  const rustSource = readRustSources(path.join(root, "src-tauri", "src")).replace(/\s+/g, " ");
24
- if (!/cfg\s*\(\s*all\s*\(\s*not\s*\(\s*debug_assertions\s*\)\s*,\s*feature\s*=\s*"qa-native"\s*\)\s*\)/.test(rustSource)
25
- || !/compile_error!/.test(rustSource)) {
26
- issues.push("Rust must compile_error when qa-native is enabled outside debug builds");
27
- }
28
- if (!/cfg\s*\(\s*all\s*\(\s*debug_assertions\s*,\s*feature\s*=\s*"qa-native"\s*\)\s*\)/.test(rustSource)
24
+ // GATE-CONTRACT GC-A07 (rightkit#1433): the dev copy is the release build plus `qa-native`, so the feature is no longer required to sit behind a
25
+ // debug-assertions profile (the earlier rule demanded a `compile_error!` for qa-native outside debug builds, which forced a debug profile). An app
26
+ // that still carries that cfg passes until it adopts GC-A07; what stays required is that the WebDriver registration exists only behind `qa-native`.
27
+ if (!/cfg\s*\([^"]{0,120}feature\s*=\s*"qa-native"/.test(rustSource)
29
28
  || !/tauri_plugin_wdio_webdriver::init/.test(rustSource)) {
30
- issues.push("WebDriver registration must require debug_assertions and qa-native");
29
+ issues.push("WebDriver registration must be behind the qa-native feature");
31
30
  }
32
31
  if (!/RIGHTKIT_QA_NATIVE/.test(rustSource)) {
33
32
  issues.push("WebDriver registration must also require RIGHTKIT_QA_NATIVE");
@@ -20,6 +20,14 @@ import { closeSync, lstatSync, openSync, readFileSync, readSync, readdirSync } f
20
20
  import path from "node:path";
21
21
  import { inflateRawSync } from "node:zlib";
22
22
 
23
+ // The web QA switch (rightkit#1480): one Vite define `__RIGHTKIT_QA__`, true only when RIGHTKIT_BUILD_MODE=dev (`rightkitQaDefine()` in
24
+ // @rightkit/config), and one fixed string the web QA code carries, `RIGHTKIT-QA-WEB-COMPILED`. Both, and the four retired per-app flags, live
25
+ // in release-switch-registry.json (`webQa`) so the release-switch scan and this scan read one list.
26
+ const WEB_QA = JSON.parse(readFileSync(new URL("./release-switch-registry.json", import.meta.url), "utf8")).webQa;
27
+ export const WEB_QA_MARKER = WEB_QA.marker;
28
+ export const WEB_QA_DEFINE = WEB_QA.define;
29
+ export const WEB_QA_RETIRED = Object.freeze([...WEB_QA.retired]);
30
+
23
31
  // Keep identical to `QA_CONTROL_MARKER` in crates/rightkit-qa/src/embedded/mod.rs.
24
32
  export const QA_CONTROL_MARKER = "RIGHTKIT-QA-CONTROL-SERVER-PRESENT";
25
33
  // Keep identical to `DEV_INSPECT_MARKER` in crates/rightkit-tauri-shell/src/devtools.rs (a `#[used]` static compiled only
@@ -392,6 +400,12 @@ export const WEB_MOCK_MARKERS = Object.freeze([
392
400
  { id: "MockDataSource", pattern: /MockDataSource/ },
393
401
  { id: "qa-build-flag", pattern: /\bVITE_[A-Z0-9_]*_QA\b/ },
394
402
 
403
+ // The one web QA switch (#1480): the marker the QA code carries, the define itself (a release build folds it to `false`, so the name
404
+ // must be gone) and the retired per-app spellings.
405
+ { id: "web-qa-marker", pattern: new RegExp(WEB_QA_MARKER) },
406
+ { id: "web-qa-define", pattern: new RegExp(`\\b${WEB_QA_DEFINE}\\b`) },
407
+ ...WEB_QA_RETIRED.map((name) => ({ id: `web-qa-retired ${name}`, pattern: new RegExp(`\\b${name}\\b`) })),
408
+
395
409
  // @rightkit/license/testing (M12): its sentinel value, and the subpath a bundle that kept the import still names.
396
410
  { id: "license-testing-sentinel", pattern: /\bRIGHTKIT_LICENSE_TESTING_DO_NOT_SHIP\b/ },
397
411
  { id: "license-testing-entry", pattern: /@rightkit\/license\/testing/ },
@@ -0,0 +1,76 @@
1
+ // The Rust half and the web half of the QA surface must not drift (rightkit#1480). One cargo feature, `qa-native`, builds the native QA
2
+ // control server; one Vite define, `__RIGHTKIT_QA__` (`rightkitQaDefine()` in @rightkit/config, true only when the dev lane's
3
+ // RIGHTKIT_BUILD_MODE=dev), builds the web QA code, which carries the fixed string `RIGHTKIT-QA-WEB-COMPILED`.
4
+ //
5
+ // Release lane: the release web scan (`assertNoWebBundleMocks`, qa-control-scan.mjs) refuses the marker, the define and the retired flags in the
6
+ // frontend bundle, and the binary scans refuse the native control marker, so neither half can ship. Nothing else is needed here.
7
+ // Dev lane: `devWebQaPairingFindings` runs after the dev build. When the build command enables `qa-native`, an app that declares
8
+ // `releaseSwitches.webQa: true` (it adopted the shared define) must have a frontend bundle that carries the marker; and a bundle
9
+ // that carries the marker without `qa-native` in the Cargo features is drift in the other direction, refused for every app.
10
+ // The app declaration keeps an app that has not adopted the define yet building; it does not weaken the release lane.
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import path from "node:path";
13
+ import { featuresInTokens, scriptTarget } from "./qa-build-features.mjs";
14
+ import { WEB_QA_MARKER, scanWebBundle } from "./qa-control-scan.mjs";
15
+ import { commandTokens } from "./release-switch-scan.mjs";
16
+
17
+ export const NATIVE_QA_FEATURE = "qa-native";
18
+
19
+ /** Does any of the build `commands` ({ cmd, args, env? } or shell strings) enable cargo feature `feature`, directly or through a package.json script (three levels)? */
20
+ export function commandsEnableFeature(commands, { root, feature = NATIVE_QA_FEATURE } = {}) {
21
+ let scripts = {};
22
+ try { scripts = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).scripts ?? {}; } catch { /* no package.json: no scripts to follow */ }
23
+ const visit = (command, depth, seen) => {
24
+ const tokens = commandTokens(command);
25
+ if (featuresInTokens(tokens).enabled.includes(feature)) return true;
26
+ if (command && typeof command === "object") {
27
+ for (const [key, value] of Object.entries(command.env ?? {})) if (/FEATURES$/i.test(key) && String(value).split(/[,\s]+/).includes(feature)) return true;
28
+ }
29
+ const script = scriptTarget(tokens);
30
+ if (script && depth < 3 && Object.hasOwn(scripts, script) && !seen.has(script)) return visit(String(scripts[script]), depth + 1, new Set([...seen, script]));
31
+ return false;
32
+ };
33
+ return commands.filter(Boolean).some((command) => visit(command, 0, new Set()));
34
+ }
35
+
36
+ /** The Tauri `frontendDist` bundle directories of an app (absolute), or [] when it has none or serves a URL. */
37
+ export function frontendBundleDirectories(root) {
38
+ const confPath = path.join(root, "src-tauri", "tauri.conf.json");
39
+ if (!existsSync(confPath)) return [];
40
+ const build = JSON.parse(readFileSync(confPath, "utf8")).build ?? {};
41
+ const dist = build.frontendDist ?? build.distDir;
42
+ if (typeof dist !== "string" || /^[a-z][a-z0-9+.-]*:\/\//i.test(dist)) return [];
43
+ return [path.resolve(root, "src-tauri", dist)];
44
+ }
45
+
46
+ /** Does any web file under `dirs` carry the web QA marker? Returns { files, carries }. */
47
+ export function webBundleCarriesQaMarker(dirs) {
48
+ const { findings, files } = scanWebBundle(dirs, { requireFiles: true });
49
+ return { files, carries: findings.some((finding) => finding.marker === "web-qa-marker"), unscannable: findings.filter((finding) => finding.rule === "unscannable") };
50
+ }
51
+
52
+ /**
53
+ * Pure pairing rule. `nativeQa`: the dev build enables qa-native. `webQa`: the frontend bundle carries the marker. `webQaDeclared`: the app
54
+ * declares releaseSwitches.webQa: true.
55
+ */
56
+ export function devWebQaPairingFindings({ nativeQa, webQa, webQaDeclared }) {
57
+ const findings = [];
58
+ if (nativeQa && webQaDeclared && !webQa) findings.push({ rule: "web-qa-missing", reason: `web-qa-missing: the dev build enables ${NATIVE_QA_FEATURE} and the app declares releaseSwitches.webQa, but the frontend bundle does not carry ${WEB_QA_MARKER} (build the bundle with \`define: { ...rightkitQaDefine() }\`, which is true when RIGHTKIT_BUILD_MODE=dev)` });
59
+ if (!nativeQa && webQa) findings.push({ rule: "web-qa-unpaired", reason: `web-qa-unpaired: the frontend bundle carries ${WEB_QA_MARKER} but the build does not enable ${NATIVE_QA_FEATURE}; the web and native QA halves must be built together` });
60
+ return findings;
61
+ }
62
+
63
+ /**
64
+ * The dev-lane pairing check for an app root: reads the build commands' features, the declaration and the built frontend bundle. Apps with no
65
+ * Tauri frontend bundle (native-only apps) have no web half and return no findings.
66
+ */
67
+ export function devWebQaPairing({ root, config, commands }) {
68
+ const dirs = frontendBundleDirectories(root).filter((dir) => existsSync(dir));
69
+ if (dirs.length === 0) return { checked: false, findings: [] };
70
+ const declared = config?.releaseSwitches?.webQa;
71
+ if (declared !== undefined && typeof declared !== "boolean") throw new Error(`releaseSwitches.webQa must be true or false, got ${JSON.stringify(declared)}`);
72
+ const bundle = webBundleCarriesQaMarker(dirs);
73
+ const unscannable = bundle.unscannable.map((finding) => ({ rule: "unscannable", reason: `unscannable: ${finding.file}: ${finding.reason}` }));
74
+ const nativeQa = commandsEnableFeature(commands, { root });
75
+ return { checked: true, nativeQa, webQa: bundle.carries, findings: [...unscannable, ...devWebQaPairingFindings({ nativeQa, webQa: bundle.carries, webQaDeclared: declared === true })] };
76
+ }
@@ -0,0 +1,190 @@
1
+ // S3-compatible R2 transport for objects above the wrangler 300 MiB cap (#902): a multipart upload and a streamed sha256 + size readback, both
2
+ // signed with AWS Signature V4 using node:crypto and fetch only (no S3 client dependency).
3
+ //
4
+ // Credentials are derived in memory from the Cloudflare API token and never printed, logged, put on a command line or written to disk
5
+ // (docs/rules/cloudflare-access.md "R2 - app distribution"): the Access Key ID is the token's id (what the token-verify endpoint returns for
6
+ // it) and the Secret Access Key is the SHA-256 of the token value (https://developers.cloudflare.com/r2/api/tokens/). Every error message
7
+ // carries an HTTP status and the S3 error code, never a header, URL query or credential.
8
+ //
9
+ // The upload hashes the bytes it sends and compares the whole-file sha256 with the publication evidence before it completes the object, so an
10
+ // object that does not match the evidence is aborted, never created. The readback streams GetObject through a sha256 and a byte counter, so no
11
+ // large object is held in memory or written to disk, and `wrangler r2 object get` (which aborts mid-stream on large objects, Rule 6) is not used.
12
+ import { createHash, createHmac } from "node:crypto";
13
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
14
+ import { PublicationError } from "./publication-artifacts.mjs";
15
+
16
+ export const R2_ACCOUNT_ID = "03ae77ccd7a07bcbb2dcfde47fa7ba3a";
17
+ /** At or above this size the object goes through the S3 route; below it wrangler's single request (cap 300 MiB) is used. */
18
+ export const R2_MULTIPART_THRESHOLD_BYTES = 200 * 1024 * 1024;
19
+ export const R2_PART_BYTES = 64 * 1024 * 1024;
20
+ const MAX_PARTS = 10000;
21
+ const REGION = "auto";
22
+ const SERVICE = "s3";
23
+ const TOKEN_VERIFY_URLS = (account) => [
24
+ "https://api.cloudflare.com/client/v4/user/tokens/verify",
25
+ `https://api.cloudflare.com/client/v4/accounts/${account}/tokens/verify`,
26
+ ];
27
+
28
+ const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
29
+ const hmac = (key, data) => createHmac("sha256", key).update(data).digest();
30
+ const rfc3986 = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
31
+
32
+ /** { accessKeyId, secretAccessKey } for an R2-capable API token, derived in memory. Throws PUBLICATION_UPLOAD_FAILED without detail that could carry the token. */
33
+ export async function deriveR2S3Credentials(token, { account = R2_ACCOUNT_ID, fetchImpl = fetch } = {}) {
34
+ if (typeof token !== "string" || !token.trim()) throw new PublicationError("PUBLICATION_UPLOAD_FAILED", "CLOUDFLARE_API_TOKEN is required for the S3-compatible R2 route");
35
+ let lastStatus = "no response";
36
+ for (const url of TOKEN_VERIFY_URLS(account)) {
37
+ let response;
38
+ try { response = await fetchImpl(url, { headers: { authorization: `Bearer ${token}` } }); } catch (error) { lastStatus = `network error ${error.name}`; continue; }
39
+ lastStatus = `HTTP ${response.status}`;
40
+ if (!response.ok) continue;
41
+ let body;
42
+ try { body = await response.json(); } catch { continue; }
43
+ const id = body?.result?.id;
44
+ if (body?.success === true && typeof id === "string" && id && body?.result?.status === "active") {
45
+ return { accessKeyId: id, secretAccessKey: sha256Hex(token) };
46
+ }
47
+ }
48
+ throw new PublicationError("PUBLICATION_UPLOAD_FAILED", `the Cloudflare API token could not be verified for R2 S3 credentials (${lastStatus})`);
49
+ }
50
+
51
+ /** The Authorization and x-amz-* headers of one SigV4 request. `query` is an array of [name, value]; `payloadHash` is the hex sha256 of the body. */
52
+ export function signRequest({ method, host, pathname, query = [], payloadHash, credentials, now = new Date(), headers = {} }) {
53
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
54
+ const date = amzDate.slice(0, 8);
55
+ const signedHeaders = { ...Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), String(value).trim()])), host, "x-amz-content-sha256": payloadHash, "x-amz-date": amzDate };
56
+ const names = Object.keys(signedHeaders).sort();
57
+ const canonicalQuery = [...query].map(([name, value]) => [rfc3986(name), rfc3986(value)]).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map(([name, value]) => `${name}=${value}`).join("&");
58
+ const canonicalRequest = `${method}\n${pathname}\n${canonicalQuery}\n${names.map((name) => `${name}:${signedHeaders[name]}\n`).join("")}\n${names.join(";")}\n${payloadHash}`;
59
+ const scope = `${date}/${REGION}/${SERVICE}/aws4_request`;
60
+ const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256Hex(canonicalRequest)].join("\n");
61
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, date), REGION), SERVICE), "aws4_request");
62
+ const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
63
+ return {
64
+ ...Object.fromEntries(Object.entries(signedHeaders).filter(([name]) => name !== "host")),
65
+ authorization: `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${signature}`,
66
+ canonicalQuery,
67
+ };
68
+ }
69
+
70
+ /**
71
+ * A time-limited GET URL for one private object (SigV4 query authentication, `UNSIGNED-PAYLOAD`, host header only), rightkit#1230. The URL is the
72
+ * product of this call and the only place the signature appears; the credentials themselves are never returned. `expiresSeconds` is 60..86400.
73
+ */
74
+ export function presignGetUrl({ bucket, key, credentials, account = R2_ACCOUNT_ID, expiresSeconds = 3600, now = new Date() }) {
75
+ if (!Number.isInteger(expiresSeconds) || expiresSeconds < 60 || expiresSeconds > 86400) throw new PublicationError("PUBLICATION_ROUTE_INVALID", "a presigned URL lives 60 to 86400 seconds");
76
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(key ?? "") || key.includes("..") || !/^[a-z0-9][a-z0-9-]*$/.test(bucket ?? "")) throw new PublicationError("PUBLICATION_ROUTE_INVALID", "invalid R2 object route");
77
+ const host = `${account}.r2.cloudflarestorage.com`;
78
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
79
+ const date = amzDate.slice(0, 8);
80
+ const scope = `${date}/${REGION}/${SERVICE}/aws4_request`;
81
+ const query = [["X-Amz-Algorithm", "AWS4-HMAC-SHA256"], ["X-Amz-Credential", `${credentials.accessKeyId}/${scope}`], ["X-Amz-Date", amzDate], ["X-Amz-Expires", String(expiresSeconds)], ["X-Amz-SignedHeaders", "host"]];
82
+ const canonicalQuery = query.map(([name, value]) => [rfc3986(name), rfc3986(value)]).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([name, value]) => `${name}=${value}`).join("&");
83
+ const pathname = `/${bucket}/${key.split("/").map(rfc3986).join("/")}`;
84
+ const canonicalRequest = `GET\n${pathname}\n${canonicalQuery}\nhost:${host}\n\nhost\nUNSIGNED-PAYLOAD`;
85
+ const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256Hex(canonicalRequest)].join("\n");
86
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, date), REGION), SERVICE), "aws4_request");
87
+ const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
88
+ return { url: `https://${host}${pathname}?${canonicalQuery}&X-Amz-Signature=${signature}`, expiresAt: new Date(now.getTime() + expiresSeconds * 1000).toISOString() };
89
+ }
90
+
91
+ const xmlText = (xml, tag) => new RegExp(`<${tag}>([^<]*)</${tag}>`).exec(xml)?.[1];
92
+ const escapeXml = (value) => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
93
+
94
+ function s3Client({ bucket, credentials, account = R2_ACCOUNT_ID, fetchImpl = fetch, retries = 3, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }) {
95
+ const host = `${account}.r2.cloudflarestorage.com`;
96
+ const objectPath = (key) => `/${bucket}/${key.split("/").map(rfc3986).join("/")}`;
97
+ async function send(method, key, { query = [], body, payloadHash, headers = {}, stream = false }) {
98
+ let failure = "no response";
99
+ for (let attempt = 1; attempt <= retries; attempt += 1) {
100
+ const pathname = objectPath(key);
101
+ const signed = signRequest({ method, host, pathname, query, payloadHash, credentials, headers });
102
+ const { canonicalQuery, ...requestHeaders } = signed;
103
+ let response;
104
+ try {
105
+ response = await fetchImpl(`https://${host}${pathname}${canonicalQuery ? `?${canonicalQuery}` : ""}`, { method, headers: requestHeaders, body });
106
+ } catch (error) { failure = `network error ${error.name}`; }
107
+ if (response) {
108
+ if (response.ok) return response;
109
+ const text = await response.text().catch(() => "");
110
+ failure = `HTTP ${response.status}${xmlText(text, "Code") ? ` ${xmlText(text, "Code")}` : ""}`;
111
+ // A client error other than throttling is final; a server error or throttle is retried.
112
+ if (response.status < 500 && response.status !== 429 && response.status !== 408) break;
113
+ }
114
+ if (attempt < retries) await sleep(500 * 2 ** (attempt - 1));
115
+ }
116
+ throw new Error(`${method} ${stream ? "object" : "request"} failed (${failure})`);
117
+ }
118
+ return { send };
119
+ }
120
+
121
+ /** Read `length` bytes at `position` of an open file descriptor into a fresh Buffer. */
122
+ function readPart(fd, position, length) {
123
+ const buffer = Buffer.allocUnsafe(length);
124
+ let filled = 0;
125
+ while (filled < length) {
126
+ const count = readSync(fd, buffer, filled, length - filled, position + filled);
127
+ if (count === 0) throw new Error("file ended before the expected size");
128
+ filled += count;
129
+ }
130
+ return buffer;
131
+ }
132
+
133
+ /**
134
+ * Upload `file` to `bucket/key` as one multipart object. The whole-file sha256 and size of what was sent must equal `evidence` before the object is
135
+ * completed; any failure aborts the multipart upload. Returns { parts, sizeBytes }.
136
+ */
137
+ export async function uploadMultipart({ file, evidence, bucket, key, credentials, partBytes = R2_PART_BYTES, account, fetchImpl, sleep }) {
138
+ const client = s3Client({ bucket, credentials, account, fetchImpl, sleep });
139
+ const fd = openSync(file, "r");
140
+ let uploadId;
141
+ try {
142
+ const size = fstatSync(fd).size;
143
+ if (evidence.sizeBytes !== undefined && size !== evidence.sizeBytes) throw new PublicationError("PUBLICATION_SIZE_MISMATCH", `artifact size mismatch: ${file}`);
144
+ const chunk = Math.max(partBytes, Math.ceil(size / MAX_PARTS));
145
+ const created = await client.send("POST", key, { query: [["uploads", ""]], payloadHash: sha256Hex("") });
146
+ uploadId = xmlText(await created.text(), "UploadId");
147
+ if (!uploadId) throw new Error("CreateMultipartUpload returned no UploadId");
148
+ const whole = createHash("sha256");
149
+ const etags = [];
150
+ for (let offset = 0, number = 1; offset < size; offset += chunk, number += 1) {
151
+ const body = readPart(fd, offset, Math.min(chunk, size - offset));
152
+ whole.update(body);
153
+ const response = await client.send("PUT", key, { query: [["partNumber", String(number)], ["uploadId", uploadId]], body, payloadHash: sha256Hex(body) });
154
+ const etag = response.headers.get("etag");
155
+ if (!etag) throw new Error(`part ${number} returned no ETag`);
156
+ etags.push({ number, etag });
157
+ }
158
+ if (whole.digest("hex") !== evidence.sha256) throw new PublicationError("PUBLICATION_HASH_MISMATCH", `artifact sha256 mismatch: ${file}`);
159
+ const xml = `<CompleteMultipartUpload>${etags.map(({ number, etag }) => `<Part><PartNumber>${number}</PartNumber><ETag>${escapeXml(etag)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;
160
+ const completeBody = Buffer.from(xml);
161
+ const completed = await client.send("POST", key, { query: [["uploadId", uploadId]], body: completeBody, payloadHash: sha256Hex(completeBody), headers: { "content-type": "application/xml" } });
162
+ // CompleteMultipartUpload can answer 200 with an error document.
163
+ const text = await completed.text();
164
+ if (/<Error>/.test(text)) throw new Error(`CompleteMultipartUpload failed (${xmlText(text, "Code") ?? "error"})`);
165
+ uploadId = undefined;
166
+ return { parts: etags.length, sizeBytes: size };
167
+ } catch (error) {
168
+ if (uploadId) await client.send("DELETE", key, { query: [["uploadId", uploadId]], payloadHash: sha256Hex("") }).catch(() => {});
169
+ throw error;
170
+ } finally { closeSync(fd); }
171
+ }
172
+
173
+ /** One signed GetObject response (optionally `range: "bytes=N-"`): the body is streamed by the caller. Throws with the HTTP status only. */
174
+ export async function getObject({ bucket, key, credentials, account, fetchImpl, sleep, range }) {
175
+ const client = s3Client({ bucket, credentials, account, fetchImpl, sleep });
176
+ return client.send("GET", key, { payloadHash: sha256Hex(""), stream: true, ...(range ? { headers: { range } } : {}) });
177
+ }
178
+
179
+ /** Stream `bucket/key` through a sha256 and a byte counter. Returns { sha256, sizeBytes }; nothing is held in memory or written to disk. */
180
+ export async function streamObjectDigest({ bucket, key, credentials, account, fetchImpl, sleep }) {
181
+ const client = s3Client({ bucket, credentials, account, fetchImpl, sleep });
182
+ const response = await client.send("GET", key, { payloadHash: sha256Hex(""), stream: true });
183
+ if (!response.body) throw new Error("GetObject returned no body");
184
+ const hash = createHash("sha256");
185
+ let sizeBytes = 0;
186
+ for await (const piece of response.body) { hash.update(piece); sizeBytes += piece.length; }
187
+ const advertised = Number(response.headers.get("content-length"));
188
+ if (Number.isFinite(advertised) && response.headers.has("content-length") && advertised !== sizeBytes) throw new Error(`GetObject stream ended at ${sizeBytes} of ${advertised} bytes`);
189
+ return { sha256: hash.digest("hex"), sizeBytes };
190
+ }