@hallohuman/hightea 0.1.2 → 0.1.9

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,78 @@
1
+ import"./chunk-0ab6h39c.js";
2
+ import {
3
+ ownerIo,
4
+ sendOwner
5
+ } from "./chunk-sbqmqp8e.js";
6
+
7
+ // src/host.ts
8
+ var USAGE = `hightea host list --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
9
+ ` + "hightea host remove --origin https://your-deployment --workspace SLUG --host HOST [--session-file FILE] [--json]";
10
+ async function hostRemove(target, io = ownerIo()) {
11
+ if (target.workspace.trim().length === 0 || target.host.trim().length === 0) {
12
+ io.err(`HOST_REMOVE_INPUT: --workspace and --host are required.
13
+ ${USAGE}`);
14
+ return 1;
15
+ }
16
+ const hostId = target.host.trim();
17
+ const sent = await sendOwner(target, io, {
18
+ method: "DELETE",
19
+ path: `/hosts/${encodeURIComponent(hostId)}`,
20
+ what: "remove",
21
+ label: "HOST_REMOVE"
22
+ });
23
+ if ("error" in sent) {
24
+ io.err(sent.error);
25
+ return sent.exit;
26
+ }
27
+ if (target.json) {
28
+ io.out(JSON.stringify(sent.answer));
29
+ return 0;
30
+ }
31
+ const host = sent.answer.host ?? {};
32
+ const ended = typeof host.endedDeliveries === "number" ? host.endedDeliveries : 0;
33
+ const name = String(host.hostId ?? hostId);
34
+ if (host.alreadyRevoked === true) {
35
+ io.out(`host ${name} was already removed; nothing was left running`);
36
+ return 0;
37
+ }
38
+ io.out(`removed host ${name}: revoked, ${ended} ${ended === 1 ? "delivery" : "deliveries"} ended`);
39
+ io.out("Its agents have no host until they join again with a new join code.");
40
+ return 0;
41
+ }
42
+ function hostLine(host) {
43
+ const field = (name) => host[name] === null || host[name] === undefined ? "none" : String(host[name]);
44
+ const agents = Array.isArray(host.agentMemberIds) && host.agentMemberIds.length > 0 ? host.agentMemberIds.join(",") : "none";
45
+ const state = field("status") === "revoked" ? `revoked ${field("revokedAt")}` : `last seen ${field("lastSeenAt")}`;
46
+ return `${field("hostId")} ${field("status")} ${host.connected === true ? "connected" : "not connected"} ` + `agents ${agents} owner ${field("ownerAccountId")} ${state}`;
47
+ }
48
+ async function hostList(target, io = ownerIo()) {
49
+ if (target.workspace.trim().length === 0) {
50
+ io.err(`HOST_LIST_INPUT: --workspace is required.
51
+ ${USAGE}`);
52
+ return 1;
53
+ }
54
+ const sent = await sendOwner(target, io, { method: "GET", path: "/hosts", what: "list", label: "HOST_LIST" });
55
+ if ("error" in sent) {
56
+ io.err(sent.error);
57
+ return sent.exit;
58
+ }
59
+ if (target.json) {
60
+ io.out(JSON.stringify(sent.answer));
61
+ return 0;
62
+ }
63
+ const hosts = Array.isArray(sent.answer.hosts) ? sent.answer.hosts : [];
64
+ if (hosts.length === 0) {
65
+ io.out(`no hosts in workspace ${target.workspace.trim()} that your account can see (a workspace owner sees every host)`);
66
+ return 0;
67
+ }
68
+ io.out(hosts.map(hostLine).join(`
69
+ `));
70
+ if (hosts.some((host) => host.status === "active")) {
71
+ io.out("A host you no longer use: `hightea host remove --workspace " + target.workspace.trim() + " --host <id>`.");
72
+ }
73
+ return 0;
74
+ }
75
+ export {
76
+ hostList,
77
+ hostRemove
78
+ };
@@ -0,0 +1,14 @@
1
+ import {
2
+ checkedOrigin2,
3
+ ensureCredential2,
4
+ authLogin2,
5
+ authStatus2,
6
+ authLogout2
7
+ } from "./chunk-0ab6h39c.js";
8
+ export {
9
+ authLogin2 as authLogin,
10
+ authLogout2 as authLogout,
11
+ authStatus2 as authStatus,
12
+ checkedOrigin2 as checkedOrigin,
13
+ ensureCredential2 as ensureCredential
14
+ };
@@ -1,9 +1,9 @@
1
1
  // ../ahp-host/src/commands.ts
