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

ApnsClient.test.ts

470 lines15.7 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
2import * as NodeCrypto from "node:crypto";
3​
4import { EnvironmentId, ThreadId } from "@t3tools/contracts";
5import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
6import { describe, expect, it } from "@effect/vitest";
7import * as DateTime from "effect/DateTime";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Redacted from "effect/Redacted";
13import * as Schema from "effect/Schema";
14import * as TestClock from "effect/testing/TestClock";
15import * as HttpClient from "effect/http/HttpClient";
16import * as HttpClientError from "effect/http/HttpClientError";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18​
19import type { ApnsCredentials } from "../Config.ts";
20import * as ApnsClient from "./ApnsClient.ts";
21import { sanitizeApnsNotificationPayload } from "./agentActivityPayloads.ts";
22import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
23​
24const isApnsJwtSigningError = Schema.is(ApnsClient.ApnsJwtSigningError);
25const isApnsHttpRequestError = Schema.is(ApnsClient.ApnsHttpRequestError);
26​
27const layerTest = ApnsClient.layer.pipe(
28 Layer.provide(ApnsProviderTokens.layer),
29 Layer.provide(
30 Layer.succeed(
31 HttpClient.HttpClient,
32 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
33 ),
34 ),
35);
36​
37describe("ApnsClient", () => {
38 const now = DateTime.makeUnsafe(0);
39 const state: RelayAgentActivityAggregateState = {
40 title: "T3 Code",
41 subtitle: "Agent work in progress",
42 activeCount: 1,
43 updatedAt: DateTime.formatIso(now),
44 activities: [
45 {
46 environmentId: EnvironmentId.make("env"),
47 threadId: ThreadId.make("thread"),
48 projectTitle: "Project",
49 threadTitle: "Thread",
50 modelTitle: "gpt-5.4",
51 phase: "running" as const,
52 status: "Working",
53 updatedAt: DateTime.formatIso(now),
54 deepLink: "/",
55 },
56 ],
57 };
58​
59 it.effect("requests an update push token when remotely starting a Live Activity", () =>
60 Effect.gen(function* () {
61 const apns = yield* ApnsClient.ApnsClient;
62 const request = apns.makeLiveActivityRequest({
63 event: "start",
64 token: "token",
65 state,
66 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
67 nowIso: DateTime.formatIso(now),
68 });
69​
70 expect(request.priority).toBe("10");
71 expect(request.payload).toMatchObject({
72 aps: {
73 event: "start",
74 "attributes-type": "LiveActivityAttributes",
75 "input-push-token": 1,
76 "content-state": {
77 name: "AgentActivity",
78 },
79 },
80 });
81 }).pipe(Effect.provide(layerTest)),
82 );
83​
84 it.effect("builds a low-priority update payload", () =>
85 Effect.gen(function* () {
86 const apns = yield* ApnsClient.ApnsClient;
87 const request = apns.makeLiveActivityRequest({
88 event: "update",
89 token: "token",
90 state,
91 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
92 nowIso: DateTime.formatIso(now),
93 });
94​
95 expect(request.priority).toBe("5");
96 expect(request.payload).toMatchObject({
97 aps: {
98 event: "update",
99 "content-state": {
100 name: "AgentActivity",
101 },
102 },
103 });
104 }).pipe(Effect.provide(layerTest)),
105 );
106​
107 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
108 Effect.gen(function* () {
109 const apns = yield* ApnsClient.ApnsClient;
110 const request = apns.makeLiveActivityRequest({
111 event: "update",
112 token: "token",
113 state,
114 alert: { title: "Thread", body: "Approval: Project" },
115 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
116 nowIso: DateTime.formatIso(now),
117 });
118​
119 expect(request.priority).toBe("10");
120 expect(request.payload).toMatchObject({
121 aps: {
122 event: "update",
123 alert: {
124 title: "Thread",
125 body: "Approval: Project",
126 sound: "default",
127 },
128 },
129 });
130 }).pipe(Effect.provide(layerTest)),
131 );
132​
133 it.effect("builds an end payload with a dismissal date", () =>
134 Effect.gen(function* () {
135 const apns = yield* ApnsClient.ApnsClient;
136 const request = apns.makeLiveActivityRequest({
137 event: "end",
138 token: "token",
139 state,
140 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
141 nowIso: DateTime.formatIso(now),
142 });
143​
144 expect(request.priority).toBe("10");
145 expect(request.payload).toMatchObject({
146 aps: {
147 event: "end",
148 "dismissal-date": 300,
149 },
150 });
151​
152 const contentless = apns.makeLiveActivityRequest({
153 event: "end",
154 token: "token",
155 state: null,
156 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
157 nowIso: DateTime.formatIso(now),
158 });
159 expect(contentless.payload).toMatchObject({
160 aps: {
161 event: "end",
162 "dismissal-date": 15,
163 },
164 });
165 }).pipe(Effect.provide(layerTest)),
166 );
167​
168 it.effect("puts remote routing metadata only in Expo's body field", () =>
169 Effect.gen(function* () {
170 const apns = yield* ApnsClient.ApnsClient;
171 const request = apns.makePushNotificationRequest({
172 token: "push-token",
173 notification: {
174 title: "Thread",
175 body: "Input: Project",
176 environmentId: "env",
177 threadId: "thread",
178 deepLink: "/threads/env/thread",
179 },
180 });
181​
182 expect(request.priority).toBe("10");
183 expect(request.payload).toEqual({
184 aps: {
185 alert: {
186 title: "Thread",
187 body: "Input: Project",
188 },
189 sound: "default",
190 "thread-id": "env/thread",
191 },
192 body: {
193 environmentId: "env",
194 threadId: "thread",
195 deepLink: "/threads/env/thread",
196 },
197 });
198 }).pipe(Effect.provide(layerTest)),
199 );
200​
201 it.effect("fits long routing metadata and multibyte alerts within the APNs 4096-byte limit", () =>
202 Effect.gen(function* () {
203 const apns = yield* ApnsClient.ApnsClient;
204 const environmentId = "é".repeat(191);
205 const threadId = "t".repeat(512);
206 const notification = sanitizeApnsNotificationPayload({
207 title: "界".repeat(120),
208 body: "界".repeat(120),
209 environmentId,
210 threadId,
211 deepLink: `/threads/${encodeURIComponent(environmentId)}/${threadId}`,
212 });
213 const request = apns.makePushNotificationRequest({ token: "push-token", notification });
214​
215 expect(
216 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
217 ).toBeLessThanOrEqual(4096);
218 expect(request.payload).toMatchObject({
219 body: {
220 environmentId,
221 threadId,
222 deepLink: notification.deepLink,
223 },
224 });
225 }).pipe(Effect.provide(layerTest)),
226 );
227​
228 it.effect("preserves JWT signing context and the crypto cause", () =>
229 Effect.gen(function* () {
230 const apns = yield* ApnsClient.ApnsClient;
231 const request = apns.makePushNotificationRequest({
232 token: "push-token",
233 notification: {
234 title: "Thread",
235 body: "Input: Project",
236 environmentId: "env",
237 threadId: "thread",
238 deepLink: "/threads/env/thread",
239 },
240 });
241 const error = yield* Effect.flip(
242 apns.sendPushNotificationRequest({
243 credentials: {
244 teamId: "team-1",
245 keyId: "key-1",
246 privateKey: Redacted.make("not-a-private-key"),
247 bundleId: "com.t3tools.test",
248 environment: "sandbox",
249 },
250 request,
251 issuedAtUnixSeconds: 123,
252 }),
253 );
254​
255 expect(isApnsJwtSigningError(error)).toBe(true);
256 if (!isApnsJwtSigningError(error)) {
257 return yield* Effect.die("expected APNs JWT signing error");
258 }
259 expect(error).toMatchObject({
260 teamId: "team-1",
261 keyId: "key-1",
262 issuedAtUnixSeconds: 0,
263 cause: expect.any(Error),
264 message: "Failed to sign APNs JWT for key key-1.",
265 });
266 }).pipe(Effect.provide(layerTest)),
267 );
268​
269 it.effect("preserves APNs request context and the HTTP cause", () => {
270 const httpCause = new Error("network unavailable");
271 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
272 namedCurve: "prime256v1",
273 privateKeyEncoding: { type: "pkcs8", format: "pem" },
274 publicKeyEncoding: { type: "spki", format: "pem" },
275 });
276 const credentials = {
277 teamId: "team-1",
278 keyId: "key-1",
279 privateKey: Redacted.make(privateKey),
280 bundleId: "com.t3tools.test",
281 environment: "sandbox",
282 } satisfies ApnsCredentials;
283 const failingHttpClient = HttpClient.make((request) =>
284 Effect.fail(
285 new HttpClientError.HttpClientError({
286 reason: new HttpClientError.TransportError({ request, cause: httpCause }),
287 }),
288 ),
289 );
290 const layer = ApnsClient.layer.pipe(
291 Layer.provide(ApnsProviderTokens.layer),
292 Layer.provide(Layer.succeed(HttpClient.HttpClient, failingHttpClient)),
293 );
294​
295 return Effect.gen(function* () {
296 const apns = yield* ApnsClient.ApnsClient;
297 const request = apns.makePushNotificationRequest({
298 token: "long-push-token",
299 notification: {
300 title: "Thread",
301 body: "Input: Project",
302 environmentId: "env",
303 threadId: "thread",
304 deepLink: "/threads/env/thread",
305 },
306 });
307 const error = yield* Effect.flip(
308 apns.sendPushNotificationRequest({
309 credentials,
310 request,
311 issuedAtUnixSeconds: 123,
312 }),
313 );
314​
315 expect(isApnsHttpRequestError(error)).toBe(true);
316 if (!isApnsHttpRequestError(error)) {
317 return yield* Effect.die("expected APNs HTTP request error");
318 }
319 expect(error).toMatchObject({
320 requestKind: "push-notification",
321 event: null,
322 environment: "sandbox",
323 bundleId: "com.t3tools.test",
324 tokenSuffix: "sh-token",
325 stage: "send",
326 status: null,
327 message: "APNs push-notification request failed during send in sandbox.",
328 });
329 expect(error.cause).toBeInstanceOf(HttpClientError.HttpClientError);
330 expect((error.cause as HttpClientError.HttpClientError).reason).toMatchObject({
331 _tag: "TransportError",
332 cause: httpCause,
333 });
334 }).pipe(Effect.provide(layer));
335 });
336​
337 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
338 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
339 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
340 namedCurve: "prime256v1",
341 privateKeyEncoding: { type: "pkcs8", format: "pem" },
342 publicKeyEncoding: { type: "spki", format: "pem" },
343 });
344 const credentials = {
345 teamId: "team-jwt-cache",
346 keyId: "key-jwt-cache",
347 privateKey: Redacted.make(privateKey),
348 bundleId: "com.t3tools.test",
349 environment: "sandbox",
350 } satisfies ApnsCredentials;
351 const authorizations: Array<string> = [];
352 const capturingHttpClient = HttpClient.make((request) => {
353 authorizations.push(request.headers.authorization ?? "");
354 return Effect.succeed(
355 HttpClientResponse.fromWeb(
356 request,
357 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
358 ),
359 );
360 });
361 const layer = ApnsClient.layer.pipe(
362 Layer.provide(ApnsProviderTokens.layer),
363 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
364 );
365​
366 return Effect.gen(function* () {
367 const apns = yield* ApnsClient.ApnsClient;
368 const request = apns.makePushNotificationRequest({
369 token: "push-token",
370 notification: {
371 title: "Thread",
372 body: "Input: Project",
373 environmentId: "env",
374 threadId: "thread",
375 deepLink: "/threads/env/thread",
376 },
377 });
378 const send = (issuedAtUnixSeconds: number) =>
379 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
380​
381 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
382 yield* send(window + 10);
383 yield* send(window * 2 - 1);
384 yield* send(window * 2);
385​
386 expect(authorizations).toHaveLength(3);
387 // Within the 45-minute window APNs must see the byte-identical token;
388 // refreshing it per push trips TooManyProviderTokenUpdates.
389 expect(authorizations[1]).toBe(authorizations[0]);
390 expect(authorizations[2]).not.toBe(authorizations[0]);
391 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
392 }).pipe(Effect.provide(layer));
393 });
394​
395 it.effect.each(
396 (["live-activity", "push-notification"] as const).flatMap((requestKind) =>
397 (["send", "read-response"] as const).map((stage) => ({ requestKind, stage })),
398 ),
399 )("aborts a stalled $requestKind $stage after ten seconds", ({ requestKind, stage }) =>
400 Effect.gen(function* () {
401 const started = yield* Deferred.make<void>();
402 const signals: AbortSignal[] = [];
403 const stalledHttpClient = HttpClient.make((request, _url, signal) => {
404 signals.push(signal);
405 const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
406 if (stage === "send") return stall;
407 const response = HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
408 Object.defineProperty(response, "text", { value: stall });
409 return Effect.succeed(response);
410 });
411 const layer = ApnsClient.layer.pipe(
412 Layer.provide(Layer.succeed(HttpClient.HttpClient, stalledHttpClient)),
413 Layer.provide(
414 Layer.succeed(ApnsProviderTokens.ApnsProviderTokens, {
415 getJwt: () => Effect.succeed("test-jwt"),
416 }),
417 ),
418 );
419 const apns = yield* ApnsClient.ApnsClient.pipe(Effect.provide(layer));
420 const credentials = {
421 teamId: "team-timeout",
422 keyId: "key-timeout",
423 privateKey: Redacted.make("unused-test-key"),
424 bundleId: "com.t3tools.test",
425 environment: "sandbox",
426 } satisfies ApnsCredentials;
427 const send =
428 requestKind === "live-activity"
429 ? apns.sendLiveActivityRequest({
430 credentials,
431 issuedAtUnixSeconds: 123,
432 request: apns.makeLiveActivityRequest({
433 event: "update",
434 token: "long-push-token",
435 state,
436 nowEpochSeconds: 123,
437 nowIso: DateTime.formatIso(now),
438 }),
439 })
440 : apns.sendPushNotificationRequest({
441 credentials,
442 issuedAtUnixSeconds: 123,
443 request: apns.makePushNotificationRequest({
444 token: "long-push-token",
445 notification: {
446 title: "Thread",
447 body: "Done",
448 environmentId: "env",
449 threadId: "thread",
450 deepLink: "/",
451 },
452 }),
453 });
454 const fiber = yield* send.pipe(Effect.flip, Effect.forkChild);
455 yield* Deferred.await(started);
456 yield* TestClock.adjust("10 seconds");
457 expect(signals[0]?.aborted).toBe(true);
458 const error = yield* Fiber.join(fiber);
459 expect(error).toMatchObject({
460 _tag: "ApnsHttpRequestError",
461 requestKind,
462 event: requestKind === "live-activity" ? "update" : null,
463 stage,
464 status: stage === "read-response" ? 200 : null,
465 tokenSuffix: "sh-token",
466 cause: { _tag: "TimeoutError" },
467 });
468 }),
469 );
470});