@zurchin/sdk 0.0.0 → 2.16.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/dist/index.js ADDED
@@ -0,0 +1,714 @@
1
+ /**
2
+ * Pidgeon's TypeScript SDK: email for founders, teams and agents.
3
+ *
4
+ * `new Pidgeon({ apiKey })`: `.inboxes`, `.messages` and `.drafts` give an
5
+ * agent its own address on @pidgeon.email or your domain, send from it and
6
+ * wait for the reply; `.threads`, `.labels`, `.contacts`, `.attachments`,
7
+ * `.domains` and `.calendar` are the rest of Email. For a platform, `.pods`
8
+ * gives each of your users inboxes of their own.
9
+ *
10
+ * Sign in with Pidgeon: `.agents.setUp()` registers an agent, makes its key
11
+ * here and publishes the public half; `signedFetch`, or `agentFromEnv().fetch`,
12
+ * signs its requests; `.sites` and `.mandates` register sites and ask
13
+ * people's permission. `generateAgentKey()` and `.publishKey()` make a key
14
+ * where the agent runs and publish its public half.
15
+ */
16
+ import { generateAgentKey, signAgentRequest, } from "./credential.js";
17
+ export * from "./credential.js";
18
+ export { DECLARED_AGENT_TOKENS, declaredAgentToken } from "./declared-agents.js";
19
+ /**
20
+ * Where the API is: zurchin.com since the switch from Pidgeon (pidgeon.ai keeps
21
+ * answering the API for six months, so a client pointed there still works). `auth.ts`, the CLI, the MCP server
22
+ * and the AI SDK tools read it from here.
23
+ */
24
+ export const DEFAULT_BASE_URL = 'https://zurchin.com';
25
+ /**
26
+ * A setting from the environment, by its name after the prefix: `ZURCHIN_<name>`
27
+ * first, then `PIDGEON_<name>` (Pidgeon is becoming Zurchin, and both names work).
28
+ * An empty value counts as unset.
29
+ */
30
+ export function envSetting(name, env = globalThis.process?.env ?? {}) {
31
+ return env[`ZURCHIN_${name}`] || env[`PIDGEON_${name}`] || undefined;
32
+ }
33
+ /** The header a proxy hands the verdict on in, to the app behind it. */
34
+ export const VERDICT_HEADER = 'pidgeon-verdict';
35
+ /** How long a verdict lasts after Pidgeon signs it. */
36
+ export const VERDICT_LIFETIME_SECONDS = 300;
37
+ export class PidgeonError extends Error {
38
+ status;
39
+ code;
40
+ constructor(status, code, message) {
41
+ super(message);
42
+ this.status = status;
43
+ this.code = code;
44
+ this.name = 'PidgeonError';
45
+ }
46
+ }
47
+ function headersOf(input) {
48
+ const raw = input.headers;
49
+ const out = {};
50
+ if (raw instanceof Headers) {
51
+ raw.forEach((value, name) => (out[name] = value));
52
+ return out;
53
+ }
54
+ for (const [name, value] of Object.entries(raw)) {
55
+ if (value !== undefined)
56
+ out[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : value;
57
+ }
58
+ return out;
59
+ }
60
+ /** The events a webhook can carry; the event log (`events.list`) holds more. */
61
+ export const WEBHOOK_EVENTS = [
62
+ 'report.created',
63
+ 'reputation.changed',
64
+ 'operator.reputation_changed',
65
+ 'mandate.requested',
66
+ 'mandate.granted',
67
+ 'mandate.declined',
68
+ 'mandate.revoked',
69
+ 'message.received',
70
+ 'message.held',
71
+ 'message.released',
72
+ 'message.blocked',
73
+ 'message.quarantined',
74
+ 'message.sent',
75
+ 'message.failed',
76
+ 'message.scheduled',
77
+ 'message.delivered',
78
+ 'message.delayed',
79
+ 'message.bounced',
80
+ 'message.complained',
81
+ 'message.rejected',
82
+ 'message.exfiltration_blocked',
83
+ 'draft.created',
84
+ 'draft.approval_requested',
85
+ 'draft.approved',
86
+ 'draft.rejected',
87
+ 'thread.updated',
88
+ 'thread.deleted',
89
+ 'inbox.created',
90
+ 'inbox.updated',
91
+ 'inbox.removed',
92
+ 'email.domain_added',
93
+ 'email.domain_verified',
94
+ 'email.domain_broken',
95
+ 'email.domain_removed',
96
+ 'calendar.event.created',
97
+ 'calendar.event.updated',
98
+ 'calendar.event.deleted',
99
+ ];
100
+ const messageBody = (input) => ({
101
+ to: input.to,
102
+ cc: input.cc,
103
+ bcc: input.bcc,
104
+ subject: input.subject,
105
+ text: input.text,
106
+ html: input.html,
107
+ reply_to: input.replyTo,
108
+ attachment_ids: input.attachmentIds,
109
+ });
110
+ const segment = (id) => encodeURIComponent(id);
111
+ /**
112
+ * The client for Pidgeon's API: the website's, the operator's, and a coding
113
+ * agent's. Keep the API key on a server. `apiKey` is an API key (`pgn_…`) or
114
+ * an OAuth access token (`pgn_oat_…`); `getToken` is asked before each
115
+ * request instead, for a token that is refreshed.
116
+ */
117
+ export class Pidgeon {
118
+ token;
119
+ baseUrl;
120
+ fetchImpl;
121
+ constructor(options) {
122
+ const { apiKey, getToken } = options;
123
+ if (getToken)
124
+ this.token = getToken;
125
+ else if (apiKey)
126
+ this.token = async () => apiKey;
127
+ else
128
+ throw new Error('Pidgeon needs an API key (Settings → API keys).');
129
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, '');
130
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
131
+ }
132
+ /** Any `/v1` call: the methods below are this with the path and body filled in. */
133
+ async request(method, path, options = {}) {
134
+ const url = new URL(`${this.baseUrl}${path}`);
135
+ for (const [name, value] of Object.entries(options.query ?? {})) {
136
+ if (value !== undefined)
137
+ url.searchParams.set(name, String(value));
138
+ }
139
+ const response = await this.fetchImpl(url, {
140
+ method,
141
+ headers: {
142
+ authorization: `Bearer ${await this.token()}`,
143
+ ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
144
+ ...options.headers,
145
+ },
146
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
147
+ });
148
+ if (response.status === 204)
149
+ return undefined;
150
+ const data = (await response.json().catch(() => null));
151
+ if (!response.ok) {
152
+ throw new PidgeonError(response.status, data?.error?.code ?? 'error', data?.error?.message ?? `Pidgeon answered ${response.status}.`);
153
+ }
154
+ return data;
155
+ }
156
+ // ---------------------------------------------------------------- Bouncer
157
+ /**
158
+ * Who stands behind an agent's request, and how they stand. Forward it as
159
+ * you received it. `ip`, the agent's address as your server saw it, is
160
+ * written into the answer's `verdict`, so a hook that sees the address can
161
+ * hold the verdict to it.
162
+ */
163
+ verify(request, options = {}) {
164
+ return this.request('POST', '/v1/verify', {
165
+ body: {
166
+ request: { method: request.method, url: request.url, headers: headersOf(request) },
167
+ ...(options.ip ? { ip: options.ip } : {}),
168
+ ...(options.place ? { place: options.place } : {}),
169
+ },
170
+ });
171
+ }
172
+ /**
173
+ * Check a verdict with Pidgeon, for a sign-up hook: signed by Pidgeon, for
174
+ * this account (and `origin`, and `ip`, when given), not expired, its key
175
+ * and agent not revoked since, and never checked before. Spending it is
176
+ * what an offline check (`verifyVerdict`, `@zurchin/sdk/verdict`)
177
+ * cannot do.
178
+ */
179
+ checkVerdict(verdict, options = {}) {
180
+ return this.request('POST', '/v1/verify/verdict', {
181
+ body: { verdict, ...options },
182
+ });
183
+ }
184
+ /** Report an agent from one of your verifications: what it did, in your words. */
185
+ report(input) {
186
+ return this.request('POST', '/v1/reports', {
187
+ body: {
188
+ verification_id: input.verificationId,
189
+ category: input.category,
190
+ evidence: input.evidence,
191
+ },
192
+ });
193
+ }
194
+ // --------------------------------------------------------------- Passport
195
+ /**
196
+ * Publish an agent identity's public key. The request is signed with the key itself,
197
+ * which is how Pidgeon knows you hold it; the private half never leaves you.
198
+ */
199
+ async publishKey(input) {
200
+ const path = `/v1/agents/${segment(input.agentId)}/keys`;
201
+ const signature = await signAgentRequest(new Request(`${this.baseUrl}${path}`, { method: 'POST' }), { privateJwk: input.key.privateJwk, directory: input.directory });
202
+ return this.request('POST', path, {
203
+ body: { public_jwk: input.key.publicJwk },
204
+ headers: signature,
205
+ });
206
+ }
207
+ /** Agent identities (once Passport): optional; an inbox works without one. */
208
+ agents = {
209
+ /** The account's agent identities, a page at a time. */
210
+ list: (options = {}) => this.request('GET', '/v1/agents', { query: options }),
211
+ /** Register an agent identity. It has no key until you make one where it runs and publish it. */
212
+ create: (input) => this.request('POST', '/v1/agents', {
213
+ body: { name: input.name, purpose: input.purpose ?? '', pod_id: input.podId },
214
+ }),
215
+ /** The agent identity, its keys, its directory and its operator's reputation. */
216
+ get: (id) => this.request('GET', `/v1/agents/${segment(id)}`),
217
+ /** Rename the agent identity, or change what its agent does: what websites see when it arrives. */
218
+ update: (id, input) => this.request('PATCH', `/v1/agents/${segment(id)}`, {
219
+ body: { name: input.name, purpose: input.purpose },
220
+ }),
221
+ /** Revoke the agent identity and every key it has. None verifies again; it cannot be undone. */
222
+ revoke: (id) => this.request('DELETE', `/v1/agents/${segment(id)}`),
223
+ /** Revoke one of the agent identity's keys, by its `kid`. Its other keys stay. */
224
+ revokeKey: (id, kid) => this.request('DELETE', `/v1/agents/${segment(id)}/keys/${segment(kid)}`),
225
+ /**
226
+ * Register an agent identity, make its key here, and publish the public half
227
+ * signed with it. Keep `key.privateJwk` where the agent runs: it is the
228
+ * agent's identity, and Pidgeon never sees it.
229
+ */
230
+ setUp: async (input) => {
231
+ const agent = await this.agents.create(input);
232
+ const key = await generateAgentKey();
233
+ const { kid } = await this.publishKey({
234
+ agentId: agent.id,
235
+ key,
236
+ directory: agent.directory,
237
+ });
238
+ return { agent, key, kid };
239
+ },
240
+ };
241
+ // ------------------------------------------------------------------ Email
242
+ inboxes = {
243
+ list: (options = {}) => this.request('GET', '/v1/email/inboxes', { query: options }),
244
+ get: (id) => this.request('GET', `/v1/email/inboxes/${segment(id)}`),
245
+ /**
246
+ * `name` is the part before the @. Optionally link it to an agent identity
247
+ * with `agentId`: its mail is then signed as that agent.
248
+ */
249
+ create: (input) => this.request('POST', '/v1/email/inboxes', {
250
+ body: {
251
+ name: input.name,
252
+ kind: input.kind ?? 'agent',
253
+ access: input.access,
254
+ display_name: input.displayName,
255
+ agent_id: input.agentId,
256
+ pod_id: input.podId,
257
+ domain: input.domain,
258
+ },
259
+ }),
260
+ /** Who reads an inbox: its access, its people and its keys. */
261
+ members: (id) => this.request('GET', `/v1/email/inboxes/${segment(id)}/members`),
262
+ /** Add a key (or a connected app) at a level, or a person of the team. Needs `admin`. */
263
+ addMember: (id, member) => this.request('POST', `/v1/email/inboxes/${segment(id)}/members`, {
264
+ body: 'keyId' in member
265
+ ? { key_id: member.keyId, level: member.level }
266
+ : { user_id: member.userId },
267
+ }),
268
+ /** Change the level a key was added at. Needs `admin`. */
269
+ updateMember: (id, memberId, level) => this.request('PATCH', `/v1/email/inboxes/${segment(id)}/members/${segment(memberId)}`, {
270
+ body: { level },
271
+ }),
272
+ /** Take a key or a person off an inbox. Needs `admin`. */
273
+ removeMember: (id, memberId) => this.request('DELETE', `/v1/email/inboxes/${segment(id)}/members/${segment(memberId)}`),
274
+ /**
275
+ * Choose who reads an inbox: `team`, `some` (the `people` given) or
276
+ * `agent` (its keys, and `people` supervising). Just me is a person's own
277
+ * choice, made in Pidgeon. Needs `admin`.
278
+ */
279
+ setAccess: (id, access, people) => this.request('PUT', `/v1/email/inboxes/${segment(id)}/access`, {
280
+ body: { access, people },
281
+ }),
282
+ /** Hold suspicious mail for a person. A key can turn holding on, never off. */
283
+ holdSuspicious: (id) => this.request('PATCH', `/v1/email/inboxes/${segment(id)}`, {
284
+ body: { hold_suspicious: true },
285
+ }),
286
+ /** Set the lines the mail client adds under mail a person writes from it; null clears it. Needs `admin`. */
287
+ setSignature: (id, signature) => this.request('PATCH', `/v1/email/inboxes/${segment(id)}`, {
288
+ body: { signature },
289
+ }),
290
+ /**
291
+ * Link the inbox to an agent identity in its pod, so its mail is signed as
292
+ * that agent; null unlinks it. Needs `admin` and a verified domain.
293
+ */
294
+ setAgent: (id, agentId) => this.request('PATCH', `/v1/email/inboxes/${segment(id)}`, {
295
+ body: { agent_id: agentId },
296
+ }),
297
+ /** Remove an inbox. Its address is retired, never given to anyone again. */
298
+ remove: (id) => this.request('DELETE', `/v1/email/inboxes/${segment(id)}`),
299
+ };
300
+ messages = {
301
+ /** Send from an inbox: `status` is `sent`, or `held` while a person approves it. */
302
+ send: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/messages`, {
303
+ body: messageBody(input),
304
+ }),
305
+ /** The inbox's mail, newest first. `body: 'clean'` serves the Firewall's cleaned text. */
306
+ list: (inboxId, options = {}) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/messages`, { query: options }),
307
+ get: (id, options = {}) => this.request('GET', `/v1/email/messages/${segment(id)}`, { query: options }),
308
+ /** Mark a received message read, or unread. */
309
+ markSeen: (id, seen = true) => this.request('PATCH', `/v1/email/messages/${segment(id)}`, { body: { seen } }),
310
+ /**
311
+ * Wait for mail: answers as soon as received mail newer than `since` (a
312
+ * time or a message id; default now) is there, or after `timeout`
313
+ * seconds (at most 50). Pass `next_since` back to wait for the next.
314
+ */
315
+ await: (inboxId, options = {}) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/messages/await`, {
316
+ query: options,
317
+ }),
318
+ /**
319
+ * Mail by words in its subject, sender or text, newest first:
320
+ * `search('invoice', { inboxId })`, or `search({ q: 'invoice', inboxId })`.
321
+ */
322
+ search: (query, options = {}) => {
323
+ const { q, ...rest } = typeof query === 'string' ? { ...options, q: query } : query;
324
+ if (typeof q !== 'string' || !q.trim()) {
325
+ return Promise.reject(new TypeError('messages.search needs the words to look for: search("invoice") or search({ q: "invoice" }).'));
326
+ }
327
+ return this.request('GET', '/v1/email/search', {
328
+ query: {
329
+ q,
330
+ inbox_id: rest.inboxId,
331
+ limit: rest.limit,
332
+ cursor: rest.cursor,
333
+ body: rest.body,
334
+ },
335
+ });
336
+ },
337
+ };
338
+ /** Conversations across your inboxes, and what is filed where. */
339
+ threads = {
340
+ list: (options = {}) => this.request('GET', '/v1/email/threads', {
341
+ query: {
342
+ inbox_id: options.inboxId,
343
+ folder: options.folder,
344
+ label_id: options.labelId,
345
+ status: options.status,
346
+ starred: options.starred ? 'true' : undefined,
347
+ limit: options.limit,
348
+ cursor: options.cursor,
349
+ },
350
+ }),
351
+ /** The conversation, and its messages oldest first. */
352
+ get: (id, options = {}) => this.request('GET', `/v1/email/threads/${segment(id)}`, { query: options }),
353
+ /** File, star or hand over: `{ ownerType: 'human', status: 'human_review' }` puts it before a person. */
354
+ update: (id, input) => this.request('PATCH', `/v1/email/threads/${segment(id)}`, {
355
+ body: {
356
+ folder: input.folder,
357
+ starred: input.starred,
358
+ status: input.status,
359
+ owner_type: input.ownerType,
360
+ assignee_id: input.assigneeId,
361
+ },
362
+ }),
363
+ /** Delete the conversation, its messages and files, for good. */
364
+ remove: (id) => this.request('DELETE', `/v1/email/threads/${segment(id)}`),
365
+ addLabel: (id, labelId) => this.request('POST', `/v1/email/threads/${segment(id)}/labels`, {
366
+ body: { label_id: labelId },
367
+ }),
368
+ removeLabel: (id, labelId) => this.request('DELETE', `/v1/email/threads/${segment(id)}/labels/${segment(labelId)}`),
369
+ };
370
+ /** An inbox's labels. */
371
+ labels = {
372
+ list: (inboxId) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/labels`),
373
+ create: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/labels`, { body: input }),
374
+ update: (id, input) => this.request('PATCH', `/v1/email/labels/${segment(id)}`, { body: input }),
375
+ remove: (id) => this.request('DELETE', `/v1/email/labels/${segment(id)}`),
376
+ };
377
+ /** Files: those that arrived, and uploads to send. */
378
+ attachments = {
379
+ /** Its details and a link to its bytes that lasts five minutes. */
380
+ get: (id) => this.request('GET', `/v1/email/attachments/${segment(id)}`),
381
+ /** Upload a file to send (name its id in `attachmentIds`). Up to 25 MB; over 4 MB goes straight to storage. */
382
+ upload: async (inboxId, file) => {
383
+ const blob = file.content instanceof Blob
384
+ ? file.content
385
+ : new Blob([file.content], { type: file.contentType });
386
+ if (blob.size <= 4 * 1024 * 1024) {
387
+ const form = new FormData();
388
+ form.set('file', new File([blob], file.filename, { type: file.contentType }));
389
+ return this.multipart(`/v1/email/inboxes/${segment(inboxId)}/attachments`, form);
390
+ }
391
+ const made = await this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/attachments/uploads`, { body: { filename: file.filename, content_type: file.contentType, size: blob.size } });
392
+ const put = await this.fetchImpl(made.upload.url, {
393
+ method: 'PUT',
394
+ headers: { 'content-type': file.contentType },
395
+ body: blob,
396
+ });
397
+ if (!put.ok)
398
+ throw new PidgeonError(put.status, 'upload_failed', 'Storage refused the file.');
399
+ return this.request('POST', `/v1/email/attachments/${segment(made.id)}/complete`, {
400
+ body: {},
401
+ });
402
+ },
403
+ };
404
+ /** Who an inbox corresponds with. */
405
+ contacts = {
406
+ list: (options = {}) => this.request('GET', '/v1/email/contacts', {
407
+ query: {
408
+ inbox_id: options.inboxId,
409
+ search: options.search,
410
+ limit: options.limit,
411
+ cursor: options.cursor,
412
+ },
413
+ }),
414
+ get: (id) => this.request('GET', `/v1/email/contacts/${segment(id)}`),
415
+ update: (id, input) => this.request('PATCH', `/v1/email/contacts/${segment(id)}`, { body: input }),
416
+ remove: (id) => this.request('DELETE', `/v1/email/contacts/${segment(id)}`),
417
+ };
418
+ /** Each inbox's calendar. */
419
+ calendar = {
420
+ list: (inboxId, options = {}) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/events`, { query: options }),
421
+ get: (id) => this.request('GET', `/v1/email/events/${segment(id)}`),
422
+ create: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/events`, {
423
+ body: {
424
+ title: input.title,
425
+ start: input.start,
426
+ end: input.end,
427
+ all_day: input.allDay,
428
+ description: input.description,
429
+ location: input.location,
430
+ attendees: input.attendees,
431
+ send_invites: input.sendInvites,
432
+ },
433
+ }),
434
+ update: (id, input) => this.request('PATCH', `/v1/email/events/${segment(id)}`, {
435
+ body: {
436
+ title: input.title,
437
+ start: input.start,
438
+ end: input.end,
439
+ all_day: input.allDay,
440
+ description: input.description,
441
+ location: input.location,
442
+ attendees: input.attendees,
443
+ send_invites: input.sendInvites,
444
+ },
445
+ }),
446
+ /** With `sendInvites`, the attendees are sent a cancellation first (a key with `send` access). */
447
+ remove: (id, options = {}) => this.request('DELETE', `/v1/email/events/${segment(id)}`, {
448
+ query: options.sendInvites ? { send_invites: 'true' } : undefined,
449
+ }),
450
+ };
451
+ /**
452
+ * Your domains, waiting and proved: add one (in a pod, for a platform's
453
+ * customer), publish its `records`, `verify`, then turn mail on for inboxes
454
+ * at it. A key of one pod reaches its own pod's domains only.
455
+ */
456
+ domains = {
457
+ list: () => this.request('GET', '/v1/domains'),
458
+ get: (id) => this.request('GET', `/v1/domains/${segment(id)}`),
459
+ /** Add a domain; answers it with the `_pidgeon` TXT record that proves it. */
460
+ create: (domain, options = {}) => this.request('POST', '/v1/domains', { body: { domain, pod_id: options.podId } }),
461
+ /** Look for the TXT record now; `verified` is true once it is found. */
462
+ verify: (id) => this.request('POST', `/v1/domains/${segment(id)}/verify`, { body: {} }),
463
+ /** Remove a domain; a proved one's mail is turned off first, and none may be left at it (`409`). */
464
+ remove: (id) => this.request('DELETE', `/v1/domains/${segment(id)}`),
465
+ /** Turn mail on for a domain you proved; answers the DNS records to set. */
466
+ enableMail: (id) => this.request('POST', `/v1/email/domains/${segment(id)}/mail`, { body: {} }),
467
+ disableMail: (id) => this.request('DELETE', `/v1/email/domains/${segment(id)}/mail`),
468
+ /** Ask DNS and the mail service where the domain stands now. */
469
+ check: (id) => this.request('POST', `/v1/email/domains/${segment(id)}/check`, { body: {} }),
470
+ };
471
+ /** Passwords for mail apps (IMAP, SMTP, CalDAV), one inbox each. */
472
+ appPasswords = {
473
+ list: (inboxId) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/app-passwords`),
474
+ /** Answers `password` this once. */
475
+ create: (inboxId, name) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/app-passwords`, {
476
+ body: { name },
477
+ }),
478
+ revoke: (id) => this.request('DELETE', `/v1/email/app-passwords/${segment(id)}`),
479
+ };
480
+ /** How much of the account's 10 GB its mail and files use. */
481
+ storage() {
482
+ return this.request('GET', '/v1/email/storage');
483
+ }
484
+ /** With a test key: deliver a message to one of your inboxes as if from outside, marked test. */
485
+ testInbound(input) {
486
+ return this.request('POST', '/v1/email/test/inbound', {
487
+ body: {
488
+ inbox_id: input.inboxId,
489
+ from: input.from,
490
+ from_name: input.fromName,
491
+ subject: input.subject,
492
+ text: input.text,
493
+ html: input.html,
494
+ in_reply_to: input.inReplyTo,
495
+ },
496
+ });
497
+ }
498
+ drafts = {
499
+ create: (inboxId, input) => this.request('POST', `/v1/email/inboxes/${segment(inboxId)}/drafts`, {
500
+ body: messageBody(input),
501
+ }),
502
+ get: (id) => this.request('GET', `/v1/email/drafts/${segment(id)}`),
503
+ /** Replace a draft's addresses and body; its thread stays, so `replyTo` is not taken. */
504
+ update: (id, input) => this.request('PATCH', `/v1/email/drafts/${segment(id)}`, { body: messageBody(input) }),
505
+ remove: (id) => this.request('DELETE', `/v1/email/drafts/${segment(id)}`),
506
+ /** Send now, or at `sendAt` (up to 90 days ahead). */
507
+ send: (id, options = {}) => this.request('POST', `/v1/email/drafts/${segment(id)}/send`, {
508
+ body: {
509
+ send_at: options.sendAt instanceof Date ? options.sendAt.toISOString() : options.sendAt,
510
+ },
511
+ }),
512
+ /** Hold it for a person of the account to send or reject (`draft.approval_requested` carries the link). */
513
+ requestApproval: (id) => this.request('POST', `/v1/email/drafts/${segment(id)}/approval`, { body: {} }),
514
+ };
515
+ /** Send and receive rules, for one inbox or (`inboxId` left out) every inbox. Keys of the whole account only. */
516
+ rules = {
517
+ list: () => this.request('GET', '/v1/email/rules'),
518
+ create: (input) => this.request('POST', '/v1/email/rules', {
519
+ body: {
520
+ direction: input.direction,
521
+ action: input.action,
522
+ pattern: input.pattern,
523
+ inbox_id: input.inboxId ?? null,
524
+ },
525
+ }),
526
+ remove: (id) => this.request('DELETE', `/v1/email/rules/${segment(id)}`),
527
+ };
528
+ /** The do-not-send list: bounces and complaints put addresses on it; you can too. */
529
+ suppressions = {
530
+ list: () => this.request('GET', '/v1/email/suppressions'),
531
+ add: (address) => this.request('POST', '/v1/email/suppressions', { body: { address } }),
532
+ remove: (address) => this.request('DELETE', '/v1/email/suppressions', { query: { address } }),
533
+ };
534
+ // ------------------------------------------------------------------- Auth
535
+ /** Sites registered for Sign in with Pidgeon. */
536
+ sites = {
537
+ list: () => this.request('GET', '/v1/auth/clients'),
538
+ /** Answers `client_secret` once: keep it on the site's server. */
539
+ create: (input) => this.request('POST', '/v1/auth/clients', {
540
+ body: { name: input.name, redirect_uris: input.redirectUris, pod_id: input.podId },
541
+ }),
542
+ /** Rename it, or replace its return addresses (the whole list); its id and secret stay. */
543
+ update: (clientId, input) => this.request('PATCH', `/v1/auth/clients/${segment(clientId)}`, {
544
+ body: { name: input.name, redirect_uris: input.redirectUris },
545
+ }),
546
+ /** A new `client_secret`, answered once; the old one stops working at once. */
547
+ rotateSecret: (clientId) => this.request('POST', `/v1/auth/clients/${segment(clientId)}/rotate-secret`),
548
+ remove: (clientId) => this.request('DELETE', `/v1/auth/clients/${segment(clientId)}`),
549
+ };
550
+ /** A person's permission for one of your agents to act for them at one site. */
551
+ mandates = {
552
+ list: () => this.request('GET', '/v1/auth/mandates'),
553
+ /** Answers `consent_url`: send it to the person, who allows or declines. */
554
+ create: (input) => this.request('POST', '/v1/auth/mandates', {
555
+ body: {
556
+ agent_id: input.agentId,
557
+ client_id: input.clientId,
558
+ scope: input.scope,
559
+ description: input.description,
560
+ days: input.days,
561
+ },
562
+ }),
563
+ revoke: (id) => this.request('DELETE', `/v1/auth/mandates/${segment(id)}`),
564
+ };
565
+ // ---------------------------------------------------------------- Account
566
+ events = {
567
+ /** The account's event log, newest first. */
568
+ list: (options = {}) => this.request('GET', '/v1/events', { query: options }),
569
+ };
570
+ pods = {
571
+ list: () => this.request('GET', '/v1/pods'),
572
+ create: (name) => this.request('POST', '/v1/pods', { body: { name } }),
573
+ /** Rename a pod. Its id, and everything in it, stay as they are. */
574
+ rename: (id, name) => this.request('PATCH', `/v1/pods/${segment(id)}`, { body: { name } }),
575
+ /**
576
+ * Move an agent, an address (`inbox`), a domain, a webhook endpoint or a
577
+ * site (by client id) into a pod. An agent takes its addresses and their
578
+ * mail with it; an address that belongs to an agent moves only with it.
579
+ */
580
+ move: (id, thing) => this.request('POST', `/v1/pods/${segment(id)}/move`, { body: thing }),
581
+ /** Remove an empty pod. Not the default pod, and not one with agents, domains or endpoints in it. */
582
+ remove: (id) => this.request('DELETE', `/v1/pods/${segment(id)}`),
583
+ };
584
+ /**
585
+ * Bouncer's site rules: per place, who gets in and whether the rule acts
586
+ * or only watches. Reading takes any key; setting takes an admin key of the
587
+ * whole account.
588
+ */
589
+ siteRules = {
590
+ get: () => this.request('GET', '/v1/site-rules'),
591
+ /** Change some places; the rest stay as they are. Answers every place. */
592
+ set: (rules) => this.request('PUT', '/v1/site-rules', { body: rules }),
593
+ };
594
+ /**
595
+ * Visits of agents that only name themselves (`declared`), recorded in a
596
+ * batch after the responses, not counted as verifications. Up to 100 a
597
+ * call; a User-Agent not on Pidgeon's list is skipped, not stored. Send
598
+ * signed requests to `verify`. `bouncer()` (`@zurchin/sdk/next`) does
599
+ * this for you.
600
+ */
601
+ visits = {
602
+ record: (visits) => this.request('POST', '/v1/visits', { body: { visits } }),
603
+ };
604
+ /** Your API keys. Making and revoking takes an admin key of the whole account. */
605
+ keys = {
606
+ list: () => this.request('GET', '/v1/keys'),
607
+ /** Answers `key` once. Never stronger than the key making it; a test key makes test keys. */
608
+ create: (input) => this.request('POST', '/v1/keys', {
609
+ body: { name: input.name, access: input.access, pod_id: input.podId, test: input.test },
610
+ }),
611
+ /**
612
+ * Make a key and put it straight on a Vercel project as a sensitive
613
+ * variable, through the account's Vercel installation: the key is never
614
+ * in the answer. `targets`: production and preview when left out.
615
+ */
616
+ deliverToVercel: (input) => this.request('POST', '/v1/keys', {
617
+ body: {
618
+ name: input.name,
619
+ access: input.access,
620
+ pod_id: input.podId,
621
+ test: input.test,
622
+ deliver_to: {
623
+ vercel_project_id: input.vercelProjectId,
624
+ env_name: input.envName,
625
+ targets: input.targets,
626
+ },
627
+ },
628
+ }),
629
+ revoke: (id) => this.request('DELETE', `/v1/keys/${segment(id)}`),
630
+ };
631
+ /** Your webhook endpoints. A key of the whole account only. */
632
+ webhooks = {
633
+ list: () => this.request('GET', '/v1/webhooks'),
634
+ /**
635
+ * Answers `secret` once: check each delivery's signature with it (`verifyWebhook`).
636
+ * With `inboxIds` it hears only those inboxes' events. `podId` puts it in a
637
+ * pod, where it hears that pod's events; left out, the default pod, where it
638
+ * hears the whole account. A key of one pod adds to its own pod only.
639
+ */
640
+ create: (input) => this.request('POST', '/v1/webhooks', {
641
+ body: {
642
+ url: input.url,
643
+ events: input.events,
644
+ inbox_ids: input.inboxIds,
645
+ pod_id: input.podId,
646
+ },
647
+ }),
648
+ remove: (id) => this.request('DELETE', `/v1/webhooks/${segment(id)}`),
649
+ };
650
+ /** A multipart POST (uploads): the same authentication and errors as `request`. */
651
+ async multipart(path, form) {
652
+ const response = await this.fetchImpl(new URL(`${this.baseUrl}${path}`), {
653
+ method: 'POST',
654
+ headers: { authorization: `Bearer ${await this.token()}` },
655
+ body: form,
656
+ });
657
+ const data = (await response.json().catch(() => null));
658
+ if (!response.ok) {
659
+ throw new PidgeonError(response.status, data?.error?.code ?? 'error', data?.error?.message ?? `Pidgeon answered ${response.status}.`);
660
+ }
661
+ return data;
662
+ }
663
+ }
664
+ /** `fetch`, signed as your agent: every request carries its Web Bot Auth signature. */
665
+ export async function signedFetch(input, init, agent) {
666
+ const request = new Request(input, init);
667
+ const signature = await signAgentRequest(request, agent);
668
+ const headers = new Headers(request.headers);
669
+ for (const [name, value] of Object.entries(signature))
670
+ headers.set(name, value);
671
+ return fetch(new Request(request, { headers }));
672
+ }
673
+ /** Your agent, from `ZURCHIN_AGENT_KEY` (else `PIDGEON_AGENT_KEY`) and `ZURCHIN_DIRECTORY` (else `PIDGEON_DIRECTORY`); the dashboard gives both. */
674
+ export function agentFromEnv(env = process.env) {
675
+ const key = envSetting('AGENT_KEY', env);
676
+ const directory = envSetting('DIRECTORY', env);
677
+ if (!key || !directory) {
678
+ throw new Error('Set ZURCHIN_AGENT_KEY and ZURCHIN_DIRECTORY (or PIDGEON_AGENT_KEY and PIDGEON_DIRECTORY): your agent’s page on pidgeon.ai has both.');
679
+ }
680
+ const privateJwk = JSON.parse(key);
681
+ return { fetch: (input, init) => signedFetch(input, init, { privateJwk, directory }) };
682
+ }
683
+ export { generateAgentKey };
684
+ async function hmacHex(secret, message) {
685
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
686
+ const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message)));
687
+ return Array.from(mac, (byte) => byte.toString(16).padStart(2, '0')).join('');
688
+ }
689
+ /**
690
+ * Check a webhook's `Pidgeon-Signature` header against your endpoint's secret
691
+ * and return the event, or throw. Pass the raw body as received, before any
692
+ * JSON parsing. Signatures older than `toleranceSeconds` are refused, so a
693
+ * captured delivery cannot be replayed later.
694
+ */
695
+ export async function verifyWebhook(secret, rawBody, signatureHeader, options = {}) {
696
+ const parts = Object.fromEntries((signatureHeader ?? '').split(',').map((part) => part.trim().split('=')));
697
+ const timestamp = Number(parts.t);
698
+ if (!Number.isInteger(timestamp) || typeof parts.v1 !== 'string') {
699
+ throw new PidgeonError(400, 'invalid_signature', 'The Pidgeon-Signature header is missing or malformed.');
700
+ }
701
+ const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
702
+ if (Math.abs(now - timestamp) > (options.toleranceSeconds ?? 300)) {
703
+ throw new PidgeonError(400, 'stale_signature', 'The webhook was signed too long ago.');
704
+ }
705
+ const expected = await hmacHex(secret, `${timestamp}.${rawBody}`);
706
+ let same = expected.length === parts.v1.length;
707
+ for (let i = 0; i < expected.length; i++)
708
+ same = same && expected[i] === parts.v1[i];
709
+ if (!same)
710
+ throw new PidgeonError(400, 'invalid_signature', 'The webhook signature does not match.');
711
+ return JSON.parse(rawBody);
712
+ }
713
+ /** The same client and error under the name Pidgeon is becoming. */
714
+ export { Pidgeon as Zurchin, PidgeonError as ZurchinError };