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

apnsJwt.ts

160 lines5.0 KB

1import * as NodeCrypto from "node:crypto";
2​
3import { p256 } from "@noble/curves/nist";
4import { sha256 } from "@noble/hashes/sha2";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as Redacted from "effect/Redacted";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10​
11import type { ApnsCredentials } from "../Config.ts";
12​
13export class ApnsJwtEncodingError extends Schema.TaggedError<ApnsJwtEncodingError>()(
14 "ApnsJwtEncodingError",
15 {
16 component: Schema.Literals(["header", "payload"]),
17 teamId: Schema.String,
18 keyId: Schema.String,
19 issuedAtUnixSeconds: Schema.Number,
20 cause: Schema.Defect(),
21 },
22) {
23 override get message(): string {
24 return `Failed to encode APNs JWT ${this.component} for key ${this.keyId}.`;
25 }
27​
28export class ApnsJwtSigningError extends Schema.TaggedError<ApnsJwtSigningError>()(
29 "ApnsJwtSigningError",
30 {
31 teamId: Schema.String,
32 keyId: Schema.String,
33 issuedAtUnixSeconds: Schema.Number,
34 cause: Schema.Defect(),
35 },
36) {
37 override get message(): string {
38 return `Failed to sign APNs JWT for key ${this.keyId}.`;
39 }
41​
42export type ApnsJwtError = ApnsJwtEncodingError | ApnsJwtSigningError;
43​
44const encodeApnsJwtHeaderJson = Schema.encodeEffect(
45 Schema.fromJsonString(
46 Schema.Struct({
47 alg: Schema.Literal("ES256"),
48 kid: Schema.String,
49 }),
50 ),
51);
52const encodeApnsJwtPayloadJson = Schema.encodeEffect(
53 Schema.fromJsonString(
54 Schema.Struct({
55 iss: Schema.String,
56 iat: Schema.Number,
57 }),
58 ),
59);
60​
61export interface ApnsJwtSigningInput {
62 readonly teamId: ApnsCredentials["teamId"];
63 readonly keyId: ApnsCredentials["keyId"];
64 readonly privateKey: ApnsCredentials["privateKey"];
65 readonly issuedAtUnixSeconds: number;
67​
68export const makeApnsJwt = Effect.fn("relay.apns.make_jwt")(function* (input: ApnsJwtSigningInput) {
69 const headerJson = yield* encodeApnsJwtHeaderJson({ alg: "ES256", kid: input.keyId }).pipe(
70 Effect.mapError(
71 (cause) =>
72 new ApnsJwtEncodingError({
73 component: "header",
74 teamId: input.teamId,
75 keyId: input.keyId,
76 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
77 cause,
78 }),
79 ),
80 );
81 const payloadJson = yield* encodeApnsJwtPayloadJson({
82 iss: input.teamId,
83 iat: input.issuedAtUnixSeconds,
84 }).pipe(
85 Effect.mapError(
86 (cause) =>
87 new ApnsJwtEncodingError({
88 component: "payload",
89 teamId: input.teamId,
90 keyId: input.keyId,
91 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
92 cause,
93 }),
94 ),
95 );
96​
97 const privateKey = Redacted.value(input.privateKey);
98 const header = Encoding.encodeBase64Url(headerJson);
99 const payload = Encoding.encodeBase64Url(payloadJson);
100 const signingInput = `${header}.${payload}`;
101​
102 return yield* Effect.try({
103 try: () => {
104 // Deterministic ES256 (RFC 6979 via noble) instead of node's randomized
105 // signer: identical (key, iat) yields the byte-identical JWT on every
106 // worker isolate, so the fleet presents one stable provider token to
107 // APNs without any shared storage. Node crypto only converts the PEM to
108 // the raw scalar noble signs with.
109 const scalar = apnsSigningScalar(privateKey);
110 const signature = p256
111 .sign(sha256(new TextEncoder().encode(signingInput)), scalar, { prehash: false })
112 .toCompactRawBytes();
113 return `${signingInput}.${Encoding.encodeBase64Url(signature)}`;
114 },
115 catch: (cause) =>
116 new ApnsJwtSigningError({
117 teamId: input.teamId,
118 keyId: input.keyId,
119 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
120 cause,
121 }),
122 });
123});
124​
125// PEM parsing is pure and the key set is static per deployment; memoize the
126// extracted P-256 scalar so signing never re-parses the PKCS8 document.
127const signingScalarCache = new Map<string, Uint8Array>();
128​
129function apnsSigningScalar(privateKeyPem: string): Uint8Array {
130 const cached = signingScalarCache.get(privateKeyPem);
131 if (cached) {
132 return cached;
133 }
134 const jwk = NodeCrypto.createPrivateKey(privateKeyPem.replace(/\\n/g, "\n")).export({
135 format: "jwk",
136 });
137 if (jwk.crv !== "P-256" || typeof jwk.d !== "string") {
138 throw new Error("APNs signing key is not a P-256 private key.");
139 }
140 const scalar = Result.getOrThrowWith(
141 Encoding.decodeBase64Url(jwk.d),
142 () => new Error("APNs signing key scalar is not valid base64url."),
143 );
144 signingScalarCache.set(privateKeyPem, scalar);
145 return scalar;
147​
148// Fingerprint the key material so rotated credentials never reuse a JWT
149// signed by the previous key.
150export function apnsProviderTokenCacheKey(input: {
151 readonly teamId: string;
152 readonly keyId: string;
153 readonly privateKey: ApnsCredentials["privateKey"];
154}): string {
155 const keyFingerprint = NodeCrypto.createHash("sha256")
156 .update(Redacted.value(input.privateKey))
157 .digest("hex")
158 .slice(0, 16);
159 return `${input.teamId}:${input.keyId}:${keyFingerprint}`;