first commit

This commit is contained in:
2026-05-29 08:20:56 +01:00
commit 949299f58d
6368 changed files with 527176 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
# `range/constant-time-compare.ts`
## Purpose
`constantTimeEqualsHex` compares two hex suffixes without early-exit on
the first mismatching character. It is used by the range-API client to
verify whether any line in the response matches the input password's
35-char suffix, so a timing-side-channel attacker cannot infer which
slot the real suffix lands in. The instrumented variant
(`constantTimeEqualsHexInstrumented`) returns the byte-XOR count for
test assertions.
## Features
- Branch-free byte loop using OR-accumulator over XOR pairs.
- Touches every byte of the input — no length-based shortcut beyond the
initial length-mismatch check.
- ASCII-only (uppercase hex) inputs guarantee `charCodeAt` is
single-byte, keeping per-character cost predictable.
- Test instrumentation exposed without changing the hot path.
## Usage: Basic Example
```ts
import { constantTimeEqualsHex } from "@suaveplan/hibp";
if (constantTimeEqualsHex(line.suffix, target)) {
/* matched */
}
```
## Usage: Advanced Example
```ts
import { constantTimeEqualsHexInstrumented } from "@suaveplan/hibp";
const { equal, bytesTouched } = constantTimeEqualsHexInstrumented(a, b);
if (!equal && bytesTouched !== a.length) {
throw new Error("comparator regressed to early-exit");
}
```
## API Reference
- `constantTimeEqualsHex(a: string, b: string): boolean`.
- `constantTimeEqualsHexInstrumented(a, b): { equal, bytesTouched }`.
## Implementation Notes
JavaScript does not expose a true constant-time string compare, but the
loop pattern above is the canonical approximation. The OR-accumulator
trick converts every byte XOR into a single boolean test at the end,
eliminating the data-dependent branch that an `if (a[i] !== b[i])
return false` would introduce. The length-mismatch check leaks only the
public fact that the two strings differ in length, which is never
secret in this protocol. The test suite asserts the wall-clock mean
delta between equal and unequal pairs stays within tolerance over
10 000 samples; the more rigorous proof is the bytes-touched
invariant.

View File

@@ -0,0 +1,62 @@
# `range/differential-privacy.ts`
## Purpose
`padPrefixes` generates the decoy prefixes used by the
differential-privacy mode of `checkPassword`. Given the real 5-hex
prefix and a positive `n`, it returns an array of `n + 1` prefixes —
the real one plus `n` uniformly random siblings drawn from the
`[00000, FFFFF]` space, with the real prefix guaranteed never to appear
in a decoy slot. The injectable `Rng` keeps the function deterministic
under test.
## Features
- Always includes the real prefix at index 0, normalised to uppercase.
- Decoys are unique within a single call (a `Set` guards against
collisions) and never equal to the real prefix.
- Uses `Rng.nextIntInRange` when present (unbiased on any range) and
falls back to unbiased rejection sampling over `nextUint32` so
`Math.random`-style RNGs without range support still produce
uniform output.
- Returns an immutable array literal, so consumers can iterate without
worrying about accidental mutation.
## Usage: Basic Example
```ts
import { padPrefixes } from "@suaveplan/hibp";
const prefixes = padPrefixes("F3BBB", 3, myRng);
// length 4, includes "F3BBB", three random siblings
```
## Usage: Advanced Example
```ts
import { padPrefixes } from "@suaveplan/hibp";
import type { Rng } from "@suaveplan/types";
const deterministic: Rng = {
nextUint32: () => 0,
nextFloat: () => 0,
nextIntInRange: (_, max) => max - 1,
};
const prefixes = padPrefixes("AAAAA", 2, deterministic);
// Reproducible decoy set for tests.
```
## API Reference
- `padPrefixes(realPrefix, n, rng): readonly string[]`.
## Implementation Notes
The rejection-sampling fallback divides the `[0, 2^32)` space by 16 and
discards any draw landing in the residual partial range to keep the
distribution uniform — a `% 16` shortcut would bias the low nibbles.
The seen-set deduplication keeps the algorithm O(n) on average even
under unlikely RNG repeats. The function intentionally throws no
typed `HibpError` because input validation (range, RNG presence) is
handled one layer up in `RangeClient.checkPassword`.

View File

