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,651 @@
1
+ // Device-flow pairing (RFC 8628) end to end against the real Worker fetch handler, with D1 on node:sqlite and the
2
+ // wake webhook captured. 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 P from "../src/pairing.ts";
7
+ import { wakeSummary, renderWake, type WakeEvent } from "../src/wake.ts";
8
+ import { d1 } from "./d1.ts";
9
+
10
+ const BASE = "https://agent.example.com";
11
+ const GRANT = "urn:ietf:params:oauth:grant-type:device_code";
12
+ const PASSWORD = "correct horse battery staple";
13
+
14
+ const realNow = Date.now;
15
+ let offset = 0;
16
+ Date.now = () => realNow() + offset;
17
+ const advance = (s: number) => { offset += s * 1000; };
18
+
19
+ async function passwordRecord(pw = PASSWORD) {
20
+ const salt = crypto.getRandomValues(new Uint8Array(16));
21
+ const hash = await P.pbkdf2(pw, salt, 100000);
22
+ const b64 = (b: Uint8Array) => btoa(String.fromCharCode(...b));
23
+ return { alg: "pbkdf2-sha256", iterations: 100000, salt: b64(salt), hash: b64(hash) };
24
+ }
25
+
26
+ function setup(over: Record<string, string> = {}) {
27
+ const DB = d1(new URL("../migrations/", import.meta.url));
28
+ const env: any = { DB, PUBLIC_URL: BASE, OWNER_TOKEN: "owner-secret", AGENT_NAME: "Test Inbox", WAKE_PRESET: "grok-bot",
29
+ WAKE_WEBHOOK_URL: "https://hook.example.net/wake", WAKE_WEBHOOK_KEY: "hook-key", ...over };
30
+ const wakes: any[] = [];
31
+ const origFetch = globalThis.fetch;
32
+ globalThis.fetch = (async (url: any, init: any) => {
33
+ wakes.push({ url: String(url), body: JSON.parse(init.body) });
34
+ return new Response("ok");
35
+ }) as any;
36
+ const call = async (method: string, path: string, o: { form?: Record<string, string>; json?: any; headers?: Record<string, string>; ip?: string; cookie?: string } = {}) => {
37
+ const headers: Record<string, string> = { "cf-connecting-ip": o.ip || "198.51.100.7", ...(o.headers || {}) };
38
+ let body: string | undefined;
39
+ if (o.form) { headers["content-type"] = "application/x-www-form-urlencoded"; body = new URLSearchParams(o.form).toString(); }
40
+ if (o.json !== undefined) { headers["content-type"] = "application/json"; body = JSON.stringify(o.json); }
41
+ if (o.cookie) headers.cookie = o.cookie;
42
+ const pending: Promise<unknown>[] = [];
43
+ 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);
44
+ await Promise.allSettled(pending);
45
+ const text = await res.text();
46
+ let data: any = text;
47
+ try { data = JSON.parse(text); } catch { /* html */ }
48
+ return { status: res.status, headers: res.headers, data, text };
49
+ };
50
+ const owner = (method: string, path: string, json?: any) => call(method, path, { json, headers: { authorization: "Bearer owner-secret" } });
51
+ const start = (form: Record<string, string> = { client_name: "Barry Bot", client_id: "barry", agent_card_url: "https://barry.example.org/.well-known/agent-card.json" }, ip?: string) =>
52
+ call("POST", "/oauth/device_authorization", { form, ip });
53
+ const poll = (device_code: string) => call("POST", "/oauth/token", { form: { grant_type: GRANT, device_code } });
54
+ /** GET the page (sets the CSRF cookie), then POST the decision with it. */
55
+ const decidePage = async (userCode: string, password: string, decision: "approve" | "deny", ip?: string) => {
56
+ const g = await call("GET", `/device?user_code=${userCode}`, { ip });
57
+ const cookie = (g.headers.get("set-cookie") || "").split(";")[0];
58
+ const csrf = /name="csrf" value="([^"]+)"/.exec(g.text)?.[1] || cookie.split("=")[1];
59
+ return call("POST", "/device", { form: { csrf, user_code: userCode, password, decision }, cookie, ip, headers: { origin: BASE } });
60
+ };
61
+ return { env, DB, wakes, call, owner, start, poll, decidePage, restore: () => { globalThis.fetch = origFetch; } };
62
+ }
63
+
64
+ test("pairing helpers: user codes, labels, requester text, params, password hashing", async () => {
65
+ for (let i = 0; i < 200; i++) assert.match(P.newUserCode(), /^[BCDFGHJKLMNPQRSTVWXZ]{4}[2-9]{4}$/);
66
+ assert.equal(P.formatUserCode("WDJB4827"), "WDJB-4827");
67
+ assert.equal(P.normUserCode(" wdjb-4827 "), "WDJB4827");
68
+ assert.equal(P.normUserCode("WDJB 4827"), "WDJB4827");
69
+ for (const bad of ["WDJB-4801", "WXYZ-4827", "AEIO-2345", "WDJ-2345", "", 7]) assert.equal(P.normUserCode(bad), null, String(bad));
70
+ assert.match(P.newDeviceCode(), /^[A-Za-z0-9_-]{43}$/);
71
+ assert.equal(P.labelBase("Barry Bot (Hermes)", "x"), "Barry-Bot-Hermes");
72
+ assert.equal(P.labelBase(" *** ", "hermes.local"), "hermes-local");
73
+ assert.equal(P.labelBase("", ""), "paired-agent");
74
+ assert.equal(P.dedupeLabel("barry", new Set(["barry", "barry-2"])), "barry-3");
75
+ assert.equal(P.cleanText("a\u202eb\nc\u0000d " + "x".repeat(100)).length, 64);
76
+ assert.equal(P.cleanText("Barry\u202e\nBot"), "Barry Bot");
77
+ assert.equal(P.cleanCardUrl("https://a.example/.well-known/agent-card.json"), "https://a.example/.well-known/agent-card.json");
78
+ for (const bad of ["http://a.example/", "https://u:p@a.example/", "javascript:alert(1)", "https://a.example/" + "x".repeat(300)]) assert.equal(P.cleanCardUrl(bad), "");
79
+ assert.deepEqual(P.parseParams("client_name=A+B&client_id=x&client_id=y", "application/x-www-form-urlencoded"), { client_name: "A B", client_id: "x" });
80
+ assert.deepEqual(P.parseParams('{"client_name":"A","n":1}', "application/json"), { client_name: "A" });
81
+ assert.throws(() => P.parseParams("[1]", "application/json"));
82
+ assert.equal(P.pairingMode(undefined), "human");
83
+ assert.equal(P.pairingMode("AGENT"), "agent");
84
+ assert.equal(P.pairingMode("off"), "off");
85
+ assert.equal(P.pairingMode("yolo"), "human", "unknown values fall back to the safe mode");
86
+ const rec = await passwordRecord();
87
+ assert.equal(P.checkPasswordRecord(rec), "");
88
+ assert.match(P.checkPasswordRecord({ ...rec, iterations: 1000 }), /iterations/);
89
+ assert.match(P.checkPasswordRecord({ ...rec, hash: "AAAA" }), /32 bytes/);
90
+ assert.equal(await P.verifyPassword(PASSWORD, rec as any), true);
91
+ assert.equal(await P.verifyPassword(PASSWORD + "!", rec as any), false);
92
+ assert.equal(await P.verifyPassword("", rec as any), false);
93
+ });
94
+
95
+ test("agent card, RFC 8414 metadata and the 401 hint advertise the device flow; bearer stays", async (t) => {
96
+ const s = setup(); t.after(s.restore);
97
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
98
+ assert.deepEqual(card.securitySchemes.bearer.httpAuthSecurityScheme.scheme, "Bearer");
99
+ const o = card.securitySchemes.pairing.oauth2SecurityScheme;
100
+ assert.deepEqual(o.flows.deviceCode.deviceAuthorizationUrl, `${BASE}/oauth/device_authorization`);
101
+ assert.deepEqual(o.flows.deviceCode.tokenUrl, `${BASE}/oauth/token`);
102
+ assert.equal(typeof o.flows.deviceCode.scopes, "object");
103
+ assert.equal(o.oauth2MetadataUrl, `${BASE}/.well-known/oauth-authorization-server`);
104
+ assert.match(o.description, /RFC 8628[\s\S]*user_code[\s\S]*owner approves/);
105
+ assert.deepEqual(card.securityRequirements, [{ schemes: { bearer: { list: [] } } }, { schemes: { pairing: { list: [] } } }]);
106
+ assert.deepEqual(card.supportedInterfaces.map((i: any) => i.protocolVersion), ["1.0", "0.3"], "both bindings unchanged");
107
+
108
+ const meta = await s.call("GET", "/.well-known/oauth-authorization-server");
109
+ assert.equal(meta.status, 200);
110
+ assert.deepEqual([meta.data.issuer, meta.data.device_authorization_endpoint, meta.data.token_endpoint], [BASE, `${BASE}/oauth/device_authorization`, `${BASE}/oauth/token`]);
111
+ assert.deepEqual(meta.data.grant_types_supported, [GRANT]);
112
+ assert.deepEqual(meta.data.token_endpoint_auth_methods_supported, ["none"]);
113
+
114
+ for (const [method, v] of [["message/send", "0.3"], ["SendMessage", "1.0"]]) {
115
+ const r = await s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method, params: { message: {} } }, headers: { "a2a-version": v } });
116
+ assert.equal(r.status, 401);
117
+ assert.equal(r.headers.get("www-authenticate"), `Bearer realm="a2a", resource_metadata="${BASE}/.well-known/oauth-protected-resource"`);
118
+ assert.equal(r.data.id, 1, "the JSON-RPC id is echoed");
119
+ assert.equal(r.data.error.code, -32000);
120
+ assert.match(r.data.error.message, /device flow \(RFC 8628\): POST client_name and agent_card_url to https:\/\/agent\.example\.com\/oauth\/device_authorization/);
121
+ assert.equal(r.data.error.data.pairing.device_authorization_endpoint, `${BASE}/oauth/device_authorization`);
122
+ assert.equal(r.data.error.data.pairing.token_endpoint, `${BASE}/oauth/token`);
123
+ assert.equal(r.data.error.data.pairing.grant_type, GRANT);
124
+ }
125
+ const bad = await s.call("POST", "/", { json: { jsonrpc: "2.0", id: "req-7", method: "SendMessage", params: {} }, headers: { authorization: "Bearer nope" } });
126
+ assert.equal(bad.headers.get("www-authenticate"), `Bearer realm="a2a", resource_metadata="${BASE}/.well-known/oauth-protected-resource", error="invalid_token", error_description="the bearer token is not valid (revoked, rotated or mistyped)"`);
127
+ assert.equal(bad.data.id, "req-7");
128
+ assert.match(bad.data.error.message, /^Unauthorized: the bearer token is not valid \(revoked, rotated or mistyped\)\. Get a new one with the OAuth 2\.0 device flow/);
129
+ const garbage = await s.call("POST", "/", { headers: { "content-type": "application/json" } });
130
+ assert.equal(garbage.data.id, null, "no parseable body: id null");
131
+ // RFC 9728 metadata names the authorization server
132
+ const prm = await s.call("GET", "/.well-known/oauth-protected-resource");
133
+ assert.equal(prm.status, 200);
134
+ assert.deepEqual([prm.data.resource, prm.data.authorization_servers, prm.data.bearer_methods_supported], [`${BASE}/`, [BASE], ["header"]]);
135
+ });
136
+
137
+ test("/.well-known/agent.json serves an A2A 0.3 card (url, preferredTransport, protocolVersion); agent-card.json stays 1.0", async (t) => {
138
+ const s = setup({ AGENT_SKILLS: JSON.stringify([{ id: "s1", name: "S1", description: "d" }]) }); t.after(s.restore);
139
+ const old = (await s.call("GET", "/.well-known/agent.json")).data;
140
+ assert.equal(old.protocolVersion, "0.3.0");
141
+ assert.equal(old.url, `${BASE}/`);
142
+ assert.equal(old.preferredTransport, "JSONRPC");
143
+ assert.deepEqual(old.additionalInterfaces, [{ url: `${BASE}/`, transport: "JSONRPC" }]);
144
+ assert.deepEqual([old.name, old.version], ["Test Inbox", "1.0.0"]);
145
+ assert.deepEqual(old.capabilities, { streaming: false, pushNotifications: true, stateTransitionHistory: false });
146
+ assert.deepEqual(old.securitySchemes.bearer, { type: "http", scheme: "bearer", description: old.securitySchemes.bearer.description });
147
+ assert.equal(old.securitySchemes.pairing.type, "oauth2");
148
+ assert.equal(old.securitySchemes.pairing.oauth2MetadataUrl, `${BASE}/.well-known/oauth-authorization-server`);
149
+ assert.deepEqual(old.security, [{ bearer: [] }]);
150
+ assert.deepEqual(old.skills, [{ id: "s1", name: "S1", description: "d", tags: [] }], "0.3 requires tags");
151
+ assert.equal(old.supportedInterfaces, undefined, "no 1.0-only fields");
152
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
153
+ assert.equal(card.url, undefined);
154
+ assert.deepEqual(card.supportedInterfaces.map((i: any) => i.protocolVersion), ["1.0", "0.3"]);
155
+ const off = setup({ PAIRING_APPROVAL: "off" }); t.after(off.restore);
156
+ assert.deepEqual(Object.keys((await off.call("GET", "/.well-known/agent.json")).data.securitySchemes), ["bearer"]);
157
+ });
158
+
159
+ test("PAIRING_APPROVAL=off: no pairing scheme, endpoints 404, plain 401", async (t) => {
160
+ const s = setup({ PAIRING_APPROVAL: "off" }); t.after(s.restore);
161
+ const card = (await s.call("GET", "/.well-known/agent-card.json")).data;
162
+ assert.deepEqual(Object.keys(card.securitySchemes), ["bearer"]);
163
+ assert.deepEqual(card.securityRequirements, [{ schemes: { bearer: { list: [] } } }]);
164
+ for (const [m, p] of [["GET", "/.well-known/oauth-authorization-server"], ["POST", "/oauth/device_authorization"], ["POST", "/oauth/token"], ["GET", "/device"]]) {
165
+ const r = await s.call(m, p, m === "POST" ? { form: {} } : {});
166
+ assert.equal(r.status, 404, p);
167
+ assert.match(r.data.error_description, /disabled/);
168
+ }
169
+ const r = await s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method: "SendMessage", params: {} } });
170
+ assert.equal(r.status, 401);
171
+ assert.equal(r.data.error.data, undefined);
172
+ assert.equal(s.wakes.length, 0);
173
+ const a = await s.owner("POST", "/owner/pairing/WDJB-2345/approve");
174
+ assert.equal(a.status, 404);
175
+ });
176
+
177
+ test("human approval: pending, slow_down, page approve with the password, single-use token, owner approve refused", async (t) => {
178
+ const s = setup(); t.after(s.restore);
179
+ const st = await s.start({ client_name: 'Barry <script>alert(1)</script>', client_id: "barry", agent_card_url: "https://barry.example.org/.well-known/agent-card.json" });
180
+ assert.equal(st.status, 200);
181
+ assert.equal(st.headers.get("cache-control"), "no-store");
182
+ const d = st.data;
183
+ assert.match(d.device_code, /^[A-Za-z0-9_-]{43}$/);
184
+ assert.match(d.user_code, /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[2-9]{4}$/);
185
+ assert.equal(d.verification_uri, `${BASE}/device`);
186
+ assert.equal(d.verification_uri_complete, `${BASE}/device?user_code=${d.user_code}`);
187
+ assert.deepEqual([d.expires_in, d.interval], [600, 5]);
188
+ // the device code is stored hashed only
189
+ const row: any = s.DB.db.prepare("SELECT * FROM device_requests").get();
190
+ assert.notEqual(row.device_hash, d.device_code);
191
+ assert.ok(!JSON.stringify(row).includes(d.device_code));
192
+
193
+ // the wake: kind pairing_request with the code and the link; the agent is told to ask its human
194
+ assert.equal(s.wakes.length, 1);
195
+ const w = s.wakes[0].body;
196
+ assert.equal(w.kind, "pairing_request");
197
+ assert.equal(w.hint, "npx a2a-exposed pair list");
198
+ assert.deepEqual([w.pairing.userCode, w.pairing.verificationUriComplete, w.pairing.approval, w.pairing.clientId], [d.user_code, d.verification_uri_complete, "human", "barry"]);
199
+ assert.equal(w.pairing.agentCardUrl, "https://barry.example.org/.well-known/agent-card.json");
200
+ assert.match(w.pairing.instructions, /never approve on your own[\s\S]*give them this link/);
201
+
202
+ let p = await s.poll(d.device_code);
203
+ assert.deepEqual([p.status, p.data.error], [400, "authorization_pending"]);
204
+ p = await s.poll(d.device_code);
205
+ assert.deepEqual([p.status, p.data.error], [400, "slow_down"], "polled again at once");
206
+ assert.match(p.data.error_description, /at least 10 seconds/);
207
+ advance(6);
208
+ p = await s.poll(d.device_code);
209
+ assert.equal(p.data.error, "slow_down", "the interval grew to 10 s");
210
+ assert.match(p.data.error_description, /at least 15 seconds/, "and grows by 5 s on every slow_down (RFC 8628 §3.5)");
211
+ advance(16);
212
+ assert.equal((await s.poll(d.device_code)).data.error, "authorization_pending");
213
+
214
+ // human mode: the owner API (the agent) cannot approve
215
+ const oa = await s.owner("POST", `/owner/pairing/${d.user_code}/approve`);
216
+ assert.equal(oa.status, 403);
217
+ assert.match(oa.data.error, /approval mode is human: the owner approves on https:\/\/agent\.example\.com\/device\?user_code=/);
218
+ const list = await s.owner("GET", "/owner/pairing");
219
+ assert.deepEqual([list.data.mode, list.data.passwordSet, list.data.pending.length, list.data.pending[0].userCode], ["human", false, 1, d.user_code]);
220
+
221
+ // the page: escaped requester text, strict CSP, no caching; no password yet -> how to set one
222
+ let g = await s.call("GET", `/device?user_code=${d.user_code.toLowerCase()}`);
223
+ assert.equal(g.status, 200);
224
+ assert.ok(!g.text.includes("<script>") && g.text.includes("Barry &lt;script&gt;"));
225
+ assert.ok(g.text.includes("https://barry.example.org/.well-known/agent-card.json") && g.text.includes("198.51.100.7"));
226
+ assert.match(g.headers.get("content-security-policy")!, /^default-src 'none'; style-src 'nonce-[A-Za-z0-9_-]+'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'$/);
227
+ assert.equal(g.headers.get("cache-control"), "no-store");
228
+ assert.equal(g.headers.get("x-frame-options"), "DENY");
229
+ assert.match(g.headers.get("set-cookie")!, /^a2a_device_csrf=[A-Za-z0-9_-]{24}; Path=\/device; Secure; HttpOnly; SameSite=Strict/);
230
+ assert.ok(!/<script|src=|href=/i.test(g.text), "no scripts or external assets");
231
+ assert.match(g.text, /No approval password is set yet[\s\S]*npx a2a-exposed pair set-password/);
232
+ assert.ok(!g.text.includes('name="password"'));
233
+ assert.equal((await s.decidePage(d.user_code, PASSWORD, "approve")).status, 409);
234
+
235
+ assert.equal((await s.owner("PUT", "/owner/pairing/password", { ...(await passwordRecord()), iterations: 1000 })).status, 400);
236
+ assert.equal((await s.owner("PUT", "/owner/pairing/password", await passwordRecord())).status, 200);
237
+ g = await s.call("GET", `/device?user_code=${d.user_code}`);
238
+ assert.ok(g.text.includes('name="password"') && g.text.includes('value="approve"') && g.text.includes('value="deny"'));
239
+
240
+ // CSRF: no cookie, or another site's Origin -> refused without checking the password
241
+ const csrf = /name="csrf" value="([^"]+)"/.exec(g.text)![1];
242
+ let r = await s.call("POST", "/device", { form: { csrf, user_code: d.user_code, password: PASSWORD, decision: "approve" } });
243
+ assert.equal(r.status, 403);
244
+ assert.match(r.text, /expired or came from another site/);
245
+ r = await s.call("POST", "/device", { form: { csrf, user_code: d.user_code, password: PASSWORD, decision: "approve" }, cookie: `a2a_device_csrf=${csrf}`, headers: { origin: "https://evil.example" } });
246
+ assert.equal(r.status, 403);
247
+
248
+ r = await s.decidePage(d.user_code, "wrong password", "approve");
249
+ assert.equal(r.status, 403);
250
+ assert.match(r.text, /Wrong password\. 4 attempts left for this code\./);
251
+ r = await s.decidePage(d.user_code, PASSWORD, "approve");
252
+ assert.equal(r.status, 200, r.text);
253
+ assert.match(r.text, /Approved\. Barry &lt;script&gt;alert\(1\)&lt;\/script&gt; can now collect its token \(label &quot;Barry-script-alert-1-scr&quot;\)/);
254
+
255
+ advance(11);
256
+ p = await s.poll(d.device_code);
257
+ assert.equal(p.status, 200);
258
+ assert.equal(p.headers.get("cache-control"), "no-store");
259
+ assert.deepEqual(Object.keys(p.data).sort(), ["access_token", "peer_label", "token_type"]);
260
+ assert.equal(p.data.peer_label, "Barry-script-alert-1-scr");
261
+ assert.equal(p.data.token_type, "Bearer");
262
+ assert.match(p.data.access_token, /^a2aow_[A-Za-z0-9_-]{43}$/);
263
+ // single use: the device code is gone
264
+ advance(11);
265
+ assert.deepEqual([(await s.poll(d.device_code)).data.error], ["invalid_grant"]);
266
+ assert.equal(s.DB.db.prepare("SELECT COUNT(*) AS n FROM device_requests").get()!.n, 0);
267
+
268
+ // the token is a normal peer token
269
+ const rpc = await s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method: "GetTask", params: { id: "nope" } }, headers: { authorization: `Bearer ${p.data.access_token}`, "a2a-version": "1.0" } });
270
+ assert.equal(rpc.status, 200);
271
+ assert.equal(rpc.data.error.code, -32001, "authenticated: task not found");
272
+ const peers = (await s.owner("GET", "/owner/peers")).data;
273
+ assert.equal(peers.length, 1);
274
+ assert.deepEqual([peers[0].label, peers[0].source, peers[0].user_code, peers[0].client_name], ["Barry-script-alert-1-scr", "pairing", d.user_code, "Barry <script>alert(1)</script>"]);
275
+ assert.ok(!JSON.stringify(s.DB.db.prepare("SELECT * FROM peers").all()).includes(p.data.access_token), "stored hashed");
276
+ // revocation works as for any token
277
+ await s.owner("DELETE", `/owner/peers/${peers[0].label}`);
278
+ assert.equal((await s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method: "GetTask", params: { id: "x" } }, headers: { authorization: `Bearer ${p.data.access_token}` } })).status, 401);
279
+ });
280
+
281
+ test("labels are deduplicated; denied and expired requests; JSON bodies; bad requests", async (t) => {
282
+ const s = setup({ PAIRING_APPROVAL: "agent" }); t.after(s.restore);
283
+ await s.owner("POST", "/owner/peers", { label: "barry" });
284
+ const a = (await s.start({ client_id: "barry" }, "203.0.113.1", )).data;
285
+ const ok = await s.owner("POST", `/owner/pairing/${a.user_code}/approve`);
286
+ assert.equal(ok.status, 200);
287
+ assert.deepEqual([ok.data.decision, ok.data.label], ["approved", "barry-2"]);
288
+ const b = (await s.call("POST", "/oauth/device_authorization", { json: { client_id: "barry" }, ip: "203.0.113.2" })).data;
289
+ assert.equal((await s.owner("POST", `/owner/pairing/${b.user_code}/approve`)).data.label, "barry-3", "barry-2 is reserved by the approved request");
290
+ assert.equal((await s.poll(a.device_code)).data.token_type, "Bearer");
291
+ assert.equal((await s.owner("POST", `/owner/pairing/${a.user_code}/approve`)).status, 409, "already decided (and redeemed)");
292
+
293
+ const c = (await s.start(undefined, "203.0.113.3")).data;
294
+ const dn = await s.owner("POST", `/owner/pairing/${c.user_code}/deny`);
295
+ assert.equal(dn.data.decision, "denied");
296
+ assert.equal((await s.poll(c.device_code)).data.error, "access_denied");
297
+ advance(6);
298
+ assert.equal((await s.poll(c.device_code)).data.error, "invalid_grant", "reported once, then gone");
299
+
300
+ const e = (await s.start(undefined, "203.0.113.4")).data;
301
+ advance(601);
302
+ assert.equal((await s.poll(e.device_code)).data.error, "expired_token");
303
+ assert.equal((await s.owner("POST", `/owner/pairing/${e.user_code}/approve`)).status, 409);
304
+ advance(3600);
305
+ assert.equal((await s.poll(e.device_code)).data.error, "expired_token", "still expired_token an hour later (RFC 8628), not invalid_grant");
306
+ advance(86400);
307
+ await s.start(undefined, "203.0.113.5"); // cleanup runs on new requests
308
+ assert.equal((await s.poll(e.device_code)).data.error, "invalid_grant", "forgotten a day after expiry");
309
+
310
+ assert.equal((await s.call("POST", "/oauth/token", { form: { grant_type: "password", device_code: "x" } })).data.error, "unsupported_grant_type");
311
+ assert.equal((await s.call("POST", "/oauth/token", { form: { grant_type: GRANT } })).data.error, "invalid_request");
312
+ assert.equal((await s.poll("not-a-real-code")).data.error, "invalid_grant");
313
+ const badCard = await s.start({ client_name: "x", agent_card_url: "http://insecure.example/card" }, "203.0.113.6");
314
+ assert.deepEqual([badCard.status, badCard.data.error], [400, "invalid_request"]);
315
+ assert.equal((await s.owner("POST", "/owner/pairing/AEIO-0000/approve")).status, 400);
316
+ });
317
+
318
+ test("wrong-password lockout: per code (request denied) and per IP (locked even with the right password)", async (t) => {
319
+ const s = setup(); t.after(s.restore);
320
+ await s.owner("PUT", "/owner/pairing/password", await passwordRecord());
321
+ const a = (await s.start(undefined, "203.0.113.10")).data;
322
+ for (let i = 4; i >= 1; i--) assert.match((await s.decidePage(a.user_code, `guess-${i}`, "approve", "192.0.2.1")).text, new RegExp(`${i} attempts? left`));
323
+ const last = await s.decidePage(a.user_code, "guess-0", "approve", "192.0.2.1");
324
+ assert.match(last.text, /Too many wrong attempts for this code: the request was denied/);
325
+ assert.equal((await s.poll(a.device_code)).data.error, "access_denied");
326
+
327
+ // per IP: 10 wrong passwords an hour (across codes), then even the right one is refused
328
+ const b = (await s.start(undefined, "203.0.113.11")).data;
329
+ const c = (await s.start(undefined, "203.0.113.12")).data;
330
+ for (let i = 0; i < 4; i++) await s.decidePage(b.user_code, "nope", "approve", "192.0.2.1");
331
+ for (let i = 0; i < 1; i++) await s.decidePage(c.user_code, "nope", "approve", "192.0.2.1");
332
+ const locked = await s.decidePage(c.user_code, PASSWORD, "approve", "192.0.2.1");
333
+ assert.equal(locked.status, 429);
334
+ assert.match(locked.text, /Too many wrong passwords/);
335
+ // another address still works; after the hour the first one does too
336
+ assert.equal((await s.decidePage(c.user_code, PASSWORD, "deny", "192.0.2.2")).status, 200);
337
+ advance(3600);
338
+ const d2 = (await s.start(undefined, "203.0.113.13")).data;
339
+ assert.equal((await s.decidePage(d2.user_code, PASSWORD, "approve", "192.0.2.1")).status, 200);
340
+ });
341
+
342
+ test("flood control: requests per IP and outstanding requests are capped (no flood of approval prompts)", async (t) => {
343
+ const s = setup(); t.after(s.restore);
344
+ for (let i = 0; i < 5; i++) assert.equal((await s.start(undefined, "198.51.100.50")).status, 200);
345
+ const sixth = await s.start(undefined, "198.51.100.50");
346
+ assert.deepEqual([sixth.status, sixth.data.error], [429, "slow_down"]);
347
+ assert.equal(sixth.headers.get("retry-after"), "600");
348
+ assert.equal(s.wakes.length, 5, "no wake for refused requests");
349
+ for (let i = 0; i < 5; i++) assert.equal((await s.start(undefined, `198.51.100.${60 + i}`)).status, 200);
350
+ const over = await s.start(undefined, "198.51.100.99");
351
+ assert.equal(over.status, 429);
352
+ assert.match(over.data.error_description, /too many pairing requests waiting/);
353
+ // expiry frees the slots
354
+ advance(601);
355
+ assert.equal((await s.start(undefined, "198.51.100.99")).status, 200);
356
+ // the page: code lookups per IP are capped (no enumerating pending requests)
357
+ for (let i = 0; i < 30; i++) assert.doesNotMatch((await s.call("GET", "/device?user_code=BCDF-2345", { ip: "192.0.2.77" })).text, /Too many code lookups/);
358
+ assert.match((await s.call("GET", "/device?user_code=BCDF-2345", { ip: "192.0.2.77" })).text, /Too many code lookups from this address/);
359
+ assert.doesNotMatch((await s.call("GET", "/device?user_code=BCDF-2345", { ip: "192.0.2.78" })).text, /Too many code lookups/);
360
+ });
361
+
362
+ test("pairing wakes: summary for each preset; requester text only where previews are allowed", async () => {
363
+ const ev: WakeEvent = { contextId: "pairing", taskId: "none", taskIds: [], from: "Barry", preview: "", kind: "pairing_request", publicUrl: BASE,
364
+ pairing: { userCode: "WDJB-2345", verificationUriComplete: `${BASE}/device?user_code=WDJB-2345`, approval: "human", clientName: "Barry", clientId: "barry", agentCardUrl: "https://barry.example.org/card", expiresIn: 600 } };
365
+ const sum = wakeSummary(ev, "npx a2a-exposed");
366
+ assert.match(sum, /^A2A pairing request: an agent calling itself "Barry" \(claimed card: "https:\/\/barry\.example\.org\/card"\) asks to connect to your inbox \(code WDJB-2345, expires in 10 minutes\)\./);
367
+ assert.match(sum, /never approve on your own\. Show them the code WDJB-2345 and give them this link: https:\/\/agent\.example\.com\/device\?user_code=WDJB-2345/);
368
+ const agentSum = wakeSummary({ ...ev, pairing: { ...ev.pairing!, approval: "agent" } }, "a2a");
369
+ assert.match(agentSum, /Only if they say yes, run `a2a pair approve WDJB-2345`; if they say no \(or don't answer\), `a2a pair deny WDJB-2345`/);
370
+ const oc = (await renderWake({ preset: "openclaw-wake", url: "https://gw.example/hooks/wake", key: "k" }, ev))!;
371
+ const text = JSON.parse(oc.body).text;
372
+ assert.ok(!text.includes("Barry") && !text.includes("barry.example.org"), "trusted system event: no requester text");
373
+ assert.match(text, /WDJB-2345/);
374
+ });
375
+
376
+ test("/device deny needs no password and runs no PBKDF2; an empty password on approve costs no attempt", async (t) => {
377
+ const s = setup(); t.after(s.restore);
378
+ await s.owner("PUT", "/owner/pairing/password", await passwordRecord());
379
+ const a = (await s.start(undefined, "203.0.113.20")).data;
380
+ const g = await s.call("GET", `/device?user_code=${a.user_code}`);
381
+ assert.match(g.text, /<button name="decision" value="deny" type="submit" class="d" formnovalidate>Deny<\/button>/, "the browser skips the required password for Deny");
382
+ // empty password on approve: refused without hashing or counting
383
+ let r = await s.decidePage(a.user_code, "", "approve");
384
+ assert.equal(r.status, 400);
385
+ assert.match(r.text, /Enter the approval password to approve/);
386
+ assert.equal((s.DB.db.prepare("SELECT failed_attempts FROM device_requests").get() as any).failed_attempts, 0);
387
+ assert.equal(s.DB.db.prepare("SELECT COUNT(*) AS n FROM pairing_rate WHERE key LIKE 'pw:%'").get()!.n, 0, "no wrong-password counter touched");
388
+ // deny with no password at all
389
+ const realPbkdf2 = crypto.subtle.deriveBits;
390
+ let derived = 0;
391
+ (crypto.subtle as any).deriveBits = (...x: any[]) => { derived++; return (realPbkdf2 as any).apply(crypto.subtle, x); };
392
+ try { r = await s.decidePage(a.user_code, "", "deny"); } finally { (crypto.subtle as any).deriveBits = realPbkdf2; }
393
+ assert.equal(r.status, 200, r.text);
394
+ assert.match(r.text, /Denied\. Barry Bot gets no token\./);
395
+ assert.equal(derived, 0, "no PBKDF2 for a deny");
396
+ assert.equal((await s.poll(a.device_code)).data.error, "access_denied");
397
+ // CSRF still applies to deny
398
+ const b = (await s.start(undefined, "203.0.113.21")).data;
399
+ r = await s.call("POST", "/device", { form: { csrf: "x".repeat(24), user_code: b.user_code, decision: "deny" }, cookie: `a2a_device_csrf=${"y".repeat(24)}` });
400
+ assert.equal(r.status, 403);
401
+ // denies count against the per-IP lookup limit (no enumerating codes through deny)
402
+ for (let i = 0; i < 30; i++) await s.decidePage("BCDF-2345", "", "deny", "192.0.2.90");
403
+ r = await s.decidePage(b.user_code, "", "deny", "192.0.2.90");
404
+ assert.equal(r.status, 429);
405
+ // without an approval password the page still offers Deny
406
+ const s2 = setup(); t.after(s2.restore);
407
+ const c = (await s2.start(undefined, "203.0.113.22")).data;
408
+ const g2 = await s2.call("GET", `/device?user_code=${c.user_code}`);
409
+ assert.match(g2.text, /pair set-password --web<\/code> and send you the one-time link/);
410
+ assert.ok(!g2.text.includes('name="password"') && g2.text.includes('value="deny"'));
411
+ assert.equal((await s2.decidePage(c.user_code, "", "deny")).status, 200);
412
+ });
413
+
414
+ test("re-pairing with the current token replaces it under the same label (no orphan token, no -2 label)", async (t) => {
415
+ const s = setup({ PAIRING_APPROVAL: "agent" }); t.after(s.restore);
416
+ const a = (await s.start(undefined, "203.0.113.30")).data;
417
+ await s.owner("POST", `/owner/pairing/${a.user_code}/approve`);
418
+ const first = (await s.poll(a.device_code)).data;
419
+ assert.equal(first.peer_label, "Barry-Bot");
420
+ // the requester sends its current token: the request is marked as a replacement
421
+ const b = await s.call("POST", "/oauth/device_authorization", { form: { client_name: "Barry Bot", client_id: "barry" }, ip: "203.0.113.31", headers: { authorization: `Bearer ${first.access_token}` } });
422
+ assert.equal(b.data.replaces_label, "Barry-Bot");
423
+ assert.equal(s.wakes.at(-1).body.pairing.replacesLabel, "Barry-Bot");
424
+ assert.equal((await s.owner("GET", "/owner/pairing")).data.pending[0].replacesLabel, "Barry-Bot");
425
+ const g = await s.call("GET", `/device?user_code=${b.data.user_code}`);
426
+ assert.match(g.text, /Replaces<\/th><td>the active token &quot;Barry-Bot&quot;/);
427
+ const ok = await s.owner("POST", `/owner/pairing/${b.data.user_code}/approve`);
428
+ assert.deepEqual([ok.data.label, ok.data.replaced], ["Barry-Bot", true]);
429
+ const second = (await s.poll(b.data.device_code)).data;
430
+ assert.deepEqual([second.peer_label, second.replaced], ["Barry-Bot", true]);
431
+ const peers = (await s.owner("GET", "/owner/peers")).data;
432
+ assert.deepEqual(peers.map((p: any) => [p.label, p.revoked_at, p.user_code]), [["Barry-Bot", null, b.data.user_code]], "one label, new code");
433
+ const rpc = (tok: string) => s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method: "GetTask", params: { id: "x" } }, headers: { authorization: `Bearer ${tok}` } });
434
+ assert.equal((await rpc(first.access_token)).status, 401, "the old token stops working");
435
+ assert.equal((await rpc(second.access_token)).status, 200);
436
+ // a bogus bearer is ignored (ordinary request); a replaced token revoked meanwhile -> a new label
437
+ const c = await s.call("POST", "/oauth/device_authorization", { form: { client_name: "Barry Bot" }, ip: "203.0.113.32", headers: { authorization: "Bearer nope" } });
438
+ assert.equal(c.data.replaces_label, undefined);
439
+ const d = await s.call("POST", "/oauth/device_authorization", { form: { client_name: "Barry Bot" }, ip: "203.0.113.33", headers: { authorization: `Bearer ${second.access_token}` } });
440
+ await s.owner("POST", `/owner/pairing/${d.data.user_code}/approve`);
441
+ await s.owner("DELETE", "/owner/peers/Barry-Bot");
442
+ const third = (await s.poll(d.data.device_code)).data;
443
+ assert.equal(third.replaced, undefined);
444
+ assert.equal(third.peer_label, "Barry-Bot-2");
445
+ });
446
+
447
+ test("re-pairing: a rotate between request and redemption refuses the swap (old token cannot overwrite the new one)", async (t) => {
448
+ const s = setup({ PAIRING_APPROVAL: "agent" }); t.after(s.restore);
449
+ const a = (await s.start(undefined, "203.0.113.50")).data;
450
+ await s.owner("POST", `/owner/pairing/${a.user_code}/approve`);
451
+ const first = (await s.poll(a.device_code)).data;
452
+ assert.equal(first.peer_label, "Barry-Bot");
453
+ // start a replacement with the current (soon-to-be-compromised) token
454
+ const b = await s.call("POST", "/oauth/device_authorization", { form: { client_name: "Barry Bot", client_id: "barry" }, ip: "203.0.113.51", headers: { authorization: `Bearer ${first.access_token}` } });
455
+ assert.equal(b.data.replaces_label, "Barry-Bot");
456
+ // the owner rotates the token before approving: the pending request still names Barry-Bot, but its hash no longer matches
457
+ const rotated = (await s.owner("POST", "/owner/peers", { label: "Barry-Bot", rotate: true })).data;
458
+ assert.ok(rotated.token && rotated.token !== first.access_token);
459
+ const ok = await s.owner("POST", `/owner/pairing/${b.data.user_code}/approve`);
460
+ assert.deepEqual([ok.data.label, ok.data.replaced], ["Barry-Bot-2", false], "downgrades to a new label");
461
+ const second = (await s.poll(b.data.device_code)).data;
462
+ assert.equal(second.peer_label, "Barry-Bot-2");
463
+ assert.equal(second.replaced, undefined);
464
+ const rpc = (tok: string) => s.call("POST", "/", { json: { jsonrpc: "2.0", id: 1, method: "GetTask", params: { id: "x" } }, headers: { authorization: `Bearer ${tok}` } });
465
+ assert.equal((await rpc(rotated.token)).status, 200, "the rotated token still works");
466
+ assert.equal((await rpc(first.access_token)).status, 401, "the old token stays dead");
467
+ assert.equal((await rpc(second.access_token)).status, 200, "the pairing got a fresh label");
468
+ const peers = (await s.owner("GET", "/owner/peers")).data.filter((p: any) => !p.revoked_at);
469
+ assert.deepEqual(peers.map((p: any) => p.label).sort(), ["Barry-Bot", "Barry-Bot-2"]);
470
+ });
471
+
472
+ test("owner API: revoking an unknown or revoked label is a 404; rotate needs an existing label; off mode lists no stale requests", async (t) => {
473
+ const s = setup(); t.after(s.restore);
474
+ let r = await s.owner("DELETE", "/owner/peers/No-Such-Label");
475
+ assert.deepEqual([r.status, r.data.revoked], [404, false]);
476
+ assert.match(r.data.error, /no active token with label No-Such-Label/);
477
+ await s.owner("POST", "/owner/peers", { label: "bob" });
478
+ assert.deepEqual((await s.owner("DELETE", "/owner/peers/bob")).data, { revoked: true, label: "bob" });
479
+ r = await s.owner("DELETE", "/owner/peers/bob");
480
+ assert.equal(r.status, 404);
481
+ assert.match(r.data.error, /already revoked/);
482
+ r = await s.owner("POST", "/owner/peers", { label: "typo", rotate: true, mustExist: true });
483
+ assert.equal(r.status, 404);
484
+ assert.equal((await s.owner("POST", "/owner/peers", { label: "bob", rotate: true, mustExist: true })).status, 200, "a revoked label can be rotated back");
485
+ await s.start(undefined, "203.0.113.40");
486
+ assert.equal((await s.owner("GET", "/owner/pairing")).data.pending.length, 1);
487
+ s.env.PAIRING_APPROVAL = "off";
488
+ assert.deepEqual((await s.owner("GET", "/owner/pairing")).data.pending, []);
489
+ });
490
+
491
+ // ------------------------------------------------------------------ one-time password setup link (pair set-password --web)
492
+ async function setupFlow(s: ReturnType<typeof setup>, url: string, pw1: string, pw2 = pw1, o: { ip?: string; origin?: string; csrf?: string } = {}) {
493
+ const path = new URL(url).pathname + new URL(url).search;
494
+ const g = await s.call("GET", path, { ip: o.ip });
495
+ const cookie = (g.headers.get("set-cookie") || "").split(";")[0];
496
+ const csrf = o.csrf ?? /name="csrf" value="([^"]+)"/.exec(g.text)?.[1] ?? cookie.split("=")[1];
497
+ const tok = new URL(url).searchParams.get("t")!;
498
+ const post = await s.call("POST", "/device/setup", { form: { csrf, t: tok, password: pw1, password2: pw2 }, cookie, ip: o.ip, headers: { origin: o.origin ?? BASE } });
499
+ return { get: g, post };
500
+ }
501
+
502
+ test("password setup link: one-time page sets the password (hashed on the Worker), then /device approves with it", async (t) => {
503
+ const s = setup(); t.after(s.restore);
504
+ const link = await s.owner("POST", "/owner/pairing/password-link", {});
505
+ assert.equal(link.status, 200);
506
+ assert.match(link.data.url, /^https:\/\/agent\.example\.com\/device\/setup\?t=[A-Za-z0-9_-]{43}$/);
507
+ assert.equal(link.data.expiresIn, 900, "15 minutes by default");
508
+ const stored = s.DB.db.prepare("SELECT value FROM settings WHERE key = 'password_setup'").get() as any;
509
+ assert.ok(!stored.value.includes(new URL(link.data.url).searchParams.get("t")!), "only the token's hash is stored");
510
+ assert.ok((await s.owner("GET", "/owner/pairing")).data.setupLinkExpiresAt);
511
+
512
+ const { get, post } = await setupFlow(s, link.data.url, PASSWORD);
513
+ assert.equal(get.status, 200);
514
+ assert.match(get.headers.get("content-security-policy")!, /^default-src 'none'; style-src 'nonce-[A-Za-z0-9_-]+'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'$/);
515
+ assert.equal(get.headers.get("cache-control"), "no-store");
516
+ assert.ok(!/<script|src=/i.test(get.text), "no scripts or external assets");
517
+ assert.match(get.text, /name="password" type="password" autocomplete="new-password" required minlength="12"/);
518
+ assert.match(get.text, /name="password2"/);
519
+ assert.match(get.text, /expires in 15 min/);
520
+ assert.equal(post.status, 200, post.text);
521
+ assert.match(post.text, /Approval password set \(\d{4}-\d\d-\d\dT[^)]+\)/);
522
+ assert.match(post.text, /<a href="\/device">approval page<\/a>/);
523
+ assert.ok(!post.text.includes(PASSWORD), "the password is never echoed");
524
+ const rec = JSON.parse((s.DB.db.prepare("SELECT value FROM settings WHERE key = 'approval_password'").get() as any).value);
525
+ assert.deepEqual([rec.alg, rec.iterations, rec.setVia], ["pbkdf2-sha256", 100000, "web"]);
526
+ assert.ok(!JSON.stringify(rec).includes(PASSWORD));
527
+ const list = (await s.owner("GET", "/owner/pairing")).data;
528
+ assert.deepEqual([list.passwordSet, list.passwordSetVia, list.passwordSetAt, list.setupLinkExpiresAt], [true, "web", rec.setAt, null]);
529
+
530
+ // reuse: the link is burned
531
+ const again = await setupFlow(s, link.data.url, "another password 123");
532
+ assert.equal(again.get.status, 404);
533
+ assert.match(again.get.text, /invalid, expired or already used/);
534
+ assert.equal(again.post.status, 404);
535
+ // the new password works on /device
536
+ const a = (await s.start(undefined, "203.0.113.50")).data;
537
+ assert.equal((await s.decidePage(a.user_code, PASSWORD, "approve")).status, 200);
538
+ // a change: the page says a password exists
539
+ const link2 = (await s.owner("POST", "/owner/pairing/password-link", { ttlSeconds: 120 })).data;
540
+ assert.equal(link2.expiresIn, 120);
541
+ const ch = await setupFlow(s, link2.url, "a brand new passphrase");
542
+ assert.match(ch.get.text, /already set \(since /);
543
+ assert.match(ch.post.text, /Approval password changed/);
544
+ });
545
+
546
+ test("password setup link: expiry, mismatch, too short, CSRF, a new link invalidates the old one, burn after 5 bad tries", async (t) => {
547
+ const s = setup(); t.after(s.restore);
548
+ assert.equal((await s.owner("POST", "/owner/pairing/password-link", { ttlSeconds: 5 })).status, 400, "TTL bounds");
549
+ assert.equal((await s.owner("POST", "/owner/pairing/password-link", { ttlSeconds: 7200 })).status, 400);
550
+ // expiry
551
+ const exp = (await s.owner("POST", "/owner/pairing/password-link", {})).data;
552
+ advance(901);
553
+ assert.equal((await setupFlow(s, exp.url, PASSWORD)).get.status, 404);
554
+ // a new link invalidates the old one
555
+ const old = (await s.owner("POST", "/owner/pairing/password-link", {})).data;
556
+ const cur = (await s.owner("POST", "/owner/pairing/password-link", {})).data;
557
+ const o = await setupFlow(s, old.url, PASSWORD);
558
+ assert.deepEqual([o.get.status, o.post.status], [404, 404]);
559
+ // CSRF: another Origin, or a wrong token, is refused and changes nothing
560
+ let r = await setupFlow(s, cur.url, PASSWORD, PASSWORD, { origin: "https://evil.example" });
561
+ assert.equal(r.post.status, 403);
562
+ assert.match(r.post.text, /expired or came from another site/);
563
+ r = await setupFlow(s, cur.url, PASSWORD, PASSWORD, { csrf: "z".repeat(24) });
564
+ assert.equal(r.post.status, 403);
565
+ assert.equal(s.DB.db.prepare("SELECT COUNT(*) AS n FROM settings WHERE key = 'approval_password'").get()!.n, 0);
566
+ // mismatch and too short: explained, nothing stored, password not echoed
567
+ r = await setupFlow(s, cur.url, PASSWORD, PASSWORD + "!");
568
+ assert.equal(r.post.status, 400);
569
+ assert.match(r.post.text, /The two entries differ\. Nothing was changed\./);
570
+ assert.ok(!r.post.text.includes(PASSWORD));
571
+ r = await setupFlow(s, cur.url, "short", "short");
572
+ assert.match(r.post.text, /Too short: use at least 12 characters/);
573
+ for (let i = 0; i < 2; i++) await setupFlow(s, cur.url, "x", "y");
574
+ r = await setupFlow(s, cur.url, "x", "y");
575
+ assert.equal(r.post.status, 403);
576
+ assert.match(r.post.text, /this link is now used up/, "the 5th bad submission burns the link");
577
+ assert.equal((await setupFlow(s, cur.url, PASSWORD)).post.status, 404);
578
+ assert.equal(s.DB.db.prepare("SELECT COUNT(*) AS n FROM settings WHERE key = 'approval_password'").get()!.n, 0);
579
+ // rate limit per IP (page loads and submissions)
580
+ const l = (await s.owner("POST", "/owner/pairing/password-link", {})).data;
581
+ for (let i = 0; i < 20; i++) await s.call("GET", "/device/setup?t=nope", { ip: "192.0.2.200" });
582
+ const limited = await s.call("GET", new URL(l.url).pathname + new URL(l.url).search, { ip: "192.0.2.200" });
583
+ assert.equal(limited.status, 429);
584
+ // off mode: no link
585
+ s.env.PAIRING_APPROVAL = "off";
586
+ assert.equal((await s.owner("POST", "/owner/pairing/password-link", {})).status, 409);
587
+ assert.equal((await s.call("GET", "/device/setup?t=x")).status, 404);
588
+ });
589
+
590
+ test("PBKDF2 iterations: stored per hash, tunable from 50,000 to 100,000; the web setup uses the deployment's count", async (t) => {
591
+ assert.equal(P.pbkdf2Iterations(undefined), 100000);
592
+ assert.equal(P.pbkdf2Iterations("60000"), 60000);
593
+ assert.equal(P.pbkdf2Iterations("1000"), 100000, "out of range: the default");
594
+ const rec = await passwordRecord();
595
+ assert.equal(P.checkPasswordRecord({ ...rec, iterations: 50000 }), "");
596
+ assert.match(P.checkPasswordRecord({ ...rec, iterations: 49999 }), /between 50000 and 100000/);
597
+ const s = setup({ PBKDF2_ITERATIONS: "60000" }); t.after(s.restore);
598
+ assert.equal((await s.owner("GET", "/owner/pairing")).data.pbkdf2Iterations, 60000);
599
+ const link = (await s.owner("POST", "/owner/pairing/password-link", {})).data;
600
+ await setupFlow(s, link.url, PASSWORD);
601
+ const stored = JSON.parse((s.DB.db.prepare("SELECT value FROM settings WHERE key = 'approval_password'").get() as any).value);
602
+ assert.equal(stored.iterations, 60000);
603
+ const a = (await s.start(undefined, "203.0.113.60")).data;
604
+ assert.equal((await s.decidePage(a.user_code, PASSWORD, "approve")).status, 200, "verification uses the stored count");
605
+ });
606
+
607
+ test("GET /: a browser gets an HTML landing page (strict CSP, no scripts); curl/agents still get JSON", async (t) => {
608
+ const s = setup({ AGENT_NAME: "Barry <b>& Co</b>", AGENT_DESCRIPTION: "Answers questions about <bricks>." }); t.after(s.restore);
609
+ const h = await s.call("GET", "/", { headers: { accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } });
610
+ assert.equal(h.status, 200);
611
+ assert.match(h.headers.get("content-type")!, /^text\/html/);
612
+ const csp = h.headers.get("content-security-policy")!;
613
+ assert.match(csp, /default-src 'none'/);
614
+ assert.match(csp, /form-action 'none'/);
615
+ assert.match(csp, /frame-ancestors 'none'/);
616
+ assert.equal(h.headers.get("vary"), "accept");
617
+ assert.equal(h.headers.get("x-frame-options"), "DENY");
618
+ assert.ok(!/<script|<link|<img|<iframe|src=/i.test(h.text), "no scripts or external assets");
619
+ assert.ok(h.text.includes("Barry &lt;b&gt;&amp; Co&lt;/b&gt;") && !h.text.includes("<b>&"), "name escaped");
620
+ assert.ok(h.text.includes("Answers questions about &lt;bricks&gt;."));
621
+ assert.match(h.text, /A2A \(Agent2Agent\)<\/a> endpoint/);
622
+ assert.ok(h.text.includes(`href="/.well-known/agent-card.json"`) && h.text.includes(`${BASE}/.well-known/agent-card.json`));
623
+ assert.ok(h.text.includes(`href="/device"`), "pairing link");
624
+ assert.ok(h.text.includes(`npx a2a-exposed connect ${BASE}`));
625
+ assert.match(h.text, /1\.0, 0\.3/);
626
+ // the style block carries the CSP nonce
627
+ const nonce = /style-src 'nonce-([^']+)'/.exec(csp)![1];
628
+ assert.ok(h.text.includes(`<style nonce="${nonce}">`));
629
+ // machine-readable: no Accept, Accept: application/json, or ?format=json even from a browser
630
+ for (const o of [{}, { headers: { accept: "application/json" } }]) {
631
+ const j = await s.call("GET", "/", o);
632
+ assert.match(j.headers.get("content-type")!, /^application\/json/);
633
+ assert.equal(j.data.name, "Barry <b>& Co</b>");
634
+ assert.equal(j.data.agentCard, `${BASE}/.well-known/agent-card.json`);
635
+ assert.equal(j.data.a2a, `${BASE}/`);
636
+ assert.equal(j.data.pairing, `${BASE}/device`);
637
+ }
638
+ const f = await s.call("GET", "/?format=json", { headers: { accept: "text/html" } });
639
+ assert.equal(f.data.agentCard, `${BASE}/.well-known/agent-card.json`);
640
+ const head = await s.call("HEAD", "/", { headers: { accept: "text/html" } });
641
+ assert.equal(head.status, 200);
642
+ assert.equal(head.text, "");
643
+ });
644
+
645
+ test("GET / with pairing off: no /device link, says to ask the operator", async (t) => {
646
+ const s = setup({ PAIRING_APPROVAL: "off" }); t.after(s.restore);
647
+ const h = await s.call("GET", "/", { headers: { accept: "text/html" } });
648
+ assert.ok(!h.text.includes(`href="/device"`));
649
+ assert.match(h.text, /ask this agent's operator for a bearer token/);
650
+ assert.equal((await s.call("GET", "/")).data.pairing, undefined);
651
+ });