2
- import { readdir, readFile as readFile2 } from "node:fs/promises";
2
+ import { readdir, readFile as readFile3 } from "node:fs/promises";
3
3
  import { createRequire } from "node:module";
4
4
  import { homedir } from "node:os";
5
- import { basename, dirname as dirname3, isAbsolute as isAbsolute3, join as join5, resolve } from "node:path";
6
- import { fromEnvRef as fromEnvRef2, isRecord as isRecord3, readSecret, secretRef as secretRef2 } from "@ahpd/sdk";
5
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute3, join as join7, resolve } from "node:path";
6
+ import { fromEnvRef as fromEnvRef2, isRecord as isRecord3, readJsonObject as readJsonObject3, readSecret, secretRef as secretRef2, writeJsonAtomic as writeJsonAtomic2 } from "@ahpd/sdk";
7
7
  import { fileVault as fileVault2 } from "@ahpd/server/dist/vault.js";
8
8
 
9
9
  // ../ahp-host/src/claim.ts
@@ -13,6 +13,11 @@ import { link, lstat, mkdir, mkdtemp, open as open2, realpath, rm } from "node:f
13
13
  import { dirname, join } from "node:path";
14
14
  import { isDeepStrictEqual } from "node:util";
15
15
  import { fileVault } from "@ahpd/server/dist/vault.js";
16
+ // ../members/src/waitlist.ts
17
+ var migrations = new WeakMap;
18
+ // ../members/src/invitations.ts
19
+ var INVITATION_TTL_MS = 30 * 86400000;
20
+ var migrations2 = new WeakMap;
16
21
  // ../members/src/members-store.ts
17
22
  var DEFAULT_SESSION_TTL_MS = 30 * 86400000;
18
23
  var AGENT_BINDING_REQUEST_TTL_MS = 15 * 60000;
