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

ApnsClient.test.ts

443 lines15.1 KB

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