@inhera/cli 0.0.0-stage → 0.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.
- package/README.md +26 -2
- package/bin/inhera.mjs +532 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @inhera/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Inhera command line: workspaces, assets, documents, contracts, members, votes, the activity log and exports, from a terminal, a script or a scheduled job. One file, no dependencies, Node 20 or newer.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm install -g @inhera/cli # or: npx @inhera/cli …
|
|
7
|
+
inhera login --key inh_live_… # a key from Account → API access & CLI
|
|
8
|
+
inhera whoami
|
|
9
|
+
inhera use "Harbor Family"
|
|
10
|
+
inhera assets list
|
|
11
|
+
inhera documents upload ~/Desktop/deed.pdf --name "Deed, Harbor Lane" --kind deed
|
|
12
|
+
inhera export --out harbor-$(date +%F).zip
|
|
13
|
+
inhera schedule install export ~/Backups/Inhera --at 02:30 # the nightly backup (the workspace owner approves it)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
A key acts as you, with your role in each workspace, narrowed to the permissions you ticked when you made it, and optionally to one workspace. The vault is never reachable with a key.
|
|
17
|
+
|
|
18
|
+
- `--json` on any command gives machine-readable output; errors come back as `{ "error", "code" }`.
|
|
19
|
+
- `INHERA_API_KEY` in the environment overrides the saved key (servers, CI). `INHERA_API` points at another server, for example staging. `INHERA_WORKSPACE` sets the default workspace.
|
|
20
|
+
- The saved key lives in `~/.config/inhera/config.json`, readable by you only.
|
|
21
|
+
- Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in or key refused, 4 permission denied.
|
|
22
|
+
|
|
23
|
+
## The nightly job
|
|
24
|
+
|
|
25
|
+
`inhera schedule install export <folder> [--data-only] [--keep 14] [--at HH:MM] [--wait]` asks Inhera to save a nightly backup of the workspace (the same ZIP as `inhera export`, readable without Inhera) into that folder on this computer, keeping the newest `--keep` backups it made. `inhera schedule install documents <folder> [--kind statement] [--at HH:MM] [--wait]` uploads new files that appear in a folder as documents, each file once (same contents are recognised even if this computer forgets). Nothing is installed until the workspace owner approves the request in Settings → Scheduled jobs (they get a notification and an email naming the computer, the folder and the time). Once approved, the command writes the scheduler entry itself: a Task Scheduler task on Windows, a launchd agent on a Mac, a crontab line on Linux. The entry runs `inhera schedule run <id>`; it carries no key (the key stays in the config file, readable by you only), checks the job is still approved before every run, and removes itself if the owner stops the job. `schedule status`, `schedule test <id>` and `schedule remove` round it out. The key needs the "Install the nightly job" permission plus exports:read (backup) or documents:write (folder). Install with `npm install -g`, not `npx`, so the job survives.
|
|
26
|
+
|
|
27
|
+
Full guide and the REST endpoints: https://inhera.app/developers
|
package/bin/inhera.mjs
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The Inhera command line. One file, no dependencies, Node 20 or newer.
|
|
3
|
+
// Signs every request with an API key made in Account → API access & CLI.
|
|
4
|
+
//
|
|
5
|
+
// inhera login [--key inh_live_…] [--api https://inhera.app]
|
|
6
|
+
// inhera whoami | workspaces | use <workspace>
|
|
7
|
+
// inhera assets list|get|create|import|template
|
|
8
|
+
// inhera documents list|get|upload|download
|
|
9
|
+
// inhera contracts list|get
|
|
10
|
+
// inhera members list|invite
|
|
11
|
+
// inhera votes list|open|ballot
|
|
12
|
+
// inhera activity | export | api <METHOD> <path>
|
|
13
|
+
// inhera schedule install export|documents <folder> [--at HH:MM] [--wait] (the nightly job; the workspace owner approves it)
|
|
14
|
+
// inhera schedule status | remove [id] | run <id> | test <id>
|
|
15
|
+
//
|
|
16
|
+
// Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in / key refused, 4 permission denied.
|
|
17
|
+
|
|
18
|
+
import { createInterface } from "node:readline";
|
|
19
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, chmodSync, statSync, readdirSync, appendFileSync } from "node:fs";
|
|
20
|
+
import { homedir, hostname, userInfo, platform } from "node:os";
|
|
21
|
+
import { basename, join, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { spawnSync } from "node:child_process";
|
|
25
|
+
|
|
26
|
+
const VERSION = "0.2.0";
|
|
27
|
+
const DEFAULT_API = "https://inhera.app";
|
|
28
|
+
const CONFIG_DIR = process.env.INHERA_CONFIG_DIR || join(homedir(), ".config", "inhera");
|
|
29
|
+
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Arguments
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
const argv = process.argv.slice(2);
|
|
36
|
+
const flags = {}; const positional = [];
|
|
37
|
+
for (let i = 0; i < argv.length; i++) {
|
|
38
|
+
const a = argv[i];
|
|
39
|
+
if (a === "--") { positional.push(...argv.slice(i + 1)); break; }
|
|
40
|
+
if (a.startsWith("--")) {
|
|
41
|
+
const eq = a.indexOf("=");
|
|
42
|
+
const name = eq > 0 ? a.slice(2, eq) : a.slice(2);
|
|
43
|
+
let value = eq > 0 ? a.slice(eq + 1) : (argv[i + 1] !== undefined && !argv[i + 1].startsWith("--") ? argv[++i] : true);
|
|
44
|
+
if (name in flags) flags[name] = [].concat(flags[name], value); else flags[name] = value;
|
|
45
|
+
} else positional.push(a);
|
|
46
|
+
}
|
|
47
|
+
const JSON_OUT = Boolean(flags.json);
|
|
48
|
+
const [command, sub, ...rest] = positional;
|
|
49
|
+
|
|
50
|
+
class CliError extends Error { constructor(message, code = 1) { super(message); this.code = code; } }
|
|
51
|
+
const fail = (message, code = 1) => { throw new CliError(message, code); };
|
|
52
|
+
const out = (s = "") => process.stdout.write(`${s}\n`);
|
|
53
|
+
const emit = (data, human) => { if (JSON_OUT) out(JSON.stringify(data, null, 2)); else human(); };
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
// Config
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
function readConfig() { try { return JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch { return {}; } }
|
|
60
|
+
function writeConfig(cfg) {
|
|
61
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
62
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
|
|
63
|
+
try { chmodSync(CONFIG_FILE, 0o600); } catch { /* Windows */ }
|
|
64
|
+
}
|
|
65
|
+
const config = readConfig();
|
|
66
|
+
const API = String(flags.api || process.env.INHERA_API || config.api || DEFAULT_API).replace(/\/+$/, "");
|
|
67
|
+
const KEY = process.env.INHERA_API_KEY || config.key || null;
|
|
68
|
+
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
// HTTP
|
|
71
|
+
// ---------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
async function call(method, path, { body, form, raw = false, key = KEY } = {}) {
|
|
74
|
+
if (!key) fail("Not signed in. Run `inhera login` with a key from Account → API access & CLI.", 3);
|
|
75
|
+
const headers = { authorization: `Bearer ${key}`, "user-agent": `inhera-cli/${VERSION}` };
|
|
76
|
+
let payload;
|
|
77
|
+
if (form) payload = form;
|
|
78
|
+
else if (body !== undefined) { headers["content-type"] = "application/json"; payload = JSON.stringify(body); }
|
|
79
|
+
let res;
|
|
80
|
+
try { res = await fetch(`${API}${path}`, { method, headers, body: payload }); }
|
|
81
|
+
catch (e) { fail(`Couldn't reach ${API}: ${e.message}`); }
|
|
82
|
+
if (raw) {
|
|
83
|
+
if (!res.ok) { const err = await res.json().catch(() => ({})); throw httpError(res.status, err); }
|
|
84
|
+
return res;
|
|
85
|
+
}
|
|
86
|
+
const type = res.headers.get("content-type") || "";
|
|
87
|
+
const data = type.includes("json") ? await res.json().catch(() => ({})) : await res.text();
|
|
88
|
+
if (!res.ok) throw httpError(res.status, data);
|
|
89
|
+
return data;
|
|
90
|
+
}
|
|
91
|
+
function httpError(status, data) {
|
|
92
|
+
const message = (data && typeof data === "object" && data.error) || `HTTP ${status}`;
|
|
93
|
+
if (status === 401) return new CliError(`${message} (run \`inhera login\` with a valid key)`, 3);
|
|
94
|
+
if (status === 403) return new CliError(message, 4);
|
|
95
|
+
if (status === 402) return new CliError(`${message} (the workspace owner's plan is read-only)`, 4);
|
|
96
|
+
return new CliError(message, 1);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// Helpers
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
function table(rows, columns) {
|
|
104
|
+
if (rows.length === 0) { out("(nothing)"); return; }
|
|
105
|
+
const cells = rows.map((r) => columns.map(([, get]) => String(get(r) ?? "")));
|
|
106
|
+
const widths = columns.map(([h], i) => Math.min(60, Math.max(h.length, ...cells.map((c) => c[i].length))));
|
|
107
|
+
const line = (parts) => parts.map((p, i) => p.slice(0, widths[i]).padEnd(widths[i])).join(" ");
|
|
108
|
+
out(line(columns.map(([h]) => h)));
|
|
109
|
+
out(line(widths.map((w) => "-".repeat(w))));
|
|
110
|
+
for (const c of cells) out(line(c));
|
|
111
|
+
}
|
|
112
|
+
const money = (cents, currency = "USD") => { try { return new Intl.NumberFormat("en-US", { style: "currency", currency, maximumFractionDigits: 0 }).format((cents || 0) / 100); } catch { return `${currency} ${(cents || 0) / 100}`; } };
|
|
113
|
+
const day = (s) => (s ? String(s).slice(0, 10) : "");
|
|
114
|
+
const flag = (name, fallback) => (flags[name] === undefined || flags[name] === true ? fallback : String(flags[name]));
|
|
115
|
+
const need = (value, what) => value ?? fail(`Missing ${what}.`, 2);
|
|
116
|
+
|
|
117
|
+
async function ask(prompt, { hidden = false } = {}) {
|
|
118
|
+
if (!process.stdin.isTTY) fail(`${prompt} is required when not in a terminal; pass it as a flag.`, 2);
|
|
119
|
+
return new Promise((resolveAnswer) => {
|
|
120
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
121
|
+
if (hidden) { rl._writeToOutput = (s) => { if (s.includes(prompt)) process.stdout.write(prompt); }; }
|
|
122
|
+
rl.question(`${prompt}: `, (answer) => { rl.close(); if (hidden) process.stdout.write("\n"); resolveAnswer(answer.trim()); });
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let workspacesCache = null;
|
|
127
|
+
async function workspaces() { if (!workspacesCache) workspacesCache = (await call("GET", "/api/workspaces")).workspaces; return workspacesCache; }
|
|
128
|
+
/** The workspace for this command: --workspace, INHERA_WORKSPACE, the saved default, or the only one. Accepts an id or a name. */
|
|
129
|
+
async function workspaceId() {
|
|
130
|
+
const list = await workspaces();
|
|
131
|
+
const find = (want) => list.find((x) => x.id === want) || list.find((x) => x.name.toLowerCase() === String(want).toLowerCase());
|
|
132
|
+
if (flags.workspace) {
|
|
133
|
+
const w = find(flags.workspace);
|
|
134
|
+
if (w) return w.id;
|
|
135
|
+
// An id the key can't see: let the server answer, so a permission problem reads as one.
|
|
136
|
+
if (/^[0-9a-f-]{20,}$/i.test(String(flags.workspace))) return String(flags.workspace);
|
|
137
|
+
fail(`No workspace "${flags.workspace}" among the ${list.length} this key can see. Try \`inhera workspaces\`.`, 2);
|
|
138
|
+
}
|
|
139
|
+
// The saved or environment default, when this key can see it; otherwise the only workspace it can.
|
|
140
|
+
const preset = process.env.INHERA_WORKSPACE || config.workspace;
|
|
141
|
+
const w = preset ? find(preset) : null;
|
|
142
|
+
if (w) return w.id;
|
|
143
|
+
if (list.length === 1) return list[0].id;
|
|
144
|
+
if (list.length === 0) fail("This key can't see any workspace.", 4);
|
|
145
|
+
fail("Several workspaces: pick one with --workspace <id|name>, or set a default with `inhera use <workspace>`.", 2);
|
|
146
|
+
}
|
|
147
|
+
const W = async () => `/api/workspaces/${await workspaceId()}`;
|
|
148
|
+
|
|
149
|
+
const MIME = { pdf: "application/pdf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", heic: "image/heic", txt: "text/plain", md: "text/markdown", csv: "text/csv", doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", xls: "application/vnd.ms-excel", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", json: "application/json", zip: "application/zip" };
|
|
150
|
+
const mimeOf = (path) => MIME[(path.split(".").pop() || "").toLowerCase()] || "application/octet-stream";
|
|
151
|
+
|
|
152
|
+
function fileForm(path, fields = {}) {
|
|
153
|
+
const abs = resolve(path);
|
|
154
|
+
if (!existsSync(abs)) fail(`No such file: ${path}`, 2);
|
|
155
|
+
if (statSync(abs).size > 200 * 1024 * 1024) fail("Files over 200 MB go through the app's resumable upload; the CLI keeps to 200 MB.", 2);
|
|
156
|
+
const form = new FormData();
|
|
157
|
+
form.append("file", new Blob([readFileSync(abs)], { type: mimeOf(abs) }), basename(abs));
|
|
158
|
+
for (const [k, v] of Object.entries(fields)) if (v !== undefined && v !== null && v !== "") form.append(k, String(v));
|
|
159
|
+
return form;
|
|
160
|
+
}
|
|
161
|
+
async function saveResponse(res, outPath, fallbackName) {
|
|
162
|
+
const cd = res.headers.get("content-disposition") || "";
|
|
163
|
+
const suggested = /filename="?([^";]+)"?/.exec(cd)?.[1] || fallbackName;
|
|
164
|
+
const target = resolve(outPath || suggested);
|
|
165
|
+
writeFileSync(target, Buffer.from(await res.arrayBuffer()));
|
|
166
|
+
return target;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
// Commands
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
const commands = {
|
|
174
|
+
async login() {
|
|
175
|
+
const key = flag("key") || (await ask("API key (inh_live_…)", { hidden: true }));
|
|
176
|
+
if (!/^inh_[a-z]+_[0-9a-f]{64}$/.test(key)) fail("That doesn't look like an Inhera API key (inh_live_ followed by 64 characters).", 2);
|
|
177
|
+
const me = await call("GET", "/api/me", { key });
|
|
178
|
+
writeConfig({ ...config, api: API, key, workspace: flags.workspace ? String(flags.workspace) : config.workspace });
|
|
179
|
+
emit({ ok: true, api: API, email: me.user.email, key: me.user.apiKey?.name, scopes: me.user.apiKey?.scopes ?? [] }, () => {
|
|
180
|
+
out(`Signed in to ${API} as ${me.user.email} with key "${me.user.apiKey?.name}". Saved to ${CONFIG_FILE}.`);
|
|
181
|
+
out(`Permissions: ${(me.user.apiKey?.scopes ?? []).join(", ")}`);
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
async logout() {
|
|
185
|
+
if (existsSync(CONFIG_FILE)) unlinkSync(CONFIG_FILE);
|
|
186
|
+
emit({ ok: true }, () => out("Signed out; the saved key was removed from this computer. Revoke it in your account if it shouldn't be used again."));
|
|
187
|
+
},
|
|
188
|
+
async whoami() {
|
|
189
|
+
const me = await call("GET", "/api/me");
|
|
190
|
+
emit({ api: API, user: { id: me.user.id, email: me.user.email, name: me.user.name }, key: me.user.apiKey, workspaces: me.workspaces.length }, () => {
|
|
191
|
+
out(`${me.user.name || me.user.email} <${me.user.email}> on ${API}`);
|
|
192
|
+
if (me.user.apiKey) out(`Key "${me.user.apiKey.name}"${me.user.apiKey.workspaceId ? " (one workspace)" : ""}: ${me.user.apiKey.scopes.join(", ")}`);
|
|
193
|
+
out(`${me.workspaces.length} workspace${me.workspaces.length === 1 ? "" : "s"} visible.`);
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
async workspaces() {
|
|
197
|
+
const list = await workspaces();
|
|
198
|
+
emit({ workspaces: list }, () => table(list, [["id", (w) => w.id], ["name", (w) => w.name], ["kind", (w) => w.kind], ["role", (w) => w.role], ["members", (w) => w.members]]));
|
|
199
|
+
},
|
|
200
|
+
async use() {
|
|
201
|
+
const want = need(sub, "a workspace id or name");
|
|
202
|
+
const list = await workspaces();
|
|
203
|
+
const w = list.find((x) => x.id === want) || list.find((x) => x.name.toLowerCase() === want.toLowerCase());
|
|
204
|
+
if (!w) fail(`No workspace "${want}". Try \`inhera workspaces\`.`, 2);
|
|
205
|
+
writeConfig({ ...config, workspace: w.id });
|
|
206
|
+
emit({ ok: true, workspace: w }, () => out(`Default workspace: ${w.name} (${w.id}).`));
|
|
207
|
+
},
|
|
208
|
+
|
|
209
|
+
async assets() {
|
|
210
|
+
const base = `${await W()}/assets`;
|
|
211
|
+
switch (sub || "list") {
|
|
212
|
+
case "list": { const r = await call("GET", base); emit(r, () => table(r.assets, [["id", (a) => a.id], ["name", (a) => a.name], ["kind", (a) => a.kind], ["value", (a) => money(a.valueCents, a.currency)], ["valued on", (a) => day(a.valuedOn)], ["status", (a) => a.status]])); return; }
|
|
213
|
+
case "get": { const r = await call("GET", `${base}/${need(rest[0], "an asset id")}`); emit(r, () => { const a = r.asset; out(`${a.name} (${a.kind}) · ${money(a.valueCents, a.currency)}${a.valuedOn ? ` as of ${day(a.valuedOn)}` : ""}`); if (a.description) out(a.description); if (a.location) out(`Location: ${a.location}`); if (a.institution) out(`Institution: ${a.institution}`); out(`Documents: ${a.documents} · visibility: ${a.visibility} · id ${a.id}`); if (r.history?.length) { out("\nValue history:"); table(r.history, [["date", (v) => day(v.valuedOn)], ["value", (v) => money(v.valueCents, a.currency)], ["source", (v) => v.source], ["note", (v) => v.note]]); } }); return; }
|
|
214
|
+
case "create": {
|
|
215
|
+
let body = flags.from ? JSON.parse(readFileSync(resolve(String(flags.from)), "utf8")) : {};
|
|
216
|
+
const map = { name: "name", kind: "kind", description: "description", "valued-on": "valuedOn", location: "location", institution: "institution", identifier: "identifier", notes: "notes", "acquired-on": "acquiredOn", visibility: "visibility" };
|
|
217
|
+
for (const [f, k] of Object.entries(map)) if (flags[f] !== undefined) body[k] = String(flags[f]);
|
|
218
|
+
if (flags.value !== undefined) body.value = Number(String(flags.value).replace(/[,$]/g, ""));
|
|
219
|
+
if (flags["cost-basis"] !== undefined) body.costBasis = Number(String(flags["cost-basis"]).replace(/[,$]/g, ""));
|
|
220
|
+
if (!body.name) fail("--name is required (or --from file.json).", 2);
|
|
221
|
+
const r = await call("POST", base, { body });
|
|
222
|
+
emit(r, () => out(`Created ${r.asset.name} (${r.asset.id}).`)); return;
|
|
223
|
+
}
|
|
224
|
+
case "value": { const id = need(rest[0], "an asset id"); const value = Number(String(need(rest[1], "a value")).replace(/[,$]/g, "")); const r = await call("POST", `${base}/${id}/values`, { body: { value, valuedOn: flag("valued-on", new Date().toISOString().slice(0, 10)), source: flag("source", "manual"), note: flag("note", "") } }); emit(r, () => out(`Recorded ${money(value * 100)} for ${id}.`)); return; }
|
|
225
|
+
case "template": { const res = await call("GET", `${base}/import/template`, { raw: true }); out((await res.text()).trim()); return; }
|
|
226
|
+
case "import": {
|
|
227
|
+
const path = need(rest[0], "a CSV file"); const csv = readFileSync(resolve(path), "utf8");
|
|
228
|
+
const r = await call("POST", `${base}/import`, { body: { csv, dryRun: Boolean(flags["dry-run"]) } });
|
|
229
|
+
const okRows = (r.rows || []).filter((x) => x.ok).length, bad = (r.rows || []).filter((x) => !x.ok);
|
|
230
|
+
emit(r, () => { out(r.dryRun ? `Dry run: ${okRows} asset(s) would be created${bad.length ? `, ${bad.length} row(s) have problems` : ""}.` : `Imported ${r.imported} asset(s).`); for (const x of bad) out(` line ${x.line}: ${x.errors.join("; ")}`); if (r.unknownColumns?.length) out(`Ignored columns: ${r.unknownColumns.join(", ")}`); }); return;
|
|
231
|
+
}
|
|
232
|
+
default: fail(`Unknown: assets ${sub}. Try list, get, create, value, import, template.`, 2);
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
async documents() {
|
|
237
|
+
const base = `${await W()}/documents`;
|
|
238
|
+
switch (sub || "list") {
|
|
239
|
+
case "list": { const r = await call("GET", base); emit(r, () => table(r.documents, [["id", (d) => d.id], ["name", (d) => d.name], ["kind", (d) => d.kind], ["version", (d) => d.currentVersion ?? d.version ?? ""], ["expires", (d) => day(d.expiresOn)], ["updated", (d) => day(d.updatedAt)]])); return; }
|
|
240
|
+
case "get": { const r = await call("GET", `${base}/${need(rest[0], "a document id")}`); emit(r, () => { const d = r.document; out(`${d.name} (${d.kind}) · ${d.fileName || ""} ${d.size ? `${Math.round(d.size / 1024)} KB` : ""}`); if (d.description) out(d.description); out(`Visibility ${d.visibility}${d.expiresOn ? ` · expires ${day(d.expiresOn)}` : ""} · id ${d.id}`); }); return; }
|
|
241
|
+
case "upload": {
|
|
242
|
+
const path = need(rest[0], "a file");
|
|
243
|
+
const form = fileForm(path, { name: flags.name, kind: flags.kind, description: flags.description, expiresOn: flags["expires-on"], assetId: flags.asset, visibility: flags.visibility });
|
|
244
|
+
const r = await call("POST", base, { form });
|
|
245
|
+
emit(r, () => out(`Uploaded ${r.document.name} (${r.document.id}).`)); return;
|
|
246
|
+
}
|
|
247
|
+
case "version": { const id = need(rest[0], "a document id"); const form = fileForm(need(rest[1], "a file"), { note: flags.note }); const r = await call("POST", `${base}/${id}/versions`, { form }); emit(r, () => out(`New version of ${r.document?.name || id}.`)); return; }
|
|
248
|
+
case "download": {
|
|
249
|
+
const id = need(rest[0], "a document id");
|
|
250
|
+
const res = await call("GET", `${base}/${id}/file?download=1`, { raw: true });
|
|
251
|
+
const target = await saveResponse(res, flags.out, `${id}.bin`);
|
|
252
|
+
emit({ ok: true, path: target }, () => out(`Saved ${target}`)); return;
|
|
253
|
+
}
|
|
254
|
+
default: fail(`Unknown: documents ${sub}. Try list, get, upload, version, download.`, 2);
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
|
|
258
|
+
async contracts() {
|
|
259
|
+
const base = `${await W()}/contracts`;
|
|
260
|
+
switch (sub || "list") {
|
|
261
|
+
case "list": { const r = await call("GET", base); emit(r, () => table(r.contracts, [["id", (k) => k.id], ["title", (k) => k.title], ["kind", (k) => k.kind], ["status", (k) => k.status], ["parties", (k) => (k.parties || []).length], ["expires", (k) => day(k.expiresOn)]])); return; }
|
|
262
|
+
case "get": { const r = await call("GET", `${base}/${need(rest[0], "a contract id")}`); emit(r, () => { const k = r.contract; out(`${k.title} (${k.kind}) · ${k.status} · version ${k.currentVersion}`); if (k.parties?.length) table(k.parties, [["party", (p) => p.name || p.email], ["role", (p) => p.role], ["status", (p) => p.status], ["signed", (p) => day(p.signedAt)]]); out(`\n${k.body}`); }); return; }
|
|
263
|
+
default: fail(`Unknown: contracts ${sub}. Try list, get.`, 2);
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
async members() {
|
|
268
|
+
const base = await W();
|
|
269
|
+
switch (sub || "list") {
|
|
270
|
+
case "list": { const r = await call("GET", base); emit({ members: r.members }, () => table(r.members, [["email", (m) => m.email], ["name", (m) => m.displayName], ["role", (m) => m.role], ["status", (m) => m.status], ["last seen", (m) => day(m.lastSeenAt)]])); return; }
|
|
271
|
+
case "invite": { const email = need(rest[0], "an email address"); const r = await call("POST", `${base}/invites`, { body: { email, role: flag("role", "member"), displayName: flag("name", ""), message: flag("message", "") } }); emit(r, () => out(`Invited ${email} as ${flag("role", "member")}.`)); return; }
|
|
272
|
+
default: fail(`Unknown: members ${sub}. Try list, invite.`, 2);
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
|
|
276
|
+
async votes() {
|
|
277
|
+
const base = `${await W()}/votes`;
|
|
278
|
+
switch (sub || "list") {
|
|
279
|
+
case "list": { const r = await call("GET", base); emit(r, () => table(r.votes, [["id", (v) => v.id], ["title", (v) => v.title], ["status", (v) => v.status], ["closes", (v) => day(v.closesAt)], ["cast", (v) => `${v.cast}/${v.eligible}`], ["outcome", (v) => v.outcome]])); return; }
|
|
280
|
+
case "open": case "request": {
|
|
281
|
+
const options = [].concat(flags.option || []).filter(Boolean);
|
|
282
|
+
const body = { title: need(flag("title"), "--title"), question: flag("question", ""), kind: options.length ? "choice" : "yes_no", options, closesAt: need(flag("closes"), "--closes YYYY-MM-DD"), quorumPct: Number(flag("quorum", "50")), thresholdPct: Number(flag("threshold", "50")), anonymous: Boolean(flags.anonymous), note: flag("note", "") };
|
|
283
|
+
const r = await call("POST", base, { body });
|
|
284
|
+
emit(r, () => out(`${r.vote.status === "open" ? "Opened" : "Requested"} "${r.vote.title}" (${r.vote.id}), ${r.vote.eligible} voter(s).`)); return;
|
|
285
|
+
}
|
|
286
|
+
case "ballot": { const id = need(rest[0], "a vote id"); const choice = need(rest[1], "a choice"); const r = await call("POST", `${base}/${id}/ballot`, { body: { choice, note: flag("note", "") } }); emit(r, () => out(`Ballot cast: ${choice}. ${r.vote.cast} of ${r.vote.eligible} have voted${r.vote.status === "closed" ? `; the vote is closed: ${r.vote.outcome}` : ""}.`)); return; }
|
|
287
|
+
default: fail(`Unknown: votes ${sub}. Try list, open, request, ballot.`, 2);
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
async activity() {
|
|
292
|
+
const r = await call("GET", `${await W()}/audit`);
|
|
293
|
+
const limit = Number(flag("limit", "50"));
|
|
294
|
+
emit(r, () => table(r.entries.slice(0, limit), [["when", (e) => String(e.createdAt).slice(0, 16)], ["who", (e) => e.actor], ["what", (e) => e.summary]]));
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
async export() {
|
|
298
|
+
const dataOnly = Boolean(flags["data-only"]);
|
|
299
|
+
const res = await call("GET", `${await W()}/export${dataOnly ? "?files=0" : ""}`, { raw: true });
|
|
300
|
+
const target = await saveResponse(res, flags.out, `inhera-export.zip`);
|
|
301
|
+
emit({ ok: true, path: target }, () => out(`Saved ${target}`));
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
async api() {
|
|
305
|
+
const method = String(need(sub, "a method (GET, POST, PUT, DELETE)")).toUpperCase();
|
|
306
|
+
const path = need(rest[0], "a path like /api/workspaces");
|
|
307
|
+
const body = flags.data ? JSON.parse(String(flags.data)) : undefined;
|
|
308
|
+
const r = await call(method, path.startsWith("/") ? path : `/${path}`, { body });
|
|
309
|
+
out(typeof r === "string" ? r : JSON.stringify(r, null, 2));
|
|
310
|
+
},
|
|
311
|
+
|
|
312
|
+
// The nightly job. Nothing touches Task Scheduler, launchd or cron until the workspace owner has approved the job in Settings.
|
|
313
|
+
async schedule() {
|
|
314
|
+
const action = sub || "status";
|
|
315
|
+
if (action === "install") return scheduleInstall();
|
|
316
|
+
if (action === "status") return scheduleStatus();
|
|
317
|
+
if (action === "remove") return scheduleRemove(rest[0]);
|
|
318
|
+
if (action === "run" || action === "test") return scheduleRun(need(rest[0], "a job id (see inhera schedule status)"), action === "test");
|
|
319
|
+
fail(`Unknown: schedule ${action}. Try install, status, remove, run, test.`, 2);
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
version() { out(VERSION); },
|
|
323
|
+
help() {
|
|
324
|
+
out(`inhera ${VERSION}: the Inhera command line.
|
|
325
|
+
|
|
326
|
+
inhera login [--key inh_live_…] [--api URL] save a key for this computer
|
|
327
|
+
inhera logout | whoami | workspaces | use <workspace>
|
|
328
|
+
inhera assets list | get <id> | create --name … [--kind --value --valued-on --description --location --institution] | value <id> <amount> | import <file.csv> [--dry-run] | template
|
|
329
|
+
inhera documents list | get <id> | upload <file> [--name --kind --description --expires-on --asset] | version <id> <file> | download <id> [--out path]
|
|
330
|
+
inhera contracts list | get <id>
|
|
331
|
+
inhera members list | invite <email> [--role member|admin|advisor|heir|viewer] [--name]
|
|
332
|
+
inhera votes list | open --title … --closes YYYY-MM-DD [--question --option A --option B --quorum --threshold --anonymous] | ballot <id> <choice>
|
|
333
|
+
inhera activity [--limit N]
|
|
334
|
+
inhera export [--out file.zip] [--data-only]
|
|
335
|
+
inhera api <METHOD> <path> [--data '{"…":…}']
|
|
336
|
+
inhera schedule install export <folder> [--data-only] [--keep 14] [--at 02:30] [--wait] nightly backup into that folder; the owner approves it
|
|
337
|
+
inhera schedule install documents <folder> [--kind other] [--at 02:30] [--wait] new files in that folder uploaded nightly; the owner approves it
|
|
338
|
+
inhera schedule status | remove [id] | test <id>
|
|
339
|
+
|
|
340
|
+
Everywhere: --json for machine-readable output, --workspace <id|name> for one command, --api <url> for staging.
|
|
341
|
+
Keys: Account → API access & CLI at ${DEFAULT_API}. Guide: ${DEFAULT_API}/developers`);
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
// Scheduled jobs: helpers
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
const CLI_PATH = fileURLToPath(import.meta.url);
|
|
350
|
+
const SCHEDULER = process.env.INHERA_SCHEDULER || platform(); // darwin | win32 | linux | dry (tests: write the entry, touch nothing)
|
|
351
|
+
const OS_NAME = platform() === "darwin" ? "darwin" : platform() === "win32" ? "win32" : "linux";
|
|
352
|
+
const SCHEDULE_TYPES = ["export", "documents"];
|
|
353
|
+
const jobLog = (id) => join(CONFIG_DIR, `schedule-${id}.log`);
|
|
354
|
+
const logLine = (id, text) => { try { mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); appendFileSync(jobLog(id), `${new Date().toISOString()} ${text}\n`, { mode: 0o600 }); } catch { /* best effort */ } };
|
|
355
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
356
|
+
const parseAt = (v) => { const m = /^(\d{1,2}):(\d{2})$/.exec(String(v || "").trim()); if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) fail("--at takes a 24-hour time like 02:30 or 23:15.", 2); return { hour: Number(m[1]), minute: Number(m[2]) }; };
|
|
357
|
+
const runningFromNpx = () => /[\\/]_npx[\\/]/.test(CLI_PATH);
|
|
358
|
+
const scheduledCommand = (id) => [process.execPath, CLI_PATH, "schedule", "run", id];
|
|
359
|
+
const q = (s) => `"${String(s).replace(/"/g, '\\"')}"`;
|
|
360
|
+
const hhmm = (j) => `${String(j.hour).padStart(2, "0")}:${String(j.minute).padStart(2, "0")}`;
|
|
361
|
+
|
|
362
|
+
/** Writes the OS scheduler entry for an approved job. Returns a short description of what was written. */
|
|
363
|
+
function installEntry(job) {
|
|
364
|
+
const id = job.id; const [node, cli] = scheduledCommand(id); const log = jobLog(id);
|
|
365
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
366
|
+
if (SCHEDULER === "dry") {
|
|
367
|
+
writeFileSync(join(CONFIG_DIR, `scheduler-${id}.txt`), `dry: ${OS_NAME} ${hhmm(job)} ${scheduledCommand(id).join(" ")}\n`, { mode: 0o600 });
|
|
368
|
+
return `dry run: entry written to ${join(CONFIG_DIR, `scheduler-${id}.txt`)} (nothing scheduled)`;
|
|
369
|
+
}
|
|
370
|
+
if (SCHEDULER === "darwin") {
|
|
371
|
+
const dir = join(homedir(), "Library", "LaunchAgents"); mkdirSync(dir, { recursive: true });
|
|
372
|
+
const plist = join(dir, `app.inhera.job.${id}.plist`);
|
|
373
|
+
const esc = (t) => String(t).replace(/&/g, "&").replace(/</g, "<");
|
|
374
|
+
writeFileSync(plist, `<?xml version="1.0" encoding="UTF-8"?>
|
|
375
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
376
|
+
<plist version="1.0"><dict>
|
|
377
|
+
<key>Label</key><string>app.inhera.job.${id}</string>
|
|
378
|
+
<key>ProgramArguments</key><array>${scheduledCommand(id).map((a) => `<string>${esc(a)}</string>`).join("")}</array>
|
|
379
|
+
<key>StartCalendarInterval</key><dict><key>Hour</key><integer>${job.hour}</integer><key>Minute</key><integer>${job.minute}</integer></dict>
|
|
380
|
+
<key>StandardOutPath</key><string>${esc(log)}</string><key>StandardErrorPath</key><string>${esc(log)}</string>
|
|
381
|
+
<key>RunAtLoad</key><false/>
|
|
382
|
+
</dict></plist>
|
|
383
|
+
`, { mode: 0o644 });
|
|
384
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 501;
|
|
385
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" });
|
|
386
|
+
const r = spawnSync("launchctl", ["bootstrap", `gui/${uid}`, plist], { encoding: "utf8" });
|
|
387
|
+
if (r.status !== 0) { const r2 = spawnSync("launchctl", ["load", "-w", plist], { encoding: "utf8" }); if (r2.status !== 0) fail(`launchd refused the job: ${(r.stderr || r2.stderr || "").trim()}`); }
|
|
388
|
+
return `launchd agent ${plist} (runs daily, catches up after sleep; log: ${log})`;
|
|
389
|
+
}
|
|
390
|
+
if (SCHEDULER === "win32") {
|
|
391
|
+
const name = `Inhera job ${id}`; const st = hhmm(job);
|
|
392
|
+
const r = spawnSync("schtasks", ["/Create", "/F", "/SC", "DAILY", "/ST", st, "/TN", name, "/TR", `${q(node)} ${q(cli)} schedule run ${id}`], { encoding: "utf8" });
|
|
393
|
+
if (r.status !== 0) fail(`Task Scheduler refused the job: ${(r.stderr || r.stdout || "").trim()}`);
|
|
394
|
+
return `Task Scheduler task "${name}" at ${st} (log: ${log})`;
|
|
395
|
+
}
|
|
396
|
+
// linux and anything else: the user's crontab
|
|
397
|
+
const marker = `# inhera:${id}`;
|
|
398
|
+
const current = spawnSync("crontab", ["-l"], { encoding: "utf8" }); const lines = (current.status === 0 ? current.stdout : "").split("\n").filter((l) => l.trim() && !l.includes(marker));
|
|
399
|
+
lines.push(`${job.minute} ${job.hour} * * * ${q(node)} ${q(cli)} schedule run ${id} >> ${q(log)} 2>&1 ${marker}`);
|
|
400
|
+
const w = spawnSync("crontab", ["-"], { input: lines.join("\n") + "\n", encoding: "utf8" });
|
|
401
|
+
if (w.status !== 0) fail(`crontab refused the job: ${(w.stderr || "").trim()}`);
|
|
402
|
+
return `crontab entry (${job.minute} ${job.hour} * * *; log: ${log})`;
|
|
403
|
+
}
|
|
404
|
+
function removeEntry(id) {
|
|
405
|
+
if (SCHEDULER === "dry") { const f = join(CONFIG_DIR, `scheduler-${id}.txt`); if (existsSync(f)) unlinkSync(f); return; }
|
|
406
|
+
if (SCHEDULER === "darwin") {
|
|
407
|
+
const plist = join(homedir(), "Library", "LaunchAgents", `app.inhera.job.${id}.plist`); const uid = typeof process.getuid === "function" ? process.getuid() : 501;
|
|
408
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" }); if (existsSync(plist)) unlinkSync(plist); return;
|
|
409
|
+
}
|
|
410
|
+
if (SCHEDULER === "win32") { spawnSync("schtasks", ["/Delete", "/F", "/TN", `Inhera job ${id}`], { stdio: "ignore" }); return; }
|
|
411
|
+
const marker = `# inhera:${id}`; const current = spawnSync("crontab", ["-l"], { encoding: "utf8" });
|
|
412
|
+
if (current.status === 0) { const lines = current.stdout.split("\n").filter((l) => l.trim() && !l.includes(marker)); spawnSync("crontab", ["-"], { input: lines.join("\n") + (lines.length ? "\n" : ""), encoding: "utf8" }); }
|
|
413
|
+
}
|
|
414
|
+
const savedJobs = () => (config.schedules && typeof config.schedules === "object" ? config.schedules : {});
|
|
415
|
+
const saveJob = (job, extra = {}) => { const all = savedJobs(); all[job.id] = { workspaceId: job.workspaceId, type: job.type, path: job.path, options: job.options, hour: job.hour, minute: job.minute, ...(all[job.id] || {}), ...extra }; writeConfig({ ...config, schedules: all }); };
|
|
416
|
+
const forgetJob = (id) => { const all = savedJobs(); delete all[id]; writeConfig({ ...config, schedules: all }); };
|
|
417
|
+
const statusLine = (j) => (j.status === "approved" ? (j.installedAt ? "approved, installed" : "approved, not installed yet") : j.status);
|
|
418
|
+
const jobUrl = (job, tail = "") => `/api/workspaces/${job.workspaceId}/schedules/${job.id}${tail}`;
|
|
419
|
+
/** The file names a backup job writes, so --keep only ever deletes its own. */
|
|
420
|
+
const backupName = (job, date) => `inhera-backup-${job.workspaceId.slice(0, 8)}-${date}${job.options?.dataOnly ? "-data" : ""}.zip`;
|
|
421
|
+
const backupPattern = (job) => new RegExp(`^inhera-backup-${job.workspaceId.slice(0, 8)}-\\d{4}-\\d{2}-\\d{2}(?:-\\d{6})?${job.options?.dataOnly ? "-data" : ""}\\.zip$`);
|
|
422
|
+
|
|
423
|
+
async function scheduleInstall() {
|
|
424
|
+
const type = need(rest[0], `a job type (${SCHEDULE_TYPES.join(" or ")})`); if (!SCHEDULE_TYPES.includes(type)) fail(`The type is one of ${SCHEDULE_TYPES.join(", ")}.`, 2);
|
|
425
|
+
const target = resolve(need(rest[1], type === "export" ? "the folder to save backups into" : "the folder to watch"));
|
|
426
|
+
if (!existsSync(target) || !statSync(target).isDirectory()) fail(`${target} isn't a folder on this computer. Make it first.`, 2);
|
|
427
|
+
if (runningFromNpx() && !flags["allow-npx"]) fail("Install the command line first so the job survives: npm install -g @inhera/cli (the npx copy can be cleaned away).", 2);
|
|
428
|
+
const { hour, minute } = parseAt(flag("at", "02:30"));
|
|
429
|
+
const options = type === "export" ? { dataOnly: Boolean(flags["data-only"]), keep: Number(flag("keep", "14")) } : { kind: flag("kind", "other") };
|
|
430
|
+
if (type === "export" && !(Number.isInteger(options.keep) && options.keep >= 1 && options.keep <= 365)) fail("--keep is how many backups to keep, 1 to 365.", 2);
|
|
431
|
+
const me = await call("GET", "/api/me");
|
|
432
|
+
if (!me.user.apiKey) fail("Scheduled jobs need an API key sign-in (inhera login --key inh_live_…).", 3);
|
|
433
|
+
const scopes = me.user.apiKey.scopes || [];
|
|
434
|
+
if (!scopes.includes("schedule:write")) fail("This key can't install the nightly job. Make a key with “Install the nightly job” ticked (Account → API access & CLI).", 4);
|
|
435
|
+
if (type === "export" && !scopes.includes("exports:read")) fail("A nightly backup needs the exports:read permission on this key as well.", 4);
|
|
436
|
+
if (type === "documents" && !scopes.includes("documents:write")) fail("A watched folder needs the documents:write permission on this key as well.", 4);
|
|
437
|
+
const wid = await workspaceId();
|
|
438
|
+
const body = { type, path: target, options, hour, minute, machine: hostname().slice(0, 80), os: OS_NAME, username: (() => { try { return userInfo().username; } catch { return ""; } })().slice(0, 80), cliVersion: VERSION };
|
|
439
|
+
const r = await call("POST", `/api/workspaces/${wid}/schedules`, { body });
|
|
440
|
+
let job = r.job;
|
|
441
|
+
if (job.status === "pending") {
|
|
442
|
+
out(`Asked the owner to approve: ${type === "export" ? `a ${options.dataOnly ? "data-only " : ""}backup into ${target}` : `uploading new files from ${target}`} every day at ${hhmm(job)} from ${body.machine}.`);
|
|
443
|
+
out(`Nothing is installed until it's approved in Settings → Scheduled jobs (${r.approveUrl}).`);
|
|
444
|
+
if (!flags.wait) { saveJob(job); emit({ job, installed: false }, () => out("Run this same command again after the approval, or add --wait to keep checking for up to 15 minutes.")); return; }
|
|
445
|
+
const until = Date.now() + 15 * 60_000;
|
|
446
|
+
while (Date.now() < until && job.status === "pending") { await new Promise((ok) => setTimeout(ok, 10_000)); job = (await call("GET", jobUrl(job))).job; }
|
|
447
|
+
}
|
|
448
|
+
if (job.status !== "approved") { saveJob(job); fail(job.status === "pending" ? "Still waiting for the owner's approval. Run the command again once it's approved." : `The owner ${job.status === "revoked" ? "stopped" : job.status} this job; nothing was installed.`, job.status === "pending" ? 1 : 4); }
|
|
449
|
+
const where = installEntry(job);
|
|
450
|
+
await call("POST", jobUrl(job, "/installed"), { body: {} });
|
|
451
|
+
saveJob(job, { installedAt: new Date().toISOString() });
|
|
452
|
+
logLine(job.id, `installed: ${where}`);
|
|
453
|
+
emit({ job, installed: true, where }, () => { out(`Installed: ${where}.`); out(`Every day at ${hhmm(job)} this computer ${type === "export" ? "saves a backup of the workspace" : "uploads new files from the folder"}. Try it now: inhera schedule test ${job.id}`); });
|
|
454
|
+
}
|
|
455
|
+
async function scheduleStatus() {
|
|
456
|
+
const saved = savedJobs(); const jobs = [];
|
|
457
|
+
for (const [id, s] of Object.entries(saved)) { try { jobs.push((await call("GET", `/api/workspaces/${s.workspaceId}/schedules/${id}`)).job); } catch (e) { jobs.push({ id, status: `unknown (${e.message})`, type: s.type, path: s.path, hour: s.hour, minute: s.minute }); } }
|
|
458
|
+
emit({ jobs }, () => { if (!jobs.length) { out("No scheduled jobs on this computer. Set one up: inhera schedule install export ~/Backups/Inhera --at 02:30"); return; } table(jobs, [["id", (j) => j.id.slice(0, 8)], ["type", (j) => j.type], ["folder", (j) => j.path], ["at", (j) => hhmm(j)], ["status", (j) => statusLine(j)], ["last run", (j) => (j.lastRunAt ? `${j.lastOutcome} ${j.lastRunAt}` : "")]]); });
|
|
459
|
+
}
|
|
460
|
+
async function scheduleRemove(idArg) {
|
|
461
|
+
const ids = Object.keys(savedJobs()); const id = idArg ? ids.find((x) => x === idArg || x.startsWith(idArg)) ?? idArg : ids.length === 1 ? ids[0] : null;
|
|
462
|
+
if (!id) fail(ids.length ? `Say which job: ${ids.join(", ")}` : "No scheduled jobs on this computer.", 2);
|
|
463
|
+
removeEntry(id); forgetJob(id); logLine(id, "removed from this computer");
|
|
464
|
+
emit({ ok: true, id }, () => out(`Removed the scheduled job ${id.slice(0, 8)} from this computer. The owner can also stop it in Settings → Scheduled jobs.`));
|
|
465
|
+
}
|
|
466
|
+
async function scheduleRun(idArg, verbose) {
|
|
467
|
+
const saved = savedJobs(); const id = Object.keys(saved).find((x) => x === idArg || x.startsWith(idArg)) ?? idArg;
|
|
468
|
+
const s = saved[id]; if (!s) fail(`No job ${idArg} on this computer. See inhera schedule status.`, 2);
|
|
469
|
+
const url = (tail = "") => `/api/workspaces/${s.workspaceId}/schedules/${id}${tail}`;
|
|
470
|
+
let job;
|
|
471
|
+
try { job = (await call("GET", url())).job; }
|
|
472
|
+
catch (e) { logLine(id, `could not check the job: ${e.message}`); if (e.code === 3 || e.code === 4) { removeEntry(id); forgetJob(id); logLine(id, "key refused: removed the scheduled entry"); } throw e; }
|
|
473
|
+
if (job.status !== "approved") { removeEntry(id); forgetJob(id); logLine(id, `job is ${job.status}: removed the scheduled entry`); fail(`This job is ${job.status === "revoked" ? "stopped" : job.status}; the scheduled entry was removed from this computer.`, 4); }
|
|
474
|
+
const report = (outcome, message, extra = {}) => call("POST", url("/ping"), { body: { outcome, message: String(message).slice(0, 500), ...extra } }).catch((e) => { logLine(id, `report failed: ${e.message}`); if (e.message && /stopped|revoked|declined/.test(e.message)) { removeEntry(id); forgetJob(id); } });
|
|
475
|
+
const W = `/api/workspaces/${job.workspaceId}`;
|
|
476
|
+
try {
|
|
477
|
+
if (!existsSync(job.path) || !statSync(job.path).isDirectory()) throw new CliError(`The folder isn't there: ${job.path}`, 2);
|
|
478
|
+
if (job.type === "export") {
|
|
479
|
+
const res = await call("GET", `${W}/export${job.options?.dataOnly ? "?files=0" : ""}`, { raw: true });
|
|
480
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
481
|
+
let target = join(job.path, backupName(job, date));
|
|
482
|
+
if (existsSync(target)) target = join(job.path, backupName(job, `${date}-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`));
|
|
483
|
+
writeFileSync(target, Buffer.from(await res.arrayBuffer()), { mode: 0o600 });
|
|
484
|
+
const size = statSync(target).size;
|
|
485
|
+
// Keep the newest N backups this job made; never touch anything else in the folder.
|
|
486
|
+
const mine = readdirSync(job.path).filter((f) => backupPattern(job).test(f)).map((f) => ({ f, t: statSync(join(job.path, f)).mtimeMs })).sort((a, b) => b.t - a.t);
|
|
487
|
+
const pruned = mine.slice(job.options?.keep || 14); for (const p of pruned) { try { unlinkSync(join(job.path, p.f)); } catch { /* leave it */ } }
|
|
488
|
+
const message = `${basename(target)} saved (${(size / 1024 / 1024).toFixed(1)} MB)${pruned.length ? `, ${pruned.length} older backup${pruned.length === 1 ? "" : "s"} removed` : ""}`;
|
|
489
|
+
await report("ok", message, { file: basename(target) });
|
|
490
|
+
logLine(id, message);
|
|
491
|
+
emit({ outcome: "ok", file: target, size, pruned: pruned.length }, () => out(`Saved ${target} (${(size / 1024 / 1024).toFixed(1)} MB).${pruned.length ? ` Removed ${pruned.length} older backup(s), keeping ${job.options?.keep || 14}.` : ""}`));
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
// documents: upload what's new in the folder (top level, no hidden files), skipping contents already in the workspace
|
|
495
|
+
const files = readdirSync(job.path).filter((f) => !f.startsWith(".")).map((f) => join(job.path, f)).filter((f) => { try { return statSync(f).isFile(); } catch { return false; } });
|
|
496
|
+
const existing = new Set(((await call("GET", `${W}/documents`)).documents || []).map((d) => d.sha256).filter(Boolean));
|
|
497
|
+
const ledgerFile = join(CONFIG_DIR, `schedule-${id}-sent.json`); const ledger = (() => { try { return JSON.parse(readFileSync(ledgerFile, "utf8")); } catch { return {}; } })();
|
|
498
|
+
let uploaded = 0, skipped = 0, tooBig = 0; const names = [];
|
|
499
|
+
for (const f of files) {
|
|
500
|
+
if (uploaded >= 50) break; // the rest goes tomorrow night
|
|
501
|
+
const st = statSync(f); if (st.size > 200 * 1024 * 1024) { tooBig++; logLine(id, `skipped ${basename(f)}: over 200 MB`); continue; }
|
|
502
|
+
const buf = readFileSync(f); const hash = sha256(buf);
|
|
503
|
+
if (existing.has(hash) || ledger[hash]) { skipped++; continue; }
|
|
504
|
+
const form = new FormData(); form.append("file", new Blob([buf], { type: mimeOf(f) }), basename(f)); form.append("kind", job.options?.kind || "other");
|
|
505
|
+
const r = await call("POST", `${W}/documents`, { form });
|
|
506
|
+
ledger[hash] = { name: basename(f), at: new Date().toISOString(), documentId: r.document?.id }; writeFileSync(ledgerFile, JSON.stringify(ledger), { mode: 0o600 });
|
|
507
|
+
uploaded++; names.push(basename(f)); logLine(id, `uploaded ${basename(f)}`);
|
|
508
|
+
}
|
|
509
|
+
if (!uploaded) { const why = files.length ? `${skipped} file(s) already in the workspace${tooBig ? `, ${tooBig} over 200 MB` : ""}; nothing new.` : "The folder is empty."; await report("skipped", why); emit({ outcome: "skipped", skipped, tooBig }, () => out(why)); return; }
|
|
510
|
+
const message = `${uploaded} file${uploaded === 1 ? "" : "s"} uploaded (${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""})${skipped ? `, ${skipped} already there` : ""}${tooBig ? `, ${tooBig} over 200 MB skipped` : ""}`;
|
|
511
|
+
await report("ok", message, { file: names[0] });
|
|
512
|
+
emit({ outcome: "ok", uploaded, skipped, tooBig, files: names }, () => out(message + "."));
|
|
513
|
+
} catch (e) {
|
|
514
|
+
logLine(id, `failed: ${e.message}`);
|
|
515
|
+
await report("failed", e.message);
|
|
516
|
+
if (verbose) throw e; else fail(e.message, e instanceof CliError ? e.code : 1);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// ---------------------------------------------------------------------------
|
|
521
|
+
|
|
522
|
+
try {
|
|
523
|
+
const name = !command || flags.help ? "help" : flags.version ? "version" : command;
|
|
524
|
+
const fn = commands[name];
|
|
525
|
+
if (!fn) fail(`Unknown command "${command}". Try \`inhera help\`.`, 2);
|
|
526
|
+
await fn();
|
|
527
|
+
} catch (e) {
|
|
528
|
+
const code = e instanceof CliError ? e.code : 1;
|
|
529
|
+
if (JSON_OUT) out(JSON.stringify({ error: e.message, code }));
|
|
530
|
+
else process.stderr.write(`inhera: ${e.message}\n`);
|
|
531
|
+
process.exit(code);
|
|
532
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inhera/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The Inhera command line: workspaces, assets, documents, contracts, members, votes, activity and exports from a terminal or a script, behind an API key you make in your account; plus a nightly backup or watched folder the workspace owner approves.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"inhera": "bin/inhera.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"inhera",
|
|
19
|
+
"estate",
|
|
20
|
+
"family-office",
|
|
21
|
+
"cli"
|
|
22
|
+
],
|
|
23
|
+
"homepage": "https://inhera.app/developers",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/Inhera-App/Inhera-App",
|
|
27
|
+
"directory": "cli"
|
|
28
|
+
}
|
|
29
|
+
}
|