@@ -0,0 +1,60 @@
# `range/range-mode.ts`
## Purpose
Houses the hash-mode dispatch utilities used by `checkPassword`:
`hashSha1Prefix` (SHA-1 via `@noble/hashes/sha1`), `hashNtlmPrefix`
(MD4-over-UTF-16-LE, supplied by an injectable adapter because not every
runtime ships an MD4 implementation), and `buildRangeUrl` (assembles the
final `/range/<prefix>[?mode=ntlm]` URL). The split between hashing and
URL building keeps each function small, testable, and reusable from
both the public `checkPassword` path and the privacy-leak verification
helpers.
## Features
- `hashSha1Prefix(password)` returns `{ prefix, suffix, full }` with the
uppercase 40-char digest and its k-anonymity decomposition.
- `hashNtlmPrefix(password, adapter)` accepts a caller-supplied adapter,
validating that the returned digest is exactly 40 uppercase hex chars.
- `buildRangeUrl(prefix, mode)` appends `?mode=ntlm` only when the mode
is `"ntlm"` — SHA-1 mode never sends a query string.
- `RangeMode` type alias narrows callers to the two valid values.
## Usage: Basic Example
```ts
import { buildRangeUrl, hashSha1Prefix } from "@suaveplan/hibp";
const { prefix } = hashSha1Prefix("hunter2");
const url = buildRangeUrl(prefix, "sha1");
```
## Usage: Advanced Example
```ts
import { buildRangeUrl, hashNtlmPrefix } from "@suaveplan/hibp";
import { md4 } from "my-ntlm-adapter";
const { prefix } = hashNtlmPrefix("hunter2", (pw) => md4(pw).toUpperCase());
const url = buildRangeUrl(prefix, "ntlm");
```
## API Reference
- `RangeMode = "sha1" | "ntlm"`.
- `NtlmHashAdapter = (password: string) => string`.
- `hashSha1Prefix(password): { prefix, suffix, full }`.
- `hashNtlmPrefix(password, adapter): { prefix, suffix, full }`.
- `buildRangeUrl(prefix, mode): string`.
## Implementation Notes
SHA-1 is sourced from `@noble/hashes/sha1` rather than from
`@suaveplan/crypto-hash` because the crypto-hash package deliberately
omits SHA-1 (collision-broken for security purposes). The HIBP API
requires SHA-1 strictly for k-anonymity bucket selection — never for
security — so the direct noble dependency is the right call.
`hashNtlmPrefix` validates the adapter output rather than trusting it
because a buggy adapter could produce shorter strings and accidentally
leak unrelated bytes.

View File

@@ -0,0 +1,67 @@
# `range/range-stream-parse.ts`
## Purpose
Streams an HTTP response body line-by-line through a `TextDecoderStream`
and a newline framer, yielding `{ suffix, count }` records as soon as
each line crosses a complete byte boundary. The parser deliberately
never calls `Response.text()` and never collects the body into a single
string buffer, so even a 30 KiB `Add-Padding` response is processed in
bounded memory. Mid-flight `AbortSignal` is honoured between chunks.
## Features
- Async generator interface — drop in to `for await` loops.
- CRLF and LF newlines both work; trailing line without newline is
emitted; empty lines are skipped.
- Per-line validation delegated to `parseRangeLine` so strict-mode
rejection happens at first-fault.
- AbortSignal threading: pre-aborted and mid-flight aborts both throw
`HIBP.ABORTED` and the underlying reader is released in a `finally`
guard.
## Usage: Basic Example
```ts
import { streamParseRangeBody } from "@suaveplan/hibp";
for await (const line of streamParseRangeBody(response.body!, { strict: true })) {
if (line.suffix === expected) /* ... */;
}
```
## Usage: Advanced Example
```ts
import { streamParseRangeBody } from "@suaveplan/hibp";
const ac = new AbortController();
const iter = streamParseRangeBody(response.body!, {
strict: false,
signal: ac.signal,
});
setTimeout(() => ac.abort(), 100);
try {
for await (const _line of iter) { /* ... */ }
} catch (err) {
if ((err as { code?: string }).code === "HIBP.ABORTED") {
// user cancelled
}
}
```
## API Reference
- `streamParseRangeBody(body, { strict, signal? }): AsyncGenerator<RangeLine>`.
## Implementation Notes
The `TextDecoderStream` typings model the writable side as
`BufferSource`, which trips the structural `pipeThrough` constraint, so
the parser casts at the boundary. Calls to `Response.text()` are
forbidden by the spec — the test suite asserts zero invocations. The
generator's `finally` clause releases the underlying reader even when
the consumer breaks out early, preventing leaked readable streams when
a caller chooses to short-circuit on the first match.

View File