@@ -5156,6 +5161,8 @@ var JOIN_ROUTE_REFUSAL_STATUS = {
5156
5161
  JOIN_LINK_NOT_FOUND: 404,
5157
5162
  ROLE_NOT_ALLOWED: 400,
5158
5163
  NOT_A_MEMBER: 403,
5164
+ PEOPLE_LIMIT: 409,
5165
+ AGENTS_LIMIT: 409,
5159
5166
  FORBIDDEN: 403,
5160
5167
  HOST_REGISTRATION_CANCELLED: 410,
5161
5168
  HOST_REGISTRATION_CONFLICT: 409,
@@ -5728,6 +5735,102 @@ function isCode(error, code) {
5728
5735
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
5729
5736
  }
5730
5737
 
5738
+ // ../ahp-host/src/ask-gate.ts
5739
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign as sign2 } from "node:crypto";
5740
+ import { appendFile, chmod, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
5741
+ import { join as join6 } from "node:path";
5742
+
5743
+ // ../ahp-host/src/signed-asks.ts
5744
+ var ED25519_SPKI_HEADER = Buffer.from("302a300506032b6570032100", "hex");
5745
+
5746
+ // ../ahp-host/src/trusted-keys.ts
5747
+ import { createHash as createHash3 } from "node:crypto";
5748
+ import { existsSync, readFileSync } from "node:fs";
5749
+ import { join as join5 } from "node:path";
5750
+ var TRUSTED_KEYS_FILE = "trusted-keys.json";
5751
+ var TRUSTED_KEY_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
5752
+ var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u;
5753
+ var base64url2 = (bytes) => Buffer.from(bytes).toString("base64url");
5754
+ function trustedKeyId(publicKey) {
5755
+ if (!BASE64URL_32_BYTES.test(publicKey)) {
5756
+ return { error: "TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it" };
5757
+ }
5758
+ return { keyId: base64url2(createHash3("sha256").update(Buffer.from(publicKey, "base64url")).digest()) };
5759
+ }
5760
+ function readTrustedKeys(configDir) {
5761
+ const file = join5(configDir, TRUSTED_KEYS_FILE);
5762
+ if (!existsSync(file))
5763
+ return { state: "missing", file };
5764
+ let parsed;
5765
+ try {
5766
+ parsed = JSON.parse(readFileSync(file, "utf8"));
5767
+ } catch (error) {
5768
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not JSON (${error.message})`);
5769
+ }
5770
+ const record = parsed;
5771
+ if (typeof parsed !== "object" || parsed === null || record.v !== 1 || !Array.isArray(record.keys)) {
5772
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not a version 1 list of trusted keys`);
5773
+ }
5774
+ for (const key of record.keys) {
5775
+ const row = key;
5776
+ const id = typeof row.publicKey === "string" ? trustedKeyId(row.publicKey) : undefined;
5777
+ if (typeof row.name !== "string" || !TRUSTED_KEY_NAME.test(row.name) || id === undefined || "error" in id || row.keyId !== id.keyId || typeof row.addedAt !== "string") {
5778
+ throw new Error(`TRUST_FILE_UNREADABLE: ${file} holds an entry that is not a valid trusted key: ${JSON.stringify(key)}`);
5779
+ }
5780
+ }
5781
+ return { state: "read", file, keys: record.keys };
5782
+ }
5783
+
5784
+ // ../ahp-host/src/ask-gate.ts
5785
+ var HOST_SIGNING_KEY_FILE = "host-signing-key";
5786
+ var ASK_FRESH_MS = 10 * 60000;
5787
+ var ACTED_KEEP_MS = 30 * 24 * 60 * 60000;
5788
+ async function readHostSigningKey(configDir) {
5789
+ try {
5790
+ await readFile2(join6(configDir, HOST_SIGNING_KEY_FILE));
5791
+ } catch (error) {
5792
+ if (error.code === "ENOENT")
5793
+ return { state: "missing" };
5794
+ }
5795
+ try {
5796
+ return { state: "ok", key: await hostSigningKey(configDir) };
5797
+ } catch (error) {
5798
+ return { state: "unreadable", reason: error instanceof Error ? error.message : String(error) };
5799
+ }
5800
+ }
5801
+ async function hostSigningKey(configDir, now = () => Date.now()) {
5802
+ const file = join6(configDir, HOST_SIGNING_KEY_FILE);
5803
+ let pem;
5804
+ try {
5805
+ pem = await readFile2(file, "utf8");
5806
+ } catch (error) {
5807
+ if (error.code !== "ENOENT") {
5808
+ throw new Error(`HOST_KEY_UNREADABLE: ${file} exists but cannot be read (${String(error)}); it is never regenerated, fix or remove it by hand`);
5809
+ }
5810
+ }
5811
+ if (pem === undefined) {
5812
+ const made = generateKeyPairSync("ed25519").privateKey.export({ format: "pem", type: "pkcs8" }).toString();
5813
+ const temporary = `${file}.${String(process.pid)}.tmp`;
5814
+ await writeFile2(temporary, made, { mode: 384, flag: "wx" });
5815
+ await chmod(temporary, 384);
5816
+ await rename2(temporary, file);
5817
+ pem = made;
5818
+ }
5819
+ let privateKey;
5820
+ try {
5821
+ privateKey = createPrivateKey({ key: pem, format: "pem" });
5822
+ if (privateKey.asymmetricKeyType !== "ed25519")
5823
+ throw new Error(`a ${String(privateKey.asymmetricKeyType)} key, not Ed25519`);
5824
+ } catch (error) {
5825
+ throw new Error(`HOST_KEY_UNREADABLE: ${file} is not an Ed25519 PKCS8 key (${String(error)}); it is never regenerated, fix or remove it by hand`);
5826
+ }
5827
+ const publicKey = createPublicKey(privateKey).export({ format: "jwk" }).x;
5828
+ const id = publicKey === undefined ? { error: "no public key" } : trustedKeyId(publicKey);
5829
+ if ("error" in id)
5830
+ throw new Error(`HOST_KEY_UNREADABLE: ${file}: ${id.error}`);
5831
+ return { privateKey, trusted: { name: "this-host", keyId: id.keyId, publicKey, addedAt: new Date(now()).toISOString() } };
5832
+ }
5833
+
5731
5834
  // ../ahp-host/src/commands.ts
