Skip to content
Myr

webcrypto.ts

This file

Path

packages/visibility/src/vault/webcrypto.ts

210 lines · 5.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 1–2why, one step back
1// A fresh AES-GCM-256 data key and IV per value, the data key wrapped with the
2// master key by AES-KW (RFC 3394, which checks the key's integrity on unwrap).

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–38why, one step back
3import { Effect, Layer, Option, Redacted, Schema } from "effect";
45import {6 admitLength,7 SealedValueUnopenable,8 WriteOnlyValues,9} from "../vault.ts";10import type { SealedValue, ValueToSeal } from "../vault.ts";1112/**13 * Which master key a value was sealed under. Only version 1 exists; a new14 * master key takes the next number, so values sealed under the old one can15 * be found and sealed again.16 */17const KEY_VERSION = 1;1819const IV_BYTES = 12;2021const KEY_BYTES = 32;2223/**24 * Values are padded to a multiple of this many bytes before sealing, so a25 * ciphertext's length tells only which 64-byte step the value's length26 * falls in, not the length itself.27 */28const PAD_TO = 64;2930const PAD_MARK = 0x80;3132class MasterKeyUnusable extends Schema.TaggedError<MasterKeyUnusable>()(33 "MasterKeyUnusable",34 {}35) {}3637const encodeBase64 = Schema.encodeEffect(Schema.Uint8ArrayFromBase64);38

Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff

lines 39–44why, one step back
39/**
40 * The bytes in a buffer of their own. WebCrypto takes an `ArrayBuffer`-backed41 * view, and a decoded `Uint8Array` is typed over any buffer under Node's types.42 */43const owned = (bytes: Uint8Array): Uint8Array<ArrayBuffer> =>44 new Uint8Array(bytes);

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 45why, one step back
45

Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff

lines 46–48why, one step back
46const decodeBase64 = (text: string) =>
47 Effect.map(Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(text), owned);48

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 49–66why, one step back
49const padded = (value: string) => {
50 const bytes = new TextEncoder().encode(value);51 const out = new Uint8Array((Math.floor(bytes.length / PAD_TO) + 1) * PAD_TO);5253 out.set(bytes);54 out[bytes.length] = PAD_MARK;5556 return out;57};5859const unpadded = (bytes: Uint8Array) => {60 const end = bytes.findLastIndex((byte) => byte !== 0);6162 return end !== -1 && bytes[end] === PAD_MARK63 ? Option.some(bytes.subarray(0, end))64 : Option.none();65};66

Merge build/1007oscabrielbefore adoption77fa97a

line 67why, one step back
67const masterKeyBytes = (masterKey: Redacted.Redacted) =>

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 68–73why, one step back
68 Schema.decodeEffect(Schema.Uint8ArrayFromHex)(Redacted.value(masterKey)).pipe(
69 Effect.mapError(() => new MasterKeyUnusable()),70 Effect.filterOrFail(71 (bytes) => bytes.length === KEY_BYTES,72 () => new MasterKeyUnusable()73 ),

Merge build/1007oscabrielbefore adoption77fa97a

line 74why, one step back
74 Effect.map(owned),

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 75–77why, one step back
75 Effect.orDie
76 );77

Merge build/1007oscabrielbefore adoption77fa97a

