magpie-multi-usage 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -0
- package/README.md +153 -2
- package/README.zh-CN.md +154 -0
- package/hooks.mjs +31 -0
- package/index.mjs +103 -0
- package/package.json +68 -4
- package/page/boot.js +161 -0
- package/page/icon.svg +6 -0
- package/page/index.html +46 -0
- package/src/aggregator.mjs +643 -0
- package/src/atomic-fs.mjs +207 -0
- package/src/config.mjs +435 -0
- package/src/github-store.mjs +722 -0
- package/src/http-server.mjs +526 -0
- package/src/magpie-client.mjs +670 -0
- package/src/sync-engine.mjs +958 -0
- package/src/ui/app.css +877 -0
- package/src/ui/app.js +869 -0
- package/src/ui/index.html +135 -0
- package/src/ui/view-model.mjs +410 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Create a directory tree if it does not already exist.
|
|
7
|
+
*/
|
|
8
|
+
export async function ensureDir(dirPath, mode = 0o700) {
|
|
9
|
+
await fs.mkdir(dirPath, { recursive: true, mode });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Assert that targetPath stays strictly contained within rootDir.
|
|
14
|
+
*/
|
|
15
|
+
export function assertContainedPath(rootDir, targetPath) {
|
|
16
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
17
|
+
const resolvedTarget = path.resolve(targetPath);
|
|
18
|
+
const prefix = resolvedRoot.endsWith(path.sep) ? resolvedRoot : `${resolvedRoot}${path.sep}`;
|
|
19
|
+
if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(prefix)) {
|
|
20
|
+
const err = new Error(`Path escapes allowed directory: ${targetPath}`);
|
|
21
|
+
err.code = "PATH_TRAVERSAL";
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
return resolvedTarget;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Atomically write UTF-8 text via a unique sibling temp file and rename.
|
|
29
|
+
*/
|
|
30
|
+
export async function writeTextAtomic(filePath, content, { mode = 0o644 } = {}) {
|
|
31
|
+
const dir = path.dirname(filePath);
|
|
32
|
+
await ensureDir(dir, 0o700);
|
|
33
|
+
|
|
34
|
+
const tmpPath = path.join(
|
|
35
|
+
dir,
|
|
36
|
+
`.${path.basename(filePath)}.tmp.${process.pid}.${crypto.randomBytes(6).toString("hex")}`,
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
let handle = null;
|
|
40
|
+
try {
|
|
41
|
+
handle = await fs.open(tmpPath, "wx", mode);
|
|
42
|
+
await handle.writeFile(content, "utf8");
|
|
43
|
+
await handle.sync();
|
|
44
|
+
await handle.close();
|
|
45
|
+
handle = null;
|
|
46
|
+
|
|
47
|
+
if (process.platform !== "win32") {
|
|
48
|
+
await fs.chmod(tmpPath, mode);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
await fs.rename(tmpPath, filePath);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
if (handle) {
|
|
54
|
+
try {
|
|
55
|
+
await handle.close();
|
|
56
|
+
} catch {
|
|
57
|
+
// Ignore close error while unwinding.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await fs.unlink(tmpPath);
|
|
62
|
+
} catch {
|
|
63
|
+
// Ignore cleanup error if temp file was not created.
|
|
64
|
+
}
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Atomically write a JSON document with a trailing newline.
|
|
71
|
+
*/
|
|
72
|
+
export async function writeJsonAtomic(filePath, value, { mode = 0o644, pretty = true } = {}) {
|
|
73
|
+
const serialized = `${JSON.stringify(value, null, pretty ? 2 : 0)}\n`;
|
|
74
|
+
await writeTextAtomic(filePath, serialized, { mode });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Strictly read and parse a JSON file.
|
|
79
|
+
*
|
|
80
|
+
* Returns a discriminated union so callers never confuse missing files with
|
|
81
|
+
* unreadable or corrupted JSON:
|
|
82
|
+
* - { status: "ok", value }
|
|
83
|
+
* - { status: "missing" }
|
|
84
|
+
* - { status: "error", code: "IO_ERROR" | "PARSE_ERROR", error }
|
|
85
|
+
*/
|
|
86
|
+
export async function readJsonStrict(filePath) {
|
|
87
|
+
let raw;
|
|
88
|
+
try {
|
|
89
|
+
raw = await fs.readFile(filePath, "utf8");
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error && error.code === "ENOENT") {
|
|
92
|
+
return { status: "missing" };
|
|
93
|
+
}
|
|
94
|
+
return { status: "error", code: "IO_ERROR", error };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
const value = JSON.parse(raw);
|
|
99
|
+
return { status: "ok", value };
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return { status: "error", code: "PARSE_ERROR", error };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Acquire a cooperative cross-process lockfile to serialize ledger and state
|
|
107
|
+
* mutations across concurrent hosts, hooks, and refreshes.
|
|
108
|
+
*/
|
|
109
|
+
export async function withFileLock(
|
|
110
|
+
lockPath,
|
|
111
|
+
fn,
|
|
112
|
+
{ timeoutMs = 15000, staleMs = 60000, pollMs = 20 } = {},
|
|
113
|
+
) {
|
|
114
|
+
await ensureDir(path.dirname(lockPath), 0o700);
|
|
115
|
+
const deadline = Date.now() + timeoutMs;
|
|
116
|
+
|
|
117
|
+
while (true) {
|
|
118
|
+
try {
|
|
119
|
+
const handle = await fs.open(lockPath, "wx", 0o600);
|
|
120
|
+
try {
|
|
121
|
+
await handle.writeFile(
|
|
122
|
+
JSON.stringify({ pid: process.pid, acquiredAt: new Date().toISOString() }),
|
|
123
|
+
"utf8",
|
|
124
|
+
);
|
|
125
|
+
} finally {
|
|
126
|
+
await handle.close();
|
|
127
|
+
}
|
|
128
|
+
break;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
if (!err || err.code !== "EEXIST") {
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
const stat = await fs.stat(lockPath);
|
|
136
|
+
if (Date.now() - stat.mtimeMs > staleMs) {
|
|
137
|
+
await fs.unlink(lockPath).catch(() => {});
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
} catch (statErr) {
|
|
141
|
+
if (statErr?.code === "ENOENT") {
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (Date.now() >= deadline) {
|
|
147
|
+
const timeoutErr = new Error(`Timed out waiting for lock ${lockPath}`);
|
|
148
|
+
timeoutErr.code = "LOCK_TIMEOUT";
|
|
149
|
+
throw timeoutErr;
|
|
150
|
+
}
|
|
151
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
return await fn();
|
|
157
|
+
} finally {
|
|
158
|
+
await fs.unlink(lockPath).catch(() => {});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Recursively canonicalize JSON values with lexicographically sorted object keys,
|
|
164
|
+
* preserving reserved own keys such as "__proto__" without prototype mutation.
|
|
165
|
+
*/
|
|
166
|
+
function canonicalizeValue(value) {
|
|
167
|
+
if (Array.isArray(value)) {
|
|
168
|
+
return value.map(canonicalizeValue);
|
|
169
|
+
}
|
|
170
|
+
if (value !== null && typeof value === "object") {
|
|
171
|
+
const sorted = Object.create(null);
|
|
172
|
+
for (const key of Object.keys(value).sort()) {
|
|
173
|
+
const next = value[key];
|
|
174
|
+
if (next !== undefined) {
|
|
175
|
+
Object.defineProperty(sorted, key, {
|
|
176
|
+
value: canonicalizeValue(next),
|
|
177
|
+
enumerable: true,
|
|
178
|
+
configurable: true,
|
|
179
|
+
writable: true,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return sorted;
|
|
184
|
+
}
|
|
185
|
+
return value;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Produce deterministic JSON string output independent of object key order.
|
|
190
|
+
*/
|
|
191
|
+
export function canonicalJson(value) {
|
|
192
|
+
return JSON.stringify(canonicalizeValue(value));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Compute lowercase hex SHA-256 over a UTF-8 string or Buffer.
|
|
197
|
+
*/
|
|
198
|
+
export function sha256Hex(input) {
|
|
199
|
+
return crypto.createHash("sha256").update(input, "utf8").digest("hex");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Compute deterministic lowercase hex SHA-256 over canonical JSON.
|
|
204
|
+
*/
|
|
205
|
+
export function sha256CanonicalJson(value) {
|
|
206
|
+
return sha256Hex(canonicalJson(value));
|
|
207
|
+
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { ensureDir, readJsonStrict, writeJsonAtomic } from "./atomic-fs.mjs";
|
|
5
|
+
|
|
6
|
+
export const PLUGIN_ID = "magpie-multi-usage";
|
|
7
|
+
export const GITHUB_TOKEN_ENV = "MAGPIE_MULTI_USAGE_GITHUB_TOKEN";
|
|
8
|
+
export const DATA_DIR_ENV = "MAGPIE_MULTI_USAGE_DATA_DIR";
|
|
9
|
+
export const MAGPIE_CONFIG_DIR_ENV = "MAGPIE_CONFIG_DIR";
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_CONFIG = Object.freeze({
|
|
12
|
+
port: 18792,
|
|
13
|
+
deviceName: "",
|
|
14
|
+
lang: "auto",
|
|
15
|
+
repo: "",
|
|
16
|
+
branch: "",
|
|
17
|
+
prefix: "devices",
|
|
18
|
+
pushEnabled: true,
|
|
19
|
+
pushIntervalSec: 300,
|
|
20
|
+
filterForwarded: true,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const ALLOWED_LANGS = new Set(["auto", "en", "zh"]);
|
|
24
|
+
|
|
25
|
+
const REPO_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
|
|
26
|
+
const BRANCH_PATTERN = /^[A-Za-z0-9._/-]{1,128}$/;
|
|
27
|
+
const PREFIX_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
28
|
+
const CONTROL_CHARS_STRIP_PATTERN = /[\u0000-\u001f\u007f]/g;
|
|
29
|
+
const CONTROL_CHARS_TEST_PATTERN = /[\u0000-\u001f\u007f]/;
|
|
30
|
+
|
|
31
|
+
export class ConfigError extends Error {
|
|
32
|
+
constructor(code, message, options) {
|
|
33
|
+
super(message, options);
|
|
34
|
+
this.name = "ConfigError";
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Resolve Magpie's configuration directory (strictly read-only by this plugin).
|
|
41
|
+
*/
|
|
42
|
+
export function resolveMagpieConfigDir({ env = process.env, homeDir = os.homedir() } = {}) {
|
|
43
|
+
const explicit = typeof env[MAGPIE_CONFIG_DIR_ENV] === "string"
|
|
44
|
+
? env[MAGPIE_CONFIG_DIR_ENV].trim()
|
|
45
|
+
: "";
|
|
46
|
+
if (explicit) {
|
|
47
|
+
return path.resolve(explicit);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const xdg = typeof env.XDG_CONFIG_HOME === "string" ? env.XDG_CONFIG_HOME.trim() : "";
|
|
51
|
+
if (xdg) {
|
|
52
|
+
return path.resolve(xdg, "magpie");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return path.resolve(homeDir, ".config", "magpie");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Deterministically resolve this plugin's dedicated data directory outside
|
|
60
|
+
* ~/.config/magpie so index.mjs and hooks.mjs always share the exact same
|
|
61
|
+
* storage without writing into Magpie's settings directory.
|
|
62
|
+
*
|
|
63
|
+
* Precedence:
|
|
64
|
+
* 1. env.MAGPIE_MULTI_USAGE_DATA_DIR
|
|
65
|
+
* 2. options.dataDir
|
|
66
|
+
* 3. OS user data directory ($XDG_DATA_HOME/magpie-multi-usage,
|
|
67
|
+
* ~/.local/share/magpie-multi-usage, or %LOCALAPPDATA%\magpie-multi-usage)
|
|
68
|
+
*/
|
|
69
|
+
export function resolveDataDir({
|
|
70
|
+
optionDataDir = "",
|
|
71
|
+
env = process.env,
|
|
72
|
+
homeDir = os.homedir(),
|
|
73
|
+
platform = process.platform,
|
|
74
|
+
} = {}) {
|
|
75
|
+
const envDir = typeof env[DATA_DIR_ENV] === "string" ? env[DATA_DIR_ENV].trim() : "";
|
|
76
|
+
if (envDir) {
|
|
77
|
+
return path.resolve(envDir);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (typeof optionDataDir === "string" && optionDataDir.trim()) {
|
|
81
|
+
return path.resolve(optionDataDir.trim());
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (platform === "win32") {
|
|
85
|
+
const localAppData = typeof env.LOCALAPPDATA === "string" ? env.LOCALAPPDATA.trim() : "";
|
|
86
|
+
if (localAppData) {
|
|
87
|
+
return path.resolve(localAppData, PLUGIN_ID);
|
|
88
|
+
}
|
|
89
|
+
return path.resolve(homeDir, "AppData", "Local", PLUGIN_ID);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const xdgData = typeof env.XDG_DATA_HOME === "string" ? env.XDG_DATA_HOME.trim() : "";
|
|
93
|
+
if (xdgData) {
|
|
94
|
+
return path.resolve(xdgData, PLUGIN_ID);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return path.resolve(homeDir, ".local", "share", PLUGIN_ID);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function getConfigPaths(dataDir) {
|
|
101
|
+
const root = path.resolve(dataDir);
|
|
102
|
+
return {
|
|
103
|
+
root,
|
|
104
|
+
configFile: path.join(root, "config.json"),
|
|
105
|
+
credentialsFile: path.join(root, "credentials.json"),
|
|
106
|
+
stateFile: path.join(root, "state.json"),
|
|
107
|
+
syncLockFile: path.join(root, ".sync.lock"),
|
|
108
|
+
localMonthsDir: path.join(root, "local-months"),
|
|
109
|
+
localRowIndexFile: path.join(root, "local-row-index.json"),
|
|
110
|
+
remoteCacheDir: path.join(root, "remote-cache"),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function normalizeRepo(value) {
|
|
115
|
+
if (value === undefined || value === null) {
|
|
116
|
+
return "";
|
|
117
|
+
}
|
|
118
|
+
if (typeof value !== "string") {
|
|
119
|
+
throw new ConfigError("INVALID_REPO", "Repository must be a string in owner/repo format.");
|
|
120
|
+
}
|
|
121
|
+
const trimmed = value.trim();
|
|
122
|
+
if (!trimmed) {
|
|
123
|
+
return "";
|
|
124
|
+
}
|
|
125
|
+
if (!REPO_PATTERN.test(trimmed) || trimmed.includes("..")) {
|
|
126
|
+
throw new ConfigError("INVALID_REPO", "Repository must use owner/repo format without path traversal.");
|
|
127
|
+
}
|
|
128
|
+
const [owner, repo] = trimmed.split("/");
|
|
129
|
+
if (owner === "." || owner === ".." || repo === "." || repo === "..") {
|
|
130
|
+
throw new ConfigError("INVALID_REPO", "Repository must use valid owner and repo names.");
|
|
131
|
+
}
|
|
132
|
+
return trimmed;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function normalizeBranch(value) {
|
|
136
|
+
if (value === undefined || value === null) {
|
|
137
|
+
return "";
|
|
138
|
+
}
|
|
139
|
+
if (typeof value !== "string") {
|
|
140
|
+
throw new ConfigError("INVALID_BRANCH", "Branch name must be a string.");
|
|
141
|
+
}
|
|
142
|
+
const trimmed = value.trim();
|
|
143
|
+
if (!trimmed) {
|
|
144
|
+
return "";
|
|
145
|
+
}
|
|
146
|
+
if (
|
|
147
|
+
!BRANCH_PATTERN.test(trimmed) ||
|
|
148
|
+
trimmed.startsWith("/") ||
|
|
149
|
+
trimmed.endsWith("/") ||
|
|
150
|
+
trimmed.startsWith("-") ||
|
|
151
|
+
trimmed.includes("..") ||
|
|
152
|
+
trimmed.includes("//") ||
|
|
153
|
+
trimmed.endsWith(".lock")
|
|
154
|
+
) {
|
|
155
|
+
throw new ConfigError("INVALID_BRANCH", "Branch name contains invalid git ref characters.");
|
|
156
|
+
}
|
|
157
|
+
return trimmed;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function normalizePrefix(value) {
|
|
161
|
+
if (value === undefined || value === null) {
|
|
162
|
+
return DEFAULT_CONFIG.prefix;
|
|
163
|
+
}
|
|
164
|
+
if (typeof value !== "string") {
|
|
165
|
+
throw new ConfigError("INVALID_PREFIX", "Folder prefix must be a string.");
|
|
166
|
+
}
|
|
167
|
+
const trimmed = value.trim().replace(/^\/+|\/+$/g, "");
|
|
168
|
+
if (!trimmed) {
|
|
169
|
+
return DEFAULT_CONFIG.prefix;
|
|
170
|
+
}
|
|
171
|
+
if (trimmed.includes("\\")) {
|
|
172
|
+
throw new ConfigError("INVALID_PREFIX", "Folder prefix must use forward slashes.");
|
|
173
|
+
}
|
|
174
|
+
const segments = trimmed.split("/");
|
|
175
|
+
for (const segment of segments) {
|
|
176
|
+
if (!segment || segment === "." || segment === ".." || !PREFIX_SEGMENT_PATTERN.test(segment)) {
|
|
177
|
+
throw new ConfigError("INVALID_PREFIX", "Folder prefix contains invalid path segments.");
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return segments.join("/");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function normalizeDeviceName(value) {
|
|
184
|
+
if (value === undefined || value === null) {
|
|
185
|
+
return "";
|
|
186
|
+
}
|
|
187
|
+
if (typeof value !== "string") {
|
|
188
|
+
throw new ConfigError("INVALID_DEVICE_NAME", "Device name must be a string.");
|
|
189
|
+
}
|
|
190
|
+
return value.replace(CONTROL_CHARS_STRIP_PATTERN, "").trim().slice(0, 80);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function normalizeLang(value, fallback = DEFAULT_CONFIG.lang) {
|
|
194
|
+
if (value === undefined || value === null || value === "") {
|
|
195
|
+
return fallback;
|
|
196
|
+
}
|
|
197
|
+
if (typeof value !== "string") {
|
|
198
|
+
throw new ConfigError("INVALID_LANG", "Language must be auto, en, or zh.");
|
|
199
|
+
}
|
|
200
|
+
const normalized = value.trim().toLowerCase();
|
|
201
|
+
if (!ALLOWED_LANGS.has(normalized)) {
|
|
202
|
+
throw new ConfigError("INVALID_LANG", "Language must be auto, en, or zh.");
|
|
203
|
+
}
|
|
204
|
+
return normalized;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function normalizePort(value, fallback = DEFAULT_CONFIG.port) {
|
|
208
|
+
if (value === undefined || value === null || value === "") {
|
|
209
|
+
return fallback;
|
|
210
|
+
}
|
|
211
|
+
const parsed = Number(value);
|
|
212
|
+
if (!Number.isInteger(parsed) || parsed < 1024 || parsed > 65535) {
|
|
213
|
+
throw new ConfigError("INVALID_PORT", "Port must be an integer between 1024 and 65535.");
|
|
214
|
+
}
|
|
215
|
+
return parsed;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function normalizePushIntervalSec(value, fallback = DEFAULT_CONFIG.pushIntervalSec) {
|
|
219
|
+
if (value === undefined || value === null || value === "") {
|
|
220
|
+
return fallback;
|
|
221
|
+
}
|
|
222
|
+
const parsed = Number(value);
|
|
223
|
+
if (!Number.isInteger(parsed) || parsed < 30 || parsed > 86400) {
|
|
224
|
+
throw new ConfigError("INVALID_PUSH_INTERVAL", "Push interval must be an integer between 30 and 86400 seconds.");
|
|
225
|
+
}
|
|
226
|
+
return parsed;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function normalizeBoolean(value, fieldName, fallback) {
|
|
230
|
+
if (value === undefined || value === null) {
|
|
231
|
+
return fallback;
|
|
232
|
+
}
|
|
233
|
+
if (typeof value !== "boolean") {
|
|
234
|
+
throw new ConfigError("INVALID_BOOLEAN", `${fieldName} must be a boolean.`);
|
|
235
|
+
}
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Validate a GitHub PAT before persistence so malformed values fail upfront.
|
|
241
|
+
*/
|
|
242
|
+
export function validateGitHubToken(token) {
|
|
243
|
+
if (typeof token !== "string" || !token.trim()) {
|
|
244
|
+
throw new ConfigError("INVALID_TOKEN", "GitHub token must be a non-empty string.");
|
|
245
|
+
}
|
|
246
|
+
const trimmed = token.trim();
|
|
247
|
+
if (CONTROL_CHARS_TEST_PATTERN.test(trimmed) || /\s/.test(trimmed)) {
|
|
248
|
+
throw new ConfigError("INVALID_TOKEN", "GitHub token contains invalid whitespace or control characters.");
|
|
249
|
+
}
|
|
250
|
+
return trimmed;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Normalize and allowlist configuration fields.
|
|
255
|
+
* Unknown and secret-bearing fields (e.g., token, githubToken, pat) are dropped.
|
|
256
|
+
*/
|
|
257
|
+
export function sanitizeConfig(raw = {}, base = DEFAULT_CONFIG) {
|
|
258
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
259
|
+
throw new ConfigError("INVALID_CONFIG", "Configuration must be a plain object.");
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
port: raw.port !== undefined ? normalizePort(raw.port, base.port) : base.port,
|
|
263
|
+
deviceName: raw.deviceName !== undefined ? normalizeDeviceName(raw.deviceName) : base.deviceName,
|
|
264
|
+
lang: raw.lang !== undefined ? normalizeLang(raw.lang, base.lang) : (base.lang ?? DEFAULT_CONFIG.lang),
|
|
265
|
+
repo: raw.repo !== undefined ? normalizeRepo(raw.repo) : base.repo,
|
|
266
|
+
branch: raw.branch !== undefined ? normalizeBranch(raw.branch) : base.branch,
|
|
267
|
+
prefix: raw.prefix !== undefined ? normalizePrefix(raw.prefix) : base.prefix,
|
|
268
|
+
pushEnabled: normalizeBoolean(raw.pushEnabled, "pushEnabled", base.pushEnabled),
|
|
269
|
+
pushIntervalSec: raw.pushIntervalSec !== undefined
|
|
270
|
+
? normalizePushIntervalSec(raw.pushIntervalSec, base.pushIntervalSec)
|
|
271
|
+
: base.pushIntervalSec,
|
|
272
|
+
filterForwarded: normalizeBoolean(raw.filterForwarded, "filterForwarded", base.filterForwarded),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Load non-sensitive plugin configuration from <dataDir>/config.json.
|
|
278
|
+
* Throws if config.json exists but cannot be read or parsed (never silently resets).
|
|
279
|
+
*/
|
|
280
|
+
export async function loadConfig(dataDir, { defaults = {} } = {}) {
|
|
281
|
+
const base = sanitizeConfig(defaults, DEFAULT_CONFIG);
|
|
282
|
+
const { configFile } = getConfigPaths(dataDir);
|
|
283
|
+
const result = await readJsonStrict(configFile);
|
|
284
|
+
|
|
285
|
+
if (result.status === "missing") {
|
|
286
|
+
return base;
|
|
287
|
+
}
|
|
288
|
+
if (result.status === "error") {
|
|
289
|
+
throw new ConfigError(
|
|
290
|
+
"CONFIG_READ_ERROR",
|
|
291
|
+
`Failed to read plugin config at ${configFile}: ${result.code}`,
|
|
292
|
+
{ cause: result.error },
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return sanitizeConfig(result.value, base);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Merge and persist non-sensitive configuration atomically to <dataDir>/config.json.
|
|
301
|
+
*/
|
|
302
|
+
export async function saveConfig(dataDir, patch, { defaults = {} } = {}) {
|
|
303
|
+
const current = await loadConfig(dataDir, { defaults });
|
|
304
|
+
const next = sanitizeConfig(patch, current);
|
|
305
|
+
const { root, configFile } = getConfigPaths(dataDir);
|
|
306
|
+
await ensureDir(root, 0o700);
|
|
307
|
+
await writeJsonAtomic(configFile, next, { mode: 0o600 });
|
|
308
|
+
return next;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Return a non-reversible masked hint for UI display.
|
|
313
|
+
*/
|
|
314
|
+
export function maskToken(token) {
|
|
315
|
+
if (typeof token !== "string") {
|
|
316
|
+
return "";
|
|
317
|
+
}
|
|
318
|
+
const trimmed = token.trim();
|
|
319
|
+
if (!trimmed) {
|
|
320
|
+
return "";
|
|
321
|
+
}
|
|
322
|
+
if (trimmed.length <= 8) {
|
|
323
|
+
return "***";
|
|
324
|
+
}
|
|
325
|
+
return `${trimmed.slice(0, 4)}...${trimmed.slice(-4)}`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Load the GitHub PAT from environment variable or 0600 credentials.json.
|
|
330
|
+
* Rejects group/world-accessible credential files on POSIX and throws on
|
|
331
|
+
* unreadable/corrupt credentials.json rather than silently returning empty.
|
|
332
|
+
*/
|
|
333
|
+
export async function loadGitHubToken(dataDir, { env = process.env } = {}) {
|
|
334
|
+
const envToken = typeof env[GITHUB_TOKEN_ENV] === "string" ? env[GITHUB_TOKEN_ENV].trim() : "";
|
|
335
|
+
if (envToken) {
|
|
336
|
+
return { token: validateGitHubToken(envToken), source: "env" };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const { credentialsFile } = getConfigPaths(dataDir);
|
|
340
|
+
if (process.platform !== "win32") {
|
|
341
|
+
try {
|
|
342
|
+
const stat = await fs.stat(credentialsFile);
|
|
343
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
344
|
+
throw new ConfigError(
|
|
345
|
+
"CREDENTIALS_INSECURE_PERMISSIONS",
|
|
346
|
+
`Refusing to read ${credentialsFile} with mode ${(stat.mode & 0o777).toString(8)}; expected 0600.`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (error instanceof ConfigError) {
|
|
351
|
+
throw error;
|
|
352
|
+
}
|
|
353
|
+
if (error && error.code !== "ENOENT") {
|
|
354
|
+
throw new ConfigError("CREDENTIALS_READ_ERROR", `Failed to stat ${credentialsFile}.`, { cause: error });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const result = await readJsonStrict(credentialsFile);
|
|
360
|
+
if (result.status === "missing") {
|
|
361
|
+
return { token: "", source: "none" };
|
|
362
|
+
}
|
|
363
|
+
if (result.status === "error") {
|
|
364
|
+
throw new ConfigError(
|
|
365
|
+
"CREDENTIALS_READ_ERROR",
|
|
366
|
+
`Failed to read credentials file at ${credentialsFile}: ${result.code}`,
|
|
367
|
+
{ cause: result.error },
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
if (result.value === null || typeof result.value !== "object" || Array.isArray(result.value)) {
|
|
371
|
+
throw new ConfigError("CREDENTIALS_INVALID", "Credentials file must contain a JSON object.");
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const rawToken = result.value.githubToken;
|
|
375
|
+
if (rawToken !== undefined && typeof rawToken !== "string") {
|
|
376
|
+
throw new ConfigError("CREDENTIALS_INVALID", "Stored githubToken must be a string.");
|
|
377
|
+
}
|
|
378
|
+
const trimmed = typeof rawToken === "string" ? rawToken.trim() : "";
|
|
379
|
+
return {
|
|
380
|
+
token: trimmed ? validateGitHubToken(trimmed) : "",
|
|
381
|
+
source: trimmed ? "file" : "none",
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Persist the GitHub PAT strictly to <dataDir>/credentials.json with mode 0600.
|
|
387
|
+
*/
|
|
388
|
+
export async function saveGitHubToken(dataDir, token) {
|
|
389
|
+
const trimmed = validateGitHubToken(token);
|
|
390
|
+
|
|
391
|
+
const { root, credentialsFile } = getConfigPaths(dataDir);
|
|
392
|
+
await ensureDir(root, 0o700);
|
|
393
|
+
await writeJsonAtomic(
|
|
394
|
+
credentialsFile,
|
|
395
|
+
{
|
|
396
|
+
githubToken: trimmed,
|
|
397
|
+
updatedAt: new Date().toISOString(),
|
|
398
|
+
},
|
|
399
|
+
{ mode: 0o600 },
|
|
400
|
+
);
|
|
401
|
+
return {
|
|
402
|
+
tokenConfigured: true,
|
|
403
|
+
tokenHint: maskToken(trimmed),
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Remove <dataDir>/credentials.json if present.
|
|
409
|
+
*/
|
|
410
|
+
export async function clearGitHubToken(dataDir) {
|
|
411
|
+
const { credentialsFile } = getConfigPaths(dataDir);
|
|
412
|
+
try {
|
|
413
|
+
await fs.unlink(credentialsFile);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (!error || error.code !== "ENOENT") {
|
|
416
|
+
throw error;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Build the safe, non-sensitive config payload exposed to GET /api/config.
|
|
423
|
+
* Never includes the raw GitHub PAT.
|
|
424
|
+
*/
|
|
425
|
+
export async function getPublicConfigView(dataDir, { deviceId = "", defaults = {}, env = process.env } = {}) {
|
|
426
|
+
const config = await loadConfig(dataDir, { defaults });
|
|
427
|
+
const cred = await loadGitHubToken(dataDir, { env });
|
|
428
|
+
return {
|
|
429
|
+
...config,
|
|
430
|
+
deviceId,
|
|
431
|
+
tokenConfigured: Boolean(cred.token),
|
|
432
|
+
tokenSource: cred.source,
|
|
433
|
+
tokenHint: maskToken(cred.token),
|
|
434
|
+
};
|
|
435
|
+
}
|