@yaks/resend 0.0.0-stage → 0.2.36

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.
Files changed (59) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +96 -2
  3. package/_dist/api.d.ts +2 -0
  4. package/_dist/api.d.ts.map +1 -0
  5. package/_dist/box-queue.d.ts +30 -0
  6. package/_dist/box-queue.d.ts.map +1 -0
  7. package/_dist/box-wire.d.ts +35 -0
  8. package/_dist/box-wire.d.ts.map +1 -0
  9. package/_dist/domains.d.ts +55 -0
  10. package/_dist/domains.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +8 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +5 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/options.d.ts +19 -0
  16. package/_dist/options.d.ts.map +1 -0
  17. package/_dist/receive.d.ts +45 -0
  18. package/_dist/receive.d.ts.map +1 -0
  19. package/_dist/routes.d.ts +8 -0
  20. package/_dist/routes.d.ts.map +1 -0
  21. package/_dist/sender.d.ts +19 -0
  22. package/_dist/sender.d.ts.map +1 -0
  23. package/_dist/service.d.ts +10 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/api.js +19 -0
  26. package/api.js.map +1 -0
  27. package/api.ts +27 -0
  28. package/box-queue.js +161 -0
  29. package/box-queue.js.map +1 -0
  30. package/box-queue.ts +188 -0
  31. package/box-wire.js +18 -0
  32. package/box-wire.js.map +1 -0
  33. package/box-wire.ts +57 -0
  34. package/deno.json +1 -0
  35. package/domains.js +226 -0
  36. package/domains.js.map +1 -0
  37. package/domains.ts +300 -0
  38. package/graph.js +31 -0
  39. package/graph.js.map +1 -0
  40. package/graph.ts +54 -0
  41. package/mod.js +5 -0
  42. package/mod.js.map +1 -0
  43. package/mod.ts +5 -0
  44. package/options.js +19 -0
  45. package/options.js.map +1 -0
  46. package/options.ts +48 -0
  47. package/package.json +54 -4
  48. package/receive.js +206 -0
  49. package/receive.js.map +1 -0
  50. package/receive.ts +266 -0
  51. package/routes.js +43 -0
  52. package/routes.js.map +1 -0
  53. package/routes.ts +45 -0
  54. package/sender.js +101 -0
  55. package/sender.js.map +1 -0
  56. package/sender.ts +124 -0
  57. package/service.js +102 -0
  58. package/service.js.map +1 -0
  59. package/service.ts +107 -0
