@sheaf-labs/kya 0.3.1 → 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.
package/README.md CHANGED
@@ -5,6 +5,7 @@ Before one agent deals with another, it asks who the other is, who stands behind
5
5
 
6
6
  `kya` puts an agent on the [Know Your Agent](https://know-your-agent.org) in one command,
7
7
  lets it prove who it is, writes its record, and checks other agents before dealing with them.
8
+ It also gives a service a door: a check on every agent that calls it.
8
9
 
9
10
  It needs Node 18 or later and nothing else. Keys are made on your machine and never leave it.
10
11
  The register only ever sees public keys and signatures.
@@ -46,6 +47,64 @@ kya check 9c21e0a7b4d3f815 --proof '<the JSON B returned>' --challenge 3f9a…
46
47
  The answer is one of three: identified with a verified owner, identified with an owner on record, or
47
48
  unknown. What A does with each answer is A's own policy.
48
49
 
50
+ ## The Door
51
+
52
+ A service checks each agent that calls it. The agent adds one header to its request. The service lets it
53
+ in, refuses it, or holds it for a person.
54
+
55
+ **The agent's side.** One line:
56
+
57
+ ```js
58
+ import { proofHeader } from "@sheaf-labs/kya";
59
+ import { readFileSync } from "node:fs";
60
+
61
+ const key = readFileSync(process.env.HOME + "/.config/kya/agents/invoice-payer.key");
62
+ const url = "https://tools.acme.example/pay";
63
+ await fetch(url, { method: "POST", headers: { "KYA-Proof": proofHeader(key, url) }, body });
64
+ ```
65
+
66
+ The header is a proof signed with the agent's key. It names the exact address being called and is good
67
+ for 60 seconds. It works once. From a shell: `kya header invoice-payer https://tools.acme.example/pay`.
68
+
69
+ **The service's side.** Works with Node's http server, Express and Connect:
70
+
71
+ ```js
72
+ import { door } from "@sheaf-labs/kya";
73
+
74
+ const guard = door({
75
+ origin: "https://tools.acme.example", // this service's own public address
76
+ require: "verified", // "identified" (the default), "verified" or "proof"
77
+ approved: new Set(), // IDs a person has approved
78
+ onHold: held => notifyAPerson(held) // without this, an agent that falls short is refused
79
+ });
80
+ app.use(guard.middleware()); // a request that gets through carries req.kya.id
81
+ ```
82
+
83
+ | `require` | Who comes in |
84
+ |---|---|
85
+ | `identified` | An agent on the register and in good standing. |
86
+ | `verified` | The same, and its owner has proved a domain or been reviewed. |
87
+ | `proof` | Any agent with a valid proof. The register is not asked. |
88
+
89
+ An agent with a valid proof that falls short of `require` is held when `onHold` is set: the request gets
90
+ status 403 and your function gets the agent's ID, its owner and the reason. To let it in next time, add
91
+ its ID to `approved`. A revoked, retired or expired agent is refused even when approved. With no header,
92
+ a wrong address, an old proof or a used one, the request gets 401.
93
+
94
+ Three things to know:
95
+
96
+ - **Set `origin` yourself.** The door never reads the host from the request. That is what stops a proof
97
+ made for another service from working at yours.
98
+ - **The signature is checked on your machine.** The register is asked only who owns the agent and whether
99
+ it is in good standing, at most once a minute for each agent. If the register cannot be reached, the
100
+ door refuses everyone except approved agents.
101
+ - **Each proof works once.** The door remembers the ID and random value of each proof for 70 seconds, in memory.
102
+ If your service runs as several processes, pass `seen` with `has(key)` and `add(key, seconds)` backed
103
+ by a store they share.
104
+
105
+ Without the middleware: `await guard.check({ path, headers })` answers
106
+ `{ decision: "allow" | "hold" | "refuse", reason, id, agent, owner }`.
107
+
49
108
  ## The record
50
109
 
51
110
  ```sh
package/bin/kya.mjs CHANGED
@@ -9,6 +9,7 @@ import { generateKeyPairSync, createPrivateKey, sign, createHash, randomBytes }
9
9
  import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, chmodSync } from "node:fs";
10
10
  import { join as pathJoin } from "node:path";
11
11
  import { homedir } from "node:os";
12
+ import { proofHeader, requestProof, canonicalAudience } from "../lib/door.mjs";
12
13
 
13
14
  const REGISTER = (process.env.KYA_REGISTER || "https://know-your-agent.org").replace(/\/$/, "");
14
15
  const HOME = process.env.KYA_HOME || pathJoin(process.env.XDG_CONFIG_HOME || pathJoin(homedir(), ".config"), "kya");
@@ -70,8 +71,14 @@ const HELP = `kya: Know Your Agent. The Know Your Agent from the command line.
70
71
  Your owner ID and the agents you have entered.
71
72
  kya prove <agent> <challenge> [--audience <did>]
72
73
  Answer another agent's challenge: a proof signed with this agent's key, as JSON.
73
- kya check <id or fingerprint> [--proof '<json>' --challenge <c>]
74
+ kya check <id or fingerprint> [--proof '<json>' --challenge <c>] [--audience <who>]
74
75
  Look another agent up. With a proof and the challenge you sent, also checks the proof is theirs.
76
+ With --audience, a proof made for anyone else is refused.
77
+ kya header <agent> <url> [--json]
78
+ The KYA-Proof header for one request to <url>: the agent's signed proof, good for 60 seconds and
79
+ only at that address. Send it as the request header "KYA-Proof".
80
+ kya check --header <value> --audience <url>
81
+ Check a KYA-Proof header a request carried. The audience is your own address for that request.
75
82
  kya challenge
76
83
  A fresh random challenge to send to another agent.
77
84
  kya receipt <agent> --kind <kind> --decision <decision> [--action "<text>"] [--run <id>]
@@ -150,14 +157,25 @@ async function prove() {
150
157
  out(signed(a.key, proof));
151
158
  }
152
159
 
160
+ async function header() {
161
+ const a = agent(safeName(rest[0]));
162
+ const url = rest[1];
163
+ if (!url || !canonicalAudience(url)) die("kya header <agent> <url>: the full http or https address the request goes to.");
164
+ out(flags.json ? requestProof(a.key, url) : proofHeader(a.key, url));
165
+ }
166
+
153
167
  async function check() {
154
168
  const id = rest[0];
155
- if (!id) die("kya check <id or fingerprint>");
156
169
  let r;
157
- if (flags.proof) {
170
+ if (flags.header) {
171
+ const audience = canonicalAudience(String(flags.audience || ""));
172
+ if (!audience) die("--audience is your own address for the request, as a full http or https URL.");
173
+ r = await post("/api/v1/register/check", { header: String(flags.header), audience });
174
+ } else if (!id) die("kya check <id or fingerprint>");
175
+ else if (flags.proof) {
158
176
  let proof; try { proof = JSON.parse(flags.proof); } catch { die("--proof must be the proof JSON exactly as the other agent gave it."); }
159
177
  if (!flags.challenge) die("--challenge is the value you sent; the register checks the proof is over it.");
160
- r = await post("/api/v1/register/check", { proof, challenge: flags.challenge });
178
+ r = await post("/api/v1/register/check", { proof, challenge: flags.challenge, audience: flags.audience ? String(flags.audience) : undefined });
161
179
  } else {
162
180
  r = await post("/api/v1/register/check", { id });
163
181
  }
@@ -222,7 +240,7 @@ async function record() {
222
240
  if (flags.json) out(j);
223
241
  }
224
242
 
225
- const run = { init, join, whoami, prove, check, challenge, receipt, record, verify, "verify-check": verifyCheck, retire: () => standing("retired"), revoke: () => standing("revoked") };
243
+ const run = { init, join, whoami, prove, header, check, challenge, receipt, record, verify, "verify-check": verifyCheck, retire: () => standing("retired"), revoke: () => standing("revoked") };
226
244
  if (!cmd || cmd === "help" || flags.help) { out(HELP); process.exit(0); }
227
245
  if (!run[cmd]) die(`Unknown command "${cmd}".\n\n${HELP}`);
228
246
  run[cmd]().catch(e => die(e && e.message ? e.message : String(e)));
package/lib/door.mjs ADDED
@@ -0,0 +1,175 @@
1
+ // The Door: an agent shows who it is on an ordinary web request, and a service checks it before letting it in.
2
+ //
3
+ // The agent adds one header, KYA-Proof, to its request. The header is a proof signed with the agent's key.
4
+ // It names the exact address being called and is good for 60 seconds, so it cannot be used anywhere else
5
+ // or kept for later. The service checks the signature here, with no network call, then asks the Know Your
6
+ // Agent register who owns the agent and whether it is in good standing.
7
+ //
8
+ // Needs Node 18 or later and nothing else.
9
+ import { createPrivateKey, createPublicKey, sign, verify, randomBytes } from "node:crypto";
10
+
11
+ export const HEADER = "KYA-Proof";
12
+ export const PROOF_TYPE = "request-proof";
13
+ export const MAX_AGE_SECONDS = 60;
14
+ export const AHEAD_SECONDS = 10;
15
+ const DEFAULT_REGISTER = "https://know-your-agent.org";
16
+
17
+ // ── the format ──────────────────────────────────────────────────────────────────────────────
18
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
19
+ const b58 = bytes => { let n = BigInt("0x" + (Buffer.from(bytes).toString("hex") || "0")), s = ""; while (n > 0n) { s = B58[Number(n % 58n)] + s; n /= 58n; } for (const b of bytes) { if (b !== 0) break; s = "1" + s; } return s; };
20
+ const unb58 = s => { let n = 0n; for (const c of s) { const i = B58.indexOf(c); if (i < 0) throw new Error("not base58"); n = n * 58n + BigInt(i); } let h = n.toString(16); if (h.length % 2) h = "0" + h; let z = 0; for (const c of s) { if (c !== "1") break; z++; } return Buffer.concat([Buffer.alloc(z), Buffer.from(h, "hex")]); };
21
+ const canonical = v => Array.isArray(v) ? "[" + v.map(canonical).join(",") + "]"
22
+ : v && typeof v === "object" ? "{" + Object.keys(v).filter(k => v[k] !== undefined).sort().map(k => JSON.stringify(k) + ":" + canonical(v[k])).join(",") + "}"
23
+ : JSON.stringify(v);
24
+ const SPKI = Buffer.from("302a300506032b6570032100", "hex");
25
+ const pubFromDid = did => {
26
+ if (typeof did !== "string" || !did.startsWith("did:key:z")) throw new Error("not a did:key");
27
+ const raw = unb58(did.slice("did:key:z".length));
28
+ if (raw.length !== 34 || raw[0] !== 0xed || raw[1] !== 0x01) throw new Error("not an Ed25519 did:key");
29
+ return createPublicKey({ key: Buffer.concat([SPKI, raw.subarray(2)]), format: "der", type: "spki" });
30
+ };
31
+ const didOfKey = priv => "did:key:z" + b58(Buffer.concat([Buffer.from([0xed, 0x01]), Buffer.from(createPrivateKey(priv).export({ format: "jwk" }).x, "base64url")]));
32
+
33
+ /** The one written form of an address a proof is bound to: scheme, host and path. The scheme and host are
34
+ * lower case, a default port is dropped, an empty path is "/", and the query and fragment are left out.
35
+ * The path is the one a web client sends: "." and ".." segments are resolved and characters that cannot
36
+ * travel in a path are percent-encoded, exactly as fetch does. Returns null when the address is not http
37
+ * or https. */
38
+ export function canonicalAudience(url) {
39
+ let u; try { u = new URL(String(url).trim()); } catch { return null; }
40
+ if ((u.protocol !== "http:" && u.protocol !== "https:") || !u.host || u.username || u.password) return null;
41
+ return u.protocol + "//" + u.host + u.pathname;
42
+ }
43
+
44
+ // ── the agent's side ────────────────────────────────────────────────────────────────────────
45
+ /** A signed proof for one request to `url`. `privateKey` is the agent's key (PEM, as kya keeps it). */
46
+ export function requestProof(privateKey, url, { now = Date.now() } = {}) {
47
+ const audience = canonicalAudience(url);
48
+ if (!audience) throw new Error("The address must be a full http or https URL.");
49
+ const body = { v: 1, type: PROOF_TYPE, id: didOfKey(privateKey), audience, nonce: randomBytes(16).toString("hex"), at: new Date(now).toISOString().replace(/\.\d{3}Z$/, "Z") };
50
+ return { ...body, signature: sign(null, Buffer.from(canonical(body), "utf8"), createPrivateKey(privateKey)).toString("base64") };
51
+ }
52
+ /** The value of the KYA-Proof header for one request to `url`: fetch(url, { headers: { "KYA-Proof": proofHeader(key, url) } }) */
53
+ export function proofHeader(privateKey, url, opts) {
54
+ return Buffer.from(JSON.stringify(requestProof(privateKey, url, opts)), "utf8").toString("base64url");
55
+ }
56
+
57
+ // ── the service's side ──────────────────────────────────────────────────────────────────────
58
+ export function decodeHeader(value) {
59
+ try { const p = JSON.parse(Buffer.from(String(value).trim(), "base64url").toString("utf8")); return p && typeof p === "object" && !Array.isArray(p) ? p : null; } catch { return null; }
60
+ }
61
+
62
+ /** Check a request proof with no network call. `audience` is the service's own address for this request,
63
+ * in the canonical form. Returns { ok: true, id } or { ok: false, reason }. */
64
+ export function checkRequestProof(proof, audience, { now = Date.now(), maxAgeSeconds = MAX_AGE_SECONDS, aheadSeconds = AHEAD_SECONDS } = {}) {
65
+ const no = reason => ({ ok: false, reason });
66
+ if (!proof || typeof proof !== "object") return no("there is no proof");
67
+ if (proof.type !== PROOF_TYPE) return no("this is not a request proof");
68
+ for (const [k, why] of [["id", "the proof names no id"], ["audience", "the proof does not say who it is for"], ["nonce", "the proof has no random value"], ["at", "the proof has no time"], ["signature", "the proof has no signature"]])
69
+ if (typeof proof[k] !== "string" || !proof[k]) return no(why);
70
+ let pub; try { pub = pubFromDid(proof.id); } catch { return no("the id is not a did:key this checker understands"); }
71
+ if (proof.audience !== audience) return no("the proof was made for another address");
72
+ const at = Date.parse(proof.at);
73
+ if (Number.isNaN(at)) return no("the time is not readable");
74
+ if (now - at > maxAgeSeconds * 1000) return no("the proof is stale");
75
+ if (at - now > aheadSeconds * 1000) return no("the proof is dated in the future");
76
+ const body = { v: 1, type: PROOF_TYPE, id: proof.id, audience: proof.audience, nonce: proof.nonce, at: proof.at };
77
+ let good = false; try { good = verify(null, Buffer.from(canonical(body), "utf8"), pub, Buffer.from(proof.signature, "base64")); } catch { good = false; }
78
+ return good ? { ok: true, id: proof.id } : no("the signature does not match the id");
79
+ }
80
+
81
+ /** A door for one service.
82
+ *
83
+ * origin The service's own public address, for example "https://tools.acme.example". Set it yourself.
84
+ * It is never read from the request, so a proof made for another service is refused here.
85
+ * require Who may come in:
86
+ * "identified" on the register and in good standing (the default)
87
+ * "verified" the same, and the owner has proved a domain or been reviewed
88
+ * "proof" anyone with a valid proof; the register is not asked
89
+ * approved Agent IDs a person has approved: an array, a Set, or a function (id) => true/false (may be
90
+ * async). An approved agent comes in whatever `require` says, unless the register says it
91
+ * is revoked, retired or expired.
92
+ * onHold If set, an agent with a valid proof that does not meet `require` is held instead of refused,
93
+ * and this function is called with the details so a person can decide. To let it in next
94
+ * time, add its ID to `approved`.
95
+ * register The register to ask. The default is https://know-your-agent.org.
96
+ *
97
+ * door.check({ path, headers }) answers { decision: "allow" | "hold" | "refuse", reason, id, agent, owner }.
98
+ * door.middleware() is the same check for Node's http server, Express and Connect.
99
+ *
100
+ * Each proof works once: the door remembers the id and nonce of each proof it has let through the checks,
101
+ * for 70 seconds. That memory is per process. Behind several processes, pass `seen` (has/add, may be
102
+ * async) backed by a shared store. */
103
+ export function door({ origin, require: req = "identified", approved, onHold, register = DEFAULT_REGISTER, lookupSeconds = 60, seen, fetch: fetchFn = globalThis.fetch, now = () => Date.now() } = {}) {
104
+ const base = canonicalAudience(origin);
105
+ if (!base || !/^https?:\/\/[^/]+\/$/.test(base)) throw new Error('door({ origin }): set origin to this service\'s own address, for example "https://tools.acme.example".');
106
+ if (!["identified", "verified", "proof"].includes(req)) throw new Error('door({ require }): "identified", "verified" or "proof".');
107
+ const root = base.slice(0, -1), reg = String(register).replace(/\/$/, "");
108
+ const used = new Map(), looked = new Map();
109
+ const sweep = t => { for (const [k, exp] of used) if (exp <= t) used.delete(k); for (const [k, v] of looked) if (v.exp <= t) looked.delete(k); };
110
+ const isApproved = async id => !approved ? false : typeof approved === "function" ? !!(await approved(id)) : approved instanceof Set ? approved.has(id) : Array.isArray(approved) && approved.includes(id);
111
+ const lookup = async id => {
112
+ const t = now(), hit = looked.get(id);
113
+ if (hit && hit.exp > t) return hit.value;
114
+ let value;
115
+ try {
116
+ const r = await fetchFn(reg + "/api/v1/register/lookup?id=" + encodeURIComponent(id));
117
+ const j = await r.json();
118
+ value = r.status === 404 || j.status === "unknown" ? { known: false } : (j && j.agent) ? { known: true, agent: j.agent, owner: j.owner || null } : { down: true };
119
+ } catch { value = { down: true }; }
120
+ if (!value.down) looked.set(id, { exp: t + lookupSeconds * 1000, value });
121
+ return value;
122
+ };
123
+
124
+ async function check({ path, url, headers } = {}) {
125
+ const t = now();
126
+ const p = String(path ?? url ?? "/").replace(/[?#].*$/, "") || "/";
127
+ const audience = root + (p.startsWith("/") ? p : "/" + p);
128
+ const get = name => { if (!headers) return undefined; if (typeof headers.get === "function") return headers.get(name) ?? undefined; const k = Object.keys(headers).find(h => h.toLowerCase() === name.toLowerCase()); const v = k ? headers[k] : undefined; return Array.isArray(v) ? v[0] : v; };
129
+ const raw = get(HEADER);
130
+ if (!raw) return { decision: "refuse", reason: "the request carries no KYA-Proof header", audience };
131
+ const proof = decodeHeader(raw);
132
+ if (!proof) return { decision: "refuse", reason: "the KYA-Proof header could not be read", audience };
133
+ const c = checkRequestProof(proof, audience, { now: t });
134
+ if (!c.ok) return { decision: "refuse", reason: c.reason, id: typeof proof.id === "string" ? proof.id : undefined, audience };
135
+ sweep(t);
136
+ // Remembered by the signed id and nonce. The signature text is no use for this: base64 can be written
137
+ // more than one way, so the same proof could be sent again looking different.
138
+ const id = c.id, key = id + "\n" + proof.nonce;
139
+ if (seen ? await seen.has(key) : used.has(key)) return { decision: "refuse", reason: "this proof was already used", id, audience };
140
+ if (seen) await seen.add(key, MAX_AGE_SECONDS + AHEAD_SECONDS); else used.set(key, t + (MAX_AGE_SECONDS + AHEAD_SECONDS) * 1000);
141
+
142
+ const ok = await isApproved(id);
143
+ if (req === "proof" && !ok) return { decision: "allow", reason: "its proof is valid", id, audience };
144
+ const l = await lookup(id);
145
+ const out = (decision, reason) => ({ decision, reason, id, audience, agent: l.agent, owner: l.owner });
146
+ const standing = l.known ? l.agent.standing : undefined;
147
+ if (l.known && standing !== "good") return out("refuse", `the register says this agent is ${standing || "not in good standing"}`);
148
+ if (ok) return out("allow", l.down ? "a person approved it; the register could not be reached" : "a person approved it");
149
+ if (req === "proof") return out("allow", "its proof is valid");
150
+ if (l.down) return out("refuse", "the register could not be reached, so the agent could not be looked up");
151
+ let why = null;
152
+ if (!l.known) why = "it is not on the register";
153
+ else if (req === "verified" && !(l.owner && l.owner.verification === "verified")) why = "its owner is not verified";
154
+ if (!why) return out("allow", req === "verified" ? "it is in good standing with a verified owner" : "it is on the register and in good standing");
155
+ if (!onHold) return out("refuse", why);
156
+ const held = out("hold", why + "; held for a person to decide");
157
+ try { await onHold(held); } catch { /* the hold stands whatever the callback does */ }
158
+ return held;
159
+ }
160
+
161
+ function middleware() {
162
+ return async (request, response, next) => {
163
+ let r;
164
+ try { r = await check({ path: request.originalUrl || request.url, headers: request.headers }); }
165
+ catch { r = { decision: "refuse", reason: "the check failed" }; }
166
+ request.kya = r;
167
+ if (r.decision === "allow") return typeof next === "function" ? next() : undefined;
168
+ const status = r.decision === "hold" ? 403 : 401;
169
+ const body = JSON.stringify({ ok: false, decision: r.decision, reason: r.reason, expected: { header: HEADER, audience: r.audience }, how: reg + "/format.html" });
170
+ response.writeHead(status, { "content-type": "application/json", "www-authenticate": HEADER });
171
+ response.end(body);
172
+ };
173
+ }
174
+ return { check, middleware, origin: root };
175
+ }
package/package.json CHANGED
@@ -1,13 +1,39 @@
1
1
  {
2
2
  "name": "@sheaf-labs/kya",
3
- "version": "0.3.1",
4
- "description": "Know Your Agent. Put an AI agent on the Know Your Agent register, prove who it is, write its record, and check other agents before dealing with them.",
3
+ "version": "0.4.0",
4
+ "description": "Know Your Agent. Put an AI agent on the Know Your Agent register, prove who it is, write its record, check other agents before dealing with them, and check agents at the door of your own service.",
5
5
  "type": "module",
6
- "bin": { "kya": "bin/kya.mjs" },
7
- "files": ["bin", "README.md", "LICENSE"],
8
- "engines": { "node": ">=18" },
9
- "keywords": ["kya", "know-your-agent", "ai-agents", "agent-identity", "did", "ed25519", "traceable-agents", "register"],
6
+ "bin": {
7
+ "kya": "bin/kya.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "keywords": [
19
+ "kya",
20
+ "know-your-agent",
21
+ "ai-agents",
22
+ "agent-identity",
23
+ "did",
24
+ "ed25519",
25
+ "traceable-agents",
26
+ "register"
27
+ ],
10
28
  "homepage": "https://know-your-agent.org",
11
- "repository": { "type": "git", "url": "https://github.com/jackmitchelwidman/know-your-agent" },
12
- "license": "Apache-2.0"
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/jackmitchelwidman/know-your-agent"
32
+ },
33
+ "license": "Apache-2.0",
34
+ "exports": {
35
+ ".": "./lib/door.mjs",
36
+ "./door": "./lib/door.mjs"
37
+ },
38
+ "main": "lib/door.mjs"
13
39
  }