@rine-network/cli 0.11.4 → 0.11.6

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.
Files changed (2) hide show
  1. package/dist/main.js +151 -35
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { Command } from "commander";
3
- import { HttpClient, IdempotencyStore, RineApiError, UUID_RE, addMlsGroupMember, agentKeysExist, buildIssueCertDeps, cacheToken, connectTunnel, decryptGroupMessage, decryptMessage, deleteHookSecret, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, ensureCert, externalJoinMlsGroup, fetchAgents, fetchAndIngestPendingSKDistributions, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, handleWebhookRequest, ingestSenderKeyDistribution, initMlsGroup, isBareAgentName, isValidHookName, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMlsState, loadTokenCache, normalizeHandle, performAgentCreation, performRegistration, processMlsWelcomes, resolveAgent, resolveApiUrl, resolveConfigDir, resolveHandleViaWebFinger, resolveToUuid, revokeAndWipeCache, saveAgentKeys, saveCredentials, saveHookSecret, savePqEncryptionKey, saveTokenCache, sendGroupInviteNotification, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug } from "@rine-network/core";
3
+ import { FUNNEL_TIERS, HttpClient, IdempotencyStore, RineApiError, UUID_RE, addMlsGroupMember, agentKeysExist, agentLabel, buildIssueCertDeps, cacheToken, connectTunnel, decryptGroupMessage, decryptMessage, deleteHookSecret, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, ensureCert, externalJoinMlsGroup, fetchAgents, fetchAndIngestPendingSKDistributions, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, handleWebhookRequest, ingestSenderKeyDistribution, initMlsGroup, isBareAgentName, isValidHookName, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsState, loadTokenCache, normalizeHandle, performAgentCreation, performRegistration, processMlsWelcomes, renewalDueWithJitter, resolveAgent, resolveApiUrl, resolveConfigDir, resolveHandleViaWebFinger, resolveToUuid, saveAgentKeys, saveCredentials, saveHookSecret, savePqEncryptionKey, saveTokenCache, sendGroupInviteNotification, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug } from "@rine-network/core";
4
4
  import readline from "node:readline";
5
5
  import * as fs from "node:fs";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
+ import { resolve4 } from "node:dns/promises";
8
9
  import { createEventSource } from "eventsource-client";
9
10
  //#region src/output.ts
10
11
  function printSuccess(msg) {
@@ -909,25 +910,48 @@ function registerGroup(program) {
909
910
  //#region src/commands/hook.ts
910
911
  const SIGNATURE_HEADER = "X-Hub-Signature-256";
911
912
  const CONTENT_TYPE = "application/json";
913
+ const TIER_CLI_TO_WIRE = Object.fromEntries(FUNNEL_TIERS.map((t) => [t.replace("_", "-"), t]));
914
+ /**
915
+ * Map a `--tier` flag value (hyphenated) to the wire FunnelTier, or `undefined`
916
+ * when the flag was omitted (the backend resolves the default). Throws on an
917
+ * unknown value so a typo fails loudly client-side rather than 422'ing.
918
+ */
919
+ function resolveTier(raw) {
920
+ if (raw === void 0) return void 0;
921
+ const wire = TIER_CLI_TO_WIRE[raw];
922
+ if (!wire) throw new Error(`Invalid --tier '${raw}': expected one of ${Object.keys(TIER_CLI_TO_WIRE).join(", ")}.`);
923
+ return wire;
924
+ }
912
925
  function registerHook(program) {
913
926
  const hook = program.command("hook").description("Manage inbound webhook funnel hooks");
914
- hook.command("create").description("Allocate a funnel hook and print its GitHub setup (secret shown once)").option("--agent <id>", "Agent ID (defaults to your agent)").option("--name <name>", "Hook name (default: default)", "default").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
927
+ hook.command("create").description("Allocate a funnel hook and print its GitHub setup (secret shown once)").option("--agent <id>", "Agent ID (defaults to your agent)").option("--name <name>", "Hook name (default: default)", "default").option("--tier <tier>", "TLS-termination tier: zero-trust (relay-terminated) or shared-edge (broker-terminated). Default: by your org's trust tier.").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
915
928
  if (!isValidHookName(opts.name)) {
916
929
  printError(`Invalid hook name '${opts.name}': use lowercase letters, digits and hyphens (max 32).`);
917
930
  process.exitCode = 2;
918
931
  return;
919
932
  }
933
+ let tier;
934
+ try {
935
+ tier = resolveTier(opts.tier);
936
+ } catch (err) {
937
+ printError(err instanceof Error ? err.message : String(err));
938
+ process.exitCode = 2;
939
+ return;
940
+ }
920
941
  const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
921
942
  const secret = generateHookSecret();
922
943
  saveHookSecret(configDir, agentId, opts.name, secret);
923
944
  let created;
924
945
  try {
925
- created = await client.post(`/agents/${agentId}/funnel/hooks`, { hook_name: opts.name });
946
+ created = await client.post(`/agents/${agentId}/funnel/hooks`, {
947
+ hook_name: opts.name,
948
+ tier: tier ?? null
949
+ });
926
950
  } catch (err) {
927
951
  deleteHookSecret(configDir, agentId, opts.name);
928
952
  throw err;
929
953
  }
930
- printCreated(created, opts.name, secret, gOpts.json);
954
+ printCreated(created, secret, gOpts.json);
931
955
  }));
