@hallohuman/hightea 0.1.1 → 0.1.8

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,123 @@
1
+ import {
2
+ checkedOrigin2,
3
+ ensureCredential2
4
+ } from "./chunk-0ab6h39c.js";
5
+
6
+ // src/owner-session.ts
7
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ var NOT_OWNER = new Set(["FORBIDDEN", "NOT_A_MEMBER", "UNAUTHENTICATED"]);
11
+ function ownerIo() {
12
+ return {
13
+ fetch: (url, init) => globalThis.fetch(url, init),
14
+ readFile: (path) => readFile(path, "utf8"),
15
+ stat: (path) => stat(path),
16
+ writeFile: (path, data, options) => writeFile(path, data, options),
17
+ mkdir: async (path, options) => {
18
+ await mkdir(path, options);
19
+ },
20
+ chmod: (path, mode) => chmod(path, mode),
21
+ rm: (path, options) => rm(path, options),
22
+ env: process.env,
23
+ home: homedir(),
24
+ nowMs: () => Date.now(),
25
+ out: (line) => {
26
+ process.stdout.write(`${line}
27
+ `);
28
+ },
29
+ err: (line) => {
30
+ process.stderr.write(`${line}
31
+ `);
32
+ }
33
+ };
34
+ }
35
+ async function readSession(target, io, label, origin) {
36
+ const explicit = target.sessionFile?.trim() || io.env.HIGHTEA_SESSION_FILE?.trim();
37
+ if (explicit === undefined || explicit === "") {
38
+ const stored = await ensureCredential2(origin, io);
39
+ if ("credential" in stored)
40
+ return { cookie: stored.credential.sessionToken };
41
+ if (stored.error.startsWith("AUTH_NOT_SIGNED_IN")) {
42
+ const legacy = join(io.env.XDG_CONFIG_HOME?.trim() || join(io.home, ".config"), "hightea", "session");
43
+ const copied = await readSessionFile(legacy, io, label);
44
+ if (!("error" in copied))
45
+ return copied;
46
+ return { error: `${label}_SESSION_MISSING: ${stored.error}` };
47
+ }
48
+ if (stored.error.startsWith("AUTH_CREDENTIALS_EXPOSED"))
49
+ return { error: `${label}_SESSION_EXPOSED: ${stored.error}` };
50
+ if (stored.error.startsWith("AUTH_SESSION_EXPIRED") || stored.error.startsWith("AUTH_REFRESH")) {
51
+ return { error: `${label}_SESSION_EXPIRED: ${stored.error}` };
52
+ }
53
+ return { error: `${label}_SESSION_INVALID: ${stored.error}` };
54
+ }
55
+ return await readSessionFile(explicit, io, label);
56
+ }
57
+ async function readSessionFile(file, io, label) {
58
+ let raw;
59
+ let mode;
60
+ try {
61
+ raw = await io.readFile(file);
62
+ mode = (await io.stat(file)).mode;
63
+ } catch (error) {
64
+ return { error: `${label}_SESSION_MISSING: no session in ${file} (${error.message}). Sign in to the deployment in a browser and write its ht_session cookie to that file, or pass --session-file.` };
65
+ }
66
+ if ((mode & 63) !== 0) {
67
+ return { error: `${label}_SESSION_EXPOSED: ${file} is mode 0${(mode & 511).toString(8).padStart(3, "0")}; run chmod 600 ${file}.` };
68
+ }
69
+ const lines = raw.split(`
70
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
71
+ if (lines.length !== 1) {
72
+ return { error: `${label}_SESSION_INVALID: ${file} must hold exactly one non-empty line (the ht_session cookie value); it holds ${lines.length}.` };
73
+ }
74
+ return { cookie: lines[0] };
75
+ }
76
+ async function sendOwner(target, io, request) {
77
+ const where = checkedOrigin2(target.origin, request.label);
78
+ if ("error" in where)
79
+ return { exit: 1, error: where.error };
80
+ const session = await readSession(target, io, request.label, where.origin);
81
+ if ("error" in session)
82
+ return { exit: 1, error: session.error };
83
+ const url = `${where.origin}/api/ws/${encodeURIComponent(target.workspace)}${request.path}`;
84
+ let response;
85
+ try {
86
+ response = await io.fetch(url, {
87
+ method: request.method,
88
+ headers: {
89
+ cookie: `ht_session=${session.cookie}`,
90
+ origin: where.origin,
91
+ accept: "application/json",
92
+ "cache-control": "no-store",
93
+ ...request.body === undefined ? {} : { "content-type": "application/json" }
94
+ },
95
+ ...request.body === undefined ? {} : { body: JSON.stringify(request.body) }
96
+ });
97
+ } catch (error) {
98
+ return { exit: 1, error: `${request.label}_UNREACHABLE: ${request.what} ${request.method} ${url} did not answer: ${error.message}` };
99
+ }
100
+ const text = await response.text();
101
+ let answer = {};
102
+ if (text.length > 0) {
103
+ try {
104
+ const parsed = JSON.parse(text);
105
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
106
+ throw new SyntaxError("not a JSON object");
107
+ answer = parsed;
108
+ } catch (error) {
109
+ if (!(error instanceof SyntaxError))
110
+ throw error;
111
+ return { exit: 1, error: `${request.label}_ANSWER_INVALID: ${request.what} ${request.method} ${url} answered HTTP ${response.status} with non-JSON: ${text.slice(0, 300)}` };
112
+ }
113
+ }
114
+ if (response.ok)
115
+ return { answer };
116
+ const refusal = answer.error;
117
+ const code = typeof refusal?.code === "string" ? refusal.code : `HTTP_${response.status}`;
118
+ const message = typeof refusal?.message === "string" ? refusal.message : text.slice(0, 300);
119
+ const exit = NOT_OWNER.has(code) ? 3 : request.extraExits?.[code] ?? 1;
120
+ return { exit, error: `${code}: ${message}`, body: answer };
121
+ }
122
+
123
+ export { ownerIo, sendOwner };
@@ -0,0 +1,347 @@
1
+ import"./chunk-0ab6h39c.js";
2
+ import {
3
+ ownerIo,
4
+ sendOwner
5
+ } from "./chunk-sbqmqp8e.js";
6
+
7
+ // src/service.ts
8
+ var USAGE = `hightea service list (--host HOST --origin URL --workspace SLUG | --local [--host HOST]) [--json]
9
+ ` + `hightea service add|change NAME [--command CMD] [--cwd DIR] [--patch JSON] (--host … | --local)
10
+ ` + `hightea service remove|start|stop|restart NAME (--host … | --local)
11
+ ` + `hightea service logs NAME [--limit N] [--end N] (--host … | --local)
12
+ ` + `hightea service acknowledge (--host … | --local)
13
+ ` + `hightea service backup --host HOST --origin URL --workspace SLUG [--json]
14
+ ` + `hightea service restore [NAME...] --from OLD_HOST (--host NEW_HOST | --local) --origin URL --workspace SLUG [--yes] [--json]
15
+ ` + "hightea service enable|disable [--host HOST] (run on the machine)";
16
+ var asAnswer = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.ok === "boolean" ? value : undefined;
17
+ function remoteDriver(target, io) {
18
+ const host = encodeURIComponent((target.host ?? "").trim());
19
+ const send = async (method, path, what, body) => {
20
+ const sent = await sendOwner(target, io, { method, path: `/hosts/${host}/services${path}`, what, label: "SERVICE", ...body === undefined ? {} : { body } });
21
+ if ("error" in sent) {
22
+ const answer = asAnswer(sent.body?.answer);
23
+ return answer === undefined ? sent : { answer };
24
+ }
25
+ const answer = asAnswer(sent.answer.answer);
26
+ return answer === undefined ? { exit: 1, error: `SERVICE_ANSWER_INVALID: ${what} answered without the host's answer: ${JSON.stringify(sent.answer).slice(0, 300)}` } : { answer };
27
+ };
28
+ const name = (value) => `/${encodeURIComponent(value)}`;
29
+ return {
30
+ machine: (target.host ?? "").trim(),
31
+ list: () => send("GET", "", "list"),
32
+ put: (params) => send("PUT", name(String(params.service.name)), "put", params),
33
+ remove: (params) => send("DELETE", name(params.name), "remove", { ifVersion: params.ifVersion }),
34
+ control: (service, verb) => send("POST", `${name(service)}/${verb}`, verb),
35
+ logs: (params) => {
36
+ const query = new URLSearchParams;
37
+ if (params.end !== undefined)
38
+ query.set("end", String(params.end));
39
+ if (params.limit !== undefined)
40
+ query.set("limit", String(params.limit));
41
+ const suffix = query.size === 0 ? "" : `?${query}`;
42
+ return send("GET", `${name(params.name)}/logs${suffix}`, "logs");
43
+ },
44
+ acknowledge: (params) => send("POST", "/acknowledge", "acknowledge", params)
45
+ };
46
+ }
47
+ async function localDriver(target) {
48
+ const { localHost } = await import("./chunk-3qbh10ga.js");
49
+ const found = await localHost(target.host);
50
+ if ("error" in found)
51
+ return found;
52
+ const { localServices, LOG_LINES_MAX } = await import("@ahpd/services");
53
+ const local = localServices(found.configDir);
54
+ if (typeof local === "string")
55
+ return { error: `SERVICE_NOT_CONFIGURED: ${local}` };
56
+ const reached = (answer) => ({ answer });
57
+ return {
58
+ machine: local.machine.name,
59
+ list: async () => reached(local.list()),
60
+ put: async (params) => reached(await local.put(params)),
61
+ remove: async (params) => reached(await local.remove(params)),
62
+ control: async (name, verb) => reached(await local.control(name, verb)),
63
+ logs: async (params) => reached(await local.logs({
64
+ name: params.name,
65
+ endOffset: params.end ?? 0,
66
+ limit: Math.min(params.limit ?? 100, LOG_LINES_MAX)
67
+ })),
68
+ acknowledge: async (params) => reached(await local.acknowledge(params))
69
+ };
70
+ }
71
+ async function serviceCommand(target, input, io = ownerIo(), drivers = {}) {
72
+ const remote = !target.local;
73
+ if (remote && ((target.host ?? "").trim() === "" || target.workspace.trim() === "")) {
74
+ io.err(`SERVICE_INPUT: name the host with --host and --workspace, or act on this machine with --local.
75
+ ${USAGE}`);
76
+ return 1;
77
+ }
78
+ const needsName = input.command !== "list" && input.command !== "acknowledge";
79
+ const name = input.name?.trim() ?? "";
80
+ if (needsName && name === "") {
81
+ io.err(`SERVICE_INPUT: ${input.command} names one service.
82
+ ${USAGE}`);
83
+ return 1;
84
+ }
85
+ const driver = remote ? remoteDriver(target, io) : await (drivers.local ?? localDriver)(target);
86
+ if ("error" in driver) {
87
+ io.err(driver.error);
88
+ return 1;
89
+ }
90
+ const done = (reached, print) => {
91
+ if ("error" in reached) {
92
+ io.err(reached.error);
93
+ return reached.exit;
94
+ }
95
+ const answer = reached.answer;
96
+ if (!answer.ok) {
97
+ io.err(`${String(answer.code ?? "SERVICE_REFUSED")}: ${String(answer.message ?? "the machine refused")}`);
98
+ if (typeof answer.diff === "string" && answer.diff !== "")
99
+ io.err(answer.diff);
100
+ if (target.json)
101
+ io.out(JSON.stringify(answer));
102
+ return 1;
103
+ }
104
+ if (target.json)
105
+ io.out(JSON.stringify(answer));
106
+ else
107
+ print(answer);
108
+ return 0;
109
+ };
110
+ switch (input.command) {
111
+ case "list":
112
+ return done(await driver.list(), (answer) => io.out(listing(answer, driver.machine)));
113
+ case "start":
114
+ case "stop":
115
+ case "restart":
116
+ return done(await driver.control(name, input.command), () => io.out(`${input.command}: ${name} on ${driver.machine}`));
117
+ case "logs": {
118
+ const end = wholeNumber(input.end, 0), limit = wholeNumber(input.limit, 1);
119
+ if (end === null || limit === null) {
120
+ io.err("SERVICE_INPUT: --end and --limit are whole numbers of lines; --limit is at least 1");
121
+ return 1;
122
+ }
123
+ const reached = await driver.logs({ name, ...end === undefined ? {} : { end }, ...limit === undefined ? {} : { limit } });
124
+ return done(reached, (answer) => {
125
+ io.out(`raw output from ${name} on ${driver.machine}:`);
126
+ for (const line of Array.isArray(answer.lines) ? answer.lines : [])
127
+ io.out(String(line));
128
+ });
129
+ }
130
+ case "acknowledge":
131
+ case "add":
132
+ case "change":
133
+ case "remove": {
134
+ const listed = await driver.list();
135
+ if ("error" in listed) {
136
+ io.err(listed.error);
137
+ return listed.exit;
138
+ }
139
+ if (!listed.answer.ok)
140
+ return done(listed, () => {});
141
+ const ifVersion = String(listed.answer.ifVersion ?? "");
142
+ const services = Array.isArray(listed.answer.services) ? listed.answer.services : [];
143
+ const exists = services.some((service) => service.name === name);
144
+ if (input.command === "acknowledge") {
145
+ const hashes = listed.answer.hashes ?? {};
146
+ return done(await driver.acknowledge({ hashes }), () => io.out(`acknowledged ${Object.keys(hashes).join(", ") || "no files"} on ${driver.machine} as they are now`));
147
+ }
148
+ if (input.command === "remove") {
149
+ return done(await driver.remove({ name, ifVersion }), () => io.out(`removed ${name} on ${driver.machine}`));
150
+ }
151
+ if (input.command === "add" && exists) {
152
+ io.err(`SERVICE_EXISTS: ${name} is already a service on ${driver.machine}; use \`hightea service change\``);
153
+ return 1;
154
+ }
155
+ if (input.command === "change" && !exists) {
156
+ io.err(`SERVICE_NOT_FOUND: ${name} is not a service on ${driver.machine}; use \`hightea service add\``);
157
+ return 1;
158
+ }
159
+ const service = patchOf(name, input.fields ?? {});
160
+ if (typeof service === "string") {
161
+ io.err(`SERVICE_INPUT: ${service}`);
162
+ return 1;
163
+ }
164
+ if (input.command === "add" && service.command === undefined) {
165
+ io.err("SERVICE_INPUT: a new service needs --command");
166
+ return 1;
167
+ }
168
+ return done(await driver.put({ service, ifVersion }), (answer) => io.out(answer.changed === false ? `${name} on ${driver.machine} already reads so; nothing was written` : `${input.command === "add" ? "added" : "changed"} ${name} on ${driver.machine}`));
169
+ }
170
+ }
171
+ }
172
+ function patchOf(name, fields) {
173
+ let extra = {};
174
+ if (fields.patch !== undefined) {
175
+ try {
176
+ extra = JSON.parse(fields.patch);
177
+ } catch {
178
+ return "--patch is a JSON object of service fields";
179
+ }
180
+ if (typeof extra !== "object" || extra === null || Array.isArray(extra))
181
+ return "--patch is a JSON object of service fields";
182
+ if (extra.name !== undefined && extra.name !== name)
183
+ return "--patch names another service";
184
+ }
185
+ return {
186
+ ...extra,
187
+ name,
188
+ ...fields.command === undefined ? {} : { command: fields.command },
189
+ ...fields.cwd === undefined ? {} : { cwd: fields.cwd }
190
+ };
191
+ }
192
+ function wholeNumber(raw, least) {
193
+ if (raw === undefined)
194
+ return;
195
+ return /^\d{1,7}$/u.test(raw.trim()) && Number(raw) >= least ? Number(raw) : null;
196
+ }
197
+ function listing(answer, machine) {
198
+ const services = Array.isArray(answer.services) ? answer.services : [];
199
+ const readOnly = Array.isArray(answer.readOnly) ? answer.readOnly : [];
200
+ const lines = services.map((service) => {
201
+ const plain = Array.isArray(service.plainEnv) && service.plainEnv.length > 0 ? ` (plain env: ${service.plainEnv.join("; ")})` : "";
202
+ return `${String(service.name)} ${String(service.command ?? "")}${plain}`;
203
+ });
204
+ for (const entry of readOnly)
205
+ lines.push(`${String(entry.name)} read-only: ${String(entry.reason)}`);
206
+ if (lines.length === 0)
207
+ return `no services on ${machine} (${String(answer.file ?? "its file")})`;
208
+ return lines.join(`
209
+ `);
210
+ }
211
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
212
+ async function readBackup(target, io, host) {
213
+ const sent = await sendOwner(target, io, { method: "GET", path: `/hosts/${encodeURIComponent(host)}/services/backup`, what: "backup", label: "SERVICE" });
214
+ if ("error" in sent)
215
+ return sent;
216
+ const backup = sent.answer.backup;
217
+ if (!isObject(backup) || typeof backup.label !== "string" || !isObject(backup.listing) || !Array.isArray(backup.lines)) {
218
+ return { exit: 1, error: `SERVICE_ANSWER_INVALID: backup answered without a backup: ${JSON.stringify(sent.answer).slice(0, 300)}` };
219
+ }
220
+ return { backup };
221
+ }
222
+ function describeBackupLine(line) {
223
+ if (line.unreadable === true)
224
+ return `unreadable line at ${String(line.offset)} (${String(line.bytes)} bytes)`;
225
+ if (line.boundary === true)
226
+ return `--- ${String(line.message)} ---`;
227
+ const refused = isObject(line.refused) ? ` refused ${String(line.refused.code)}` : "";
228
+ const name = typeof line.name === "string" && line.name !== "" ? ` ${line.name}` : "";
229
+ return `${String(line.at ?? "")} ${String(line.principal ?? "")} ${String(line.op ?? "")}${name}${refused}`;
230
+ }
231
+ async function serviceBackupCommand(target, io = ownerIo()) {
232
+ const host = (target.host ?? "").trim();
233
+ if (host === "" || target.workspace.trim() === "" || target.local) {
234
+ io.err(`SERVICE_INPUT: name the host with --host and --workspace; a backup is read from Hightea, never --local.
235
+ ${USAGE}`);
236
+ return 1;
237
+ }
238
+ const read = await readBackup(target, io, host);
239
+ if ("error" in read) {
240
+ io.err(read.error);
241
+ return read.exit;
242
+ }
243
+ const { backup } = read;
244
+ if (target.json) {
245
+ io.out(JSON.stringify(backup));
246
+ return 0;
247
+ }
248
+ const state = backup.hostStatus === "revoked" ? `revoked ${backup.revokedAt ?? ""}`.trim() : backup.connected ? "connected" : "offline";
249
+ io.out(`${host} (${state}): ${backup.label}`);
250
+ if (typeof backup.reason === "string")
251
+ io.out(`last pull: ${backup.reason}`);
252
+ io.out(listing({ ok: true, ...backup.listing }, host));
253
+ io.out(backup.lines.length === 0 ? "no changes backed up" : `changes, oldest first (${backup.lines.length}):`);
254
+ for (const { line } of backup.lines)
255
+ io.out(` ${describeBackupLine(line)}`);
256
+ return 0;
257
+ }
258
+ function restoreIo() {
259
+ return {
260
+ ...ownerIo(),
261
+ confirm: async (question) => {
262
+ const { createInterface } = await import("node:readline/promises");
263
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
264
+ try {
265
+ return /^y(es)?$/iu.test((await prompt.question(question)).trim());
266
+ } finally {
267
+ prompt.close();
268
+ }
269
+ }
270
+ };
271
+ }
272
+ async function serviceRestore(target, input, io = restoreIo(), drivers = {}) {
273
+ const from = input.from.trim();
274
+ const to = (target.host ?? "").trim();
275
+ if (from === "" || target.workspace.trim() === "" || !target.local && to === "") {
276
+ io.err(`SERVICE_INPUT: restore names the old host with --from, the workspace with --workspace, and the new host with --host or --local.
277
+ ${USAGE}`);
278
+ return 1;
279
+ }
280
+ const read = await readBackup(target, io, from);
281
+ if ("error" in read) {
282
+ io.err(read.error);
283
+ return read.exit;
284
+ }
285
+ const { backup } = read;
286
+ const all = Array.isArray(backup.listing.services) ? backup.listing.services.filter(isObject) : [];
287
+ const unknown = input.names.filter((name) => !all.some((service) => service.name === name));
288
+ if (unknown.length > 0) {
289
+ io.err(`SERVICE_NOT_IN_BACKUP: ${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not in ${from}'s backup (${backup.label}); it holds ${all.map((service) => String(service.name)).join(", ") || "no services"}`);
290
+ return 1;
291
+ }
292
+ const chosen = input.names.length === 0 ? all : all.filter((service) => input.names.includes(String(service.name)));
293
+ if (chosen.length === 0) {
294
+ io.err(`SERVICE_NOTHING_TO_RESTORE: ${from}'s backup (${backup.label}) holds no services`);
295
+ return 1;
296
+ }
297
+ const driver = target.local ? await (drivers.local ?? localDriver)(target) : remoteDriver(target, io);
298
+ if ("error" in driver) {
299
+ io.err(driver.error);
300
+ return 1;
301
+ }
302
+ const secretsOf = (service) => isObject(service.env) ? Object.entries(service.env).map(([key, value]) => `${key} (${String(isObject(value) ? value.$secret : value)})`) : [];
303
+ const plainOf = (service) => Array.isArray(service.plainEnv) ? service.plainEnv.map(String) : [];
304
+ io.err(`restore from ${from} (${backup.label}) to ${driver.machine}, create only:`);
305
+ for (const service of chosen) {
306
+ io.err(` ${String(service.name)} ${String(service.command ?? "")}`);
307
+ const secrets = secretsOf(service);
308
+ if (secrets.length > 0)
309
+ io.err(` secrets to enter again on ${driver.machine}: ${secrets.join(", ")}`);
310
+ }
311
+ if (!input.yes && !await io.confirm(`create ${chosen.length} service${chosen.length === 1 ? "" : "s"} on ${driver.machine}? [y/N] `)) {
312
+ io.err("SERVICE_RESTORE_DECLINED: nothing was sent");
313
+ return 1;
314
+ }
315
+ const results = [];
316
+ for (const service of chosen) {
317
+ const { plainEnv: _keysOnly, ...record } = service;
318
+ const name = String(service.name);
319
+ const secrets = secretsOf(service), plainEnv = plainOf(service);
320
+ const reached = await driver.put({ service: record, ifVersion: "absent" });
321
+ if ("error" in reached) {
322
+ const [code = "SERVICE_FAILED", ...rest] = reached.error.split(": ");
323
+ results.push({ name, outcome: "failed", code, message: rest.join(": "), secrets, plainEnv });
324
+ } else if (!reached.answer.ok) {
325
+ results.push({ name, outcome: "refused", code: String(reached.answer.code ?? "SERVICE_REFUSED"), message: String(reached.answer.message ?? ""), secrets, plainEnv });
326
+ } else {
327
+ results.push({ name, outcome: "created", secrets, plainEnv });
328
+ }
329
+ }
330
+ if (target.json)
331
+ io.out(JSON.stringify({ from, to: driver.machine, label: backup.label, results }));
332
+ else {
333
+ for (const result of results) {
334
+ io.out(result.outcome === "created" ? `created ${result.name}` : `${result.outcome} ${result.name}: ${result.code}: ${result.message}`);
335
+ if (result.outcome === "created" && result.secrets.length > 0)
336
+ io.out(` secrets to enter again: ${result.secrets.join(", ")}`);
337
+ if (result.outcome === "created" && result.plainEnv.length > 0)
338
+ io.out(` plain values never backed up: ${result.plainEnv.join("; ")}`);
339
+ }
340
+ }
341
+ return results.every((result) => result.outcome === "created") ? 0 : 1;
342
+ }
343
+ export {
344
+ serviceBackupCommand,
345
+ serviceCommand,
346
+ serviceRestore
347
+ };
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "id": "hightea-pipe",
3
3
  "main": "./plugin.mjs",
4
- "version": "0.1.1"
4
+ "version": "0.1.8"
5
5
  }