@pidgeon-ai/sdk 1.67.4 → 2.0.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 +20 -1054
- package/LICENSE +55 -21
- package/README.md +88 -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 +342 -13910
- package/dist/index.js +275 -2040
- 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 -13951
- package/dist/index.js.map +0 -1
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Pidgeon, type Agent } from './index.ts';
|
|
2
|
+
type Env = Record<string, string | undefined>;
|
|
3
|
+
export declare function configDir(env?: Env): string;
|
|
4
|
+
export declare function baseUrlOf(env?: Env): string;
|
|
5
|
+
export type Session = {
|
|
6
|
+
baseUrl: string;
|
|
7
|
+
issuer: string;
|
|
8
|
+
tokenEndpoint: string;
|
|
9
|
+
revocationEndpoint: string | null;
|
|
10
|
+
resource: string;
|
|
11
|
+
clientId: string;
|
|
12
|
+
accessToken: string;
|
|
13
|
+
refreshToken: string | null;
|
|
14
|
+
/** Milliseconds since the epoch. */
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
scope: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function readSession(baseUrl: string, env?: Env): Promise<Session>;
|
|
19
|
+
type Metadata = {
|
|
20
|
+
issuer: string;
|
|
21
|
+
authorization_endpoint: string;
|
|
22
|
+
token_endpoint: string;
|
|
23
|
+
registration_endpoint?: string;
|
|
24
|
+
revocation_endpoint?: string;
|
|
25
|
+
};
|
|
26
|
+
/** RFC 9728 then RFC 8414: who guards `<base>/mcp`, and where its endpoints are. */
|
|
27
|
+
export declare function discover(baseUrl: string, fetchImpl?: typeof fetch): Promise<{
|
|
28
|
+
resource: string;
|
|
29
|
+
metadata: Metadata;
|
|
30
|
+
}>;
|
|
31
|
+
/** Open a URL in the person's browser; where none can be opened, they are shown the URL instead. */
|
|
32
|
+
export declare function openInBrowser(url: string): void;
|
|
33
|
+
/**
|
|
34
|
+
* Sign in with a browser: the person signs in to Pidgeon there and chooses
|
|
35
|
+
* what this machine may do (`scope` is the most it asks for). Resolves once
|
|
36
|
+
* they answer, with the session saved.
|
|
37
|
+
*
|
|
38
|
+
* `onUrl` is told the address to open, which is also opened in the browser
|
|
39
|
+
* unless `openBrowser` is false (a headless machine shows it instead).
|
|
40
|
+
*/
|
|
41
|
+
export declare function signIn(options?: {
|
|
42
|
+
baseUrl?: string;
|
|
43
|
+
scope?: 'read' | 'draft' | 'send' | 'admin';
|
|
44
|
+
clientName?: string;
|
|
45
|
+
onUrl?: (url: string) => void;
|
|
46
|
+
openBrowser?: boolean;
|
|
47
|
+
timeoutMs?: number;
|
|
48
|
+
fetch?: typeof fetch;
|
|
49
|
+
env?: Env;
|
|
50
|
+
}): Promise<Session>;
|
|
51
|
+
/** A live access token for the saved session, refreshed (and saved) when it is about to run out. */
|
|
52
|
+
export declare function sessionToken(baseUrl: string, options?: {
|
|
53
|
+
fetch?: typeof fetch;
|
|
54
|
+
env?: Env;
|
|
55
|
+
}): Promise<string>;
|
|
56
|
+
/** End the session: Pidgeon is told (which ends the connection there), and the tokens are forgotten. */
|
|
57
|
+
export declare function signOut(baseUrl: string, options?: {
|
|
58
|
+
fetch?: typeof fetch;
|
|
59
|
+
env?: Env;
|
|
60
|
+
}): Promise<boolean>;
|
|
61
|
+
/**
|
|
62
|
+
* The API client for this machine: `PIDGEON_API_KEY` if it is set, else the
|
|
63
|
+
* signed-in session (refreshed as needed). Nothing is checked until the first call.
|
|
64
|
+
*/
|
|
65
|
+
export declare function clientFromEnvironment(options?: {
|
|
66
|
+
env?: Env;
|
|
67
|
+
baseUrl?: string;
|
|
68
|
+
fetch?: typeof fetch;
|
|
69
|
+
}): Pidgeon;
|
|
70
|
+
export type StoredAgentKey = {
|
|
71
|
+
agent_id: string;
|
|
72
|
+
name: string;
|
|
73
|
+
kid: string;
|
|
74
|
+
directory: string;
|
|
75
|
+
public_jwk: JsonWebKey;
|
|
76
|
+
private_jwk: JsonWebKey;
|
|
77
|
+
created_at: string;
|
|
78
|
+
};
|
|
79
|
+
/** Where an agent's key is kept on this machine. */
|
|
80
|
+
export declare const agentKeyPath: (agentId: string, env?: Env) => string;
|
|
81
|
+
export declare function saveAgentKey(entry: StoredAgentKey, env?: Env): Promise<string>;
|
|
82
|
+
export declare function readAgentKey(agentId: string, env?: Env): Promise<StoredAgentKey | null>;
|
|
83
|
+
/** Every agent key kept here, without their private halves. */
|
|
84
|
+
export declare function listAgentKeys(env?: Env): Promise<(Omit<StoredAgentKey, 'private_jwk'> & {
|
|
85
|
+
path: string;
|
|
86
|
+
})[]>;
|
|
87
|
+
export declare function forgetAgentKey(agentId: string, env?: Env): Promise<void>;
|
|
88
|
+
/** Your agent, from a key file this machine keeps: `fetch` signs every request as it. */
|
|
89
|
+
export declare function agentFromKeyFile(path: string): Promise<{
|
|
90
|
+
fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
91
|
+
}>;
|
|
92
|
+
/**
|
|
93
|
+
* Register an agent, make its key on this machine, publish the public half
|
|
94
|
+
* signed with it (the possession proof the dashboard sends too), and keep
|
|
95
|
+
* the key here. Answers where the key is, never the key.
|
|
96
|
+
*/
|
|
97
|
+
export declare function setUpAgent(pidgeon: Pidgeon, input: {
|
|
98
|
+
name: string;
|
|
99
|
+
purpose?: string;
|
|
100
|
+
podId?: string;
|
|
101
|
+
}, env?: Env): Promise<{
|
|
102
|
+
agent: Agent & {
|
|
103
|
+
directory: string;
|
|
104
|
+
};
|
|
105
|
+
kid: string;
|
|
106
|
+
keyFile: string;
|
|
107
|
+
}>;
|
|
108
|
+
/**
|
|
109
|
+
* A new key for an agent already registered, made and kept here. It replaces
|
|
110
|
+
* the key this machine kept for that agent; the old one stays published
|
|
111
|
+
* until it is revoked in the dashboard.
|
|
112
|
+
*/
|
|
113
|
+
export declare function addAgentKey(pidgeon: Pidgeon, agentId: string, env?: Env): Promise<{
|
|
114
|
+
kid: string;
|
|
115
|
+
keyFile: string;
|
|
116
|
+
}>;
|
|
117
|
+
/**
|
|
118
|
+
* For a server that cannot make keys (the hosted MCP server): make the
|
|
119
|
+
* agent's key here, keep it, and answer what publishing it needs, never the
|
|
120
|
+
* key: the public half, and the signature headers of a `POST` to
|
|
121
|
+
* `publishUrl` made with the key, which is the possession proof. The proof
|
|
122
|
+
* holds for `lifetimeSeconds` (ten minutes), long enough to hand it over.
|
|
123
|
+
*/
|
|
124
|
+
export declare function makeKeyProof(input: {
|
|
125
|
+
agentId: string;
|
|
126
|
+
directory: string;
|
|
127
|
+
publishUrl: string;
|
|
128
|
+
name?: string;
|
|
129
|
+
lifetimeSeconds?: number;
|
|
130
|
+
}, env?: Env): Promise<{
|
|
131
|
+
agent_id: string;
|
|
132
|
+
kid: string;
|
|
133
|
+
key_file: string;
|
|
134
|
+
public_jwk: JsonWebKey;
|
|
135
|
+
signature: Record<string, string>;
|
|
136
|
+
}>;
|
|
137
|
+
export {};
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@pidgeon-ai/sdk/node`: what the CLI and the MCP server share, for Node only.
|
|
3
|
+
*
|
|
4
|
+
* - **Signing in** with a browser, through Pidgeon's OAuth server (MCP
|
|
5
|
+
* authorization: RFC 9728 discovery from the resource `<issuer>/mcp`, a
|
|
6
|
+
* client registered with RFC 7591, the code flow with PKCE on a loopback
|
|
7
|
+
* redirect, RFC 8252). The tokens are kept in `credentials.json` and
|
|
8
|
+
* refreshed when they run out; `PIDGEON_API_KEY` wins over them.
|
|
9
|
+
* - **Agent keys**, made on this machine and kept in `agents/<id>.json`, so
|
|
10
|
+
* the private half never leaves it: not to Pidgeon, and not to the model a
|
|
11
|
+
* coding agent talks to.
|
|
12
|
+
*
|
|
13
|
+
* Both live in `PIDGEON_CONFIG_DIR`, else `$XDG_CONFIG_HOME/pidgeon`, else
|
|
14
|
+
* `~/.config/pidgeon`, readable by this user only.
|
|
15
|
+
*/
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
18
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { createServer } from 'node:http';
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
import { generateAgentKey, signAgentRequest } from "./credential.js";
|
|
23
|
+
import { DEFAULT_BASE_URL, Pidgeon, PidgeonError } from "./index.js";
|
|
24
|
+
export function configDir(env = process.env) {
|
|
25
|
+
if (env.PIDGEON_CONFIG_DIR)
|
|
26
|
+
return env.PIDGEON_CONFIG_DIR;
|
|
27
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'pidgeon');
|
|
28
|
+
}
|
|
29
|
+
export function baseUrlOf(env = process.env) {
|
|
30
|
+
return (env.PIDGEON_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
31
|
+
}
|
|
32
|
+
async function readJson(path) {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Written whole, readable by this user only, and never half-written. */
|
|
41
|
+
async function writePrivate(path, value) {
|
|
42
|
+
const dir = path.slice(0, path.lastIndexOf('/'));
|
|
43
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
44
|
+
const temporary = `${path}.${randomBytes(4).toString('hex')}.tmp`;
|
|
45
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
46
|
+
await rename(temporary, path);
|
|
47
|
+
}
|
|
48
|
+
const credentialsPath = (env) => join(configDir(env), 'credentials.json');
|
|
49
|
+
async function sessions(env) {
|
|
50
|
+
return (await readJson(credentialsPath(env))) ?? {};
|
|
51
|
+
}
|
|
52
|
+
async function saveSession(session, env) {
|
|
53
|
+
const all = await sessions(env);
|
|
54
|
+
all[session.baseUrl] = session;
|
|
55
|
+
await writePrivate(credentialsPath(env), all);
|
|
56
|
+
}
|
|
57
|
+
export async function readSession(baseUrl, env = process.env) {
|
|
58
|
+
return (await sessions(env))[baseUrl] ?? null;
|
|
59
|
+
}
|
|
60
|
+
async function getJson(fetchImpl, url) {
|
|
61
|
+
const response = await fetchImpl(url, { headers: { accept: 'application/json' } });
|
|
62
|
+
if (!response.ok)
|
|
63
|
+
throw new PidgeonError(response.status, 'discovery', `${url} answered ${response.status}.`);
|
|
64
|
+
return (await response.json());
|
|
65
|
+
}
|
|
66
|
+
/** RFC 9728 then RFC 8414: who guards `<base>/mcp`, and where its endpoints are. */
|
|
67
|
+
export async function discover(baseUrl, fetchImpl = fetch) {
|
|
68
|
+
const resource = await getJson(fetchImpl, `${baseUrl}/.well-known/oauth-protected-resource/mcp`);
|
|
69
|
+
const server = resource.authorization_servers[0];
|
|
70
|
+
if (!server)
|
|
71
|
+
throw new PidgeonError(500, 'discovery', 'Pidgeon named no authorization server.');
|
|
72
|
+
const metadata = await getJson(fetchImpl, `${server.replace(/\/+$/, '')}/.well-known/oauth-authorization-server`);
|
|
73
|
+
return { resource: resource.resource, metadata };
|
|
74
|
+
}
|
|
75
|
+
async function postForm(fetchImpl, url, form) {
|
|
76
|
+
const response = await fetchImpl(url, {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
79
|
+
body: new URLSearchParams(form).toString(),
|
|
80
|
+
});
|
|
81
|
+
const data = (await response.json().catch(() => null));
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
throw new PidgeonError(response.status, data?.error ?? 'oauth', data?.error_description ?? `${url} answered ${response.status}.`);
|
|
84
|
+
}
|
|
85
|
+
return data;
|
|
86
|
+
}
|
|
87
|
+
/** Open a URL in the person's browser; where none can be opened, they are shown the URL instead. */
|
|
88
|
+
export function openInBrowser(url) {
|
|
89
|
+
const [command, args] = process.platform === 'darwin'
|
|
90
|
+
? ['open', [url]]
|
|
91
|
+
: process.platform === 'win32'
|
|
92
|
+
? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
|
|
93
|
+
: ['xdg-open', [url]];
|
|
94
|
+
try {
|
|
95
|
+
spawn(command, args, { stdio: 'ignore', detached: true })
|
|
96
|
+
.on('error', () => { })
|
|
97
|
+
.unref();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// The URL was shown as well.
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const page = (title, line) => `<!doctype html><meta charset="utf-8"><title>${title}</title>` +
|
|
104
|
+
`<body style="font:16px system-ui;margin:4rem auto;max-width:28rem"><h1>${title}</h1><p>${line}</p>`;
|
|
105
|
+
/**
|
|
106
|
+
* Sign in with a browser: the person signs in to Pidgeon there and chooses
|
|
107
|
+
* what this machine may do (`scope` is the most it asks for). Resolves once
|
|
108
|
+
* they answer, with the session saved.
|
|
109
|
+
*
|
|
110
|
+
* `onUrl` is told the address to open, which is also opened in the browser
|
|
111
|
+
* unless `openBrowser` is false (a headless machine shows it instead).
|
|
112
|
+
*/
|
|
113
|
+
export async function signIn(options = {}) {
|
|
114
|
+
const env = options.env ?? process.env;
|
|
115
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
116
|
+
const baseUrl = (options.baseUrl ?? baseUrlOf(env)).replace(/\/+$/, '');
|
|
117
|
+
const { resource, metadata } = await discover(baseUrl, fetchImpl);
|
|
118
|
+
const previous = await readSession(baseUrl, env);
|
|
119
|
+
let clientId = previous?.issuer === metadata.issuer ? previous.clientId : null;
|
|
120
|
+
if (!clientId) {
|
|
121
|
+
if (!metadata.registration_endpoint)
|
|
122
|
+
throw new PidgeonError(500, 'discovery', 'Pidgeon offers no client registration.');
|
|
123
|
+
const response = await fetchImpl(metadata.registration_endpoint, {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
headers: { 'content-type': 'application/json' },
|
|
126
|
+
body: JSON.stringify({
|
|
127
|
+
client_name: options.clientName ?? 'Pidgeon CLI',
|
|
128
|
+
// Any port on the loopback matches this (RFC 8252 §7.3).
|
|
129
|
+
redirect_uris: ['http://127.0.0.1/callback'],
|
|
130
|
+
token_endpoint_auth_method: 'none',
|
|
131
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
132
|
+
response_types: ['code'],
|
|
133
|
+
}),
|
|
134
|
+
});
|
|
135
|
+
const registered = (await response.json().catch(() => null));
|
|
136
|
+
if (!response.ok || !registered?.client_id)
|
|
137
|
+
throw new PidgeonError(response.status, 'registration', 'Pidgeon did not register this client.');
|
|
138
|
+
clientId = registered.client_id;
|
|
139
|
+
}
|
|
140
|
+
const verifier = randomBytes(32).toString('base64url');
|
|
141
|
+
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
|
142
|
+
const state = randomBytes(16).toString('base64url');
|
|
143
|
+
let finish;
|
|
144
|
+
const answered = new Promise((r) => (finish = r));
|
|
145
|
+
const server = createServer((req, res) => {
|
|
146
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
147
|
+
if (url.pathname !== '/callback') {
|
|
148
|
+
res.writeHead(404).end();
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const error = url.searchParams.get('error');
|
|
152
|
+
const code = url.searchParams.get('code');
|
|
153
|
+
const fromIssuer = url.searchParams.get('iss');
|
|
154
|
+
if (url.searchParams.get('state') !== state || (fromIssuer && fromIssuer !== metadata.issuer)) {
|
|
155
|
+
res.writeHead(400, { 'content-type': 'text/html' });
|
|
156
|
+
res.end(page('That was not this sign-in', 'Start again from your terminal.'));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
res.writeHead(200, { 'content-type': 'text/html' });
|
|
160
|
+
if (error || !code) {
|
|
161
|
+
res.end(page('Not signed in', 'You can close this tab.'));
|
|
162
|
+
finish({ error: url.searchParams.get('error_description') ?? error ?? 'no code' });
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
res.end(page('Signed in', 'You can close this tab and go back.'));
|
|
166
|
+
finish({ code });
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
170
|
+
const { port } = server.address();
|
|
171
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
172
|
+
const authorize = new URL(metadata.authorization_endpoint);
|
|
173
|
+
for (const [name, value] of Object.entries({
|
|
174
|
+
response_type: 'code',
|
|
175
|
+
client_id: clientId,
|
|
176
|
+
redirect_uri: redirectUri,
|
|
177
|
+
code_challenge: challenge,
|
|
178
|
+
code_challenge_method: 'S256',
|
|
179
|
+
state,
|
|
180
|
+
scope: options.scope ?? 'admin',
|
|
181
|
+
resource,
|
|
182
|
+
})) {
|
|
183
|
+
authorize.searchParams.set(name, value);
|
|
184
|
+
}
|
|
185
|
+
options.onUrl?.(authorize.toString());
|
|
186
|
+
if (options.openBrowser !== false)
|
|
187
|
+
openInBrowser(authorize.toString());
|
|
188
|
+
let timer;
|
|
189
|
+
const timeout = new Promise((resolve) => {
|
|
190
|
+
timer = setTimeout(() => resolve({ error: 'Nobody answered in the browser in time.' }), options.timeoutMs ?? 5 * 60_000);
|
|
191
|
+
});
|
|
192
|
+
const result = await Promise.race([answered, timeout]).finally(() => {
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
server.close();
|
|
195
|
+
});
|
|
196
|
+
if ('error' in result)
|
|
197
|
+
throw new PidgeonError(401, 'not_signed_in', result.error);
|
|
198
|
+
const tokens = await postForm(fetchImpl, metadata.token_endpoint, {
|
|
199
|
+
grant_type: 'authorization_code',
|
|
200
|
+
code: result.code,
|
|
201
|
+
redirect_uri: redirectUri,
|
|
202
|
+
client_id: clientId,
|
|
203
|
+
code_verifier: verifier,
|
|
204
|
+
resource,
|
|
205
|
+
});
|
|
206
|
+
const session = {
|
|
207
|
+
baseUrl,
|
|
208
|
+
issuer: metadata.issuer,
|
|
209
|
+
tokenEndpoint: metadata.token_endpoint,
|
|
210
|
+
revocationEndpoint: metadata.revocation_endpoint ?? null,
|
|
211
|
+
resource,
|
|
212
|
+
clientId,
|
|
213
|
+
accessToken: tokens.access_token,
|
|
214
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
215
|
+
expiresAt: Date.now() + tokens.expires_in * 1000,
|
|
216
|
+
scope: tokens.scope,
|
|
217
|
+
};
|
|
218
|
+
await saveSession(session, env);
|
|
219
|
+
return session;
|
|
220
|
+
}
|
|
221
|
+
/** A live access token for the saved session, refreshed (and saved) when it is about to run out. */
|
|
222
|
+
export async function sessionToken(baseUrl, options = {}) {
|
|
223
|
+
const env = options.env ?? process.env;
|
|
224
|
+
const session = await readSession(baseUrl, env);
|
|
225
|
+
if (!session)
|
|
226
|
+
throw notSignedIn();
|
|
227
|
+
if (session.expiresAt - 60_000 > Date.now())
|
|
228
|
+
return session.accessToken;
|
|
229
|
+
if (!session.refreshToken)
|
|
230
|
+
throw notSignedIn();
|
|
231
|
+
const tokens = await postForm(options.fetch ?? fetch, session.tokenEndpoint, {
|
|
232
|
+
grant_type: 'refresh_token',
|
|
233
|
+
refresh_token: session.refreshToken,
|
|
234
|
+
client_id: session.clientId,
|
|
235
|
+
resource: session.resource,
|
|
236
|
+
}).catch((error) => {
|
|
237
|
+
if (error instanceof PidgeonError && error.code === 'invalid_grant')
|
|
238
|
+
throw notSignedIn();
|
|
239
|
+
throw error;
|
|
240
|
+
});
|
|
241
|
+
await saveSession({
|
|
242
|
+
...session,
|
|
243
|
+
accessToken: tokens.access_token,
|
|
244
|
+
refreshToken: tokens.refresh_token ?? session.refreshToken,
|
|
245
|
+
expiresAt: Date.now() + tokens.expires_in * 1000,
|
|
246
|
+
scope: tokens.scope,
|
|
247
|
+
}, env);
|
|
248
|
+
return tokens.access_token;
|
|
249
|
+
}
|
|
250
|
+
/** End the session: Pidgeon is told (which ends the connection there), and the tokens are forgotten. */
|
|
251
|
+
export async function signOut(baseUrl, options = {}) {
|
|
252
|
+
const env = options.env ?? process.env;
|
|
253
|
+
const all = await sessions(env);
|
|
254
|
+
const session = all[baseUrl];
|
|
255
|
+
if (!session)
|
|
256
|
+
return false;
|
|
257
|
+
if (session.revocationEndpoint) {
|
|
258
|
+
await postForm(options.fetch ?? fetch, session.revocationEndpoint, {
|
|
259
|
+
token: session.refreshToken ?? session.accessToken,
|
|
260
|
+
client_id: session.clientId,
|
|
261
|
+
}).catch(() => { });
|
|
262
|
+
}
|
|
263
|
+
delete all[baseUrl];
|
|
264
|
+
await writePrivate(credentialsPath(env), all);
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
const notSignedIn = () => new PidgeonError(401, 'not_signed_in', 'Not signed in to Pidgeon: run `pidgeon login`, or set PIDGEON_API_KEY.');
|
|
268
|
+
/**
|
|
269
|
+
* The API client for this machine: `PIDGEON_API_KEY` if it is set, else the
|
|
270
|
+
* signed-in session (refreshed as needed). Nothing is checked until the first call.
|
|
271
|
+
*/
|
|
272
|
+
export function clientFromEnvironment(options = {}) {
|
|
273
|
+
const env = options.env ?? process.env;
|
|
274
|
+
const baseUrl = options.baseUrl ?? baseUrlOf(env);
|
|
275
|
+
if (env.PIDGEON_API_KEY)
|
|
276
|
+
return new Pidgeon({ apiKey: env.PIDGEON_API_KEY, baseUrl, fetch: options.fetch });
|
|
277
|
+
return new Pidgeon({
|
|
278
|
+
baseUrl,
|
|
279
|
+
fetch: options.fetch,
|
|
280
|
+
getToken: () => sessionToken(baseUrl, { fetch: options.fetch, env }),
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
const agentsDir = (env) => join(configDir(env), 'agents');
|
|
284
|
+
/** Where an agent's key is kept on this machine. */
|
|
285
|
+
export const agentKeyPath = (agentId, env = process.env) => join(agentsDir(env), `${agentId.replace(/[^A-Za-z0-9-]/g, '')}.json`);
|
|
286
|
+
export async function saveAgentKey(entry, env = process.env) {
|
|
287
|
+
const path = agentKeyPath(entry.agent_id, env);
|
|
288
|
+
await writePrivate(path, entry);
|
|
289
|
+
return path;
|
|
290
|
+
}
|
|
291
|
+
export async function readAgentKey(agentId, env = process.env) {
|
|
292
|
+
return readJson(agentKeyPath(agentId, env));
|
|
293
|
+
}
|
|
294
|
+
/** Every agent key kept here, without their private halves. */
|
|
295
|
+
export async function listAgentKeys(env = process.env) {
|
|
296
|
+
const names = await readdir(agentsDir(env)).catch(() => []);
|
|
297
|
+
const out = [];
|
|
298
|
+
for (const name of names.filter((n) => n.endsWith('.json')).sort()) {
|
|
299
|
+
const path = join(agentsDir(env), name);
|
|
300
|
+
const entry = await readJson(path);
|
|
301
|
+
if (!entry)
|
|
302
|
+
continue;
|
|
303
|
+
const { private_jwk: _secret, ...shown } = entry;
|
|
304
|
+
out.push({ ...shown, path });
|
|
305
|
+
}
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
export async function forgetAgentKey(agentId, env = process.env) {
|
|
309
|
+
await rm(agentKeyPath(agentId, env), { force: true });
|
|
310
|
+
}
|
|
311
|
+
/** Your agent, from a key file this machine keeps: `fetch` signs every request as it. */
|
|
312
|
+
export async function agentFromKeyFile(path) {
|
|
313
|
+
const entry = await readJson(path);
|
|
314
|
+
if (!entry?.private_jwk || !entry.directory)
|
|
315
|
+
throw new Error(`${path} is not an agent key Pidgeon made.`);
|
|
316
|
+
return {
|
|
317
|
+
fetch: async (input, init) => {
|
|
318
|
+
const request = new Request(input, init);
|
|
319
|
+
const signature = await signAgentRequest(request, {
|
|
320
|
+
privateJwk: entry.private_jwk,
|
|
321
|
+
directory: entry.directory,
|
|
322
|
+
});
|
|
323
|
+
const headers = new Headers(request.headers);
|
|
324
|
+
for (const [name, value] of Object.entries(signature))
|
|
325
|
+
headers.set(name, value);
|
|
326
|
+
return fetch(new Request(request, { headers }));
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Register an agent, make its key on this machine, publish the public half
|
|
332
|
+
* signed with it (the possession proof the dashboard sends too), and keep
|
|
333
|
+
* the key here. Answers where the key is, never the key.
|
|
334
|
+
*/
|
|
335
|
+
export async function setUpAgent(pidgeon, input, env = process.env) {
|
|
336
|
+
const { agent, key, kid } = await pidgeon.agents.setUp(input);
|
|
337
|
+
const keyFile = await saveAgentKey({
|
|
338
|
+
agent_id: agent.id,
|
|
339
|
+
name: agent.name,
|
|
340
|
+
kid,
|
|
341
|
+
directory: agent.directory,
|
|
342
|
+
public_jwk: key.publicJwk,
|
|
343
|
+
private_jwk: key.privateJwk,
|
|
344
|
+
created_at: new Date().toISOString(),
|
|
345
|
+
}, env);
|
|
346
|
+
return { agent, kid, keyFile };
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* A new key for an agent already registered, made and kept here. It replaces
|
|
350
|
+
* the key this machine kept for that agent; the old one stays published
|
|
351
|
+
* until it is revoked in the dashboard.
|
|
352
|
+
*/
|
|
353
|
+
export async function addAgentKey(pidgeon, agentId, env = process.env) {
|
|
354
|
+
const agent = await pidgeon.agents.get(agentId);
|
|
355
|
+
const key = await generateAgentKey();
|
|
356
|
+
const { kid } = await pidgeon.publishKey({ agentId: agent.id, key, directory: agent.directory });
|
|
357
|
+
const keyFile = await saveAgentKey({
|
|
358
|
+
agent_id: agent.id,
|
|
359
|
+
name: agent.name,
|
|
360
|
+
kid,
|
|
361
|
+
directory: agent.directory,
|
|
362
|
+
public_jwk: key.publicJwk,
|
|
363
|
+
private_jwk: key.privateJwk,
|
|
364
|
+
created_at: new Date().toISOString(),
|
|
365
|
+
}, env);
|
|
366
|
+
return { kid, keyFile };
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* For a server that cannot make keys (the hosted MCP server): make the
|
|
370
|
+
* agent's key here, keep it, and answer what publishing it needs, never the
|
|
371
|
+
* key: the public half, and the signature headers of a `POST` to
|
|
372
|
+
* `publishUrl` made with the key, which is the possession proof. The proof
|
|
373
|
+
* holds for `lifetimeSeconds` (ten minutes), long enough to hand it over.
|
|
374
|
+
*/
|
|
375
|
+
export async function makeKeyProof(input, env = process.env) {
|
|
376
|
+
const url = new URL(input.publishUrl);
|
|
377
|
+
if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost')
|
|
378
|
+
throw new Error('The publish address must be https.');
|
|
379
|
+
if (!/\/v1\/agents\/[^/]+\/keys$/.test(url.pathname))
|
|
380
|
+
throw new Error('The publish address must be an agent’s /v1/agents/<id>/keys.');
|
|
381
|
+
const key = await generateAgentKey();
|
|
382
|
+
const signature = await signAgentRequest(new Request(url, { method: 'POST' }), {
|
|
383
|
+
privateJwk: key.privateJwk,
|
|
384
|
+
directory: input.directory,
|
|
385
|
+
lifetimeSeconds: input.lifetimeSeconds ?? 600,
|
|
386
|
+
});
|
|
387
|
+
const keyFile = await saveAgentKey({
|
|
388
|
+
agent_id: input.agentId,
|
|
389
|
+
name: input.name ?? input.agentId,
|
|
390
|
+
kid: key.kid,
|
|
391
|
+
directory: input.directory,
|
|
392
|
+
public_jwk: key.publicJwk,
|
|
393
|
+
private_jwk: key.privateJwk,
|
|
394
|
+
created_at: new Date().toISOString(),
|
|
395
|
+
}, env);
|
|
396
|
+
return {
|
|
397
|
+
agent_id: input.agentId,
|
|
398
|
+
kid: key.kid,
|
|
399
|
+
key_file: keyFile,
|
|
400
|
+
public_jwk: key.publicJwk,
|
|
401
|
+
signature,
|
|
402
|
+
};
|
|
403
|
+
}
|
package/package.json
CHANGED
|
@@ -1,66 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pidgeon-ai/sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Email
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
"email-api",
|
|
8
|
-
"inbox",
|
|
9
|
-
"ai-agents",
|
|
10
|
-
"agent",
|
|
11
|
-
"llm",
|
|
12
|
-
"mcp",
|
|
13
|
-
"otp",
|
|
14
|
-
"verification-code",
|
|
15
|
-
"pidgeon",
|
|
16
|
-
"webhooks",
|
|
17
|
-
"api-client"
|
|
18
|
-
],
|
|
19
|
-
"license": "MIT",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Pidgeon's TypeScript SDK: Passport, Bouncer, Email and Auth. Sign your agents' requests, verify agents at your site, send mail from agent inboxes, and Sign in with Pidgeon.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
20
7
|
"repository": {
|
|
21
8
|
"type": "git",
|
|
22
9
|
"url": "git+https://github.com/pidgeon-ai/pidgeon-js.git",
|
|
23
10
|
"directory": "packages/sdk"
|
|
24
11
|
},
|
|
25
12
|
"homepage": "https://pidgeon.ai",
|
|
26
|
-
"
|
|
27
|
-
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
28
16
|
"exports": {
|
|
29
17
|
".": {
|
|
30
|
-
"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./credential": {
|
|
22
|
+
"types": "./dist/credential.d.ts",
|
|
23
|
+
"default": "./dist/credential.js"
|
|
24
|
+
},
|
|
25
|
+
"./auth": {
|
|
26
|
+
"types": "./dist/auth.d.ts",
|
|
27
|
+
"default": "./dist/auth.js"
|
|
28
|
+
},
|
|
29
|
+
"./node": {
|
|
30
|
+
"types": "./dist/node.d.ts",
|
|
31
|
+
"default": "./dist/node.js"
|
|
38
32
|
}
|
|
39
33
|
},
|
|
40
|
-
"main": "./dist/index.cjs",
|
|
41
|
-
"module": "./dist/index.js",
|
|
42
|
-
"types": "./dist/index.d.ts",
|
|
43
34
|
"files": [
|
|
44
35
|
"dist",
|
|
45
36
|
"README.md",
|
|
46
37
|
"CHANGELOG.md",
|
|
47
38
|
"LICENSE"
|
|
48
39
|
],
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
|
|
52
|
-
"publishConfig": {
|
|
53
|
-
"access": "public"
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"web-bot-auth": "0.2.0",
|
|
42
|
+
"jose": "^6.2.17"
|
|
54
43
|
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"ai-agents",
|
|
46
|
+
"web-bot-auth",
|
|
47
|
+
"http-message-signatures",
|
|
48
|
+
"agent-identity",
|
|
49
|
+
"email",
|
|
50
|
+
"oauth",
|
|
51
|
+
"mcp"
|
|
52
|
+
],
|
|
55
53
|
"devDependencies": {
|
|
56
|
-
"
|
|
54
|
+
"@types/node": "^24.10.1",
|
|
57
55
|
"typescript": "^5"
|
|
58
56
|
},
|
|
59
|
-
"bugs": {
|
|
60
|
-
"url": "https://github.com/pidgeon-ai/pidgeon-js/issues"
|
|
61
|
-
},
|
|
62
57
|
"scripts": {
|
|
63
|
-
"build": "
|
|
64
|
-
"typecheck": "tsc --noEmit"
|
|
58
|
+
"build": "tsc -p tsconfig.build.json"
|
|
65
59
|
}
|
|
66
60
|
}
|