@agent-custody/receipts 0.16.11 → 0.16.13
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 +23 -5
- package/dist/admission.d.ts +62 -0
- package/dist/admission.js +101 -0
- package/dist/check.js +42 -3
- package/dist/cli.js +179 -7
- package/dist/config.d.ts +6 -1
- package/dist/config.js +21 -2
- package/dist/door-app.js +1 -1
- package/dist/door-core.d.ts +81 -3
- package/dist/door-core.js +113 -13
- package/dist/door-error-rates.d.ts +102 -0
- package/dist/door-error-rates.js +178 -0
- package/dist/door-form.d.ts +7 -2
- package/dist/door-form.js +52 -4
- package/dist/door-measure.d.ts +153 -0
- package/dist/door-measure.js +325 -0
- package/dist/door-signals.d.ts +414 -0
- package/dist/door-signals.js +555 -0
- package/dist/door-test-set.d.ts +43 -0
- package/dist/door-test-set.js +117 -0
- package/dist/door-worker.d.ts +20 -1
- package/dist/door-worker.js +30 -2
- package/dist/door.js +18 -2
- package/dist/erc8004-link.d.ts +24 -0
- package/dist/erc8004-link.js +11 -0
- package/dist/erc8004.d.ts +26 -0
- package/dist/erc8004.js +208 -0
- package/dist/index.d.ts +17 -3
- package/dist/index.js +9 -2
- package/dist/lock.d.ts +5 -0
- package/dist/lock.js +1 -1
- package/dist/log-store.d.ts +3 -1
- package/dist/log-store.js +2 -2
- package/dist/passport.d.ts +53 -0
- package/dist/passport.js +87 -0
- package/dist/portal.d.ts +14 -0
- package/dist/portal.js +102 -0
- package/dist/registry.d.ts +145 -0
- package/dist/registry.js +294 -0
- package/dist/web-bot-auth.d.ts +9 -3
- package/dist/web-bot-auth.js +31 -4
- package/docs/admission-lists.md +89 -0
- package/docs/agent-registry.md +173 -0
- package/docs/door-error-rates.md +490 -0
- package/docs/door-languages.md +3 -1
- package/docs/door-middleware.md +6 -1
- package/docs/door-quickstart.md +2 -2
- package/docs/door-signals.md +112 -2
- package/docs/door-worker.md +14 -1
- package/docs/door.md +37 -6
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +7 -0
- package/docs/usage.md +1 -1
- package/package.json +2 -1
package/dist/registry.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// The agent registry: an organisation registers its agents on the portal, each with its own Ed25519 key named as a
|
|
2
|
+
// did:key, and the registry signs a passport for each: a short-lived statement of who the agent is (its key, its
|
|
3
|
+
// owner, a contact, its capabilities). A door that trusts the registry's key admits an agent that presents a passport
|
|
4
|
+
// and signs its request with the key the passport names. The door needs nothing per agent and asks the registry nothing
|
|
5
|
+
// at request time: the registry's key document is all it holds.
|
|
6
|
+
//
|
|
7
|
+
// A passport is public. It proves nothing without a signature by the agent's own key on the same request, so it is
|
|
8
|
+
// served to anyone who asks, like a certificate. It lives for a day by default: revoking an agent stops new passports,
|
|
9
|
+
// and the last one issued stops working when it expires.
|
|
10
|
+
import { randomBytes, sign as edSign, verify as edVerify } from "node:crypto";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.js";
|
|
13
|
+
import { transaction } from "./log-store.js";
|
|
14
|
+
import { AGENT_ID, CAPABILITY, DEFAULT_PASSPORT_SECONDS, DID_KEY, PASSPORT_HEADER, PASSPORT_TYPE, PassportSchema, text } from "./passport.js";
|
|
15
|
+
import { Erc8004LinkSchema } from "./erc8004-link.js";
|
|
16
|
+
export * from "./passport.js";
|
|
17
|
+
const didKeyOfKey = (k) => didKeyOf(k.publicKey);
|
|
18
|
+
/** the furthest ahead an agent's registration may expire */
|
|
19
|
+
export const MAX_REGISTRATION_DAYS = 366;
|
|
20
|
+
export const MAX_AGENTS_PER_OWNER = 100;
|
|
21
|
+
/**
|
|
22
|
+
* What an agent's key signs to show that whoever registers it holds it: the registry, the owner, and the key. Without
|
|
23
|
+
* it, a tenant could register a did:key it saw in a grant or a signature, and choose that agent's capabilities.
|
|
24
|
+
*/
|
|
25
|
+
export function registrationMessage(registryUrl, owner, didKey) {
|
|
26
|
+
return Buffer.from(`agent-custody registry registration v1\n${registryUrl}\n${owner}\n${didKey}`, "utf8");
|
|
27
|
+
}
|
|
28
|
+
/** The proof a registration carries: the agent's key's Ed25519 signature over `registrationMessage`, base64url. */
|
|
29
|
+
export function registrationProof(agentKey, registryUrl, owner) {
|
|
30
|
+
const agent = didKeyOfKey(agentKey);
|
|
31
|
+
return { agent, proof: edSign(null, registrationMessage(registryUrl, owner, agent), agentKey.privateKey).toString("base64url") };
|
|
32
|
+
}
|
|
33
|
+
/** The ERC-8004 link a passport may carry: one whose last check succeeded within `recheckSeconds`. */
|
|
34
|
+
export function freshErc8004(e, recheckSeconds, now = Date.now()) {
|
|
35
|
+
const l = e.erc8004;
|
|
36
|
+
return l && !l.error && now - Date.parse(l.checkedAt) <= recheckSeconds * 1000 ? l : null;
|
|
37
|
+
}
|
|
38
|
+
export const agentStatus = (e, now = Date.now()) => (e.revokedAt ? "revoked" : Date.parse(e.expiresAt) <= now ? "expired" : "active");
|
|
39
|
+
/** What the registry publishes about an agent: the entry, its status, and its key as a JWK. */
|
|
40
|
+
export function publicEntry(e, now = Date.now()) {
|
|
41
|
+
const x = publicKeyFromDidKey(e.agent).publicKey.export({ format: "jwk" }).x;
|
|
42
|
+
return {
|
|
43
|
+
id: e.id,
|
|
44
|
+
name: e.name,
|
|
45
|
+
owner: e.owner,
|
|
46
|
+
contact: e.contact,
|
|
47
|
+
capabilities: e.capabilities,
|
|
48
|
+
agent: e.agent,
|
|
49
|
+
keys: [{ kty: "OKP", crv: "Ed25519", x, kid: e.agent, exp: Math.floor(Date.parse(e.expiresAt) / 1000) }],
|
|
50
|
+
createdAt: e.createdAt,
|
|
51
|
+
expiresAt: e.expiresAt,
|
|
52
|
+
status: agentStatus(e, now),
|
|
53
|
+
erc8004: e.erc8004 ?? null,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** A request to register or change an agent, checked; throws a message fit for the caller. */
|
|
57
|
+
export const AgentInputSchema = z.object({
|
|
58
|
+
name: text(100),
|
|
59
|
+
contact: text(200),
|
|
60
|
+
capabilities: z.array(z.string().regex(CAPABILITY, { message: "a capability is lowercase letters, digits, and . _ : -, at most 64 characters" })).max(32).optional(),
|
|
61
|
+
agent: z.string().regex(DID_KEY, { message: "the agent's key is an Ed25519 did:key (did:key:z6Mk...)" }),
|
|
62
|
+
/** the agent key's signature over `registrationMessage`, base64url: needed to register a key, and to change to a new one */
|
|
63
|
+
proof: z.string().regex(/^[A-Za-z0-9_-]{86}$/, { message: "proof is the agent key's Ed25519 signature over the registration message, base64url" }).optional(),
|
|
64
|
+
expiresAt: z.iso.datetime({ offset: true }),
|
|
65
|
+
/** link an ERC-8004 identity (checked against the chain before it is stored), or null to unlink */
|
|
66
|
+
erc8004: Erc8004LinkSchema.nullable().optional(),
|
|
67
|
+
});
|
|
68
|
+
export class RegistryInputError extends Error {
|
|
69
|
+
}
|
|
70
|
+
async function checkedLink(checker, link, didKey) {
|
|
71
|
+
if (!checker)
|
|
72
|
+
throw new RegistryInputError("erc8004: this registry reads no ERC-8004 registry");
|
|
73
|
+
const r = await checker(link, didKey);
|
|
74
|
+
if (!r.ok)
|
|
75
|
+
throw new RegistryInputError(`erc8004: ${r.error}`);
|
|
76
|
+
return r.link;
|
|
77
|
+
}
|
|
78
|
+
function checkProof(registryUrl, owner, didKey, proof) {
|
|
79
|
+
if (!proof)
|
|
80
|
+
throw new RegistryInputError("proof: a key is registered with its proof, the agent key's signature over the registration message (registrationProof, or agent-custody registry proof)");
|
|
81
|
+
if (!edVerify(null, registrationMessage(registryUrl, owner, didKey), publicKeyFromDidKey(didKey).publicKey, Buffer.from(proof, "base64url")))
|
|
82
|
+
throw new RegistryInputError(`proof: the signature does not verify with ${didKey} over the registration message for this registry and owner`);
|
|
83
|
+
}
|
|
84
|
+
/** Postgres refused a row that breaks the one-live-agent-per-key index. */
|
|
85
|
+
const keyTaken = (e) => !!e && typeof e === "object" && e.code === "23505";
|
|
86
|
+
const TAKEN = "agent: this key is already registered to an agent; each agent has its own key";
|
|
87
|
+
function checkInput(raw, partial, now) {
|
|
88
|
+
const schema = partial ? AgentInputSchema.partial() : AgentInputSchema;
|
|
89
|
+
const r = schema.safeParse(raw);
|
|
90
|
+
if (!r.success)
|
|
91
|
+
throw new RegistryInputError(r.error.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
|
|
92
|
+
const v = r.data;
|
|
93
|
+
if (v.agent) {
|
|
94
|
+
try {
|
|
95
|
+
publicKeyFromDidKey(v.agent);
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
throw new RegistryInputError(`agent: ${e instanceof Error ? e.message : String(e)}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (v.expiresAt) {
|
|
102
|
+
const t = Date.parse(v.expiresAt);
|
|
103
|
+
if (t <= now)
|
|
104
|
+
throw new RegistryInputError("expiresAt: the registration must expire in the future");
|
|
105
|
+
if (t > now + MAX_REGISTRATION_DAYS * 86_400_000)
|
|
106
|
+
throw new RegistryInputError(`expiresAt: a registration lasts at most ${MAX_REGISTRATION_DAYS} days; renew it before then`);
|
|
107
|
+
}
|
|
108
|
+
if (v.capabilities)
|
|
109
|
+
v.capabilities = [...new Set(v.capabilities)].sort();
|
|
110
|
+
return v;
|
|
111
|
+
}
|
|
112
|
+
/** The registry's table, beside the portal's own. */
|
|
113
|
+
export class RegistryStore {
|
|
114
|
+
client;
|
|
115
|
+
t;
|
|
116
|
+
ready = null;
|
|
117
|
+
registryUrl;
|
|
118
|
+
/** `registryUrl` is what a registration's proof names */
|
|
119
|
+
constructor(client, registryUrl, prefix = "portal_") {
|
|
120
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(prefix))
|
|
121
|
+
throw new Error(`invalid table prefix ${prefix}`);
|
|
122
|
+
this.client = client;
|
|
123
|
+
this.registryUrl = registryUrl;
|
|
124
|
+
this.t = `${prefix}agents`;
|
|
125
|
+
}
|
|
126
|
+
init() {
|
|
127
|
+
this.ready ??= (async () => {
|
|
128
|
+
await this.client.query(`CREATE TABLE IF NOT EXISTS ${this.t} (id TEXT PRIMARY KEY, owner TEXT NOT NULL, name TEXT NOT NULL, contact TEXT NOT NULL, capabilities TEXT[] NOT NULL, agent TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), expires_at TIMESTAMPTZ NOT NULL, revoked_at TIMESTAMPTZ)`);
|
|
129
|
+
await this.client.query(`CREATE INDEX IF NOT EXISTS ${this.t}_owner ON ${this.t} (owner)`);
|
|
130
|
+
// one live agent per key, held by the database so that two registrations at once cannot both pass
|
|
131
|
+
await this.client.query(`CREATE UNIQUE INDEX IF NOT EXISTS ${this.t}_live_key ON ${this.t} (agent) WHERE revoked_at IS NULL`);
|
|
132
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS erc8004 TEXT`);
|
|
133
|
+
await this.client.query(`CREATE INDEX IF NOT EXISTS ${this.t}_capabilities ON ${this.t} USING GIN (capabilities)`);
|
|
134
|
+
})();
|
|
135
|
+
return this.ready;
|
|
136
|
+
}
|
|
137
|
+
static row(r) {
|
|
138
|
+
const iso = (v) => (v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString());
|
|
139
|
+
return { id: String(r.id), owner: String(r.owner), name: String(r.name), contact: String(r.contact), capabilities: r.capabilities ?? [], agent: String(r.agent), createdAt: iso(r.created_at), expiresAt: iso(r.expires_at), revokedAt: r.revoked_at ? iso(r.revoked_at) : null, erc8004: r.erc8004 ? JSON.parse(String(r.erc8004)) : null };
|
|
140
|
+
}
|
|
141
|
+
async register(owner, raw, now = Date.now(), erc8004) {
|
|
142
|
+
await this.init();
|
|
143
|
+
const v = checkInput(raw, false, now);
|
|
144
|
+
checkProof(this.registryUrl, owner, v.agent, v.proof);
|
|
145
|
+
const link = v.erc8004 ? await checkedLink(erc8004, v.erc8004, v.agent) : null;
|
|
146
|
+
const capabilities = v.capabilities ?? [];
|
|
147
|
+
const id = `agt_${randomBytes(8).toString("hex")}`;
|
|
148
|
+
try {
|
|
149
|
+
// the owner's lock makes the count and the insert one step, so registrations at once cannot pass the cap together
|
|
150
|
+
return await transaction(this.client, async (q) => {
|
|
151
|
+
await q("SELECT pg_advisory_xact_lock(hashtext($1))", [`${this.t}:${owner}`]);
|
|
152
|
+
const { rows: count } = await q(`SELECT count(*)::int AS n FROM ${this.t} WHERE owner = $1 AND revoked_at IS NULL`, [owner]);
|
|
153
|
+
if (Number(count[0].n) >= MAX_AGENTS_PER_OWNER)
|
|
154
|
+
throw new RegistryInputError(`an owner registers at most ${MAX_AGENTS_PER_OWNER} agents; revoke one first`);
|
|
155
|
+
const { rows } = await q(`INSERT INTO ${this.t} (id, owner, name, contact, capabilities, agent, created_at, expires_at, erc8004) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`, [id, owner, v.name, v.contact, capabilities, v.agent, new Date(now).toISOString(), v.expiresAt, link ? JSON.stringify(link) : null]);
|
|
156
|
+
return RegistryStore.row(rows[0]);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
if (keyTaken(e))
|
|
161
|
+
throw new RegistryInputError(TAKEN);
|
|
162
|
+
throw e;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async get(id) {
|
|
166
|
+
if (!AGENT_ID.test(id))
|
|
167
|
+
return null;
|
|
168
|
+
await this.init();
|
|
169
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE id = $1`, [id]);
|
|
170
|
+
return rows[0] ? RegistryStore.row(rows[0]) : null;
|
|
171
|
+
}
|
|
172
|
+
async list(owner) {
|
|
173
|
+
await this.init();
|
|
174
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE owner = $1 ORDER BY created_at, id`, [owner]);
|
|
175
|
+
return rows.map((r) => RegistryStore.row(r));
|
|
176
|
+
}
|
|
177
|
+
/** Changes an active agent of this owner: any of name, contact, capabilities, key, expiry. Null when the owner has no such active agent. */
|
|
178
|
+
async update(owner, id, raw, now = Date.now(), erc8004) {
|
|
179
|
+
await this.init();
|
|
180
|
+
const v = checkInput(raw, true, now);
|
|
181
|
+
if (Object.keys(v).filter((k) => k !== "proof").length === 0)
|
|
182
|
+
throw new RegistryInputError("nothing to change: give name, contact, capabilities, agent, expiresAt, or erc8004");
|
|
183
|
+
const current = await this.get(id);
|
|
184
|
+
if (!current || current.owner !== owner || agentStatus(current, now) === "revoked")
|
|
185
|
+
return null;
|
|
186
|
+
if (v.agent && v.agent !== current.agent)
|
|
187
|
+
checkProof(this.registryUrl, owner, v.agent, v.proof);
|
|
188
|
+
const { proof: _proof, erc8004: wanted, ...fields } = v;
|
|
189
|
+
const next = { ...current, ...fields };
|
|
190
|
+
// a link stays only while the registration file lists the agent's key: a new key checks the standing link again
|
|
191
|
+
const target = wanted === undefined ? (current.erc8004 && next.agent !== current.agent ? current.erc8004 : undefined) : wanted;
|
|
192
|
+
const link = target === undefined ? current.erc8004 : target === null ? null : await checkedLink(erc8004, target, next.agent);
|
|
193
|
+
try {
|
|
194
|
+
const { rows } = await this.client.query(`UPDATE ${this.t} SET name = $3, contact = $4, capabilities = $5, agent = $6, expires_at = $7, erc8004 = $8 WHERE id = $1 AND owner = $2 AND revoked_at IS NULL RETURNING *`, [id, owner, next.name, next.contact, next.capabilities, next.agent, next.expiresAt, link ? JSON.stringify(link) : null]);
|
|
195
|
+
return rows[0] ? RegistryStore.row(rows[0]) : null;
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (keyTaken(e))
|
|
199
|
+
throw new RegistryInputError(TAKEN);
|
|
200
|
+
throw e;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Active agents, by id, that hold `capability` (and belong to `owner`) when given: at most `limit` of them, after the
|
|
205
|
+
* id `after`. What the registry's public search serves; revoked and expired agents are not listed.
|
|
206
|
+
*/
|
|
207
|
+
async search(o, now = Date.now()) {
|
|
208
|
+
await this.init();
|
|
209
|
+
if (o.capability !== undefined && !CAPABILITY.test(o.capability))
|
|
210
|
+
throw new RegistryInputError("capability: lowercase letters, digits, and . _ : -, at most 64 characters");
|
|
211
|
+
if (o.owner !== undefined && !/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(o.owner))
|
|
212
|
+
throw new RegistryInputError("owner: a tenant id");
|
|
213
|
+
if (o.after !== undefined && !AGENT_ID.test(o.after))
|
|
214
|
+
throw new RegistryInputError("after: an agent id, the next value of the last page");
|
|
215
|
+
const limit = Math.min(Math.max(Math.trunc(o.limit ?? 50), 1), 100);
|
|
216
|
+
const where = ["revoked_at IS NULL", "expires_at > $1"];
|
|
217
|
+
const values = [new Date(now).toISOString()];
|
|
218
|
+
const param = (v) => { values.push(v); return `$${values.length}`; };
|
|
219
|
+
if (o.capability !== undefined)
|
|
220
|
+
where.push(`capabilities @> ${param([o.capability])}::text[]`);
|
|
221
|
+
if (o.owner !== undefined)
|
|
222
|
+
where.push(`owner = ${param(o.owner)}`);
|
|
223
|
+
if (o.after !== undefined)
|
|
224
|
+
where.push(`id > ${param(o.after)}`);
|
|
225
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE ${where.join(" AND ")} ORDER BY id LIMIT ${param(limit + 1)}`, values);
|
|
226
|
+
const agents = rows.slice(0, limit).map((r) => RegistryStore.row(r));
|
|
227
|
+
return { agents, next: rows.length > limit ? agents.at(-1).id : null };
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Records a later check of an agent's standing link: the fresh result, or the error beside the last good one. `checked`
|
|
231
|
+
* is the key and the link that were checked. The result is stored only while the row still names them: a check that
|
|
232
|
+
* finishes after the owner changed the link or rotated the key would otherwise write over the new link. Returns the
|
|
233
|
+
* row as it is.
|
|
234
|
+
*/
|
|
235
|
+
async recordErc8004(id, checked, r, now = Date.now()) {
|
|
236
|
+
await this.init();
|
|
237
|
+
const current = await this.get(id);
|
|
238
|
+
if (!current?.erc8004)
|
|
239
|
+
return current;
|
|
240
|
+
if (current.agent !== checked.agent || current.erc8004.agentRegistry !== checked.link.agentRegistry || current.erc8004.agentId !== checked.link.agentId)
|
|
241
|
+
return current;
|
|
242
|
+
const link = r.ok ? r.link : { ...current.erc8004, error: r.error.slice(0, 300), errorAt: new Date(now).toISOString() };
|
|
243
|
+
// the same comparison in the write, so a change between the read and the write is not overwritten either
|
|
244
|
+
const { rows } = await this.client.query(`UPDATE ${this.t} SET erc8004 = $2 WHERE id = $1 AND agent = $3 AND erc8004::jsonb->>'agentRegistry' = $4 AND erc8004::jsonb->>'agentId' = $5 AND revoked_at IS NULL RETURNING *`, [id, JSON.stringify(link), checked.agent, checked.link.agentRegistry, checked.link.agentId]);
|
|
245
|
+
return rows[0] ? RegistryStore.row(rows[0]) : await this.get(id);
|
|
246
|
+
}
|
|
247
|
+
/** Revokes an agent of this owner for good: the registry issues it no more passports. False when there is none to revoke. */
|
|
248
|
+
async revoke(owner, id, now = Date.now()) {
|
|
249
|
+
await this.init();
|
|
250
|
+
if (!AGENT_ID.test(id))
|
|
251
|
+
return false;
|
|
252
|
+
const { rows } = await this.client.query(`UPDATE ${this.t} SET revoked_at = $3 WHERE id = $1 AND owner = $2 AND revoked_at IS NULL RETURNING id`, [id, owner, new Date(now).toISOString()]);
|
|
253
|
+
return rows.length > 0;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Signs a passport for an active agent. It lives `passportSeconds`, never past the registration's expiry, and carries
|
|
258
|
+
* `erc8004` when given (the link as last checked). Throws when the agent is revoked or expired.
|
|
259
|
+
*/
|
|
260
|
+
export async function issuePassport(signer, registryUrl, e, passportSeconds = DEFAULT_PASSPORT_SECONDS, now = Date.now(), erc8004) {
|
|
261
|
+
const status = agentStatus(e, now);
|
|
262
|
+
if (status !== "active")
|
|
263
|
+
throw new RegistryInputError(`the agent ${e.id} is ${status}; the registry issues it no passport`);
|
|
264
|
+
if (!e.agent.startsWith(DID_KEY_PREFIX))
|
|
265
|
+
throw new Error("the agent's key is not a did:key");
|
|
266
|
+
const expires = Math.min(now + passportSeconds * 1000, Date.parse(e.expiresAt));
|
|
267
|
+
const passport = PassportSchema.parse({
|
|
268
|
+
version: "0.1",
|
|
269
|
+
registry: registryUrl,
|
|
270
|
+
agentId: e.id,
|
|
271
|
+
agent: e.agent,
|
|
272
|
+
name: e.name,
|
|
273
|
+
owner: e.owner,
|
|
274
|
+
contact: e.contact,
|
|
275
|
+
capabilities: e.capabilities,
|
|
276
|
+
...(erc8004 ? { erc8004: { agentRegistry: erc8004.agentRegistry, agentId: erc8004.agentId, owner: erc8004.owner, block: erc8004.block } } : {}),
|
|
277
|
+
issuedAt: new Date(now).toISOString(),
|
|
278
|
+
expiresAt: new Date(expires).toISOString(),
|
|
279
|
+
});
|
|
280
|
+
return signer.sign(PASSPORT_TYPE, passport);
|
|
281
|
+
}
|
|
282
|
+
/** The registry's key document, served at REGISTRY_DOCUMENT_PATH. */
|
|
283
|
+
export async function registryDocument(signer, registryUrl, passportSeconds, erc8004Chains = []) {
|
|
284
|
+
return {
|
|
285
|
+
registry: registryUrl,
|
|
286
|
+
/** the chain ids whose ERC-8004 registries it checks links against */
|
|
287
|
+
erc8004Chains,
|
|
288
|
+
passportType: PASSPORT_TYPE,
|
|
289
|
+
passportHeader: PASSPORT_HEADER,
|
|
290
|
+
passportSeconds,
|
|
291
|
+
agents: `${registryUrl}registry/agents/`,
|
|
292
|
+
keys: (await signer.keys()).keys,
|
|
293
|
+
};
|
|
294
|
+
}
|
package/dist/web-bot-auth.d.ts
CHANGED
|
@@ -53,6 +53,11 @@ export declare function normalizeAuthority(host: string): string;
|
|
|
53
53
|
* component or component parameter is refused rather than guessed at.
|
|
54
54
|
*/
|
|
55
55
|
export declare function signatureBase(req: SignedRequest, input: SfInnerList): string;
|
|
56
|
+
/**
|
|
57
|
+
* True when a `Content-Digest` field (RFC 9530) holds a sha-256 or sha-512 digest of `body`, and every such digest it
|
|
58
|
+
* holds matches. A field with neither, or one that does not parse, is false.
|
|
59
|
+
*/
|
|
60
|
+
export declare function contentDigestMatches(field: string | undefined, body: Uint8Array): boolean;
|
|
56
61
|
/** The RFC 7638 thumbprint of an Ed25519 JWK (RFC 8037 appendix A.3): the base64url SHA-256 of `{"crv","kty","x"}`. */
|
|
57
62
|
export declare function jwkThumbprint(x: string): string;
|
|
58
63
|
export interface WebBotAuthOptions {
|
|
@@ -79,7 +84,8 @@ export type SignatureCheck = {
|
|
|
79
84
|
outcome: "verified";
|
|
80
85
|
agent: string;
|
|
81
86
|
keyid: string;
|
|
82
|
-
label: string;
|
|
87
|
+
label: string; /** the components the signature covered whole (no parameters), as named in Signature-Input */
|
|
88
|
+
covered?: string[];
|
|
83
89
|
} | {
|
|
84
90
|
outcome: "invalid" | "unavailable";
|
|
85
91
|
error: string;
|
|
@@ -89,8 +95,8 @@ export type SignatureCheck = {
|
|
|
89
95
|
outcome: "unchecked" | "absent";
|
|
90
96
|
};
|
|
91
97
|
export interface WebBotAuthVerifier {
|
|
92
|
-
/** `
|
|
93
|
-
verify(req: SignedRequest,
|
|
98
|
+
/** `keyAgents`: the did:key, or did:keys, that a trusted grant or a trusted registry's passport in the request names; a did:key signature keeps its nonce only for one of them */
|
|
99
|
+
verify(req: SignedRequest, keyAgents?: string | readonly string[]): Promise<SignatureCheck>;
|
|
94
100
|
/** nonces held now, or undefined when the nonce store does not count them */
|
|
95
101
|
nonces(): number | undefined;
|
|
96
102
|
}
|
package/dist/web-bot-auth.js
CHANGED
|
@@ -277,6 +277,33 @@ export function signatureBase(req, input) {
|
|
|
277
277
|
lines.push(`"@signature-params": ${serializeMember(input)}`);
|
|
278
278
|
return lines.join("\n");
|
|
279
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* True when a `Content-Digest` field (RFC 9530) holds a sha-256 or sha-512 digest of `body`, and every such digest it
|
|
282
|
+
* holds matches. A field with neither, or one that does not parse, is false.
|
|
283
|
+
*/
|
|
284
|
+
export function contentDigestMatches(field, body) {
|
|
285
|
+
if (!field)
|
|
286
|
+
return false;
|
|
287
|
+
let members;
|
|
288
|
+
try {
|
|
289
|
+
members = parseDictionary(field);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
let checked = 0;
|
|
295
|
+
for (const alg of ["sha-256", "sha-512"]) {
|
|
296
|
+
const m = members.get(alg);
|
|
297
|
+
if (!m)
|
|
298
|
+
continue;
|
|
299
|
+
if ("list" in m || m.item.t !== "bytes")
|
|
300
|
+
return false;
|
|
301
|
+
if (!createHash(alg.replace("-", "")).update(body).digest().equals(m.item.v))
|
|
302
|
+
return false;
|
|
303
|
+
checked++;
|
|
304
|
+
}
|
|
305
|
+
return checked > 0;
|
|
306
|
+
}
|
|
280
307
|
/** The RFC 7638 thumbprint of an Ed25519 JWK (RFC 8037 appendix A.3): the base64url SHA-256 of `{"crv","kty","x"}`. */
|
|
281
308
|
export function jwkThumbprint(x) {
|
|
282
309
|
return createHash("sha256").update(`{"crv":"Ed25519","kty":"OKP","x":"${x}"}`).digest("base64url");
|
|
@@ -411,7 +438,7 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now(), nonceS
|
|
|
411
438
|
inflight.set(origin, p);
|
|
412
439
|
return p;
|
|
413
440
|
};
|
|
414
|
-
async function verify(req,
|
|
441
|
+
async function verify(req, keyAgents = []) {
|
|
415
442
|
const inputText = req.header("signature-input");
|
|
416
443
|
const sigText = req.header("signature");
|
|
417
444
|
if (!inputText && !sigText)
|
|
@@ -517,8 +544,8 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now(), nonceS
|
|
|
517
544
|
if (opts.requireNonce && !nonceP)
|
|
518
545
|
return invalid(`${label} has no nonce, and this door requires one`, { agent, keyid });
|
|
519
546
|
// Anyone can make a did:key, so a stranger's signatures must not fill the nonce store. A did:key signature that no
|
|
520
|
-
// trusted grant names is never accepted by the door, and its nonce is not kept.
|
|
521
|
-
const nonceKey = nonceP && (!didKey ||
|
|
547
|
+
// trusted grant or passport names is never accepted by the door, and its nonce is not kept.
|
|
548
|
+
const nonceKey = nonceP && (!didKey || (typeof keyAgents === "string" ? keyAgents === keyid : keyAgents.includes(keyid))) ? `${agent} ${keyid} ${nonceP.v}` : undefined;
|
|
522
549
|
const full = { outcome: "unavailable", error: nonceStore ? "the door's nonce store is full and cannot record another" : `the door holds ${opts.maxNonces} nonces and cannot record another`, agent, keyid };
|
|
523
550
|
if (nonceKey && nonces.check) {
|
|
524
551
|
let state;
|
|
@@ -562,7 +589,7 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now(), nonceS
|
|
|
562
589
|
if (claim === "full")
|
|
563
590
|
return full;
|
|
564
591
|
}
|
|
565
|
-
return { outcome: "verified", agent, keyid, label };
|
|
592
|
+
return { outcome: "verified", agent, keyid, label, covered: covered.filter((c) => c.params.length === 0 && c.item.t === "string").map((c) => c.item.v) };
|
|
566
593
|
}
|
|
567
594
|
return { verify, nonces: () => nonces.size?.() };
|
|
568
595
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Admission lists
|
|
2
|
+
|
|
3
|
+
A site keeps its own named lists of agents, such as `partners` or `blocked`. Its [door](door.md) records in each arrival fact which lists the arrival's agent is on, and its Cedar policy decides what each list means. The decision is a receipt that names the lists and the digest of the lists in force, so a reader knows which version of the lists the door used.
|
|
4
|
+
|
|
5
|
+
To fill a list, a site can search an [agent registry](agent-registry.md) by capability.
|
|
6
|
+
|
|
7
|
+
## Find agents in the registry
|
|
8
|
+
|
|
9
|
+
The registry answers a search without a session:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
curl 'https://app.agent-custody.dev/registry/agents?capability=refunds&limit=50'
|
|
13
|
+
# { "registry": "https://app.agent-custody.dev/", "agents": [ <entry>, … ], "next": "agt_…" | null }
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
It lists active agents only, never a revoked or expired one, ordered by id. `capability` filters by one capability and `owner` by one tenant. `limit` is 1 to 100 (50 by default); any other value is a `400`. To get the next page, send `after=<next>`. `registry` is the registry's URL as its passports name it: copy it into a list entry. Each entry is the one `GET /registry/agents/<id>` publishes, without `contact`: id, name, owner, capabilities, its key as a did:key and a JWK, and its ERC-8004 link when it has one. A search finds agents; it is not a directory of contacts. An agent's contact is on its own entry and in its passport, which reaches every site the agent visits.
|
|
17
|
+
|
|
18
|
+
The registry's public reads (the search, an agent's entry, and its passport) allow each address a burst of 120 and then one every 2 seconds; past that they answer `429` with `Retry-After`.
|
|
19
|
+
|
|
20
|
+
The registry signs nothing about a search. A site that lists an agent from a search names it by the entry's registry and id, and the door then admits the agent only on a passport the registry signed.
|
|
21
|
+
|
|
22
|
+
## Write the lists
|
|
23
|
+
|
|
24
|
+
The lists are a JSON file beside the door config:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"lists": {
|
|
29
|
+
"partners": [
|
|
30
|
+
{ "registry": "https://app.agent-custody.dev/", "agentId": "agt_d0cdd11e729cf856" },
|
|
31
|
+
{ "erc8004": { "agentRegistry": "eip155:8453:0x…", "agentId": "7" } }
|
|
32
|
+
],
|
|
33
|
+
"crawlers": [{ "agent": "https://crawler.example" }],
|
|
34
|
+
"blocked": [{ "agent": "did:key:z6Mk…" }]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{ "admissionLists": "admission.json" }
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
A list name is lowercase letters, digits, and `. _ -`, at most 64 characters. There are at most 64 lists, of at most 10,000 entries each. An entry names an agent in one of three ways, by what the door checks:
|
|
44
|
+
|
|
45
|
+
| entry | matches a `verified` arrival | survives a key rotation |
|
|
46
|
+
| --- | --- | --- |
|
|
47
|
+
| `{ "registry", "agentId" }` | whose [passport](agent-registry.md#admit-registered-agents-at-a-door) is `verified`, from that registry, for that agent id | yes |
|
|
48
|
+
| `{ "erc8004": { "agentRegistry", "agentId" } }` | whose `verified` passport carries that [ERC-8004 link](agent-registry.md#link-an-erc-8004-identity), which the registry checked on chain | yes, while the token's file names the new key |
|
|
49
|
+
| `{ "agent" }` | whose `subject` is that value: a did:key, a Web Bot Auth signature agent's origin, or the agent a trusted grant names | no, for a did:key |
|
|
50
|
+
|
|
51
|
+
The registry's URL is part of a registry entry because an agent id is unique only within one registry. A URL or origin is compared in one spelling, so `https://APP.example.test:443` and `https://app.example.test/` name the same registry, and `https://Crawler.Example/` the agent `https://crawler.example`; a did:key is compared exactly.
|
|
52
|
+
|
|
53
|
+
**A trusted registry key can name any registry URL.** A passport's `registry` is written by the registry that signs it, and the door holds only keys. So a door that trusts the keys of two registries lets either one issue a passport that names the other's URL and an agent id from it, and so put its own agent on a list entry meant for the other's agent. Trust only registries you would let list any agent, or keep one registry's key per door. Prefer registry entries for registered agents, because they survive a key rotation. Use `agent` for an agent with no registry, or to block one key whatever registry vouches for it.
|
|
54
|
+
|
|
55
|
+
The door reads the file when it starts, and refuses to start if the file is not valid. It reads the file again whenever it changes. A changed file that cannot be read, or is not valid, leaves the lists in force and prints `ADMISSION LISTS NOT RELOADED`. Emptying the lists instead would also empty a block list. `agent-custody check --config door.json` checks the file. In a Worker, the lists are the `ADMISSION_LISTS` variable, and a change is a deploy.
|
|
56
|
+
|
|
57
|
+
## Use them in a policy
|
|
58
|
+
|
|
59
|
+
The door adds `admission` to every arrival fact when it has lists:
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{ "admission": { "lists": ["partners"], "digest": "c34ef919ab97…" } }
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`lists` holds the names of the lists the agent is on, sorted, and is empty when it is on none. `digest` is the sha256 of the lists file in force. The names mean what the policy makes of them:
|
|
66
|
+
|
|
67
|
+
```cedar
|
|
68
|
+
// a refund is for a verified partner, and never for a blocked agent
|
|
69
|
+
permit(principal, action == Action::"refund", resource)
|
|
70
|
+
when {
|
|
71
|
+
context.facts.arrival.class == "verified" &&
|
|
72
|
+
context.facts.arrival has admission &&
|
|
73
|
+
context.facts.arrival.admission.lists.contains("partners")
|
|
74
|
+
};
|
|
75
|
+
forbid(principal, action == Action::"refund", resource)
|
|
76
|
+
when { context.facts.arrival has admission && context.facts.arrival.admission.lists.contains("blocked") };
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
A `forbid` beats a `permit`, so an agent that is a partner by its registry entry and blocked by its key is refused. Test `has admission`, because a door without lists, or a receipt from before the lists, has no such field.
|
|
80
|
+
|
|
81
|
+
## What puts an agent on a list
|
|
82
|
+
|
|
83
|
+
Only what the door checked. An arrival that is not `verified` is on no list. A passport under another key's signature, or under a signature that does not bind it to the request, does not put the registry's agent on a list, even when the arrival is verified as itself by its own grant. A claim therefore cannot add an agent to an allow list. A policy that blocks with `forbid` must not rely on a claimed arrival being listed: such an arrival is on no list, so refuse it some other way, for example by permitting only `verified` arrivals, as above.
|
|
84
|
+
|
|
85
|
+
## What it does not do
|
|
86
|
+
|
|
87
|
+
- **Lists live in the door's config, not the registry.** The registry holds agents; each site keeps its own lists in its own file, so no one else can change who a site admits. There is no shared list service.
|
|
88
|
+
- **Lists do not deny or allow on their own.** Every meaning comes from the policy.
|
|
89
|
+
- **The digest names a version of the lists, not the lists themselves.** To read what a receipt's lists said, keep each version of the file, for example in version control.
|