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

ApnsClient.test.ts

254 lines8.2 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 Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Redacted from "effect/Redacted";
11import * as HttpClient from "effect/http/HttpClient";
12import * as HttpClientResponse from "effect/http/HttpClientResponse";
13​
14import type { ApnsCredentials } from "../Config.ts";
15import * as ApnsClient from "./ApnsClient.ts";
16import { sanitizeApnsNotificationPayload } from "./agentActivityPayloads.ts";
17import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
18​
19const layerTest = ApnsClient.layer.pipe(
20 Layer.provide(ApnsProviderTokens.layer),
21 Layer.provide(
22 Layer.succeed(
23 HttpClient.HttpClient,
24 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
25 ),
26 ),
27);
28​
29describe("ApnsClient", () => {
30 const now = DateTime.makeUnsafe(0);
31 const state: RelayAgentActivityAggregateState = {
32 title: "T3 Code",
33 subtitle: "Agent work in progress",
34 activeCount: 1,
35 updatedAt: DateTime.formatIso(now),
36 activities: [
37 {
38 environmentId: EnvironmentId.make("env"),
39 threadId: ThreadId.make("thread"),
40 projectTitle: "Project",
41 threadTitle: "Thread",
42 modelTitle: "gpt-5.4",
43 phase: "running" as const,
44 status: "Working",
45 updatedAt: DateTime.formatIso(now),
46 deepLink: "/",
47 },
48 ],
49 };
50​
51 it.effect("requests an update push token when remotely starting a Live Activity", () =>
52 Effect.gen(function* () {
53 const apns = yield* ApnsClient.ApnsClient;
54 const request = apns.makeLiveActivityRequest({
55 event: "start",
56 token: "token",
57 state,
58 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
59 nowIso: DateTime.formatIso(now),
60 });
61​
62 expect(request.priority).toBe("10");
63 expect(request.payload).toMatchObject({
64 aps: {
65 event: "start",
66 "attributes-type": "LiveActivityAttributes",
67 "input-push-token": 1,
68 "content-state": {
69 name: "AgentActivity",
70 },
71 },
72 });
73 }).pipe(Effect.provide(layerTest)),
74 );
75​
76 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
77 Effect.gen(function* () {
78 const apns = yield* ApnsClient.ApnsClient;
79 const request = apns.makeLiveActivityRequest({
80 event: "update",
81 token: "token",
82 state,
83 alert: { title: "Thread", body: "Approval: Project" },
84 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
85 nowIso: DateTime.formatIso(now),
86 });
87​
88 expect(request.priority).toBe("10");
89 expect(request.payload).toMatchObject({
90 aps: {
91 event: "update",
92 alert: {
93 title: "Thread",
94 body: "Approval: Project",
95 sound: "default",
96 },
97 },
98 });
99 }).pipe(Effect.provide(layerTest)),
100 );
101​
102 it.effect("builds an end payload with a dismissal date", () =>
103 Effect.gen(function* () {
104 const apns = yield* ApnsClient.ApnsClient;
105 const request = apns.makeLiveActivityRequest({
106 event: "end",
107 token: "token",
108 state,
109 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
110 nowIso: DateTime.formatIso(now),
111 });
112​
113 expect(request.priority).toBe("10");
114 expect(request.payload).toMatchObject({
115 aps: {
116 event: "end",
117 "dismissal-date": 300,
118 },
119 });
120​
121 const contentless = apns.makeLiveActivityRequest({
122 event: "end",
123 token: "token",
124 state: null,
125 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
126 nowIso: DateTime.formatIso(now),
127 });
128 expect(contentless.payload).toMatchObject({
129 aps: {
130 event: "end",
131 "dismissal-date": 15,
132 },
133 });
134 }).pipe(Effect.provide(layerTest)),
135 );
136​
137 it.effect("puts remote routing metadata only in Expo's body field", () =>
138 Effect.gen(function* () {
139 const apns = yield* ApnsClient.ApnsClient;
140 const request = apns.makePushNotificationRequest({
141 token: "push-token",
142 notification: {
143 title: "Thread",
144 body: "Input: Project",
145 environmentId: "env",
146 threadId: "thread",
147 deepLink: "/threads/env/thread",
148 },
149 });
150​
151 expect(request.priority).toBe("10");
152 expect(request.payload).toEqual({
153 aps: {
154 alert: {
155 title: "Thread",
156 body: "Input: Project",
157 },
158 sound: "default",
159 "thread-id": "env/thread",
160 },
161 body: {
162 environmentId: "env",
163 threadId: "thread",
164 deepLink: "/threads/env/thread",
165 },
166 });
167 }).pipe(Effect.provide(layerTest)),
168 );
169​
170 it.effect("fits long routing metadata and multibyte alerts within the APNs 4096-byte limit", () =>
171 Effect.gen(function* () {
172 const apns = yield* ApnsClient.ApnsClient;
173 const environmentId = "é".repeat(191);
174 const threadId = "t".repeat(512);
175 const notification = sanitizeApnsNotificationPayload({
176 title: "界".repeat(120),
177 body: "界".repeat(120),
178 environmentId,
179 threadId,
180 deepLink: `/threads/${encodeURIComponent(environmentId)}/${threadId}`,
181 });
182 const request = apns.makePushNotificationRequest({ token: "push-token", notification });
183​
184 expect(
185 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
186 ).toBeLessThanOrEqual(4096);
187 expect(request.payload).toMatchObject({
188 body: {
189 environmentId,
190 threadId,
191 deepLink: notification.deepLink,
192 },
193 });
194 }).pipe(Effect.provide(layerTest)),
195 );
196​
197 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
198 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
199 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
200 namedCurve: "prime256v1",
201 privateKeyEncoding: { type: "pkcs8", format: "pem" },
202 publicKeyEncoding: { type: "spki", format: "pem" },
203 });
204 const credentials = {
205 teamId: "team-jwt-cache",
206 keyId: "key-jwt-cache",
207 privateKey: Redacted.make(privateKey),
208 bundleId: "com.t3tools.test",
209 environment: "sandbox",
210 } satisfies ApnsCredentials;
211 const authorizations: Array<string> = [];
212 const capturingHttpClient = HttpClient.make((request) => {
213 authorizations.push(request.headers.authorization ?? "");
214 return Effect.succeed(
215 HttpClientResponse.fromWeb(
216 request,
217 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
218 ),
219 );
220 });
221 const layer = ApnsClient.layer.pipe(
222 Layer.provide(ApnsProviderTokens.layer),
223 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
224 );
225​
226 return Effect.gen(function* () {
227 const apns = yield* ApnsClient.ApnsClient;
228 const request = apns.makePushNotificationRequest({
229 token: "push-token",
230 notification: {
231 title: "Thread",
232 body: "Input: Project",
233 environmentId: "env",
234 threadId: "thread",
235 deepLink: "/threads/env/thread",
236 },
237 });
238 const send = (issuedAtUnixSeconds: number) =>
239 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
240​
241 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
242 yield* send(window + 10);
243 yield* send(window * 2 - 1);
244 yield* send(window * 2);
245​
246 expect(authorizations).toHaveLength(3);
247 // Within the 45-minute window APNs must see the byte-identical token;
248 // refreshing it per push trips TooManyProviderTokenUpdates.
249 expect(authorizations[1]).toBe(authorizations[0]);
250 expect(authorizations[2]).not.toBe(authorizations[0]);
251 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
252 }).pipe(Effect.provide(layer));
253 });
254});