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

relayJwt.ts

99 lines3.2 KB

1import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Predicate from "effect/Predicate";
5import * as Schema from "effect/Schema";
6​
7export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";
8export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt";
9export const RELAY_HEALTH_REQUEST_TYP = "t3-cloud-health+jwt";
10export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt";
11export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt";
12export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt";
13​
14export class RelayJwtError extends Schema.TaggedError<RelayJwtError>()("RelayJwtError", {
15 operation: Schema.Literals(["sign", "verify"]),
16 typ: Schema.String,
17 issuer: Schema.optional(Schema.String),
18 audience: Schema.optional(Schema.String),
19 cause: Schema.Defect(),
20}) {
21 override get message(): string {
22 return `Failed to ${this.operation} relay JWT of type "${this.typ}".`;
23 }
24​
25 static diagnosticCode(error: RelayJwtError): string {
26 if (
27 Predicate.isObject(error.cause) &&
28 Predicate.hasProperty(error.cause, "code") &&
29 Predicate.isString(error.cause.code) &&
30 error.cause.code.length > 0
31 ) {
32 return error.cause.code;
33 }
34​
35 return error.cause instanceof Error && error.cause.name ? error.cause.name : "unknown";
36 }
38​
39export function normalizeRelayIssuer(value: string): string {
40 return value.trim().replace(/\/+$/gu, "");
42​
43export function decodeRelayJwt(token: string): JWTPayload {
44 return decodeJwt(token);
46​
47function normalizePem(value: string): string {
48 return value.replace(/\\n/gu, "\n").trim();
50​
51export function signRelayJwt(input: {
52 readonly privateKey: string;
53 readonly typ: string;
54 readonly payload: JWTPayload;
55}): Effect.Effect<string, RelayJwtError> {
56 return Effect.tryPromise({
57 try: async () => {
58 const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");
59 return new SignJWT(input.payload)
60 .setProtectedHeader({ alg: "EdDSA", typ: input.typ })
61 .sign(key);
62 },
63 catch: (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
64 });
66​
67export function verifyRelayJwt(input: {
68 readonly publicKey: string;
69 readonly token: string;
70 readonly typ: string;
71 readonly issuer: string;
72 readonly audience: string;
73 readonly nowEpochSeconds: number;
74 readonly maxTokenAge?: string | number;
75}): Effect.Effect<JWTPayload, RelayJwtError> {
76 return Effect.tryPromise({
77 try: async () => {
78 const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");
79 const verified = await jwtVerify(input.token, key, {
80 algorithms: ["EdDSA"],
81 typ: input.typ,
82 issuer: input.issuer,
83 audience: input.audience,
84 maxTokenAge: input.maxTokenAge ?? "5 minutes",
85 clockTolerance: 60,
86 currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),
87 });
88 return verified.payload;
89 },
90 catch: (cause) =>
91 new RelayJwtError({
92 operation: "verify",
93 typ: input.typ,
94 issuer: input.issuer,
95 audience: input.audience,
96 cause,
97 }),
98 });