@agent-custody/receipts 0.16.12 → 0.16.14
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 +15 -1
- package/dist/admission.d.ts +75 -0
- package/dist/admission.js +136 -0
- package/dist/check.js +48 -4
- package/dist/cli.js +63 -4
- package/dist/config.d.ts +11 -1
- package/dist/config.js +10 -2
- package/dist/door-core.d.ts +82 -2
- package/dist/door-core.js +113 -12
- package/dist/door-worker.d.ts +14 -0
- package/dist/door-worker.js +33 -1
- package/dist/door.d.ts +1 -1
- package/dist/door.js +18 -1
- 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 +9 -3
- package/dist/index.js +5 -2
- package/dist/log-store.d.ts +3 -1
- package/dist/log-store.js +2 -2
- package/dist/passport.d.ts +66 -0
- package/dist/passport.js +127 -0
- package/dist/portal.d.ts +14 -0
- package/dist/portal.js +109 -0
- package/dist/registry.d.ts +170 -0
- package/dist/registry.js +331 -0
- package/dist/web-bot-auth.d.ts +9 -3
- package/dist/web-bot-auth.js +31 -4
- package/docs/admission-lists.md +91 -0
- package/docs/agent-registry.md +191 -0
- package/docs/door-quickstart.md +2 -2
- package/docs/door-wordpress.md +128 -0
- package/docs/door-worker.md +1 -1
- package/docs/door.md +7 -3
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +1 -1
- package/package.json +2 -1
package/dist/portal.js
CHANGED
|
@@ -16,6 +16,7 @@ import { welcomeSheet } from "./log-admin.js";
|
|
|
16
16
|
import { clientAddress } from "./log-sink.js";
|
|
17
17
|
import { SITE_NAV, siteUrl } from "./site-links.js";
|
|
18
18
|
import { PLAN_QUOTAS, RateLimiter } from "./log-store.js";
|
|
19
|
+
import { agentStatus, freshErc8004, issuePassport, publicEntry, registryDocument, RegistryInputError, RegistryStore, DEFAULT_PASSPORT_SECONDS, MAX_PASSPORT_SECONDS, REGISTRY_DOCUMENT_PATH } from "./registry.js";
|
|
19
20
|
import { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.js";
|
|
20
21
|
/** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
|
|
21
22
|
export class UnverifiedAccountError extends Error {
|
|
@@ -828,6 +829,30 @@ export async function sendFollowUps(store, mail, o) {
|
|
|
828
829
|
}
|
|
829
830
|
export function portalHandler(o) {
|
|
830
831
|
const store = new PortalStore(o.client, o.prefix);
|
|
832
|
+
if (o.registry && !o.portalUrl)
|
|
833
|
+
throw new Error("the agent registry needs portalUrl: it names the registry in every passport");
|
|
834
|
+
const passportSeconds = o.registry?.passportSeconds ?? DEFAULT_PASSPORT_SECONDS;
|
|
835
|
+
if (!Number.isInteger(passportSeconds) || passportSeconds < 60 || passportSeconds > MAX_PASSPORT_SECONDS)
|
|
836
|
+
throw new Error(`a passport lives from 60 to ${MAX_PASSPORT_SECONDS} seconds; got ${passportSeconds}`);
|
|
837
|
+
const agents = o.registry ? new RegistryStore(o.client, (o.portalUrl ?? "http://localhost/").replace(/\/?$/, "/"), o.prefix) : null;
|
|
838
|
+
const recheckSeconds = o.registry?.erc8004RecheckSeconds ?? 3600;
|
|
839
|
+
if (!Number.isInteger(recheckSeconds) || recheckSeconds < 60 || recheckSeconds > 86_400)
|
|
840
|
+
throw new Error(`an ERC-8004 link is rechecked every 60 to 86400 seconds; got ${recheckSeconds}`);
|
|
841
|
+
const resolver = o.registry?.erc8004;
|
|
842
|
+
const checker = resolver ? (link, didKey) => resolver.check(link, didKey) : undefined;
|
|
843
|
+
// a stale link is checked again at most once a minute per agent, so anonymous passport requests cannot drive the chain
|
|
844
|
+
const lastRecheck = new Map();
|
|
845
|
+
const passportFor = async (entry) => {
|
|
846
|
+
let e = entry;
|
|
847
|
+
if (resolver && agents && e.erc8004 && !freshErc8004(e, recheckSeconds) && Date.now() - (lastRecheck.get(e.id) ?? 0) >= 60_000) {
|
|
848
|
+
lastRecheck.set(e.id, Date.now());
|
|
849
|
+
if (lastRecheck.size > 10_000)
|
|
850
|
+
lastRecheck.delete(lastRecheck.keys().next().value);
|
|
851
|
+
const checked = { agent: e.agent, link: { agentRegistry: e.erc8004.agentRegistry, agentId: e.erc8004.agentId } };
|
|
852
|
+
e = (await agents.recordErc8004(e.id, checked, await resolver.check(checked.link, checked.agent))) ?? e;
|
|
853
|
+
}
|
|
854
|
+
return issuePassport(o.registry.signer, portalBase, e, passportSeconds, Date.now(), freshErc8004(e, recheckSeconds));
|
|
855
|
+
};
|
|
831
856
|
const heads = postgresCheckpoints(o.client);
|
|
832
857
|
const log = o.log ?? ((m) => console.error(m));
|
|
833
858
|
const loginFailures = new RateLimiter({ perSecond: 1 / 30, burst: 8 });
|
|
@@ -836,6 +861,8 @@ export function portalHandler(o) {
|
|
|
836
861
|
const mfaFailures = new RateLimiter({ perSecond: 1 / 120, burst: 5 });
|
|
837
862
|
const resetsByClient = new RateLimiter({ perSecond: 1 / 600, burst: 5 });
|
|
838
863
|
const resetsByEmail = new RateLimiter({ perSecond: 1 / 900, burst: 3 });
|
|
864
|
+
// the registry's public reads need no session; per address, so one client cannot walk every entry at once
|
|
865
|
+
const registryReads = new RateLimiter({ perSecond: 1 / 2, burst: 120 });
|
|
839
866
|
const base = o.publicUrl.endsWith("/") ? o.publicUrl : `${o.publicUrl}/`;
|
|
840
867
|
const cookieName = "custody_session";
|
|
841
868
|
const sheet = (tenant, logId) => welcomeSheet({ tenant, logId, publicUrl: base, ...(o.checkpointsUrl ? { checkpointsUrl: o.checkpointsUrl } : {}), ...(o.keyid ? { keyid: o.keyid } : {}) });
|
|
@@ -955,6 +982,47 @@ export function portalHandler(o) {
|
|
|
955
982
|
res.writeHead(200, { "content-type": "image/svg+xml", "cache-control": "public, max-age=86400" });
|
|
956
983
|
return void res.end(FAVICON);
|
|
957
984
|
}
|
|
985
|
+
// ---- the agent registry's public side: its keys, each agent's entry, and passports, for anyone ----
|
|
986
|
+
if (o.registry && agents && req.method === "GET" && url.pathname === REGISTRY_DOCUMENT_PATH)
|
|
987
|
+
return json(200, await registryDocument(o.registry.signer, portalBase, passportSeconds, resolver?.chains ?? []));
|
|
988
|
+
const agentPath = /^\/registry\/agents\/([^/]+)(\/passport)?$/.exec(url.pathname);
|
|
989
|
+
if (o.registry && agents && req.method === "GET" && (url.pathname === "/registry/agents" || agentPath) && !registryReads.take(`registry:${addr}`)) {
|
|
990
|
+
return json(429, { error: "too many registry reads from this address; slow down" }, { "retry-after": "2" });
|
|
991
|
+
}
|
|
992
|
+
if (o.registry && agents && req.method === "GET" && url.pathname === "/registry/agents") {
|
|
993
|
+
const q = (k) => url.searchParams.get(k) ?? undefined;
|
|
994
|
+
const limit = q("limit");
|
|
995
|
+
if (limit !== undefined && !(/^[1-9][0-9]{0,2}$/.test(limit) && Number(limit) <= 100))
|
|
996
|
+
return json(400, { error: "limit is 1 to 100" });
|
|
997
|
+
try {
|
|
998
|
+
const page = await agents.search({ ...(q("capability") !== undefined ? { capability: q("capability") } : {}), ...(q("owner") !== undefined ? { owner: q("owner") } : {}), ...(q("after") !== undefined ? { after: q("after") } : {}), ...(limit !== undefined ? { limit: Number(limit) } : {}) });
|
|
999
|
+
// a search finds agents; it is not a directory of contacts, nor of each agent's history, which each agent's own entry carries
|
|
1000
|
+
return json(200, { registry: portalBase, agents: page.agents.map((e) => { const { contact: _contact, history: _history, ...listed } = publicEntry(e); return listed; }), next: page.next });
|
|
1001
|
+
}
|
|
1002
|
+
catch (e) {
|
|
1003
|
+
if (e instanceof RegistryInputError)
|
|
1004
|
+
return json(400, { error: e.message });
|
|
1005
|
+
throw e;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (o.registry && agents && req.method === "GET" && agentPath) {
|
|
1009
|
+
const entry = await agents.get(agentPath[1]);
|
|
1010
|
+
if (!entry)
|
|
1011
|
+
return json(404, { error: "no agent with this id is registered" });
|
|
1012
|
+
if (!agentPath[2])
|
|
1013
|
+
return json(200, publicEntry(entry));
|
|
1014
|
+
const status = agentStatus(entry);
|
|
1015
|
+
if (status !== "active")
|
|
1016
|
+
return json(410, { error: `the agent is ${status}; the registry issues it no passport`, status });
|
|
1017
|
+
try {
|
|
1018
|
+
return json(200, await passportFor(entry));
|
|
1019
|
+
}
|
|
1020
|
+
catch (e) {
|
|
1021
|
+
if (e instanceof RegistryInputError)
|
|
1022
|
+
return json(400, { error: e.message });
|
|
1023
|
+
throw e;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
958
1026
|
if (req.method === "GET" && url.pathname === "/") {
|
|
959
1027
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'" });
|
|
960
1028
|
const providers = JSON.stringify(["github", "google"].filter((p) => !!o.oauth?.[p]));
|
|
@@ -1596,6 +1664,44 @@ document.getElementById("f").onsubmit = async (e) => {
|
|
|
1596
1664
|
await jsonBody();
|
|
1597
1665
|
return json(200, { revoked: await o.tenancy.revokeToken(tenantId, revoke[1], `portal:${user.email}`) });
|
|
1598
1666
|
}
|
|
1667
|
+
// The tenant's agents in the registry. Writes need admin, like keys.
|
|
1668
|
+
const agentRoute = /^\/api\/agents(?:\/([^/]+)(\/revoke)?)?$/.exec(url.pathname);
|
|
1669
|
+
if (agentRoute) {
|
|
1670
|
+
if (!o.registry || !agents)
|
|
1671
|
+
return json(404, { error: "this portal runs no agent registry" });
|
|
1672
|
+
const [, id, revokeAgent] = agentRoute;
|
|
1673
|
+
const actor = `portal:${user.email}`;
|
|
1674
|
+
try {
|
|
1675
|
+
if (req.method === "GET" && !id)
|
|
1676
|
+
return json(200, { agents: (await agents.list(tenantId)).map((e) => publicEntry(e)) });
|
|
1677
|
+
if (req.method === "POST" && !id) {
|
|
1678
|
+
const entry = await agents.register(tenantId, await jsonBody(), Date.now(), checker);
|
|
1679
|
+
await o.tenancy.record(actor, "agent.register", tenantId, { agent: entry.id, key: entry.agent, capabilities: entry.capabilities, expiresAt: entry.expiresAt, ...(entry.version ? { version: entry.version } : {}), ...(entry.erc8004 ? { erc8004: `${entry.erc8004.agentRegistry}:${entry.erc8004.agentId}` } : {}) });
|
|
1680
|
+
return json(200, { agent: publicEntry(entry), passport: await passportFor(entry) });
|
|
1681
|
+
}
|
|
1682
|
+
if (req.method === "POST" && id && revokeAgent) {
|
|
1683
|
+
await jsonBody();
|
|
1684
|
+
const revoked = await agents.revoke(tenantId, id);
|
|
1685
|
+
if (revoked)
|
|
1686
|
+
await o.tenancy.record(actor, "agent.revoke", tenantId, { agent: id });
|
|
1687
|
+
return json(revoked ? 200 : 404, revoked ? { revoked: true } : { error: "no active agent with this id belongs to this tenant" });
|
|
1688
|
+
}
|
|
1689
|
+
if (req.method === "POST" && id) {
|
|
1690
|
+
const b = await jsonBody();
|
|
1691
|
+
const entry = await agents.update(tenantId, id, b, Date.now(), checker);
|
|
1692
|
+
if (!entry)
|
|
1693
|
+
return json(404, { error: "no active agent with this id belongs to this tenant" });
|
|
1694
|
+
await o.tenancy.record(actor, "agent.update", tenantId, { agent: entry.id, changed: Object.keys(b).sort(), key: entry.agent, capabilities: entry.capabilities, ...(entry.version ? { version: entry.version } : {}), expiresAt: entry.expiresAt, erc8004: entry.erc8004 ? `${entry.erc8004.agentRegistry}:${entry.erc8004.agentId}` : null });
|
|
1695
|
+
return json(200, { agent: publicEntry(entry), ...(agentStatus(entry) === "active" ? { passport: await passportFor(entry) } : {}) });
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
catch (e) {
|
|
1699
|
+
if (e instanceof RegistryInputError)
|
|
1700
|
+
return json(400, { error: e.message });
|
|
1701
|
+
throw e;
|
|
1702
|
+
}
|
|
1703
|
+
return json(404, { error: "not found" });
|
|
1704
|
+
}
|
|
1599
1705
|
// Policies: named versions the tenant publishes so a receipt's policyDigest reads as a name. The gateway never
|
|
1600
1706
|
// reads these; enforcement stays on the tenant's machines.
|
|
1601
1707
|
if (req.method === "GET" && url.pathname === "/api/policies") {
|
|
@@ -2134,6 +2240,9 @@ ${DESIGN_CSS}
|
|
|
2134
2240
|
"sso.set": (d) => "set up single sign-on" + (d.protocol ? " (" + String(d.protocol).toUpperCase() + ")" : ""),
|
|
2135
2241
|
"sso.remove": () => "removed single sign-on",
|
|
2136
2242
|
"user.mfa-reset": (d) => "turned off two-step sign-in for " + (d.email || "a member"),
|
|
2243
|
+
"agent.register": (d) => "registered the agent " + d.agent + " in the agent registry",
|
|
2244
|
+
"agent.update": (d) => "changed the agent " + d.agent + (Array.isArray(d.changed) && d.changed.length ? " (" + d.changed.join(", ") + ")" : ""),
|
|
2245
|
+
"agent.revoke": (d) => "revoked the agent " + d.agent + "; the registry issues it no more passports",
|
|
2137
2246
|
};
|
|
2138
2247
|
const sentence = (e) => { const d = e.detail || {}; return actor(e.actor) + " " + (Object.hasOwn(SENTENCES, e.action) ? SENTENCES[e.action](d) : "did '" + e.action + "'" + (Object.keys(d).length ? " (" + Object.entries(d).map(([k, v]) => k + ": " + v).join(", ") + ")" : "")) + "."; };
|
|
2139
2248
|
const feed = (entries) => entries.map((e) => "<li><span title=\\"" + esc(e.action + " " + JSON.stringify(e.detail || {})) + "\\">" + esc(sentence(e)) + "</span>" + when(e.at) + "</li>").join("");
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { Envelope, KeyPair } from "./crypto.ts";
|
|
3
|
+
import { type PostgresLike } from "./log-store.ts";
|
|
4
|
+
import type { Signer } from "./signer.ts";
|
|
5
|
+
import { type Erc8004Check, type Erc8004Checked, type Erc8004Link } from "./erc8004-link.ts";
|
|
6
|
+
export * from "./passport.ts";
|
|
7
|
+
/** the furthest ahead an agent's registration may expire */
|
|
8
|
+
export declare const MAX_REGISTRATION_DAYS = 366;
|
|
9
|
+
export declare const MAX_AGENTS_PER_OWNER = 100;
|
|
10
|
+
/**
|
|
11
|
+
* What an agent's key signs to show that whoever registers it holds it: the registry, the owner, and the key. Without
|
|
12
|
+
* it, a tenant could register a did:key it saw in a grant or a signature, and choose that agent's capabilities.
|
|
13
|
+
*/
|
|
14
|
+
export declare function registrationMessage(registryUrl: string, owner: string, didKey: string): Buffer;
|
|
15
|
+
/** The proof a registration carries: the agent's key's Ed25519 signature over `registrationMessage`, base64url. */
|
|
16
|
+
export declare function registrationProof(agentKey: KeyPair, registryUrl: string, owner: string): {
|
|
17
|
+
agent: string;
|
|
18
|
+
proof: string;
|
|
19
|
+
};
|
|
20
|
+
/** One registered agent, as the registry keeps it. */
|
|
21
|
+
export interface AgentEntry {
|
|
22
|
+
id: string;
|
|
23
|
+
owner: string;
|
|
24
|
+
name: string;
|
|
25
|
+
contact: string;
|
|
26
|
+
capabilities: string[];
|
|
27
|
+
/** the agent's current key */
|
|
28
|
+
agent: string;
|
|
29
|
+
createdAt: string;
|
|
30
|
+
expiresAt: string;
|
|
31
|
+
revokedAt: string | null;
|
|
32
|
+
/** the version its owner registered, MAJOR.MINOR.PATCH; null or absent when none */
|
|
33
|
+
version?: string | null;
|
|
34
|
+
/** since when this version and key have been in force; the registration's time when absent */
|
|
35
|
+
versionSince?: string;
|
|
36
|
+
/** the tool endpoints its owner says it calls: a claim */
|
|
37
|
+
endpoints?: string[];
|
|
38
|
+
/** the versions and keys it had before, newest first, each with when it was in force */
|
|
39
|
+
history?: AgentVersionRecord[];
|
|
40
|
+
/** the linked ERC-8004 identity as last checked, with the error of the last check when it failed */
|
|
41
|
+
erc8004?: (Erc8004Checked & {
|
|
42
|
+
error?: string;
|
|
43
|
+
errorAt?: string;
|
|
44
|
+
}) | null;
|
|
45
|
+
}
|
|
46
|
+
/** A version and key an agent had, and when they were in force. */
|
|
47
|
+
export interface AgentVersionRecord {
|
|
48
|
+
version: string | null;
|
|
49
|
+
agent: string;
|
|
50
|
+
from: string;
|
|
51
|
+
to: string;
|
|
52
|
+
}
|
|
53
|
+
/** how many past versions an entry keeps; the oldest go first */
|
|
54
|
+
export declare const MAX_AGENT_HISTORY = 100;
|
|
55
|
+
/** The ERC-8004 link a passport may carry: one whose last check succeeded within `recheckSeconds`. */
|
|
56
|
+
export declare function freshErc8004(e: AgentEntry, recheckSeconds: number, now?: number): Erc8004Checked | null;
|
|
57
|
+
export type AgentStatus = "active" | "revoked" | "expired";
|
|
58
|
+
export declare const agentStatus: (e: AgentEntry, now?: number) => AgentStatus;
|
|
59
|
+
/** What the registry publishes about an agent: the entry, its status, and its key as a JWK. */
|
|
60
|
+
export declare function publicEntry(e: AgentEntry, now?: number): {
|
|
61
|
+
id: string;
|
|
62
|
+
name: string;
|
|
63
|
+
owner: string;
|
|
64
|
+
contact: string;
|
|
65
|
+
capabilities: string[];
|
|
66
|
+
agent: string;
|
|
67
|
+
keys: {
|
|
68
|
+
kty: string;
|
|
69
|
+
crv: string;
|
|
70
|
+
x: string;
|
|
71
|
+
kid: string;
|
|
72
|
+
exp: number;
|
|
73
|
+
}[];
|
|
74
|
+
createdAt: string;
|
|
75
|
+
expiresAt: string;
|
|
76
|
+
status: AgentStatus;
|
|
77
|
+
version: string | null;
|
|
78
|
+
versionSince: string;
|
|
79
|
+
/** the version this one replaced, when it replaced one */
|
|
80
|
+
replaces: string | null;
|
|
81
|
+
endpoints: string[];
|
|
82
|
+
history: AgentVersionRecord[];
|
|
83
|
+
erc8004: (Erc8004Checked & {
|
|
84
|
+
error?: string;
|
|
85
|
+
errorAt?: string;
|
|
86
|
+
}) | null;
|
|
87
|
+
};
|
|
88
|
+
/** A request to register or change an agent, checked; throws a message fit for the caller. */
|
|
89
|
+
export declare const AgentInputSchema: z.ZodObject<{
|
|
90
|
+
name: z.ZodString;
|
|
91
|
+
contact: z.ZodString;
|
|
92
|
+
capabilities: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
93
|
+
agent: z.ZodString;
|
|
94
|
+
proof: z.ZodOptional<z.ZodString>;
|
|
95
|
+
expiresAt: z.ZodISODateTime;
|
|
96
|
+
version: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
97
|
+
endpoints: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
|
|
98
|
+
erc8004: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
99
|
+
agentRegistry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
100
|
+
agentId: z.ZodString;
|
|
101
|
+
}, z.core.$strip>>>;
|
|
102
|
+
}, z.core.$strip>;
|
|
103
|
+
export type AgentInput = z.infer<typeof AgentInputSchema>;
|
|
104
|
+
export declare class RegistryInputError extends Error {
|
|
105
|
+
}
|
|
106
|
+
/** Checks an ERC-8004 link against the chain for a did:key; absent when the registry reads no chain. */
|
|
107
|
+
export type Erc8004Checker = (link: Erc8004Link, didKey: string) => Promise<Erc8004Check>;
|
|
108
|
+
/** The registry's table, beside the portal's own. */
|
|
109
|
+
export declare class RegistryStore {
|
|
110
|
+
private readonly client;
|
|
111
|
+
private readonly t;
|
|
112
|
+
private ready;
|
|
113
|
+
private readonly registryUrl;
|
|
114
|
+
/** `registryUrl` is what a registration's proof names */
|
|
115
|
+
constructor(client: PostgresLike, registryUrl: string, prefix?: string);
|
|
116
|
+
private init;
|
|
117
|
+
private static row;
|
|
118
|
+
register(owner: string, raw: unknown, now?: number, erc8004?: Erc8004Checker): Promise<AgentEntry>;
|
|
119
|
+
get(id: string): Promise<AgentEntry | null>;
|
|
120
|
+
list(owner: string): Promise<AgentEntry[]>;
|
|
121
|
+
/** Changes an active agent of this owner: any of name, contact, capabilities, key, expiry, version, endpoints, ERC-8004 link. Null when the owner has no such active agent. */
|
|
122
|
+
update(owner: string, id: string, raw: unknown, now?: number, erc8004?: Erc8004Checker): Promise<AgentEntry | null>;
|
|
123
|
+
/**
|
|
124
|
+
* Active agents, by id, that hold `capability` (and belong to `owner`) when given: at most `limit` of them, after the
|
|
125
|
+
* id `after`. What the registry's public search serves; revoked and expired agents are not listed.
|
|
126
|
+
*/
|
|
127
|
+
search(o: {
|
|
128
|
+
capability?: string;
|
|
129
|
+
owner?: string;
|
|
130
|
+
after?: string;
|
|
131
|
+
limit?: number;
|
|
132
|
+
}, now?: number): Promise<{
|
|
133
|
+
agents: AgentEntry[];
|
|
134
|
+
next: string | null;
|
|
135
|
+
}>;
|
|
136
|
+
/**
|
|
137
|
+
* Records a later check of an agent's standing link: the fresh result, or the error beside the last good one. `checked`
|
|
138
|
+
* is the key and the link that were checked. The result is stored only while the row still names them: a check that
|
|
139
|
+
* finishes after the owner changed the link or rotated the key would otherwise write over the new link. Returns the
|
|
140
|
+
* row as it is.
|
|
141
|
+
*/
|
|
142
|
+
recordErc8004(id: string, checked: {
|
|
143
|
+
agent: string;
|
|
144
|
+
link: Erc8004Link;
|
|
145
|
+
}, r: Erc8004Check, now?: number): Promise<AgentEntry | null>;
|
|
146
|
+
/** Revokes an agent of this owner for good: the registry issues it no more passports. False when there is none to revoke. */
|
|
147
|
+
revoke(owner: string, id: string, now?: number): Promise<boolean>;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Signs a passport for an active agent. It lives `passportSeconds`, never past the registration's expiry, and carries
|
|
151
|
+
* `erc8004` when given (the link as last checked). Throws when the agent is revoked or expired.
|
|
152
|
+
*/
|
|
153
|
+
export declare function issuePassport(signer: Signer, registryUrl: string, e: AgentEntry, passportSeconds?: number, now?: number, erc8004?: Erc8004Checked | null): Promise<Envelope>;
|
|
154
|
+
/** The registry's key document, served at REGISTRY_DOCUMENT_PATH. */
|
|
155
|
+
export declare function registryDocument(signer: Signer, registryUrl: string, passportSeconds: number, erc8004Chains?: string[]): Promise<{
|
|
156
|
+
registry: string;
|
|
157
|
+
/** the chain ids whose ERC-8004 registries it checks links against */
|
|
158
|
+
erc8004Chains: string[];
|
|
159
|
+
passportType: string;
|
|
160
|
+
passportHeader: string;
|
|
161
|
+
passportSeconds: number;
|
|
162
|
+
agents: string;
|
|
163
|
+
keys: {
|
|
164
|
+
keyid: string;
|
|
165
|
+
alg: "ed25519";
|
|
166
|
+
publicKeyPem: string;
|
|
167
|
+
validFrom: string;
|
|
168
|
+
validTo?: string;
|
|
169
|
+
}[];
|
|
170
|
+
}>;
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
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, AGENT_VERSION, CAPABILITY, DEFAULT_PASSPORT_SECONDS, DID_KEY, EndpointSchema, MAX_ENDPOINT_CHARS, MAX_PASSPORT_HEADER, PASSPORT_HEADER, PASSPORT_TYPE, passportHeader, 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
|
+
/** how many past versions an entry keeps; the oldest go first */
|
|
34
|
+
export const MAX_AGENT_HISTORY = 100;
|
|
35
|
+
/** The ERC-8004 link a passport may carry: one whose last check succeeded within `recheckSeconds`. */
|
|
36
|
+
export function freshErc8004(e, recheckSeconds, now = Date.now()) {
|
|
37
|
+
const l = e.erc8004;
|
|
38
|
+
return l && !l.error && now - Date.parse(l.checkedAt) <= recheckSeconds * 1000 ? l : null;
|
|
39
|
+
}
|
|
40
|
+
export const agentStatus = (e, now = Date.now()) => (e.revokedAt ? "revoked" : Date.parse(e.expiresAt) <= now ? "expired" : "active");
|
|
41
|
+
/** What the registry publishes about an agent: the entry, its status, and its key as a JWK. */
|
|
42
|
+
export function publicEntry(e, now = Date.now()) {
|
|
43
|
+
const x = publicKeyFromDidKey(e.agent).publicKey.export({ format: "jwk" }).x;
|
|
44
|
+
return {
|
|
45
|
+
id: e.id,
|
|
46
|
+
name: e.name,
|
|
47
|
+
owner: e.owner,
|
|
48
|
+
contact: e.contact,
|
|
49
|
+
capabilities: e.capabilities,
|
|
50
|
+
agent: e.agent,
|
|
51
|
+
keys: [{ kty: "OKP", crv: "Ed25519", x, kid: e.agent, exp: Math.floor(Date.parse(e.expiresAt) / 1000) }],
|
|
52
|
+
createdAt: e.createdAt,
|
|
53
|
+
expiresAt: e.expiresAt,
|
|
54
|
+
status: agentStatus(e, now),
|
|
55
|
+
version: e.version ?? null,
|
|
56
|
+
versionSince: e.versionSince ?? e.createdAt,
|
|
57
|
+
/** the version this one replaced, when it replaced one */
|
|
58
|
+
replaces: e.history?.[0]?.version ?? null,
|
|
59
|
+
endpoints: e.endpoints ?? [],
|
|
60
|
+
history: e.history ?? [],
|
|
61
|
+
erc8004: e.erc8004 ?? null,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** A request to register or change an agent, checked; throws a message fit for the caller. */
|
|
65
|
+
export const AgentInputSchema = z.object({
|
|
66
|
+
name: text(100),
|
|
67
|
+
contact: text(200),
|
|
68
|
+
capabilities: z.array(z.string().regex(CAPABILITY, { message: "a capability is lowercase letters, digits, and . _ : -, at most 64 characters" })).max(32).optional(),
|
|
69
|
+
agent: z.string().regex(DID_KEY, { message: "the agent's key is an Ed25519 did:key (did:key:z6Mk...)" }),
|
|
70
|
+
/** the agent key's signature over `registrationMessage`, base64url: needed to register a key, and to change to a new one */
|
|
71
|
+
proof: z.string().regex(/^[A-Za-z0-9_-]{86}$/, { message: "proof is the agent key's Ed25519 signature over the registration message, base64url" }).optional(),
|
|
72
|
+
expiresAt: z.iso.datetime({ offset: true }),
|
|
73
|
+
/** the agent's version, MAJOR.MINOR.PATCH, or null for none; a change is recorded in the entry's history */
|
|
74
|
+
version: z.string().regex(AGENT_VERSION, { message: "version is MAJOR.MINOR.PATCH, numbers only" }).nullable().optional(),
|
|
75
|
+
/** the tool endpoints the agent says it calls: host names or https/wss URLs, shown to sites as a claim */
|
|
76
|
+
endpoints: z.array(EndpointSchema).max(32).refine((l) => l.reduce((n, e) => n + e.length, 0) <= MAX_ENDPOINT_CHARS, { message: `the endpoints take at most ${MAX_ENDPOINT_CHARS} characters together, so that a door can read the passport` }).optional(),
|
|
77
|
+
/** link an ERC-8004 identity (checked against the chain before it is stored), or null to unlink */
|
|
78
|
+
erc8004: Erc8004LinkSchema.nullable().optional(),
|
|
79
|
+
});
|
|
80
|
+
export class RegistryInputError extends Error {
|
|
81
|
+
}
|
|
82
|
+
async function checkedLink(checker, link, didKey) {
|
|
83
|
+
if (!checker)
|
|
84
|
+
throw new RegistryInputError("erc8004: this registry reads no ERC-8004 registry");
|
|
85
|
+
const r = await checker(link, didKey);
|
|
86
|
+
if (!r.ok)
|
|
87
|
+
throw new RegistryInputError(`erc8004: ${r.error}`);
|
|
88
|
+
return r.link;
|
|
89
|
+
}
|
|
90
|
+
function checkProof(registryUrl, owner, didKey, proof) {
|
|
91
|
+
if (!proof)
|
|
92
|
+
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)");
|
|
93
|
+
if (!edVerify(null, registrationMessage(registryUrl, owner, didKey), publicKeyFromDidKey(didKey).publicKey, Buffer.from(proof, "base64url")))
|
|
94
|
+
throw new RegistryInputError(`proof: the signature does not verify with ${didKey} over the registration message for this registry and owner`);
|
|
95
|
+
}
|
|
96
|
+
/** Postgres refused a row that breaks the one-live-agent-per-key index. */
|
|
97
|
+
const keyTaken = (e) => !!e && typeof e === "object" && e.code === "23505";
|
|
98
|
+
const TAKEN = "agent: this key is already registered to an agent; each agent has its own key";
|
|
99
|
+
function checkInput(raw, partial, now) {
|
|
100
|
+
const schema = partial ? AgentInputSchema.partial() : AgentInputSchema;
|
|
101
|
+
const r = schema.safeParse(raw);
|
|
102
|
+
if (!r.success)
|
|
103
|
+
throw new RegistryInputError(r.error.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
|
|
104
|
+
const v = r.data;
|
|
105
|
+
if (v.agent) {
|
|
106
|
+
try {
|
|
107
|
+
publicKeyFromDidKey(v.agent);
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
throw new RegistryInputError(`agent: ${e instanceof Error ? e.message : String(e)}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (v.expiresAt) {
|
|
114
|
+
const t = Date.parse(v.expiresAt);
|
|
115
|
+
if (t <= now)
|
|
116
|
+
throw new RegistryInputError("expiresAt: the registration must expire in the future");
|
|
117
|
+
if (t > now + MAX_REGISTRATION_DAYS * 86_400_000)
|
|
118
|
+
throw new RegistryInputError(`expiresAt: a registration lasts at most ${MAX_REGISTRATION_DAYS} days; renew it before then`);
|
|
119
|
+
}
|
|
120
|
+
if (v.capabilities)
|
|
121
|
+
v.capabilities = [...new Set(v.capabilities)].sort();
|
|
122
|
+
return v;
|
|
123
|
+
}
|
|
124
|
+
/** The registry's table, beside the portal's own. */
|
|
125
|
+
export class RegistryStore {
|
|
126
|
+
client;
|
|
127
|
+
t;
|
|
128
|
+
ready = null;
|
|
129
|
+
registryUrl;
|
|
130
|
+
/** `registryUrl` is what a registration's proof names */
|
|
131
|
+
constructor(client, registryUrl, prefix = "portal_") {
|
|
132
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(prefix))
|
|
133
|
+
throw new Error(`invalid table prefix ${prefix}`);
|
|
134
|
+
this.client = client;
|
|
135
|
+
this.registryUrl = registryUrl;
|
|
136
|
+
this.t = `${prefix}agents`;
|
|
137
|
+
}
|
|
138
|
+
init() {
|
|
139
|
+
this.ready ??= (async () => {
|
|
140
|
+
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)`);
|
|
141
|
+
await this.client.query(`CREATE INDEX IF NOT EXISTS ${this.t}_owner ON ${this.t} (owner)`);
|
|
142
|
+
// one live agent per key, held by the database so that two registrations at once cannot both pass
|
|
143
|
+
await this.client.query(`CREATE UNIQUE INDEX IF NOT EXISTS ${this.t}_live_key ON ${this.t} (agent) WHERE revoked_at IS NULL`);
|
|
144
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS erc8004 TEXT`);
|
|
145
|
+
await this.client.query(`CREATE INDEX IF NOT EXISTS ${this.t}_capabilities ON ${this.t} USING GIN (capabilities)`);
|
|
146
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS agent_version TEXT`);
|
|
147
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS version_since TIMESTAMPTZ`);
|
|
148
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS endpoints TEXT[] NOT NULL DEFAULT '{}'`);
|
|
149
|
+
await this.client.query(`ALTER TABLE ${this.t} ADD COLUMN IF NOT EXISTS history TEXT`);
|
|
150
|
+
// a row from before these columns starts its first stretch at its registration, to the millisecond, as the entry
|
|
151
|
+
// reads it: the guard in update compares the stored value with the one it read, and NULL would never match
|
|
152
|
+
await this.client.query(`UPDATE ${this.t} SET version_since = date_trunc('milliseconds', created_at) WHERE version_since IS NULL`);
|
|
153
|
+
})();
|
|
154
|
+
return this.ready;
|
|
155
|
+
}
|
|
156
|
+
static row(r) {
|
|
157
|
+
const iso = (v) => (v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString());
|
|
158
|
+
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, version: r.agent_version ? String(r.agent_version) : null, versionSince: iso(r.version_since ?? r.created_at), endpoints: r.endpoints ?? [], history: r.history ? JSON.parse(String(r.history)) : [], erc8004: r.erc8004 ? JSON.parse(String(r.erc8004)) : null };
|
|
159
|
+
}
|
|
160
|
+
async register(owner, raw, now = Date.now(), erc8004) {
|
|
161
|
+
await this.init();
|
|
162
|
+
const v = checkInput(raw, false, now);
|
|
163
|
+
checkProof(this.registryUrl, owner, v.agent, v.proof);
|
|
164
|
+
const link = v.erc8004 ? await checkedLink(erc8004, v.erc8004, v.agent) : null;
|
|
165
|
+
const capabilities = v.capabilities ?? [];
|
|
166
|
+
const id = `agt_${randomBytes(8).toString("hex")}`;
|
|
167
|
+
try {
|
|
168
|
+
// the owner's lock makes the count and the insert one step, so registrations at once cannot pass the cap together
|
|
169
|
+
return await transaction(this.client, async (q) => {
|
|
170
|
+
await q("SELECT pg_advisory_xact_lock(hashtext($1))", [`${this.t}:${owner}`]);
|
|
171
|
+
const { rows: count } = await q(`SELECT count(*)::int AS n FROM ${this.t} WHERE owner = $1 AND revoked_at IS NULL`, [owner]);
|
|
172
|
+
if (Number(count[0].n) >= MAX_AGENTS_PER_OWNER)
|
|
173
|
+
throw new RegistryInputError(`an owner registers at most ${MAX_AGENTS_PER_OWNER} agents; revoke one first`);
|
|
174
|
+
const { rows } = await q(`INSERT INTO ${this.t} (id, owner, name, contact, capabilities, agent, created_at, expires_at, erc8004, agent_version, version_since, endpoints, history) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $7, $11, '[]') RETURNING *`, [id, owner, v.name, v.contact, capabilities, v.agent, new Date(now).toISOString(), v.expiresAt, link ? JSON.stringify(link) : null, v.version ?? null, v.endpoints ?? []]);
|
|
175
|
+
return RegistryStore.row(rows[0]);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
catch (e) {
|
|
179
|
+
if (keyTaken(e))
|
|
180
|
+
throw new RegistryInputError(TAKEN);
|
|
181
|
+
throw e;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async get(id) {
|
|
185
|
+
if (!AGENT_ID.test(id))
|
|
186
|
+
return null;
|
|
187
|
+
await this.init();
|
|
188
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE id = $1`, [id]);
|
|
189
|
+
return rows[0] ? RegistryStore.row(rows[0]) : null;
|
|
190
|
+
}
|
|
191
|
+
async list(owner) {
|
|
192
|
+
await this.init();
|
|
193
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE owner = $1 ORDER BY created_at, id`, [owner]);
|
|
194
|
+
return rows.map((r) => RegistryStore.row(r));
|
|
195
|
+
}
|
|
196
|
+
/** Changes an active agent of this owner: any of name, contact, capabilities, key, expiry, version, endpoints, ERC-8004 link. Null when the owner has no such active agent. */
|
|
197
|
+
async update(owner, id, raw, now = Date.now(), erc8004) {
|
|
198
|
+
await this.init();
|
|
199
|
+
const v = checkInput(raw, true, now);
|
|
200
|
+
if (Object.keys(v).filter((k) => k !== "proof").length === 0)
|
|
201
|
+
throw new RegistryInputError("nothing to change: give name, contact, capabilities, agent, expiresAt, version, endpoints, or erc8004");
|
|
202
|
+
const current = await this.get(id);
|
|
203
|
+
if (!current || current.owner !== owner || agentStatus(current, now) === "revoked")
|
|
204
|
+
return null;
|
|
205
|
+
if (v.agent && v.agent !== current.agent)
|
|
206
|
+
checkProof(this.registryUrl, owner, v.agent, v.proof);
|
|
207
|
+
const { proof: _proof, erc8004: wanted, ...fields } = v;
|
|
208
|
+
const next = { ...current, ...fields };
|
|
209
|
+
// a new version or a new key starts a new stretch of the entry's history; the one it replaces is kept, with its dates
|
|
210
|
+
const moved = (v.version !== undefined && v.version !== current.version) || next.agent !== current.agent;
|
|
211
|
+
const past = current.history ?? [];
|
|
212
|
+
const history = moved ? [{ version: current.version ?? null, agent: current.agent, from: current.versionSince ?? current.createdAt, to: new Date(now).toISOString() }, ...past].slice(0, MAX_AGENT_HISTORY) : past;
|
|
213
|
+
const since = moved ? new Date(now).toISOString() : (current.versionSince ?? current.createdAt);
|
|
214
|
+
// a link stays only while the registration file lists the agent's key: a new key checks the standing link again
|
|
215
|
+
const target = wanted === undefined ? (current.erc8004 && next.agent !== current.agent ? current.erc8004 : undefined) : wanted;
|
|
216
|
+
const link = target === undefined ? current.erc8004 : target === null ? null : await checkedLink(erc8004, target, next.agent);
|
|
217
|
+
try {
|
|
218
|
+
// the version and key read above must still be the row's, so two changes at once cannot both write one stretch of history
|
|
219
|
+
const { rows } = await this.client.query(`UPDATE ${this.t} SET name = $3, contact = $4, capabilities = $5, agent = $6, expires_at = $7, erc8004 = $8, agent_version = $9, version_since = $10, endpoints = $11, history = $12 WHERE id = $1 AND owner = $2 AND revoked_at IS NULL AND agent = $13 AND agent_version IS NOT DISTINCT FROM $14 AND version_since IS NOT DISTINCT FROM $15 RETURNING *`, [id, owner, next.name, next.contact, next.capabilities, next.agent, next.expiresAt, link ? JSON.stringify(link) : null, next.version ?? null, since, next.endpoints ?? [], JSON.stringify(history), current.agent, current.version ?? null, current.versionSince ?? null]);
|
|
220
|
+
if (rows[0])
|
|
221
|
+
return RegistryStore.row(rows[0]);
|
|
222
|
+
// the row was there when read: if it still is, another change moved its version or key in between, and this one, which read the old ones, is not written
|
|
223
|
+
const after = await this.get(id);
|
|
224
|
+
if (after && after.owner === owner && agentStatus(after, now) !== "revoked")
|
|
225
|
+
throw new RegistryInputError("the agent's version or key changed while this change was made; read the entry again and retry");
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
if (keyTaken(e))
|
|
230
|
+
throw new RegistryInputError(TAKEN);
|
|
231
|
+
throw e;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Active agents, by id, that hold `capability` (and belong to `owner`) when given: at most `limit` of them, after the
|
|
236
|
+
* id `after`. What the registry's public search serves; revoked and expired agents are not listed.
|
|
237
|
+
*/
|
|
238
|
+
async search(o, now = Date.now()) {
|
|
239
|
+
await this.init();
|
|
240
|
+
if (o.capability !== undefined && !CAPABILITY.test(o.capability))
|
|
241
|
+
throw new RegistryInputError("capability: lowercase letters, digits, and . _ : -, at most 64 characters");
|
|
242
|
+
if (o.owner !== undefined && !/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(o.owner))
|
|
243
|
+
throw new RegistryInputError("owner: a tenant id");
|
|
244
|
+
if (o.after !== undefined && !AGENT_ID.test(o.after))
|
|
245
|
+
throw new RegistryInputError("after: an agent id, the next value of the last page");
|
|
246
|
+
const limit = Math.min(Math.max(Math.trunc(o.limit ?? 50), 1), 100);
|
|
247
|
+
const where = ["revoked_at IS NULL", "expires_at > $1"];
|
|
248
|
+
const values = [new Date(now).toISOString()];
|
|
249
|
+
const param = (v) => { values.push(v); return `$${values.length}`; };
|
|
250
|
+
if (o.capability !== undefined)
|
|
251
|
+
where.push(`capabilities @> ${param([o.capability])}::text[]`);
|
|
252
|
+
if (o.owner !== undefined)
|
|
253
|
+
where.push(`owner = ${param(o.owner)}`);
|
|
254
|
+
if (o.after !== undefined)
|
|
255
|
+
where.push(`id > ${param(o.after)}`);
|
|
256
|
+
const { rows } = await this.client.query(`SELECT * FROM ${this.t} WHERE ${where.join(" AND ")} ORDER BY id LIMIT ${param(limit + 1)}`, values);
|
|
257
|
+
const agents = rows.slice(0, limit).map((r) => RegistryStore.row(r));
|
|
258
|
+
return { agents, next: rows.length > limit ? agents.at(-1).id : null };
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Records a later check of an agent's standing link: the fresh result, or the error beside the last good one. `checked`
|
|
262
|
+
* is the key and the link that were checked. The result is stored only while the row still names them: a check that
|
|
263
|
+
* finishes after the owner changed the link or rotated the key would otherwise write over the new link. Returns the
|
|
264
|
+
* row as it is.
|
|
265
|
+
*/
|
|
266
|
+
async recordErc8004(id, checked, r, now = Date.now()) {
|
|
267
|
+
await this.init();
|
|
268
|
+
const current = await this.get(id);
|
|
269
|
+
if (!current?.erc8004)
|
|
270
|
+
return current;
|
|
271
|
+
if (current.agent !== checked.agent || current.erc8004.agentRegistry !== checked.link.agentRegistry || current.erc8004.agentId !== checked.link.agentId)
|
|
272
|
+
return current;
|
|
273
|
+
const link = r.ok ? r.link : { ...current.erc8004, error: r.error.slice(0, 300), errorAt: new Date(now).toISOString() };
|
|
274
|
+
// the same comparison in the write, so a change between the read and the write is not overwritten either
|
|
275
|
+
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]);
|
|
276
|
+
return rows[0] ? RegistryStore.row(rows[0]) : await this.get(id);
|
|
277
|
+
}
|
|
278
|
+
/** Revokes an agent of this owner for good: the registry issues it no more passports. False when there is none to revoke. */
|
|
279
|
+
async revoke(owner, id, now = Date.now()) {
|
|
280
|
+
await this.init();
|
|
281
|
+
if (!AGENT_ID.test(id))
|
|
282
|
+
return false;
|
|
283
|
+
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()]);
|
|
284
|
+
return rows.length > 0;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Signs a passport for an active agent. It lives `passportSeconds`, never past the registration's expiry, and carries
|
|
289
|
+
* `erc8004` when given (the link as last checked). Throws when the agent is revoked or expired.
|
|
290
|
+
*/
|
|
291
|
+
export async function issuePassport(signer, registryUrl, e, passportSeconds = DEFAULT_PASSPORT_SECONDS, now = Date.now(), erc8004) {
|
|
292
|
+
const status = agentStatus(e, now);
|
|
293
|
+
if (status !== "active")
|
|
294
|
+
throw new RegistryInputError(`the agent ${e.id} is ${status}; the registry issues it no passport`);
|
|
295
|
+
if (!e.agent.startsWith(DID_KEY_PREFIX))
|
|
296
|
+
throw new Error("the agent's key is not a did:key");
|
|
297
|
+
const expires = Math.min(now + passportSeconds * 1000, Date.parse(e.expiresAt));
|
|
298
|
+
const passport = PassportSchema.parse({
|
|
299
|
+
version: "0.1",
|
|
300
|
+
registry: registryUrl,
|
|
301
|
+
agentId: e.id,
|
|
302
|
+
agent: e.agent,
|
|
303
|
+
name: e.name,
|
|
304
|
+
owner: e.owner,
|
|
305
|
+
contact: e.contact,
|
|
306
|
+
capabilities: e.capabilities,
|
|
307
|
+
...(e.version ? { agentVersion: e.version } : {}),
|
|
308
|
+
...(e.endpoints?.length ? { endpoints: e.endpoints } : {}),
|
|
309
|
+
...(erc8004 ? { erc8004: { agentRegistry: erc8004.agentRegistry, agentId: erc8004.agentId, owner: erc8004.owner, block: erc8004.block } } : {}),
|
|
310
|
+
issuedAt: new Date(now).toISOString(),
|
|
311
|
+
expiresAt: new Date(expires).toISOString(),
|
|
312
|
+
});
|
|
313
|
+
const env = await signer.sign(PASSPORT_TYPE, passport);
|
|
314
|
+
const size = passportHeader(env).length;
|
|
315
|
+
if (size > MAX_PASSPORT_HEADER)
|
|
316
|
+
throw new RegistryInputError(`the passport would be ${size} characters, more than the ${MAX_PASSPORT_HEADER} a door reads; declare fewer or shorter endpoints or capabilities`);
|
|
317
|
+
return env;
|
|
318
|
+
}
|
|
319
|
+
/** The registry's key document, served at REGISTRY_DOCUMENT_PATH. */
|
|
320
|
+
export async function registryDocument(signer, registryUrl, passportSeconds, erc8004Chains = []) {
|
|
321
|
+
return {
|
|
322
|
+
registry: registryUrl,
|
|
323
|
+
/** the chain ids whose ERC-8004 registries it checks links against */
|
|
324
|
+
erc8004Chains,
|
|
325
|
+
passportType: PASSPORT_TYPE,
|
|
326
|
+
passportHeader: PASSPORT_HEADER,
|
|
327
|
+
passportSeconds,
|
|
328
|
+
agents: `${registryUrl}registry/agents/`,
|
|
329
|
+
keys: (await signer.keys()).keys,
|
|
330
|
+
};
|
|
331
|
+
}
|