@pidgeon-ai/sdk 2.1.1 → 2.4.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 CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.4.0
4
+
5
+ - `signedFetch`, `agentFromEnv().fetch` and `agentFromKeyFile().fetch` send
6
+ a request with a body. They threw "Cannot construct a Request with a
7
+ Request object that has already been used" on any POST or PUT with one.
8
+ - Every signature carries a fresh 64-byte nonce and covers `@query` (`?`
9
+ when the URL has none), so neither the query nor the signature can be
10
+ reused: sign again to retry. `newNonce()`; `signAgentRequest` takes
11
+ `nonce` for tests. `verifyAgentRequest` answers the signature's `nonce`.
12
+ - `VerifyAnswer`: `replay_protected`, and the reason `replayed`.
13
+ - `messages.search` takes `search(q, options)` or `search({ q, ...options })`;
14
+ with no words it rejects with a `TypeError` instead of answering nothing.
15
+ - `agents.update`, `agents.revoke`, `agents.revokeKey` and `pods.remove`.
16
+ - `WEBHOOK_EVENTS` has `mandate.requested`, `mandate.granted`,
17
+ `mandate.declined` and `mandate.revoked`.
18
+ - Typings no longer cite documents outside the package.
19
+
20
+ ## 2.3.0
21
+
22
+ - `messages.search` takes `body: 'clean'`, as reading does.
23
+ - `WEBHOOK_EVENTS` and `WebhookEventType`: the events a webhook carries.
24
+ `webhooks.create`, `Webhook.events` and `WebhookPayload.type` use them,
25
+ so a misspelt event fails to compile rather than with a 400.
26
+ - Types say what the API answers: `CalendarEvent` in full, `Site` with
27
+ `created_at`, `Mandate.status` and `request_expires_at`, `Inbox.status`.
28
+ - `calendar.update` takes `null` to clear `description` or `location`;
29
+ `calendar.create` takes no `end` for an all-day event; `subject` and
30
+ `testInbound`'s `subject` are optional, as in the API.
31
+ - `drafts.update` no longer takes `replyTo`: a draft keeps its conversation.
32
+
33
+ ## 2.2.0
34
+
35
+ - `webhooks.create` takes `inboxIds`: the endpoint hears only those inboxes'
36
+ events. `Webhook` has `inbox_ids`, null for one of the whole account.
37
+
3
38
  ## 2.1.1
4
39
 
5
40
  - `calendar.create` and `calendar.update` take `attendees` and `sendInvites`,
package/README.md CHANGED
@@ -40,9 +40,17 @@ import { agentFromEnv } from '@pidgeon-ai/sdk';
40
40
 
41
41
  // PIDGEON_AGENT_KEY is the private JWK, PIDGEON_DIRECTORY the agent's directory.
42
42
  const agent = agentFromEnv();
43
- await agent.fetch('https://shop.example/api/orders', { method: 'POST' });
43
+ await agent.fetch('https://shop.example/api/orders', {
44
+ method: 'POST',
45
+ headers: { 'content-type': 'application/json' },
46
+ body: JSON.stringify({ sku: 'tea' }),
47
+ });
44
48
  ```
45
49
 
50
+ Each call is signed afresh: the signature covers the host, method, path and
51
+ query, carries a new nonce, and lasts a minute. Pidgeon accepts a signature
52
+ once, so sign again to retry; never resend old signature headers.
53
+
46
54
  ## Verify an agent at your site (Bouncer)
47
55
 
48
56
  ```ts
@@ -4,7 +4,7 @@ export type PublicJwk = {
4
4
  crv: 'Ed25519';
5
5
  x: string;
6
6
  };