932
956
  hook.command("list").description("List your agent's funnel hooks").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl }, opts) => {
933
957
  const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
@@ -936,6 +960,7 @@ function registerHook(program) {
936
960
  else printTable(data.items.map((h) => ({
937
961
  Name: h.hook_name,
938
962
  Hostname: h.hostname,
963
+ Tier: h.termination,
939
964
  Active: h.active,
940
965
  Created: h.created_at
941
966
  })));
@@ -960,14 +985,15 @@ function registerHook(program) {
960
985
  }));
961
986
  }
962
987
  /** Print the print-once GitHub setup block (the secret is shown exactly once). */
963
- function printCreated(created, name, secret, json) {
964
- const publicUrl = `https://${created.hostname}/${name}`;
988
+ function printCreated(created, secret, json) {
989
+ const publicUrl = `https://${created.hostname}/`;
965
990
  if (json) {
966
991
  printJson({
967
992
  hook: {
968
993
  name: created.hook_name,
969
994
  hostname: created.hostname,
970
- agent_id: created.agent_id
995
+ agent_id: created.agent_id,
996
+ termination: created.termination
971
997
  },
972
998
  public_url: publicUrl,
973
999
  secret,
@@ -985,6 +1011,10 @@ function printCreated(created, name, secret, json) {
985
1011
  Field: "Hostname",
986
1012
  Value: created.hostname
987
1013
  },
1014
+ {
1015
+ Field: "Tier",
1016
+ Value: created.termination
1017
+ },
988
1018
  {
989
1019
  Field: "Payload URL",
990
1020
  Value: publicUrl
@@ -1615,6 +1645,7 @@ function emitLifecycle$1(json, data) {
1615
1645
  function jitteredDelayMs$1(backoffSeconds) {
1616
1646
  return Math.round(backoffSeconds * (.5 + Math.random()) * 1e3);
1617
1647
  }
1648
+ const RENEWAL_CHECK_INTERVAL_MS = 720 * 60 * 1e3;
1618
1649
  function sleep(ms) {
1619
1650
  return new Promise((r) => setTimeout(r, ms));
1620
1651
  }
@@ -1696,31 +1727,77 @@ async function runRelayLoop(ctx) {
1696
1727
  let stopped = false;
1697
1728
  let lastDeps;
1698
1729
  let certHandle;
1730
+ let certBusy = false;
1731
+ let renewalTimer;
1699
1732
  const idempotency = new IdempotencyStore();
1700
1733
  process.on("SIGINT", () => {
1701
1734
  stopped = true;
1702
1735
  process.exitCode = 0;
1736
+ if (renewalTimer) clearInterval(renewalTimer);
1703
1737
  });
1738
+ const startRenewalTimer = () => {
1739
+ if (renewalTimer) return;
1740
+ renewalTimer = setInterval(() => {
1741
+ maybeRenewCert();
1742
+ }, RENEWAL_CHECK_INTERVAL_MS);
1743
+ renewalTimer.unref?.();
1744
+ };
1745
+ const maybeRenewCert = async () => {
1746
+ if (stopped || certBusy || !certHandle || !lastDeps) return;
1747
+ const meta = loadMeta(configDir, certHandle, options);
1748
+ if (!meta || !renewalDueWithJitter(meta, certHandle, Date.now())) return;
1749
+ certBusy = true;
1750
+ try {
1751
+ await ensureCert({
1752
+ handle: certHandle,
1753
+ agentId,
1754
+ delegationId: certHandle,
1755
+ configDir,
1756
+ options,
1757
+ deps: lastDeps
1758
+ });
1759
+ emitLifecycle$1(json, {
1760
+ state: "cert_renewed",
1761
+ handle: certHandle
1762
+ });
1763
+ } catch (err) {
1764
+ emitLifecycle$1(json, {
1765
+ state: "cert_renew_error",
1766
+ handle: certHandle,
1767
+ reason: err instanceof Error ? err.message : String(err)
1768
+ });
1769
+ } finally {
1770
+ certBusy = false;
1771
+ }
1772
+ };
1704
1773
  while (!stopped) {
1705
1774
  attempt++;
1706
1775
  let listener;
1707
1776
  try {
1708
- const { hostname, control_ws_url: controlWsUrl } = await resolveHook(client, agentId, opts.hook);
1709
- certHandle = hookLabel(hostname);
1777
+ const hook = await resolveHook(client, agentId, opts.hook);
1778
+ const { hostname, control_ws_url: controlWsUrl } = hook;
1779
+ assertZeroTrustTier(hook);
1780
+ certHandle = agentLabel(hostname);
1710
1781
  lastDeps = await buildIssueCertDeps({
1711
1782
  configDir,
1712
1783
  options,
1713
1784
  http: client,
1714
1785
  agentId
1715
1786
  });
1716
- const cert = await ensureCert({
1717
- handle: certHandle,
1718
- agentId,
1719
- delegationId: certHandle,
1720
- configDir,
1721
- options,
1722
- deps: lastDeps
1723
- });
1787
+ certBusy = true;
1788
+ let cert;
1789
+ try {
1790
+ cert = await ensureCert({
1791
+ handle: certHandle,
1792
+ agentId,
1793
+ delegationId: certHandle,
1794
+ configDir,
1795
+ options,
1796
+ deps: lastDeps
1797
+ });
1798
+ } finally {
1799
+ certBusy = false;
1800
+ }
1724
1801
  emitLifecycle$1(json, {
1725
1802
  state: "cert_ready",
1726
1803
  hostname
@@ -1756,10 +1833,12 @@ async function runRelayLoop(ctx) {
1756
1833
  });
1757
1834
  listener = live;
1758
1835
  ref.live = live;
1836
+ await assertAgentARecord(hostname, json);
1759
1837
  emitLifecycle$1(json, {
1760
1838
  state: "listener_ready",
1761
1839
  port: live.port
1762
1840
  });
1841
+ startRenewalTimer();
1763
1842
  backoff = 1;
1764
1843
  const close = await waitForClose(tunnel, () => stopped);
1765
1844
  tunnel.close();
@@ -1787,14 +1866,15 @@ async function runRelayLoop(ctx) {
1787
1866
  } catch (err) {
1788
1867
  listener?.close();
1789
1868
  if (stopped) break;
1869
+ if (err instanceof SharedEdgeNotSupportedError) {
1870
+ if (renewalTimer) clearInterval(renewalTimer);
1871
+ printError(err.message);
1872
+ process.exitCode = 2;
1873
+ return;
1874
+ }
1790
1875
  if (isRevoked(err)) {
1876
+ if (renewalTimer) clearInterval(renewalTimer);
1791
1877
  emitLifecycle$1(json, { state: "tunnel_revoked" });
1792
- if (lastDeps && certHandle) await revokeAndWipeCache({
1793
- handle: certHandle,
1794
- configDir,
1795
- options,
1796
- deps: lastDeps
1797
- }).catch(() => {});
1798
1878
  process.exitCode = 1;
1799
1879
  return;
1800
1880
  }
@@ -1810,6 +1890,7 @@ async function runRelayLoop(ctx) {
1810
1890
  backoff = Math.min(backoff * 2, 30);
1811
1891
  }
1812
1892
  }
1893
+ if (renewalTimer) clearInterval(renewalTimer);
1813
1894
  emitLifecycle$1(json, {
1814
1895
  state: "stopped",
1815
1896
  reason: "signal"
@@ -1832,13 +1913,14 @@ function waitForClose(tunnel, isStopped) {
1832
1913
  }
1833
1914
  /**
1834
1915
  * The server hook row — the SINGLE source of truth, used VERBATIM. Its
1835
- * `hostname` (the `{hook}--{slug}.hook.rine.network` form) goes into the BIND and
1836
- * (via its label) the cert CN/SAN; its `control_ws_url` is the broker control-WS
1837
- * endpoint the relay dials. NEITHER is reconstructed client-side: a fabricated
1838
- * `<uuid>.hook.rine.network` matches no funnel_hook row (BIND would NAK, the cert
1839
- * would never match GitHub's TLS), and the API base resolves to the primary IP /
1840
- * Caddy, which has no funnel route. On a missing row or a transient lookup
1841
- * failure we THROW so the loop backs off and retries.
1916
+ * `hostname` (the zero-trust `{hook}.{agentLabel}.hook.rine.network` form) goes
1917
+ * into the BIND and (via its agent label) the cert CN/SAN; its `control_ws_url`
1918
+ * is the broker control-WS endpoint the relay dials; its `termination` is the
1919
+ * tier. NEITHER is reconstructed client-side: a fabricated name matches no
1920
+ * funnel_hook row (BIND would NAK, the cert would never match GitHub's TLS), and
1921
+ * the API base resolves to the primary IP / Caddy, which has no funnel route. On
1922
+ * a missing row or a transient lookup failure we THROW so the loop backs off and
1923
+ * retries.
1842
1924
  */
1843
1925
  async function resolveHook(client, agentId, hookName) {
1844
1926
  const hook = (await client.get(`/agents/${agentId}/funnel/hooks`, {}))?.items?.find((h) => h.hook_name === hookName);
@@ -1846,12 +1928,46 @@ async function resolveHook(client, agentId, hookName) {
1846
1928
  return hook;
1847
1929
  }
1848
1930
  /**
1849
- * The DNS LABEL of a hook hostname — everything before `.hook.rine.network`. The
1850
- * cert is issued for this label via hookFqdn(label), so the leaf's CN/SAN equals
1851
- * the public hostname GitHub connects to (no name mismatch on the TLS handshake).
1931
+ * Fatal — this build serves only the zero-trust tier. Thrown (not retried) for a
1932
+ * shared-edge hook so the relay never enters a backoff loop it cannot escape.
1852
1933
  */
1853
- function hookLabel(hostname) {
1854
- return hostname.endsWith(".hook.rine.network") ? hostname.slice(0, -18) : hostname;
1934
+ var SharedEdgeNotSupportedError = class extends Error {
1935
+ constructor() {
1936
+ super("This hook uses the shared-edge tier, which requires the Phase B broker and is not available in this build. Recreate the hook with `--tier zero-trust`, or upgrade to a build with shared-edge support.");
1937
+ this.name = "SharedEdgeNotSupportedError";
1938
+ }
1939
+ };
1940
+ /**
1941
+ * Gate the relay to the zero-trust tier (REQ-TIER-03). The relay branches ONCE on
1942
+ * `hook.termination` and this build implements only zero-trust — the relay
1943
+ * terminates TLS with a per-agent wildcard cert. Shared-edge is broker-terminated
1944
+ * (Phase B); fail LOUD here, BEFORE any `.hook` label/FQDN derivation, so a
1945
+ * `.edge` host is never fed to the zero-trust agentLabel deriver (relay F-4).
1946
+ */
1947
+ function assertZeroTrustTier(hook) {
1948
+ if (hook.termination !== "zero_trust") throw new SharedEdgeNotSupportedError();
1949
+ }
1950
+ /**
1951
+ * (AUD-A1) Assert the zero-trust hostname resolves to an A record before
1952
+ * declaring the listener ready. The per-agent `*.{agentLabel}.hook` A is a
1953
+ * DELIVERY prerequisite written best-effort by the backend (REQ-OPS-04); a
1954
+ * healthy cert does NOT imply a routable name (DNS-01 validates the independent
1955
+ * challenge TXT). Non-fatal — emit a loud `dns_a_missing` event and continue (the
1956
+ * cert is valid and the backend self-heals the A on the next ZT-hook create), so
1957
+ * a missing A is surfaced rather than a silent black hole.
1958
+ */
1959
+ async function assertAgentARecord(hostname, json) {
1960
+ try {
1961
+ if ((await resolve4(hostname)).length === 0) emitLifecycle$1(json, {
1962
+ state: "dns_a_missing",
1963
+ hostname
1964
+ });
1965
+ } catch {
1966
+ emitLifecycle$1(json, {
1967
+ state: "dns_a_missing",
1968
+ hostname
1969
+ });
1970
+ }
1855
1971
  }
1856
1972
  //#endregion
1857
1973
  //#region src/commands/stream-cursor.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-network/cli",
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
4
4
  "description": "CLI client for rine.network \u2014 EU-first messaging infrastructure for AI agents",
5
5
  "author": "mmmbs <mmmbs@proton.me>",
6
6
  "license": "EUPL-1.2",
@@ -28,7 +28,7 @@
28
28
  "dev": "tsx src/main.ts"
29
29
  },
30
30
  "dependencies": {
31
- "@rine-network/core": "^0.6.3",
31
+ "@rine-network/core": "^0.6.4",
32
32
  "commander": "^12.0.0",
33
33
  "eventsource-client": "^1.1.0"
34
34
  },