@cassiomc1/forgeloop 2.1.0 → 2.3.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.
Files changed (67) hide show
  1. package/CONTRIBUTING.md +22 -2
  2. package/DOCS_INDEX.md +4 -13
  3. package/ENG/sec-code-eng.md +1 -1
  4. package/ENG/test-code-eng.md +32 -1
  5. package/LOOP_SYSTEM_DESIGN.md +2 -3
  6. package/QUALITY_SCORECARD.md +0 -1
  7. package/README.md +19 -48
  8. package/THIRD_PARTY_NOTICES.md +0 -15
  9. package/completions/_forgeloop +7 -1
  10. package/completions/forgeloop.bash +13 -1
  11. package/completions/forgeloop.fish +51 -1
  12. package/docs/AGENT_PROTOCOL_SUMMARY.md +7 -1
  13. package/docs/ARTIFACT_REFERENCE.md +1 -0
  14. package/docs/CLI_REFERENCE.md +111 -3
  15. package/docs/CODE_ATTESTATION.md +16 -7
  16. package/docs/DOCUMENTATION_GUIDE.md +10 -28
  17. package/docs/PACKAGE_CONTENTS.md +0 -3
  18. package/docs/RELEASE_CHECKLIST.md +81 -15
  19. package/docs/REVISION_PROVIDERS.md +3 -6
  20. package/docs/TROUBLESHOOTING.md +11 -0
  21. package/docs/documentation-manifest.json +0 -13
  22. package/package.json +2 -6
  23. package/schemas/config.schema.json +1 -0
  24. package/scripts/CI_VALIDATORS.md +2 -2
  25. package/src/cli.js +31 -0
  26. package/src/commands/assess.js +36 -0
  27. package/src/commands/attestation-create.js +21 -1
  28. package/src/commands/complete.js +3 -0
  29. package/src/commands/evidence-export.js +17 -0
  30. package/src/commands/evidence-publish.js +22 -0
  31. package/src/commands/evidence-verify.js +36 -0
  32. package/src/commands/sync-pull.js +111 -0
  33. package/src/commands/sync-push.js +52 -0
  34. package/src/core/assessment/facts.js +146 -0
  35. package/src/core/assessment/plan.js +133 -0
  36. package/src/core/audit.js +7 -0
  37. package/src/core/cli-command-definitions.js +88 -0
  38. package/src/core/command-executors.js +42 -5
  39. package/src/core/config.js +44 -37
  40. package/src/core/error-codes.js +70 -0
  41. package/src/core/evidence/auto-export.js +61 -0
  42. package/src/core/evidence/bundle-format.js +74 -0
  43. package/src/core/evidence/export.js +184 -0
  44. package/src/core/evidence/markdown.js +40 -0
  45. package/src/core/evidence/publish.js +187 -0
  46. package/src/core/evidence/verify.js +179 -0
  47. package/src/core/integration-invocation-policy.js +5 -2
  48. package/src/core/sync/merge.js +135 -0
  49. package/src/core/sync/remote.js +124 -0
  50. package/src/core/sync/snapshot.js +129 -0
  51. package/docs/assets/diagrams/forgeloop-code-attestation-flow.html +0 -13852
  52. package/docs/assets/diagrams/forgeloop-code-attestation-flow.receipt.json +0 -37
  53. package/docs/assets/diagrams/forgeloop-code-attestation-flow.svg +0 -5055
  54. package/docs/assets/diagrams/forgeloop-engineering-flow.html +0 -13837
  55. package/docs/assets/diagrams/forgeloop-engineering-flow.receipt.json +0 -37
  56. package/docs/assets/diagrams/forgeloop-engineering-flow.svg +0 -5011
  57. package/docs/assets/diagrams/forgeloop-verification-trust-flow.html +0 -13795
  58. package/docs/assets/diagrams/forgeloop-verification-trust-flow.receipt.json +0 -37
  59. package/docs/assets/diagrams/forgeloop-verification-trust-flow.svg +0 -4997
  60. package/docs/diagrams/README.md +0 -103
  61. package/docs/diagrams/forgeloop-code-attestation-flow.workflow.json +0 -451
  62. package/docs/diagrams/forgeloop-engineering-flow.workflow.json +0 -459
  63. package/docs/diagrams/forgeloop-verification-trust-flow.workflow.json +0 -398
  64. package/docs/diagrams/manifest.json +0 -84
  65. package/docs/diagrams/reviews/forgeloop-code-attestation-flow.review.json +0 -20
  66. package/docs/diagrams/reviews/forgeloop-engineering-flow.review.json +0 -20
  67. package/docs/diagrams/reviews/forgeloop-verification-trust-flow.review.json +0 -20
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { assertSafePath } from "../filesystem.js";
6
+ import { claimsOverlap } from "../task-scope.js";
7
+ import { backupProjectStorage, verifyProjectStorageBackup } from "../../storage/project-backup.js";
8
+ import { openStorageDatabase } from "../../storage/connection.js";
9
+ import { verifyAttachmentFile } from "../../storage/attachment-files.js";
10
+ import { syncError } from "./snapshot.js";
11
+
12
+ // Three-way, task-granular merge of two ForgeLoop states (this machine and the
13
+ // remote snapshot). Every table except storage_meta and sessions is keyed by
14
+ // task_id, and each task's ledger is its own hash chain, so a whole task can
15
+ // move between stores without rewriting any history. Tasks are compared by a
16
+ // digest of all their rows; the base is the digest recorded at the last push
17
+ // or pull. Nothing is ever resolved inside a task: a task changed on both
18
+ // sides is a conflict.
19
+
20
+ // Table, ordering key. The order is the insert order (tasks first, for the
21
+ // foreign keys).
22
+ export const TASK_TABLES = Object.freeze([
23
+ ["tasks", "task_id"],
24
+ ["claims", "task_id, claim_norm"],
25
+ ["events", "task_id, seq"],
26
+ ["actions", "task_id, action_id"],
27
+ ["approvals", "task_id, approval_id"],
28
+ ["executions", "task_id, execution_id"],
29
+ ["task_artifacts", "task_id, kind, artifact_id"],
30
+ ["attachment_references", "task_id, reference_id"],
31
+ ]);
32
+
33
+ function rowsOf(db, table, order, taskId, schema = "main") {
34
+ return db.prepare(`SELECT * FROM ${schema}.${table} WHERE task_id = ? ORDER BY ${order}`).all(taskId);
35
+ }
36
+
37
+ // One digest per task over every task-scoped row (attachment bytes are bound
38
+ // through attachment_references.sha256).
39
+ export function taskDigests(db, schema = "main") {
40
+ const digests = {};
41
+ for (const { task_id: taskId } of db.prepare(`SELECT task_id FROM ${schema}.tasks ORDER BY task_id`).all()) {
42
+ const hash = createHash("sha256");
43
+ for (const [table, order] of TASK_TABLES) {
44
+ hash.update(`${table}\n`);
45
+ for (const row of rowsOf(db, table, order, taskId, schema)) hash.update(`${JSON.stringify(row, Object.keys(row).sort())}\n`);
46
+ }
47
+ digests[taskId] = hash.digest("hex");
48
+ }
49
+ return digests;
50
+ }
51
+
52
+ export function readDatabaseDigests(databasePath) {
53
+ const db = openStorageDatabase(databasePath, { readOnly: true });
54
+ try { return taskDigests(db); } finally { db.close(); }
55
+ }
56
+
57
+ // local/remote/base: { taskId: digest }. base may be null (no recorded base).
58
+ export function classifyTasks({ local, remote, base = null }) {
59
+ const result = { take: [], keep: [], same: [], conflicts: [] };
60
+ for (const taskId of [...new Set([...Object.keys(local), ...Object.keys(remote)])].sort()) {
61
+ const mine = local[taskId] ?? null;
62
+ const theirs = remote[taskId] ?? null;
63
+ const known = base ? base[taskId] ?? null : undefined;
64
+ if (mine === theirs) result.same.push(taskId);
65
+ else if (theirs === null) result.keep.push({ taskId, reason: "local only" });
66
+ else if (mine === null) result.take.push({ taskId, reason: "remote only" });
67
+ else if (known !== undefined && mine === known) result.take.push({ taskId, reason: "changed remotely" });
68
+ else if (known !== undefined && theirs === known) result.keep.push({ taskId, reason: "changed locally" });
69
+ else result.conflicts.push({ taskId, reason: known === undefined ? "differs and no sync base is recorded" : "changed on both machines" });
70
+ }
71
+ return result;
72
+ }
73
+
74
+ function activeClaims(db, schema, taskIds, include) {
75
+ const rows = db.prepare(`SELECT task_id, claim_norm FROM ${schema}.claims WHERE reservation_state = 'ACTIVE' ORDER BY task_id, claim_norm`).all();
76
+ return rows.filter((row) => include === taskIds.has(row.task_id));
77
+ }
78
+
79
+ // A task taken from the remote must not hold an active claim that overlaps an
80
+ // active claim of a task that stays local.
81
+ function assertNoClaimOverlap(db, taken) {
82
+ const takenIds = new Set(taken);
83
+ const incoming = activeClaims(db, "remote", takenIds, true);
84
+ const staying = activeClaims(db, "main", takenIds, false);
85
+ const overlaps = [];
86
+ for (const left of incoming) {
87
+ for (const right of staying) {
88
+ if (claimsOverlap(left.claim_norm, right.claim_norm)) overlaps.push(`${left.task_id}:${left.claim_norm} ↔ ${right.task_id}:${right.claim_norm}`);
89
+ }
90
+ }
91
+ if (overlaps.length > 0) throw syncError("E_SYNC_MERGE_CONFLICT", `Merged tasks would hold overlapping active claims: ${overlaps.slice(0, 5).join(", ")}`);
92
+ }
93
+
94
+ // Builds a verified backup at `destination` holding the local state plus the
95
+ // remote's version of every task in `take`. `localBackup` is a writable copy of
96
+ // the local storage backup and doubles as the attachment root.
97
+ export async function buildMergedBackup({ localBackup, remoteBackup, take, destination }) {
98
+ const remoteDatabase = await assertSafePath(remoteBackup, "state.sqlite");
99
+ const db = openStorageDatabase(await assertSafePath(localBackup, "state.sqlite"), { allowSchemaUpgrade: false });
100
+ try {
101
+ db.prepare("ATTACH DATABASE ? AS remote").run(remoteDatabase);
102
+ assertNoClaimOverlap(db, take);
103
+ const attachments = [];
104
+ db.exec("BEGIN IMMEDIATE");
105
+ try {
106
+ for (const taskId of take) {
107
+ for (const [table] of [...TASK_TABLES].reverse()) db.prepare(`DELETE FROM main.${table} WHERE task_id = ?`).run(taskId);
108
+ for (const [table, order] of TASK_TABLES) {
109
+ db.prepare(`INSERT INTO main.${table} SELECT * FROM remote.${table} WHERE task_id = ? ORDER BY ${order}`).run(taskId);
110
+ }
111
+ db.prepare("INSERT OR IGNORE INTO main.sessions SELECT * FROM remote.sessions WHERE task_id = ?").run(taskId);
112
+ attachments.push(...rowsOf(db, "attachment_references", "task_id, reference_id", taskId, "remote"));
113
+ }
114
+ db.exec("COMMIT");
115
+ } catch (error) {
116
+ db.exec("ROLLBACK");
117
+ throw error;
118
+ }
119
+ db.prepare("DETACH DATABASE remote").run();
120
+ for (const row of attachments) {
121
+ const reference = { taskId: row.task_id, referenceId: row.reference_id, path: row.path, size: row.size, sha256: row.sha256 };
122
+ await verifyAttachmentFile(remoteBackup, reference);
123
+ const destinationFile = await assertSafePath(localBackup, row.path);
124
+ await mkdir(path.dirname(destinationFile), { recursive: true });
125
+ await copyFile(await assertSafePath(remoteBackup, row.path), destinationFile);
126
+ await verifyAttachmentFile(localBackup, reference);
127
+ }
128
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
129
+ await backupProjectStorage(db, localBackup, destination);
130
+ } finally {
131
+ db.close();
132
+ }
133
+ await verifyProjectStorageBackup(destination);
134
+ return destination;
135
+ }
@@ -0,0 +1,124 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+
8
+ import { syncError } from "./snapshot.js";
9
+
10
+ // Cloud-sync transport and local bookkeeping. The bearer token and passphrase
11
+ // come only from the environment and are never written anywhere. The last
12
+ // remote ETag is kept per project outside the repository, under the user's
13
+ // config directory, so sync never adds files to the working tree.
14
+
15
+ export const DEFAULT_SYNC_REMOTE = "https://forgeloop.monster/api/sync";
16
+ const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u;
17
+ const NAME = /^[A-Za-z0-9._-]{1,100}$/u;
18
+ const REQUEST_TIMEOUT_MS = 60_000;
19
+
20
+ // The hosting edge may weaken a validator (W/"x") for the same version the
21
+ // store reports as "x"; sync always stores and sends the strong form.
22
+ export function strongEtag(value) {
23
+ return typeof value === "string" && value ? value.replace(/^W\//u, "") : null;
24
+ }
25
+
26
+ export function normalizeRepository(value) {
27
+ const [owner, name, extra] = String(value ?? "").split("/");
28
+ if (extra !== undefined || !OWNER.test(owner ?? "") || !NAME.test(name ?? "") || name === "." || name === "..") return null;
29
+ return `${owner}/${name}`.toLowerCase();
30
+ }
31
+
32
+ export function repositoryFromRemoteUrl(url) {
33
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/u.exec(String(url ?? "").trim());
34
+ return match ? normalizeRepository(`${match[1]}/${match[2]}`) : null;
35
+ }
36
+
37
+ export async function resolveRepository(target, explicit) {
38
+ if (explicit) {
39
+ const repository = normalizeRepository(explicit);
40
+ if (!repository) throw syncError("E_SYNC_CONFIG", "--repo must be owner/name");
41
+ return repository;
42
+ }
43
+ try {
44
+ const { stdout } = await promisify(execFile)("git", ["-C", target, "config", "--get", "remote.origin.url"], { timeout: 10_000 });
45
+ const repository = repositoryFromRemoteUrl(stdout);
46
+ if (repository) return repository;
47
+ } catch {
48
+ // Fall through to the explicit-repository error.
49
+ }
50
+ throw syncError("E_SYNC_CONFIG", "Could not derive owner/name from the git origin; pass --repo owner/name");
51
+ }
52
+
53
+ export function resolveRemote(value) {
54
+ let url;
55
+ try {
56
+ url = new URL(value || DEFAULT_SYNC_REMOTE);
57
+ } catch {
58
+ throw syncError("E_SYNC_CONFIG", "--remote must be a URL");
59
+ }
60
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
61
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw syncError("E_SYNC_CONFIG", "--remote must use https (http is allowed only for localhost)");
62
+ if (url.username || url.password || url.search || url.hash) throw syncError("E_SYNC_CONFIG", "--remote must not contain credentials, a query or a fragment");
63
+ return url.toString();
64
+ }
65
+
66
+ export function readSyncCredentials(env = process.env) {
67
+ const bearer = env.FORGELOOP_SYNC_TOKEN ?? "";
68
+ if (!/^[A-Za-z0-9._~+/-]{32,512}$/u.test(bearer)) throw syncError("E_SYNC_CONFIG", "FORGELOOP_SYNC_TOKEN must be set to the sync token (32 or more URL-safe characters)");
69
+ return { token: bearer, passphrase: env.FORGELOOP_SYNC_KEY ?? "" };
70
+ }
71
+
72
+ export async function syncRequest({ remote, repository, token, method, body, headers = {}, fetchImpl = fetch }) {
73
+ const url = new URL(remote);
74
+ url.searchParams.set("repo", repository);
75
+ let response;
76
+ try {
77
+ response = await fetchImpl(url.toString(), {
78
+ method,
79
+ headers: { authorization: `Bearer ${token}`, accept: "application/json", ...headers, ...(body ? { "content-type": "application/json" } : {}) },
80
+ ...(body ? { body } : {}),
81
+ signal: globalThis.AbortSignal.timeout(REQUEST_TIMEOUT_MS),
82
+ });
83
+ } catch (error) {
84
+ throw syncError("E_SYNC_REMOTE", `Sync remote unreachable: ${error.message}`);
85
+ }
86
+ return response;
87
+ }
88
+
89
+ export async function remoteError(response) {
90
+ const detail = await response.json().catch(() => ({}));
91
+ const message = typeof detail?.error === "string" ? detail.error : `HTTP ${response.status}`;
92
+ if (response.status === 412) return syncError("E_SYNC_CONFLICT", `${message}. Run forgeloop sync-pull first.`);
93
+ if (response.status === 401 || response.status === 403) return syncError("E_SYNC_UNAUTHORIZED", message);
94
+ if (response.status === 413) return syncError("E_SYNC_TOO_LARGE", message);
95
+ return syncError("E_SYNC_REMOTE", `Sync remote refused the request: ${message}`);
96
+ }
97
+
98
+ function stateDirectory(env = process.env) {
99
+ const base = env.FORGELOOP_SYNC_STATE_DIR
100
+ || (env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, "forgeloop") : path.join(os.homedir(), ".config", "forgeloop"));
101
+ return path.join(base, "sync");
102
+ }
103
+
104
+ function stateFile(target, env) {
105
+ const key = createHash("sha256").update(path.resolve(target)).digest("hex").slice(0, 32);
106
+ return path.join(stateDirectory(env), `${key}.json`);
107
+ }
108
+
109
+ export async function readSyncState(target, { remote, repository, env = process.env } = {}) {
110
+ try {
111
+ const state = JSON.parse(await readFile(stateFile(target, env), "utf8"));
112
+ return state.remote === remote && state.repository === repository && typeof state.etag === "string" ? state : null;
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ export async function writeSyncState(target, state, { env = process.env } = {}) {
119
+ const file = stateFile(target, env);
120
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
121
+ const temporary = `${file}.${process.pid}.tmp`;
122
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
123
+ await rename(temporary, file);
124
+ }
@@ -0,0 +1,129 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "node:crypto";
2
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { gunzipSync, gzipSync } from "node:zlib";
5
+
6
+ // Cloud-sync snapshots: an attachment-inclusive storage backup directory,
7
+ // packed into JSON, gzipped and encrypted on the client with AES-256-GCM. The
8
+ // key is derived with scrypt from FORGELOOP_SYNC_KEY and never leaves this
9
+ // machine; the repository name is authenticated as associated data, so a
10
+ // snapshot cannot be replayed under another repository.
11
+
12
+ export const SNAPSHOT_KIND = "forgeloop-sync-snapshot";
13
+ export const MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024;
14
+ export const MIN_PASSPHRASE_LENGTH = 16;
15
+ const SCRYPT = Object.freeze({ N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
16
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/u;
17
+
18
+ export function syncError(code, message) {
19
+ return Object.assign(new Error(message), { code });
20
+ }
21
+
22
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
23
+
24
+ // Relative POSIX paths only: no absolute paths, no "." or ".." segments.
25
+ export function isSafeSnapshotPath(value) {
26
+ if (typeof value !== "string" || value.length === 0 || value.length > 512) return false;
27
+ return value.split("/").every((segment) => SAFE_SEGMENT.test(segment) && segment !== "." && segment !== "..");
28
+ }
29
+
30
+ async function listFiles(root, relative = "") {
31
+ const entries = await readdir(path.join(root, relative), { withFileTypes: true });
32
+ const files = [];
33
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
34
+ const child = relative ? `${relative}/${entry.name}` : entry.name;
35
+ if (entry.isDirectory()) files.push(...await listFiles(root, child));
36
+ else if (entry.isFile()) files.push(child);
37
+ else throw syncError("E_SYNC_SNAPSHOT_INVALID", `Backup contains an unsupported entry: ${child}`);
38
+ }
39
+ return files;
40
+ }
41
+
42
+ export async function packDirectory(directory) {
43
+ const files = [];
44
+ for (const name of await listFiles(directory)) {
45
+ if (!isSafeSnapshotPath(name)) throw syncError("E_SYNC_SNAPSHOT_INVALID", `Backup contains an unsafe path: ${name}`);
46
+ const bytes = await readFile(path.join(directory, name));
47
+ files.push({ path: name, sha256: sha256(bytes), data: bytes.toString("base64") });
48
+ }
49
+ return { schemaVersion: 1, files };
50
+ }
51
+
52
+ export async function unpackDirectory(payload, directory) {
53
+ if (!payload || payload.schemaVersion !== 1 || !Array.isArray(payload.files) || payload.files.length === 0) {
54
+ throw syncError("E_SYNC_SNAPSHOT_INVALID", "Snapshot payload has no files");
55
+ }
56
+ const seen = new Set();
57
+ for (const file of payload.files) {
58
+ if (!isSafeSnapshotPath(file?.path) || seen.has(file.path)) throw syncError("E_SYNC_SNAPSHOT_INVALID", "Snapshot payload has an unsafe or duplicate path");
59
+ seen.add(file.path);
60
+ const bytes = Buffer.from(String(file.data ?? ""), "base64");
61
+ if (sha256(bytes) !== file.sha256) throw syncError("E_SYNC_SNAPSHOT_INVALID", `Snapshot file digest mismatch: ${file.path}`);
62
+ const destination = path.join(directory, ...file.path.split("/"));
63
+ await mkdir(path.dirname(destination), { recursive: true });
64
+ await writeFile(destination, bytes, { flag: "wx" });
65
+ }
66
+ return [...seen];
67
+ }
68
+
69
+ function deriveKey(passphrase, salt) {
70
+ return scryptSync(passphrase, salt, 32, SCRYPT);
71
+ }
72
+
73
+ export function assertPassphrase(passphrase) {
74
+ if (typeof passphrase !== "string" || passphrase.length < MIN_PASSPHRASE_LENGTH) {
75
+ throw syncError("E_SYNC_CONFIG", `FORGELOOP_SYNC_KEY must be at least ${MIN_PASSPHRASE_LENGTH} characters`);
76
+ }
77
+ }
78
+
79
+ export function sealSnapshot(payload, { passphrase, repository, forgeloopVersion = null, now = new Date() }) {
80
+ assertPassphrase(passphrase);
81
+ const salt = randomBytes(16);
82
+ const iv = randomBytes(12);
83
+ const cipher = createCipheriv("aes-256-gcm", deriveKey(passphrase, salt), iv);
84
+ cipher.setAAD(Buffer.from(repository, "utf8"));
85
+ const data = Buffer.concat([cipher.update(gzipSync(Buffer.from(JSON.stringify(payload), "utf8"))), cipher.final()]);
86
+ const envelope = {
87
+ schemaVersion: 1,
88
+ kind: SNAPSHOT_KIND,
89
+ repository,
90
+ createdAt: now.toISOString(),
91
+ forgeloopVersion,
92
+ cipher: {
93
+ alg: "aes-256-gcm",
94
+ kdf: "scrypt",
95
+ kdfParams: { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p },
96
+ salt: salt.toString("base64"),
97
+ iv: iv.toString("base64"),
98
+ tag: cipher.getAuthTag().toString("base64"),
99
+ data: data.toString("base64"),
100
+ },
101
+ };
102
+ const body = Buffer.from(JSON.stringify(envelope), "utf8");
103
+ if (body.length > MAX_SNAPSHOT_BYTES) throw syncError("E_SYNC_TOO_LARGE", `Encrypted snapshot is ${body.length} bytes; the limit is ${MAX_SNAPSHOT_BYTES}`);
104
+ return body;
105
+ }
106
+
107
+ export function openSnapshot(body, { passphrase, repository }) {
108
+ assertPassphrase(passphrase);
109
+ let envelope;
110
+ try {
111
+ envelope = JSON.parse(Buffer.from(body).toString("utf8"));
112
+ } catch {
113
+ throw syncError("E_SYNC_SNAPSHOT_INVALID", "Remote snapshot is not valid JSON");
114
+ }
115
+ const cipher = envelope?.cipher;
116
+ if (envelope?.schemaVersion !== 1 || envelope.kind !== SNAPSHOT_KIND || cipher?.alg !== "aes-256-gcm" || cipher.kdf !== "scrypt") {
117
+ throw syncError("E_SYNC_SNAPSHOT_INVALID", "Remote snapshot has an unsupported format");
118
+ }
119
+ if (String(envelope.repository).toLowerCase() !== repository) throw syncError("E_SYNC_SNAPSHOT_INVALID", "Remote snapshot belongs to another repository");
120
+ try {
121
+ const decipher = createDecipheriv("aes-256-gcm", deriveKey(passphrase, Buffer.from(cipher.salt, "base64")), Buffer.from(cipher.iv, "base64"));
122
+ decipher.setAAD(Buffer.from(repository, "utf8"));
123
+ decipher.setAuthTag(Buffer.from(cipher.tag, "base64"));
124
+ const plain = Buffer.concat([decipher.update(Buffer.from(cipher.data, "base64")), decipher.final()]);
125
+ return { envelope, payload: JSON.parse(gunzipSync(plain).toString("utf8")) };
126
+ } catch {
127
+ throw syncError("E_SYNC_SNAPSHOT_INVALID", "Remote snapshot could not be decrypted: wrong FORGELOOP_SYNC_KEY or tampered data");
128
+ }
129
+ }