Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Redacted from "effect/Redacted";
8import * as Schema from "effect/Schema";
9import * as TestClock from "effect/testing/TestClock";
10import * as HttpClient from "effect/unstable/http/HttpClient";
11import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
12import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
13
14import { RelayConfiguration } from "../Config.ts";
15import { FcmClient, layer } from "./FcmClient.ts";
16
17import * as WebCrypto from "../WebCrypto.ts";
18import * as FcmAssertionSigner from "./FcmAssertionSigner.ts";
19
20const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("rsa", {
21 modulusLength: 2048,
22 privateKeyEncoding: { type: "pkcs8", format: "pem" },
23 publicKeyEncoding: { type: "spki", format: "pem" },
24});
25const account = {
26 project_id: "test-project",
27 client_email: "push@test-project.iam.gserviceaccount.com",
28 private_key: privateKey,
29};
30const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
31const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
32const config = {
33 relayIssuer: "https://relay.test",
34 apns: {
35 environment: "sandbox",
36 teamId: "team",
37 keyId: "key",
38 bundleId: "app",
39 privateKey: Redacted.make("unused"),
40 },
41 fcmServiceAccount: Redacted.make(encodeJson(account)),
42 clerkSecretKey: Redacted.make("unused"),
43 clerkPublishableKey: "unused",
44 clerkJwtAudience: "unused",
45 apnsDeliveryJobSigningSecret: Redacted.make("unused"),
46 cloudMintPrivateKey: Redacted.make("unused"),
47 cloudMintPublicKey: "unused",
48 managedEndpointBaseDomain: undefined,
49 managedEndpointNamespace: undefined,
50} satisfies RelayConfiguration["Service"];
51const input = {
52 token: "device-token",
53 packageName: "com.t3tools.t3code.dev",
54 data: { t3_kind: "agent_activity", active: "true" },
55 alert: false,
56};
57
58function testLayer(requests: HttpClientRequest.HttpClientRequest[], responses: Response[]) {
59 const http = HttpClient.make((request) => {
60 requests.push(request);
61 const response = responses.shift();
62 return response
63 ? Effect.succeed(HttpClientResponse.fromWeb(request, response))
64 : Effect.die("unexpected request");
65 });
66 return layer.pipe(
67 Layer.provide(
68 FcmAssertionSigner.layer.pipe(
69 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
70 ),
71 ),
72 Layer.provide(
73 Layer.mergeAll(
74 Layer.succeed(RelayConfiguration, config),
75 Layer.succeed(HttpClient.HttpClient, http),
76 ),
77 ),
78 );
79}
80
81describe("FCM delivery", () => {
82 it.effect.each([
83 { operation: "authorize", stage: "headers", status: null },
84 { operation: "authorize", stage: "body", status: 200 },
85 { operation: "send", stage: "headers", status: null },
86 { operation: "send", stage: "body", status: 503 },
87 ] as const)("bounds a stalled $operation $stage and allows the next delivery", (scenario) =>
88 Effect.gen(function* () {
89 const started = yield* Deferred.make<void>();
90 let shouldStall = true;
91 const http = HttpClient.make((request) => {
92 const isAuthorization = request.url === "https://oauth2.googleapis.com/token";
93 const stall = shouldStall && isAuthorization === (scenario.operation === "authorize");
94 const response = HttpClientResponse.fromWeb(
95 request,
96 isAuthorization
97 ? Response.json({ access_token: "access-token" })
98 : Response.json({}, { status: stall ? 503 : 200 }),
99 );
100 if (stall) {
101 shouldStall = false;
102 const stalled = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
103 if (scenario.stage === "headers") return stalled;
104 Object.defineProperty(response, "json", { value: stalled });
105 }
106 return Effect.succeed(response);
107 });
108 yield* Effect.gen(function* () {
109 const client = yield* FcmClient;
110 const delivery = yield* client.send(input).pipe(Effect.flip, Effect.forkChild);
111 yield* Deferred.await(started);
112 yield* TestClock.adjust("10 seconds");
113 expect(yield* Fiber.join(delivery)).toMatchObject({
114 _tag: "FcmClientError",
115 operation: scenario.operation,
116 status: scenario.status,
117 cause: expect.objectContaining({ _tag: "TimeoutError" }),
118 });
119 expect(yield* client.send(input)).toEqual({ unregistered: false });
120 }).pipe(
121 Effect.provide(
122 layer.pipe(
123 Layer.provide(
124 FcmAssertionSigner.layer.pipe(
125 Layer.provide(
126 Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle }),
127 ),
128 ),
129 ),
130 Layer.provide(Layer.succeed(RelayConfiguration, config)),
131 Layer.provide(Layer.succeed(HttpClient.HttpClient, http)),
132 ),
133 ),
134 );
135 }),
136 );
137
138 it.effect("signs a verifiable Google OAuth assertion scoped to messaging", () =>
139 Effect.gen(function* () {
140 const signer = yield* FcmAssertionSigner.FcmAssertionSigner;
141 const assertion = yield* signer.sign({
142 privateKey: account.private_key,
143 clientEmail: account.client_email,
144 issuedAt: 1000,
145 });
146 const [header, claims, signature] = assertion.split(".");
147 expect(
148 NodeCrypto.verify(
149 "RSA-SHA256",
150 Buffer.from(`${header}.${claims}`),
151 publicKey,
152 Buffer.from(signature!, "base64url"),
153 ),
154 ).toBe(true);
155 expect(decodeJson(Buffer.from(claims!, "base64url").toString())).toEqual({
156 iss: account.client_email,
157 scope: "https://www.googleapis.com/auth/firebase.messaging",
158 aud: "https://oauth2.googleapis.com/token",
159 iat: 1000,
160 exp: 4600,
161 });
162 }).pipe(
163 Effect.provide(
164 FcmAssertionSigner.layer.pipe(
165 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
166 ),
167 ),
168 ),
169 );
170
171 it.effect(
172 "reuses OAuth authorization and sends native data messages to the correct package",
173 () => {
174 const requests: HttpClientRequest.HttpClientRequest[] = [];
175 return Effect.gen(function* () {
176 const client = yield* FcmClient;
177 yield* client.send(input);
178 yield* client.send({ ...input, alert: true });
179 expect(requests.map((request) => request.url)).toEqual([
180 "https://oauth2.googleapis.com/token",
181 "https://fcm.googleapis.com/v1/projects/test-project/messages:send",
182 "https://fcm.googleapis.com/v1/projects/test-project/messages:send",
183 ]);
184 expect(requests[1]!.headers.authorization).toBe("Bearer access-token");
185 const body = requests[1]!.body;
186 if (body._tag !== "Uint8Array") throw new Error("Expected encoded FCM body");
187 expect(decodeJson(new TextDecoder().decode(body.body))).toEqual({
188 message: {
189 token: input.token,
190 data: input.data,
191 android: {
192 priority: "HIGH",
193 ttl: "300s",
194 collapse_key: "t3-agent-activity",
195 restricted_package_name: input.packageName,
196 },
197 },
198 });
199 }).pipe(
200 Effect.provide(
201 testLayer(requests, [
202 Response.json({ access_token: "access-token" }),
203 Response.json({ name: "one" }),
204 Response.json({ name: "two" }),
205 ]),
206 ),
207 );
208 },
209 );
210
211 it.effect("invalidates authorization after 401 and recognizes unregistered device tokens", () => {
212 const requests: HttpClientRequest.HttpClientRequest[] = [];
213 return Effect.gen(function* () {
214 const client = yield* FcmClient;
215 const first = yield* client.send(input).pipe(Effect.flip);
216 expect(first.status).toBe(401);
217 expect(yield* client.send(input)).toEqual({ unregistered: true });
218 expect(requests[2]!.url).toBe("https://oauth2.googleapis.com/token");
219 expect(requests[3]!.headers.authorization).toBe("Bearer fresh-token");
220 }).pipe(
221 Effect.provide(
222 testLayer(requests, [
223 Response.json({ access_token: "old-token" }),
224 Response.json({}, { status: 401 }),
225 Response.json({ access_token: "fresh-token" }),
226 Response.json(
227 {
228 error: {
229 details: [
230 {
231 "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
232 errorCode: "UNREGISTERED",
233 },
234 ],
235 },
236 },
237 { status: 404 },
238 ),
239 ]),
240 ),
241 );
242 });
243 it.effect("rejects oversized data before contacting Firebase", () => {
244 const requests: HttpClientRequest.HttpClientRequest[] = [];
245 return Effect.gen(function* () {
246 const client = yield* FcmClient;
247 const error = yield* client
248 .send({ ...input, data: { body: "漢".repeat(1500) } })
249 .pipe(Effect.flip);
250 expect(error.operation).toBe("send");
251 expect(requests).toHaveLength(0);
252 }).pipe(Effect.provide(testLayer(requests, [])));
253 });
254});