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

relayJwt.ts

69 lines2.2 KB

1import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";
2import * as Data from "effect/Data";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5​
6export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";
7export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt";
8export const RELAY_HEALTH_REQUEST_TYP = "t3-cloud-health+jwt";
9export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt";
10export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt";
11export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt";
12​
13export class RelayJwtError extends Data.TaggedError("RelayJwtError")<{
14 readonly cause: unknown;
15}> {}
16​
17export function normalizeRelayIssuer(value: string): string {
18 return value.trim().replace(/\/+$/gu, "");
20​
21export function decodeRelayJwt(token: string): JWTPayload {
22 return decodeJwt(token);
24​
25function normalizePem(value: string): string {
26 return value.replace(/\\n/gu, "\n").trim();
28​
29export function signRelayJwt(input: {
30 readonly privateKey: string;
31 readonly typ: string;
32 readonly payload: JWTPayload;
33}): Effect.Effect<string, RelayJwtError> {
34 return Effect.tryPromise({
35 try: async () => {
36 const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");
37 return new SignJWT(input.payload)
38 .setProtectedHeader({ alg: "EdDSA", typ: input.typ })
39 .sign(key);
40 },
41 catch: (cause) => new RelayJwtError({ cause }),
42 });
44​
45export function verifyRelayJwt(input: {
46 readonly publicKey: string;
47 readonly token: string;
48 readonly typ: string;
49 readonly issuer: string;
50 readonly audience: string;
51 readonly nowEpochSeconds: number;
52}): Effect.Effect<JWTPayload, RelayJwtError> {
53 return Effect.tryPromise({
54 try: async () => {
55 const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");
56 const verified = await jwtVerify(input.token, key, {
57 algorithms: ["EdDSA"],
58 typ: input.typ,
59 issuer: input.issuer,
60 audience: input.audience,
61 maxTokenAge: "5 minutes",
62 clockTolerance: 60,
63 currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),
64 });
65 return verified.payload;
66 },
67 catch: (cause) => new RelayJwtError({ cause }),
68 });