@agimon-ai/po-remote 0.0.0-alpha.185 → 0.0.0-alpha.187

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.
package/README.md CHANGED
@@ -23,6 +23,10 @@ Each listener owns its pairing codes, sessions, channels, timers, and failures.
23
23
 
24
24
  `dualRemote.test.ts` exercises both connections with an isolated host and fake carriers. This does not demonstrate a live public tunnel, staging pairing, or physical-device acceptance. Private relay pairing in the host dialog uses the Po app; Cloud browser bootstrap is a separate acceptance requirement.
25
25
 
26
+ ## Tailscale Serve
27
+
28
+ Set `PO_TAILSCALE_SERVE_HOSTNAME` to the exact `device.tailnet.ts.net` name in the host service environment. When the operator turns on the tunnel connection, Po uses the existing origin-pinned paired gateway on `127.0.0.1:7543` instead of starting a Cloudflare connector. It does not auto-restore named Cloudflare intent in this mode. The normal loopback presentation and headless listeners are unchanged. The operator manages the Serve proxy, certificates and tailnet grants separately; Po does not enable Funnel or treat forwarded identity headers as device authorization. See the [VPS setup guide](../../../templates/po-selfhost-vps/README.md#optional-private-https-with-tailscale-serve).
29
+
26
30
  ## Help and authoring
27
31
 
28
32
  The package publishes `src/prompts/help-how-to-remote/SKILL.md` through a named resource route and `llms.txt`. Keep additional guides package-owned and in the publish allowlist; do not export Markdown or copy it into `dist`.
package/dist/index.cjs CHANGED
@@ -1485,6 +1485,20 @@ const pairOperation = (name) => `calendar.host-pair.${name}`;
1485
1485
  const pairWorkId = (targetHostId) => `host-pair/${targetHostId}`;
1486
1486
  /** Exact shape only: both constraints, only pair operations, never a workspace or a re-delegation. */
1487
1487
  const exactPairGrant = (grant) => grant.workspaceId === "" && grant.redelegable === false && Object.keys(grant.constraints).length === 2 && grant.constraints.package === PAIR_PACKAGE && grant.constraints.scope === "host-pair" && Array.isArray(grant.operations) && grant.operations.length > 0 && grant.operations.every((name) => PAIR_OPERATIONS.some((op) => name === pairOperation(op)));
1488
+ /**
1489
+ * Host-scoped operations the owner may call directly, traced from every route that reaches `authorize` with an
1490
+ * empty workspace: the network router's user-proof operations and the settings consent route. Anything else is denied.
1491
+ */
1492
+ const OWNER_HOST_OPERATIONS = /* @__PURE__ */ new Set([
1493
+ "voters",
1494
+ "roster.read",
1495
+ "roster.apply",
1496
+ "coordinator.vote",
1497
+ "coordinator.lease",
1498
+ "coordinator.mutate",
1499
+ "settings-consent",
1500
+ "host-pair-consent"
1501
+ ]);
1488
1502
  /** Default own-hub boundary, enabled only by a durable claim and pinned issuer. */
1489
1503
  function createDefaultHubFederation(ports) {
1490
1504
  let opened;
@@ -1704,14 +1718,14 @@ function createDefaultHubFederation(ports) {
1704
1718
  } catch {
1705
1719
  return false;
1706
1720
  }
1707
- if (input.operation === "host-pair-consent") return !caller.via && !grant;
1708
1721
  if (input.operation.startsWith("calendar.host-pair.")) {
1709
1722
  if (!caller.via || !grant || !exactPairGrant(grant) || !grant.operations.includes(input.operation)) return false;
1710
1723
  const held = await pairGrant(caller.via.callingHostId, hostId);
1711
1724
  return held?.payload.grantId === grant.grantId && held.payload.callingHostId === grant.callingHostId && held.payload.targetHostId === grant.targetHostId;
1712
1725
  }
1713
1726
  if (caller.via && input.operation.startsWith("calendar.")) return !!grant && grant.constraints.package === "@agimon-ai/po-calendar" && Object.keys(grant.constraints).length === 1;
1714
- return true;
1727
+ if (caller.via || grant) return false;
1728
+ return input.workspaceId !== "" || OWNER_HOST_OPERATIONS.has(input.operation);
1715
1729
  }
1716
1730
  });