5732
5835
  var USAGE = "hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json";
5733
5836
  var DIAGNOSTICS = {
@@ -5756,14 +5859,14 @@ var DIAGNOSTICS = {
5756
5859
  HOST_JOIN_PLUGIN_BUNDLE_CONFLICT: "The installed host plugin for this version differs from this installation's copy. It was preserved; reinstall the same version or repair that directory. No configuration was written."
5757
5860
  };
5758
5861
  function xdgHome(variable, fallback) {
5759
- const home = process.env[variable] || join5(homedir(), fallback);
5862
+ const home = process.env[variable] || join7(homedir(), fallback);
5760
5863
  if (!isAbsolute3(home))
5761
5864
  throw new Error("HOST_JOIN_UNSAFE_PATH");
5762
5865
  return home;
5763
5866
  }
5764
5867
  function installedDaemon() {
5765
5868
  const manifest = createRequire(import.meta.url).resolve("@ahpd/server/package.json");
5766
- return { node: process.execPath, main: join5(dirname3(manifest), "dist", "main.js") };
5869
+ return { node: process.execPath, main: join7(dirname3(manifest), "dist", "main.js") };
5767
5870
  }
5768
5871
  var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
5769
5872
  function hostStartCommand(claim, daemon = installedDaemon()) {
@@ -5782,21 +5885,23 @@ var SERVER_REFUSALS = {
5782
5885
  INVALID_REQUEST: "the deployment did not accept this request's shape",
5783
5886
  BAD_ORIGIN: "the request came from another site",
5784
5887
  UNAUTHENTICATED: "the request carried no signed-in account",
5785
- WORKSPACE_NOT_FOUND: "no such workspace for this account"
5888
+ WORKSPACE_NOT_FOUND: "no such workspace for this account",
5889
+ PEOPLE_LIMIT: "that workspace is at its beta limit of people",
5890
+ AGENTS_LIMIT: "that workspace is at its beta limit of agents"
5786
5891
  };
5787
5892
  var REFUSAL_EXIT = { HOST_JOIN_NOT_AUTHORISED: 3, HOST_JOIN_AGENT_BOUND: 4, HOST_JOIN_REJECTED: 1 };
5788
5893
  function refusalLine(refusal) {
5789
5894
  const meaning = refusal.serverCode === undefined ? "" : ` The deployment says ${SERVER_REFUSALS[refusal.serverCode]}.`;
5790
5895
  return `${refusal.kind}: ${DIAGNOSTICS[refusal.kind]}${meaning} (HTTP ${refusal.status}, server code ${refusal.serverCode ?? "unrecognised"})`;
5791
5896
  }
5792
- async function hostJoin(input, plugin) {
5897
+ async function hostJoin2(input, plugin) {
5793
5898
  try {
5794
5899
  const { origin, workspace, code, ownerConfig: ownerFile } = input;
5795
5900
  if (!origin || !workspace || !code || !ownerFile)
5796
5901
  throw new Error("HOST_JOIN_USAGE");
5797
5902
  const ownerConfiguration = await readOwnerConfiguration(resolve(ownerFile));
5798
5903
  const configHome = xdgHome("XDG_CONFIG_HOME", ".config");
5799
- const dataHome = xdgHome("XDG_DATA_HOME", join5(".local", "share"));
5904
+ const dataHome = xdgHome("XDG_DATA_HOME", join7(".local", "share"));
5800
5905
  const claim = await selectHostClaim(configHome, {
5801
5906
  origin,
5802
5907
  workspaceSlug: workspace,
@@ -5849,7 +5954,7 @@ async function hostJoin(input, plugin) {
5849
5954
  pluginMarketplaces: [],
5850
5955
  plugins: [...ownerConfiguration.plugins, {
5851
5956
  source: bundle.manifest,
5852
- grants: ["session:write", "session:state", "chat:turns"],
5957
+ grants: ["session:write", "session:state", "chat:turns", "agent:list"],
5853
5958
  options: {
5854
5959
  cloudUrl: cloud.href,
5855
5960
  houseId: receipt.workspaceId,
@@ -5871,11 +5976,14 @@ async function hostJoin(input, plugin) {
5871
5976
  return 1;
5872
5977
  }
5873
5978
  }
5979
+ function isHighteaPipeEntry(entry) {
5980
+ return isRecord3(entry) && isRecord3(entry.options) && typeof entry.options.houseId === "string" && isRecord3(entry.options.headers) && typeof entry.options.headers["x-hightea-host"] === "string";
5981
+ }
5874
5982
  async function readStatusEntry(claim) {
5875
- const config = join5(claim, "ahpd", "config.json");
5983
+ const config = join7(claim, "ahpd", "config.json");
5876
5984
  let text;
5877
5985
  try {
5878
- text = await readFile2(config, "utf8");
5986
+ text = await readFile3(config, "utf8");
5879
5987
  } catch (error) {
5880
5988
  const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
5881
5989
  return missing ? { claim, state: "pending" } : { claim, state: "unreadable", config };
@@ -5887,7 +5995,7 @@ async function readStatusEntry(claim) {
5887
5995
  return { claim, state: "unreadable", config };
5888
5996
  }
5889
5997
  const plugins = isRecord3(saved) && Array.isArray(saved.plugins) ? saved.plugins : [];
5890
- const ours = plugins.find((entry) => isRecord3(entry) && isRecord3(entry.options) && typeof entry.options.houseId === "string" && isRecord3(entry.options.headers) && typeof entry.options.headers["x-hightea-host"] === "string");
5998
+ const ours = plugins.find(isHighteaPipeEntry);
5891
5999
  if (ours === undefined || typeof ours.source !== "string" || !isRecord3(ours.options) || !isRecord3(ours.options.headers)) {
5892
6000
  return { claim, state: "unreadable", config };
5893
6001
  }
@@ -5904,18 +6012,32 @@ async function readStatusEntry(claim) {
5904
6012
  ...installed.ok ? { pluginVersion: installed.bundle.version } : {},
5905
6013
  workspaceId: String(ours.options.houseId),
5906
6014
  hostId: String(ours.options.headers["x-hightea-host"]),
5907
- ...typeof ours.options.cloudUrl === "string" ? { gateway: ours.options.cloudUrl } : {}
6015
+ ...typeof ours.options.cloudUrl === "string" ? { gateway: ours.options.cloudUrl } : {},
6016
+ signingKey: await statusSigningKey(dirname3(config))
5908
6017
  };
5909
6018
  }
6019
+ async function statusSigningKey(configDir) {
6020
+ const read = await readHostSigningKey(configDir);
6021
+ if (read.state === "ok")
6022
+ return { state: "ok", keyId: read.key.trusted.keyId, publicKey: read.key.trusted.publicKey };
6023
+ return read;
6024
+ }
6025
+ function signingKeyLine(key) {
6026
+ if (key === undefined || key.state === "missing")
6027
+ return "(made on this host's first start)";
6028
+ if (key.state === "unreadable")
6029
+ return `unreadable: ${key.reason}`;
6030
+ return `${key.keyId} public ${key.publicKey} (another machine trusts it with: hightea host trust add <name> ${key.publicKey})`;
6031
+ }
5910
6032
  function versionNote(bundleVersion, cliVersion) {
5911
6033
  if (bundleVersion === undefined)
5912
6034
  return "";
5913
6035
  return bundleVersion === cliVersion ? `, version ${bundleVersion}` : `, version ${bundleVersion}; this CLI is ${cliVersion}`;
5914
6036
  }
5915
- async function hostStatus(options) {
6037
+ async function hostStatus2(options) {
5916
6038
  let claimsDirectory;
5917
6039
  try {
5918
- claimsDirectory = join5(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
6040
+ claimsDirectory = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
5919
6041
  } catch {
5920
6042
  console.error(`HOST_STATUS_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}`);
5921
6043
  return 1;
@@ -5930,7 +6052,7 @@ async function hostStatus(options) {
5930
6052
  return 1;
5931
6053
  }
5932
6054
  }
5933
- const entries = await Promise.all(names.map((name) => readStatusEntry(join5(claimsDirectory, name))));
6055
+ const entries = await Promise.all(names.map((name) => readStatusEntry(join7(claimsDirectory, name))));
5934
6056
  if (options.json)
5935
6057
  console.log(JSON.stringify({ version: options.version, claims: claimsDirectory, hosts: entries }, null, 2));
5936
6058
  else {
@@ -5945,7 +6067,8 @@ async function hostStatus(options) {
5945
6067
  ` gateway ${entry.gateway ?? "(none)"}`,
5946
6068
  ` config ${entry.config}`,
5947
6069
  ` start ${entry.start}`,
5948
- ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`
6070
+ ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`,
6071
+ ` key ${signingKeyLine(entry.signingKey)}`
5949
6072
  ].join(`
5950
6073
  `));
5951
6074
  }
@@ -5968,7 +6091,86 @@ async function hostStatus(options) {
5968
6091
  }
5969
6092
  return 0;
5970
6093
  }
5971
- export {
5972
- hostJoin,
5973
- hostStatus
5974
- };
6094
+ var SERVICES_GRANTS = ["services:list", "services:get", "services:put", "services:delete", "services:control"];
6095
+ async function localHost2(host) {
6096
+ let claims;
6097
+ try {
6098
+ claims = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
6099
+ } catch {
6100
+ return { error: `SERVICE_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}` };
6101
+ }
6102
+ let names = [];
6103
+ try {
6104
+ names = (await readdir(claims)).filter((name) => !name.startsWith(".")).sort();
6105
+ } catch (error) {
6106
+ const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
6107
+ if (!missing)
6108
+ return { error: `SERVICE_HOST_UNREADABLE: cannot list ${claims}` };
6109
+ }
6110
+ const entries = await Promise.all(names.map((name) => readStatusEntry(join7(claims, name))));
6111
+ const joined = entries.filter((entry) => entry.state === "joined");
6112
+ const wanted = host?.trim();
6113
+ if (wanted !== undefined && wanted !== "") {
6114
+ const named = joined.find((entry) => entry.hostId === wanted);
6115
+ if (named === undefined) {
6116
+ return { error: `SERVICE_HOST_UNKNOWN: no joined host ${wanted} on this machine (joined here: ${joined.map((entry) => entry.hostId).join(", ") || "none"})` };
6117
+ }
6118
+ return toLocalHost(named);
6119
+ }
6120
+ if (joined.length === 0) {
6121
+ const unreadable = entries.find((entry) => entry.state === "unreadable");
6122
+ return { error: unreadable === undefined ? `SERVICE_NO_HOST: no joined host under ${claims}; join this machine with \`hightea host join\` first` : `SERVICE_HOST_UNREADABLE: ${unreadable.config} could not be read; it was left unchanged` };
6123
+ }
6124
+ if (joined.length > 1) {
6125
+ return { error: `SERVICE_HOST_AMBIGUOUS: this machine holds ${joined.length} joined hosts (${joined.map((entry) => entry.hostId).join(", ")}); name one with --host <id>` };
6126
+ }
6127
+ return toLocalHost(joined[0]);
6128
+ }
6129
+ function toLocalHost(entry) {
6130
+ const config = entry.config;
6131
+ return { claim: entry.claim, configDir: dirname3(config), config, workspaceId: entry.workspaceId, hostId: entry.hostId };
6132
+ }
6133
+ async function hostServicesGrants2(options) {
6134
+ const found = await localHost2(options.host);
6135
+ if ("error" in found) {
6136
+ console.error(found.error);
6137
+ return 1;
6138
+ }
6139
+ const read = readJsonObject3(found.config);
6140
+ if (!read.ok) {
6141
+ console.error(`SERVICE_CONFIG_UNREADABLE: ${found.config} could not be read as a JSON object; it was left unchanged`);
6142
+ return 1;
6143
+ }
6144
+ const plugins = Array.isArray(read.value.plugins) ? read.value.plugins : [];
6145
+ const at = plugins.findIndex(isHighteaPipeEntry);
6146
+ const ours = plugins[at];
6147
+ if (ours === undefined) {
6148
+ console.error(`SERVICE_CONFIG_UNREADABLE: ${found.config} holds no Hightea plugin entry; it was left unchanged`);
6149
+ return 1;
6150
+ }
6151
+ if (ours.grants !== undefined && !(Array.isArray(ours.grants) && ours.grants.every((grant) => typeof grant === "string"))) {
6152
+ console.error(`SERVICE_CONFIG_UNREADABLE: the Hightea plugin entry's grants in ${found.config} are not a list of grants; it was left unchanged`);
6153
+ return 1;
6154
+ }
6155
+ const held = ours.grants ?? [];
6156
+ const services = SERVICES_GRANTS;
6157
+ const grants = options.enable ? [...held, ...SERVICES_GRANTS.filter((grant) => !held.includes(grant))] : held.filter((grant) => !services.includes(grant));
6158
+ const what = `Hightea managing this machine's services (host ${found.hostId})`;
6159
+ if (grants.length === held.length && grants.every((grant, index) => grant === held[index])) {
6160
+ console.log(`${what} is already ${options.enable ? "enabled" : "disabled"}; ${found.config} was left unchanged.`);
6161
+ return 0;
6162
+ }
6163
+ const next = plugins.slice();
6164
+ next[at] = { ...ours, grants };
6165
+ try {
6166
+ writeJsonAtomic2(found.config, { ...read.value, plugins: next }, { mode: 384 });
6167
+ } catch (error) {
6168
+ console.error(`SERVICE_CONFIG_UNWRITABLE: ${found.config}: ${error.message}`);
6169
+ return 1;
6170
+ }
6171
+ console.log(`${what} is now ${options.enable ? "enabled" : "disabled"}: ${options.enable ? "added" : "removed"} ${SERVICES_GRANTS.join(", ")} in ${found.config}.`);
6172
+ console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${hostStartCommand(found.claim)}`);
6173
+ return 0;
6174
+ }
6175
+
6176
+ export { TRUSTED_KEY_NAME, trustedKeyId, readTrustedKeys, hostJoin2, hostStatus2, localHost2, hostServicesGrants2 };
@@ -0,0 +1,91 @@
1
+ import {
2
+ TRUSTED_KEY_NAME,
3
+ trustedKeyId,
4
+ readTrustedKeys,
5
+ localHost2
6
+ } from "./chunk-k2ws7xvy.js";
7
+
8
+ // ../ahp-host/src/trust.ts
9
+ import { writeJsonAtomic } from "@ahpd/sdk";
10
+ var TRUST_MEANS = "A trusted browser key lets posts made in that browser ask this machine's agents; a trusted host key " + "lets that machine's agents ask them too.";
11
+ async function hostTrust(input, now = () => new Date) {
12
+ const found = await localHost2(input.host);
13
+ if ("error" in found) {
14
+ console.error(found.error.replace(/^SERVICE_/u, "TRUST_"));
15
+ return 1;
16
+ }
17
+ let current;
18
+ try {
19
+ current = readTrustedKeys(found.configDir);
20
+ } catch (error) {
21
+ console.error(`${error.message}; it was left unchanged`);
22
+ return 1;
23
+ }
24
+ const keys = current.state === "read" ? current.keys : [];
25
+ const where = `host ${found.hostId} (${current.file})`;
26
+ if (input.action === "list") {
27
+ if (input.json === true) {
28
+ console.log(JSON.stringify({ hostId: found.hostId, file: current.file, keys }));
29
+ return 0;
30
+ }
31
+ if (keys.length === 0) {
32
+ console.log(`No trusted keys for ${where}: room asks to this machine's agents are refused until you add one with` + " `hightea host trust add <name> <public key>`.");
33
+ return 0;
34
+ }
35
+ console.log(`Trusted keys for ${where}:`);
36
+ for (const key of keys)
37
+ console.log(` ${key.name} key ${key.keyId} added ${key.addedAt}`);
38
+ console.log(TRUST_MEANS);
39
+ return 0;
40
+ }
41
+ if (!TRUSTED_KEY_NAME.test(input.name)) {
42
+ console.error("TRUST_NAME_INVALID: a name is 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit; nothing was changed");
43
+ return 1;
44
+ }
45
+ const named = keys.find((key) => key.name === input.name);
46
+ if (input.action === "remove") {
47
+ if (named === undefined) {
48
+ console.error(`TRUST_NAME_UNKNOWN: ${where} trusts no key named ${input.name} (trusted: ${keys.map((key) => key.name).join(", ") || "none"}); nothing was changed`);
49
+ return 1;
50
+ }
51
+ if (!write(current.file, keys.filter((key) => key !== named)))
52
+ return 1;
53
+ console.log(`Removed ${input.name} (key ${named.keyId}) from ${where}. Asks signed with it are refused from now on.`);
54
+ return 0;
55
+ }
56
+ const id = trustedKeyId(input.publicKey);
57
+ if ("error" in id) {
58
+ console.error(`${id.error}; nothing was changed`);
59
+ return 1;
60
+ }
61
+ if (named !== undefined) {
62
+ if (named.publicKey === input.publicKey) {
63
+ console.log(`${input.name} (key ${id.keyId}) is already trusted by ${where}; it was left unchanged.`);
64
+ return 0;
65
+ }
66
+ console.error(`TRUST_NAME_TAKEN: ${where} already trusts another key as ${input.name}; remove it first or pick another name. Nothing was changed`);
67
+ return 1;
68
+ }
69
+ const holder = keys.find((key) => key.keyId === id.keyId);
70
+ if (holder !== undefined) {
71
+ console.error(`TRUST_KEY_TAKEN: ${where} already trusts this key as ${holder.name}; nothing was changed`);
72
+ return 1;
73
+ }
74
+ const added = { name: input.name, keyId: id.keyId, publicKey: input.publicKey, addedAt: now().toISOString() };
75
+ if (!write(current.file, [...keys, added]))
76
+ return 1;
77
+ console.log(`Trusted ${input.name} (key ${id.keyId}) on ${where}. ${TRUST_MEANS}`);
78
+ return 0;
79
+ }
80
+ function write(file, keys) {
81
+ try {
82
+ writeJsonAtomic(file, { v: 1, keys }, { mode: 384 });
83
+ } catch (error) {
84
+ console.error(`TRUST_FILE_UNWRITABLE: ${file}: ${error.message}`);
85
+ return false;
86
+ }
87
+ return true;
88
+ }
89
+ export {
90
+ hostTrust
91
+ };
@@ -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 };