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