Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as Headers from "effect/unstable/http/Headers";
12import * as HttpClient from "effect/unstable/http/HttpClient";
13import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
14import { ApnsEnvironment as ApnsEnvironmentSchema, type ApnsCredentials } from "../Config.ts";
15import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
16
17const LIVE_ACTIVITY_NAME = "AgentActivity";
18const STALE_AFTER_SECONDS = 2 * 60;
19const DISMISS_AFTER_SECONDS = 5 * 60;
20
21const ApnsLiveActivityEventSchema = Schema.Literals(["start", "update", "end"]);
22export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
23
24const ApnsRequestKindSchema = Schema.Literals(["live-activity", "push-notification"]);
25
26interface ApnsLiveActivityRequest {
27 readonly token: string;
28 readonly event: ApnsLiveActivityEvent;
29 readonly priority: "5" | "10";
30 readonly payload: unknown;
31}
32
33interface ApnsPushNotificationRequest {
34 readonly token: string;
35 readonly priority: "10";
36 readonly payload: unknown;
37}
38
39export interface ApnsDeliveryResult {
40 readonly ok: boolean;
41 readonly status: number;
42 readonly reason?: string;
43 readonly apnsId: string | null;
44}
45
46export class ApnsJwtEncodingError extends Schema.TaggedErrorClass<ApnsJwtEncodingError>()(
47 "ApnsJwtEncodingError",
48 {
49 component: Schema.Literals(["header", "payload"]),
50 teamId: Schema.String,
51 keyId: Schema.String,
52 issuedAtUnixSeconds: Schema.Number,
53 cause: Schema.Defect(),
54 },
55) {
56 override get message(): string {
57 return `Failed to encode APNs JWT ${this.component} for key ${this.keyId}.`;
58 }
59}
60
61export class ApnsJwtSigningError extends Schema.TaggedErrorClass<ApnsJwtSigningError>()(
62 "ApnsJwtSigningError",
63 {
64 teamId: Schema.String,
65 keyId: Schema.String,
66 issuedAtUnixSeconds: Schema.Number,
67 cause: Schema.Defect(),
68 },
69) {
70 override get message(): string {
71 return `Failed to sign APNs JWT for key ${this.keyId}.`;
72 }
73}
74
75export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(
76 "ApnsHttpRequestError",
77 {
78 requestKind: ApnsRequestKindSchema,
79 event: Schema.NullOr(ApnsLiveActivityEventSchema),
80 environment: ApnsEnvironmentSchema,
81 bundleId: Schema.String,
82 tokenSuffix: Schema.String,
83 stage: Schema.Literals(["send", "read-response"]),
84 status: Schema.NullOr(Schema.Number),
85 cause: Schema.Defect(),
86 },
87) {
88 override get message(): string {
89 return `APNs ${this.requestKind} request failed during ${this.stage} in ${this.environment}.`;
90 }
91}
92
93export const ApnsError = Schema.Union([
94 ApnsJwtEncodingError,
95 ApnsJwtSigningError,
96 ApnsHttpRequestError,
97]);
98export type ApnsError = typeof ApnsError.Type;
99
100const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
101 Schema.fromJsonString(
102 Schema.Struct({
103 reason: Schema.optional(Schema.String),
104 }),
105 ),
106);
107const encodeApnsJwtHeaderJson = Schema.encodeEffect(
108 Schema.fromJsonString(
109 Schema.Struct({
110 alg: Schema.Literal("ES256"),
111 kid: Schema.String,
112 }),
113 ),
114);
115const encodeApnsJwtPayloadJson = Schema.encodeEffect(
116 Schema.fromJsonString(
117 Schema.Struct({
118 iss: Schema.String,
119 iat: Schema.Number,
120 }),
121 ),
122);
123
124const makeApnsJwt = Effect.fn("relay.apns.make_jwt")(function* (input: {
125 readonly teamId: ApnsCredentials["teamId"];
126 readonly keyId: ApnsCredentials["keyId"];
127 readonly privateKey: ApnsCredentials["privateKey"];
128 readonly issuedAtUnixSeconds: number;
129}) {
130 const headerJson = yield* encodeApnsJwtHeaderJson({ alg: "ES256", kid: input.keyId }).pipe(
131 Effect.mapError(
132 (cause) =>
133 new ApnsJwtEncodingError({
134 component: "header",
135 teamId: input.teamId,
136 keyId: input.keyId,
137 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
138 cause,
139 }),
140 ),
141 );
142 const payloadJson = yield* encodeApnsJwtPayloadJson({
143 iss: input.teamId,
144 iat: input.issuedAtUnixSeconds,
145 }).pipe(
146 Effect.mapError(
147 (cause) =>
148 new ApnsJwtEncodingError({
149 component: "payload",
150 teamId: input.teamId,
151 keyId: input.keyId,
152 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
153 cause,
154 }),
155 ),
156 );
157
158 const privateKey = Redacted.value(input.privateKey);
159 const header = Encoding.encodeBase64Url(headerJson);
160 const payload = Encoding.encodeBase64Url(payloadJson);
161 const signingInput = `${header}.${payload}`;
162
163 return yield* Effect.try({
164 try: () => {
165 const signature = NodeCrypto.createSign("sha256")
166 .update(signingInput)
167 .sign({
168 key: privateKey.replace(/\\n/g, "\n"),
169 dsaEncoding: "ieee-p1363",
170 });
171 return `${signingInput}.${Encoding.encodeBase64Url(signature)}`;
172 },
173 catch: (cause) =>
174 new ApnsJwtSigningError({
175 teamId: input.teamId,
176 keyId: input.keyId,
177 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
178 cause,
179 }),
180 });
181});
182
183function contentState(state: RelayAgentActivityAggregateState) {
184 return {
185 name: LIVE_ACTIVITY_NAME,
186 props: JSON.stringify(state),
187 };
188}
189
190interface LiveActivityRequestBase {
191 readonly token: string;
192 readonly nowEpochSeconds: number;
193 readonly nowIso: string;
194}
195
196type MakeLiveActivityRequestInput =
197 | (LiveActivityRequestBase & {
198 readonly event: "end";
199 readonly state: RelayAgentActivityAggregateState | null;
200 })
201 | (LiveActivityRequestBase & {
202 readonly event: "start" | "update";
203 readonly state: RelayAgentActivityAggregateState;
204 });
205
206function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
207 const timestamp = input.nowEpochSeconds;
208 if (input.event === "end") {
209 return {
210 token: input.token,
211 event: input.event,
212 priority: "10",
213 payload: {
214 aps: {
215 timestamp,
216 event: "end",
217 ...(input.state ? { "content-state": contentState(input.state) } : {}),
218 "dismissal-date": timestamp + DISMISS_AFTER_SECONDS,
219 },
220 },
221 };
222 }
223
224 const state = input.state;
225 return {
226 token: input.token,
227 event: input.event,
228 priority: input.event === "update" ? "5" : "10",
229 payload: {
230 aps: {
231 timestamp,
232 event: input.event,
233 ...(input.event === "start"
234 ? {
235 "attributes-type": "LiveActivityAttributes",
236 attributes: {},
237 "input-push-token": 1,
238 alert: {
239 title: state.title,
240 body: state.subtitle,
241 },
242 }
243 : {}),
244 "content-state": contentState(state),
245 "stale-date": timestamp + STALE_AFTER_SECONDS,
246 },
247 },
248 };
249}
250
251function makePushNotificationRequest(input: {
252 readonly token: string;
253 readonly notification: ApnsNotificationPayload;
254}): ApnsPushNotificationRequest {
255 return {
256 token: input.token,
257 priority: "10",
258 payload: {
259 aps: {
260 alert: {
261 title: input.notification.title,
262 body: input.notification.body,
263 },
264 sound: "default",
265 },
266 environmentId: input.notification.environmentId,
267 threadId: input.notification.threadId,
268 deepLink: input.notification.deepLink,
269 },
270 };
271}
272
273function apnsReasonFromBody(body: string): string | undefined {
274 if (body.trim().length === 0) {
275 return undefined;
276 }
277 return Option.match(decodeApnsErrorResponseJson(body), {
278 onNone: () => body,
279 onSome: (parsed) => parsed.reason ?? body,
280 });
281}
282
283export class ApnsClient extends Context.Service<
284 ApnsClient,
285 {
286 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
287 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
288 readonly sendLiveActivityRequest: (input: {
289 readonly credentials: ApnsCredentials;
290 readonly request: ApnsLiveActivityRequest;
291 readonly issuedAtUnixSeconds: number;
292 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
293 readonly sendPushNotificationRequest: (input: {
294 readonly credentials: ApnsCredentials;
295 readonly request: ApnsPushNotificationRequest;
296 readonly issuedAtUnixSeconds: number;
297 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
298 }
299>()("t3code-relay/agentActivity/ApnsClient") {}
300
301export const make = Effect.gen(function* () {
302 const httpClient = yield* HttpClient.HttpClient;
303
304 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
305 "relay.apns.send_live_activity_request",
306 )(function* (input) {
307 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
308 const jwt = yield* makeApnsJwt({
309 ...input.credentials,
310 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
311 });
312 const host =
313 input.credentials.environment === "production"
314 ? "https://api.push.apple.com"
315 : "https://api.sandbox.push.apple.com";
316 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
317 HttpClientRequest.setHeaders({
318 authorization: `bearer ${jwt}`,
319 "apns-priority": input.request.priority,
320 "apns-push-type": "liveactivity",
321 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
322 }),
323 HttpClientRequest.bodyJson(input.request.payload),
324 Effect.flatMap(httpClient.execute),
325 Effect.mapError(
326 (cause) =>
327 new ApnsHttpRequestError({
328 requestKind: "live-activity",
329 event: input.request.event,
330 environment: input.credentials.environment,
331 bundleId: input.credentials.bundleId,
332 tokenSuffix: input.request.token.slice(-8),
333 stage: "send",
334 status: null,
335 cause,
336 }),
337 ),
338 );
339 const responseText = yield* response.text.pipe(
340 Effect.mapError(
341 (cause) =>
342 new ApnsHttpRequestError({
343 requestKind: "live-activity",
344 event: input.request.event,
345 environment: input.credentials.environment,
346 bundleId: input.credentials.bundleId,
347 tokenSuffix: input.request.token.slice(-8),
348 stage: "read-response",
349 status: response.status,
350 cause,
351 }),
352 ),
353 );
354 const reason = apnsReasonFromBody(responseText);
355 return {
356 ok: response.status >= 200 && response.status < 300,
357 status: response.status,
358 ...(reason === undefined ? {} : { reason }),
359 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
360 };
361 });
362
363 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
364 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
365 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
366 const jwt = yield* makeApnsJwt({
367 ...input.credentials,
368 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
369 });
370 const host =
371 input.credentials.environment === "production"
372 ? "https://api.push.apple.com"
373 : "https://api.sandbox.push.apple.com";
374 const response = yield* HttpClientRequest.post(
375 `${host}/3/device/${input.request.token}`,
376 ).pipe(
377 HttpClientRequest.setHeaders({
378 authorization: `bearer ${jwt}`,
379 "apns-priority": input.request.priority,
380 "apns-push-type": "alert",
381 "apns-topic": input.credentials.bundleId,
382 }),
383 HttpClientRequest.bodyJson(input.request.payload),
384 Effect.flatMap(httpClient.execute),
385 Effect.mapError(
386 (cause) =>
387 new ApnsHttpRequestError({
388 requestKind: "push-notification",
389 event: null,
390 environment: input.credentials.environment,
391 bundleId: input.credentials.bundleId,
392 tokenSuffix: input.request.token.slice(-8),
393 stage: "send",
394 status: null,
395 cause,
396 }),
397 ),
398 );
399 const responseText = yield* response.text.pipe(
400 Effect.mapError(
401 (cause) =>
402 new ApnsHttpRequestError({
403 requestKind: "push-notification",
404 event: null,
405 environment: input.credentials.environment,
406 bundleId: input.credentials.bundleId,
407 tokenSuffix: input.request.token.slice(-8),
408 stage: "read-response",
409 status: response.status,
410 cause,
411 }),
412 ),
413 );
414 const reason = apnsReasonFromBody(responseText);
415 return {
416 ok: response.status >= 200 && response.status < 300,
417 status: response.status,
418 ...(reason === undefined ? {} : { reason }),
419 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
420 };
421 });
422
423 return ApnsClient.of({
424 makeLiveActivityRequest,
425 makePushNotificationRequest,
426 sendLiveActivityRequest,
427 sendPushNotificationRequest,
428 });
429});
430
431export const layer = Layer.effect(ApnsClient, make);