7
- /** Both halves. The private half never reaches Pidgeon (docs/plan.md §3). */
7
+ /** Both halves. The private half never reaches Pidgeon. */
8
8
  export type AgentKeyPair = {
9
9
  kid: string;
10
10
  publicJwk: PublicJwk;
@@ -15,10 +15,15 @@ export declare const DEFAULT_LIFETIME_SECONDS = 60;
15
15
  /**
16
16
  * The longest a signature lasts, whatever the signer asks, and the oldest a
17
17
  * verifier accepts, whatever its `expires` says: five minutes, so a captured
18
- * request is soon useless (docs/plan.md §5: short lifetimes). The draft's own
18
+ * request is soon useless. The draft's own
19
19
  * ceiling, a day, left a copied request replayable at the same site all day.
20
20
  */
21
21
  export declare const MAX_LIFETIME_SECONDS: number;
22
+ /**
23
+ * A fresh nonce: 64 random bytes, base64url (Web Bot Auth §4.2.2). A
24
+ * verifier that remembers nonces refuses the same signature twice.
25
+ */
26
+ export declare function newNonce(): string;
22
27
  /** An operator's directory: where its agents' public keys are published. */
23
28
  export declare function directoryUrl(slug: string, host?: string): string;
24
29
  /** A key's id: its JWK SHA-256 thumbprint (RFC 7638), Web Bot Auth's `keyid`. */
@@ -29,13 +34,16 @@ export declare function isPublicJwk(value: unknown): value is PublicJwk;
29
34
  export declare function generateAgentKey(): Promise<AgentKeyPair>;
30
35
  /**
31
36
  * Sign a request as an agent: returns the headers to add. The request must
32
- * not carry a Signature-Agent of its own; this sets it.
37
+ * not carry a Signature-Agent of its own; this sets it. Every signature has
38
+ * a fresh nonce, so sign again for each send, retries included; `nonce` is
39
+ * for tests that need the same bytes twice.
33
40
  */
34
41
  export declare function signAgentRequest(request: Request, options: {
35
42
  privateJwk: JsonWebKey;
36
43
  directory: string;
37
44
  lifetimeSeconds?: number;
38
45
  now?: Date;
46
+ nonce?: string;
39
47
  }): Promise<Record<string, string>>;
40
48
  /** Why a request's credential was not accepted, in the API's words. */
41
49
  export type Rejection = 'unsigned' | 'invalid' | 'unknown_key' | 'expired';
@@ -45,6 +53,8 @@ export type Verification = {
45
53
  directory: string | null;
46
54
  created: Date;
47
55
  expires: Date;
56
+ /** The signature's nonce, when it has one: remember it to refuse the same signature twice. */
57
+ nonce: string | null;
48
58
  } | {
49
59
  ok: false;
50
60
  reason: Rejection;
@@ -1,19 +1,21 @@
1
1
  /**
2
- * The agent credential (docs/plan.md §5): Web Bot Auth, unchanged.
2
+ * The agent credential: Web Bot Auth, unchanged.
3
3
  *
4
4
  * An agent signs each request with its Ed25519 key under HTTP Message
5
5
  * Signatures (RFC 9421), tagged `web-bot-auth`, covering the request's
6
- * authority, method and path and the `Signature-Agent` header, which points
6
+ * authority, method, path and query and the `Signature-Agent` header, which points
7
7
  * at its operator's directory on Pidgeon. Signing and verifying are
8
8
  * Cloudflare's open-source `web-bot-auth`; this module fixes our choices on
9
9
  * top of it and nothing more.
10
10
  *
11
- * Choices, each from the plan:
11
+ * Choices:
12
12
  * - Ed25519 only, because Cloudflare accepts nothing else.
13
13
  * - `Signature-Agent` in the string form (`"https://…"`), which Cloudflare
14
14
  * requires today; the verifier accepts the working group's dictionary form
15
15
  * too.
16
16
  * - A minute's lifetime by default, so a captured request is useless soon.
17
+ * - A fresh nonce in every signature, so a verifier that remembers them
18
+ * accepts each signature once.
17
19
  */
18
20
  import { jwkToKeyID, sign, verify } from 'web-bot-auth';
19
21
  import { signerFromJWK, verifierFromJWK } from 'web-bot-auth/crypto';
@@ -22,14 +24,30 @@ export const DEFAULT_LIFETIME_SECONDS = 60;
22
24
  /**
23
25
  * The longest a signature lasts, whatever the signer asks, and the oldest a
24
26
  * verifier accepts, whatever its `expires` says: five minutes, so a captured
25
- * request is soon useless (docs/plan.md §5: short lifetimes). The draft's own
27
+ * request is soon useless. The draft's own
26
28
  * ceiling, a day, left a copied request replayable at the same site all day.
27
29
  */
28
30
  export const MAX_LIFETIME_SECONDS = 5 * 60;
29
31
  /** How far an agent's clock may run ahead of the verifier's. */
30
32
  const CLOCK_SKEW_SECONDS = 30;
31
- /** What the signature covers beyond the authority and the Signature-Agent. */
32
- const COVERED = ['@method', '@path'];
33
+ /**
34
+ * What the signature covers beyond the authority and the Signature-Agent:
35
+ * the method, the path and the query. The query is covered when the URL has
36
+ * none too (its value is then `?`), so one cannot be added in transit.
37
+ */
38
+ const COVERED = ['@method', '@path', '@query'];
39
+ /**
40
+ * A fresh nonce: 64 random bytes, base64url (Web Bot Auth §4.2.2). A
41
+ * verifier that remembers nonces refuses the same signature twice.
42
+ */
43
+ export function newNonce() {
44
+ const bytes = new Uint8Array(64);
45
+ crypto.getRandomValues(bytes);
46
+ let binary = '';
47
+ for (const byte of bytes)
48
+ binary += String.fromCharCode(byte);
49
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
50
+ }
33
51
  /** An operator's directory: where its agents' public keys are published. */
34
52
  export function directoryUrl(slug, host = process.env.AGENTS_HOST ?? 'agents.pidgeon.ai') {
35
53
  return `https://${slug}.${host}`;
@@ -70,7 +88,9 @@ export async function generateAgentKey() {
70
88
  }
71
89
  /**
72
90
  * Sign a request as an agent: returns the headers to add. The request must
73
- * not carry a Signature-Agent of its own; this sets it.
91
+ * not carry a Signature-Agent of its own; this sets it. Every signature has
92
+ * a fresh nonce, so sign again for each send, retries included; `nonce` is
93
+ * for tests that need the same bytes twice.
74
94
  */
75
95
  export async function signAgentRequest(request, options) {
76
96
  const now = options.now ?? new Date();
@@ -78,11 +98,15 @@ export async function signAgentRequest(request, options) {
78
98
  const signatureAgent = `"${options.directory}"`;
79
99
  const headers = new Headers(request.headers);
80
100
  headers.set('signature-agent', signatureAgent);
81
- const signed = new Request(request, { headers });
101
+ // The signature covers the authority, method, path and Signature-Agent,
102
+ // never the body, so sign a body-less copy: building it from `request`
103
+ // itself would consume the body and leave the caller nothing to send.
104
+ const signed = new Request(request.url, { method: request.method, headers });
82
105
  const fields = await sign(signed, {
83
106
  signer: await signerFromJWK(options.privateJwk),
84
107
  created: now,
85
108
  expires: new Date(now.getTime() + lifetime * 1000),
109
+ nonce: options.nonce ?? newNonce(),
86
110
  additionalComponents: COVERED,
87
111
  });
88
112
  return {
@@ -122,6 +146,7 @@ export async function verifyAgentRequest(request, findKey, options = {}) {
122
146
  directory: verified.signatureAgent?.uri ?? null,
123
147
  created: verified.created,
124
148
  expires: verified.expires,
149
+ nonce: verified.nonce ?? null,
125
150
  };
126
151
  }
127
152
  catch (error) {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Pidgeon's TypeScript SDK (docs/plan.md §11).
2
+ * Pidgeon's TypeScript SDK.
3
3
  *
4
4
  * For an agent: `signedFetch`, or `agentFromEnv().fetch`, signs every request
5
5
  * with the agent's key, so a website that checks can tell who stands behind it.
@@ -19,7 +19,7 @@ import { generateAgentKey, type AgentKeyPair } from './credential.ts';
19
19
  export * from './credential.ts';
20
20
  export declare const DEFAULT_BASE_URL = "https://pidgeon.ai";
21
21
  export type Band = 'unverified' | 'new' | 'good' | 'flagged' | 'suspended';
22
- /** What `verify` answers (docs/plan.md §6). */
22
+ /** What `verify` answers. */
23
23
  export type VerifyAnswer = {
24
24
  valid: true;
25
25
  verification_id: string;
@@ -42,10 +42,16 @@ export type VerifyAnswer = {
42
42
  reports_90d: number;
43
43
  revoked: false;
44
44
  };
45
+ /**
46
+ * Whether Pidgeon will refuse this signature if it is sent again: true
47
+ * when it carries a nonce (every signature these SDKs make does).
48
+ */
49
+ replay_protected?: boolean;
45
50
  } | {
46
51
  valid: false;
47
52
  verification_id: string;
48
- reason: 'unsigned' | 'invalid' | 'unknown_key' | 'expired' | 'revoked';
53
+ /** `replayed`: this signature was verified before, so the request is a copy. */
54
+ reason: 'unsigned' | 'invalid' | 'unknown_key' | 'expired' | 'revoked' | 'replayed';
49
55
  operator?: {
50
56
  id: string;
51
57
  name: string;
@@ -73,6 +79,11 @@ export type ListOptions = {
73
79
  limit?: number;
74
80
  cursor?: string;
75
81
  };
82
+ /** What `messages.search` narrows by, beside the words. */
83
+ export type SearchOptions = ListOptions & {
84
+ inboxId?: string;
85
+ body?: BodyChoice;
86
+ };
76
87
  /** An agent, as `/v1/agents` answers it. */
77
88
  export type Agent = {
78
89
  id: string;
@@ -107,7 +118,7 @@ export type Inbox = {
107
118
  display_name: string | null;
108
119
  pod_id: string;
109
120
  agent_id: string | null;
110
- status: string;
121
+ status: 'active' | 'suspended';
111
122
  /** Mail the Firewall calls suspicious waits for a person. */
112
123
  hold_suspicious: boolean;
113
124
  created_at: string;
@@ -200,6 +211,8 @@ export type MailDomain = {
200
211
  mail: boolean;
201
212
  status: 'pending' | 'verified' | 'failed' | null;
202
213
  receiving: boolean;
214
+ /** Whether Pidgeon signs agents' `Agent-of` here: the `pgn2._domainkey` record answered at the last check. */
215
+ agent_signing: boolean;
203
216
  checked_at: string | null;
204
217
  records: {
205
218
  purpose: string;
@@ -223,28 +236,44 @@ export type AppPassword = {
223
236
  };
224
237
  export type CalendarEvent = {
225
238
  id: string;
239
+ inbox_id: string;
240
+ uid: string;
226
241
  title: string | null;
242
+ /** Timed: an instant. All day: the first day, `YYYY-MM-DD`. */
227
243
  start: string;
244
+ /** Timed: an instant. All day: the last day, inclusive. */
228
245
  end: string;
246
+ starts_at: string;
247
+ ends_at: string;
229
248
  all_day: boolean;
230
- description?: string | null;
231
- location?: string | null;
232
- organizer?: string | null;
233
- attendees?: {
249
+ /** The series' RRULE as written, or null for a one-off. */
250
+ recurrence: string | null;
251
+ description: string | null;
252
+ location: string | null;
253
+ /** The address organising it, when it has attendees. */
254
+ organizer: string | null;
255
+ attendees: {
234
256
  email: string;
235
257
  status: 'needs_action' | 'accepted' | 'declined' | 'tentative';
236
258
  }[];
259
+ etag: string;
260
+ created_at: string;
261
+ updated_at: string;
237
262
  /** After a write with `sendInvites`: who was sent the invitation, or why nobody was. */
238
263
  invites?: {
239
264
  sent_to: string[];
240
265
  error: string | null;
241
266
  };
242
- [field: string]: unknown;
243
267
  };
268
+ /** The events a webhook can carry; the event log (`events.list`) holds more. */
269
+ export declare const WEBHOOK_EVENTS: readonly ["report.created", "reputation.changed", "operator.reputation_changed", "mandate.requested", "mandate.granted", "mandate.declined", "mandate.revoked", "message.received", "message.held", "message.released", "message.blocked", "message.quarantined", "message.sent", "message.failed", "message.scheduled", "message.delivered", "message.delayed", "message.bounced", "message.complained", "message.rejected", "message.exfiltration_blocked", "draft.created", "draft.approval_requested", "draft.approved", "draft.rejected", "thread.updated", "thread.deleted", "inbox.created", "inbox.updated", "inbox.removed", "email.domain_added", "email.domain_verified", "email.domain_broken", "email.domain_removed", "calendar.event.created", "calendar.event.updated", "calendar.event.deleted"];
270
+ export type WebhookEventType = (typeof WEBHOOK_EVENTS)[number];
244
271
  export type Webhook = {
245
272
  id: string;
246
273
  url: string;
247
- events: string[];
274
+ events: WebhookEventType[];
275
+ /** The inboxes it hears; null when it hears the whole account. */
276
+ inbox_ids: string[] | null;
248
277
  created_at: string;
249
278
  disabled_at: string | null;
250
279
  };
@@ -254,11 +283,11 @@ export type MessageInput = {
254
283
  to: string[];
255
284
  cc?: string[];
256
285
  bcc?: string[];
257
- subject: string;
286
+ subject?: string;
258
287
  text?: string;
259
288
  html?: string;
260
289
  replyTo?: string;
261
- /** Finished uploads of this inbox (`email.attachments.upload`). */
290
+ /** Finished uploads of this inbox (`pidgeon.attachments.upload`). */
262
291
  attachmentIds?: string[];
263
292
  };
264
293
  /** What sending answers: `sent`, `held` for a person's approval, or `scheduled`. */
@@ -313,9 +342,9 @@ export type Site = {
313
342
  client_id: string;
314
343
  name: string;
315
344
  redirect_uris: string[];
316
- pod_id?: string | null;
345
+ pod_id: string | null;
346
+ created_at: string;
317
347
  client_secret?: string;
318
- [field: string]: unknown;
319
348
  };
320
349
  export type Mandate = {
321
350
  id: string;
@@ -323,10 +352,12 @@ export type Mandate = {
323
352
  client_id: string;
324
353
  scope: string;
325
354
  description: string;
326
- status: string;
355
+ status: 'requested' | 'granted' | 'declined' | 'revoked';
327
356
  expires_at: string;
328
357
  created_at: string;
358
+ /** On a request: the link to send the person, and until when it works. */
329
359
  consent_url?: string;
360
+ request_expires_at?: string;
330
361
  };
331
362
  /**
332
363
  * The client for Pidgeon's API: the website's, the operator's, and a coding
@@ -383,6 +414,15 @@ export declare class Pidgeon {
383
414
  }>;
384
415
  /** The agent, its keys, its directory and its operator's reputation. */
385
416
  get: (id: string) => Promise<AgentDetail>;
417
+ /** Rename the agent, or change what it does: what websites see when it arrives. */
418
+ update: (id: string, input: {
419
+ name?: string;
420
+ purpose?: string;
421
+ }) => Promise<Agent>;
422
+ /** Revoke the agent and every key it has. None verifies again; it cannot be undone. */
423
+ revoke: (id: string) => Promise<void>;
424
+ /** Revoke one of the agent's keys, by its `kid`. Its other keys stay. */
425
+ revokeKey: (id: string, kid: string) => Promise<void>;
386
426
  /**
387
427
  * Register an agent, make its key here, and publish the public half
388
428
  * signed with it. Keep `key.privateJwk` where the agent runs: it is the
@@ -444,10 +484,13 @@ export declare class Pidgeon {
444
484
  held: number;
445
485
  next_since: string;
446
486
  }>;
447
- /** Mail by words in its subject, sender or text, newest first. */
448
- search: (q: string, options?: ListOptions & {
449
- inboxId?: string;
450
- }) => Promise<Page<Message>>;
487
+ /**
488
+ * Mail by words in its subject, sender or text, newest first:
489
+ * `search('invoice', { inboxId })`, or `search({ q: 'invoice', inboxId })`.
490
+ */
491
+ search: (query: string | (SearchOptions & {
492
+ q: string;
493
+ }), options?: SearchOptions) => Promise<Page<Message>>;
451
494
  };
452
495
  /** Conversations across your inboxes, and what is filed where. */
453
496
  readonly threads: {
@@ -529,7 +572,8 @@ export declare class Pidgeon {
529
572
  create: (inboxId: string, input: {
530
573
  title: string;
531
574
  start: string;
532
- end: string;
575
+ /** Required for a timed event; for an all-day one, the last day (default the start). */
576
+ end?: string;
533
577
  allDay?: boolean;
534
578
  description?: string;
535
579
  location?: string;
@@ -543,8 +587,10 @@ export declare class Pidgeon {
543
587
  start?: string;
544
588
  end?: string;
545
589
  allDay?: boolean;
546
- description?: string;
547
- location?: string;
590
+ /** `null` clears it. */
591
+ description?: string | null;
592
+ /** `null` clears it. */
593
+ location?: string | null;
548
594
  attendees?: string[];
549
595
  /** Send the attendees the updated invitation (a key with `send` access). */
550
596
  sendInvites?: boolean;
@@ -591,7 +637,7 @@ export declare class Pidgeon {
591
637
  inboxId: string;
592
638
  from: string;
593
639
  fromName?: string;
594
- subject: string;
640
+ subject?: string;
595
641
  text?: string;
596
642
  html?: string;
597
643
  inReplyTo?: string;
@@ -603,8 +649,8 @@ export declare class Pidgeon {
603
649
  readonly drafts: {
604
650
  create: (inboxId: string, input: MessageInput) => Promise<Draft>;
605
651
  get: (id: string) => Promise<Draft>;
606
- /** Replace a draft's addresses and body. */
607
- update: (id: string, input: MessageInput) => Promise<Draft>;
652
+ /** Replace a draft's addresses and body; its thread stays, so `replyTo` is not taken. */
653
+ update: (id: string, input: Omit<MessageInput, "replyTo">) => Promise<Draft>;
608
654
  remove: (id: string) => Promise<void>;
609
655
  /** Send now, or at `sendAt` (up to 90 days ahead). */
610
656
  send: (id: string, options?: {
@@ -675,16 +721,22 @@ export declare class Pidgeon {
675
721
  data: Pod[];
676
722
  }>;
677
723
  create: (name: string) => Promise<Pod>;
724
+ /** Remove an empty pod. Not the default pod, and not one with agents, domains or endpoints in it. */
725
+ remove: (id: string) => Promise<void>;
678
726
  };
679
727
  /** Your webhook endpoints. A key of the whole account only. */
680
728
  readonly webhooks: {
681
729
  list: () => Promise<{
682
730
  data: Webhook[];
683
731
  }>;
684
- /** Answers `secret` once: check each delivery's signature with it (`verifyWebhook`). */
732
+ /**
733
+ * Answers `secret` once: check each delivery's signature with it (`verifyWebhook`).
734
+ * With `inboxIds` it hears only those inboxes' events; without, the whole account's.
735
+ */
685
736
  create: (input: {
686
737
  url: string;
687
- events: string[];
738
+ events: WebhookEventType[];
739
+ inboxIds?: string[];
688
740
  }) => Promise<{
689
741
  id: string;
690
742
  secret: string;
@@ -707,7 +759,7 @@ export { generateAgentKey };
707
759
  /** A webhook Pidgeon sent you, once its signature checks out. */
708
760
  export type WebhookPayload = {
709
761
  id: string;
710
- type: string;
762
+ type: WebhookEventType;
711
763
  created: string;
712
764
  data: Record<string, unknown>;
713
765
  };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Pidgeon's TypeScript SDK (docs/plan.md §11).
2
+ * Pidgeon's TypeScript SDK.
3
3
  *
4
4
  * For an agent: `signedFetch`, or `agentFromEnv().fetch`, signs every request
5
5
  * with the agent's key, so a website that checks can tell who stands behind it.
@@ -41,6 +41,46 @@ function headersOf(input) {
41
41
  }
42
42
  return out;
43
43
  }
44
+ /** The events a webhook can carry; the event log (`events.list`) holds more. */
45
+ export const WEBHOOK_EVENTS = [
46
+ 'report.created',
47
+ 'reputation.changed',
48
+ 'operator.reputation_changed',
49
+ 'mandate.requested',
50
+ 'mandate.granted',
51
+ 'mandate.declined',
52
+ 'mandate.revoked',
53
+ 'message.received',
54
+ 'message.held',
55
+ 'message.released',
56
+ 'message.blocked',
57
+ 'message.quarantined',
58
+ 'message.sent',
59
+ 'message.failed',
60
+ 'message.scheduled',
61
+ 'message.delivered',
62
+ 'message.delayed',
63
+ 'message.bounced',
64
+ 'message.complained',
65
+ 'message.rejected',
66
+ 'message.exfiltration_blocked',
67
+ 'draft.created',
68
+ 'draft.approval_requested',
69
+ 'draft.approved',
70
+ 'draft.rejected',
71
+ 'thread.updated',
72
+ 'thread.deleted',
73
+ 'inbox.created',
74
+ 'inbox.updated',
75
+ 'inbox.removed',
76
+ 'email.domain_added',
77
+ 'email.domain_verified',
78
+ 'email.domain_broken',
79
+ 'email.domain_removed',
80
+ 'calendar.event.created',
81
+ 'calendar.event.updated',
82
+ 'calendar.event.deleted',
83
+ ];
44
84
  const messageBody = (input) => ({
45
85
  to: input.to,
46
86
  cc: input.cc,
@@ -135,6 +175,14 @@ export class Pidgeon {
135
175
  }),
136
176
  /** The agent, its keys, its directory and its operator's reputation. */
137
177
  get: (id) => this.request('GET', `/v1/agents/${segment(id)}`),
178
+ /** Rename the agent, or change what it does: what websites see when it arrives. */
179
+ update: (id, input) => this.request('PATCH', `/v1/agents/${segment(id)}`, {
180
+ body: { name: input.name, purpose: input.purpose },
181
+ }),
182
+ /** Revoke the agent and every key it has. None verifies again; it cannot be undone. */
183
+ revoke: (id) => this.request('DELETE', `/v1/agents/${segment(id)}`),
184
+ /** Revoke one of the agent's keys, by its `kid`. Its other keys stay. */
185
+ revokeKey: (id, kid) => this.request('DELETE', `/v1/agents/${segment(id)}/keys/${segment(kid)}`),
138
186
  /**
139
187
  * Register an agent, make its key here, and publish the public half
140
188
  * signed with it. Keep `key.privateJwk` where the agent runs: it is the
@@ -191,10 +239,25 @@ export class Pidgeon {
191
239
  await: (inboxId, options = {}) => this.request('GET', `/v1/email/inboxes/${segment(inboxId)}/messages/await`, {
192
240
  query: options,
193
241
  }),
194
- /** Mail by words in its subject, sender or text, newest first. */
195
- search: (q, options = {}) => this.request('GET', '/v1/email/search', {
196
- query: { q, inbox_id: options.inboxId, limit: options.limit, cursor: options.cursor },
197
- }),
242
+ /**
243
+ * Mail by words in its subject, sender or text, newest first:
244
+ * `search('invoice', { inboxId })`, or `search({ q: 'invoice', inboxId })`.
245
+ */
246
+ search: (query, options = {}) => {
247
+ const { q, ...rest } = typeof query === 'string' ? { ...options, q: query } : query;
248
+ if (typeof q !== 'string' || !q.trim()) {
249
+ return Promise.reject(new TypeError('messages.search needs the words to look for: search("invoice") or search({ q: "invoice" }).'));
250
+ }
251
+ return this.request('GET', '/v1/email/search', {
252
+ query: {
253
+ q,
254
+ inbox_id: rest.inboxId,
255
+ limit: rest.limit,
256
+ cursor: rest.cursor,
257
+ body: rest.body,
258
+ },
259
+ });
260
+ },
198
261
  };
199
262
  /** Conversations across your inboxes, and what is filed where. */
200
263
  threads = {
@@ -351,7 +414,7 @@ export class Pidgeon {
351
414
  body: messageBody(input),
352
415
  }),
353
416
  get: (id) => this.request('GET', `/v1/email/drafts/${segment(id)}`),
354
- /** Replace a draft's addresses and body. */
417
+ /** Replace a draft's addresses and body; its thread stays, so `replyTo` is not taken. */
355
418
  update: (id, input) => this.request('PATCH', `/v1/email/drafts/${segment(id)}`, { body: messageBody(input) }),
356
419
  remove: (id) => this.request('DELETE', `/v1/email/drafts/${segment(id)}`),
357
420
  /** Send now, or at `sendAt` (up to 90 days ahead). */
@@ -415,12 +478,19 @@ export class Pidgeon {
415
478
  pods = {
416
479
  list: () => this.request('GET', '/v1/pods'),
417
480
  create: (name) => this.request('POST', '/v1/pods', { body: { name } }),
481
+ /** Remove an empty pod. Not the default pod, and not one with agents, domains or endpoints in it. */
482
+ remove: (id) => this.request('DELETE', `/v1/pods/${segment(id)}`),
418
483
  };
419
484
  /** Your webhook endpoints. A key of the whole account only. */
420
485
  webhooks = {
421
486
  list: () => this.request('GET', '/v1/webhooks'),
422
- /** Answers `secret` once: check each delivery's signature with it (`verifyWebhook`). */
423
- create: (input) => this.request('POST', '/v1/webhooks', { body: input }),
487
+ /**
488
+ * Answers `secret` once: check each delivery's signature with it (`verifyWebhook`).
489
+ * With `inboxIds` it hears only those inboxes' events; without, the whole account's.
490
+ */
491
+ create: (input) => this.request('POST', '/v1/webhooks', {
492
+ body: { url: input.url, events: input.events, inbox_ids: input.inboxIds },
493
+ }),
424
494
  remove: (id) => this.request('DELETE', `/v1/webhooks/${segment(id)}`),
425
495
  };
426
496
  /** A multipart POST (uploads): the same authentication and errors as `request`. */
package/dist/node.js CHANGED
@@ -20,7 +20,7 @@ import { createServer } from 'node:http';
20
20
  import { homedir } from 'node:os';
21
21
  import { join } from 'node:path';
22
22
  import { generateAgentKey, signAgentRequest } from "./credential.js";
23
- import { DEFAULT_BASE_URL, Pidgeon, PidgeonError } from "./index.js";
23
+ import { DEFAULT_BASE_URL, Pidgeon, PidgeonError, signedFetch } from "./index.js";
24
24
  export function configDir(env = process.env) {
25
25
  if (env.PIDGEON_CONFIG_DIR)
26
26
  return env.PIDGEON_CONFIG_DIR;
@@ -313,19 +313,8 @@ export async function agentFromKeyFile(path) {
313
313
  const entry = await readJson(path);
314
314
  if (!entry?.private_jwk || !entry.directory)
315
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
- };
316
+ const agent = { privateJwk: entry.private_jwk, directory: entry.directory };
317
+ return { fetch: (input, init) => signedFetch(input, init, agent) };
329
318
  }
330
319
  /**
331
320
  * Register an agent, make its key on this machine, publish the public half
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pidgeon-ai/sdk",
3
- "version": "2.1.1",
3
+ "version": "2.4.0",
4
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
5
  "license": "Apache-2.0",
6
6
  "type": "module",