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

dpop.ts

170 lines6.0 KB

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