@pidgeon-ai/sdk 1.68.0 → 2.1.1
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 +42 -1060
- package/LICENSE +55 -21
- package/README.md +113 -188
- package/dist/auth.d.ts +115 -0
- package/dist/auth.js +150 -0
- package/dist/credential.d.ts +61 -0
- package/dist/credential.js +135 -0
- package/dist/index.d.ts +670 -13914
- package/dist/index.js +464 -2036
- package/dist/node.d.ts +137 -0
- package/dist/node.js +403 -0
- package/package.json +35 -41
- package/dist/index.cjs +0 -2239
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -13967
- package/dist/index.js.map +0 -1
package/dist/auth.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
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 { keyIdOf, signAgentRequest, verifyAgentRequest } from "./credential.js";
|
|
17
|
+
export const DEFAULT_ISSUER = 'https://pidgeon.ai';
|
|
18
|
+
export const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
|
19
|
+
export const AGENT_KEY_TOKEN = 'urn:pidgeon:params:oauth:token-type:agent-key';
|
|
20
|
+
export const ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token';
|
|
21
|
+
export const ID_JAG = 'urn:ietf:params:oauth:token-type:id-jag';
|
|
22
|
+
/** Why a sign-in was not accepted. */
|
|
23
|
+
export class SignInError extends Error {
|
|
24
|
+
reason;
|
|
25
|
+
constructor(reason, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.reason = reason;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const trim = (issuer) => issuer.replace(/\/+$/, '');
|
|
31
|
+
/**
|
|
32
|
+
* The agent's side: an ID token for one site, for ten minutes. `site` is the
|
|
33
|
+
* site's client id (it tells you, or puts it on its sign-in page); `key` and
|
|
34
|
+
* `directory` are the agent's, as for any signed request.
|
|
35
|
+
*/
|
|
36
|
+
export async function signInAsAgent(options) {
|
|
37
|
+
const url = `${trim(options.issuer ?? DEFAULT_ISSUER)}/oauth/token`;
|
|
38
|
+
const signature = await signAgentRequest(new Request(url, { method: 'POST' }), {
|
|
39
|
+
privateJwk: options.key.privateJwk,
|
|
40
|
+
directory: options.directory,
|
|
41
|
+
});
|
|
42
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: { ...signature, 'content-type': 'application/x-www-form-urlencoded' },
|
|
45
|
+
body: new URLSearchParams({
|
|
46
|
+
grant_type: TOKEN_EXCHANGE,
|
|
47
|
+
subject_token: options.key.kid,
|
|
48
|
+
subject_token_type: AGENT_KEY_TOKEN,
|
|
49
|
+
audience: options.site,
|
|
50
|
+
}).toString(),
|
|
51
|
+
});
|
|
52
|
+
const body = (await response.json().catch(() => ({})));
|
|
53
|
+
if (!response.ok || !body.access_token) {
|
|
54
|
+
throw new SignInError('refused', body.error_description ?? body.error ?? `HTTP ${response.status}`);
|
|
55
|
+
}
|
|
56
|
+
return { idToken: body.access_token, expiresIn: body.expires_in ?? 600 };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The agent's side, for an MCP server whose authorization server trusts
|
|
60
|
+
* Pidgeon (MCP Enterprise-Managed Authorization): an ID-JAG, five minutes,
|
|
61
|
+
* to present there as a JWT bearer grant. `audience` is that authorization
|
|
62
|
+
* server's issuer, `clientId` your client id there, `resource` the MCP
|
|
63
|
+
* server's resource identifier.
|
|
64
|
+
*/
|
|
65
|
+
export async function requestIdJag(options) {
|
|
66
|
+
const url = `${trim(options.issuer ?? DEFAULT_ISSUER)}/oauth/token`;
|
|
67
|
+
const signature = await signAgentRequest(new Request(url, { method: 'POST' }), {
|
|
68
|
+
privateJwk: options.key.privateJwk,
|
|
69
|
+
directory: options.directory,
|
|
70
|
+
});
|
|
71
|
+
const form = new URLSearchParams({
|
|
72
|
+
grant_type: TOKEN_EXCHANGE,
|
|
73
|
+
requested_token_type: ID_JAG,
|
|
74
|
+
subject_token: options.key.kid,
|
|
75
|
+
subject_token_type: AGENT_KEY_TOKEN,
|
|
76
|
+
audience: options.audience,
|
|
77
|
+
client_id: options.clientId,
|
|
78
|
+
});
|
|
79
|
+
if (options.resource)
|
|
80
|
+
form.set('resource', options.resource);
|
|
81
|
+
if (options.scope)
|
|
82
|
+
form.set('scope', options.scope);
|
|
83
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
84
|
+
method: 'POST',
|
|
85
|
+
headers: { ...signature, 'content-type': 'application/x-www-form-urlencoded' },
|
|
86
|
+
body: form.toString(),
|
|
87
|
+
});
|
|
88
|
+
const body = (await response.json().catch(() => ({})));
|
|
89
|
+
if (!response.ok || !body.access_token) {
|
|
90
|
+
throw new SignInError('refused', body.error_description ?? body.error ?? `HTTP ${response.status}`);
|
|
91
|
+
}
|
|
92
|
+
return { idJag: body.access_token, expiresIn: body.expires_in ?? 300 };
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The site's side, for any ID token from Pidgeon (a person's or an agent's):
|
|
96
|
+
* signed with Pidgeon's published key, issued by Pidgeon, for your client
|
|
97
|
+
* id, not expired, and with your `nonce` if you sent one.
|
|
98
|
+
*/
|
|
99
|
+
export async function verifyIdToken(idToken, options) {
|
|
100
|
+
const issuer = trim(options.issuer ?? DEFAULT_ISSUER);
|
|
101
|
+
const keys = options.jwks
|
|
102
|
+
? createLocalJWKSet(options.jwks)
|
|
103
|
+
: remoteKeys(`${issuer}/.well-known/jwks.json`);
|
|
104
|
+
try {
|
|
105
|
+
const { payload } = await jwtVerify(idToken, keys, {
|
|
106
|
+
issuer,
|
|
107
|
+
audience: options.clientId,
|
|
108
|
+
algorithms: ['RS256'],
|
|
109
|
+
// An ID-JAG (typ oauth-id-jag+jwt) shares the key and the issuer; it is never a sign-in.
|
|
110
|
+
typ: 'JWT',
|
|
111
|
+
});
|
|
112
|
+
if (options.nonce !== undefined && payload.nonce !== options.nonce) {
|
|
113
|
+
throw new Error('The nonce does not match.');
|
|
114
|
+
}
|
|
115
|
+
return payload;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
throw new SignInError('invalid_token', error instanceof Error ? error.message : String(error));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const remote = new Map();
|
|
122
|
+
function remoteKeys(url) {
|
|
123
|
+
let keys = remote.get(url);
|
|
124
|
+
if (!keys) {
|
|
125
|
+
keys = createRemoteJWKSet(new URL(url));
|
|
126
|
+
remote.set(url, keys);
|
|
127
|
+
}
|
|
128
|
+
return keys;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The site's side, for an agent's request: the ID token in
|
|
132
|
+
* `Authorization: Bearer`, and the request signed with the key that token
|
|
133
|
+
* names. Answers who the agent is and who stands behind it.
|
|
134
|
+
*/
|
|
135
|
+
export async function verifyAgentSignIn(request, options) {
|
|
136
|
+
const token = request.headers.get('authorization')?.match(/^Bearer\s+(\S+)$/)?.[1];
|
|
137
|
+
if (!token)
|
|
138
|
+
throw new SignInError('unsigned', 'Send the ID token as `Authorization: Bearer`.');
|
|
139
|
+
const claims = await verifyIdToken(token, options);
|
|
140
|
+
if (claims.kind !== 'agent' || !claims.cnf?.jwk) {
|
|
141
|
+
throw new SignInError('not_an_agent', 'This token is not an agent’s.');
|
|
142
|
+
}
|
|
143
|
+
const bound = claims.cnf.jwk;
|
|
144
|
+
const boundKid = await keyIdOf(bound);
|
|
145
|
+
const proof = await verifyAgentRequest(request, async (kid) => (kid === boundKid ? bound : null));
|
|
146
|
+
if (!proof.ok) {
|
|
147
|
+
throw new SignInError(proof.reason === 'unsigned' ? 'unsigned' : 'wrong_key', 'The request must be signed with the key the token was issued to.');
|
|
148
|
+
}
|
|
149
|
+
return claims;
|
|
150
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
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 (docs/plan.md §3). */
|
|
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 (docs/plan.md §5: short lifetimes). 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
|
+
/** An operator's directory: where its agents' public keys are published. */
|
|
23
|
+
export declare function directoryUrl(slug: string, host?: string): string;
|
|
24
|
+
/** A key's id: its JWK SHA-256 thumbprint (RFC 7638), Web Bot Auth's `keyid`. */
|
|
25
|
+
export declare function keyIdOf(publicJwk: PublicJwk): Promise<string>;
|
|
26
|
+
/** Whether something is an Ed25519 public key, and only that: no private part. */
|
|
27
|
+
export declare function isPublicJwk(value: unknown): value is PublicJwk;
|
|
28
|
+
/** A new key pair, for an agent. Run where the agent runs: the CLI, the SDK. */
|
|
29
|
+
export declare function generateAgentKey(): Promise<AgentKeyPair>;
|
|
30
|
+
/**
|
|
31
|
+
* Sign a request as an agent: returns the headers to add. The request must
|
|
32
|
+
* not carry a Signature-Agent of its own; this sets it.
|
|
33
|
+
*/
|
|
34
|
+
export declare function signAgentRequest(request: Request, options: {
|
|
35
|
+
privateJwk: JsonWebKey;
|
|
36
|
+
directory: string;
|
|
37
|
+
lifetimeSeconds?: number;
|
|
38
|
+
now?: Date;
|
|
39
|
+
}): Promise<Record<string, string>>;
|
|
40
|
+
/** Why a request's credential was not accepted, in the API's words. */
|
|
41
|
+
export type Rejection = 'unsigned' | 'invalid' | 'unknown_key' | 'expired';
|
|
42
|
+
export type Verification = {
|
|
43
|
+
ok: true;
|
|
44
|
+
kid: string;
|
|
45
|
+
directory: string | null;
|
|
46
|
+
created: Date;
|
|
47
|
+
expires: Date;
|
|
48
|
+
} | {
|
|
49
|
+
ok: false;
|
|
50
|
+
reason: Rejection;
|
|
51
|
+
kid?: string;
|
|
52
|
+
detail: string;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Check a request's agent signature. `findKey` turns a key id into the public
|
|
56
|
+
* key Pidgeon published for it, or null; whether that key is revoked, and the
|
|
57
|
+
* operator's reputation, are the caller's next questions.
|
|
58
|
+
*/
|
|
59
|
+
export declare function verifyAgentRequest(request: Request, findKey: (kid: string) => Promise<PublicJwk | null>, options?: {
|
|
60
|
+
now?: Date;
|
|
61
|
+
}): Promise<Verification>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent credential (docs/plan.md §5): 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 and path 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, each from the plan:
|
|
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
|
+
*/
|
|
18
|
+
import { jwkToKeyID, sign, verify } from 'web-bot-auth';
|
|
19
|
+
import { signerFromJWK, verifierFromJWK } from 'web-bot-auth/crypto';
|
|
20
|
+
/** How long a signature lasts unless the agent asks for less. */
|
|
21
|
+
export const DEFAULT_LIFETIME_SECONDS = 60;
|
|
22
|
+
/**
|
|
23
|
+
* The longest a signature lasts, whatever the signer asks, and the oldest a
|
|
24
|
+
* verifier accepts, whatever its `expires` says: five minutes, so a captured
|
|
25
|
+
* request is soon useless (docs/plan.md §5: short lifetimes). The draft's own
|
|
26
|
+
* ceiling, a day, left a copied request replayable at the same site all day.
|
|
27
|
+
*/
|
|
28
|
+
export const MAX_LIFETIME_SECONDS = 5 * 60;
|
|
29
|
+
/** How far an agent's clock may run ahead of the verifier's. */
|
|
30
|
+
const CLOCK_SKEW_SECONDS = 30;
|
|
31
|
+
/** What the signature covers beyond the authority and the Signature-Agent. */
|
|
32
|
+
const COVERED = ['@method', '@path'];
|
|
33
|
+
/** An operator's directory: where its agents' public keys are published. */
|
|
34
|
+
export function directoryUrl(slug, host = process.env.AGENTS_HOST ?? 'agents.pidgeon.ai') {
|
|
35
|
+
return `https://${slug}.${host}`;
|
|
36
|
+
}
|
|
37
|
+
/** A key's id: its JWK SHA-256 thumbprint (RFC 7638), Web Bot Auth's `keyid`. */
|
|
38
|
+
export async function keyIdOf(publicJwk) {
|
|
39
|
+
return jwkToKeyID(publicJwk, (bytes) => crypto.subtle.digest('SHA-256', bytes), base64Url);
|
|
40
|
+
}
|
|
41
|
+
/** base64url without padding; in the browser too, where there is no Buffer (the dashboard makes keys there). */
|
|
42
|
+
function base64Url(buffer) {
|
|
43
|
+
let binary = '';
|
|
44
|
+
for (const byte of new Uint8Array(buffer))
|
|
45
|
+
binary += String.fromCharCode(byte);
|
|
46
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
47
|
+
}
|
|
48
|
+
/** Whether something is an Ed25519 public key, and only that: no private part. */
|
|
49
|
+
export function isPublicJwk(value) {
|
|
50
|
+
if (typeof value !== 'object' || value === null)
|
|
51
|
+
return false;
|
|
52
|
+
const jwk = value;
|
|
53
|
+
return (jwk.kty === 'OKP' &&
|
|
54
|
+
jwk.crv === 'Ed25519' &&
|
|
55
|
+
typeof jwk.x === 'string' &&
|
|
56
|
+
/^[A-Za-z0-9_-]{43}$/.test(jwk.x) &&
|
|
57
|
+
!('d' in jwk));
|
|
58
|
+
}
|
|
59
|
+
/** A new key pair, for an agent. Run where the agent runs: the CLI, the SDK. */
|
|
60
|
+
export async function generateAgentKey() {
|
|
61
|
+
const pair = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
|
|
62
|
+
'sign',
|
|
63
|
+
'verify',
|
|
64
|
+
]));
|
|
65
|
+
// Web Bot Auth wants an Ed25519 JWK's alg to be EdDSA or absent; Node writes "Ed25519".
|
|
66
|
+
const { alg: _alg, ...privateJwk } = await crypto.subtle.exportKey('jwk', pair.privateKey);
|
|
67
|
+
const exported = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
68
|
+
const publicJwk = { kty: 'OKP', crv: 'Ed25519', x: exported.x };
|
|
69
|
+
return { kid: await keyIdOf(publicJwk), publicJwk, privateJwk };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Sign a request as an agent: returns the headers to add. The request must
|
|
73
|
+
* not carry a Signature-Agent of its own; this sets it.
|
|
74
|
+
*/
|
|
75
|
+
export async function signAgentRequest(request, options) {
|
|
76
|
+
const now = options.now ?? new Date();
|
|
77
|
+
const lifetime = Math.min(options.lifetimeSeconds ?? DEFAULT_LIFETIME_SECONDS, MAX_LIFETIME_SECONDS);
|
|
78
|
+
const signatureAgent = `"${options.directory}"`;
|
|
79
|
+
const headers = new Headers(request.headers);
|
|
80
|
+
headers.set('signature-agent', signatureAgent);
|
|
81
|
+
const signed = new Request(request, { headers });
|
|
82
|
+
const fields = await sign(signed, {
|
|
83
|
+
signer: await signerFromJWK(options.privateJwk),
|
|
84
|
+
created: now,
|
|
85
|
+
expires: new Date(now.getTime() + lifetime * 1000),
|
|
86
|
+
additionalComponents: COVERED,
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
'signature-agent': signatureAgent,
|
|
90
|
+
signature: fields.signature,
|
|
91
|
+
'signature-input': fields.signatureInput,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Check a request's agent signature. `findKey` turns a key id into the public
|
|
96
|
+
* key Pidgeon published for it, or null; whether that key is revoked, and the
|
|
97
|
+
* operator's reputation, are the caller's next questions.
|
|
98
|
+
*/
|
|
99
|
+
export async function verifyAgentRequest(request, findKey, options = {}) {
|
|
100
|
+
if (!request.headers.has('signature') || !request.headers.has('signature-input')) {
|
|
101
|
+
return { ok: false, reason: 'unsigned', detail: 'The request carries no agent signature.' };
|
|
102
|
+
}
|
|
103
|
+
let unknown;
|
|
104
|
+
try {
|
|
105
|
+
const verified = await verify(request, {
|
|
106
|
+
algorithms: ['ed25519'],
|
|
107
|
+
maxAge: MAX_LIFETIME_SECONDS,
|
|
108
|
+
clockSkew: CLOCK_SKEW_SECONDS,
|
|
109
|
+
now: options.now,
|
|
110
|
+
resolver: async (candidate) => {
|
|
111
|
+
const jwk = await findKey(candidate.keyid);
|
|
112
|
+
if (!jwk) {
|
|
113
|
+
unknown = candidate.keyid;
|
|
114
|
+
throw new Error(`No published key ${candidate.keyid}.`);
|
|
115
|
+
}
|
|
116
|
+
return verifierFromJWK(jwk);
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
return {
|
|
120
|
+
ok: true,
|
|
121
|
+
kid: verified.keyid,
|
|
122
|
+
directory: verified.signatureAgent?.uri ?? null,
|
|
123
|
+
created: verified.created,
|
|
124
|
+
expires: verified.expires,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
129
|
+
if (unknown)
|
|
130
|
+
return { ok: false, reason: 'unknown_key', kid: unknown, detail };
|
|
131
|
+
if (/expir|too old|max ?age|future/i.test(detail))
|
|
132
|
+
return { ok: false, reason: 'expired', detail };
|
|
133
|
+
return { ok: false, reason: 'invalid', detail };
|
|
134
|
+
}
|
|
135
|
+
}
|