@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,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,8 +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
+ import { createRequire } from "node:module";
3
4
  import { homedir } from "node:os";
4
- import { basename, dirname as dirname3, isAbsolute as isAbsolute3, join as join5, resolve } from "node:path";
5
- 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";
6
7
  import { fileVault as fileVault2 } from "@ahpd/server/dist/vault.js";
7
8
 
8
9
  // ../ahp-host/src/claim.ts
@@ -12,6 +13,11 @@ import { link, lstat, mkdir, mkdtemp, open as open2, realpath, rm } from "node:f
12
13
  import { dirname, join } from "node:path";
13
14
  import { isDeepStrictEqual } from "node:util";
14
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;
15
21
  // ../members/src/members-store.ts
16
22
  var DEFAULT_SESSION_TTL_MS = 30 * 86400000;
17
23
  var AGENT_BINDING_REQUEST_TTL_MS = 15 * 60000;
@@ -5150,6 +5156,26 @@ function superRefine(fn, params) {
5150
5156
  return _superRefine(fn, params);
5151
5157
  }
5152
5158
  // ../members/src/host-join-types.ts
5159
+ var JOIN_ROUTE_REFUSAL_STATUS = {
5160
+ JOIN_LINK_INVALID: 410,
5161
+ JOIN_LINK_NOT_FOUND: 404,
5162
+ ROLE_NOT_ALLOWED: 400,
5163
+ NOT_A_MEMBER: 403,
5164
+ PEOPLE_LIMIT: 409,
5165
+ AGENTS_LIMIT: 409,
5166
+ FORBIDDEN: 403,
5167
+ HOST_REGISTRATION_CANCELLED: 410,
5168
+ HOST_REGISTRATION_CONFLICT: 409,
5169
+ AGENT_HOST_CONFLICT: 409,
5170
+ HOST_REGISTRATION_MISSING: 409,
5171
+ INVALID_REQUEST: 400,
5172
+ BAD_ORIGIN: 403,
5173
+ UNAUTHENTICATED: 401,
5174
+ WORKSPACE_NOT_FOUND: 404
5175
+ };
5176
+ function isJoinRouteRefusalCode(value) {
5177
+ return typeof value === "string" && Object.hasOwn(JOIN_ROUTE_REFUSAL_STATUS, value);
5178
+ }
5153
5179
  var id = string2().min(1).max(256);
5154
5180
  var digest = string2().regex(/^sha256:[a-f0-9]{64}$/u);
5155
5181
  var version2 = string2().min(1).max(64);
