Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

apnsDeliveryJobs.ts

438 lines14.2 KB

1import * as NodeCrypto from "node:crypto";
2​
3import {
4 RelayAgentActivityAggregateState,
5 RelayAgentAwarenessPhase,
6 type RelayDeliveryKind,
7} from "@t3tools/contracts/relay";
8import { stableStringify } from "@t3tools/shared/relaySigning";
9import * as DateTime from "effect/DateTime";
10import * as Option from "effect/Option";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13​
14const MAX_JOB_AGE_MS = 10 * 60 * 1_000;
15export const APNS_DELIVERY_JOB_SIGNING_ALGORITHM = "hmac-sha256";
16​
17const ApnsDeliveryKindSchema = Schema.Literals([
18 "live_activity_start",
19 "live_activity_update",
20 "live_activity_end",
21 "push_notification",
22]);
23const LiveActivityStartOrUpdateKindSchema = Schema.Literals([
24 "live_activity_start",
25 "live_activity_update",
26]);
27const LiveActivityKindSchema = Schema.Literals([
28 "live_activity_start",
29 "live_activity_update",
30 "live_activity_end",
31]);
32​
33const ApnsDeliveryJobContext = {
34 jobId: Schema.String,
35 userId: Schema.String,
36 deviceId: Schema.String,
37};
38​
39export const ApnsNotificationPayload = Schema.Struct({
40 title: Schema.String,
41 body: Schema.String,
42 environmentId: Schema.String,
43 threadId: Schema.String,
44 deepLink: Schema.String,
45 // Optional so delivery jobs queued by older relay builds still decode.
46 // New jobs use these fields to avoid delivering a stale Done/attention
47 // notification after the thread has moved to another phase.
48 phase: Schema.optional(RelayAgentAwarenessPhase),
49 updatedAt: Schema.optional(Schema.String),
50});
51export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
52​
53// Alert copy attached to a Live Activity update/end push. Its presence makes
54// the update "alerting": iOS wakes the screen, plays the haptic, and briefly
55// expands the Dynamic Island instead of silently redrawing.
56export const ApnsLiveActivityAlert = Schema.Struct({
57 title: Schema.String,
58 body: Schema.String,
59});
60export type ApnsLiveActivityAlert = typeof ApnsLiveActivityAlert.Type;
61​
62export const ApnsDeliveryJobPayload = Schema.Struct({
63 version: Schema.Literal(1),
64 jobId: Schema.String,
65 kind: ApnsDeliveryKindSchema,
66 target: Schema.Struct({
67 userId: Schema.String,
68 deviceId: Schema.String,
69 token: Schema.String,
70 // Per-device APNs routing; absent on jobs queued by older relay builds,
71 // which fall back to the configured defaults.
72 bundleId: Schema.optional(Schema.NullOr(Schema.String)),
73 apsEnvironment: Schema.optional(Schema.NullOr(Schema.Literals(["sandbox", "production"]))),
74 }),
75 aggregate: Schema.NullOr(RelayAgentActivityAggregateState),
76 notification: Schema.NullOr(ApnsNotificationPayload),
77 // Optional so jobs queued by older relay builds still decode.
78 alert: Schema.optional(Schema.NullOr(ApnsLiveActivityAlert)),
79 createdAt: Schema.String,
80 expiresAt: Schema.String,
81});
82export type ApnsDeliveryJobPayload = typeof ApnsDeliveryJobPayload.Type;
83​
84export const SignedApnsDeliveryJob = Schema.Struct({
85 algorithm: Schema.Literal(APNS_DELIVERY_JOB_SIGNING_ALGORITHM),
86 payload: ApnsDeliveryJobPayload,
87 signature: Schema.String,
88});
89export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
90​
91export class ApnsDeliveryJobQueuePayloadInvalid extends Schema.TaggedError<ApnsDeliveryJobQueuePayloadInvalid>()(
92 "ApnsDeliveryJobQueuePayloadInvalid",
93 {
94 receivedType: Schema.String,
95 cause: Schema.Defect(),
96 },
97) {
98 override get message(): string {
99 return `Invalid APNs delivery queue job with ${this.receivedType} payload.`;
100 }
102​
103export class ApnsDeliveryJobLiveActivityAggregateMissing extends Schema.TaggedError<ApnsDeliveryJobLiveActivityAggregateMissing>()(
104 "ApnsDeliveryJobLiveActivityAggregateMissing",
105 {
106 ...ApnsDeliveryJobContext,
107 kind: LiveActivityStartOrUpdateKindSchema,
108 },
109) {
110 override get message(): string {
111 return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} requires an aggregate.`;
112 }
114​
115export class ApnsDeliveryJobLiveActivityNotificationUnexpected extends Schema.TaggedError<ApnsDeliveryJobLiveActivityNotificationUnexpected>()(
116 "ApnsDeliveryJobLiveActivityNotificationUnexpected",
117 {
118 ...ApnsDeliveryJobContext,
119 kind: LiveActivityKindSchema,
120 },
121) {
122 override get message(): string {
123 return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} must not carry a push notification payload.`;
124 }
126​
127export class ApnsDeliveryJobPushNotificationMissing extends Schema.TaggedError<ApnsDeliveryJobPushNotificationMissing>()(
128 "ApnsDeliveryJobPushNotificationMissing",
129 ApnsDeliveryJobContext,
130) {
131 override get message(): string {
132 return `APNs push notification job ${this.jobId} requires a notification payload.`;
133 }
135​
136export class ApnsDeliveryJobPushNotificationAggregateUnexpected extends Schema.TaggedError<ApnsDeliveryJobPushNotificationAggregateUnexpected>()(
137 "ApnsDeliveryJobPushNotificationAggregateUnexpected",
138 ApnsDeliveryJobContext,
139) {
140 override get message(): string {
141 return `APNs push notification job ${this.jobId} must not carry aggregate state.`;
142 }
144​
145export class ApnsDeliveryJobCreatedAtInvalid extends Schema.TaggedError<ApnsDeliveryJobCreatedAtInvalid>()(
146 "ApnsDeliveryJobCreatedAtInvalid",
147 {
148 ...ApnsDeliveryJobContext,
149 kind: ApnsDeliveryKindSchema,
150 createdAt: Schema.String,
151 },
152) {
153 override get message(): string {
154 return `APNs delivery job ${this.jobId} has invalid creation time ${this.createdAt}.`;
155 }
157​
158export class ApnsDeliveryJobExpiresAtInvalid extends Schema.TaggedError<ApnsDeliveryJobExpiresAtInvalid>()(
159 "ApnsDeliveryJobExpiresAtInvalid",
160 {
161 ...ApnsDeliveryJobContext,
162 kind: ApnsDeliveryKindSchema,
163 expiresAt: Schema.String,
164 },
165) {
166 override get message(): string {
167 return `APNs delivery job ${this.jobId} has invalid expiry ${this.expiresAt}.`;
168 }
170​
171export class ApnsDeliveryJobTimeWindowInvalid extends Schema.TaggedError<ApnsDeliveryJobTimeWindowInvalid>()(
172 "ApnsDeliveryJobTimeWindowInvalid",
173 {
174 ...ApnsDeliveryJobContext,
175 kind: ApnsDeliveryKindSchema,
176 createdAt: Schema.String,
177 expiresAt: Schema.String,
178 },
179) {
180 override get message(): string {
181 return `APNs delivery job ${this.jobId} has invalid time window ${this.createdAt} to ${this.expiresAt}.`;
182 }
184​
185export class ApnsDeliveryJobTimeWindowTooLong extends Schema.TaggedError<ApnsDeliveryJobTimeWindowTooLong>()(
186 "ApnsDeliveryJobTimeWindowTooLong",
187 {
188 ...ApnsDeliveryJobContext,
189 kind: ApnsDeliveryKindSchema,
190 createdAt: Schema.String,
191 expiresAt: Schema.String,
192 },
193) {
194 override get message(): string {
195 return `APNs delivery job ${this.jobId} time window ${this.createdAt} to ${this.expiresAt} is too long.`;
196 }
198​
199export class ApnsDeliveryJobSignatureInvalid extends Schema.TaggedError<ApnsDeliveryJobSignatureInvalid>()(
200 "ApnsDeliveryJobSignatureInvalid",
201 {
202 ...ApnsDeliveryJobContext,
203 kind: ApnsDeliveryKindSchema,
204 },
205) {
206 override get message(): string {
207 return `Invalid signature for APNs delivery job ${this.jobId}.`;
208 }
210​
211export const ApnsDeliveryJobInvalid = Schema.Union([
212 ApnsDeliveryJobQueuePayloadInvalid,
213 ApnsDeliveryJobLiveActivityAggregateMissing,
214 ApnsDeliveryJobLiveActivityNotificationUnexpected,
215 ApnsDeliveryJobPushNotificationMissing,
216 ApnsDeliveryJobPushNotificationAggregateUnexpected,
217 ApnsDeliveryJobCreatedAtInvalid,
218 ApnsDeliveryJobExpiresAtInvalid,
219 ApnsDeliveryJobTimeWindowInvalid,
220 ApnsDeliveryJobTimeWindowTooLong,
221 ApnsDeliveryJobSignatureInvalid,
222]);
223export type ApnsDeliveryJobInvalid = typeof ApnsDeliveryJobInvalid.Type;
224​
225export class ApnsDeliveryJobExpired extends Schema.TaggedError<ApnsDeliveryJobExpired>()(
226 "ApnsDeliveryJobExpired",
227 {
228 ...ApnsDeliveryJobContext,
229 kind: ApnsDeliveryKindSchema,
230 expiresAt: Schema.String,
231 },
232) {
233 override get message(): string {
234 return `APNs delivery job ${this.jobId} expired at ${this.expiresAt}.`;
235 }
237​
238export const ApnsDeliveryJobVerificationError = Schema.Union([
239 ApnsDeliveryJobInvalid,
240 ApnsDeliveryJobExpired,
241]);
242export type ApnsDeliveryJobVerificationError = typeof ApnsDeliveryJobVerificationError.Type;
243​
244export const isApnsDeliveryJobVerificationError = Schema.is(ApnsDeliveryJobVerificationError);
245​
246export function makeApnsDeliveryJobPayload(input: {
247 readonly kind: RelayDeliveryKind;
248 readonly userId: string;
249 readonly deviceId: string;
250 readonly token: string;
251 readonly bundleId?: string | null | undefined;
252 readonly apsEnvironment?: "sandbox" | "production" | null | undefined;
253 readonly aggregate: ApnsDeliveryJobPayload["aggregate"];
254 readonly notification?: ApnsNotificationPayload | null;
255 readonly alert?: ApnsLiveActivityAlert | null | undefined;
256 readonly createdAt: string;
257 readonly expiresAt: string;
258 readonly jobId: string;
259}): ApnsDeliveryJobPayload {
260 return {
261 version: 1,
262 jobId: input.jobId,
263 kind: input.kind,
264 target: {
265 userId: input.userId,
266 deviceId: input.deviceId,
267 token: input.token,
268 ...(input.bundleId ? { bundleId: input.bundleId } : {}),
269 ...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
270 },
271 aggregate: input.aggregate,
272 notification: input.notification ?? null,
273 // Omitted (not null) when absent so signatures stay identical to jobs from
274 // relay builds that predate the field.
275 ...(input.alert ? { alert: input.alert } : {}),
276 createdAt: input.createdAt,
277 expiresAt: input.expiresAt,
278 };
280​
281export function expiresAtForJob(createdAtMs: number): string {
282 return DateTime.formatIso(Option.getOrThrow(DateTime.make(createdAtMs + MAX_JOB_AGE_MS)));
284​
285function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobInvalid | null {
286 switch (payload.kind) {
287 case "live_activity_start":
288 case "live_activity_update":
289 if (payload.aggregate === null) {
290 return new ApnsDeliveryJobLiveActivityAggregateMissing({
291 jobId: payload.jobId,
292 kind: payload.kind,
293 userId: payload.target.userId,
294 deviceId: payload.target.deviceId,
295 });
296 }
297 if (payload.notification !== null) {
298 return new ApnsDeliveryJobLiveActivityNotificationUnexpected({
299 jobId: payload.jobId,
300 kind: payload.kind,
301 userId: payload.target.userId,
302 deviceId: payload.target.deviceId,
303 });
304 }
305 return null;
306 case "live_activity_end":
307 if (payload.notification !== null) {
308 return new ApnsDeliveryJobLiveActivityNotificationUnexpected({
309 jobId: payload.jobId,
310 kind: payload.kind,
311 userId: payload.target.userId,
312 deviceId: payload.target.deviceId,
313 });
314 }
315 return null;
316 case "push_notification":
317 if (payload.notification === null) {
318 return new ApnsDeliveryJobPushNotificationMissing({
319 jobId: payload.jobId,
320 userId: payload.target.userId,
321 deviceId: payload.target.deviceId,
322 });
323 }
324 if (payload.aggregate !== null) {
325 return new ApnsDeliveryJobPushNotificationAggregateUnexpected({
326 jobId: payload.jobId,
327 userId: payload.target.userId,
328 deviceId: payload.target.deviceId,
329 });
330 }
331 return null;
332 }
334​
335function signatureForPayload(input: {
336 readonly secret: Redacted.Redacted<string>;
337 readonly payload: ApnsDeliveryJobPayload;
338}): string {
339 return NodeCrypto.createHmac("sha256", Redacted.value(input.secret))
340 .update(stableStringify(input.payload))
341 .digest("base64url");
343​
344function timingSafeEqualBase64Url(left: string, right: string): boolean {
345 const leftBuffer = Buffer.from(left, "base64url");
346 const rightBuffer = Buffer.from(right, "base64url");
347 if (leftBuffer.length !== rightBuffer.length) {
348 return false;
349 }
350 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
352​
353export function signApnsDeliveryJob(input: {
354 readonly secret: Redacted.Redacted<string>;
355 readonly payload: ApnsDeliveryJobPayload;
356}): SignedApnsDeliveryJob {
357 return {
358 algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM,
359 payload: input.payload,
360 signature: signatureForPayload(input),
361 };
363​
364export function verifySignedApnsDeliveryJob(input: {
365 readonly secret: Redacted.Redacted<string>;
366 readonly job: SignedApnsDeliveryJob;
367 readonly nowMs: number;
368}): ApnsDeliveryJobPayload | ApnsDeliveryJobVerificationError {
369 const payload = input.job.payload;
370 const invalidPayload = validatePayloadShape(payload);
371 if (invalidPayload !== null) {
372 return invalidPayload;
373 }
374 const createdAt = DateTime.make(payload.createdAt);
375 if (Option.isNone(createdAt)) {
376 return new ApnsDeliveryJobCreatedAtInvalid({
377 jobId: payload.jobId,
378 kind: payload.kind,
379 userId: payload.target.userId,
380 deviceId: payload.target.deviceId,
381 createdAt: payload.createdAt,
382 });
383 }
384 const expiresAt = DateTime.make(payload.expiresAt);
385 if (Option.isNone(expiresAt)) {
386 return new ApnsDeliveryJobExpiresAtInvalid({
387 jobId: payload.jobId,
388 kind: payload.kind,
389 userId: payload.target.userId,
390 deviceId: payload.target.deviceId,
391 expiresAt: payload.expiresAt,
392 });
393 }
394 const createdAtMs = createdAt.value.epochMilliseconds;
395 const expiresAtMs = expiresAt.value.epochMilliseconds;
396 if (expiresAtMs <= createdAtMs) {
397 return new ApnsDeliveryJobTimeWindowInvalid({
398 jobId: payload.jobId,
399 kind: payload.kind,
400 userId: payload.target.userId,
401 deviceId: payload.target.deviceId,
402 createdAt: payload.createdAt,
403 expiresAt: payload.expiresAt,
404 });
405 }
406 if (expiresAtMs - createdAtMs > MAX_JOB_AGE_MS) {
407 return new ApnsDeliveryJobTimeWindowTooLong({
408 jobId: payload.jobId,
409 kind: payload.kind,
410 userId: payload.target.userId,
411 deviceId: payload.target.deviceId,
412 createdAt: payload.createdAt,
413 expiresAt: payload.expiresAt,
414 });
415 }
416 if (expiresAtMs <= input.nowMs) {
417 return new ApnsDeliveryJobExpired({
418 jobId: payload.jobId,
419 kind: payload.kind,
420 userId: payload.target.userId,
421 deviceId: payload.target.deviceId,
422 expiresAt: payload.expiresAt,
423 });
424 }
425 const expected = signatureForPayload({
426 secret: input.secret,
427 payload,
428 });
429 if (!timingSafeEqualBase64Url(input.job.signature, expected)) {
430 return new ApnsDeliveryJobSignatureInvalid({
431 jobId: payload.jobId,
432 kind: payload.kind,
433 userId: payload.target.userId,
434 deviceId: payload.target.deviceId,
435 });
436 }
437 return payload;