Open History to see the last commit
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";
13export const RELAY_MANAGED_TUNNEL_RECOVERY_TYP = "t3-env-managed-tunnel-recovery+jwt";
14export const RELAY_HOOK_DELIVERY_TYP = "t3-relay-hook-delivery+jwt";
15export const RELAY_HOOK_DELIVERY_HEADER = "x-t3-relay-delivery";
16
17export class RelayJwtError extends Schema.TaggedError<RelayJwtError>()("RelayJwtError", {
18 operation: Schema.Literals(["sign", "verify"]),
19 typ: Schema.String,
20 issuer: Schema.optional(Schema.String),
21 audience: Schema.optional(Schema.String),
22 cause: Schema.Defect(),
23}) {
24 override get message(): string {
25 return `Failed to ${this.operation} relay JWT of type "${this.typ}".`;
26 }
27
28 static diagnosticCode(error: RelayJwtError): string {
29 if (
30 Predicate.isObject(error.cause) &&
31 Predicate.hasProperty(error.cause, "code") &&
32 Predicate.isString(error.cause.code) &&
33 error.cause.code.length > 0
34 ) {
35 return error.cause.code;
36 }
37
38 return error.cause instanceof Error && error.cause.name ? error.cause.name : "unknown";
39 }
40}
41
42export function normalizeRelayIssuer(value: string): string {
43 return value.trim().replace(/\/+$/gu, "");
44}
45
46export function decodeRelayJwt(token: string): JWTPayload {
47 return decodeJwt(token);
48}
49
50function normalizePem(value: string): string {
51 return value.replace(/\\n/gu, "\n").trim();
52}
53
54export function signRelayJwt(input: {
55 readonly privateKey: string;
56 readonly typ: string;
57 readonly payload: JWTPayload;
58}): Effect.Effect<string, RelayJwtError> {
59 return Effect.tryPromise({
60 try: async () => {
61 const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");
62 return new SignJWT(input.payload)
63 .setProtectedHeader({ alg: "EdDSA", typ: input.typ })
64 .sign(key);
65 },
66 catch: (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
67 });
68}
69
70export function verifyRelayJwt(input: {
71 readonly publicKey: string;
72 readonly token: string;
73 readonly typ: string;
74 readonly issuer: string;
75 readonly audience: string;
76 readonly nowEpochSeconds: number;
77 readonly maxTokenAge?: string | number;
78}): Effect.Effect<JWTPayload, RelayJwtError> {
79 return Effect.tryPromise({
80 try: async () => {
81 const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");
82 const verified = await jwtVerify(input.token, key, {
83 algorithms: ["EdDSA"],
84 typ: input.typ,
85 issuer: input.issuer,
86 audience: input.audience,
87 maxTokenAge: input.maxTokenAge ?? "5 minutes",
88 clockTolerance: 60,
89 currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),
90 });
91 return verified.payload;
92 },
93 catch: (cause) =>
94 new RelayJwtError({
95 operation: "verify",
96 typ: input.typ,
97 issuer: input.issuer,
98 audience: input.audience,
99 cause,
100 }),
101 });
102}