Repository navigation
Expand file tree
/
Copy pathsend.ts
More file actions
177 lines (159 loc) · 7.04 KB
/
Copy pathsend.ts
File metadata and controls
177 lines (159 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**
* The sender. One call fans out over every stored subscription.
*
* Two things the caller is entitled to know and cannot work out for itself:
* how many devices the message actually reached, and which subscriptions died.
* A fan-out of zero is not a success, and this is the only place that can tell.
*/
import { encryptPayload } from "./encrypt.ts";
import { InvalidRequest } from "./errors.ts";
import { buildDeclarativePayload, type BuildPayloadOptions } from "./payload.ts";
import { utf8 } from "./bytes.ts";
import { deleteSubscription, listSubscriptions } from "./subscriptions.ts";
import { importVapidKeys, signVapidToken } from "./vapid.ts";
import type { KukurooEnv } from "./env.ts";
/**
* There is no `topic`. Apple's push service answers any push carrying a Topic
* header with 400 `BadWebPushTopic`, whatever its value, and every device
* Kukuroo can reach is behind it. `notification.tag` is how a later
* notification replaces an earlier one.
*/
export interface SendOptions extends BuildPayloadOptions {
/** Seconds the push service may hold an undelivered message. Default 4 hours. */
ttl?: number;
}
export interface SendResult {
/** Subscriptions the push service accepted the message for. */
delivered: number;
/** Subscriptions that returned 404 or 410 and have been deleted. */
removed: number;
/** Everything else: transient, retryable, or a bug. */
failures: Array<{ endpoint: string; status: number | null; detail: string }>;
}
const DEFAULT_TTL_SECONDS = 4 * 60 * 60;
/**
* Just under 2^31 seconds. The bound is what makes this check mean anything:
* `Number.isInteger(1e21)` is true, and `String(1e21)` is "1e+21", so an
* integer test alone still lets exponent notation reach the TTL header, which
* every push service then rejects for every subscription.
*/
const MAX_TTL_SECONDS = 2_147_483_647;
/**
* The header options, checked once before the loop.
*
* Everything else the caller supplies is validated by buildDeclarativePayload
* before any network call, for the reason stated there: a bad value is bad for
* every device, and finding out after a partial fan-out is strictly worse. A
* header option that reached the push service wrong produced a rejection per
* subscription and an HTTP 200 carrying `delivered: 0`, which reads as "it
* worked" everywhere except the phone.
*/
function assertHeaderOptions(options: SendOptions): void {
const { ttl } = options;
if (ttl !== undefined && (!Number.isInteger(ttl) || ttl < 0 || ttl > MAX_TTL_SECONDS)) {
throw new InvalidRequest(
`ttl must be an integer number of seconds between 0 and ${MAX_TTL_SECONDS}; got ` +
`${JSON.stringify(ttl)}. It goes out as the TTL header, and a push service rejects ` +
`a malformed one for every subscription.`,
);
}
if ((options as { topic?: unknown }).topic !== undefined) {
throw new InvalidRequest(
`topic is not supported: Apple's push service rejects every push that carries a ` +
`Topic header (400 BadWebPushTopic), so no device would receive it. Use ` +
`notification.tag to have a later notification replace an earlier one.`,
);
}
}
/**
* `sub` in the VAPID token must be a mailto: or https: URI. Apple rejects the
* token without one and the 400 does not say why, so it is never left unset.
*
* The fallback is the *push service's* own origin, which is a valid https URI
* and is accepted, but it identifies nobody. Set KUKUROO_VAPID_SUBJECT to a
* mailto: you actually read if you want a push service to be able to reach you
* about your traffic.
*/
function vapidSubject(env: KukurooEnv, endpoint: string): string {
if (env.KUKUROO_VAPID_SUBJECT) return env.KUKUROO_VAPID_SUBJECT;
return new URL(endpoint).origin;
}
export async function send(env: KukurooEnv, options: SendOptions): Promise<SendResult> {
// Built and validated once, before any network call. If the payload is wrong
// it is wrong for every device, and finding out after a partial fan-out is
// strictly worse than finding out now.
// The origin restriction is operator policy from the environment, never from
// the request body: a caller holding the send token controls the body, so a
// body-supplied limit would restrict nobody.
// An empty string is how an unset var reaches a Worker when someone declares
// it in wrangler.jsonc and leaves the value blank. `"" !== undefined` would
// activate the policy against an origin nothing can match.
const json = buildDeclarativePayload(options, {
navigateOrigin: env.KUKUROO_NAVIGATE_ORIGIN || undefined,
});
const plaintext = utf8(json);
assertHeaderOptions(options);
// Validated once, before the loop, because it is an env-level mistake: a
// malformed subject would otherwise surface as one failure per device, or
// worse, as Apple's unexplained 400 on every send. RFC 8292 wants a mailto:
// or https: URI here.
if (env.KUKUROO_VAPID_SUBJECT && !/^(mailto:|https:)/.test(env.KUKUROO_VAPID_SUBJECT)) {
throw new Error(
`KUKUROO_VAPID_SUBJECT must be a mailto: or https: URI; got ` +
`${JSON.stringify(env.KUKUROO_VAPID_SUBJECT)}`,
);
}
const subscriptions = await listSubscriptions(env.KUKUROO_SUBS);
const result: SendResult = { delivered: 0, removed: 0, failures: [] };
if (subscriptions.length === 0) return result;
const { privateKey, publicKeyB64 } = await importVapidKeys(
env.KUKUROO_VAPID_PRIVATE,
env.KUKUROO_VAPID_PUBLIC,
);
for (const { key, subscription } of subscriptions) {
try {
const endpoint = new URL(subscription.endpoint);
const token = await signVapidToken(
privateKey,
endpoint.origin,
vapidSubject(env, subscription.endpoint),
);
const body = await encryptPayload(plaintext, subscription.keys);
const headers: Record<string, string> = {
Authorization: `vapid t=${token}, k=${publicKeyB64}`,
"Content-Encoding": "aes128gcm",
"Content-Type": "application/octet-stream",
TTL: String(options.ttl ?? DEFAULT_TTL_SECONDS),
Urgency: "normal",
};
const response = await fetch(subscription.endpoint, {
method: "POST",
headers,
body: body as unknown as BodyInit,
});
if (response.status === 404 || response.status === 410) {
// The subscription is gone: the icon was deleted, or the device rotated
// it. Nothing tells the *owner* this happened, which is why a
// deployment that cares about delivery needs a positive daily signal
// rather than error detection.
await deleteSubscription(env.KUKUROO_SUBS, key);
result.removed += 1;
} else if (response.ok) {
result.delivered += 1;
} else {
result.failures.push({
endpoint: subscription.endpoint,
status: response.status,
detail: (await response.text()).slice(0, 500),
});
}
} catch (error) {
result.failures.push({
endpoint: subscription.endpoint,
status: null,
detail: error instanceof Error ? error.message : String(error),
});
}
}
return result;
}