@@ -5412,6 +5438,24 @@ async function saveHostJson(claim, directory, name, configuration) {
5412
5438
 
5413
5439
  // ../ahp-host/src/join.ts
5414
5440
  import { isRecord } from "@ahpd/sdk";
5441
+ class HostJoinRefusal extends Error {
5442
+ kind;
5443
+ status;
5444
+ serverCode;
5445
+ constructor(kind, status, serverCode) {
5446
+ super(kind);
5447
+ this.kind = kind;
5448
+ this.status = status;
5449
+ this.serverCode = serverCode;
5450
+ }
5451
+ }
5452
+ function refusalKind(status, serverCode) {
5453
+ if (status === 401 || status === 403)
5454
+ return "HOST_JOIN_NOT_AUTHORISED";
5455
+ if (serverCode === "AGENT_HOST_CONFLICT" || serverCode === "HOST_REGISTRATION_CONFLICT")
5456
+ return "HOST_JOIN_AGENT_BOUND";
5457
+ return "HOST_JOIN_REJECTED";
5458
+ }
5415
5459
  async function redeemHostClaim(claim) {
5416
5460
  await flushHostFile(claim.vaultFile);
5417
5461
  const intent = claim.intent;
@@ -5439,8 +5483,14 @@ async function redeemHostClaim(claim) {
5439
5483
  }
5440
5484
  if (response.status >= 500)
5441
5485
  throw new Error("HOST_JOIN_REMOTE_UNAVAILABLE");
5442
- if (!response.ok)
5443
- throw new Error("HOST_JOIN_REJECTED");
5486
+ if (!response.ok) {
5487
+ let error;
5488
+ try {
5489
+ error = await response.json();
5490
+ } catch {}
5491
+ const serverCode = isRecord(error) && isRecord(error.error) && isJoinRouteRefusalCode(error.error.code) ? error.error.code : undefined;
5492
+ throw new HostJoinRefusal(refusalKind(response.status, serverCode), response.status, serverCode);
5493
+ }
5444
5494
  let receipt;
5445
5495
  try {
5446
5496
  receipt = await response.json();
@@ -5685,6 +5735,102 @@ function isCode(error, code) {
5685
5735
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
5686
5736
  }
5687
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
+
5688
5834
  // ../ahp-host/src/commands.ts
5689
5835
  var USAGE = "hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json";
5690
5836
  var DIAGNOSTICS = {
@@ -5703,6 +5849,8 @@ var DIAGNOSTICS = {
5703
5849
  HOST_JOIN_CANCELLED: "The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",
5704
5850
  HOST_JOIN_LINK_UNAVAILABLE: "This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",
5705
5851
  HOST_JOIN_REJECTED: "The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",
5852
+ HOST_JOIN_NOT_AUTHORISED: "The deployment refused this account for that workspace or agent. Join with the account that owns the agents in --owner-config; the selected credential was retained.",
5853
+ HOST_JOIN_AGENT_BOUND: "An agent in --owner-config already belongs to another host. Remove that host (or its registration) in the workspace, then rerun the same command; the selected credential was retained.",
5706
5854
  HOST_JOIN_RECEIPT_INVALID: "The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",
5707
5855
  HOST_JOIN_CONFIG_CONFLICT: "Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",
5708
5856
  HOST_JOIN_CONFIG_CORRUPT: "Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it.",
@@ -5711,19 +5859,49 @@ var DIAGNOSTICS = {
5711
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."
5712
5860
  };
5713
5861
  function xdgHome(variable, fallback) {
5714
- const home = process.env[variable] || join5(homedir(), fallback);
5862
+ const home = process.env[variable] || join7(homedir(), fallback);
5715
5863
  if (!isAbsolute3(home))
5716
5864
  throw new Error("HOST_JOIN_UNSAFE_PATH");
5717
5865
  return home;
5718
5866
  }
5719
- async function hostJoin(input, plugin) {
5867
+ function installedDaemon() {
5868
+ const manifest = createRequire(import.meta.url).resolve("@ahpd/server/package.json");
5869
+ return { node: process.execPath, main: join7(dirname3(manifest), "dist", "main.js") };
5870
+ }
5871
+ var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
5872
+ function hostStartCommand(claim, daemon = installedDaemon()) {
5873
+ return `XDG_CONFIG_HOME=${shellQuote(claim)} ${shellQuote(daemon.node)} ${shellQuote(daemon.main)} start`;
5874
+ }
5875
+ var SERVER_REFUSALS = {
5876
+ JOIN_LINK_INVALID: "the join code is no longer valid",
5877
+ JOIN_LINK_NOT_FOUND: "no such join code in that workspace",
5878
+ ROLE_NOT_ALLOWED: "the join code does not allow this role",
5879
+ NOT_A_MEMBER: "the signed-in account is not a member of that workspace",
5880
+ FORBIDDEN: "an agent in --owner-config belongs to another account",
5881
+ HOST_REGISTRATION_CANCELLED: "the owner cancelled this registration",
5882
+ HOST_REGISTRATION_CONFLICT: "this code was redeemed for a different host registration",
5883
+ AGENT_HOST_CONFLICT: "an agent already belongs to another active host",
5884
+ HOST_REGISTRATION_MISSING: "the pending registration is gone",
5885
+ INVALID_REQUEST: "the deployment did not accept this request's shape",
5886
+ BAD_ORIGIN: "the request came from another site",
5887
+ UNAUTHENTICATED: "the request carried no signed-in 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"
5891
+ };
5892
+ var REFUSAL_EXIT = { HOST_JOIN_NOT_AUTHORISED: 3, HOST_JOIN_AGENT_BOUND: 4, HOST_JOIN_REJECTED: 1 };
5893
+ function refusalLine(refusal) {
5894
+ const meaning = refusal.serverCode === undefined ? "" : ` The deployment says ${SERVER_REFUSALS[refusal.serverCode]}.`;
5895
+ return `${refusal.kind}: ${DIAGNOSTICS[refusal.kind]}${meaning} (HTTP ${refusal.status}, server code ${refusal.serverCode ?? "unrecognised"})`;
5896
+ }
5897
+ async function hostJoin2(input, plugin) {
5720
5898
  try {
5721
5899
  const { origin, workspace, code, ownerConfig: ownerFile } = input;
5722
5900
  if (!origin || !workspace || !code || !ownerFile)
5723
5901
  throw new Error("HOST_JOIN_USAGE");
5724
5902
  const ownerConfiguration = await readOwnerConfiguration(resolve(ownerFile));
5725
5903
  const configHome = xdgHome("XDG_CONFIG_HOME", ".config");
5726
- const dataHome = xdgHome("XDG_DATA_HOME", join5(".local", "share"));
5904
+ const dataHome = xdgHome("XDG_DATA_HOME", join7(".local", "share"));
5727
5905
  const claim = await selectHostClaim(configHome, {
5728
5906
  origin,
5729
5907
  workspaceSlug: workspace,
@@ -5776,7 +5954,7 @@ async function hostJoin(input, plugin) {
5776
5954
  pluginMarketplaces: [],
5777
5955
  plugins: [...ownerConfiguration.plugins, {
5778
5956
  source: bundle.manifest,
5779
- grants: ["session:write", "session:state", "chat:turns"],
5957
+ grants: ["session:write", "session:state", "chat:turns", "agent:list"],
5780
5958
  options: {
5781
5959
  cloudUrl: cloud.href,
5782
5960
  houseId: receipt.workspaceId,
@@ -5786,19 +5964,26 @@ async function hostJoin(input, plugin) {
5786
5964
  }
5787
5965
  }]
5788
5966
  });
5789
- console.log("Host registered; local configuration saved. Daemon startup requires platform setup.");
5967
+ console.log(`Host registered; local configuration saved. Start it with: ${hostStartCommand(claim.home)}`);
5790
5968
  return 0;
5791
5969
  } catch (error) {
5970
+ if (error instanceof HostJoinRefusal) {
5971
+ console.error(refusalLine(error));
5972
+ return REFUSAL_EXIT[error.kind];
5973
+ }
5792
5974
  const code = error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message) ? error.message : "HOST_JOIN_INPUT";
5793
5975
  console.error(`${code}: ${DIAGNOSTICS[code] ?? "Local claim storage could not be safely published or flushed. Keep the existing files, check filesystem access and retry; no replacement credential was selected."}`);
5794
5976
  return 1;
5795
5977
  }
5796
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
+ }
5797
5982
  async function readStatusEntry(claim) {
5798
- const config = join5(claim, "ahpd", "config.json");
5983
+ const config = join7(claim, "ahpd", "config.json");
5799
5984
  let text;
5800
5985
  try {
5801
- text = await readFile2(config, "utf8");
5986
+ text = await readFile3(config, "utf8");
5802
5987
  } catch (error) {
5803
5988
  const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
5804
5989
  return missing ? { claim, state: "pending" } : { claim, state: "unreadable", config };
@@ -5810,7 +5995,7 @@ async function readStatusEntry(claim) {
5810
5995
  return { claim, state: "unreadable", config };
5811
5996
  }
5812
5997
  const plugins = isRecord3(saved) && Array.isArray(saved.plugins) ? saved.plugins : [];
5813
- 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);
5814
5999
  if (ours === undefined || typeof ours.source !== "string" || !isRecord3(ours.options) || !isRecord3(ours.options.headers)) {
5815
6000
  return { claim, state: "unreadable", config };
5816
6001
  }
@@ -5821,23 +6006,38 @@ async function readStatusEntry(claim) {
5821
6006
  claim,
5822
6007
  state: "joined",
5823
6008
  config,
6009
+ start: hostStartCommand(claim),
5824
6010
  pluginBundle,
5825
6011
  bundle,
5826
6012
  ...installed.ok ? { pluginVersion: installed.bundle.version } : {},
5827
6013
  workspaceId: String(ours.options.houseId),
5828
6014
  hostId: String(ours.options.headers["x-hightea-host"]),
5829
- ...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))
5830
6017
  };
5831
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
+ }
5832
6032
  function versionNote(bundleVersion, cliVersion) {
5833
6033
  if (bundleVersion === undefined)
5834
6034
  return "";
5835
6035
  return bundleVersion === cliVersion ? `, version ${bundleVersion}` : `, version ${bundleVersion}; this CLI is ${cliVersion}`;
5836
6036
  }
5837
- async function hostStatus(options) {
6037
+ async function hostStatus2(options) {
5838
6038
  let claimsDirectory;
5839
6039
  try {
5840
- claimsDirectory = join5(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
6040
+ claimsDirectory = join7(xdgHome("XDG_CONFIG_HOME", ".config"), "hightea", "claims");
5841
6041
  } catch {
5842
6042
  console.error(`HOST_STATUS_UNSAFE_PATH: ${DIAGNOSTICS.HOST_JOIN_UNSAFE_PATH}`);
5843
6043
  return 1;
@@ -5852,7 +6052,7 @@ async function hostStatus(options) {
5852
6052
  return 1;
5853
6053
  }
5854
6054
  }
5855
- 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))));
5856
6056
  if (options.json)
5857
6057
  console.log(JSON.stringify({ version: options.version, claims: claimsDirectory, hosts: entries }, null, 2));
5858
6058
  else {
@@ -5866,7 +6066,9 @@ async function hostStatus(options) {
5866
6066
  `joined workspace ${entry.workspaceId} host ${entry.hostId}`,
5867
6067
  ` gateway ${entry.gateway ?? "(none)"}`,
5868
6068
  ` config ${entry.config}`,
5869
- ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`
6069
+ ` start ${entry.start}`,
6070
+ ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`,
6071
+ ` key ${signingKeyLine(entry.signingKey)}`
5870
6072
  ].join(`
5871
6073
  `));
5872
6074
  }
@@ -5889,7 +6091,86 @@ async function hostStatus(options) {
5889
6091
  }
5890
6092
  return 0;
5891
6093
  }
5892
- export {
5893
- hostJoin,
5894
- hostStatus
5895
- };
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
+ };