@zurchin/sdk 0.0.0 → 2.16.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/CHANGELOG.md +212 -0
- package/LICENSE +55 -0
- package/README.md +189 -1
- package/dist/auth.d.ts +152 -0
- package/dist/auth.js +189 -0
- package/dist/credential.d.ts +96 -0
- package/dist/credential.js +297 -0
- package/dist/declared-agents.d.ts +9 -0
- package/dist/declared-agents.js +46 -0
- package/dist/index.d.ts +1187 -0
- package/dist/index.js +714 -0
- package/dist/next.d.ts +104 -0
- package/dist/next.js +300 -0
- package/dist/node.d.ts +139 -0
- package/dist/node.js +402 -0
- package/dist/verdict.d.ts +57 -0
- package/dist/verdict.js +116 -0
- package/package.json +66 -4
package/dist/auth.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pidgeon Auth: Sign in with Pidgeon (https://pidgeon.ai).
|
|
3
|
+
*
|
|
4
|
+
* People sign in to your site with any OpenID Connect library: point it at
|
|
5
|
+
* the issuer `https://pidgeon.ai` with the client id and secret you
|
|
6
|
+
* registered, and check the ID token with `verifyIdToken`.
|
|
7
|
+
*
|
|
8
|
+
* Agents sign in with no person present: the agent calls `signInAsAgent`,
|
|
9
|
+
* which exchanges a request signed with its Pidgeon key for an ID token for
|
|
10
|
+
* your site. It then sends that token with every request it signs
|
|
11
|
+
* (`Authorization: Bearer <id_token>`), and `verifyAgentSignIn` checks both:
|
|
12
|
+
* the token is Pidgeon's and for you, and the request is signed with the key
|
|
13
|
+
* the token names (`cnf`), so a copied token is useless on its own.
|
|
14
|
+
*/
|
|
15
|
+
import { createLocalJWKSet, createRemoteJWKSet, jwtVerify } from 'jose';
|
|
16
|
+
import { DEFAULT_BASE_URL } from "./index.js";
|
|
17
|
+
import { directoryUrl, keyIdOf, sameDirectory, signAgentRequest, verifyAgentRequest, } from "./credential.js";
|
|
18
|
+
/** The issuer is the API's host: it moves with `DEFAULT_BASE_URL`. */
|
|
19
|
+
export const DEFAULT_ISSUER = DEFAULT_BASE_URL;
|
|
20
|
+
export const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
|
21
|
+
export const AGENT_KEY_TOKEN = 'urn:pidgeon:params:oauth:token-type:agent-key';
|
|
22
|
+
export const ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token';
|
|
23
|
+
export const ID_JAG = 'urn:ietf:params:oauth:token-type:id-jag';
|
|
24
|
+
export class SignInError extends Error {
|
|
25
|
+
reason;
|
|
26
|
+
constructor(reason, message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.reason = reason;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const trim = (issuer) => issuer.replace(/\/+$/, '');
|
|
32
|
+
/**
|
|
33
|
+
* The agent's side: an ID token for one site, for ten minutes. `site` is the
|
|
34
|
+
* site's client id (it tells you, or puts it on its sign-in page); `key` and
|
|
35
|
+
* `directory` are the agent's, as for any signed request.
|
|
36
|
+
*/
|
|
37
|
+
export async function signInAsAgent(options) {
|
|
38
|
+
const url = `${trim(options.issuer ?? DEFAULT_ISSUER)}/oauth/token`;
|
|
39
|
+
const signature = await signAgentRequest(new Request(url, { method: 'POST' }), {
|
|
40
|
+
privateJwk: options.key.privateJwk,
|
|
41
|
+
directory: options.directory,
|
|
42
|
+
});
|
|
43
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { ...signature, 'content-type': 'application/x-www-form-urlencoded' },
|
|
46
|
+
body: new URLSearchParams({
|
|
47
|
+
grant_type: TOKEN_EXCHANGE,
|
|
48
|
+
subject_token: options.key.kid,
|
|
49
|
+
subject_token_type: AGENT_KEY_TOKEN,
|
|
50
|
+
audience: options.site,
|
|
51
|
+
}).toString(),
|
|
52
|
+
});
|
|
53
|
+
const body = (await response.json().catch(() => ({})));
|
|
54
|
+
if (!response.ok || !body.access_token) {
|
|
55
|
+
throw new SignInError('refused', body.error_description ?? body.error ?? `HTTP ${response.status}`);
|
|
56
|
+
}
|
|
57
|
+
return { idToken: body.access_token, expiresIn: body.expires_in ?? 600 };
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The agent's side, for an MCP server whose authorization server trusts
|
|
61
|
+
* Pidgeon (MCP Enterprise-Managed Authorization): an ID-JAG, five minutes,
|
|
62
|
+
* to present there as a JWT bearer grant. `audience` is that authorization
|
|
63
|
+
* server's issuer, `clientId` your client id there, `resource` the MCP
|
|
64
|
+
* server's resource identifier.
|
|
65
|
+
*/
|
|
66
|
+
export async function requestIdJag(options) {
|
|
67
|
+
const url = `${trim(options.issuer ?? DEFAULT_ISSUER)}/oauth/token`;
|
|
68
|
+
const signature = await signAgentRequest(new Request(url, { method: 'POST' }), {
|
|
69
|
+
privateJwk: options.key.privateJwk,
|
|
70
|
+
directory: options.directory,
|
|
71
|
+
});
|
|
72
|
+
const form = new URLSearchParams({
|
|
73
|
+
grant_type: TOKEN_EXCHANGE,
|
|
74
|
+
requested_token_type: ID_JAG,
|
|
75
|
+
subject_token: options.key.kid,
|
|
76
|
+
subject_token_type: AGENT_KEY_TOKEN,
|
|
77
|
+
audience: options.audience,
|
|
78
|
+
client_id: options.clientId,
|
|
79
|
+
});
|
|
80
|
+
if (options.resource)
|
|
81
|
+
form.set('resource', options.resource);
|
|
82
|
+
if (options.scope)
|
|
83
|
+
form.set('scope', options.scope);
|
|
84
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
85
|
+
method: 'POST',
|
|
86
|
+
headers: { ...signature, 'content-type': 'application/x-www-form-urlencoded' },
|
|
87
|
+
body: form.toString(),
|
|
88
|
+
});
|
|
89
|
+
const body = (await response.json().catch(() => ({})));
|
|
90
|
+
if (!response.ok || !body.access_token) {
|
|
91
|
+
throw new SignInError('refused', body.error_description ?? body.error ?? `HTTP ${response.status}`);
|
|
92
|
+
}
|
|
93
|
+
return { idJag: body.access_token, expiresIn: body.expires_in ?? 300 };
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The site's side, for any ID token from Pidgeon (a person's or an agent's):
|
|
97
|
+
* signed with Pidgeon's published key, issued by Pidgeon, for your client
|
|
98
|
+
* id, not expired, and with your `nonce` if you sent one.
|
|
99
|
+
*/
|
|
100
|
+
export async function verifyIdToken(idToken, options) {
|
|
101
|
+
const issuer = trim(options.issuer ?? DEFAULT_ISSUER);
|
|
102
|
+
const keys = options.jwks
|
|
103
|
+
? createLocalJWKSet(options.jwks)
|
|
104
|
+
: remoteKeys(`${issuer}/.well-known/jwks.json`);
|
|
105
|
+
try {
|
|
106
|
+
const { payload } = await jwtVerify(idToken, keys, {
|
|
107
|
+
issuer,
|
|
108
|
+
audience: options.clientId,
|
|
109
|
+
algorithms: ['RS256'],
|
|
110
|
+
// An ID-JAG (typ oauth-id-jag+jwt) shares the key and the issuer; it is never a sign-in.
|
|
111
|
+
typ: 'JWT',
|
|
112
|
+
});
|
|
113
|
+
if (options.nonce !== undefined && payload.nonce !== options.nonce) {
|
|
114
|
+
throw new Error('The nonce does not match.');
|
|
115
|
+
}
|
|
116
|
+
return payload;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
throw new SignInError('invalid_token', error instanceof Error ? error.message : String(error));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const remote = new Map();
|
|
123
|
+
function remoteKeys(url) {
|
|
124
|
+
let keys = remote.get(url);
|
|
125
|
+
if (!keys) {
|
|
126
|
+
keys = createRemoteJWKSet(new URL(url));
|
|
127
|
+
remote.set(url, keys);
|
|
128
|
+
}
|
|
129
|
+
return keys;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The site's side, for an agent's request: the ID token in
|
|
133
|
+
* `Authorization: Bearer`, the request signed with the key that token names,
|
|
134
|
+
* and its `Signature-Agent` the agent's own directory. Answers who the agent
|
|
135
|
+
* is and who stands behind it.
|
|
136
|
+
*
|
|
137
|
+
* With `clientSecret` (your site's), a token issued under a mandate is also
|
|
138
|
+
* checked with Pidgeon (`/oauth/introspect`), so a mandate the person stopped
|
|
139
|
+
* is refused at once instead of when the token expires, up to ten minutes
|
|
140
|
+
* later. One request to Pidgeon per call, only for mandate tokens.
|
|
141
|
+
*/
|
|
142
|
+
export async function verifyAgentSignIn(request, options) {
|
|
143
|
+
const token = request.headers.get('authorization')?.match(/^Bearer\s+(\S+)$/)?.[1];
|
|
144
|
+
if (!token)
|
|
145
|
+
throw new SignInError('unsigned', 'Send the ID token as `Authorization: Bearer`.');
|
|
146
|
+
const claims = await verifyIdToken(token, options);
|
|
147
|
+
if (claims.kind !== 'agent' || !claims.cnf?.jwk) {
|
|
148
|
+
throw new SignInError('not_an_agent', 'This token is not an agent’s.');
|
|
149
|
+
}
|
|
150
|
+
const bound = claims.cnf.jwk;
|
|
151
|
+
const boundKid = await keyIdOf(bound);
|
|
152
|
+
const proof = await verifyAgentRequest(request, async (kid) => (kid === boundKid ? bound : null));
|
|
153
|
+
if (!proof.ok) {
|
|
154
|
+
switch (proof.reason) {
|
|
155
|
+
case 'unsigned':
|
|
156
|
+
throw new SignInError('unsigned', 'Sign the request with the key the token was issued to.');
|
|
157
|
+
case 'expired':
|
|
158
|
+
throw new SignInError('expired', 'The signature has expired, is over five minutes old, or is dated ahead. Sign the request again.');
|
|
159
|
+
case 'unknown_key':
|
|
160
|
+
throw new SignInError('wrong_key', 'The request must be signed with the key the token was issued to.');
|
|
161
|
+
default:
|
|
162
|
+
throw new SignInError('wrong_request', 'The signature does not match this request: sign it as it is sent (method, path and host).');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// Tokens from before `agent.directory` was a claim name the operator by its slug.
|
|
166
|
+
const directory = claims.agent?.directory ?? (claims.account?.slug ? directoryUrl(claims.account.slug) : null);
|
|
167
|
+
if (!directory || !sameDirectory(proof.directory, directory)) {
|
|
168
|
+
throw new SignInError('wrong_directory', `Signature-Agent must name the agent's own directory${directory ? `, ${directory}` : ''}.`);
|
|
169
|
+
}
|
|
170
|
+
if (claims.mandate && options.clientSecret !== undefined) {
|
|
171
|
+
const url = `${trim(options.issuer ?? DEFAULT_ISSUER)}/oauth/introspect`;
|
|
172
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
173
|
+
method: 'POST',
|
|
174
|
+
headers: {
|
|
175
|
+
authorization: `Basic ${btoa(`${encodeURIComponent(options.clientId)}:${encodeURIComponent(options.clientSecret)}`)}`,
|
|
176
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
177
|
+
},
|
|
178
|
+
body: new URLSearchParams({ token }).toString(),
|
|
179
|
+
});
|
|
180
|
+
const body = (await response.json().catch(() => ({})));
|
|
181
|
+
if (!response.ok) {
|
|
182
|
+
throw new SignInError('refused', `Pidgeon did not answer the mandate check (HTTP ${response.status}): check your client secret.`);
|
|
183
|
+
}
|
|
184
|
+
if (body.active !== true) {
|
|
185
|
+
throw new SignInError('mandate_ended', 'The mandate this token was issued under has been stopped or has run out.');
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return claims;
|
|
189
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** The public half of an agent's key, as published in its directory. */
|
|
2
|
+
export type PublicJwk = {
|
|
3
|
+
kty: 'OKP';
|
|
4
|
+
crv: 'Ed25519';
|
|
5
|
+
x: string;
|
|
6
|
+
};
|
|
7
|
+
/** Both halves. The private half never reaches Pidgeon. */
|
|
8
|
+
export type AgentKeyPair = {
|
|
9
|
+
kid: string;
|
|
10
|
+
publicJwk: PublicJwk;
|
|
11
|
+
privateJwk: JsonWebKey;
|
|
12
|
+
};
|
|
13
|
+
/** How long a signature lasts unless the agent asks for less. */
|
|
14
|
+
export declare const DEFAULT_LIFETIME_SECONDS = 60;
|
|
15
|
+
/**
|
|
16
|
+
* The longest a signature lasts, whatever the signer asks, and the oldest a
|
|
17
|
+
* verifier accepts, whatever its `expires` says: five minutes, so a captured
|
|
18
|
+
* request is soon useless. The draft's own
|
|
19
|
+
* ceiling, a day, left a copied request replayable at the same site all day.
|
|
20
|
+
*/
|
|
21
|
+
export declare const MAX_LIFETIME_SECONDS: number;
|
|
22
|
+
/**
|
|
23
|
+
* A fresh nonce: 64 random bytes, base64url (Web Bot Auth §4.2.2). A
|
|
24
|
+
* verifier that remembers nonces refuses the same signature twice.
|
|
25
|
+
*/
|
|
26
|
+
export declare function newNonce(): string;
|
|
27
|
+
/** An operator's directory: where its agents' public keys are published. */
|
|
28
|
+
export declare function directoryUrl(slug: string, host?: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Whether the directory a signature names (its `Signature-Agent`) is
|
|
31
|
+
* `directory`: the same origin, given bare or with the well-known path. A
|
|
32
|
+
* key's signature proves the key; this binds it to the operator whose
|
|
33
|
+
* directory publishes it, so a request cannot claim another operator's.
|
|
34
|
+
*/
|
|
35
|
+
export declare function sameDirectory(named: string | null | undefined, directory: string): boolean;
|
|
36
|
+
/** A key's id: its JWK SHA-256 thumbprint (RFC 7638), Web Bot Auth's `keyid`. */
|
|
37
|
+
export declare function keyIdOf(publicJwk: PublicJwk): Promise<string>;
|
|
38
|
+
/** Whether something is an Ed25519 public key, and only that: no private part. */
|
|
39
|
+
export declare function isPublicJwk(value: unknown): value is PublicJwk;
|
|
40
|
+
/** A new key pair, for an agent. Run where the agent runs: the CLI, the SDK. */
|
|
41
|
+
export declare function generateAgentKey(): Promise<AgentKeyPair>;
|
|
42
|
+
/**
|
|
43
|
+
* Sign a request as an agent: returns the headers to add. The request must
|
|
44
|
+
* not carry a Signature-Agent of its own; this sets it. Every signature has
|
|
45
|
+
* a fresh nonce, so sign again for each send, retries included; `nonce` is
|
|
46
|
+
* for tests that need the same bytes twice.
|
|
47
|
+
*/
|
|
48
|
+
export declare function signAgentRequest(request: Request, options: {
|
|
49
|
+
privateJwk: JsonWebKey;
|
|
50
|
+
directory: string;
|
|
51
|
+
lifetimeSeconds?: number;
|
|
52
|
+
now?: Date;
|
|
53
|
+
nonce?: string;
|
|
54
|
+
}): Promise<Record<string, string>>;
|
|
55
|
+
/** Why a request's credential was not accepted, in the API's words. */
|
|
56
|
+
export type Rejection = 'unsigned' | 'invalid' | 'unknown_key' | 'expired';
|
|
57
|
+
export type Verification = {
|
|
58
|
+
ok: true;
|
|
59
|
+
kid: string;
|
|
60
|
+
/** The directory the signature named and covered (its `Signature-Agent`), or null when it named none. */
|
|
61
|
+
directory: string | null;
|
|
62
|
+
created: Date;
|
|
63
|
+
expires: Date;
|
|
64
|
+
/** The signature's nonce, when it has one: remember it to refuse the same signature twice. */
|
|
65
|
+
nonce: string | null;
|
|
66
|
+
/** The signature itself, base64url: what to remember when it carries no nonce. */
|
|
67
|
+
signature: string;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
reason: Rejection;
|
|
71
|
+
kid?: string;
|
|
72
|
+
directory?: string | null;
|
|
73
|
+
detail: string;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* The directory a request's `Signature-Agent` names, read without checking
|
|
77
|
+
* anything: what a check records about a request it refused. Null when
|
|
78
|
+
* there is none; the header itself, cut short, when it cannot be read.
|
|
79
|
+
*/
|
|
80
|
+
export declare function signatureAgentOf(request: Request): string | null;
|
|
81
|
+
/**
|
|
82
|
+
* Check a request's agent signature, under Web Bot Auth as the working group
|
|
83
|
+
* wrote it (draft-ietf-webbotauth-httpsig-protocol-01 §5.2): Ed25519, tagged
|
|
84
|
+
* `web-bot-auth`, with `created`, `expires` and `keyid`, covering the bare
|
|
85
|
+
* `@authority` or `@target-uri`, and the `Signature-Agent` when there is one.
|
|
86
|
+
* `alg` and `nonce` are optional, as the draft and RFC 9421 make them, and a
|
|
87
|
+
* nonce of any length is remembered. On top of the draft, no signature
|
|
88
|
+
* verifies more than five minutes after it was made.
|
|
89
|
+
*
|
|
90
|
+
* `findKey` turns a key id, and the directory the signature names, into the
|
|
91
|
+
* public key to check it with, or null; whether that key is revoked, and its
|
|
92
|
+
* operator's reputation, are the caller's next questions.
|
|
93
|
+
*/
|
|
94
|
+
export declare function verifyAgentRequest(request: Request, findKey: (kid: string, directory: string | null) => Promise<PublicJwk | null>, options?: {
|
|
95
|
+
now?: Date;
|
|
96
|
+
}): Promise<Verification>;
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent credential: Web Bot Auth, unchanged.
|
|
3
|
+
*
|
|
4
|
+
* An agent signs each request with its Ed25519 key under HTTP Message
|
|
5
|
+
* Signatures (RFC 9421), tagged `web-bot-auth`, covering the request's
|
|
6
|
+
* authority, method, path and query and the `Signature-Agent` header, which points
|
|
7
|
+
* at its operator's directory on Pidgeon. Signing and verifying are
|
|
8
|
+
* Cloudflare's open-source `web-bot-auth`; this module fixes our choices on
|
|
9
|
+
* top of it and nothing more.
|
|
10
|
+
*
|
|
11
|
+
* Choices:
|
|
12
|
+
* - Ed25519 only, because Cloudflare accepts nothing else.
|
|
13
|
+
* - `Signature-Agent` in the string form (`"https://…"`), which Cloudflare
|
|
14
|
+
* requires today; the verifier accepts the working group's dictionary form
|
|
15
|
+
* too.
|
|
16
|
+
* - A minute's lifetime by default, so a captured request is useless soon.
|
|
17
|
+
* - A fresh nonce in every signature, so a verifier that remembers them
|
|
18
|
+
* accepts each signature once.
|
|
19
|
+
*/
|
|
20
|
+
import { verifySignature } from 'http-message-sig';
|
|
21
|
+
import { jwkToKeyID, parseSignatureAgentHeader, sign } from 'web-bot-auth';
|
|
22
|
+
import { signerFromJWK, verifierFromJWK } from 'web-bot-auth/crypto';
|
|
23
|
+
/** How long a signature lasts unless the agent asks for less. */
|
|
24
|
+
export const DEFAULT_LIFETIME_SECONDS = 60;
|
|
25
|
+
/**
|
|
26
|
+
* The longest a signature lasts, whatever the signer asks, and the oldest a
|
|
27
|
+
* verifier accepts, whatever its `expires` says: five minutes, so a captured
|
|
28
|
+
* request is soon useless. The draft's own
|
|
29
|
+
* ceiling, a day, left a copied request replayable at the same site all day.
|
|
30
|
+
*/
|
|
31
|
+
export const MAX_LIFETIME_SECONDS = 5 * 60;
|
|
32
|
+
/** How far an agent's clock may run ahead of the verifier's. */
|
|
33
|
+
const CLOCK_SKEW_SECONDS = 30;
|
|
34
|
+
/**
|
|
35
|
+
* What the signature covers beyond the authority and the Signature-Agent:
|
|
36
|
+
* the method, the path and the query. The query is covered when the URL has
|
|
37
|
+
* none too (its value is then `?`), so one cannot be added in transit.
|
|
38
|
+
*/
|
|
39
|
+
const COVERED = ['@method', '@path', '@query'];
|
|
40
|
+
/**
|
|
41
|
+
* A fresh nonce: 64 random bytes, base64url (Web Bot Auth §4.2.2). A
|
|
42
|
+
* verifier that remembers nonces refuses the same signature twice.
|
|
43
|
+
*/
|
|
44
|
+
export function newNonce() {
|
|
45
|
+
const bytes = new Uint8Array(64);
|
|
46
|
+
crypto.getRandomValues(bytes);
|
|
47
|
+
let binary = '';
|
|
48
|
+
for (const byte of bytes)
|
|
49
|
+
binary += String.fromCharCode(byte);
|
|
50
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
51
|
+
}
|
|
52
|
+
/** An operator's directory: where its agents' public keys are published. */
|
|
53
|
+
export function directoryUrl(slug, host = process.env.AGENTS_HOST ?? 'agents.pidgeon.ai') {
|
|
54
|
+
return `https://${slug}.${host}`;
|
|
55
|
+
}
|
|
56
|
+
const DIRECTORY_PATH = '/.well-known/http-message-signatures-directory';
|
|
57
|
+
/**
|
|
58
|
+
* Whether the directory a signature names (its `Signature-Agent`) is
|
|
59
|
+
* `directory`: the same origin, given bare or with the well-known path. A
|
|
60
|
+
* key's signature proves the key; this binds it to the operator whose
|
|
61
|
+
* directory publishes it, so a request cannot claim another operator's.
|
|
62
|
+
*/
|
|
63
|
+
export function sameDirectory(named, directory) {
|
|
64
|
+
if (!named)
|
|
65
|
+
return false;
|
|
66
|
+
try {
|
|
67
|
+
const a = new URL(named);
|
|
68
|
+
const b = new URL(directory);
|
|
69
|
+
const path = a.pathname.replace(/\/+$/, '');
|
|
70
|
+
return a.origin === b.origin && (path === '' || path === DIRECTORY_PATH) && !a.search;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** A key's id: its JWK SHA-256 thumbprint (RFC 7638), Web Bot Auth's `keyid`. */
|
|
77
|
+
export async function keyIdOf(publicJwk) {
|
|
78
|
+
return jwkToKeyID(publicJwk, (bytes) => crypto.subtle.digest('SHA-256', bytes), base64Url);
|
|
79
|
+
}
|
|
80
|
+
/** base64url without padding; in the browser too, where there is no Buffer (the dashboard makes keys there). */
|
|
81
|
+
function base64Url(buffer) {
|
|
82
|
+
let binary = '';
|
|
83
|
+
for (const byte of new Uint8Array(buffer))
|
|
84
|
+
binary += String.fromCharCode(byte);
|
|
85
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
86
|
+
}
|
|
87
|
+
/** Whether something is an Ed25519 public key, and only that: no private part. */
|
|
88
|
+
export function isPublicJwk(value) {
|
|
89
|
+
if (typeof value !== 'object' || value === null)
|
|
90
|
+
return false;
|
|
91
|
+
const jwk = value;
|
|
92
|
+
return (jwk.kty === 'OKP' &&
|
|
93
|
+
jwk.crv === 'Ed25519' &&
|
|
94
|
+
typeof jwk.x === 'string' &&
|
|
95
|
+
/^[A-Za-z0-9_-]{43}$/.test(jwk.x) &&
|
|
96
|
+
!('d' in jwk));
|
|
97
|
+
}
|
|
98
|
+
/** A new key pair, for an agent. Run where the agent runs: the CLI, the SDK. */
|
|
99
|
+
export async function generateAgentKey() {
|
|
100
|
+
const pair = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
|
|
101
|
+
'sign',
|
|
102
|
+
'verify',
|
|
103
|
+
]));
|
|
104
|
+
// Web Bot Auth wants an Ed25519 JWK's alg to be EdDSA or absent; Node writes "Ed25519".
|
|
105
|
+
const { alg: _alg, ...privateJwk } = await crypto.subtle.exportKey('jwk', pair.privateKey);
|
|
106
|
+
const exported = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
107
|
+
const publicJwk = { kty: 'OKP', crv: 'Ed25519', x: exported.x };
|
|
108
|
+
return { kid: await keyIdOf(publicJwk), publicJwk, privateJwk };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Sign a request as an agent: returns the headers to add. The request must
|
|
112
|
+
* not carry a Signature-Agent of its own; this sets it. Every signature has
|
|
113
|
+
* a fresh nonce, so sign again for each send, retries included; `nonce` is
|
|
114
|
+
* for tests that need the same bytes twice.
|
|
115
|
+
*/
|
|
116
|
+
export async function signAgentRequest(request, options) {
|
|
117
|
+
const now = options.now ?? new Date();
|
|
118
|
+
const lifetime = Math.min(options.lifetimeSeconds ?? DEFAULT_LIFETIME_SECONDS, MAX_LIFETIME_SECONDS);
|
|
119
|
+
const signatureAgent = `"${options.directory}"`;
|
|
120
|
+
const headers = new Headers(request.headers);
|
|
121
|
+
headers.set('signature-agent', signatureAgent);
|
|
122
|
+
// The signature covers the authority, method, path and Signature-Agent,
|
|
123
|
+
// never the body, so sign a body-less copy: building it from `request`
|
|
124
|
+
// itself would consume the body and leave the caller nothing to send.
|
|
125
|
+
const signed = new Request(request.url, { method: request.method, headers });
|
|
126
|
+
const fields = await sign(signed, {
|
|
127
|
+
signer: await signerFromJWK(options.privateJwk),
|
|
128
|
+
created: now,
|
|
129
|
+
expires: new Date(now.getTime() + lifetime * 1000),
|
|
130
|
+
nonce: options.nonce ?? newNonce(),
|
|
131
|
+
additionalComponents: COVERED,
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
'signature-agent': signatureAgent,
|
|
135
|
+
signature: fields.signature,
|
|
136
|
+
'signature-input': fields.signatureInput,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The `web-bot-auth` profile's refusal: a policy the signature broke, before or instead of its key. */
|
|
140
|
+
class ProfileError extends Error {
|
|
141
|
+
}
|
|
142
|
+
/** The members of a Signature-Input dictionary: each label and its own text. */
|
|
143
|
+
function inputMembers(input) {
|
|
144
|
+
return input
|
|
145
|
+
.split(/,(?=\s*[A-Za-z*][A-Za-z0-9_.*-]*=\()/)
|
|
146
|
+
.map((text) => ({ label: /^\s*([^=]+)=/.exec(text)?.[1]?.trim() ?? '', text }))
|
|
147
|
+
.filter((member) => member.label !== '');
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Which signature to check when a request carries several (RFC 9421 §4.3: a
|
|
151
|
+
* proxy or CDN may add its own): the one tagged `web-bot-auth`, or the only
|
|
152
|
+
* one there is. Undefined lets the verifier refuse an ambiguous request.
|
|
153
|
+
*/
|
|
154
|
+
function labelToCheck(request) {
|
|
155
|
+
const members = inputMembers(request.headers.get('signature-input') ?? '');
|
|
156
|
+
if (members.length === 1)
|
|
157
|
+
return members[0].label;
|
|
158
|
+
return members.find((member) => /;\s*tag="web-bot-auth"/.test(member.text))?.label;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The directory a signature names, from its `Signature-Agent`: the member it
|
|
162
|
+
* covers (`"signature-agent";key="…"`, the draft's dictionary form) or the
|
|
163
|
+
* whole header when it covers it bare (the string form our agents and
|
|
164
|
+
* Cloudflare send). The header is required to be covered when present
|
|
165
|
+
* (draft-ietf-webbotauth-httpsig-protocol §5.2.1), so a directory is never
|
|
166
|
+
* taken from an unsigned header.
|
|
167
|
+
*/
|
|
168
|
+
function coveredDirectory(request, components) {
|
|
169
|
+
const header = request.headers.get('signature-agent');
|
|
170
|
+
if (header === null)
|
|
171
|
+
return null;
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = parseSignatureAgentHeader(header);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
throw new ProfileError(error instanceof Error ? error.message : 'Unreadable Signature-Agent.');
|
|
178
|
+
}
|
|
179
|
+
const covered = components.filter((c) => c.name === 'signature-agent');
|
|
180
|
+
if (parsed.kind === 'legacy') {
|
|
181
|
+
if (!covered.some((c) => Object.keys(c.parameters).length === 0))
|
|
182
|
+
throw new ProfileError('The signature must cover Signature-Agent.');
|
|
183
|
+
return parsed.entries[0]?.uri ?? null;
|
|
184
|
+
}
|
|
185
|
+
const keys = covered.flatMap((c) => typeof c.parameters.key === 'string' && Object.keys(c.parameters).length === 1
|
|
186
|
+
? [c.parameters.key]
|
|
187
|
+
: []);
|
|
188
|
+
if (keys.length !== 1)
|
|
189
|
+
throw new ProfileError('The signature must cover exactly one Signature-Agent member.');
|
|
190
|
+
const entry = parsed.entries.find((candidate) => candidate.label === keys[0]);
|
|
191
|
+
if (!entry)
|
|
192
|
+
throw new ProfileError(`Signature-Agent has no member ${keys[0]}.`);
|
|
193
|
+
return entry.type === 'directory' ? entry.uri : null;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* The directory a request's `Signature-Agent` names, read without checking
|
|
197
|
+
* anything: what a check records about a request it refused. Null when
|
|
198
|
+
* there is none; the header itself, cut short, when it cannot be read.
|
|
199
|
+
*/
|
|
200
|
+
export function signatureAgentOf(request) {
|
|
201
|
+
const header = request.headers.get('signature-agent');
|
|
202
|
+
if (header === null)
|
|
203
|
+
return null;
|
|
204
|
+
try {
|
|
205
|
+
return parseSignatureAgentHeader(header).entries[0]?.uri.slice(0, 512) ?? null;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return header.slice(0, 512);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Why a signature failed, with the reason under the verifier's own words. */
|
|
212
|
+
function detailOf(error) {
|
|
213
|
+
const words = [];
|
|
214
|
+
for (let e = error; e instanceof Error && words.length < 3; e = e.cause)
|
|
215
|
+
if (e.message)
|
|
216
|
+
words.push(e.message);
|
|
217
|
+
return (words.join(': ') || String(error)).slice(0, 300);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Check a request's agent signature, under Web Bot Auth as the working group
|
|
221
|
+
* wrote it (draft-ietf-webbotauth-httpsig-protocol-01 §5.2): Ed25519, tagged
|
|
222
|
+
* `web-bot-auth`, with `created`, `expires` and `keyid`, covering the bare
|
|
223
|
+
* `@authority` or `@target-uri`, and the `Signature-Agent` when there is one.
|
|
224
|
+
* `alg` and `nonce` are optional, as the draft and RFC 9421 make them, and a
|
|
225
|
+
* nonce of any length is remembered. On top of the draft, no signature
|
|
226
|
+
* verifies more than five minutes after it was made.
|
|
227
|
+
*
|
|
228
|
+
* `findKey` turns a key id, and the directory the signature names, into the
|
|
229
|
+
* public key to check it with, or null; whether that key is revoked, and its
|
|
230
|
+
* operator's reputation, are the caller's next questions.
|
|
231
|
+
*/
|
|
232
|
+
export async function verifyAgentRequest(request, findKey, options = {}) {
|
|
233
|
+
if (!request.headers.has('signature') || !request.headers.has('signature-input')) {
|
|
234
|
+
return { ok: false, reason: 'unsigned', detail: 'The request carries no agent signature.' };
|
|
235
|
+
}
|
|
236
|
+
let unknown;
|
|
237
|
+
let named;
|
|
238
|
+
let profile;
|
|
239
|
+
try {
|
|
240
|
+
const verified = await verifySignature(request, {
|
|
241
|
+
label: labelToCheck(request),
|
|
242
|
+
policy: {
|
|
243
|
+
algorithms: ['ed25519'],
|
|
244
|
+
requiredComponents: [],
|
|
245
|
+
requiredParameters: ['created', 'expires', 'keyid', 'tag'],
|
|
246
|
+
maxAge: MAX_LIFETIME_SECONDS,
|
|
247
|
+
clockSkew: CLOCK_SKEW_SECONDS,
|
|
248
|
+
now: Math.floor((options.now ?? new Date()).getTime() / 1000),
|
|
249
|
+
},
|
|
250
|
+
resolveVerifier: async (candidate) => {
|
|
251
|
+
const { parameters, components } = candidate;
|
|
252
|
+
const keyid = parameters.keyid;
|
|
253
|
+
if (typeof keyid !== 'string' || keyid === '')
|
|
254
|
+
throw new ProfileError('keyid must be a non-empty string.');
|
|
255
|
+
if (parameters.tag !== 'web-bot-auth')
|
|
256
|
+
throw new ProfileError('The signature is not tagged web-bot-auth.');
|
|
257
|
+
if (typeof parameters.created !== 'number' || typeof parameters.expires !== 'number')
|
|
258
|
+
throw new ProfileError('created and expires must be integers.');
|
|
259
|
+
if (parameters.created > parameters.expires)
|
|
260
|
+
throw new ProfileError('created is after expires.');
|
|
261
|
+
if (parameters.nonce !== undefined && typeof parameters.nonce !== 'string')
|
|
262
|
+
throw new ProfileError('nonce must be a string.');
|
|
263
|
+
if (!components.some((c) => (c.name === '@authority' || c.name === '@target-uri') &&
|
|
264
|
+
Object.keys(c.parameters).length === 0))
|
|
265
|
+
throw new ProfileError('The signature must cover @authority or @target-uri.');
|
|
266
|
+
named = coveredDirectory(request, components);
|
|
267
|
+
const jwk = await findKey(keyid, named);
|
|
268
|
+
if (!jwk) {
|
|
269
|
+
unknown = keyid;
|
|
270
|
+
throw new Error(`No published key ${keyid}.`);
|
|
271
|
+
}
|
|
272
|
+
profile = { kid: keyid, directory: named };
|
|
273
|
+
return verifierFromJWK(jwk);
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
if (!profile)
|
|
277
|
+
throw new Error('The signature was not resolved.');
|
|
278
|
+
const nonce = verified.parameters.nonce;
|
|
279
|
+
return {
|
|
280
|
+
ok: true,
|
|
281
|
+
kid: profile.kid,
|
|
282
|
+
directory: profile.directory,
|
|
283
|
+
created: new Date(Number(verified.parameters.created) * 1000),
|
|
284
|
+
expires: new Date(Number(verified.parameters.expires) * 1000),
|
|
285
|
+
nonce: typeof nonce === 'string' ? nonce : null,
|
|
286
|
+
signature: base64Url(verified.signature.slice().buffer),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
const detail = detailOf(error);
|
|
291
|
+
if (unknown)
|
|
292
|
+
return { ok: false, reason: 'unknown_key', kid: unknown, directory: named, detail };
|
|
293
|
+
if (/expired|too old|max ?age|in the future/i.test(detail))
|
|
294
|
+
return { ok: false, reason: 'expired', directory: named, detail };
|
|
295
|
+
return { ok: false, reason: 'invalid', directory: named, detail };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The User-Agent tokens of agents that name themselves without signing
|
|
3
|
+
* (ChatGPT-User, Perplexity-User, Claude-User, …). Pidgeon records a request
|
|
4
|
+
* carrying one as `declared`, and checks its address where the vendor
|
|
5
|
+
* publishes its ranges.
|
|
6
|
+
*/
|
|
7
|
+
export declare const DECLARED_AGENT_TOKENS: readonly string[];
|
|
8
|
+
/** The declared agent a User-Agent names, as a whole product token, or null. */
|
|
9
|
+
export declare function declaredAgentToken(userAgent: string | null | undefined): string | null;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Written by scripts/declared-agents.mts from DECLARED_AGENTS (src/lib/checks.ts). Do not edit.
|
|
2
|
+
/**
|
|
3
|
+
* The User-Agent tokens of agents that name themselves without signing
|
|
4
|
+
* (ChatGPT-User, Perplexity-User, Claude-User, …). Pidgeon records a request
|
|
5
|
+
* carrying one as `declared`, and checks its address where the vendor
|
|
6
|
+
* publishes its ranges.
|
|
7
|
+
*/
|
|
8
|
+
export const DECLARED_AGENT_TOKENS = [
|
|
9
|
+
'ChatGPT-User',
|
|
10
|
+
'OAI-SearchBot',
|
|
11
|
+
'GPTBot',
|
|
12
|
+
'Perplexity-User',
|
|
13
|
+
'PerplexityBot',
|
|
14
|
+
'Claude-User',
|
|
15
|
+
'Claude-SearchBot',
|
|
16
|
+
'ClaudeBot',
|
|
17
|
+
'Claude-Agent',
|
|
18
|
+
'Google-Agent',
|
|
19
|
+
'Google-GeminiNotebook',
|
|
20
|
+
'meta-externalfetcher',
|
|
21
|
+
'meta-externalagent',
|
|
22
|
+
'DuckAssistBot',
|
|
23
|
+
'MistralAI-User',
|
|
24
|
+
'MistralAI-Index',
|
|
25
|
+
'Amzn-User',
|
|
26
|
+
'YouBot',
|
|
27
|
+
'CCBot',
|
|
28
|
+
];
|
|
29
|
+
/** The declared agent a User-Agent names, as a whole product token, or null. */
|
|
30
|
+
export function declaredAgentToken(userAgent) {
|
|
31
|
+
const ua = userAgent?.toLowerCase();
|
|
32
|
+
if (!ua)
|
|
33
|
+
return null;
|
|
34
|
+
for (const token of DECLARED_AGENT_TOKENS) {
|
|
35
|
+
const lower = token.toLowerCase();
|
|
36
|
+
let at = ua.indexOf(lower);
|
|
37
|
+
while (at !== -1) {
|
|
38
|
+
const before = at === 0 ? '' : ua[at - 1];
|
|
39
|
+
const after = ua[at + lower.length] ?? '';
|
|
40
|
+
if (!/[a-z0-9-]/.test(before) && !/[a-z0-9-]/.test(after))
|
|
41
|
+
return token;
|
|
42
|
+
at = ua.indexOf(lower, at + 1);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|