package/options.ts ADDED
@@ -0,0 +1,48 @@
1
+ // What a config passes to this plugin: the sender's credentials, which
2
+ // `./graph` lends the host as the sender named `resend`, the webhook
3
+ // `./routes` takes this sender's signed delivery receipts on, the key
4
+ // `./graph` sets up the mail domains it lends as `resend` with, and the key
5
+ // its notices read a received letter with.
6
+ //
7
+ // ```json
8
+ // { "use": "@yaks/resend",
9
+ // "with": { "token": { "secret": "RESEND_TOKEN" },
10
+ // "tags": { "yak_host": "box" },
11
+ // "receipts": { "secret": { "secret": "RESEND_WEBHOOK_SECRET" } },
12
+ // "domains": { "token": { "secret": "RESEND_DOMAINS_TOKEN" } },
13
+ // "receiving": { "token": { "secret": "RESEND_DOMAINS_TOKEN" } } } }
14
+ // ```
15
+ //
16
+ // A `{"secret": "NAME"}` is that secret's value when it is read, and the
17
+ // sender reads its options at every letter, so a token set after start-up is
18
+ // used for the next one.
19
+ import type { Resend } from './sender.ts'
20
+
21
+ /** What a config passes to @yaks/resend. */
22
+ export type Options = Partial<Resend> & {
23
+ /** Resend's signed delivery receipts for this graph. A receipt counts only
24
+ * where it carries every one of the sender's `tags`. */
25
+ receipts?: Receipts
26
+ /** The mail domains it sets up, reads and removes, through `base` and
27
+ * `fetch` as the sender is. */
28
+ domains?: {
29
+ /** a `full_access` key: a sending key cannot manage domains */ token?:
30
+ string
31
+ }
32
+ /** Mail Resend receives, which the notices read in full for a host that
33
+ * takes mail in. Without it, a received letter is acknowledged unread. */
34
+ receiving?: {
35
+ /** a `full_access` key: a sending key cannot read received mail */ token?:
36
+ string
37
+ /** Defer retrieval to the host when a receiving key is unavailable here. */
38
+ defer?: boolean
39
+ }
40
+ }
41
+
42
+ /** The webhook Resend posts delivery receipts to. */
43
+ export type Receipts = {
44
+ /** the endpoint's signing secret, `whsec_…` */
45
+ secret?: string
46
+ /** the path it answers on (default `/mail/resend`) */
47
+ path?: string
48
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@yaks/resend",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/resend",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./sender": {
12
+ "types": "./_dist/sender.d.ts",
13
+ "default": "./sender.js"
14
+ },
15
+ "./receive": {
16
+ "types": "./_dist/receive.d.ts",
17
+ "default": "./receive.js"
18
+ },
19
+ "./domains": {
20
+ "types": "./_dist/domains.d.ts",
21
+ "default": "./domains.js"
22
+ },
23
+ "./box-wire": {
24
+ "types": "./_dist/box-wire.d.ts",
25
+ "default": "./box-wire.js"
26
+ },
27
+ "./box-queue": {
28
+ "types": "./_dist/box-queue.d.ts",
29
+ "default": "./box-queue.js"
30
+ },
31
+ "./graph": {
32
+ "types": "./_dist/graph.d.ts",
33
+ "default": "./graph.js"
34
+ },
35
+ "./routes": {
36
+ "types": "./_dist/routes.d.ts",
37
+ "default": "./routes.js"
38
+ },
39
+ "./service": {
40
+ "types": "./_dist/service.d.ts",
41
+ "default": "./service.js"
42
+ }
43
+ },
44
+ "license": "Apache-2.0",
45
+ "dependencies": {
46
+ "@yaks/api": "0.2.36",
47
+ "@yaks/blob": "0.2.36",
48
+ "@yaks/fp": "0.2.36",
49
+ "@yaks/graph": "0.2.36",
50
+ "@yaks/host": "0.2.36",
51
+ "@yaks/mail": "0.2.36",
52
+ "@yaks/secrets": "0.2.36"
53
+ },
54
+ "description": "Resend sending, signed webhook receipts and incoming messages at the portable mail boundary.",
55
+ "repository": "https://github.com/yak-sh/yak.git"
56
+ }
package/receive.js ADDED
@@ -0,0 +1,206 @@
1
+ // Resend's signed events and receiving API. Provider ids remain in this file;
2
+ // callers receive a neutral letter, or a correlation id and RFC Message-ID.
3
+ import { Unsigned } from "@yaks/host/senders";
4
+ import { root } from "./api.js";
5
+ export { Unsigned };
6
+ let bytes = (value)=>Uint8Array.from(atob(value), (c)=>c.charCodeAt(0));
7
+ let text = new TextEncoder();
8
+ /** Verify the unparsed webhook body with its endpoint's signing key. */ export let event = async (request, secret, now = Date.now())=>{
9
+ let id = request.headers.get('svix-id');
10
+ let at = request.headers.get('svix-timestamp') ?? '';
11
+ let signatures = request.headers.get('svix-signature') ?? '';
12
+ if (!id || !/^\d+$/.test(at) || Math.abs(now / 1000 - Number(at)) > 300) {
13
+ throw new Unsigned('Resend webhook needs a fresh signed timestamp');
14
+ }
15
+ let raw = await request.text();
16
+ let key = await crypto.subtle.importKey('raw', bytes(secret.replace(/^whsec_/, '')), {
17
+ name: 'HMAC',
18
+ hash: 'SHA-256'
19
+ }, false, [
20
+ 'verify'
21
+ ]);
22
+ for (let signature of signatures.split(' ')){
23
+ let [version, digest] = signature.split(',');
24
+ if (version != 'v1' || !digest) continue;
25
+ let decoded;
26
+ try {
27
+ decoded = bytes(digest);
28
+ } catch {
29
+ continue;
30
+ }
31
+ if (await crypto.subtle.verify('HMAC', key, decoded, text.encode(`${id}.${at}.${raw}`))) {
32
+ let parsed = JSON.parse(raw);
33
+ if (parsed && typeof parsed == 'object' && 'type' in parsed && 'data' in parsed) {
34
+ return parsed;
35
+ }
36
+ }
37
+ }
38
+ throw new Unsigned('Resend webhook signature does not match');
39
+ };
40
+ /** A signed acceptance's RFC Message-ID, correlated to the caller's letter. */ export let receipt = (event)=>{
41
+ let letter = event.data.tags?.yak_letter;
42
+ let id = event.data.message_id ?? event.data.headers?.find((h)=>h.name.toLowerCase() == 'message-id')?.value;
43
+ return [
44
+ 'email.sent',
45
+ 'email.delivered'
46
+ ].includes(event.type) && letter && id ? {
47
+ letter,
48
+ id: id.replace(/[<>]/g, '')
49
+ } : undefined;
50
+ };
51
+ // One address out of either shape, `Ann <ann@example.com>` or bare.
52
+ let address = (said)=>(/<([^>]+)>/.exec(said)?.[1] ?? said).trim();
53
+ /** Receive full content and attachments, one letter for each recipient it
54
+ * names: its To, Cc and Bcc, and those Resend received it for. This
55
+ * explicitly needs a receiving credential: a sending-only key cannot retrieve
56
+ * bodies or attachments. */ export let received = async (options, email)=>decoded(await retrieved(options, email), options.fetch);
57
+ export let retrieved = async (options, email)=>{
58
+ if (!options.token) throw new Error('Resend receiving key is not configured');
59
+ let go = options.fetch ?? fetch;
60
+ let get = async (path)=>{
61
+ let res = await go(`${root(options.base)}${path}`, {
62
+ headers: {
63
+ authorization: `Bearer ${options.token}`
64
+ },
65
+ redirect: 'manual'
66
+ });
67
+ if (!res.ok) throw new Error(`Resend receive failed (HTTP ${res.status})`);
68
+ return await res.text();
69
+ };
70
+ let path = `/emails/receiving/${encodeURIComponent(email)}`;
71
+ let mail = await get(path);
72
+ let found = JSON.parse(mail);
73
+ return {
74
+ mail,
75
+ ...found.attachments?.length ? {
76
+ attachments: await get(`${path}/attachments`)
77
+ } : {}
78
+ };
79
+ };
80
+ export let decoded = async (raw, go = fetch)=>{
81
+ let mail = JSON.parse(raw.mail);
82
+ let attached = raw.attachments ? JSON.parse(raw.attachments) : {
83
+ data: []
84
+ };
85
+ let sources = [
86
+ {
87
+ name: 'message.json',
88
+ type: 'application/json',
89
+ bytes: text.encode(raw.mail)
90
+ },
91
+ ...raw.attachments ? [
92
+ {
93
+ name: 'attachments.json',
94
+ type: 'application/json',
95
+ bytes: text.encode(raw.attachments)
96
+ }
97
+ ] : []
98
+ ];
99
+ let attachments = [];
100
+ for (let a of attached.data ?? []){
101
+ // The signed download URL authorizes these bytes; never send the API key.
102
+ let url = new URL(a.download_url);
103
+ if (url.protocol != 'https:') {
104
+ throw new Error('Resend attachment needs HTTPS');
105
+ }
106
+ let response = await go(url.href, {
107
+ redirect: 'manual'
108
+ });
109
+ if (!response.ok) {
110
+ throw new Error(`Resend attachment failed (HTTP ${response.status})`);
111
+ }
112
+ attachments.push({
113
+ name: a.filename ?? '',
114
+ type: a.content_type ?? 'application/octet-stream',
115
+ bytes: new Uint8Array(await response.arrayBuffer())
116
+ });
117
+ }
118
+ let headers = new Headers(mail.headers ?? {});
119
+ let author = headers.get('from') || mail.from;
120
+ headers.set('from', address(author));
121
+ headers.set('subject', mail.subject ?? '');
122
+ headers.set('message-id', mail.message_id);
123
+ let name = /^\s*"?([^"<]*?)"?\s*</.exec(author)?.[1];
124
+ let recipients = new Map([
125
+ mail.to,
126
+ mail.cc,
127
+ mail.bcc,
128
+ mail.received_for
129
+ ].flat().filter((to)=>!!to).map((to)=>[
130
+ address(to).toLowerCase(),
131
+ address(to)
132
+ ]));
133
+ // Only the receiving server's verdict vouches for the author. Supplied
134
+ // Authentication-Results headers do not. Resend's DKIM passes only for a
135
+ // signature by the From domain, and its DMARC only aligned with it.
136
+ let checked = mail.authentication;
137
+ return [
138
+ ...recipients.values()
139
+ ].map((to)=>({
140
+ ...name ? {
141
+ name
142
+ } : {},
143
+ from: address(headers.get('return-path') || mail.from),
144
+ to,
145
+ headers,
146
+ text: mail.text ?? '',
147
+ html: mail.html ?? '',
148
+ ...checked ? {
149
+ verified: checked.dkim == 'pass'
150
+ } : {},
151
+ vouched: checked?.dmarc == 'pass',
152
+ attachments,
153
+ sources
154
+ }));
155
+ };
156
+ /** A signed provider event at the neutral receipt boundary, verified with
157
+ * the endpoint's signing secret. Where the host takes mail in (`receiving`),
158
+ * a received letter is read in full with its key. */ export let notification = async (request, secret, receiving)=>{
159
+ if (!secret) throw new Error('Resend webhook secret is not configured');
160
+ let original = request.clone();
161
+ let arrived = await event(request, secret);
162
+ if (arrived.type == 'email.received') {
163
+ let email = arrived.data.email_id;
164
+ if (!receiving) return {};
165
+ if (!email) throw new Error('Resend arrival has no email id');
166
+ if (!receiving.token && receiving.defer) return {
167
+ pending: email
168
+ };
169
+ let letters = await received(receiving, email);
170
+ let bytes = new Uint8Array(await original.arrayBuffer());
171
+ for (let mail of letters){
172
+ mail.sources = [
173
+ ...mail.sources ?? [],
174
+ {
175
+ name: 'event.json',
176
+ type: 'application/json',
177
+ bytes
178
+ },
179
+ {
180
+ name: 'event-envelope.json',
181
+ type: 'application/json',
182
+ bytes: text.encode(JSON.stringify({
183
+ url: original.url,
184
+ method: original.method,
185
+ headers: [
186
+ ...original.headers
187
+ ]
188
+ }))
189
+ }
190
+ ];
191
+ }
192
+ return {
193
+ letters
194
+ };
195
+ }
196
+ let found = receipt(arrived);
197
+ if (!found && arrived.data.tags?.yak_letter && [
198
+ 'email.sent',
199
+ 'email.delivered'
200
+ ].includes(arrived.type)) throw new Error('Resend receipt has no RFC Message-ID');
201
+ return {
202
+ tags: arrived.data.tags,
203
+ receipt: found
204
+ };
205
+ };
206
+ //# sourceMappingURL=receive.js.map
package/receive.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.js","sources":["./receive.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,SAIE,QAAQ,kCAC4B;AACtC,SAAqB,IAAI,mBAAkB;AAE3C,SAAS,QAAQ,GAAE;AAuCnB,IAAI,QAAQ,CAAC,QACX,WAAW,IAAI,CAAC,KAAK,QAAQ,CAAC,IAAM,EAAE,UAAU,CAAC;AACnD,IAAI,OAAO,IAAI;AAEf,sEAAsE,GACtE,OAAO,IAAI,QAAQ,OACjB,SACA,QACA,MAAc,KAAK,GAAG,EAAE;EAExB,IAAI,KAAK,QAAQ,OAAO,CAAC,GAAG,CAAC;EAC7B,IAAI,KAAK,QAAQ,OAAO,CAAC,GAAG,CAAC,qBAAqB;EAClD,IAAI,aAAa,QAAQ,OAAO,CAAC,GAAG,CAAC,qBAAqB;EAC1D,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,CAAC,OAAO,KAAK,GAAG,CAAC,MAAM,OAAO,OA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AAQ,IAAI,GACvD,MAAM,IAAI,MAAM;EAClB,OAAO;IAAE,MAAM,QAAQ,IAAI,CAAC,IAAI;IAAE,SAAS;EAAM;AACnD,EAAC"}
package/receive.ts ADDED
@@ -0,0 +1,266 @@
1
+ // Resend's signed events and receiving API. Provider ids remain in this file;
2
+ // callers receive a neutral letter, or a correlation id and RFC Message-ID.
3
+ import {
4
+ type Incoming,
5
+ type MailSource,
6
+ type Notice,
7
+ Unsigned,
8
+ } from '@yaks/host/senders'
9
+ import { type Fetch, root } from './api.js'
10
+
11
+ export { Unsigned }
12
+
13
+ export type Event = {
14
+ type: string
15
+ data: {
16
+ email_id?: string
17
+ message_id?: string
18
+ to?: string[]
19
+ cc?: string[]
20
+ bcc?: string[]
21
+ received_for?: string[]
22
+ tags?: Record<string, string>
23
+ headers?: { name: string; value: string }[]
24
+ }
25
+ }
26
+ type ReceivedEmail = {
27
+ from: string
28
+ to: string[]
29
+ cc?: string[]
30
+ bcc?: string[]
31
+ received_for?: string[]
32
+ subject?: string
33
+ message_id: string
34
+ headers?: Record<string, string>
35
+ text?: string
36
+ html?: string
37
+ authentication?: { spf?: string; dkim?: string; dmarc?: string } | null
38
+ attachments?: unknown[]
39
+ data?: { download_url: string; filename?: string; content_type?: string }[]
40
+ }
41
+ export type Receiving = {
42
+ /** a `full_access` key: a sending key cannot read received mail */
43
+ token?: string
44
+ /** Hand authenticated arrivals off to the host for later retrieval. */
45
+ defer?: boolean
46
+ base?: string
47
+ fetch?: Fetch
48
+ }
49
+
50
+ let bytes = (value: string) =>
51
+ Uint8Array.from(atob(value), (c) => c.charCodeAt(0))
52
+ let text = new TextEncoder()
53
+
54
+ /** Verify the unparsed webhook body with its endpoint's signing key. */
55
+ export let event = async (
56
+ request: Request,
57
+ secret: string,
58
+ now: number = Date.now(),
59
+ ): Promise<Event> => {
60
+ let id = request.headers.get('svix-id')
61
+ let at = request.headers.get('svix-timestamp') ?? ''
62
+ let signatures = request.headers.get('svix-signature') ?? ''
63
+ if (!id || !/^\d+$/.test(at) || Math.abs(now / 1000 - Number(at)) > 300) {
64
+ throw new Unsigned('Resend webhook needs a fresh signed timestamp')
65
+ }
66
+ let raw = await request.text()
67
+ let key = await crypto.subtle.importKey(
68
+ 'raw',
69
+ bytes(secret.replace(/^whsec_/, '')),
70
+ { name: 'HMAC', hash: 'SHA-256' },
71
+ false,
72
+ ['verify'],
73
+ )
74
+ for (let signature of signatures.split(' ')) {
75
+ let [version, digest] = signature.split(',')
76
+ if (version != 'v1' || !digest) continue
77
+ let decoded: Uint8Array<ArrayBuffer>
78
+ try {
79
+ decoded = bytes(digest)
80
+ } catch {
81
+ continue
82
+ }
83
+ if (
84
+ await crypto.subtle.verify(
85
+ 'HMAC',
86
+ key,
87
+ decoded,
88
+ text.encode(`${id}.${at}.${raw}`),
89
+ )
90
+ ) {
91
+ let parsed: unknown = JSON.parse(raw)
92
+ if (
93
+ parsed && typeof parsed == 'object' && 'type' in parsed &&
94
+ 'data' in parsed
95
+ ) {
96
+ return parsed as Event
97
+ }
98
+ }
99
+ }
100
+ throw new Unsigned('Resend webhook signature does not match')
101
+ }
102
+
103
+ /** A signed acceptance's RFC Message-ID, correlated to the caller's letter. */
104
+ export let receipt = (
105
+ event: Event,
106
+ ): { letter: string; id: string } | undefined => {
107
+ let letter = event.data.tags?.yak_letter
108
+ let id = event.data.message_id ??
109
+ event.data.headers?.find((h) => h.name.toLowerCase() == 'message-id')?.value
110
+ return ['email.sent', 'email.delivered'].includes(event.type) && letter && id
111
+ ? { letter, id: id.replace(/[<>]/g, '') }
112
+ : undefined
113
+ }
114
+
115
+ // One address out of either shape, `Ann <ann@example.com>` or bare.
116
+ let address = (said: string) => (/<([^>]+)>/.exec(said)?.[1] ?? said).trim()
117
+
118
+ /** Receive full content and attachments, one letter for each recipient it
119
+ * names: its To, Cc and Bcc, and those Resend received it for. This
120
+ * explicitly needs a receiving credential: a sending-only key cannot retrieve
121
+ * bodies or attachments. */
122
+ export let received = async (
123
+ options: Receiving,
124
+ email: string,
125
+ ): Promise<Incoming[]> =>
126
+ decoded(await retrieved(options, email), options.fetch)
127
+
128
+ /** The provider responses needed to relay a received letter. Attachment
129
+ * bytes travel separately from the provider's expiring download URLs. */
130
+ export type Retrieved = { mail: string; attachments?: string }
131
+
132
+ export let retrieved = async (
133
+ options: Receiving,
134
+ email: string,
135
+ ): Promise<Retrieved> => {
136
+ if (!options.token) throw new Error('Resend receiving key is not configured')
137
+ let go = options.fetch ?? fetch
138
+ let get = async (path: string) => {
139
+ let res = await go(`${root(options.base)}${path}`, {
140
+ headers: { authorization: `Bearer ${options.token}` },
141
+ redirect: 'manual',
142
+ })
143
+ if (!res.ok) throw new Error(`Resend receive failed (HTTP ${res.status})`)
144
+ return await res.text()
145
+ }
146
+ let path = `/emails/receiving/${encodeURIComponent(email)}`
147
+ let mail = await get(path)
148
+ let found = JSON.parse(mail) as ReceivedEmail
149
+ return {
150
+ mail,
151
+ ...found.attachments?.length
152
+ ? { attachments: await get(`${path}/attachments`) }
153
+ : {},
154
+ }
155
+ }
156
+
157
+ export let decoded = async (
158
+ raw: Retrieved,
159
+ go: Fetch = fetch,
160
+ ): Promise<Incoming[]> => {
161
+ let mail = JSON.parse(raw.mail) as ReceivedEmail
162
+ let attached = raw.attachments
163
+ ? JSON.parse(raw.attachments) as ReceivedEmail
164
+ : { data: [] }
165
+ let sources: MailSource[] = [
166
+ {
167
+ name: 'message.json',
168
+ type: 'application/json',
169
+ bytes: text.encode(raw.mail),
170
+ },
171
+ ...raw.attachments
172
+ ? [{
173
+ name: 'attachments.json',
174
+ type: 'application/json',
175
+ bytes: text.encode(raw.attachments),
176
+ }]
177
+ : [],
178
+ ]
179
+ let attachments: Incoming['attachments'] = []
180
+ for (let a of attached.data ?? []) {
181
+ // The signed download URL authorizes these bytes; never send the API key.
182
+ let url = new URL(a.download_url)
183
+ if (url.protocol != 'https:') {
184
+ throw new Error('Resend attachment needs HTTPS')
185
+ }
186
+ let response = await go(url.href, { redirect: 'manual' })
187
+ if (!response.ok) {
188
+ throw new Error(`Resend attachment failed (HTTP ${response.status})`)
189
+ }
190
+ attachments.push({
191
+ name: a.filename ?? '',
192
+ type: a.content_type ?? 'application/octet-stream',
193
+ bytes: new Uint8Array(await response.arrayBuffer()),
194
+ })
195
+ }
196
+ let headers = new Headers(mail.headers ?? {})
197
+ let author = headers.get('from') || mail.from
198
+ headers.set('from', address(author))
199
+ headers.set('subject', mail.subject ?? '')
200
+ headers.set('message-id', mail.message_id)
201
+ let name = /^\s*"?([^"<]*?)"?\s*</.exec(author)?.[1]
202
+ let recipients = new Map(
203
+ [mail.to, mail.cc, mail.bcc, mail.received_for].flat()
204
+ .filter((to): to is string => !!to)
205
+ .map((to) => [address(to).toLowerCase(), address(to)]),
206
+ )
207
+ // Only the receiving server's verdict vouches for the author. Supplied
208
+ // Authentication-Results headers do not. Resend's DKIM passes only for a
209
+ // signature by the From domain, and its DMARC only aligned with it.
210
+ let checked = mail.authentication
211
+ return [...recipients.values()].map((to) => ({
212
+ ...name ? { name } : {},
213
+ from: address(headers.get('return-path') || mail.from),
214
+ to,
215
+ headers,
216
+ text: mail.text ?? '',
217
+ html: mail.html ?? '',
218
+ ...checked ? { verified: checked.dkim == 'pass' } : {},
219
+ vouched: checked?.dmarc == 'pass',
220
+ attachments,
221
+ sources,
222
+ }))
223
+ }
224
+
225
+ /** A signed provider event at the neutral receipt boundary, verified with
226
+ * the endpoint's signing secret. Where the host takes mail in (`receiving`),
227
+ * a received letter is read in full with its key. */
228
+ export let notification = async (
229
+ request: Request,
230
+ secret: string | undefined,
231
+ receiving?: Receiving,
232
+ ): Promise<Notice> => {
233
+ if (!secret) throw new Error('Resend webhook secret is not configured')
234
+ let original = request.clone()
235
+ let arrived = await event(request, secret)
236
+ if (arrived.type == 'email.received') {
237
+ let email = arrived.data.email_id
238
+ if (!receiving) return {}
239
+ if (!email) throw new Error('Resend arrival has no email id')
240
+ if (!receiving.token && receiving.defer) return { pending: email }
241
+ let letters = await received(receiving, email)
242
+ let bytes = new Uint8Array(await original.arrayBuffer())
243
+ for (let mail of letters) {
244
+ mail.sources = [...mail.sources ?? [], {
245
+ name: 'event.json',
246
+ type: 'application/json',
247
+ bytes,
248
+ }, {
249
+ name: 'event-envelope.json',
250
+ type: 'application/json',
251
+ bytes: text.encode(JSON.stringify({
252
+ url: original.url,
253
+ method: original.method,
254
+ headers: [...original.headers],
255
+ })),
256
+ }]
257
+ }
258
+ return { letters }
259
+ }
260
+ let found = receipt(arrived)
261
+ if (
262
+ !found && arrived.data.tags?.yak_letter &&
263
+ ['email.sent', 'email.delivered'].includes(arrived.type)
264
+ ) throw new Error('Resend receipt has no RFC Message-ID')
265
+ return { tags: arrived.data.tags, receipt: found }
266
+ }
package/routes.js ADDED
@@ -0,0 +1,43 @@
1
+ // The `@yaks/resend/routes` facet: the webhook Resend posts this sender's
2
+ // delivery receipts to. A signed receipt updates the letter @yaks/mail
3
+ // recorded; a missing letter is a retryable answer, since an Operator may
4
+ // still be committing it. Only the endpoint's signing secret authorizes this.
5
+ import { receipted } from "@yaks/mail";
6
+ import { notification, Unsigned } from "./receive.js";
7
+ /** The receipt route, where the options configure one. */ export let routes = (host, options = {})=>{
8
+ let { receipts } = options;
9
+ if (!receipts) return [];
10
+ return [
11
+ {
12
+ method: 'POST',
13
+ path: receipts.path ?? '/mail/resend',
14
+ handle: async (request)=>{
15
+ try {
16
+ let arrived = await notification(request, receipts.secret);
17
+ let ours = Object.entries(options.tags ?? {}).every(([key, value])=>arrived.tags?.[key] == value);
18
+ if (ours && arrived.receipt) {
19
+ await receipted(host.graph, arrived.receipt);
20
+ }
21
+ return Response.json({
22
+ ok: true
23
+ });
24
+ } catch (error) {
25
+ if (error instanceof Unsigned) {
26
+ return Response.json({
27
+ error: error.message
28
+ }, {
29
+ status: 401
30
+ });
31
+ }
32
+ await host.report?.(error);
33
+ return Response.json({
34
+ error: 'mail receipt is waiting'
35
+ }, {
36
+ status: 503
37
+ });
38
+ }
39
+ }
40
+ }
41
+ ];
42
+ };
43
+ //# sourceMappingURL=routes.js.map
package/routes.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sources":["./routes.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,uEAAuE;AACvE,0EAA0E;AAC1E,8EAA8E;AAG9E,SAAS,SAAS,0BAA+B;AAEjD,SAAS,YAAY,EAAE,QAAQ,uBAAsB;AAErD,wDAAwD,GACxD,OAAO,IAAI,SAAS,CAClB,MAIA,UAAmB,CAAC,CAAC;EAErB,IAAI,EAAE,QAAQ,EAAE,GAAG;EACnB,IAAI,CAAC,UAAU,OAAO,EAAE;EACxB,OAAO;IAAC;MACN,QAAQ;MACR,MAAM,SAAS,IAAI,IAAI;MACvB,QAAQ,OAAO;QACb,IAAI;UACF,IAAI,UAAU,MAAM,aAAa,SAAS,SAAS,MAAM;UACzD,IAAI,OAAO,OAAO,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM,GAC/D,QAAQ,IAAI,EAAE,CAAC,IAAI,IAAI;UAEzB,IAAI,QAAQ,QAAQ,OAAO,EAAE;YAC3B,MAAM,UAAU,KAAK,KAAK,EAAE,QAAQ,OAAO;UAC7C;UACA,OAAO,SAAS,IAAI,CAAC;YAAE,IAAI;UAAK;QAClC,EAAE,OAAO,OAAO;UACd,IAAI,iBAAiB,UAAU;YAC7B,OAAO,SAAS,IAAI,CAAC;cAAE,OAAO,MAAM,OAAO;YAAC,GAAG;cAAE,QAAQ;YAAI;UAC/D;UACA,MAAM,KAAK,MAAM,GAAG;UACpB,OAAO,SAAS,IAAI,CAAC;YAAE,OAAO;UAA0B,GAAG;YACzD,QAAQ;UACV;QACF;MACF;IACF;GAAE;AACJ,EAAC"}
package/routes.ts ADDED
@@ -0,0 +1,45 @@
1
+ // The `@yaks/resend/routes` facet: the webhook Resend posts this sender's
2
+ // delivery receipts to. A signed receipt updates the letter @yaks/mail
3
+ // recorded; a missing letter is a retryable answer, since an Operator may
4
+ // still be committing it. Only the endpoint's signing secret authorizes this.
5
+ import type { Route } from 'jsr:@yaks/api@0.2.36'
6
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
7
+ import { receipted } from '@yaks/mail'
8
+ import type { Options } from './options.ts'
9
+ import { notification, Unsigned } from './receive.js'
10
+
11
+ /** The receipt route, where the options configure one. */
12
+ export let routes = (
13
+ host: {
14
+ graph: Pick<Graph, 'get' | 'apply'>
15
+ report?: (error: unknown) => unknown
16
+ },
17
+ options: Options = {},
18
+ ): Route[] => {
19
+ let { receipts } = options
20
+ if (!receipts) return []
21
+ return [{
22
+ method: 'POST',
23
+ path: receipts.path ?? '/mail/resend',
24
+ handle: async (request) => {
25
+ try {
26
+ let arrived = await notification(request, receipts.secret)
27
+ let ours = Object.entries(options.tags ?? {}).every(([key, value]) =>
28
+ arrived.tags?.[key] == value
29
+ )
30
+ if (ours && arrived.receipt) {
31
+ await receipted(host.graph, arrived.receipt)
32
+ }
33
+ return Response.json({ ok: true })
34
+ } catch (error) {
35
+ if (error instanceof Unsigned) {
36
+ return Response.json({ error: error.message }, { status: 401 })
37
+ }
38
+ await host.report?.(error)
39
+ return Response.json({ error: 'mail receipt is waiting' }, {
40
+ status: 503,
41
+ })
42
+ }
43
+ },
44
+ }]
45
+ }