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

dpop.ts

188 lines6.5 KB

1import {
2 computeDpopAccessTokenHash,
3 computeDpopJwkThumbprint,
4 DpopPublicJwk,
5} from "@t3tools/shared/dpop";
6import * as Crypto from "effect/Crypto";
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Schema from "effect/Schema";
11import { importJWK, SignJWT, type JWK } from "jose";
12​
13export interface BrowserDpopKey {
14 readonly privateKey: CryptoKey;
15 readonly publicJwk: DpopPublicJwk;
16 readonly thumbprint: string;
18​
19export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{
20 readonly message: string;
21 readonly cause?: unknown;
22}> {}
23​
24const DPOP_DATABASE_NAME = "t3code:cloud-auth";
25const DPOP_DATABASE_VERSION = 1;
26const DPOP_KEY_STORE_NAME = "keys";
27const DPOP_KEY_ID = "relay-dpop-proof-key";
28const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);
29​
30export const browserCryptoLayer = Layer.succeed(
31 Crypto.Crypto,
32 Crypto.make({
33 randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)),
34 digest: (algorithm, data) =>
35 Effect.promise(async () => {
36 const input = new Uint8Array(data.length);
37 input.set(data);
38 return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer));
39 }),
40 }),
41);
42​
43function dpopError(message: string, cause?: unknown) {
44 return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });
46​
47function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {
48 return Effect.callback<IDBDatabase, BrowserDpopError>((resume) => {
49 const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION);
50 request.addEventListener("error", () =>
51 resume(
52 Effect.fail(dpopError("Could not open DPoP key storage.", request.error ?? undefined)),
53 ),
54 );
55 request.addEventListener("upgradeneeded", () => {
56 if (!request.result.objectStoreNames.contains(DPOP_KEY_STORE_NAME)) {
57 request.result.createObjectStore(DPOP_KEY_STORE_NAME);
58 }
59 });
60 request.addEventListener("success", () => resume(Effect.succeed(request.result)));
61 });
63​
64export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null, BrowserDpopError> {
65 if (typeof indexedDB === "undefined") {
66 return Effect.succeed(null);
67 }
68 return Effect.acquireUseRelease(
69 openDpopDatabase(),
70 (database) =>
71 Effect.callback<BrowserDpopKey | null, BrowserDpopError>((resume) => {
72 const request = database
73 .transaction(DPOP_KEY_STORE_NAME, "readonly")
74 .objectStore(DPOP_KEY_STORE_NAME)
75 .get(DPOP_KEY_ID);
76 request.addEventListener("error", () =>
77 resume(Effect.fail(dpopError("Could not read DPoP key.", request.error ?? undefined))),
78 );
79 request.addEventListener("success", () =>
80 resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)),
81 );
82 }),
83 (database) => Effect.sync(() => database.close()),
84 );
86​
87export function writeStoredBrowserDpopKey(
88 key: BrowserDpopKey,
89): Effect.Effect<void, BrowserDpopError> {
90 if (typeof indexedDB === "undefined") {
91 return Effect.void;
92 }
93 return Effect.acquireUseRelease(
94 openDpopDatabase(),
95 (database) =>
96 Effect.callback<void, BrowserDpopError>((resume) => {
97 const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite");
98 transaction.addEventListener("error", () =>
99 resume(
100 Effect.fail(dpopError("Could not write DPoP key.", transaction.error ?? undefined)),
101 ),
102 );
103 transaction.addEventListener("complete", () => resume(Effect.void));
104 transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID);
105 }),
106 (database) => Effect.sync(() => database.close()),
107 );
109​
110export const generateBrowserDpopKey: Effect.Effect<BrowserDpopKey, BrowserDpopError> = Effect.gen(
111 function* () {
112 const generated = yield* Effect.tryPromise({
113 try: () =>
114 crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
115 "sign",
116 "verify",
117 ]) as Promise<CryptoKeyPair>,
118 catch: (cause) => dpopError("Could not generate DPoP proof key.", cause),
119 });
120 const privateJwk = yield* Effect.tryPromise({
121 try: () => crypto.subtle.exportKey("jwk", generated.privateKey),
122 catch: (cause) => dpopError("Could not export DPoP private key.", cause),
123 });
124 const publicJwk = yield* Effect.tryPromise({
125 try: () => crypto.subtle.exportKey("jwk", generated.publicKey),
126 catch: (cause) => dpopError("Could not export DPoP public key.", cause),
127 }).pipe(
128 Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),
129 Effect.mapError((cause) =>
130 cause instanceof BrowserDpopError
131 ? cause
132 : dpopError("Generated DPoP public key is invalid.", cause),
133 ),
134 );
135 const privateKey = yield* Effect.tryPromise({
136 try: () =>
137 importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,
138 catch: (cause) => dpopError("Could not import DPoP private key.", cause),
139 });
140 return {
141 privateKey,
142 publicJwk,
143 thumbprint: computeDpopJwkThumbprint(publicJwk),
144 };
145 },
146);
147​
148export function createBrowserDpopProof(input: {
149 readonly method: string;
150 readonly url: string;
151 readonly accessToken?: string;
152 readonly proofKey: BrowserDpopKey;
153}): Effect.Effect<
154 { readonly proof: string; readonly thumbprint: string },
155 BrowserDpopError,
156 Crypto.Crypto
157> {
158 return Effect.gen(function* () {
159 const normalizedUrl = yield* Effect.try({
160 try: () => new URL(input.url),
161 catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
162 });
163 normalizedUrl.search = "";
164 normalizedUrl.hash = "";
165 const jti = yield* Crypto.Crypto.pipe(
166 Effect.flatMap((crypto) => crypto.randomUUIDv4),
167 Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),
168 );
169 const proof = yield* Effect.tryPromise({
170 try: () =>
171 new SignJWT({
172 htm: input.method.toUpperCase(),
173 htu: normalizedUrl.toString(),
174 jti,
175 ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
176 })
177 .setProtectedHeader({
178 typ: "dpop+jwt",
179 alg: "ES256",
180 jwk: input.proofKey.publicJwk,
181 })
182 .setIssuedAt()
183 .sign(input.proofKey.privateKey),
184 catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
185 });
186 return { proof, thumbprint: input.proofKey.thumbprint };
187 });