Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,102 @@
# OpenSpec Change: qrcode-scan
**Package**: `@suaveplan/qrcode` (adds `/scan` subpath)
**Status**: PROPOSED
**Type**: feature
## Why
`@suaveplan/qrcode` is currently generation-only. Vaulted needs to import TOTP secrets by scanning QR codes from camera streams or image uploads. Rather than creating a standalone package that would duplicate QR matrix data structures, the decision is to extend the existing `@suaveplan/qrcode` package with a tree-shakeable `/scan` subpath.
## What changes
- ADDED: `src/scan/scan.ts` — `scanFromImageData(imageData)` decodes a QR code from `ImageData`, `Uint8Array`, `Blob`, or `File`
- ADDED: `src/scan/scan-camera.ts` — `scanFromCameraStream(stream, options?)` extracts frames from a `MediaStream` and attempts decode
- ADDED: `src/scan/totp-extract.ts` — `extractTotpUri(data)` parses `otpauth://totp/` URIs into structured config
- ADDED: `src/scan/totp-types.ts` — `TotpConfig`, `TotpAlgorithm`, `OtpAuthUri`
- ADDED: Subpath export `./scan/scan` in `package.json`
- ADDED: `QrScanError` extends `QrError` (code `QRCODE.DECODE_FAILED`)
- ADDED: `CameraAccessError` extends `QrScanError` (code `QRCODE.CAMERA_ACCESS_DENIED`)
- ADDED: `TotpUriParseError` extends `QrScanError` (code `QRCODE.TOTP_PARSE_ERROR`)
- ADDED: Injectable `clock?: Clock` in `scanFromCameraStream` options for deterministic frame-interval timing in tests
- ADDED: Zod schemas for `TotpConfig` and camera options
- ADDED: OTel counter `qrcode.scan.total` (by `source`, `outcome`) and histogram `qrcode.scan.duration_ms`
## Out of scope
- Real-time continuous scanning UI components (Vaulted app concern, not library)
- Barcode formats other than QR (use `@suaveplan/barcode`)
- Video recording, snapshot capture, or `<canvas>` rendering helpers (consume browser APIs directly)
- Native camera integration on mobile (Capacitor Camera plugin is a separate abstraction layer)
## Gap analysis: sub-standard → enterprise
Most QR scanning libraries in the npm ecosystem pull in heavy WebAssembly binaries or camera UI widgets that bloat bundles and tie the code to browser-only environments. They often lack frame-rate throttling, leak `MediaStream` resources on unmount, and provide no structured extraction for TOTP URIs. Enterprise-grade code must keep the decoder lightweight and tree-shakeable, manage camera lifecycle explicitly, and return strongly-typed TOTP config rather than raw strings.
## Security model
- **Threat model**: Malicious QR payloads exploiting URI parser bugs to inject JavaScript or redirect to phishing domains; camera stream frames intercepted by compromised browser extensions; resource exhaustion via high-frequency decode loops.
- **Privacy guarantees**: Camera frames are processed in-memory and never persisted to disk or transmitted. TOTP secrets extracted from QR codes are returned to the consumer without logging or retention.
- **Input validation**: `otpauth://` URIs validated against strict Zod schema before returning `TotpConfig`; unknown URI schemes rejected explicitly. Rejects `javascript:` and other non-`otpauth:` schemes in parsed URIs.
- **Side-channel resistance**: Decode timing is not correlated with secret content; constant-time URI component extraction where feasible.
- **Key material handling**: Extracted TOTP secrets are handled as opaque strings and passed immediately to the consumer; no key derivation or storage occurs in this package.
## Performance SLOs
- **Latency**: P95 single-frame decode < 100ms on a mid-tier laptop; camera stream first detection < 2s.
- **Throughput**: Sustained 30 fps frame sampling without dropping frames or blocking the main thread.
- **Memory bounds**: Peak memory per decode < 2 MB; camera stream buffer bounded by frame queue depth.
- **Bundle size budget**: Scan subpath < 25 kB gzipped (decoder + TOTP extractor); no WASM or heavy CV dependencies.
## Observability plan
- **OTel spans/metrics**: Counter `qrcode.scan.total` by `source` and `outcome`; histogram `qrcode.scan.duration_ms`; gauge for camera stream active duration.
- **Structured logging**: JSON logs at `warn` for camera permission denial, `error` for decode failures, `debug` for successful scans.
- **Error telemetry**: Distinct codes (`CAMERA_ACCESS_DENIED`, `TOTP_PARSE_ERROR`) with platform context and frame source.
- **Health checks**: Expose `scanFromCameraStream.isHealthy()` returning false after repeated decode failures or stream errors.
## Dependency audit
- **Runtime deps**: `@suaveplan/qrcode` (shared matrix types), `@suaveplan/errors`, `@suaveplan/otel`; decoder is pure TypeScript with no heavy CV libraries.
- **Supply-chain risk**: No WASM binaries or native modules; all dependencies are first-party or platform APIs.
- **Tree-shakeability**: `scanFromImageData`, `scanFromCameraStream`, and `extractTotpUri` are individually tree-shakeable.
- **License**: All code MIT-licensed; no copyleft dependencies.
## Operational readiness
- **Graceful degradation**: If camera access is denied, the consumer can fall back to file upload. If decode fails, return a typed error rather than throwing.
- **Resource limits**: Frame extraction rate limited by configurable throttle; max decode attempts per stream bounded.
- **Error recovery**: Automatic `MediaStream` cleanup on unmount or error; retry with backoff on transient camera glitches.
- **Backpressure**: Frame queue drops oldest frames when decoder is slower than capture rate; prevents unbounded memory growth.
- **Version compatibility**: Public API frozen after v1; additive-only changes; deprecated APIs supported for two major versions.
## Verification approach
- **100% coverage target**: All exported functions, branches, and error paths instrumented in test.
- **Property-based tests**: QR payload generation, URI parsing edge cases, and frame buffer backpressure tested with fast-check invariants.
- **Load/stress criteria**: Sustained 30 fps decode for 60s without memory growth > 10% or frame drops > 1%.
- **Security audit checklist**: Malformed URI injection, oversized image payload handling, camera stream cleanup on error, secret leakage in logs.
- `src/scan/scan.test.ts` — covers decode from ImageData, Uint8Array, File, no-QR error
- `src/scan/scan-camera.test.ts` — covers frame extraction, permission denial, stream ended
- `src/scan/totp-extract.test.ts` — covers valid otpauth URI, missing secret, malformed URI
- `src/scan/scan.spec-conformance.test.ts` — pins type-level contracts, strict-mode behaviors, OTel emission
- `tests/dep-graph.test.ts` — pins dependency invariants
## Migration impact
None — additive only. Existing `@suaveplan/qrcode` consumers are unaffected because all new code is behind the `./scan/scan` subpath export.
## Impact
### Downstream consumers
Run `bunx turbo ls --filter=...@suaveplan/qrcode` to enumerate.
### Breaking changes
None — additive only.
### Workspace dep prerequisites
- `@suaveplan/errors`
- `@suaveplan/otel`

