@cassiomc1/forgeloop 2.1.0 → 2.2.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.
@@ -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
+ }