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

apnsDeliveryJobs.ts

428 lines13.8 KB

1import {
2 RelayAgentActivityAggregateState,
3 RelayAgentAwarenessPhase,
4} from "@t3tools/contracts/relay";
5import { stableStringify } from "@t3tools/shared/relaySigning";
6import * as Mac from "effect/crypto/Mac";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Base64Url from "effect/encoding/Base64Url";
10import * as Option from "effect/Option";
11import * as Redacted from "effect/Redacted";
12import * as Result from "effect/Result";
13import * as Schema from "effect/Schema";
14​
15const MAX_JOB_AGE_MS = 10 * 60 * 1_000;
16const APNS_DELIVERY_JOB_SIGNING_ALGORITHM = "hmac-sha256";
17​
18const ApnsDeliveryKindSchema = Schema.Literals([
19 "live_activity_update",
20 "live_activity_end",
21 "push_notification",
22]);
23const LiveActivityStartOrUpdateKindSchema = Schema.Literals(["live_activity_update"]);
24const LiveActivityKindSchema = Schema.Literals(["live_activity_update", "live_activity_end"]);
25​
26const ApnsDeliveryJobContext = {
27 jobId: Schema.String,
28 userId: Schema.String,
29 deviceId: Schema.String,
30};
31​
32export const ApnsNotificationPayload = Schema.Struct({
33 title: Schema.String,
34 body: Schema.String,
35 environmentId: Schema.String,
36 threadId: Schema.String,
37 deepLink: Schema.String,
38 phase: Schema.optional(RelayAgentAwarenessPhase),
39 updatedAt: Schema.optional(Schema.String),
40});
41export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
42​
43export const ApnsLiveActivityAlert = Schema.Struct({
44 title: Schema.String,
45 body: Schema.String,
46});
47export type ApnsLiveActivityAlert = typeof ApnsLiveActivityAlert.Type;
48​
49export const ApnsDeliveryJobPayload = Schema.Struct({
50 version: Schema.Literal(1),
51 jobId: Schema.String,
52 kind: ApnsDeliveryKindSchema,
53 target: Schema.Struct({
54 userId: Schema.String,
55 deviceId: Schema.String,
56 token: Schema.String,
57 bundleId: Schema.optional(Schema.NullOr(Schema.String)),
58 apsEnvironment: Schema.optional(Schema.NullOr(Schema.Literals(["sandbox", "production"]))),
59 }),
60 aggregate: Schema.NullOr(RelayAgentActivityAggregateState),
61 notification: Schema.NullOr(ApnsNotificationPayload),
62 alert: Schema.optional(Schema.NullOr(ApnsLiveActivityAlert)),
63 createdAt: Schema.String,
64 expiresAt: Schema.String,
65});
66export type ApnsDeliveryJobPayload = typeof ApnsDeliveryJobPayload.Type;
67​
68export const SignedApnsDeliveryJob = Schema.Struct({
69 algorithm: Schema.Literal(APNS_DELIVERY_JOB_SIGNING_ALGORITHM),
70 payload: ApnsDeliveryJobPayload,
71 signature: Schema.String,
72});
73export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
74​
75export class ApnsDeliveryJobQueuePayloadInvalid extends Schema.TaggedError<ApnsDeliveryJobQueuePayloadInvalid>()(
76 "ApnsDeliveryJobQueuePayloadInvalid",
77 {
78 receivedType: Schema.String,
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 return `Invalid APNs delivery queue job with ${this.receivedType} payload.`;
84 }
86​
87export class ApnsDeliveryJobLiveActivityAggregateMissing extends Schema.TaggedError<ApnsDeliveryJobLiveActivityAggregateMissing>()(
88 "ApnsDeliveryJobLiveActivityAggregateMissing",
89 {
90 ...ApnsDeliveryJobContext,
91 kind: LiveActivityStartOrUpdateKindSchema,
92 },
93) {
94 override get message(): string {
95 return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} requires an aggregate.`;
96 }
98​
99export class ApnsDeliveryJobLiveActivityNotificationUnexpected extends Schema.TaggedError<ApnsDeliveryJobLiveActivityNotificationUnexpected>()(
100 "ApnsDeliveryJobLiveActivityNotificationUnexpected",
101 {
102 ...ApnsDeliveryJobContext,
103 kind: LiveActivityKindSchema,
104 },
105) {
106 override get message(): string {
107 return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} must not carry a push notification payload.`;
108 }
110​
111export class ApnsDeliveryJobPushNotificationMissing extends Schema.TaggedError<ApnsDeliveryJobPushNotificationMissing>()(
112 "ApnsDeliveryJobPushNotificationMissing",
113 ApnsDeliveryJobContext,
114) {
115 override get message(): string {
116 return `APNs push notification job ${this.jobId} requires a notification payload.`;
117 }
119​
120export class ApnsDeliveryJobPushNotificationAggregateUnexpected extends Schema.TaggedError<ApnsDeliveryJobPushNotificationAggregateUnexpected>()(
121 "ApnsDeliveryJobPushNotificationAggregateUnexpected",
122 ApnsDeliveryJobContext,
123) {
124 override get message(): string {
125 return `APNs push notification job ${this.jobId} must not carry aggregate state.`;
126 }
128​
129export class ApnsDeliveryJobCreatedAtInvalid extends Schema.TaggedError<ApnsDeliveryJobCreatedAtInvalid>()(
130 "ApnsDeliveryJobCreatedAtInvalid",
131 {
132 ...ApnsDeliveryJobContext,
133 kind: ApnsDeliveryKindSchema,
134 createdAt: Schema.String,
135 },
136) {
137 override get message(): string {
138 return `APNs delivery job ${this.jobId} has invalid creation time ${this.createdAt}.`;
139 }
141​
142export class ApnsDeliveryJobExpiresAtInvalid extends Schema.TaggedError<ApnsDeliveryJobExpiresAtInvalid>()(
143 "ApnsDeliveryJobExpiresAtInvalid",
144 {
145 ...ApnsDeliveryJobContext,
146 kind: ApnsDeliveryKindSchema,
147 expiresAt: Schema.String,
148 },
149) {
150 override get message(): string {
151 return `APNs delivery job ${this.jobId} has invalid expiry ${this.expiresAt}.`;
152 }
154​
155export class ApnsDeliveryJobTimeWindowInvalid extends Schema.TaggedError<ApnsDeliveryJobTimeWindowInvalid>()(
156 "ApnsDeliveryJobTimeWindowInvalid",
157 {
158 ...ApnsDeliveryJobContext,
159 kind: ApnsDeliveryKindSchema,
160 createdAt: Schema.String,
161 expiresAt: Schema.String,
162 },
163) {
164 override get message(): string {
165 return `APNs delivery job ${this.jobId} has invalid time window ${this.createdAt} to ${this.expiresAt}.`;
166 }
168​
169export class ApnsDeliveryJobTimeWindowTooLong extends Schema.TaggedError<ApnsDeliveryJobTimeWindowTooLong>()(
170 "ApnsDeliveryJobTimeWindowTooLong",
171 {
172 ...ApnsDeliveryJobContext,
173 kind: ApnsDeliveryKindSchema,
174 createdAt: Schema.String,
175 expiresAt: Schema.String,
176 },
177) {
178 override get message(): string {
179 return `APNs delivery job ${this.jobId} time window ${this.createdAt} to ${this.expiresAt} is too long.`;
180 }
182​
183export class ApnsDeliveryJobSignatureInvalid extends Schema.TaggedError<ApnsDeliveryJobSignatureInvalid>()(
184 "ApnsDeliveryJobSignatureInvalid",
185 {
186 ...ApnsDeliveryJobContext,
187 kind: ApnsDeliveryKindSchema,
188 },
189) {
190 override get message(): string {
191 return `Invalid signature for APNs delivery job ${this.jobId}.`;
192 }
194​
195export const ApnsDeliveryJobInvalid = Schema.Union([
196 ApnsDeliveryJobQueuePayloadInvalid,
197 ApnsDeliveryJobLiveActivityAggregateMissing,
198 ApnsDeliveryJobLiveActivityNotificationUnexpected,
199 ApnsDeliveryJobPushNotificationMissing,
200 ApnsDeliveryJobPushNotificationAggregateUnexpected,
201 ApnsDeliveryJobCreatedAtInvalid,
202 ApnsDeliveryJobExpiresAtInvalid,
203 ApnsDeliveryJobTimeWindowInvalid,
204 ApnsDeliveryJobTimeWindowTooLong,
205 ApnsDeliveryJobSignatureInvalid,
206]);
207export type ApnsDeliveryJobInvalid = typeof ApnsDeliveryJobInvalid.Type;
208​
209export class ApnsDeliveryJobExpired extends Schema.TaggedError<ApnsDeliveryJobExpired>()(
210 "ApnsDeliveryJobExpired",
211 {
212 ...ApnsDeliveryJobContext,
213 kind: ApnsDeliveryKindSchema,
214 expiresAt: Schema.String,
215 },
216) {
217 override get message(): string {
218 return `APNs delivery job ${this.jobId} expired at ${this.expiresAt}.`;
219 }
221​
222export const ApnsDeliveryJobVerificationError = Schema.Union([
223 ApnsDeliveryJobInvalid,
224 ApnsDeliveryJobExpired,
225]);
226export type ApnsDeliveryJobVerificationError = typeof ApnsDeliveryJobVerificationError.Type;
227​
228export function makeApnsDeliveryJobPayload(input: {
229 readonly kind: ApnsDeliveryJobPayload["kind"];
230 readonly userId: string;
231 readonly deviceId: string;
232 readonly token: string;
233 readonly bundleId?: string | null | undefined;
234 readonly apsEnvironment?: "sandbox" | "production" | null | undefined;
235 readonly aggregate: ApnsDeliveryJobPayload["aggregate"];
236 readonly notification?: ApnsNotificationPayload | null;
237 readonly alert?: ApnsLiveActivityAlert | null | undefined;
238 readonly createdAt: string;
239 readonly expiresAt: string;
240 readonly jobId: string;
241}): ApnsDeliveryJobPayload {
242 return {
243 version: 1,
244 jobId: input.jobId,
245 kind: input.kind,
246 target: {
247 userId: input.userId,
248 deviceId: input.deviceId,
249 token: input.token,
250 ...(input.bundleId ? { bundleId: input.bundleId } : {}),
251 ...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),
252 },
253 aggregate: input.aggregate,
254 notification: input.notification ?? null,
255 // Omit absent fields to preserve signatures from older relay builds.
256 ...(input.alert ? { alert: input.alert } : {}),
257 createdAt: input.createdAt,
258 expiresAt: input.expiresAt,
259 };
261​
262export function expiresAtForJob(createdAtMs: number): string {
263 return DateTime.formatIso(Option.getOrThrow(DateTime.make(createdAtMs + MAX_JOB_AGE_MS)));
265​
266function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobInvalid | null {
267 switch (payload.kind) {
268 case "live_activity_update":
269 if (payload.aggregate === null) {
270 return new ApnsDeliveryJobLiveActivityAggregateMissing({
271 jobId: payload.jobId,
272 kind: payload.kind,
273 userId: payload.target.userId,
274 deviceId: payload.target.deviceId,
275 });
276 }
277 if (payload.notification !== null) {
278 return new ApnsDeliveryJobLiveActivityNotificationUnexpected({
279 jobId: payload.jobId,
280 kind: payload.kind,
281 userId: payload.target.userId,
282 deviceId: payload.target.deviceId,
283 });
284 }
285 return null;
286 case "live_activity_end":
287 if (payload.notification !== null) {
288 return new ApnsDeliveryJobLiveActivityNotificationUnexpected({
289 jobId: payload.jobId,
290 kind: payload.kind,
291 userId: payload.target.userId,
292 deviceId: payload.target.deviceId,
293 });
294 }
295 return null;
296 case "push_notification":
297 if (payload.notification === null) {
298 return new ApnsDeliveryJobPushNotificationMissing({
299 jobId: payload.jobId,
300 userId: payload.target.userId,
301 deviceId: payload.target.deviceId,
302 });
303 }
304 if (payload.aggregate !== null) {
305 return new ApnsDeliveryJobPushNotificationAggregateUnexpected({
306 jobId: payload.jobId,
307 userId: payload.target.userId,
308 deviceId: payload.target.deviceId,
309 });
310 }
311 return null;
312 }
314​
315const signingKey = (secret: Redacted.Redacted<string>) =>
316 Mac.key(Mac.hmacSha256, new TextEncoder().encode(Redacted.value(secret)));
317​
318const payloadBytes = (payload: ApnsDeliveryJobPayload) =>
319 new TextEncoder().encode(stableStringify(payload));
320​
321export const signApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.sign")(function* (input: {
322 readonly secret: Redacted.Redacted<string>;
323 readonly payload: ApnsDeliveryJobPayload;
324}) {
325 const mac = yield* Mac.Mac;
326 const signature = yield* signingKey(input.secret).pipe(
327 Effect.flatMap((key) => mac.sign(key, payloadBytes(input.payload))),
328 Effect.orDie,
329 );
330 return {
331 algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM,
332 payload: input.payload,
333 signature: Base64Url.encode(signature),
334 } satisfies SignedApnsDeliveryJob;
335});
336​
337export const verifySignedApnsDeliveryJob = Effect.fn("relay.apns_delivery_jobs.verify")(
338 function* (input: {
339 readonly secret: Redacted.Redacted<string>;
340 readonly job: SignedApnsDeliveryJob;
341 readonly nowMs: number;
342 }) {
343 const payload = input.job.payload;
344 const invalid = validateSignedJobWindow(payload, input.nowMs);
345 if (invalid !== null) {
346 return yield* invalid;
347 }
348 const tag = Base64Url.decode(input.job.signature);
349 const mac = yield* Mac.Mac;
350 const verified =
351 Result.isSuccess(tag) &&
352 (yield* signingKey(input.secret).pipe(
353 Effect.flatMap((key) => mac.verify(key, tag.success, payloadBytes(payload))),
354 Effect.orDie,
355 ));
356 if (!verified) {
357 return yield* new ApnsDeliveryJobSignatureInvalid({
358 jobId: payload.jobId,
359 kind: payload.kind,
360 userId: payload.target.userId,
361 deviceId: payload.target.deviceId,
362 });
363 }
364 return payload;
365 },
366);
367​
368function validateSignedJobWindow(
369 payload: ApnsDeliveryJobPayload,
370 nowMs: number,
371): ApnsDeliveryJobVerificationError | null {
372 const invalidPayload = validatePayloadShape(payload);
373 if (invalidPayload !== null) {
374 return invalidPayload;
375 }
376 const createdAt = DateTime.make(payload.createdAt);
377 if (Option.isNone(createdAt)) {
378 return new ApnsDeliveryJobCreatedAtInvalid({
379 jobId: payload.jobId,
380 kind: payload.kind,
381 userId: payload.target.userId,
382 deviceId: payload.target.deviceId,
383 createdAt: payload.createdAt,
384 });
385 }
386 const expiresAt = DateTime.make(payload.expiresAt);
387 if (Option.isNone(expiresAt)) {
388 return new ApnsDeliveryJobExpiresAtInvalid({
389 jobId: payload.jobId,
390 kind: payload.kind,
391 userId: payload.target.userId,
392 deviceId: payload.target.deviceId,
393 expiresAt: payload.expiresAt,
394 });
395 }
396 const createdAtMs = createdAt.value.epochMilliseconds;
397 const expiresAtMs = expiresAt.value.epochMilliseconds;
398 if (expiresAtMs <= createdAtMs) {
399 return new ApnsDeliveryJobTimeWindowInvalid({
400 jobId: payload.jobId,
401 kind: payload.kind,
402 userId: payload.target.userId,
403 deviceId: payload.target.deviceId,
404 createdAt: payload.createdAt,
405 expiresAt: payload.expiresAt,
406 });
407 }
408 if (expiresAtMs - createdAtMs > MAX_JOB_AGE_MS) {
409 return new ApnsDeliveryJobTimeWindowTooLong({
410 jobId: payload.jobId,
411 kind: payload.kind,
412 userId: payload.target.userId,
413 deviceId: payload.target.deviceId,
414 createdAt: payload.createdAt,
415 expiresAt: payload.expiresAt,
416 });
417 }
418 if (expiresAtMs <= nowMs) {
419 return new ApnsDeliveryJobExpired({
420 jobId: payload.jobId,
421 kind: payload.kind,
422 userId: payload.target.userId,
423 deviceId: payload.target.deviceId,
424 expiresAt: payload.expiresAt,
425 });
426 }
427 return null;