line 78why, one step back
78/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 79–80why, one step back
79 * Imported for each call: WebCrypto's import is a promise, and the layer is
80 * built where nothing may be awaited (the platform's router, at module load).

Merge build/1007oscabrielbefore adoption77fa97a

lines 81–89why, one step back
81 */
82const importMasterKey = (bytes: Uint8Array<ArrayBuffer>) =>83 Effect.promise(() =>84 crypto.subtle.importKey("raw", bytes, "AES-KW", false, [85 "wrapKey",86 "unwrapKey",87 ])88 );89

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 90–189why, one step back
90const freshDataKey = Effect.sync(() =>
91 crypto.getRandomValues(new Uint8Array(KEY_BYTES))92).pipe(93 Effect.flatMap((raw) =>94 Effect.promise(() =>95 crypto.subtle.importKey("raw", raw, "AES-GCM", true, ["encrypt"])96 ).pipe(Effect.ensuring(Effect.sync(() => raw.fill(0))))97 )98);99100const seal = (master: CryptoKey, input: ValueToSeal) =>101 Effect.gen(function* () {102 yield* admitLength(input);103104 const dataKey = yield* freshDataKey;105106 const iv = yield* Effect.sync(() =>107 crypto.getRandomValues(new Uint8Array(IV_BYTES))108 );109110 const ciphertext = yield* Effect.promise(() =>111 crypto.subtle.encrypt(112 { iv, name: "AES-GCM" },113 dataKey,114 padded(Redacted.value(input.value))115 )116 );117118 const wrappedKey = yield* Effect.promise(() =>119 crypto.subtle.wrapKey("raw", dataKey, master, "AES-KW")120 );121122 const [ciphertextText, ivText, wrappedKeyText] = yield* Effect.all([123 encodeBase64(new Uint8Array(ciphertext)),124 encodeBase64(iv),125 encodeBase64(new Uint8Array(wrappedKey)),126 ]).pipe(Effect.orDie);127128 return {129 ciphertext: ciphertextText,130 iv: ivText,131 keyVersion: KEY_VERSION,132 wrappedKey: wrappedKeyText,133 } satisfies SealedValue;134 });135136const unseal = (master: CryptoKey, sealed: SealedValue) =>137 Effect.gen(function* () {138 if (sealed.keyVersion !== KEY_VERSION) {139 return yield* new SealedValueUnopenable({ step: "keyVersion" });140 }141142 const wrappedKey = yield* decodeBase64(sealed.wrappedKey).pipe(143 Effect.mapError(() => new SealedValueUnopenable({ step: "unwrap" }))144 );145146 const dataKey = yield* Effect.tryPromise({147 catch: () => new SealedValueUnopenable({ step: "unwrap" }),148 try: () =>149 crypto.subtle.unwrapKey(150 "raw",151 wrappedKey,152 master,153 "AES-KW",154 "AES-GCM",155 false,156 ["decrypt"]157 ),158 });159160 const [iv, ciphertext] = yield* Effect.all([161 decodeBase64(sealed.iv),162 decodeBase64(sealed.ciphertext),163 ]).pipe(164 Effect.mapError(() => new SealedValueUnopenable({ step: "decrypt" }))165 );166167 const plain = yield* Effect.tryPromise({168 catch: () => new SealedValueUnopenable({ step: "decrypt" }),169 try: () =>170 crypto.subtle.decrypt({ iv, name: "AES-GCM" }, dataKey, ciphertext),171 });172173 const bytes = yield* Effect.fromOption(174 unpadded(new Uint8Array(plain))175 ).pipe(176 Effect.mapError(() => new SealedValueUnopenable({ step: "decrypt" }))177 );178179 return yield* Effect.try({180 catch: () => new SealedValueUnopenable({ step: "decrypt" }),181 try: () =>182 Redacted.make(183 new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(184 bytes185 )186 ),187 });188 }).pipe(Effect.orDie);189

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

line 190why, one step back
190/** A key of any other form is a defect when the layer is built, and the defect never holds the key. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 191–195why, one step back
191export const WriteOnlyValuesWebCrypto = (
192 masterKey: Redacted.Redacted193): Layer.Layer<WriteOnlyValues> =>194 Layer.effect(195 WriteOnlyValues,

Merge build/1007oscabrielbefore adoption77fa97a

lines 196–197why, one step back
196 masterKeyBytes(masterKey).pipe(
197 Effect.map((bytes) =>

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 198why, one step back
198 WriteOnlyValues.of({

Merge build/1007oscabrielbefore adoption77fa97a

lines 199–206why, one step back
199 open: (sealed) =>
200 Effect.flatMap(importMasterKey(bytes), (master) =>201 unseal(master, sealed)202 ),203 put: (input) =>204 Effect.flatMap(importMasterKey(bytes), (master) =>205 seal(master, input)206 ),

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 207–210why, one step back
207 })
208 )209 )210 );