1717
1731
  network = await ports.network?.({
@@ -3192,8 +3206,8 @@ const TRUSTED_DEVICE_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android"]);
3192
3206
  const STORED_ID = /^[A-Za-z0-9_-]{1,64}$/u;
3193
3207
  const STORED_KEY = /^[A-Za-z0-9_-]{1,512}$/u;
3194
3208
  const MAX_STORED_LABEL = 200;
3195
- function defaultRemoteStateDir(homeDir = _agimon_ai_po_core_platform.nodeHost.homeDirectory()) {
3196
- return node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDir), "web");
3209
+ function defaultRemoteStateDir(homeDir = _agimon_ai_po_core_platform.nodeHost.homeDirectory(), environment = {}) {
3210
+ return node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDir, environment), "web");
3197
3211
  }
3198
3212
  /** Whether a file mode lets another account read the file. */
3199
3213
  function isLooseMode(mode) {
@@ -4599,7 +4613,7 @@ function readState(filePath, notice) {
4599
4613
  * @deprecated Node-only sync shim; use createRemoteAccessStoreAsync. Removed in M2.
4600
4614
  */
4601
4615
  function createRemoteAccessStore(options = {}) {
4602
- const directory = options.stateDir ?? defaultRemoteStateDir();
4616
+ const directory = options.stateDir ?? defaultRemoteStateDir(void 0, options.environment);
4603
4617
  const notice = options.onNotice ?? (() => {});
4604
4618
  const settingsPath = node_path.default.join(directory, SETTINGS_FILE);
4605
4619
  const credentialsPath = node_path.default.join(directory, CREDENTIALS_FILE);
@@ -5790,6 +5804,8 @@ const TUNNEL_REQUEST_TIMEOUT_MS = 1e4;
5790
5804
  const TUNNEL_CONNECTION_LIMIT = 64;
5791
5805
  const TUNNEL_REQUESTS_PER_SOCKET = 100;
5792
5806
  const SEALED_HTTP_VERSION = 1;
5807
+ const INTERNAL_ORIGIN = "http://po.local";
5808
+ const HTTP_ERROR_MIN = 400;
5793
5809
  /**
5794
5810
  * The relay carrier's streamed form of a sealed request. This header holds the sealed envelope `{v, n, c}` whose
5795
5811
  * plaintext is the inner request's JSON (v, method, target, headers, no body), sealed with the device's HTTP channel
@@ -5857,8 +5873,8 @@ function sealedRequest(value) {
5857
5873
  if (typeof value !== "object" || value === null) return void 0;
5858
5874
  const request = value;
5859
5875
  if (request.v !== SEALED_HTTP_VERSION || typeof request.method !== "string" || !SEALED_HTTP_METHODS.has(request.method) || typeof request.target !== "string" || !request.target.startsWith("/") || request.target.startsWith("//") || /[\\#\u0000-\u0020]/u.test(request.target) || !Array.isArray(request.headers) || !request.headers.every((header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === "string")) || request.body !== void 0 && typeof request.body !== "string") return void 0;
5860
- const parsed = new URL(request.target, "http://po.local");
5861
- if (parsed.origin !== "http://po.local" || parsed.pathname + parsed.search !== request.target || parsed.pathname === _agimon_ai_po_core_remoteContract.REMOTE_HTTP_ROUTE || parsed.pathname === _agimon_ai_po_core_remoteContract.REMOTE_CHANNEL_ROUTE) return void 0;
5876
+ const parsed = new URL(request.target, INTERNAL_ORIGIN);
5877
+ if (parsed.origin !== INTERNAL_ORIGIN || parsed.pathname + parsed.search !== request.target || parsed.pathname === _agimon_ai_po_core_remoteContract.REMOTE_HTTP_ROUTE || parsed.pathname === _agimon_ai_po_core_remoteContract.REMOTE_CHANNEL_ROUTE) return void 0;
5862
5878
  return request;
5863
5879
  }
5864
5880
  function decodedBody(value) {
@@ -5927,7 +5943,9 @@ function framedWire(input) {
5927
5943
  closed = true;
5928
5944
  try {
5929
5945
  controller.close();
5930
- } catch {}
5946
+ } catch {
5947
+ reason ??= "client closed";
5948
+ }
5931
5949
  reader.cancel().catch(() => void 0);
5932
5950
  if (reason !== void 0) endListener?.(reason);
5933
5951
  };
@@ -6065,15 +6083,24 @@ async function writeResponse(response, result) {
6065
6083
  }
6066
6084
  await (0, node_stream_promises.pipeline)(node_stream.Readable.fromWeb(result.body), response);
6067
6085
  }
6068
- /** One global control plane and a second socket dedicated to public tunnel traffic. */
6086
+ /** One local control plane and a second socket dedicated to remote traffic. */
6069
6087
  function createRemoteRuntime(options) {
6070
6088
  const lanTls = options.lanTls;
6071
6089
  const privateRelay = options.privateRelay === void 0 ? void 0 : validatePrivateRelay(options.privateRelay);
6072
6090
  const relaySetup = options.privateRelaySetup;
6073
6091
  let activeRelay;
6074
6092
  if (lanTls !== void 0 && (privateRelay !== void 0 || relaySetup !== void 0)) throw new Error("Private network and private relay exposure cannot both be on.");
6093
+ const serveHostname = options.environment?.PO_TAILSCALE_SERVE_HOSTNAME;
6094
+ const servePort = 7543;
6095
+ let serveOrigin;
6096
+ if (serveHostname !== void 0) {
6097
+ const label = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
6098
+ if (!new RegExp(`^${label}\\.${label}\\.ts\\.net$`, "u").test(serveHostname) || /\s/u.test(serveHostname)) throw new Error("PO_TAILSCALE_SERVE_HOSTNAME must be the exact device DNS name (device.tailnet.ts.net).");
6099
+ if (lanTls !== void 0 || privateRelay !== void 0) throw new Error("Tailscale Serve cannot be used with the private LAN or environment-configured relay.");
6100
+ serveOrigin = `https://${serveHostname}`;
6101
+ }
6075
6102
  const store = createRemoteAccessStore({
6076
- stateDir: defaultRemoteStateDir(options.homeDirectory),
6103
+ stateDir: defaultRemoteStateDir(options.homeDirectory, options.environment),
6077
6104
  onNotice: (message) => options.onNotice(message)
6078
6105
  });
6079
6106
  const defaultFederation = options.federationPlatform && store.hubTrust ? createDefaultHubFederation({
@@ -6117,6 +6144,7 @@ function createRemoteRuntime(options) {
6117
6144
  let lastIntent;
6118
6145
  let frontendOrigin;
6119
6146
  const tunnelIntent = () => {
6147
+ if (serveOrigin !== void 0) return void 0;
6120
6148
  const access = remote.instance("tunnel");
6121
6149
  const state = access.state();
6122
6150
  const tunnel = access.settings().tunnel;
@@ -6159,11 +6187,12 @@ function createRemoteRuntime(options) {
6159
6187
  const rawPath = context.env.incoming?.url?.split("?")[0];
6160
6188
  const publicGatewayPeer = context.env.listener === "tunnel" && context.req.header("x-po-host-proof") !== void 0 && (context.req.method === "GET" && rawPath === "/api/plugins/gateway/catalog" || context.req.method === "POST" && rawPath === "/api/plugins/gateway/calls");
6161
6189
  const computerNetwork = context.req.path.startsWith("/api/network/") || /^\/api\/networks\/[^/]+\/network\//u.test(context.req.path);
6162
- if (computerNetwork) {
6190
+ const allowRawFederation = serveOrigin === void 0 || context.env.incoming === void 0;
6191
+ if (allowRawFederation && computerNetwork) {
6163
6192
  const result = await defaultFederation?.requestNetwork(context.req.raw);
6164
6193
  if (result) return result;
6165
6194
  }
6166
- if (!publicGatewayPeer && context.req.header("x-po-federation-envelope") && context.req.path.includes("/plugins/")) {
6195
+ if (allowRawFederation && !publicGatewayPeer && context.req.header("x-po-federation-envelope") && context.req.path.includes("/plugins/")) {
6167
6196
  const request = context.req.raw;
6168
6197
  if (!await options.federationPlatform?.resolve(request.clone())) return context.json({
6169
6198
  status: "unavailable",
@@ -6346,7 +6375,11 @@ function createRemoteRuntime(options) {
6346
6375
  publishIntent();
6347
6376
  },
6348
6377
  onDeviceDropped: options.onDeviceDropped,
6349
- launchTunnel: transport === "tunnel" && lanTls === void 0 && privateRelay === void 0 ? options.launchTunnel ?? createTunnelLauncher({
6378
+ launchTunnel: transport === "tunnel" && lanTls === void 0 && privateRelay === void 0 ? serveOrigin !== void 0 ? async () => ({
6379
+ ok: true,
6380
+ publicOrigin: serveOrigin,
6381
+ stop: async () => void 0
6382
+ }) : options.launchTunnel ?? createTunnelLauncher({
6350
6383
  stateDir: store.directory,
6351
6384
  onNotice: (message) => options.onNotice(message),
6352
6385
  onExit: (message) => {
@@ -6393,6 +6426,7 @@ function createRemoteRuntime(options) {
6393
6426
  const url = new URL(incoming.url ?? "/", `http://${incoming.headers.host ?? "localhost"}`);
6394
6427
  const headers = new Headers();
6395
6428
  for (const [name, value] of Object.entries(incoming.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
6429
+ if (serveOrigin !== void 0) headers.delete("cf-connecting-ip");
6396
6430
  const body = incoming.method === "GET" || incoming.method === "HEAD" ? void 0 : await readBody(incoming);
6397
6431
  const request = new Request(url, {
6398
6432
  method: incoming.method,
@@ -6424,7 +6458,7 @@ function createRemoteRuntime(options) {
6424
6458
  return;
6425
6459
  }
6426
6460
  const url = new URL(incoming.url ?? "/", `http://${incoming.headers.host ?? "localhost"}`);
6427
- if (/^\/api\/networks\/[^/]+\/relay$/.test(url.pathname)) {
6461
+ if (serveOrigin === void 0 && /^\/api\/networks\/[^/]+\/relay$/.test(url.pathname)) {
6428
6462
  webSockets.handleUpgrade(incoming, socket, head, (client) => {
6429
6463
  const peer = {
6430
6464
  get isOpen() {
@@ -6522,7 +6556,7 @@ function createRemoteRuntime(options) {
6522
6556
  server.maxRequestsPerSocket = TUNNEL_REQUESTS_PER_SOCKET;
6523
6557
  await new Promise((resolve, reject) => {
6524
6558
  server.once("error", reject);
6525
- server.listen(lan?.port ?? 0, lan?.address ?? "127.0.0.1", resolve);
6559
+ server.listen(lan?.port ?? (serveOrigin === void 0 ? 0 : servePort), lan?.address ?? "127.0.0.1", resolve);
6526
6560
  });
6527
6561
  const address = server.address();
6528
6562
  if (!address || typeof address === "string") throw new Error("The tunnel listener has no TCP address.");
@@ -6645,6 +6679,7 @@ function createRemoteRuntime(options) {
6645
6679
  listenerOf: (context) => context.env.listener,
6646
6680
  reservedPorts: () => [
6647
6681
  remote.tunnelPort(),
6682
+ serveOrigin === void 0 ? void 0 : servePort,
6648
6683
  frontendOrigin === void 0 ? void 0 : Number(new URL(frontendOrigin).port),
6649
6684
  ...options.reservedPorts?.() ?? []
6650
6685
  ],
@@ -6682,7 +6717,7 @@ function createRemoteRuntime(options) {
6682
6717
  */
6683
6718
  const dispatchSealed = async (input) => {
6684
6719
  const { context, device, inner, body, stream, relay } = input;
6685
- const target = new URL(inner.target, "http://po.local");
6720
+ const target = new URL(inner.target, INTERNAL_ORIGIN);
6686
6721
  const headers = new Headers();
6687
6722
  for (const [name, value] of inner.headers) {
6688
6723
  const normalized = name.toLowerCase();
@@ -6909,7 +6944,7 @@ function createRemoteRuntime(options) {
6909
6944
  const sealed = channel.seal(plaintext);
6910
6945
  const sealMs = performance.now() - sealStartedAt;
6911
6946
  const durationMs = performance.now() - startedAt;
6912
- if (options.telemetry && (response.status >= 400 || durationMs >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_DURATION_MS || responseBody.byteLength >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_BYTES || body.byteLength >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_BYTES)) {
6947
+ if (options.telemetry && (response.status >= HTTP_ERROR_MIN || durationMs >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_DURATION_MS || responseBody.byteLength >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_BYTES || body.byteLength >= _agimon_ai_po_core_packageApiServer.COMPLETION_SPAN_MIN_BYTES)) {
6913
6948
  const segments = target.pathname.split("/");
6914
6949
  (0, _agimon_ai_po_core_serverTelemetry.observe)(options.telemetry.recordEvent("po_server.sealed_http", {
6915
6950
  route_name: segments[2] === "plugins" ? `plugins.${segments[3] ?? ""}` : segments[2] ?? "",
@@ -6981,7 +7016,7 @@ function createRemoteRuntime(options) {
6981
7016
  if (context.req.path === "/" && remote.authorize((0, hono_cookie.getCookie)(context, _agimon_ai_po_core_remoteContract.DEVICE_COOKIE, "host")) === void 0) return context.redirect("/pair");
6982
7017
  if (context.req.path === "/bundle-manifest.json" || context.req.path.startsWith("/bundle-assets/")) {
6983
7018
  const from = new URL(context.req.url);
6984
- return await options.forward(new Request(new URL(`${from.pathname}${from.search}`, "http://po.local"), { method: context.req.method }));
7019
+ return await options.forward(new Request(new URL(`${from.pathname}${from.search}`, INTERNAL_ORIGIN), { method: context.req.method }));
6985
7020
  }
6986
7021
  if (!frontendOrigin) return context.json({ error: "The web presentation server is unavailable." }, 503);
6987
7022
  const from = new URL(context.req.url);
@@ -7151,7 +7186,7 @@ function createRemoteRuntime(options) {
7151
7186
  restoreTunnel: async (intent) => {
7152
7187
  const parsed = store.settingsForRestore();
7153
7188
  const tunnel = parsed?.settings.tunnel;
7154
- if (closing || lanTls !== void 0 || privateRelay !== void 0 || typeof intent?.hostname !== "string" || tunnel?.kind !== "named" || tunnel.hostname !== intent.hostname || parsed?.warnings.length !== 0 || remote.settings().tunnel.kind !== "named" || intent.closesAt !== void 0 && (!Number.isFinite(intent.closesAt) || intent.closesAt <= Date.now())) return {
7189
+ if (closing || serveOrigin !== void 0 || lanTls !== void 0 || privateRelay !== void 0 || typeof intent?.hostname !== "string" || tunnel?.kind !== "named" || tunnel.hostname !== intent.hostname || parsed?.warnings.length !== 0 || remote.settings().tunnel.kind !== "named" || intent.closesAt !== void 0 && (!Number.isFinite(intent.closesAt) || intent.closesAt <= Date.now())) return {
7155
7190
  ok: false,
7156
7191
  error: "The named tunnel intent is no longer valid for automatic restore."
7157
7192
  };