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