a2a-exposed 0.0.0-stage → 0.4.0

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,102 @@
1
+ // Run: npm test (node --test, Node >= 22.18 native TypeScript type stripping)
2
+ import { test } from "node:test";
3
+ import assert from "node:assert/strict";
4
+ import { createHash } from "node:crypto";
5
+ import { publicTask, normMessage, randomToken, sha256, fingerprint, taskFromAny, movedResponse, publicOrigin, isPrivateHost } from "../src/a2a.ts";
6
+
7
+ // Internal (0.3-shaped) task after a peer message and an owner reply, as stored in D1.
8
+ const reply = { kind: "message", role: "agent", messageId: "m2", contextId: "c1", taskId: "t1", parts: [{ kind: "text", text: "pong" }] };
9
+ const task = {
10
+ id: "t1", contextId: "c1",
11
+ status: { state: "completed", timestamp: "2026-01-01T00:00:00.000Z", message: reply },
12
+ artifacts: [{ artifactId: "a1", name: "response", parts: [{ kind: "text", text: "pong" }] }],
13
+ history: [normMessage({ role: "ROLE_USER", messageId: "m1", parts: [{ text: "ping" }] }), reply],
14
+ };
15
+
16
+ function roles(t: any): string[] {
17
+ return [t.status.message.role, ...t.history.map((m: any) => m.role)];
18
+ }
19
+
20
+ test("1.0 GetTask: status.message and history both use ROLE_* enums", () => {
21
+ const t = publicTask(task, "1.0");
22
+ assert.equal(t.status.state, "TASK_STATE_COMPLETED");
23
+ assert.deepEqual(roles(t), ["ROLE_AGENT", "ROLE_USER", "ROLE_AGENT"]);
24
+ for (const m of [t.status.message, ...t.history]) {
25
+ assert.ok(!("kind" in m), "1.0 messages carry no kind");
26
+ for (const p of m.parts) assert.ok(!("kind" in p), "1.0 parts carry no kind");
27
+ }
28
+ assert.deepEqual(t.artifacts[0].parts, [{ text: "pong" }]);
29
+ assert.ok(!("kind" in t));
30
+ });
31
+
32
+ test("0.3 tasks/get: status.message and history keep user/agent", () => {
33
+ const t = publicTask(task, "0.3");
34
+ assert.equal(t.status.state, "completed");
35
+ assert.equal(t.kind, "task");
36
+ assert.deepEqual(roles(t), ["agent", "user", "agent"]);
37
+ assert.equal(t.history[0].parts[0].kind, "text");
38
+ });
39
+
40
+ test("publicTask does not mutate the stored task", () => {
41
+ publicTask(task, "1.0");
42
+ assert.equal(task.status.message.role, "agent");
43
+ assert.equal(task.history[1].role, "agent");
44
+ });
45
+
46
+ test("historyLength trims history in both versions", () => {
47
+ assert.deepEqual(publicTask(task, "1.0", 1).history.map((m: any) => m.role), ["ROLE_AGENT"]);
48
+ assert.equal(publicTask(task, "0.3", 0).history, undefined);
49
+ });
50
+
51
+ test("inbound 1.0 roles normalise to the internal user/agent", () => {
52
+ assert.equal(normMessage({ role: "ROLE_AGENT", parts: [{ text: "x" }] }).role, "agent");
53
+ assert.equal(normMessage({ role: "ROLE_USER", parts: [{ text: "x" }] }).role, "user");
54
+ assert.equal(taskFromAny({ id: "x", status: { state: "TASK_STATE_INPUT_REQUIRED" } }).status.state, "input-required");
55
+ });
56
+
57
+ test("peer tokens use the a2aow_ prefix and match by sha256", async () => {
58
+ const t = randomToken();
59
+ assert.match(t, /^a2aow_[A-Za-z0-9_-]{43}$/);
60
+ assert.equal(await sha256(t), createHash("sha256").update(t).digest("hex"));
61
+ });
62
+
63
+ test("fingerprint is the first 12 hex chars of sha256, null when unset", async () => {
64
+ const v = "https://hooks.example.com/abc?x=1";
65
+ assert.equal(await fingerprint(v), createHash("sha256").update(v).digest("hex").slice(0, 12));
66
+ assert.equal(await fingerprint(undefined), null);
67
+ assert.equal(await fingerprint(""), null);
68
+ });
69
+
70
+ test("movedResponse: retired hostnames redirect the card (301) and answer 410; others are served", () => {
71
+ const pub = "https://my-agent.acme.workers.dev";
72
+ const card = movedResponse("https://old.example.com/.well-known/agent-card.json", pub, "old.example.com");
73
+ assert.equal(card!.status, 301);
74
+ assert.equal(card!.headers.location, "https://my-agent.acme.workers.dev/.well-known/agent-card.json");
75
+ const rpc = movedResponse("https://OLD.example.com/a2a/v1", pub, " other.example.com , old.example.com ");
76
+ assert.equal(rpc!.status, 410);
77
+ assert.equal(JSON.parse(rpc!.body).agentCard, "https://my-agent.acme.workers.dev/.well-known/agent-card.json");
78
+ assert.equal(movedResponse("https://my-agent.acme.workers.dev/a2a/v1", pub, "old.example.com"), null);
79
+ assert.equal(movedResponse("https://old.example.com/a2a/v1", pub, ""), null);
80
+ assert.equal(movedResponse("https://old.example.com/a2a/v1", "https://old.example.com", "old.example.com"), null, "never the live URL");
81
+ assert.equal(movedResponse("https://old.example.com/", "", "old.example.com")!.status, 410);
82
+ });
83
+
84
+
85
+ test("publicOrigin: the card advertises the deployment's public https URL, never a local or Tailnet one", () => {
86
+ const req = "https://agent-x.acme.workers.dev/.well-known/agent-card.json";
87
+ assert.equal(publicOrigin("https://agent.example.com", req), "https://agent.example.com");
88
+ assert.equal(publicOrigin("https://agent.example.com/", req), "https://agent.example.com");
89
+ assert.equal(publicOrigin("", req), "https://agent-x.acme.workers.dev", "unknown yet: the request origin");
90
+ assert.equal(publicOrigin(undefined, req), "https://agent-x.acme.workers.dev");
91
+ for (const local of ["http://agent.example.com", "https://hermes.tail1234.ts.net", "http://100.101.102.103:8644", "https://100.64.0.1",
92
+ "https://localhost:8644", "https://hermes", "https://192.168.1.10", "https://10.0.0.5", "https://box.local", "https://[::1]:8644", "not a url"])
93
+ assert.equal(publicOrigin(local, req), "https://agent-x.acme.workers.dev", local);
94
+ });
95
+
96
+ test("isPrivateHost", () => {
97
+ for (const h of ["localhost", "hermes", "hermes.tail1234.ts.net", "100.127.255.1", "172.16.0.1", "169.254.1.1", "127.0.0.1", "nas.home.arpa", "fd00::1",
98
+ "::1", "[::1]", "::", "fe80::1", "febf::1", "::ffff:127.0.0.1", "::ffff:7f00:1", "[::ffff:c0a8:101]", "64:ff9b::a00:1", "::a00:1"])
99
+ assert.equal(isPrivateHost(h), true, h);
100
+ for (const h of ["agent.example.com", "agent-x.acme.workers.dev", "100.128.0.1", "172.32.0.1", "8.8.8.8", "2606:4700::1", "::ffff:808:808", "64:ff9b::808:808", "2001:db8::1"])
101
+ assert.equal(isPrivateHost(h), false, h);
102
+ });
@@ -0,0 +1,38 @@
1
+ // Minimal D1 stand-in over node:sqlite (in-memory), with the repo's migrations applied: lets tests drive the real
2
+ // Worker fetch handler. Covers what the Worker uses: prepare().bind().first()/all()/run(), RETURNING, and batch().
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import fs from "node:fs";
5
+
6
+ export function d1(migrationsDir: URL) {
7
+ const db = new DatabaseSync(":memory:");
8
+ for (const f of fs.readdirSync(migrationsDir).filter((n) => n.endsWith(".sql")).sort())
9
+ db.exec(fs.readFileSync(new URL(f, migrationsDir), "utf8"));
10
+ return d1On(db);
11
+ }
12
+
13
+ /** The same D1 stand-in over an existing node:sqlite database (e.g. one whose schema a test built step by step). */
14
+ export function d1On(db: DatabaseSync) {
15
+ const stmt = (sql: string, args: unknown[] = []): any => ({
16
+ bind: (...a: unknown[]) => stmt(sql, a),
17
+ first: async (col?: string) => {
18
+ const r: any = db.prepare(sql).get(...(args as any[]));
19
+ return r ? (col ? r[col] : { ...r }) : null;
20
+ },
21
+ all: async () => ({ results: db.prepare(sql).all(...(args as any[])).map((r: any) => ({ ...r })), meta: {} }),
22
+ run: async () => {
23
+ const s = db.prepare(sql);
24
+ if (/\breturning\b/i.test(sql)) { const rows = s.all(...(args as any[])); return { results: rows, meta: { changes: rows.length } }; }
25
+ const r = s.run(...(args as any[]));
26
+ return { results: [], meta: { changes: Number(r.changes) } };
27
+ },
28
+ });
29
+ return {
30
+ db,
31
+ prepare: (sql: string) => stmt(sql),
32
+ batch: async (stmts: any[]) => {
33
+ db.exec("BEGIN");
34
+ try { const out = []; for (const s of stmts) out.push(await s.run()); db.exec("COMMIT"); return out; }
35
+ catch (e) { db.exec("ROLLBACK"); throw e; }
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,421 @@
1
+ // Public façade for a private A2A agent: agent card rewriting (pure helpers and the served cards) and proxy mode
2
+ // end to end against the real Worker fetch handler, with D1 on node:sqlite and the upstream stubbed. Run: npm test
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import worker from "../src/index.ts";
6
+ import * as F from "../src/facade.ts";
7
+ import { d1 } from "./d1.ts";
8
+
9
+ const BASE = "https://agent.example.com";
10
+ const UPSTREAM = "https://agent-upstream.example.net/a2a";
11
+ const TAILNET = "https://jean.tail1234.ts.net:8443";
12
+
13
+ /** What an agent already running on a Tailnet typically serves: every URL is private. */
14
+ const tailnetCard = (over: any = {}) => ({
15
+ name: "Jean", description: `Jean's assistant. Docs at ${TAILNET}/docs, admin on http://localhost:8080/admin.`, version: "2.1.0",
16
+ supportedInterfaces: [
17
+ { url: `${TAILNET}/a2a`, protocolBinding: "JSONRPC", protocolVersion: "1.0" },
18
+ { url: `${TAILNET}/grpc`, protocolBinding: "GRPC", protocolVersion: "1.0" },
19
+ ],
20
+ securitySchemes: { upstreamKey: { apiKeySecurityScheme: { location: "header", name: "x-api-key" } } },
21
+ securityRequirements: [{ schemes: { upstreamKey: { list: [] } } }],
22
+ capabilities: { streaming: true, pushNotifications: true, extendedAgentCard: true, extensions: [{ uri: "https://a2a.example.org/ext/v1", description: "see http://100.101.102.103/ext", params: { [`${TAILNET}/admin`]: { scope: "all" } } }] },
23
+ defaultInputModes: ["text/plain", "http://10.0.0.9/mode"], defaultOutputModes: ["text/plain", "application/json; charset=utf-8"],
24
+ skills: [{ id: "chat", name: "Chat", description: "Talks. Runs on jean.tail1234.ts.net", tags: ["chat"], examples: [`Open ${TAILNET}/a2a please`] }],
25
+ provider: { organization: "Jean Inc", url: "http://192.168.1.10/" },
26
+ documentationUrl: `${TAILNET}/docs`, iconUrl: "https://cdn.example.org/jean.png",
27
+ signatures: [{ protected: "x", signature: "y" }],
28
+ ...over,
29
+ });
30
+
31
+ test("scrubText: private and upstream URLs and Tailnet names are removed, public URLs kept", () => {
32
+ const o = { publicBase: BASE, upstreamOrigins: ["https://agent-upstream.example.net"] };
33
+ assert.equal(F.scrubText("see https://docs.example.org/x.", o), "see https://docs.example.org/x.");
34
+ assert.equal(F.scrubText("see http://localhost:3000/a, ok", o), `see ${F.REMOVED_URL}, ok`);
35
+ // bracketed IPv6 literals are part of the URL (loopback, ULA, link-local, IPv4-mapped private)
36
+ for (const u of ["http://[::1]:8080/internal", "https://[::1]/x", "https://[fd12:3456::7]:8443/a2a", "https://[fe80::1%25eth0]/", "https://[::ffff:192.168.1.10]/admin", "https://user@[2606:4700::1]/"])
37
+ assert.equal(F.scrubText(`at ${u} now`, o), `at ${F.REMOVED_URL} now`, u);
38
+ assert.equal(F.scrubText("see https://[2606:4700::1]:443/docs.", o), "see https://[2606:4700::1]:443/docs.", "public IPv6 kept");
39
+ assert.equal(F.scrubText("a list [https://docs.example.org/x] stays", o), "a list [https://docs.example.org/x] stays");
40
+ assert.deepEqual(F.cardLeaks({ description: "admin at http://[::1]:8080/internal" }, BASE, []), ["description: http://[::1]:8080/internal"]);
41
+ // property names are scrubbed too (extension params keyed by URL), and a __proto__ key stays a plain property
42
+ const keyed = JSON.parse(`{"params":{"https://jean.tail1234.ts.net/admin":{"see":"http://10.0.0.5/x"},"https://docs.example.org/k":1,"__proto__":{"polluted":true}}}`);
43
+ assert.ok(F.cardLeaks(keyed, BASE, []).some((l) => l.includes("jean.tail1234.ts.net/admin")), "cardLeaks sees keys");
44
+ const clean = F.scrubDeep(keyed, o);
45
+ assert.deepEqual(Object.keys(clean.params), [F.REMOVED_URL, "https://docs.example.org/k", "__proto__"]);
46
+ assert.deepEqual(clean.params[F.REMOVED_URL], { see: F.REMOVED_URL });
47
+ assert.equal(({} as any).polluted, undefined);
48
+ assert.equal(Object.getPrototypeOf(clean.params), Object.prototype);
49
+ assert.deepEqual(F.cardLeaks(clean, BASE, []), []);
50
+ assert.equal(F.scrubText("on https://agent-upstream.example.net/a2a now", o), `on ${F.REMOVED_URL} now`);
51
+ assert.equal(F.scrubText("host agent-upstream.example.net:443 here", o), `host ${F.REMOVED_HOST} here`);
52
+ assert.equal(F.scrubText("on jean.tail1234.ts.net.", o), `on ${F.REMOVED_HOST}.`);
53
+ assert.equal(F.scrubText("lan http://10.0.0.5/x and https://192.168.0.2", o), `lan ${F.REMOVED_URL} and ${F.REMOVED_URL}`);
54
+ assert.equal(F.scrubText("urn:example:x mailto:a@example.com", o), "urn:example:x mailto:a@example.com");
55
+ assert.equal(F.publicUrlOrNothing(`${TAILNET}/docs`, o), undefined);
56
+ assert.equal(F.publicUrlOrNothing("https://docs.example.org/", o), "https://docs.example.org/");
57
+ });
58
+
59
+ test("upstream card parsing: interface origins and the JSON-RPC versions we can proxy", () => {
60
+ assert.deepEqual(F.upstreamCardOrigins(tailnetCard()), [TAILNET]);
61
+ assert.deepEqual(F.upstreamJsonRpcVersions(tailnetCard()), ["1.0"]);
62
+ const c03 = { protocolVersion: "0.3.0", url: "http://100.70.0.1:9999/", preferredTransport: "JSONRPC", additionalInterfaces: [{ url: "http://100.70.0.1:9999/rest", transport: "HTTP+JSON" }] };
63
+ assert.deepEqual(F.upstreamJsonRpcVersions(c03), ["0.3"]);
64
+ assert.deepEqual(F.upstreamCardOrigins(c03), ["http://100.70.0.1:9999"]);
65
+ assert.deepEqual(F.upstreamJsonRpcVersions({ protocolVersion: "0.3.0", preferredTransport: "GRPC" }), []);
66
+ assert.deepEqual(F.upstreamEndpoint("http://agent.example.net/"), ["", "UPSTREAM_URL must be https"]);
67
+ assert.match(F.upstreamEndpoint("https://jean.tail1234.ts.net/a2a")[1], /private-network/);
68
+ assert.match(F.upstreamEndpoint("https://localhost/a2a")[1], /private-network/);
69
+ assert.equal(F.upstreamEndpoint(UPSTREAM)[0], UPSTREAM);
70
+ assert.deepEqual(F.upstreamCardUrl(UPSTREAM, ""), ["https://agent-upstream.example.net/.well-known/agent-card.json", ""]);
71
+ assert.deepEqual(F.upstreamCardUrl(UPSTREAM, "https://agent-upstream.example.net/card.json"), ["https://agent-upstream.example.net/card.json", ""]);
72
+ assert.equal(F.sameOrigin(UPSTREAM, "https://agent-upstream.example.net/other"), true);
73
+ assert.equal(F.sameOrigin(UPSTREAM, "https://evil.example.com/card"), false);
74
+ assert.match(F.upstreamCardUrl(UPSTREAM, "https://evil.example.com/card")[1], /must be on the UPSTREAM_URL origin/);
75
+ assert.match(F.upstreamCardUrl(UPSTREAM, "http://insecure.example.net/card")[1], /must be https/);
76
+ assert.match(F.upstreamCardUrl(UPSTREAM, "https://jean.tail1234.ts.net/card")[1], /private-network/);
77
+ assert.deepEqual(F.idsFromResult({ task: { id: "t1", contextId: "c1" } }), { taskId: "t1", contextId: "c1" });
78
+ assert.deepEqual(F.idsFromResult({ kind: "task", id: "t2", contextId: "c2" }), { taskId: "t2", contextId: "c2" });
79
+ assert.deepEqual(F.idsFromResult({ message: { messageId: "m", contextId: "c3" } }), { taskId: undefined, contextId: "c3" });
80
+ assert.equal(F.taskIdOf("get", { name: "tasks/t9" }), "t9");
81
+ assert.equal(F.taskIdOf("pushget", { id: "t8", pushNotificationConfigId: "p" }), "t8");
82
+ assert.equal(F.taskIdOf("pushset", { taskId: "t7", id: "cfg" }), "t7");
83
+ assert.equal(F.taskIdOf("pushset", { id: "cfg", url: "https://x.example" }), undefined);
84
+ });
85
+
86
+ test("facadeCard: public URLs only, façade security, upstream name/skills/capabilities preserved, config wins", () => {
87
+ const schemes = { bearer: { httpAuthSecurityScheme: { scheme: "Bearer" } } };
88
+ const card = F.facadeCard({ upstream: tailnetCard(), config: {}, publicBase: BASE, upstreamOrigins: [TAILNET, "https://agent-upstream.example.net"],
89
+ securitySchemes: schemes, securityRequirements: [{ schemes: { bearer: { list: [] } } }], defaults: { description: "d", skills: [] } });
90
+ assert.deepEqual(card.supportedInterfaces, [{ url: BASE + "/", protocolBinding: "JSONRPC", protocolVersion: "1.0" }]);
91
+ assert.deepEqual(card.securitySchemes, schemes);
92
+ assert.equal(card.name, "Jean");
93
+ assert.equal(card.version, "2.1.0");
94
+ assert.equal(card.skills[0].id, "chat");
95
+ assert.equal(card.skills[0].description, `Talks. Runs on ${F.REMOVED_HOST}`);
96
+ assert.equal(card.skills[0].examples[0], `Open ${F.REMOVED_URL} please`);
97
+ assert.deepEqual(card.capabilities, { streaming: false, pushNotifications: false, extendedAgentCard: false,
98
+ extensions: [{ uri: "https://a2a.example.org/ext/v1", description: `see ${F.REMOVED_URL}`, params: { [F.REMOVED_URL]: { scope: "all" } } }] });
99
+ assert.equal(card.documentationUrl, undefined);
100
+ assert.equal(card.provider, undefined);
101
+ assert.equal(card.iconUrl, "https://cdn.example.org/jean.png");
102
+ assert.deepEqual(card.defaultInputModes, ["text/plain"], "non-media-type modes dropped");
103
+ assert.deepEqual(card.defaultOutputModes, ["text/plain", "application/json; charset=utf-8"]);
104
+ for (const k of ["url", "signatures", "additionalInterfaces", "security", "preferredTransport"]) assert.ok(!(k in card), k);
105
+ assert.deepEqual(F.cardLeaks(card, BASE, [TAILNET]), []);
106
+ assert.ok(F.cardLeaks(tailnetCard(), BASE, [TAILNET]).length > 3, "the raw upstream card does leak");
107
+
108
+ const over = F.facadeCard({ upstream: tailnetCard(), config: { name: "Jean (public)", documentationUrl: "https://docs.example.org/jean", providerOrganization: "Acme", providerUrl: "https://acme.example" },
109
+ publicBase: BASE, upstreamOrigins: [TAILNET], securitySchemes: schemes, securityRequirements: [], defaults: { description: "d", skills: [] } });
110
+ assert.equal(over.name, "Jean (public)");
111
+ assert.equal(over.documentationUrl, "https://docs.example.org/jean");
112
+ assert.deepEqual(over.provider, { organization: "Acme", url: "https://acme.example" });
113
+
114
+ const none = F.facadeCard({ upstream: null, config: {}, publicBase: BASE, upstreamOrigins: [], securitySchemes: schemes, securityRequirements: [],
115
+ defaults: { description: "fallback", skills: [{ id: "general" }] } });
116
+ assert.deepEqual(none.supportedInterfaces.map((i: any) => i.protocolVersion), ["1.0", "0.3"]);
117
+ assert.equal(none.description, "fallback");
118
+ });
119
+
120
+ // ------------------------------------------------------------------ the Worker
121
+
122
+ function setup(over: Record<string, string> = {}, upstream: (url: string, init: any) => Response | Promise<Response> = defaultUpstream()) {
123
+ const DB = d1(new URL("../migrations/", import.meta.url));
124
+ const env: any = { DB, PUBLIC_URL: BASE, OWNER_TOKEN: "owner-secret", PAIRING_APPROVAL: "human", ...over };
125
+ const calls: any[] = [];
126
+ const origFetch = globalThis.fetch;
127
+ globalThis.fetch = (async (url: any, init: any = {}) => {
128
+ calls.push({ url: String(url), method: init.method || "GET", headers: { ...(init.headers || {}) }, body: init.body });
129
+ return upstream(String(url), init);
130
+ }) as any;
131
+ const call = async (method: string, path: string, o: { json?: any; token?: string; headers?: Record<string, string> } = {}) => {
132
+ const headers: Record<string, string> = { "cf-connecting-ip": "198.51.100.7", ...(o.headers || {}) };
133
+ if (o.token) headers.authorization = `Bearer ${o.token}`;
134
+ let body: string | undefined;
135
+ if (o.json !== undefined) { headers["content-type"] = "application/json"; body = JSON.stringify(o.json); }
136
+ const pending: Promise<unknown>[] = [];
137
+ const res = await worker.fetch(new Request(BASE + path, { method, headers, body }) as any, env, { waitUntil: (p: Promise<unknown>) => pending.push(p), passThroughOnException() {} } as any);
138
+ await Promise.allSettled(pending);
139
+ const text = await res.text();
140
+ let data: any = text;
141
+ try { data = JSON.parse(text); } catch { /* text */ }
142
+ return { status: res.status, data, text };
143
+ };
144
+ const issue = async (label: string) => (await call("POST", "/owner/peers", { json: { label }, token: "owner-secret" })).data.token as string;
145
+ const rpc = (token: string, method: string, params: any, id: any = 1) => call("POST", "/", { token, json: { jsonrpc: "2.0", id, method, params }, headers: { "a2a-version": "1.0" } });
146
+ return { env, DB, calls, call, issue, rpc, restore: () => { globalThis.fetch = origFetch; } };
147
+ }
148
+
149
+ let seq = 0;
150
+ /** A stub upstream: serves the Tailnet card, and answers SendMessage with a new task (GetTask echoes the id). */
151
+ function defaultUpstream(card: any = tailnetCard()) {
152
+ return async (url: string, init: any): Promise<Response> => {
153
+ if (url.endsWith(".json")) return Response.json(card);
154
+ if (url.startsWith("https://hook.example.net/")) return new Response("ok"); // wake webhook
155
+ const rq = JSON.parse(init.body);
156
+ if (rq.method === "SendMessage") {
157
+ const m = rq.params.message;
158
+ return Response.json({ jsonrpc: "2.0", id: rq.id, result: { task: { id: m.taskId || `up-task-${++seq}`, contextId: m.contextId || `up-ctx-${seq}`, status: { state: "TASK_STATE_SUBMITTED" } } } });
159
+ }
160
+ return Response.json({ jsonrpc: "2.0", id: rq.id, result: { id: rq.params.id || rq.params.taskId, status: { state: "TASK_STATE_WORKING" } } });
161
+ };
162
+ }
163
+
164
+ test("inbox mode: private URLs in AGENT_* settings never reach the card", async (t) => {
165
+ const s = setup({ DOCUMENTATION_URL: "https://jean.tail1234.ts.net/docs", PROVIDER_ORGANIZATION: "Acme", PROVIDER_URL: "http://192.168.1.2/",
166
+ AGENT_DESCRIPTION: "Ask me. Local UI: http://localhost:3000", AGENT_SKILLS: JSON.stringify([{ id: "x", name: "X", description: "via http://100.64.1.2/", tags: [] }]) });
167
+ t.after(s.restore);
168
+ for (const p of ["/.well-known/agent-card.json", "/.well-known/agent.json"]) {
169
+ const card = (await s.call("GET", p)).data;
170
+ assert.deepEqual(F.cardLeaks(card, BASE), [], p);
171
+ assert.equal(card.documentationUrl, undefined, p);
172
+ assert.equal(card.provider, undefined, p);
173
+ assert.equal(card.description, `Ask me. Local UI: ${F.REMOVED_URL}`, p);
174
+ }
175
+ const ok = setup({ DOCUMENTATION_URL: "https://docs.example.org/", PROVIDER_ORGANIZATION: "Acme", PROVIDER_URL: "https://acme.example/" });
176
+ t.after(ok.restore);
177
+ const card = (await ok.call("GET", "/.well-known/agent-card.json")).data;
178
+ assert.equal(card.documentationUrl, "https://docs.example.org/");
179
+ assert.deepEqual(card.provider, { organization: "Acme", url: "https://acme.example/" });
180
+ assert.equal((await ok.call("GET", "/health")).data.mode, "inbox");
181
+ });
182
+
183
+ test("proxy mode: the served cards are the upstream's, rewritten to the public URL (1.0 and 0.3)", async (t) => {
184
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-a.json", UPSTREAM_TOKEN: "up-secret",
185
+ UPSTREAM_ACCESS_CLIENT_ID: "cid.access", UPSTREAM_ACCESS_CLIENT_SECRET: "csecret" });
186
+ t.after(s.restore);
187
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
188
+ assert.equal(card.name, "Jean");
189
+ assert.deepEqual(card.supportedInterfaces, [{ url: BASE + "/", protocolBinding: "JSONRPC", protocolVersion: "1.0" }]);
190
+ assert.ok(card.securitySchemes.bearer && card.securitySchemes.pairing, "façade bearer + device-flow pairing");
191
+ assert.ok(!card.securitySchemes.upstreamKey, "never the upstream's scheme");
192
+ assert.equal(card.securitySchemes.pairing.oauth2SecurityScheme.flows.deviceCode.deviceAuthorizationUrl, `${BASE}/oauth/device_authorization`);
193
+ assert.deepEqual(F.cardLeaks(card, BASE, [TAILNET, "https://agent-upstream.example.net"]), []);
194
+ assert.ok(!JSON.stringify(card).includes("agent-upstream"), "the tunnel hostname stays private too");
195
+ const c03 = (await s.call("GET", "/.well-known/agent.json")).data;
196
+ assert.equal(c03.url, BASE + "/");
197
+ assert.equal(c03.name, "Jean");
198
+ assert.deepEqual(F.cardLeaks(c03, BASE, [TAILNET]), []);
199
+ // the card fetch carried the façade's upstream credentials (Access service token + bearer)
200
+ const cf = s.calls.find((c) => c.url.endsWith("/card-a.json"));
201
+ assert.equal(cf.headers.authorization, "Bearer up-secret");
202
+ assert.equal(cf.headers["cf-access-client-id"], "cid.access");
203
+ assert.equal((await s.call("GET", "/health")).data.mode, "proxy");
204
+ const diag = (await s.call("GET", "/owner/facade", { token: "owner-secret" })).data;
205
+ assert.equal(diag.mode, "proxy");
206
+ assert.equal(diag.upstreamCard, "ok");
207
+ assert.deepEqual(diag.upstreamVersions, ["1.0"]);
208
+ assert.deepEqual(diag.publicCardLeaks, []);
209
+ assert.equal(diag.hasUpstreamToken, true);
210
+ assert.ok(!JSON.stringify(diag).includes("up-secret") && !JSON.stringify(diag).includes("csecret"), "no secret values");
211
+ });
212
+
213
+ test("proxy mode: a cross-origin UPSTREAM_CARD_URL is refused and never fetched with credentials", async (t) => {
214
+ const evil = "https://evil.example.com/steal-card.json";
215
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: evil, UPSTREAM_TOKEN: "up-secret",
216
+ UPSTREAM_ACCESS_CLIENT_ID: "cid.access", UPSTREAM_ACCESS_CLIENT_SECRET: "csecret", AGENT_NAME: "Jean" });
217
+ t.after(s.restore);
218
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
219
+ assert.equal(card.name, "Jean", "config-based card when the upstream card URL is refused");
220
+ assert.ok(!s.calls.some((c) => c.url === evil || c.url.includes("evil.example.com")), "the cross-origin URL is never fetched");
221
+ assert.ok(!s.calls.some((c) => (c.headers?.authorization || "").includes("up-secret")
222
+ || c.headers?.["cf-access-client-id"] === "cid.access"
223
+ || c.headers?.["cf-access-client-secret"] === "csecret"), "credentials never leave for a third-party host");
224
+ const diag = (await s.call("GET", "/owner/facade", { token: "owner-secret" })).data;
225
+ assert.match(diag.upstreamCardProblem || "", /must be on the UPSTREAM_URL origin/);
226
+ assert.match(diag.upstreamCard, /must be on the UPSTREAM_URL origin/);
227
+ assert.equal(diag.upstreamCardUrl, null);
228
+ });
229
+
230
+ test("proxy mode: upstream card unavailable -> config-based card, still no private URL", async (t) => {
231
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-down.json", AGENT_NAME: "Jean" },
232
+ async () => new Response("<html>Bad gateway</html>", { status: 502 }));
233
+ t.after(s.restore);
234
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
235
+ assert.equal(card.name, "Jean");
236
+ assert.deepEqual(card.supportedInterfaces.map((i: any) => i.url), [BASE + "/", BASE + "/"]);
237
+ const diag = (await s.call("GET", "/owner/facade", { token: "owner-secret" })).data;
238
+ assert.match(diag.upstreamCard, /HTTP 502/);
239
+ });
240
+
241
+ test("proxy mode: JSON-RPC is forwarded with the façade's credential, never the peer's token", async (t) => {
242
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-b.json", UPSTREAM_TOKEN: "up-secret",
243
+ UPSTREAM_ACCESS_CLIENT_ID: "cid.access", UPSTREAM_ACCESS_CLIENT_SECRET: "csecret" });
244
+ t.after(s.restore);
245
+ // no token: the usual 401 with the device-flow hint; nothing reaches the upstream
246
+ const un = await s.call("POST", "/", { json: { jsonrpc: "2.0", id: 7, method: "SendMessage", params: {} } });
247
+ assert.equal(un.status, 401);
248
+ assert.equal(un.data.id, 7);
249
+ assert.ok(!s.calls.some((c) => c.url === UPSTREAM));
250
+
251
+ const tok = await s.issue("barry");
252
+ const r = await s.rpc(tok, "SendMessage", { message: { role: "ROLE_USER", messageId: "m1", parts: [{ text: "hi" }] } });
253
+ assert.equal(r.status, 200, JSON.stringify(r.data));
254
+ const taskId = r.data.result.task.id;
255
+ const fwd = s.calls.filter((c) => c.url === UPSTREAM).at(-1);
256
+ assert.equal(fwd.method, "POST");
257
+ assert.equal(fwd.headers.authorization, "Bearer up-secret");
258
+ assert.equal(fwd.headers["cf-access-client-id"], "cid.access");
259
+ assert.equal(fwd.headers["cf-access-client-secret"], "csecret");
260
+ assert.equal(fwd.headers["x-a2a-peer"], "barry");
261
+ assert.equal(fwd.headers["a2a-version"], "1.0");
262
+ assert.ok(!JSON.stringify(fwd.headers).includes(tok), "the peer's token is not forwarded");
263
+ assert.equal(JSON.parse(fwd.body).params.message.parts[0].text, "hi");
264
+
265
+ const g = await s.rpc(tok, "GetTask", { id: taskId });
266
+ assert.equal(g.data.result.id, taskId);
267
+ // no wake, no inbox row: the upstream handles the message
268
+ assert.equal((s.DB.db.prepare("SELECT COUNT(*) AS n FROM tasks").get() as any).n, 0);
269
+ });
270
+
271
+ test("proxy mode: peers sharing the upstream identity can't touch each other's tasks or contexts", async (t) => {
272
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-c.json" });
273
+ t.after(s.restore);
274
+ const a = await s.issue("alice"), b = await s.issue("bob");
275
+ const r = await s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", parts: [{ text: "secret plan" }] } });
276
+ const { id: taskId, contextId } = r.data.result.task;
277
+ const before = s.calls.filter((c) => c.url === UPSTREAM).length;
278
+ for (const [method, params] of [
279
+ ["GetTask", { id: taskId }], ["CancelTask", { id: taskId }], ["tasks/get", { id: taskId }],
280
+ ["GetTaskPushNotificationConfig", { taskId, id: "x" }], ["ListTaskPushNotificationConfig", { taskId }],
281
+ ["DeleteTaskPushNotificationConfig", { taskId, id: "x" }], ["GetTask", { id: "never-seen" }],
282
+ ] as const) {
283
+ const x = await s.rpc(b, method, params);
284
+ assert.equal(x.data.error?.code, -32001, `${method}: ${JSON.stringify(x.data)}`);
285
+ }
286
+ const cont = await s.rpc(b, "SendMessage", { message: { role: "ROLE_USER", taskId, parts: [{ text: "x" }] } });
287
+ assert.equal(cont.data.error?.code, -32001);
288
+ const ref = await s.rpc(b, "SendMessage", { message: { role: "ROLE_USER", referenceTaskIds: [taskId], parts: [{ text: "summarize that" }] } });
289
+ assert.equal(ref.data.error?.code, -32001, "no reading another peer's task through referenceTaskIds");
290
+ const ctx = await s.rpc(b, "SendMessage", { message: { role: "ROLE_USER", contextId, parts: [{ text: "x" }] } });
291
+ assert.equal(ctx.data.error?.code, -32602);
292
+ assert.equal(s.calls.filter((c) => c.url === UPSTREAM).length, before, "refused before reaching the upstream");
293
+ // the owner of the task can continue it
294
+ const own = await s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", taskId, contextId, parts: [{ text: "more" }] } });
295
+ assert.ok(own.data.result, JSON.stringify(own.data));
296
+ assert.ok((await s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", referenceTaskIds: [taskId], parts: [{ text: "follow-up" }] } })).data.result, "own tasks can be referenced");
297
+ // fail closed: a contextId the façade has no record of (client-chosen, or an upstream context opened elsewhere) is
298
+ // refused for everyone, before the upstream; the peer's own returned context works
299
+ const n0 = s.calls.filter((c) => c.url === UPSTREAM).length;
300
+ for (const [tok, ctxId] of [[b, "bob-ctx-1"], [a, "bob-ctx-1"], [a, "upstream-ctx-made-elsewhere"]] as const) {
301
+ const x = await s.rpc(tok, "SendMessage", { message: { role: "ROLE_USER", contextId: ctxId, parts: [{ text: "x" }] } });
302
+ assert.equal(x.data.error?.code, -32602, JSON.stringify(x.data));
303
+ assert.match(x.data.error.message, /omit contextId/);
304
+ }
305
+ assert.equal(s.calls.filter((c) => c.url === UPSTREAM).length, n0, "unrecorded contexts never reach the upstream");
306
+ const bobOwn = (await s.rpc(b, "SendMessage", { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } })).data.result.task.contextId;
307
+ assert.ok((await s.rpc(b, "SendMessage", { message: { role: "ROLE_USER", contextId: bobOwn, parts: [{ text: "again" }] } })).data.result);
308
+ assert.equal((await s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", contextId: bobOwn, parts: [{ text: "x" }] } })).data.error?.code, -32602);
309
+ // ListTasks would list every peer's tasks; streaming is not proxied yet
310
+ assert.equal((await s.rpc(a, "ListTasks", {})).data.error?.code, -32004);
311
+ assert.equal((await s.rpc(a, "SendStreamingMessage", { message: { role: "ROLE_USER", parts: [{ text: "x" }] } })).data.error?.code, -32004);
312
+ assert.equal((await s.rpc(a, "GetExtendedAgentCard", {})).data.error?.code, -32601);
313
+ });
314
+
315
+ test("proxy mode: push configs never reach the upstream (it would call them from inside the private network)", async (t) => {
316
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-d.json" });
317
+ t.after(s.restore);
318
+ const a = await s.issue("alice");
319
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
320
+ assert.equal(card.capabilities.pushNotifications, false, "even though the upstream card says true");
321
+ const msg = { role: "ROLE_USER", parts: [{ text: "x" }] };
322
+ const n0 = s.calls.filter((c) => c.url === UPSTREAM).length;
323
+ // public-looking names can resolve to private space on the upstream's network (127.0.0.1.nip.io), so every push URL is refused
324
+ for (const url of ["https://127.0.0.1.nip.io/x", "https://hooks.example.org/a2a", "http://hooks.example.org/x", "https://192.168.1.1/"]) {
325
+ for (const configuration of [{ taskPushNotificationConfig: { url } }, { pushNotificationConfig: { url } }, { taskPushNotificationConfig: { pushNotificationConfig: { url } } }]) {
326
+ const r = await s.rpc(a, "SendMessage", { message: msg, configuration });
327
+ assert.equal(r.data.error?.code, -32003, `${url} ${JSON.stringify(configuration)}`);
328
+ }
329
+ }
330
+ const ok = await s.rpc(a, "SendMessage", { message: msg, configuration: { acceptedOutputModes: ["text/plain"] } });
331
+ const taskId = ok.data.result.task.id;
332
+ const n1 = s.calls.filter((c) => c.url === UPSTREAM).length;
333
+ assert.equal(n1, n0 + 1, "only the push-free message went upstream");
334
+ for (const [method, params] of [
335
+ ["CreateTaskPushNotificationConfig", { taskId, url: "https://hooks.example.org/b" }],
336
+ ["tasks/pushNotificationConfig/set", { taskId, pushNotificationConfig: { url: "https://hooks.example.org/b" } }],
337
+ ["GetTaskPushNotificationConfig", { taskId, id: "x" }], ["ListTaskPushNotificationConfig", { taskId }],
338
+ ["DeleteTaskPushNotificationConfig", { taskId, id: "x" }], ["tasks/pushNotificationConfig/get", { id: taskId }],
339
+ ] as const) {
340
+ const r = await s.rpc(a, method, params);
341
+ assert.equal(r.data.error?.code, -32003, method);
342
+ }
343
+ assert.equal(s.calls.filter((c) => c.url === UPSTREAM).length, n1, "no push call reached the upstream");
344
+ assert.equal(F.wantsPush("send", { configuration: { blocking: true } }), false);
345
+ assert.equal(F.wantsPush("send", { configuration: { pushNotificationConfig: null } }), false);
346
+ assert.equal(F.wantsPush("pushget", {}), true);
347
+ });
348
+
349
+ test("proxy mode: upstream failures are the façade's errors, never a 401 to the peer", async (t) => {
350
+ let mode = "401";
351
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_CARD_URL: "https://agent-upstream.example.net/card-e.json" }, async (url) => {
352
+ if (url.endsWith(".json")) return Response.json(tailnetCard());
353
+ if (mode === "401") return new Response("unauthorized", { status: 401 });
354
+ if (mode === "html") return new Response("<html>error 1033</html>", { status: 530 });
355
+ if (mode === "rpc-error") return Response.json({ jsonrpc: "2.0", id: 1, error: { code: -32602, message: "bad" } }, { status: 400 });
356
+ throw new Error("connect ECONNREFUSED");
357
+ });
358
+ t.after(s.restore);
359
+ const a = await s.issue("alice");
360
+ const send = () => s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", parts: [{ text: "x" }] } });
361
+ let r = await send();
362
+ assert.equal(r.status, 502);
363
+ assert.match(r.data.error.message, /refused by its upstream/);
364
+ mode = "html";
365
+ r = await send();
366
+ assert.equal(r.status, 502);
367
+ assert.equal(r.data.error.code, -32603);
368
+ mode = "down";
369
+ r = await send();
370
+ assert.equal(r.status, 502);
371
+ assert.match(r.data.error.message, /not reachable/);
372
+ mode = "rpc-error";
373
+ r = await send();
374
+ assert.equal(r.status, 200, "a JSON-RPC error from the upstream passes through");
375
+ assert.equal(r.data.error.code, -32602);
376
+ });
377
+
378
+ test("proxy mode: a private UPSTREAM_URL is a configuration error (the Worker can't reach a Tailnet)", async (t) => {
379
+ const s = setup({ UPSTREAM_URL: "https://jean.tail1234.ts.net/a2a" });
380
+ t.after(s.restore);
381
+ const a = await s.issue("alice");
382
+ const r = await s.rpc(a, "SendMessage", { message: { role: "ROLE_USER", parts: [{ text: "x" }] } });
383
+ assert.equal(r.status, 503);
384
+ assert.equal(s.calls.length, 0);
385
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
386
+ assert.deepEqual(F.cardLeaks(card, BASE), []);
387
+ assert.match((await s.call("GET", "/owner/facade", { token: "owner-secret" })).data.upstreamProblem, /private-network/);
388
+ });
389
+
390
+ test("pairing out from a Tailnet agent: a *.ts.net card URL is accepted and flagged as not publicly reachable", async (t) => {
391
+ const s = setup({ WAKE_PRESET: "grok-bot", WAKE_WEBHOOK_URL: "https://hook.example.net/wake", WAKE_WEBHOOK_KEY: "k" });
392
+ t.after(s.restore);
393
+ const st = await s.call("POST", "/oauth/device_authorization", { json: { client_name: "Jean", agent_card_url: `${TAILNET}/.well-known/agent-card.json` } });
394
+ assert.equal(st.status, 200, JSON.stringify(st.data));
395
+ const wake = s.calls.find((c) => c.url === "https://hook.example.net/wake");
396
+ assert.equal(JSON.parse(wake.body).pairing.agentCardPrivate, true, "the wake flags the private card");
397
+ const page = await s.call("GET", `/device?user_code=${st.data.user_code}`);
398
+ assert.match(page.text, /not publicly reachable/);
399
+ });
400
+
401
+ test("wake text for a private claimed card says it is not publicly reachable", async () => {
402
+ const { wakeSummary } = await import("../src/wake.ts");
403
+ const txt = wakeSummary({ contextId: "pairing", taskId: "none", taskIds: [], from: "Jean", preview: "", kind: "pairing_request", publicUrl: BASE,
404
+ pairing: { userCode: "WDJB-4827", verificationUriComplete: `${BASE}/device?user_code=WDJB-4827`, approval: "human", clientName: "Jean", clientId: "",
405
+ agentCardUrl: `${TAILNET}/.well-known/agent-card.json`, agentCardPrivate: true, expiresIn: 600 } }, "npx a2a-exposed");
406
+ assert.match(txt, /private network: not publicly reachable/);
407
+ });
408
+
409
+ test("proxy mode: the landing page shows the rewritten card (upstream name and skills, no private URL)", async (t) => {
410
+ const s = setup({ UPSTREAM_URL: UPSTREAM, UPSTREAM_TOKEN: "up-secret" });
411
+ t.after(s.restore);
412
+ const h = await s.call("GET", "/", { headers: { accept: "text/html" } });
413
+ assert.equal(h.status, 200);
414
+ assert.match(h.text, /<title>Jean<\/title>/);
415
+ assert.match(h.text, /<b>Chat<\/b>/);
416
+ for (const leak of ["ts.net", "tail1234", "localhost", "agent-upstream", "192.168.", "100.101."]) assert.ok(!h.text.includes(leak), leak);
417
+ assert.ok(!h.text.includes("inbox"), "a façade isn't an inbox");
418
+ const j = await s.call("GET", "/");
419
+ assert.equal(j.data.name, "Jean");
420
+ assert.ok(!JSON.stringify(j.data).includes("ts.net"));
421
+ });