Open History to see the last commit
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 Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as HttpClient from "effect/unstable/http/HttpClient";
12import * as HttpClientError from "effect/unstable/http/HttpClientError";
13import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
14
15import type { ApnsCredentials } from "../Config.ts";
16import * as ApnsClient from "./ApnsClient.ts";
17import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
18
19const isApnsJwtSigningError = Schema.is(ApnsClient.ApnsJwtSigningError);
20const isApnsHttpRequestError = Schema.is(ApnsClient.ApnsHttpRequestError);
21
22const TestLayer = ApnsClient.layer.pipe(
23 Layer.provide(ApnsProviderTokens.layer),
24 Layer.provide(
25 Layer.succeed(
26 HttpClient.HttpClient,
27 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
28 ),
29 ),
30);
31
32describe("ApnsClient", () => {
33 const now = DateTime.makeUnsafe(0);
34 const state: RelayAgentActivityAggregateState = {
35 title: "T3 Code",
36 subtitle: "Agent work in progress",
37 activeCount: 1,
38 updatedAt: DateTime.formatIso(now),
39 activities: [
40 {
41 environmentId: EnvironmentId.make("env"),
42 threadId: ThreadId.make("thread"),
43 projectTitle: "Project",
44 threadTitle: "Thread",
45 modelTitle: "gpt-5.4",
46 phase: "running" as const,
47 status: "Working",
48 updatedAt: DateTime.formatIso(now),
49 deepLink: "/",
50 },
51 ],
52 };
53
54 it.effect("requests an update push token when remotely starting a Live Activity", () =>
55 Effect.gen(function* () {
56 const apns = yield* ApnsClient.ApnsClient;
57 const request = apns.makeLiveActivityRequest({
58 event: "start",
59 token: "token",
60 state,
61 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
62 nowIso: DateTime.formatIso(now),
63 });
64
65 expect(request.priority).toBe("10");
66 expect(request.payload).toMatchObject({
67 aps: {
68 event: "start",
69 "attributes-type": "LiveActivityAttributes",
70 "input-push-token": 1,
71 "content-state": {
72 name: "AgentActivity",
73 },
74 },
75 });
76 }).pipe(Effect.provide(TestLayer)),
77 );
78
79 it.effect("builds a low-priority update payload", () =>
80 Effect.gen(function* () {
81 const apns = yield* ApnsClient.ApnsClient;
82 const request = apns.makeLiveActivityRequest({
83 event: "update",
84 token: "token",
85 state,
86 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
87 nowIso: DateTime.formatIso(now),
88 });
89
90 expect(request.priority).toBe("5");
91 expect(request.payload).toMatchObject({
92 aps: {
93 event: "update",
94 "content-state": {
95 name: "AgentActivity",
96 },
97 },
98 });
99 }).pipe(Effect.provide(TestLayer)),
100 );
101
102 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
103 Effect.gen(function* () {
104 const apns = yield* ApnsClient.ApnsClient;
105 const request = apns.makeLiveActivityRequest({
106 event: "update",
107 token: "token",
108 state,
109 alert: { title: "Thread", body: "Approval: Project" },
110 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
111 nowIso: DateTime.formatIso(now),
112 });
113
114 expect(request.priority).toBe("10");
115 expect(request.payload).toMatchObject({
116 aps: {
117 event: "update",
118 alert: {
119 title: "Thread",
120 body: "Approval: Project",
121 sound: "default",
122 },
123 },
124 });
125 }).pipe(Effect.provide(TestLayer)),
126 );
127
128 it.effect("builds an end payload with a dismissal date", () =>
129 Effect.gen(function* () {
130 const apns = yield* ApnsClient.ApnsClient;
131 const request = apns.makeLiveActivityRequest({
132 event: "end",
133 token: "token",
134 state,
135 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
136 nowIso: DateTime.formatIso(now),
137 });
138
139 expect(request.priority).toBe("10");
140 expect(request.payload).toMatchObject({
141 aps: {
142 event: "end",
143 "dismissal-date": 300,
144 },
145 });
146
147 // Without final content the card would freeze on its previous state;
148 // contentless ends dismiss quickly instead.
149 const contentless = apns.makeLiveActivityRequest({
150 event: "end",
151 token: "token",
152 state: null,
153 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
154 nowIso: DateTime.formatIso(now),
155 });
156 expect(contentless.payload).toMatchObject({
157 aps: {
158 event: "end",
159 "dismissal-date": 15,
160 },
161 });
162 }).pipe(Effect.provide(TestLayer)),
163 );
164
165 it.effect("builds a standard APNs alert payload with routing metadata", () =>
166 Effect.gen(function* () {
167 const apns = yield* ApnsClient.ApnsClient;
168 const request = apns.makePushNotificationRequest({
169 token: "push-token",
170 notification: {
171 title: "Thread",
172 body: "Input: Project",
173 environmentId: "env",
174 threadId: "thread",
175 deepLink: "/threads/env/thread",
176 },
177 });
178
179 expect(request.priority).toBe("10");
180 expect(request.payload).toMatchObject({
181 aps: {
182 alert: {
183 title: "Thread",
184 body: "Input: Project",
185 },
186 sound: "default",
187 },
188 environmentId: "env",
189 threadId: "thread",
190 deepLink: "/threads/env/thread",
191 });
192 }).pipe(Effect.provide(TestLayer)),
193 );
194
195 it.effect("preserves JWT signing context and the crypto cause", () =>
196 Effect.gen(function* () {
197 const apns = yield* ApnsClient.ApnsClient;
198 const request = apns.makePushNotificationRequest({
199 token: "push-token",
200 notification: {
201 title: "Thread",
202 body: "Input: Project",
203 environmentId: "env",
204 threadId: "thread",
205 deepLink: "/threads/env/thread",
206 },
207 });
208 const error = yield* Effect.flip(
209 apns.sendPushNotificationRequest({
210 credentials: {
211 teamId: "team-1",
212 keyId: "key-1",
213 privateKey: Redacted.make("not-a-private-key"),
214 bundleId: "com.t3tools.test",
215 environment: "sandbox",
216 },
217 request,
218 issuedAtUnixSeconds: 123,
219 }),
220 );
221
222 expect(isApnsJwtSigningError(error)).toBe(true);
223 if (!isApnsJwtSigningError(error)) {
224 return yield* Effect.die("expected APNs JWT signing error");
225 }
226 expect(error).toMatchObject({
227 teamId: "team-1",
228 keyId: "key-1",
229 // The provider-token service quantizes iat to the reuse window, so
230 // the signing context carries the window start rather than the raw
231 // request time.
232 issuedAtUnixSeconds: 0,
233 cause: expect.any(Error),
234 message: "Failed to sign APNs JWT for key key-1.",
235 });
236 }).pipe(Effect.provide(TestLayer)),
237 );
238
239 it.effect("preserves APNs request context and the HTTP cause", () => {
240 const httpCause = new Error("network unavailable");
241 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
242 namedCurve: "prime256v1",
243 privateKeyEncoding: { type: "pkcs8", format: "pem" },
244 publicKeyEncoding: { type: "spki", format: "pem" },
245 });
246 const credentials = {
247 teamId: "team-1",
248 keyId: "key-1",
249 privateKey: Redacted.make(privateKey),
250 bundleId: "com.t3tools.test",
251 environment: "sandbox",
252 } satisfies ApnsCredentials;
253 const failingHttpClient = HttpClient.make((request) =>
254 Effect.fail(
255 new HttpClientError.HttpClientError({
256 reason: new HttpClientError.TransportError({ request, cause: httpCause }),
257 }),
258 ),
259 );
260 const layer = ApnsClient.layer.pipe(
261 Layer.provide(ApnsProviderTokens.layer),
262 Layer.provide(Layer.succeed(HttpClient.HttpClient, failingHttpClient)),
263 );
264
265 return Effect.gen(function* () {
266 const apns = yield* ApnsClient.ApnsClient;
267 const request = apns.makePushNotificationRequest({
268 token: "long-push-token",
269 notification: {
270 title: "Thread",
271 body: "Input: Project",
272 environmentId: "env",
273 threadId: "thread",
274 deepLink: "/threads/env/thread",
275 },
276 });
277 const error = yield* Effect.flip(
278 apns.sendPushNotificationRequest({
279 credentials,
280 request,
281 issuedAtUnixSeconds: 123,
282 }),
283 );
284
285 expect(isApnsHttpRequestError(error)).toBe(true);
286 if (!isApnsHttpRequestError(error)) {
287 return yield* Effect.die("expected APNs HTTP request error");
288 }
289 expect(error).toMatchObject({
290 requestKind: "push-notification",
291 event: null,
292 environment: "sandbox",
293 bundleId: "com.t3tools.test",
294 tokenSuffix: "sh-token",
295 stage: "send",
296 status: null,
297 message: "APNs push-notification request failed during send in sandbox.",
298 });
299 expect(error.cause).toBeInstanceOf(HttpClientError.HttpClientError);
300 expect((error.cause as HttpClientError.HttpClientError).reason).toMatchObject({
301 _tag: "TransportError",
302 cause: httpCause,
303 });
304 }).pipe(Effect.provide(layer));
305 });
306
307 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
308 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
309 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
310 namedCurve: "prime256v1",
311 privateKeyEncoding: { type: "pkcs8", format: "pem" },
312 publicKeyEncoding: { type: "spki", format: "pem" },
313 });
314 const credentials = {
315 teamId: "team-jwt-cache",
316 keyId: "key-jwt-cache",
317 privateKey: Redacted.make(privateKey),
318 bundleId: "com.t3tools.test",
319 environment: "sandbox",
320 } satisfies ApnsCredentials;
321 const authorizations: Array<string> = [];
322 const capturingHttpClient = HttpClient.make((request) => {
323 authorizations.push(request.headers.authorization ?? "");
324 return Effect.succeed(
325 HttpClientResponse.fromWeb(
326 request,
327 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
328 ),
329 );
330 });
331 const layer = ApnsClient.layer.pipe(
332 Layer.provide(ApnsProviderTokens.layer),
333 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
334 );
335
336 return Effect.gen(function* () {
337 const apns = yield* ApnsClient.ApnsClient;
338 const request = apns.makePushNotificationRequest({
339 token: "push-token",
340 notification: {
341 title: "Thread",
342 body: "Input: Project",
343 environmentId: "env",
344 threadId: "thread",
345 deepLink: "/threads/env/thread",
346 },
347 });
348 const send = (issuedAtUnixSeconds: number) =>
349 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
350
351 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
352 yield* send(window + 10);
353 yield* send(window * 2 - 1);
354 yield* send(window * 2);
355
356 expect(authorizations).toHaveLength(3);
357 // Within the 45-minute window APNs must see the byte-identical token;
358 // refreshing it per push trips TooManyProviderTokenUpdates.
359 expect(authorizations[1]).toBe(authorizations[0]);
360 expect(authorizations[2]).not.toBe(authorizations[0]);
361 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
362 }).pipe(Effect.provide(layer));
363 });
364});