@rine-network/cli 0.11.3 → 0.11.5

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 +150 -32
  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, 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,20 +910,43 @@ 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;
@@ -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
  })));
@@ -967,7 +992,8 @@ function printCreated(created, name, secret, json) {
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,30 +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;
1732
+ const idempotency = new IdempotencyStore();
1699
1733
  process.on("SIGINT", () => {
1700
1734
  stopped = true;
1701
1735
  process.exitCode = 0;
1736
+ if (renewalTimer) clearInterval(renewalTimer);
1702
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
+ };
1703
1773
  while (!stopped) {
1704
1774
  attempt++;
1705
1775
  let listener;
1706
1776
  try {
1707
- const { hostname, control_ws_url: controlWsUrl } = await resolveHook(client, agentId, opts.hook);
1708
- 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);
1709
1781
  lastDeps = await buildIssueCertDeps({
1710
1782
  configDir,
1711
1783
  options,
1712
1784
  http: client,
1713
1785
  agentId
1714
1786
  });
1715
- const cert = await ensureCert({
1716
- handle: certHandle,
1717
- agentId,
1718
- delegationId: certHandle,
1719
- configDir,
1720
- options,
1721
- deps: lastDeps
1722
- });
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
+ }
1723
1801
  emitLifecycle$1(json, {
1724
1802
  state: "cert_ready",
1725
1803
  hostname
@@ -1749,15 +1827,18 @@ async function runRelayLoop(ctx) {
1749
1827
  hookName: opts.hook,
1750
1828
  secret,
1751
1829
  client,
1830
+ idempotency,
1752
1831
  emitLifecycle: (ev) => json && console.log(JSON.stringify(ev))
1753
1832
  }, req).then(() => void 0)
1754
1833
  });
1755
1834
  listener = live;
1756
1835
  ref.live = live;
1836
+ await assertAgentARecord(hostname, json);
1757
1837
  emitLifecycle$1(json, {
1758
1838
  state: "listener_ready",
1759
1839
  port: live.port
1760
1840
  });
1841
+ startRenewalTimer();
1761
1842
  backoff = 1;
1762
1843
  const close = await waitForClose(tunnel, () => stopped);
1763
1844
  tunnel.close();
@@ -1785,14 +1866,15 @@ async function runRelayLoop(ctx) {
1785
1866
  } catch (err) {
1786
1867
  listener?.close();
1787
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
+ }
1788
1875
  if (isRevoked(err)) {
1876
+ if (renewalTimer) clearInterval(renewalTimer);
1789
1877
  emitLifecycle$1(json, { state: "tunnel_revoked" });
1790
- if (lastDeps && certHandle) await revokeAndWipeCache({
1791
- handle: certHandle,
1792
- configDir,
1793
- options,
1794
- deps: lastDeps
1795
- }).catch(() => {});
1796
1878
  process.exitCode = 1;
1797
1879
  return;
1798
1880
  }
@@ -1808,6 +1890,7 @@ async function runRelayLoop(ctx) {
1808
1890
  backoff = Math.min(backoff * 2, 30);
1809
1891
  }
1810
1892
  }
1893
+ if (renewalTimer) clearInterval(renewalTimer);
1811
1894
  emitLifecycle$1(json, {
1812
1895
  state: "stopped",
1813
1896
  reason: "signal"
@@ -1830,13 +1913,14 @@ function waitForClose(tunnel, isStopped) {
1830
1913
  }
1831
1914
  /**
1832
1915
  * The server hook row — the SINGLE source of truth, used VERBATIM. Its
1833
- * `hostname` (the `{hook}--{slug}.hook.rine.network` form) goes into the BIND and
1834
- * (via its label) the cert CN/SAN; its `control_ws_url` is the broker control-WS
1835
- * endpoint the relay dials. NEITHER is reconstructed client-side: a fabricated
1836
- * `<uuid>.hook.rine.network` matches no funnel_hook row (BIND would NAK, the cert
1837
- * would never match GitHub's TLS), and the API base resolves to the primary IP /
1838
- * Caddy, which has no funnel route. On a missing row or a transient lookup
1839
- * 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.
1840
1924
  */
1841
1925
  async function resolveHook(client, agentId, hookName) {
1842
1926
  const hook = (await client.get(`/agents/${agentId}/funnel/hooks`, {}))?.items?.find((h) => h.hook_name === hookName);
@@ -1844,12 +1928,46 @@ async function resolveHook(client, agentId, hookName) {
1844
1928
  return hook;
1845
1929
  }
1846
1930
  /**
1847
- * The DNS LABEL of a hook hostname — everything before `.hook.rine.network`. The
1848
- * cert is issued for this label via hookFqdn(label), so the leaf's CN/SAN equals
1849
- * 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.
1850
1933
  */
1851
- function hookLabel(hostname) {
1852
- 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
+ }
1853
1971
  }
1854
1972
  //#endregion
1855
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.3",
3
+ "version": "0.11.5",
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.2",
31
+ "@rine-network/core": "^0.6.4",
32
32
  "commander": "^12.0.0",
33
33
  "eventsource-client": "^1.1.0"
34
34
  },