Skip to content
Myr

password.ts

This file

Path

apps/platform/src/auth/password.ts

153 lines · 4.0 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

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

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 1–2why, one step back
1import { Effect, Redacted, Schema } from "effect";
2

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

line 3why, one step back
3// 100,000 iterations is the most workerd's PBKDF2 accepts on Cloudflare.

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 4–37why, one step back
4export const PasswordPolicy = {
5 hashBytes: 32,6 iterations: 100_000,7 saltBytes: 16,8} as const;910const ALGORITHM = "pbkdf2-sha256";1112const STORED =13 /^pbkdf2-sha256\$(?<iterations>[1-9]\d{0,5})\$(?<salt>[\w-]+)\$(?<hash>[\w-]+)$/u;1415export const PasswordHash = Schema.String.pipe(16 Schema.check(17 Schema.makeFilter((stored) => {18 const iterations = Number(STORED.exec(stored)?.groups?.iterations ?? 0);1920 return iterations > 0 && iterations <= PasswordPolicy.iterations21 ? true22 : `a hash of the form ${ALGORITHM}$<iterations>$<salt>$<hash>`;23 })24 ),25 Schema.brand("PasswordHash")26);2728export type PasswordHash = typeof PasswordHash.Type;2930const Base64Url = Schema.Uint8ArrayFromBase64Url;3132const encodeBase64Url = Schema.encodeEffect(Base64Url);3334const decodeBase64Url = Schema.decodeEffect(Base64Url);3536const utf8 = (text: string) => new TextEncoder().encode(text);37

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

line 38why, one step back
38// The hash means nothing without the Worker's `PASSWORD_PEPPER`.

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 39–79why, one step back
39const peppered = (pepper: Redacted.Redacted, password: Redacted.Redacted) =>
40 Effect.promise(() =>41 crypto.subtle.importKey(42 "raw",43 utf8(Redacted.value(pepper)),44 { hash: "SHA-256", name: "HMAC" },45 false,46 ["sign"]47 )48 ).pipe(49 Effect.flatMap((key) =>50 Effect.promise(() =>51 crypto.subtle.sign("HMAC", key, utf8(Redacted.value(password)))52 )53 )54 );5556const derive = (57 pepper: Redacted.Redacted,58 password: Redacted.Redacted,59 salt: Uint8Array<ArrayBuffer>,60 iterations: number61) =>62 peppered(pepper, password).pipe(63 Effect.flatMap((mac) =>64 Effect.promise(() =>65 crypto.subtle.importKey("raw", mac, "PBKDF2", false, ["deriveBits"])66 )67 ),68 Effect.flatMap((key) =>69 Effect.promise(() =>70 crypto.subtle.deriveBits(71 { hash: "SHA-256", iterations, name: "PBKDF2", salt },72 key,73 PasswordPolicy.hashBytes * 874 )75 )76 ),77 Effect.map((bits) => new Uint8Array(bits))78 );79

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

line 80why, one step back
80// Constant time: the stored bytes are signed under a fresh random key, and `verify` checks the derived bytes against it.

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 81–153why, one step back
81const sameBytes = (
82 derived: Uint8Array<ArrayBuffer>,83 stored: Uint8Array<ArrayBuffer>84) =>85 Effect.promise(() =>86 crypto.subtle.importKey(87 "raw",88 crypto.getRandomValues(new Uint8Array(32)),89 { hash: "SHA-256", name: "HMAC" },90 false,91 ["sign", "verify"]92 )93 ).pipe(94 Effect.flatMap((key) =>95 Effect.promise(() => crypto.subtle.sign("HMAC", key, stored)).pipe(96 Effect.flatMap((signature) =>97 Effect.promise(() =>98 crypto.subtle.verify("HMAC", key, signature, derived)99 )100 )101 )102 )103 );104105export const hashPasswordWith =106 (iterations: number) =>107 (pepper: Redacted.Redacted, password: Redacted.Redacted) =>108 Effect.gen(function* () {109 const salt = crypto.getRandomValues(110 new Uint8Array(PasswordPolicy.saltBytes)111 );112113 const hash = yield* derive(pepper, password, salt, iterations);114115 const parts = yield* Effect.all([116 encodeBase64Url(salt),117 encodeBase64Url(hash),118 ]).pipe(Effect.orDie);119120 return PasswordHash.make(121 [ALGORITHM, String(iterations), ...parts].join("$")122 );123 });124125export const hashPassword = hashPasswordWith(PasswordPolicy.iterations);126127export const verifyPassword = (128 pepper: Redacted.Redacted,129 password: Redacted.Redacted,130 stored: PasswordHash131) =>132 Effect.gen(function* () {133 const { groups } = STORED.exec(stored) ?? {};134135 const iterations = Number(groups?.iterations);136137 const [salt, expected] = yield* Effect.all([138 decodeBase64Url(groups?.salt ?? ""),139 decodeBase64Url(groups?.hash ?? ""),140 ]).pipe(Effect.orDie);141142 const actual = yield* derive(143 pepper,144 password,145 new Uint8Array(salt),146 iterations147 );148149 return {150 needsRehash: iterations < PasswordPolicy.iterations,151 ok: yield* sameBytes(actual, new Uint8Array(expected)),152 };153 });