@@ -0,0 +1,65 @@
# `range/range-strict-frame.ts`
## Purpose
`parseRangeLine` is the per-line framer used by `streamParseRangeBody`.
It enforces the documented Pwned Passwords line shape (`/^[0-9A-F]{35}:[0-9]+$/`)
in strict mode, throwing `HIBP.MALFORMED_RESPONSE` with the offending
line index on any deviation. In off-mode it accepts lowercase hex,
defaults an unparseable count to `0`, and still rejects structurally
broken lines (missing colon, wrong suffix length, non-hex characters).
## Features
- Strict mode default — uppercase hex, single colon, decimal count.
- Off mode tolerant of lowercase hex and unparseable counts (defaults
to `0`), still rejecting non-hex suffixes or wrong lengths.
- Throws carry `context.lineIndex` so callers can surface a precise
diagnostic.
- Pure synchronous function — no allocations beyond the returned
`{ suffix, count }` record.
## Usage: Basic Example
```ts
import { parseRangeLine } from "@suaveplan/hibp";
const { suffix, count } = parseRangeLine(rawLine, 0, true);
```
## Usage: Advanced Example
```ts
import { HibpError, parseRangeLine } from "@suaveplan/hibp";
function parseTolerant(lines: string[]): Array<{ suffix: string; count: number }> {
const out: Array<{ suffix: string; count: number }> = [];
for (let i = 0; i < lines.length; i++) {
try {
out.push(parseRangeLine(lines[i] as string, i, false));
} catch (err) {
if (err instanceof HibpError) continue;
throw err;
}
}
return out;
}
```
## API Reference
- `RangeLine` — `{ suffix: string; count: number }`.
- `parseRangeLine(raw, lineIndex, strict): RangeLine` — throws
`HibpError(HIBP.MALFORMED_RESPONSE)` on rejection.
## Implementation Notes
The strict pattern uses a tight regex check before the colon split so
mismatches are rejected before any allocation. Off-mode counts default
to `0` rather than `NaN` so consumers can rely on integer semantics
throughout. The function avoids `try`/`catch` internally — every
branch is explicit so a future contributor can reason about the
failure paths without tracing exception flow. Strict mode is the
default because the documented Pwned Passwords contract is precise;
opting out should be a deliberate operational decision, not the
silent fallback.

View File

@@ -0,0 +1,77 @@
# `range/range.ts`
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
`RangeClient` is the heart of the package — the k-anonymity Pwned
Passwords client. `checkPassword(password, opts?)` hashes the input,
slices the 5-hex prefix, dispatches `GET https://api.pwnedpasswords.com/range/<prefix>`
with the mandatory `Add-Padding: true` header, scans the streamed
response for a matching 35-char suffix, and returns
`{ pwned, count }`. It owns the strict / off framing, the NTLM mode
opt-in, the differential-privacy decoy fan-out, the AbortSignal
threading, and the OTel emission.
## Features
- Mandatory `Add-Padding: true` on every fetch — including every
differential-privacy decoy.
- SHA-1 (default) and NTLM (caller-injected adapter) hash modes.
- Constant-time suffix compare on every parsed line.
- Streaming line parser (no `Response.text()` call ever).
- Differential-privacy decoy fan-out when `extraPrefixes > 0` — real
prefix's response is the only one consulted.
- AbortSignal threaded into fetch and the streaming parser.
- OTel histograms for duration; counters for outcome, errors,
throttling.
- Optional `assertOutgoingRequestSafe: true` runtime privacy gate.
## Usage: Basic Example
```ts
import { RangeClient } from "@suaveplan/hibp";
const client = new RangeClient();
const { pwned, count } = await client.checkPassword("hunter2");
```
## Usage: Advanced Example
```ts
import { RangeClient } from "@suaveplan/hibp";
const client = new RangeClient({
extraPrefixes: 3,
rng: myRng,
assertOutgoingRequestSafe: true,
strict: true,
});
const ac = new AbortController();
setTimeout(() => ac.abort(), 5_000);
const result = await client.checkPassword("hunter2", { signal: ac.signal });
```
## API Reference
- `CheckPasswordOptions` — `mode?`, `signal?`, `extraPrefixes?`.
- `RangeClientOptions` — `fetchFn`, `clock`, `rng`, `strict`,
`ntlmHash`, `extraPrefixes`, `assertOutgoingRequestSafe`.
- `new RangeClient(options?)`.
- `client.checkPassword(password, opts?): Promise<PwnedResult>`.
## Implementation Notes
The class is stateless beyond its constructor options — every public
method takes the password and a per-call options bag, so a single
`RangeClient` instance is safe to share across a process. Error paths
funnel through the metrics emission so dashboards see counters even
for failures the caller catches and retries. The `assertOutgoingRequestSafe`
gate constructs a `Request` to feed into `assertNoLeak`, then re-issues
the actual fetch with the same `RequestInit` so the privacy check
exercises the real outgoing bytes. The NTLM adapter is required at
runtime if `mode: "ntlm"` is ever passed; a missing adapter surfaces as
`HIBP.MALFORMED_RESPONSE` because the caller has misconfigured the
client rather than the server having misbehaved.