View File

@@ -0,0 +1,145 @@
# Capability Spec Delta: qrcode-scan
**Package**: `@suaveplan/qrcode` (`/scan` subpath)
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time. No exceptions.
## ADDED Requirements
### Requirement: Image decode from multiple input types
`scanFromImageData(input)` MUST accept `ImageData`, `Uint8Array`, `Blob`, or `File`. It MUST decode the QR code matrix and return the raw payload string. If no QR code is found, `QrScanError` (code `QRCODE.DECODE_FAILED`) MUST be thrown.
#### Scenario: Decode from ImageData
- **WHEN** `scanFromImageData` receives an `ImageData` object containing a valid QR code
- **THEN** it returns the decoded string payload
#### Scenario: Decode from File
- **WHEN** `scanFromImageData` receives a `File` object containing a valid QR code
- **THEN** it returns the decoded string payload
#### Scenario: No QR code found
- **WHEN** `scanFromImageData` receives an image with no QR code
- **THEN** it throws `QrScanError` with code `QRCODE.DECODE_FAILED`
**Verified by:** `src/scan/scan.test.ts::"decodes QR code from ImageData"` AND `src/scan/scan.test.ts::"decodes QR code from File"` AND `src/scan/scan.test.ts::"throws QrScanError when no QR code is found"`
---
### Requirement: Camera stream access
`scanFromCameraStream(stream, options?)` MUST accept a `MediaStream` and extract video frames at a configurable interval (default 250 ms). It MUST attempt to decode a QR code from each frame. On first successful decode, it MUST return the payload and stop frame extraction. If `options.signal` aborts, it MUST reject with an abort error. If the stream ends without a successful decode, it MUST throw `QrScanError` (code `QRCODE.DECODE_FAILED`).
#### Scenario: Successful decode from camera stream
- **WHEN** `scanFromCameraStream` receives a stream where one frame contains a valid QR code
- **THEN** it returns the payload after processing that frame
#### Scenario: Abort signal stops scanning
- **WHEN** `options.signal` aborts before a QR code is found
- **THEN** the promise rejects with an abort error
#### Scenario: Stream ends without decode
- **WHEN** the stream ends and no frame contained a QR code
- **THEN** it throws `QrScanError` with code `QRCODE.DECODE_FAILED`
**Verified by:** `src/scan/scan-camera.test.ts::"returns payload when QR code appears in stream"` AND `src/scan/scan-camera.test.ts::"rejects when abort signal fires before decode"` AND `src/scan/scan-camera.test.ts::"throws QrScanError when stream ends without finding QR code"`
---
### Requirement: Injectable Clock for deterministic camera timing
`scanFromCameraStream` options MUST include an optional `clock?: Clock`. When provided, frame extraction intervals and timeout deadlines MUST be driven by the injected clock instead of the global time source.
**Verified by:** `src/scan/scan-camera.test.ts::"uses injected clock for frame intervals"` AND `src/scan/scan-camera.test.ts::"uses injected clock for stream timeout"`
---
### Requirement: TOTP URI extraction
`extractTotpUri(data)` MUST parse `otpauth://totp/` URIs per the de-facto Google Authenticator Key URI Format. It MUST return a `TotpConfig` with:
- `secret` (required) — base32-encoded secret
- `issuer` (optional) — issuer name
- `account` (optional) — account name
- `algorithm` (optional, default `SHA1`) — `SHA1 | SHA256 | SHA512`
- `digits` (optional, default `6`) — `6 | 7 | 8`
- `period` (optional, default `30`) — seconds as integer
If `secret` is missing or the URI scheme is not `otpauth://totp/`, `TotpUriParseError` (code `QRCODE.TOTP_PARSE_ERROR`) MUST be thrown with `context.rawUri` populated.
#### Scenario: Valid TOTP URI
- **WHEN** `extractTotpUri` receives `"otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example"`
- **THEN** it returns a `TotpConfig` with all fields correctly populated
#### Scenario: Missing secret
- **WHEN** `extractTotpUri` receives `"otpauth://totp/Example:alice@google.com?issuer=Example"`
- **THEN** it throws `TotpUriParseError`
#### Scenario: Invalid scheme
- **WHEN** `extractTotpUri` receives `"https://example.com"`
- **THEN** it throws `TotpUriParseError`
**Verified by:** `src/scan/totp-extract.test.ts::"parses valid otpauth URI into TotpConfig"` AND `src/scan/totp-extract.test.ts::"throws TotpUriParseError when secret is missing"` AND `src/scan/totp-extract.test.ts::"throws TotpUriParseError for non-otpauth scheme"`
---
### Requirement: Subpath export configuration
The `package.json` `exports` map MUST include an entry for `./scan/scan` so consumers can import scan functionality without pulling in generation code:
```json
"./scan/scan": {
"import": { "types": "./dist/scan/scan.d.ts", "default": "./dist/scan/scan.js" }
}
```
#### Scenario: Tree-shakeable import
- **WHEN** a consumer imports from `@suaveplan/qrcode/scan/scan`
- **THEN** only scan-related code is included in the bundle
**Verified by:** `tests/dep-graph.test.ts::"scan subpath is tree-shakeable and does not import generator modules"`
---
### Requirement: Structured errors
All scan-related thrown errors MUST extend `QrScanError` which extends `QrError`. The following codes MUST be defined in the existing `qrcode` error code registry:
- `QRCODE.CAMERA_ACCESS_DENIED` — camera permission was denied or stream could not be obtained
- `QRCODE.TOTP_PARSE_ERROR` — the decoded data is not a valid `otpauth://totp/` URI
`QrScanError`, `CameraAccessError`, and `TotpUriParseError` MUST be exported from the `./scan/scan` subpath.
**Verified by:** `src/scan/scan.spec-conformance.test.ts::"all scan errors extend QrScanError"` AND `src/scan/scan.spec-conformance.test.ts::"camera access error code is registered"`
---
### Requirement: Observability
The following metrics MUST be emitted via `@opentelemetry/api` using meter name `@suaveplan/qrcode`:
- Counter `qrcode.scan.total` with attributes `source` (`image` / `camera`) and `outcome` (`success` / `error` / `not_found`)
- Histogram `qrcode.scan.duration_ms` recorded on every `scanFromImageData` and `scanFromCameraStream` call
All instruments MUST be no-ops when no OTel metric exporter is configured.
**Verified by:** `src/scan/scan.spec-conformance.test.ts::"emits scan total counter with correct attributes on success"` AND `src/scan/scan.spec-conformance.test.ts::"emits scan duration histogram on every call"`
---
### Requirement: 100% coverage
Vitest thresholds for the `@suaveplan/qrcode` package MUST remain at 100/100/100/100 after adding the scan subpath. No `.skip` or `.only` is permitted in `src/scan/`.
**Verified by:** `vitest.config.ts` AND `src/scan/scan.test.ts` (all branches covered)

