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