conare 0.19.0 → 0.20.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,289 @@
1
+ // The background schedule: `conare sync --quiet` every 10 minutes, from a copy of the built
2
+ // package under ~/.conare/sync/<version>/ so it does not depend on the npx cache.
3
+ // macOS: a launchd agent. Linux: a systemd user timer.
4
+ import { execFileSync } from "node:child_process";
5
+ import { cpSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { basename, delimiter, join, resolve } from "node:path";
8
+ export const LABEL = "ai.conare.sync";
9
+ export const UNIT = "conare-sync";
10
+ export const INTERVAL_SECONDS = 600;
11
+ function command(job) {
12
+ return [...(job.via ? [job.via] : []), job.node, job.script, "sync", "--quiet"];
13
+ }
14
+ /** Variables passed on to the scheduled run when set at install time. */
15
+ export const PASSED_ENV = ["CONARE_BASE_URL", "CLAUDE_CONFIG_DIR", "CODEX_HOME"];
16
+ /**
17
+ * Copy the built package (the directory holding index.js and cli/) to <root>/<version> and
18
+ * return the installed script path. The copy is made beside the target, checked file by file
19
+ * against the source (same files, same sizes, nothing empty that was not), and only then
20
+ * moved into place, so the schedule never points at an empty or partial copy. Other versions
21
+ * stay until the new schedule is loaded (pruneVersions), so a failed reinstall leaves the
22
+ * running schedule its script.
23
+ */
24
+ export function installCopy(distDir, root, version) {
25
+ if (!existsSync(join(distDir, "cli", "main.js")) || !existsSync(join(distDir, "index.js"))) {
26
+ throw new Error("Install from the published package: npx conare sync --install (or bunx conare sync --install)");
27
+ }
28
+ const target = join(root, version);
29
+ const script = join(target, "cli", "main.js");
30
+ if (resolve(distDir) === resolve(target) || copyMatches(distDir, target))
31
+ return script;
32
+ mkdirSync(root, { recursive: true });
33
+ const staging = join(root, `.staging-${version}-${process.pid}`);
34
+ rmSync(staging, { recursive: true, force: true });
35
+ try {
36
+ cpSync(distDir, staging, { recursive: true });
37
+ // The files are ES modules; outside the package, Node needs to be told.
38
+ writeFileSync(join(staging, "package.json"), PACKAGE_JSON);
39
+ const problem = compareTrees(distDir, staging);
40
+ if (problem)
41
+ throw new Error(`The copy in ${staging} is incomplete (${problem}); nothing was installed.`);
42
+ rmSync(target, { recursive: true, force: true });
43
+ renameSync(staging, target);
44
+ }
45
+ finally {
46
+ rmSync(staging, { recursive: true, force: true });
47
+ }
48
+ return script;
49
+ }
50
+ const PACKAGE_JSON = `${JSON.stringify({ type: "module", private: true })}\n`;
51
+ /** True when target already holds an exact copy of distDir (a reinstall of the same version). */
52
+ function copyMatches(distDir, target) {
53
+ return existsSync(target) && compareTrees(distDir, target) === undefined;
54
+ }
55
+ /** Undefined when every file of src is in dst with the same size; else what differs. */
56
+ export function compareTrees(src, dst) {
57
+ const a = sizes(src);
58
+ const b = sizes(dst);
59
+ if (a.size === 0)
60
+ return "the source is empty";
61
+ for (const [path, size] of a) {
62
+ if (path === "package.json")
63
+ continue; // the copy writes its own
64
+ const got = b.get(path);
65
+ if (got === undefined)
66
+ return `${path} is missing`;
67
+ if (got !== size)
68
+ return `${path} is ${got} bytes, not ${size}`;
69
+ }
70
+ return undefined;
71
+ }
72
+ function sizes(dir) {
73
+ const out = new Map();
74
+ const walk = (d, prefix) => {
75
+ let entries;
76
+ try {
77
+ entries = readdirSync(d, { withFileTypes: true });
78
+ }
79
+ catch {
80
+ return;
81
+ }
82
+ for (const e of entries) {
83
+ const rel = prefix ? `${prefix}/${e.name}` : e.name;
84
+ if (e.isDirectory())
85
+ walk(join(d, e.name), rel);
86
+ else if (e.isFile())
87
+ out.set(rel, statSync(join(d, e.name)).size);
88
+ }
89
+ };
90
+ walk(dir, "");
91
+ return out;
92
+ }
93
+ /**
94
+ * The runtime to schedule: a PATH entry that resolves to the running node or bun (e.g.
95
+ * /opt/homebrew/bin/node rather than its versioned Cellar path, which an upgrade deletes),
96
+ * else the running binary itself.
97
+ */
98
+ export function stableRuntime(execPath, pathEnv = process.env.PATH ?? "") {
99
+ let real;
100
+ try {
101
+ real = realpathSync(execPath);
102
+ }
103
+ catch {
104
+ return execPath;
105
+ }
106
+ const name = basename(execPath);
107
+ for (const dir of pathEnv.split(delimiter)) {
108
+ if (!dir)
109
+ continue;
110
+ const candidate = join(dir, name);
111
+ try {
112
+ if (realpathSync(candidate) === real)
113
+ return candidate;
114
+ }
115
+ catch {
116
+ // Not in this directory.
117
+ }
118
+ }
119
+ return execPath;
120
+ }
121
+ /** Remove every installed version but `version`, once the schedule runs it. */
122
+ export function pruneVersions(root, version) {
123
+ for (const entry of readdirSync(root)) {
124
+ if (entry.startsWith(".staging-"))
125
+ continue; // another install in progress
126
+ if (entry !== version)
127
+ rmSync(join(root, entry), { recursive: true, force: true });
128
+ }
129
+ }
130
+ // ---- launchd ---------------------------------------------------------------
131
+ export function launchdPlistPath(home = homedir()) {
132
+ return join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
133
+ }
134
+ export function launchdPlist(job) {
135
+ const args = command(job).map((a) => ` <string>${xml(a)}</string>`).join("\n");
136
+ const env = Object.entries(job.env)
137
+ .map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
138
+ .join("\n");
139
+ return `<?xml version="1.0" encoding="UTF-8"?>
140
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
141
+ <plist version="1.0">
142
+ <dict>
143
+ <key>Label</key>
144
+ <string>${LABEL}</string>
145
+ <key>ProgramArguments</key>
146
+ <array>
147
+ ${args}
148
+ </array>
149
+ <key>StartInterval</key>
150
+ <integer>${INTERVAL_SECONDS}</integer>
151
+ <key>RunAtLoad</key>
152
+ <true/>
153
+ <key>ProcessType</key>
154
+ <string>Background</string>
155
+ <key>StandardOutPath</key>
156
+ <string>${xml(job.logFile)}</string>
157
+ <key>StandardErrorPath</key>
158
+ <string>${xml(job.logFile)}</string>
159
+ ${env ? ` <key>EnvironmentVariables</key>\n <dict>\n${env}\n </dict>\n` : ""}</dict>
160
+ </plist>
161
+ `;
162
+ }
163
+ function xml(s) {
164
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
165
+ }
166
+ // ---- systemd ---------------------------------------------------------------
167
+ export function systemdDir(env = process.env, home = homedir()) {
168
+ return join(env.XDG_CONFIG_HOME || join(home, ".config"), "systemd", "user");
169
+ }
170
+ export function systemdService(job) {
171
+ const exec = command(job).map(quoteArg).join(" ");
172
+ const env = Object.entries(job.env).map(([k, v]) => `Environment=${quoteArg(`${k}=${v}`)}\n`).join("");
173
+ return `[Unit]
174
+ Description=Conare sync of Claude Code and Codex sessions
175
+
176
+ [Service]
177
+ Type=oneshot
178
+ ExecStart=${exec}
179
+ ${env}StandardOutput=append:${unitPath(job.logFile)}
180
+ StandardError=append:${unitPath(job.logFile)}
181
+ Nice=10
182
+ `;
183
+ }
184
+ export function systemdTimer() {
185
+ return `[Unit]
186
+ Description=Run the Conare sync every 10 minutes
187
+
188
+ [Timer]
189
+ OnCalendar=*:0/10
190
+ Persistent=true
191
+
192
+ [Install]
193
+ WantedBy=timers.target
194
+ `;
195
+ }
196
+ /** A double-quoted systemd argument: quotes and backslashes escaped, % doubled (specifiers). */
197
+ function quoteArg(s) {
198
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
199
+ }
200
+ function unitPath(s) {
201
+ return s.replace(/%/g, "%%");
202
+ }
203
+ const run = (cmd, args) => {
204
+ execFileSync(cmd, args, { stdio: "ignore" });
205
+ };
206
+ function tryRun(r, cmd, args) {
207
+ try {
208
+ r(cmd, args);
209
+ return true;
210
+ }
211
+ catch {
212
+ return false;
213
+ }
214
+ }
215
+ /** Write and load the schedule. Returns a short description of what was installed. */
216
+ export function installSchedule(job, s) {
217
+ const r = s.run ?? run;
218
+ const home = s.home ?? homedir();
219
+ if (s.platform === "darwin") {
220
+ const plist = launchdPlistPath(home);
221
+ mkdirSync(join(home, "Library", "LaunchAgents"), { recursive: true });
222
+ writeFileSync(plist, launchdPlist(job));
223
+ const domain = `gui/${s.uid ?? process.getuid?.() ?? 0}`;
224
+ tryRun(r, "launchctl", ["bootout", `${domain}/${LABEL}`]);
225
+ if (!tryRun(r, "launchctl", ["bootstrap", domain, plist]))
226
+ r("launchctl", ["load", "-w", plist]);
227
+ return `launchd agent ${plist}`;
228
+ }
229
+ if (s.platform === "linux") {
230
+ const dir = systemdDir(s.env, home);
231
+ mkdirSync(dir, { recursive: true });
232
+ writeFileSync(join(dir, `${UNIT}.service`), systemdService(job));
233
+ writeFileSync(join(dir, `${UNIT}.timer`), systemdTimer());
234
+ r("systemctl", ["--user", "daemon-reload"]);
235
+ r("systemctl", ["--user", "enable", "--now", `${UNIT}.timer`]);
236
+ return `systemd user timer ${join(dir, `${UNIT}.timer`)}`;
237
+ }
238
+ throw new Error(`--install supports macOS and Linux. On ${s.platform}, run \`npx conare sync --quiet\` every 10 minutes with your scheduler.`);
239
+ }
240
+ /** Stop and remove the schedule. Returns false when there was nothing to remove. */
241
+ export function uninstallSchedule(s) {
242
+ const r = s.run ?? run;
243
+ const home = s.home ?? homedir();
244
+ if (s.platform === "darwin") {
245
+ const plist = launchdPlistPath(home);
246
+ const domain = `gui/${s.uid ?? process.getuid?.() ?? 0}`;
247
+ if (!tryRun(r, "launchctl", ["bootout", `${domain}/${LABEL}`]))
248
+ tryRun(r, "launchctl", ["unload", plist]);
249
+ return remove(plist);
250
+ }
251
+ if (s.platform === "linux") {
252
+ const dir = systemdDir(s.env, home);
253
+ tryRun(r, "systemctl", ["--user", "disable", "--now", `${UNIT}.timer`]);
254
+ const removed = [remove(join(dir, `${UNIT}.timer`)), remove(join(dir, `${UNIT}.service`))].some(Boolean);
255
+ tryRun(r, "systemctl", ["--user", "daemon-reload"]);
256
+ return removed;
257
+ }
258
+ return false;
259
+ }
260
+ const NOT_LOADED = " (NOT LOADED: run npx conare sync --install again)";
261
+ /** Where the schedule is installed, flagged when the scheduler has not loaded it; undefined when it is not installed. */
262
+ export function installedSchedule(s) {
263
+ const r = s.run ?? run;
264
+ const home = s.home ?? homedir();
265
+ if (s.platform === "darwin") {
266
+ const plist = launchdPlistPath(home);
267
+ if (!existsSync(plist))
268
+ return undefined;
269
+ const loaded = tryRun(r, "launchctl", ["print", `gui/${s.uid ?? process.getuid?.() ?? 0}/${LABEL}`]);
270
+ return `launchd agent ${plist}${loaded ? "" : NOT_LOADED}`;
271
+ }
272
+ if (s.platform === "linux") {
273
+ const timer = join(systemdDir(s.env, home), `${UNIT}.timer`);
274
+ if (!existsSync(timer))
275
+ return undefined;
276
+ const loaded = tryRun(r, "systemctl", ["--user", "is-active", "--quiet", `${UNIT}.timer`]);
277
+ return `systemd user timer ${timer}${loaded ? "" : NOT_LOADED}`;
278
+ }
279
+ return undefined;
280
+ }
281
+ function remove(path) {
282
+ try {
283
+ unlinkSync(path);
284
+ return true;
285
+ }
286
+ catch {
287
+ return false;
288
+ }
289
+ }
@@ -0,0 +1,115 @@
1
+ // Secret scrubbing. Every document text passes through scrub() before it is hashed or
2
+ // uploaded. A rule replaces the secret itself (not the label in front of it) with
3
+ // [REDACTED:<kind>]. Specific key formats run before the generic rules, and a redaction
4
+ // marker never matches again, so scrub(scrub(x)) === scrub(x).
5
+ const hasDigit = (s) => /\d/.test(s);
6
+ const REFERENCE = /^[$%{<([~/.#*]|\(|\$\{|\{\{|->|::/; // $VAR, %VAR%, {{x}}, <token>, [REDACTED:…], paths, calls
7
+ const DOTTED = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+$/; // process.env.TOKEN, config.auth.token
8
+ const CODE = /[([]/; // readPassword(prompt), os.environ["TOKEN"]
9
+ // GITHUB_TOKEN, YOUR_TOKEN_HERE: an underscore makes it a variable name; a bare all-caps word
10
+ // ("SUPERSECRET") is a value like any other.
11
+ const ENV_NAME = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]*)+$/;
12
+ const TYPE_OR_LITERAL = /^(?:string|number|boolean|null|none|nil|undefined|true|false|required|optional)$/i;
13
+ /**
14
+ * The value of password=…, token: … and the like, unless it is code, a variable name or a
15
+ * placeholder. Any other value counts, letters or digits alone included: a chosen password
16
+ * ("supersecretpassword") or a numeric token is still a secret.
17
+ */
18
+ function assignedSecret(value) {
19
+ return !(REFERENCE.test(value) || DOTTED.test(value) || CODE.test(value) || ENV_NAME.test(value) || TYPE_OR_LITERAL.test(value));
20
+ }
21
+ /** An Authorization value: anything but a reference, a dotted name or a short plain word. */
22
+ function credentialLike(value) {
23
+ if (REFERENCE.test(value) || DOTTED.test(value))
24
+ return false;
25
+ return !/^[A-Za-z]+$/.test(value) || value.length >= 24;
26
+ }
27
+ const RULES = [
28
+ // PEM private keys: the whole block, or the base64 lines after a header whose END is missing.
29
+ {
30
+ kind: "private_key",
31
+ re: /-----BEGIN[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s\\:,.-]{0,16384}?-----END[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----|(?:(?:\r?\n|\\n)[A-Za-z0-9+/=]{16,})*)/g,
32
+ },
33
+ { kind: "conare_key", re: /\b(?:sk-conare-|cmem_)[A-Za-z0-9]{16,}/g },
34
+ { kind: "anthropic_key", re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
35
+ // OpenAI (sk-, sk-proj-, sk-svcacct-), OpenRouter (sk-or-v1-), DeepSeek and the like. A
36
+ // hyphenated slug ("sk-some-component-name") has no digit, or is short and lowercase.
37
+ {
38
+ kind: "api_key",
39
+ re: /\bsk-[A-Za-z0-9][A-Za-z0-9_-]{19,}/g,
40
+ accept: (s) => hasDigit(s) && (/[A-Z]/.test(s) || s.length >= 35),
41
+ },
42
+ { kind: "github_token", re: /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})/g },
43
+ { kind: "aws_access_key", re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
44
+ { kind: "slack_token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
45
+ { kind: "google_api_key", re: /\bAIza[0-9A-Za-z_-]{35}/g },
46
+ { kind: "huggingface_token", re: /\bhf_[A-Za-z0-9]{30,}/g },
47
+ // 1Password service-account tokens: ops_ then base64 JSON (not a three-part JWT).
48
+ { kind: "onepassword_token", re: /\bops_[A-Za-z0-9_=-]{40,}/g, accept: hasDigit },
49
+ // Telegram bot tokens, also inside api.telegram.org/bot<token>/ URLs (no \b after "bot").
50
+ { kind: "telegram_token", re: /(?<!\d)\d{8,10}:AA[A-Za-z0-9_-]{30,}/g },
51
+ // Modal token ids and secrets (ak-…, as-…).
52
+ { kind: "modal_token", re: /\ba[ks]-[A-Za-z0-9]{20,}\b/g, accept: hasDigit },
53
+ // Azure AD (service principal) client secrets: three characters, a digit, "Q~", the rest.
54
+ { kind: "azure_client_secret", re: /(?<![A-Za-z0-9_~.-])[A-Za-z0-9_~.]{3}\dQ~[A-Za-z0-9_~.-]{31,34}(?![A-Za-z0-9_~.-])/g },
55
+ // Azure Storage and Service Bus connection strings.
56
+ { kind: "azure_key", re: /(\b(?:AccountKey|SharedAccessKey)=)([A-Za-z0-9+/]{40,}={0,2})/g, label: true },
57
+ { kind: "jwt", re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
58
+ // Authorization: Bearer <token>, also Basic/Token/Bot, JSON and curl -H forms.
59
+ {
60
+ kind: "bearer_token",
61
+ re: /(\bAuthorization["']?\s*[:=]\s*["']?(?:(?:Bearer|Basic|Token|Bot)\s+)?)([^\s"'`,;]{8,})/gi,
62
+ label: true,
63
+ accept: credentialLike,
64
+ },
65
+ { kind: "bearer_token", re: /(\bBearer\s+)([A-Za-z0-9._~+/-]{16,}=*)/g, label: true, accept: hasDigit },
66
+ // scheme://user:password@host
67
+ {
68
+ kind: "password",
69
+ re: /(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@"'<>]+:)([^\s@/"'<>]{3,})(?=@)/gi,
70
+ label: true,
71
+ accept: (s) => !/^[$%{<[]/.test(s),
72
+ },
73
+ // password=…, secret: "…", api_key=…, token=…; the keyword ends the name, so
74
+ // max_tokens=4096 and tokenizer=… are not matched. A password is chosen by a person and
75
+ // can be short (6+); the other values are generated (12+).
76
+ {
77
+ kind: "secret",
78
+ re: /((?:password|passwd)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{6,})/gi,
79
+ label: true,
80
+ accept: assignedSecret,
81
+ },
82
+ {
83
+ kind: "secret",
84
+ re: /((?:secret|token|api[_-]?key|access[_-]?key|private[_-]?key)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{12,})/gi,
85
+ label: true,
86
+ accept: assignedSecret,
87
+ },
88
+ // --password …, --token=…
89
+ {
90
+ kind: "secret",
91
+ re: /(--(?:password|passwd)(?:=|\s+)["']?)([^\s"'`]{6,})/gi,
92
+ label: true,
93
+ accept: assignedSecret,
94
+ },
95
+ {
96
+ kind: "secret",
97
+ re: /(--(?:secret|token|api-key|access-key|auth-token|client-secret)(?:=|\s+)["']?)([^\s"'`]{12,})/gi,
98
+ label: true,
99
+ accept: assignedSecret,
100
+ },
101
+ ];
102
+ /** Replace every secret in text with [REDACTED:<kind>]. */
103
+ export function scrub(text) {
104
+ let out = text;
105
+ for (const rule of RULES) {
106
+ out = out.replace(rule.re, (match, group1) => {
107
+ const label = rule.label ? String(group1) : "";
108
+ const secret = match.slice(label.length);
109
+ if (rule.accept && !rule.accept(secret))
110
+ return match;
111
+ return `${label}[REDACTED:${rule.kind}]`;
112
+ });
113
+ }
114
+ return out;
115
+ }