View File

@@ -0,0 +1,72 @@
# Tasks — qrcode-scan
> Every checkbox MUST reflect work actually done in this change. Do not retroactively tick boxes for work that was already in main when this change opened.
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Spec authoring
- [ ] 1.1 Read `MIGRATION.md` Section 4.5 for source requirements (skip enterprise — genesis-original)
- [ ] 1.2 Read `openspec/specs/qrcode/spec.md` (existing capability)
- [ ] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
- [ ] 1.4 Draft `proposal.md` from `openspec/templates/proposal.md`
- [ ] 1.5 Confirm no `## Source mapping` section (genesis-original)
- [ ] 1.6 Draft `specs/qrcode-scan/spec.md` from `openspec/templates/spec-delta.md`
- [ ] 1.7 Every requirement in the spec delta carries a `**Verified by:**` line naming concrete `it(...)` titles
## 2. Implementation
- [ ] 2.1 Add `src/scan/scan.ts` — `scanFromImageData` decode entry point
- [ ] 2.2 Add `src/scan/scan-camera.ts` — `scanFromCameraStream` frame extraction wrapper
- [ ] 2.3 Add `src/scan/totp-extract.ts` — `extractTotpUri` otpauth parser
- [ ] 2.4 Add `src/scan/totp-types.ts` — `TotpConfig`, `TotpAlgorithm`, `OtpAuthUri`
- [ ] 2.5 Add `src/scan/scan-schemas.ts` — Zod schemas for boundary types
- [ ] 2.6 Add error codes `QRCODE.DECODE_FAILED`, `QRCODE.CAMERA_ACCESS_DENIED`, and `QRCODE.TOTP_PARSE_ERROR` to existing `src/error-codes.ts`
- [ ] 2.7 Add `src/scan/qr-scan-error.ts`, `camera-access-error.ts`, `totp-uri-parse-error.ts`
- [ ] 2.8 Add `src/scan/telemetry.ts` — OTel instruments for scan operations
- [ ] 2.9 Register `./scan/scan` subpath export in `package.json`
- [ ] 2.10 Update barrel `src/index.ts` if scan symbols are re-exported from root
- [ ] 2.11 Add `src/scan/clock.ts` — injectable `Clock` for deterministic frame-interval timing in tests
## 3. Tests
- [ ] 3.1 Unit tests at `src/scan/scan.test.ts` covering every scenario
- [ ] 3.2 Unit tests at `src/scan/scan-camera.test.ts` covering every scenario
- [ ] 3.3 Unit tests at `src/scan/totp-extract.test.ts` covering every scenario
- [ ] 3.4 Spec-conformance tests at `src/scan/scan.spec-conformance.test.ts` pinning type-level / observability / strict-mode scenarios
- [ ] 3.5 Integration / contract tests where the spec demands them
- [ ] 3.6 Every `it(...)` carries `{ timeout: 5000 }` (or 30000 for genuinely async)
## 4. Documentation
- [ ] 4.1 Sibling `.md` for every new implementation `.ts` (≥200 words, basic + advanced examples, full API reference)
- [ ] 4.2 Update `README.md` to list `./scan/scan` under `## Modules`
- [ ] 4.3 Update `CLAUDE.md` package listing if public surface changed
## 5. Pre-archive verification (the 5-gate triple)
- [ ] 5.1 `bun run check` — Biome 0 errors / 0 warnings / 0 info across the whole monorepo
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/qrcode` — green
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/qrcode` — 100/100/100/100
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/qrcode` — exit 0, no `error` findings
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/qrcode` — green
## 6. Pre-archive 7-row checklist (AGENTS.md Section 13)
- [ ] 6.1 Generics threaded; `expectTypeOf` assertions on every literal-type claim
- [ ] 6.2 Zod schemas wired at every declared boundary
- [ ] 6.3 Every error code in `error-codes.ts` thrown by at least one production path
- [ ] 6.4 Strict-mode behaviors tested both on and off
- [ ] 6.5 OTel instruments emitted from production paths and asserted with a real in-memory `MeterProvider`
- [ ] 6.6 Lifecycle dedup tested where claimed (in-flight Promise, idempotent set/load)
- [ ] 6.7 No retroactive tick — every box above reflects work done in this change
## 7. Archive
- [ ] 7.1 Fold spec delta into `openspec/specs/qrcode/spec.md`
- [ ] 7.2 Move `openspec/changes/qrcode-scan/` → `openspec/archive/<yyyy-mm-dd>-qrcode-scan/`
- [ ] 7.3 Refresh `MANIFEST.md` if package set or deps changed