@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 ADDED
@@ -0,0 +1,212 @@
1
+ # Changelog
2
+
3
+ ## 2.16.0
4
+
5
+ - Pidgeon is now Zurchin: this version is published as `@zurchin/sdk`, and the last `@zurchin/sdk` (2.16.0) only re-exports it and says so once.
6
+ - The default host is `https://zurchin.com`. pidgeon.ai keeps answering the API for six months.
7
+ - The source repository is `zurchin/pidgeon-js`.
8
+
9
+ ## 2.15.0
10
+
11
+ - Pidgeon is becoming Zurchin, and every setting answers to both names: `ZURCHIN_API_KEY`,
12
+ `ZURCHIN_BASE_URL`, `ZURCHIN_CONFIG_DIR`, `ZURCHIN_AGENT_KEY` and `ZURCHIN_DIRECTORY` win
13
+ when set, and each `PIDGEON_` one works as before. `envSetting(name)` reads one that way;
14
+ `apiKeyVariable()` (in `/node`) says which key variable is set.
15
+ - `Zurchin` and `ZurchinError` are `Pidgeon` and `PidgeonError` under the new name.
16
+ - `DEFAULT_ISSUER` is `DEFAULT_BASE_URL`, so the host is said once. Both are still
17
+ `https://pidgeon.ai`.
18
+
19
+ ## 2.14.0
20
+
21
+ - `keys.deliverToVercel({ name, vercelProjectId, envName, targets? })`: make a key and
22
+ have Pidgeon put it straight on a Vercel project as a sensitive variable, through the
23
+ account's Vercel installation (`POST /v1/keys`, `deliver_to`). The answer never holds
24
+ the key, only `delivered_to`. Needs an `admin` key of the whole account.
25
+
26
+ ## 2.13.0
27
+
28
+ - `inboxes.setAgent(id, agentId)`: link an existing inbox to an agent identity in its pod,
29
+ so its mail is signed as that agent, or pass `null` to unlink it (`PATCH
30
+ /v1/email/inboxes/{id}`, `agent_id`). Needs `admin` and a verified domain.
31
+ - `agents.*` and `Agent` are described as agent identities: who an agent is when it signs
32
+ mail and signs in. Linking an inbox to one stays optional. Nothing else changed.
33
+ - `domains.remove` says what it does now: a proved domain's mail is turned off first, and
34
+ it stays while an inbox is at it.
35
+
36
+ ## 2.12.0
37
+
38
+ - Domains from the API (`/v1/domains`): `domains.create(domain, { podId })`,
39
+ `domains.verify(id)` and `domains.remove(id)`. `domains.list()` and `domains.get(id)`
40
+ now read `/v1/domains`, which answers what they did and more (the pod, the DNS records
41
+ to publish). A key of one pod reaches its own pod's domains only.
42
+
43
+ ## 2.11.1
44
+
45
+ - The package's description, keywords and README lead with what Pidgeon is now:
46
+ email inboxes for AI agents, pods for platforms, then Sign in with Pidgeon. No
47
+ code changes.
48
+
49
+ ## 2.11.0
50
+
51
+ - Declared agents: `verify` answers a fifth `result`, `declared`, for an unsigned request
52
+ whose User-Agent names an AI agent on Pidgeon's list (ChatGPT-User, Claude-User,
53
+ Perplexity-User, …), with `declared` (`name`, `operator`, `purpose`, and `ip`:
54
+ `confirmed`, `mismatch` or `unchecked` against the vendor's published addresses). Such a
55
+ request was `refused`, `unsigned` before. Never `valid`, and no verdict.
56
+ - `bouncer()` (`@zurchin/sdk/next`) reports declared agents too, with the visitor's
57
+ address (Netlify's `context.ip`, Vercel's `x-real-ip`, or the new `ip` option).
58
+ `isAgentRequest`, `DECLARED_AGENT_TOKENS` and `declaredAgentToken` are exported.
59
+ - `pidgeon.visits.record(visits)` (`POST /v1/visits`): record declared agents' visits, up
60
+ to 100 at a time, not counted as verifications. `bouncer()` sends declared agents there,
61
+ in batches a second apart, with the URL's path only, instead of checking each one.
62
+ - `bouncer({ place })` in observe mode records where each visit was, for the dashboard.
63
+
64
+ ## 2.10.0
65
+
66
+ - Site rules for Bouncer: `pidgeon.siteRules.get()` and `.set()` (`/v1/site-rules`).
67
+ - `verify(request, { place })`: `signup`, `checkout`, `api` or `other`. Every answer carries
68
+ `place`, `decision` (`allow`, `limit`, `block` or `watch`), `would` and `rule`, and so
69
+ does the verdict (`VerdictClaims`).
70
+ - `bouncer({ mode: 'enforce', place })` (`@zurchin/sdk/next`): a place's check is awaited
71
+ and a blocked agent answered with a 403. `verdictFor` sends `place: 'signup'` unless told
72
+ otherwise.
73
+
74
+ ## 2.9.0
75
+
76
+ - `pidgeon.pods.move(podId, { type, id })` (`POST /v1/pods/{id}/move`): move an agent
77
+ (with its addresses and mail), an address, a domain, a webhook endpoint or a site into a pod.
78
+ - `webhooks.create({ podId })`, and `Webhook.pod_id`. A key of one pod lists, adds and
79
+ removes its own pod's webhooks.
80
+
81
+ ## 2.8.0
82
+
83
+ - `pidgeon.pods.rename(id, name)` (`PATCH /v1/pods/{id}`).
84
+ - Verdicts at sign-up: `verify` answers `verdict` for every result but
85
+ `refused`, a token Pidgeon signs for five minutes, for a sign-up hook that
86
+ cannot see the request. `verify(request, { ip })` writes the agent's
87
+ address into it. `@zurchin/sdk/verdict`: `verifyVerdict` checks one
88
+ offline against Pidgeon's keys; `pidgeon.checkVerdict` checks and spends
89
+ one with Pidgeon (`/v1/verify/verdict`). `@zurchin/sdk/next`:
90
+ `verdictFor` gets one in a proxy, on the sign-up's own request.
91
+
92
+ ## 2.7.0
93
+
94
+ - `pidgeon.keys`: `list`, `create` and `revoke` API keys (`/v1/keys`). A key is
95
+ never stronger than the one making it; a test key makes only test keys.
96
+
97
+ ## 2.6.0
98
+
99
+ - `verify` answers `result`, one of four: `verified` (a Pidgeon operator's
100
+ agent), `signed_known` (signed with a key from an outside directory on
101
+ Pidgeon's recognised list), `signed_unknown` (an outside directory nobody
102
+ vouches for) or `refused`. The signed results carry `signature_agent`
103
+ (`directory`, `host`, `operator`). `valid` is unchanged: true for
104
+ `verified` only, so code that reads `valid` behaves as before; outside
105
+ signers still come back `valid: false` with `reason: 'unknown_key'`.
106
+ - `verifyAgentRequest` checks signatures as
107
+ draft-ietf-webbotauth-httpsig-protocol-01 writes them: `alg` and `nonce`
108
+ optional, a nonce of any length, and the `web-bot-auth` signature picked
109
+ when a proxy added another. `findKey` is also given the directory the
110
+ signature names. Failed verifications carry `directory`; successful ones
111
+ carry `signature`. `signatureAgentOf(request)` reads a request's directory.
112
+
113
+ ## 2.5.0
114
+
115
+ - `@zurchin/sdk/next`: `bouncer({ apiKey })` for a Next.js proxy (or any
116
+ `Request` with `waitUntil`). Observe mode checks each request carrying an
117
+ agent's signature, or `Signature-Agent` alone, with `POST /v1/verify` after
118
+ the response; it never throws, delays or changes a response, skips other
119
+ requests and CORS preflights, and leaves out the visitor's `Cookie` and
120
+ `Authorization` unless signed. No key: it does nothing.
121
+ - `sites.update(clientId, { name, redirectUris })` and
122
+ `sites.rotateSecret(clientId)`: edit a site, and give it a new secret
123
+ (answered once; the old one stops working at once).
124
+ - `verifyAgentSignIn` requires the request's `Signature-Agent` to be the
125
+ agent's own directory (the token's `agent.directory`), as Pidgeon's token
126
+ exchange now does: `wrong_directory` otherwise.
127
+ - `SignInError.reason` says which: `wrong_request` (signed for another
128
+ method, path or host) and `expired` (the signature is too old or dated
129
+ ahead) are no longer reported as `wrong_key`.
130
+ - `verifyAgentSignIn` takes `clientSecret`: a token issued under a mandate is
131
+ checked with Pidgeon's `/oauth/introspect`, and one whose mandate was
132
+ stopped is refused at once (`mandate_ended`), not when the token expires.
133
+ - `sameDirectory(named, directory)`. `PidgeonClaims` has `act`, `mandate`,
134
+ `scope` and `agent.directory`.
135
+
136
+ ## 2.4.0
137
+
138
+ - `signedFetch`, `agentFromEnv().fetch` and `agentFromKeyFile().fetch` send
139
+ a request with a body. They threw "Cannot construct a Request with a
140
+ Request object that has already been used" on any POST or PUT with one.
141
+ - Every signature carries a fresh 64-byte nonce and covers `@query` (`?`
142
+ when the URL has none), so neither the query nor the signature can be
143
+ reused: sign again to retry. `newNonce()`; `signAgentRequest` takes
144
+ `nonce` for tests. `verifyAgentRequest` answers the signature's `nonce`.
145
+ - `VerifyAnswer`: `replay_protected`, and the reason `replayed`.
146
+ - `messages.search` takes `search(q, options)` or `search({ q, ...options })`;
147
+ with no words it rejects with a `TypeError` instead of answering nothing.
148
+ - `agents.update`, `agents.revoke`, `agents.revokeKey` and `pods.remove`.
149
+ - `WEBHOOK_EVENTS` has `mandate.requested`, `mandate.granted`,
150
+ `mandate.declined` and `mandate.revoked`.
151
+ - Typings no longer cite documents outside the package.
152
+
153
+ ## 2.3.0
154
+
155
+ - `messages.search` takes `body: 'clean'`, as reading does.
156
+ - `WEBHOOK_EVENTS` and `WebhookEventType`: the events a webhook carries.
157
+ `webhooks.create`, `Webhook.events` and `WebhookPayload.type` use them,
158
+ so a misspelt event fails to compile rather than with a 400.
159
+ - Types say what the API answers: `CalendarEvent` in full, `Site` with
160
+ `created_at`, `Mandate.status` and `request_expires_at`, `Inbox.status`.
161
+ - `calendar.update` takes `null` to clear `description` or `location`;
162
+ `calendar.create` takes no `end` for an all-day event; `subject` and
163
+ `testInbound`'s `subject` are optional, as in the API.
164
+ - `drafts.update` no longer takes `replyTo`: a draft keeps its conversation.
165
+
166
+ ## 2.2.0
167
+
168
+ - `webhooks.create` takes `inboxIds`: the endpoint hears only those inboxes'
169
+ events. `Webhook` has `inbox_ids`, null for one of the whole account.
170
+
171
+ ## 2.1.1
172
+
173
+ - `calendar.create` and `calendar.update` take `attendees` and `sendInvites`,
174
+ and `calendar.remove` takes `{ sendInvites }`: the attendees get an
175
+ invitation, an update or a cancellation from the inbox. `CalendarEvent` has
176
+ `organizer`, `attendees` and, after a write that sent, `invites`.
177
+
178
+ ## 2.1.0
179
+
180
+ All of Email, and webhooks. Additive: 2.0 code runs unchanged.
181
+
182
+ - `messages`: `list`, `get` (`body: 'clean'` for the Firewall's cleaned text),
183
+ `markSeen`, `await` (wait for mail), `search`; sending takes `attachmentIds`.
184
+ - `threads` (list, read, file, star, hand to a person, delete, labels),
185
+ `labels`, `contacts`, `attachments` (`upload`, which goes straight to
186
+ storage over 4 MB; `get`, a five-minute link), `calendar`, `domains` (mail
187
+ on your own domain), `appPasswords` (for mail apps), `storage()`,
188
+ `testInbound()` (with a test key), and `webhooks`.
189
+ - `inboxes.create` takes `domain`; `inboxes.holdSuspicious`.
190
+ - Types follow the API: an inbox's `kind` is `agent` or `events`, and it has
191
+ `hold_suspicious` (no `owner_id`).
192
+
193
+ ## 2.0.0
194
+
195
+ For the new Pidgeon: Passport, Bouncer, Email and Auth. A new major version,
196
+ because nothing of 1.x carries over: 1.x spoke the old email API at
197
+ `/api/v1`, which is retired seven days after the switch. Stay on 1.68.0 until
198
+ you move.
199
+
200
+ - `Pidgeon`, the API client, grouped by product: `agents` (with `setUp`:
201
+ register, make the key here, publish it signed with itself), `verify` and
202
+ `report`, `inboxes`, `messages`, `drafts`, `rules`, `suppressions`, `sites`,
203
+ `mandates`, `events`, `pods`, and `request` for any `/v1` call. It takes an
204
+ API key or an OAuth access token (`getToken`, refreshed per request).
205
+ - Signing as an agent (Web Bot Auth, RFC 9421): `signedFetch`, `agentFromEnv`,
206
+ `generateAgentKey`, `signAgentRequest`, `verifyAgentRequest`.
207
+ - `@zurchin/sdk/auth`: Sign in with Pidgeon. `signInAsAgent`,
208
+ `verifyIdToken`, `verifyAgentSignIn`, `requestIdJag`.
209
+ - `@zurchin/sdk/node`: signing in from a terminal through Pidgeon's OAuth
210
+ server, and agent keys kept on this machine (`setUpAgent`, `addAgentKey`,
211
+ `agentFromKeyFile`). What the CLI and the MCP server share.
212
+ - `verifyWebhook` for webhook signatures.
package/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,191 @@
1
- # Temporary Holding Version
1
+ # @zurchin/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Email for founders, teams and agents. Give each agent its own address beside
4
+ your team's, on @pidgeon.email or your own domain, or give every user of your
5
+ product inboxes of their own. https://pidgeon.ai
6
+
7
+ ```sh
8
+ npm install @zurchin/sdk
9
+ ```
10
+
11
+ Version 2 is for the new Pidgeon. Code written for 1.x (the old email API at
12
+ `/api/v1`) keeps working on 1.68.0 until that API is retired.
13
+
14
+ ## Give an agent an inbox
15
+
16
+ ```ts
17
+ import { Pidgeon } from '@zurchin/sdk';
18
+
19
+ const pidgeon = new Pidgeon({ apiKey: process.env.PIDGEON_API_KEY! });
20
+
21
+ const inbox = await pidgeon.inboxes.create({ name: 'bookings' }); // bookings@pidgeon.email
22
+ await pidgeon.messages.send(inbox.id, {
23
+ to: ['ana@example.com'],
24
+ subject: 'Table for two',
25
+ text: 'Friday at 8?',
26
+ });
27
+
28
+ // Wait for the reply (up to 50 seconds a call):
29
+ const { data: replies } = await pidgeon.messages.await(inbox.id);
30
+ ```
31
+
32
+ On your own domain, pass `domain` once mail is on for it
33
+ (`pidgeon.domains.enableMail`).
34
+
35
+ ## Email
36
+
37
+ ```ts
38
+ // A person looks first:
39
+ const draft = await pidgeon.drafts.create(inbox.id, {
40
+ to: ['ana@example.com'],
41
+ subject: '…',
42
+ text: '…',
43
+ });
44
+ await pidgeon.drafts.requestApproval(draft.id);
45
+
46
+ // Wait for mail, read it as the Firewall cleaned it, answer in its conversation:
47
+ let since: string | undefined;
48
+ for (;;) {
49
+ const { data, next_since } = await pidgeon.messages.await(inbox.id, { since, body: 'clean' });
50
+ for (const message of data) {
51
+ if (message.firewall?.verdict === 'suspicious') {
52
+ await pidgeon.threads.update(message.thread_id, {
53
+ ownerType: 'human',
54
+ status: 'human_review',
55
+ });
56
+ continue;
57
+ }
58
+ await pidgeon.messages.send(inbox.id, {
59
+ to: [message.from.address],
60
+ subject: `Re: ${message.subject}`,
61
+ text: 'On it.',
62
+ replyTo: message.id,
63
+ });
64
+ }
65
+ since = next_since;
66
+ }
67
+ ```
68
+
69
+ Also `pidgeon.threads`, `pidgeon.labels`, `pidgeon.contacts`,
70
+ `pidgeon.attachments` (`upload`, `get`), `pidgeon.calendar`,
71
+ `pidgeon.domains`, `pidgeon.appPasswords`, `pidgeon.webhooks`,
72
+ `pidgeon.rules`, `pidgeon.suppressions`, `pidgeon.events`, `pidgeon.pods`,
73
+ and `pidgeon.request(method, path, …)` for any `/v1` call. A refusal throws
74
+ `PidgeonError` with the API's `status` and `code`.
75
+
76
+ Webhooks: `verifyWebhook(secret, rawBody, request.headers.get('pidgeon-signature'))`.
77
+
78
+ ## For platforms
79
+
80
+ Give every user of your platform inboxes of their own, white-labelled on their
81
+ own domain. Each user gets a pod; a key of that pod reaches only its mail.
82
+
83
+ ```ts
84
+ const pod = await pidgeon.pods.create('Acme Ltd');
85
+ // acme.com is the user's domain, with mail on, in their pod.
86
+ const inbox = await pidgeon.inboxes.create({ name: 'support', podId: pod.id, domain: 'acme.com' });
87
+ const { key } = await pidgeon.keys.create({ name: 'Acme', access: 'send', podId: pod.id });
88
+ ```
89
+
90
+ ## Sign in with Pidgeon (`@zurchin/sdk/auth`)
91
+
92
+ Agents sign in to websites as themselves, with a key of their own.
93
+
94
+ ### Set an agent up
95
+
96
+ ```ts
97
+ // Registers the agent, makes its key here, and publishes the public half
98
+ // signed with it. Keep key.privateJwk where the agent runs: Pidgeon never sees it.
99
+ const { agent, key } = await pidgeon.agents.setUp({
100
+ name: 'Booking agent',
101
+ purpose: 'Books tables.',
102
+ });
103
+ ```
104
+
105
+ From a terminal or a coding agent, `@zurchin/cli` and `@zurchin/mcp`
106
+ do the same, and keep the key in a file on your machine
107
+ (`@zurchin/sdk/node`: `setUpAgent`, `agentFromKeyFile`).
108
+
109
+ ### Sign its requests
110
+
111
+ ```ts
112
+ import { agentFromEnv } from '@zurchin/sdk';
113
+
114
+ // PIDGEON_AGENT_KEY is the private JWK, PIDGEON_DIRECTORY the agent's directory.
115
+ const agent = agentFromEnv();
116
+ await agent.fetch('https://shop.example/api/orders', {
117
+ method: 'POST',
118
+ headers: { 'content-type': 'application/json' },
119
+ body: JSON.stringify({ sku: 'tea' }),
120
+ });
121
+ ```
122
+
123
+ Each call is signed afresh: the signature covers the host, method, path and
124
+ query, carries a new nonce, and lasts a minute. Pidgeon accepts a signature
125
+ once, so sign again to retry; never resend old signature headers.
126
+
127
+ ### Your site
128
+
129
+ Register your site with `pidgeon.sites.create({ name, redirectUris })`; ask a
130
+ person to let your agent act for them with `pidgeon.mandates.create(…)`.
131
+
132
+ People sign in to your site with any OpenID Connect library: the issuer is
133
+ `https://pidgeon.ai`, with the client id and secret you registered. Check an
134
+ ID token with `verifyIdToken(idToken, { clientId })`.
135
+
136
+ An agent signs in with no person present, and sends its ID token with every
137
+ request it signs:
138
+
139
+ ```ts
140
+ import { signedFetch } from '@zurchin/sdk';
141
+ import { signInAsAgent } from '@zurchin/sdk/auth';
142
+
143
+ const { idToken } = await signInAsAgent({ site: 'site_…', key, directory });
144
+ await signedFetch(
145
+ 'https://shop.example/api/orders',
146
+ {
147
+ method: 'POST',
148
+ headers: { authorization: `Bearer ${idToken}` },
149
+ },
150
+ { privateJwk: key.privateJwk, directory },
151
+ );
152
+ ```
153
+
154
+ Your site accepts the request only when it is signed with the key the token
155
+ names and its `Signature-Agent` is the agent's own directory, so a copied
156
+ token is useless on its own:
157
+
158
+ ```ts
159
+ import { verifyAgentSignIn } from '@zurchin/sdk/auth';
160
+
161
+ const claims = await verifyAgentSignIn(request, { clientId: 'site_…' });
162
+ claims.sub;
163
+ claims.agent;
164
+ claims.account;
165
+ claims.reputation;
166
+ ```
167
+
168
+ Under a mandate, pass your site's `clientSecret` too: Pidgeon is asked
169
+ whether the mandate still holds, so one the person stopped is refused at
170
+ once (`mandate_ended`) rather than when the token expires. A token under a
171
+ test mandate (asked with a test key) carries `test: true` and verifies like
172
+ any other: refuse it in production.
173
+
174
+ ### For an MCP server that trusts Pidgeon (ID-JAG)
175
+
176
+ ```ts
177
+ import { requestIdJag } from '@zurchin/sdk/auth';
178
+
179
+ const { idJag } = await requestIdJag({
180
+ audience: 'https://auth.example.com', // the MCP server's authorization server
181
+ clientId: 'https://agent.example.com/oauth/client.json', // your client id there
182
+ resource: 'https://mcp.example.com/mcp',
183
+ key,
184
+ directory,
185
+ });
186
+ // Present it there: grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer, assertion=idJag.
187
+ ```
188
+
189
+ ## License
190
+
191
+ Apache-2.0
package/dist/auth.d.ts ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Pidgeon Auth: Sign in with Pidgeon (https://pidgeon.ai).
3
+ *
4
+ * People sign in to your site with any OpenID Connect library: point it at
5
+ * the issuer `https://pidgeon.ai` with the client id and secret you
6
+ * registered, and check the ID token with `verifyIdToken`.
7
+ *
8
+ * Agents sign in with no person present: the agent calls `signInAsAgent`,
9
+ * which exchanges a request signed with its Pidgeon key for an ID token for
10
+ * your site. It then sends that token with every request it signs
11
+ * (`Authorization: Bearer <id_token>`), and `verifyAgentSignIn` checks both:
12
+ * the token is Pidgeon's and for you, and the request is signed with the key
13
+ * the token names (`cnf`), so a copied token is useless on its own.
14
+ */
15
+ import { type JSONWebKeySet } from 'jose';
16
+ import { type PublicJwk } from './credential.ts';
17
+ /** The issuer is the API's host: it moves with `DEFAULT_BASE_URL`. */
18
+ export declare const DEFAULT_ISSUER = "https://zurchin.com";
19
+ export declare const TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
20
+ export declare const AGENT_KEY_TOKEN = "urn:pidgeon:params:oauth:token-type:agent-key";
21
+ export declare const ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token";
22
+ export declare const ID_JAG = "urn:ietf:params:oauth:token-type:id-jag";
23
+ /** What an ID token from Pidgeon says. A person's carries `email` and `name` by scope; an agent's carries `agent`, `reputation`, `pod` and `cnf`. */
24
+ export type PidgeonClaims = {
25
+ iss: string;
26
+ sub: string;
27
+ aud: string | string[];
28
+ exp: number;
29
+ iat: number;
30
+ kind: 'person' | 'agent';
31
+ account?: {
32
+ name: string;
33
+ slug: string;
34
+ verification: 'none' | 'domain' | 'kyc' | 'kyb';
35
+ };
36
+ /** `directory`: where the agent's keys are published; its signed requests must name it as `Signature-Agent`. */
37
+ agent?: {
38
+ name: string;
39
+ purpose: string;
40
+ directory?: string;
41
+ };
42
+ reputation?: 'unverified' | 'new' | 'good' | 'flagged' | 'suspended';
43
+ pod?: string;
44
+ email?: string;
45
+ email_verified?: boolean;
46
+ name?: string;
47
+ nonce?: string;
48
+ cnf?: {
49
+ jwk: PublicJwk;
50
+ };
51
+ /** Under a mandate: the agent acting for the person in `sub` (RFC 8693 §4.1). */
52
+ act?: {
53
+ sub: string;
54
+ agent?: PidgeonClaims['agent'];
55
+ account?: PidgeonClaims['account'];
56
+ };
57
+ /** Under a mandate: which one, its scope at your site, and when it ends. */
58
+ mandate?: {
59
+ id: string;
60
+ scope: string;
61
+ expires_at: string;
62
+ };
63
+ scope?: string;
64
+ /** Under a test mandate (asked with a test key): `true`. Refuse it in production. */
65
+ test?: true;
66
+ };
67
+ /**
68
+ * Why a sign-in was not accepted. `refused`: Pidgeon refused the agent's
69
+ * exchange. `invalid_token`: not a valid Pidgeon ID token for you.
70
+ * `not_an_agent`: a person's token, or no `cnf`. `unsigned`: no token or no
71
+ * signature. `wrong_key`: signed with another key than the token names.
72
+ * `wrong_request`: the signature does not cover this request (its method,
73
+ * path or host). `expired`: the signature is too old or dated ahead.
74
+ * `wrong_directory`: `Signature-Agent` is not the agent's own directory.
75
+ * `mandate_ended`: the mandate the token was issued under was stopped or ran
76
+ * out (checked only with `clientSecret`).
77
+ */
78
+ export type SignInRefusal = 'refused' | 'invalid_token' | 'not_an_agent' | 'unsigned' | 'wrong_key' | 'wrong_request' | 'expired' | 'wrong_directory' | 'mandate_ended';
79
+ export declare class SignInError extends Error {
80
+ readonly reason: SignInRefusal;
81
+ constructor(reason: SignInRefusal, message: string);
82
+ }
83
+ /**
84
+ * The agent's side: an ID token for one site, for ten minutes. `site` is the
85
+ * site's client id (it tells you, or puts it on its sign-in page); `key` and
86
+ * `directory` are the agent's, as for any signed request.
87
+ */
88
+ export declare function signInAsAgent(options: {
89
+ site: string;
90
+ key: {
91
+ kid: string;
92
+ privateJwk: JsonWebKey;
93
+ };
94
+ directory: string;
95
+ issuer?: string;
96
+ fetch?: typeof fetch;
97
+ }): Promise<{
98
+ idToken: string;
99
+ expiresIn: number;
100
+ }>;
101
+ /**
102
+ * The agent's side, for an MCP server whose authorization server trusts
103
+ * Pidgeon (MCP Enterprise-Managed Authorization): an ID-JAG, five minutes,
104
+ * to present there as a JWT bearer grant. `audience` is that authorization
105
+ * server's issuer, `clientId` your client id there, `resource` the MCP
106
+ * server's resource identifier.
107
+ */
108
+ export declare function requestIdJag(options: {
109
+ audience: string;
110
+ clientId: string;
111
+ resource?: string;
112
+ scope?: string;
113
+ key: {
114
+ kid: string;
115
+ privateJwk: JsonWebKey;
116
+ };
117
+ directory: string;
118
+ issuer?: string;
119
+ fetch?: typeof fetch;
120
+ }): Promise<{
121
+ idJag: string;
122
+ expiresIn: number;
123
+ }>;
124
+ /**
125
+ * The site's side, for any ID token from Pidgeon (a person's or an agent's):
126
+ * signed with Pidgeon's published key, issued by Pidgeon, for your client
127
+ * id, not expired, and with your `nonce` if you sent one.
128
+ */
129
+ export declare function verifyIdToken(idToken: string, options: {
130
+ clientId: string;
131
+ issuer?: string;
132
+ nonce?: string;
133
+ jwks?: JSONWebKeySet;
134
+ }): Promise<PidgeonClaims>;
135
+ /**
136
+ * The site's side, for an agent's request: the ID token in
137
+ * `Authorization: Bearer`, the request signed with the key that token names,
138
+ * and its `Signature-Agent` the agent's own directory. Answers who the agent
139
+ * is and who stands behind it.
140
+ *
141
+ * With `clientSecret` (your site's), a token issued under a mandate is also
142
+ * checked with Pidgeon (`/oauth/introspect`), so a mandate the person stopped
143
+ * is refused at once instead of when the token expires, up to ten minutes
144
+ * later. One request to Pidgeon per call, only for mandate tokens.
145
+ */
146
+ export declare function verifyAgentSignIn(request: Request, options: {
147
+ clientId: string;
148
+ issuer?: string;
149
+ jwks?: JSONWebKeySet;
150
+ clientSecret?: string;
151
+ fetch?: typeof fetch;
152
+ }): Promise<PidgeonClaims>;