Initial Commit
This commit is contained in:
56
openspec/archive/2026-05-26-api-auth-jwt/proposal.md
Normal file
56
openspec/archive/2026-05-26-api-auth-jwt/proposal.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# `@suaveplan/api-auth-jwt` — JWT session resolver
|
||||
|
||||
**Package**: `@suaveplan/api-auth-jwt`
|
||||
**Status**: PROPOSED
|
||||
**Type**: new-package
|
||||
**Stage**: 4 (Base adapters) — see umbrella `openspec/changes/api-plugin-foundation/`
|
||||
|
||||
## Why
|
||||
|
||||
Per design doc §2.3, auth is split into two distinct contracts: session resolution (`Request → Principal | null`) and account lifecycle (provider). `api-auth-jwt` implements only the session-resolver half — it verifies a JWT from an `Authorization: Bearer` header or cookie against a JWKS URL or static key using `@suaveplan/jws`, and projects the resulting claims onto a `Principal`. It is NOT a provider: no login/register/refresh routes. This is what you pair with hosted IdPs (Clerk, Auth0, Cognito) or with any self-hosted JWT-issuing provider.
|
||||
|
||||
Per Stage 4: ships both a direct callable surface and a worker-proxy surface (§5.2a). `runAuthSessionConformance` passes against both.
|
||||
|
||||
## What changes
|
||||
|
||||
Net-new package depending on `@suaveplan/api-auth` (contract), `@suaveplan/api-types`, `@suaveplan/api-worker-rpc`, `@suaveplan/jws`, `@suaveplan/error`, and `zod`.
|
||||
|
||||
- ADDED: `createJwtSessionResolver(opts)` — direct-surface factory returning an `AuthAdapter` (session-resolver only).
|
||||
- ADDED: `createJwtSessionResolverWorkerProxy(port, opts)` — proxy-surface factory.
|
||||
- ADDED: `JwtSessionResolverOptions` — Zod schema (`jwksUrl?: string`, `staticKey?: JsonWebKey`, `algorithms: string[]`, `audience?: string | string[]`, `issuer?: string | string[]`, `clockToleranceSec?: number`, `cookieName?: string`, `headerName?: string`, `claimToPrincipal?: (claims) => Principal`).
|
||||
- ADDED: `defaultClaimToPrincipal` — projects `sub`/`scope`/`scopes`/`tenant_id`/`tid` onto a `Principal`.
|
||||
- ADDED: `securitySchemeContribution()` — returns OpenAPI `securitySchemes` block describing the Bearer JWT scheme (consumed by `api-openapi` Stage 8).
|
||||
- ADDED: `AUTH_JWT_*` error codes (`AUTH_JWT_MISSING_TOKEN`, `AUTH_JWT_INVALID_SIGNATURE`, `AUTH_JWT_EXPIRED`, `AUTH_JWT_WRONG_AUDIENCE`, `AUTH_JWT_WRONG_ISSUER`, `AUTH_JWT_ALGORITHM_NOT_ALLOWED`, `AUTH_JWT_JWKS_FETCH_FAILED`, `AUTH_JWT_INVALID_OPTIONS`).
|
||||
- ADDED: JWKS caching with TTL + ETag revalidation; refresh on `kid` miss.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Account lifecycle (register/login/logout/refresh) — that's `auth.provider`, not this package. See `api-auth-better-auth` (Stage 6) and `api-auth-rolled` (Stage 8).
|
||||
- Cookie-based CSRF gating — the host's request pipeline (§6) triggers `Bun.CSRF` based on auth-adapter declaration; this package only declares whether cookie auth is in use.
|
||||
- Multi-resolver chaining — handled by `api-auth` core (Stage 1).
|
||||
|
||||
## Source mapping
|
||||
|
||||
Genesis-original. Source of design intent: `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md`.
|
||||
|
||||
| Requirement | Design doc section |
|
||||
|---|---|
|
||||
| Session resolver, not provider | §2.3 |
|
||||
| JWKS + static-key support | §2.3 (`api-auth-jwt` bullet) |
|
||||
| Worker-proxy variant | §5.2a |
|
||||
| Conformance both surfaces | §13.4 |
|
||||
| OpenAPI securityScheme contribution | §7 |
|
||||
|
||||
## Verification approach
|
||||
|
||||
- `src/factory/create-jwt-session-resolver.test.ts` — direct-surface tests against real `@suaveplan/jws`-signed tokens.
|
||||
- `src/factory/create-jwt-session-resolver.spec-conformance.test.ts` — `runAuthSessionConformance("jwt-direct", ...)`.
|
||||
- `src/proxy/create-jwt-session-resolver-worker-proxy.test.ts` — proxy unit tests over `MessageChannel`.
|
||||
- `src/proxy/create-jwt-session-resolver-worker-proxy.spec-conformance.test.ts` — `runAuthSessionConformance("jwt-worker-proxy", ...)`.
|
||||
- `src/jwks/jwks-cache.test.ts` — TTL, ETag, `kid` miss refresh.
|
||||
- `src/claim-mapping/default-claim-to-principal.test.ts` — claim projection, scope normalization, tenant extraction.
|
||||
- `tests/integration/integration.test.ts` — sign with `@suaveplan/jws`, verify through this resolver end-to-end.
|
||||
|
||||
## Migration impact
|
||||
|
||||
None — additive only.
|
||||
@@ -0,0 +1,101 @@
|
||||
<!-- markdownlint-disable MD024 -->
|
||||
|
||||
# Capability Spec Delta: api-auth-jwt (api-auth-jwt)
|
||||
|
||||
**Package**: `@suaveplan/api-auth-jwt`
|
||||
**Status**: PROPOSED
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Session-resolver-only surface
|
||||
|
||||
The package SHALL implement the `AuthAdapter` session-resolver contract from `@suaveplan/api-auth`. It MUST NOT register any HTTP routes — login/logout/refresh are provider responsibilities and live in separate adapters.
|
||||
|
||||
#### Scenario: factory exposes resolveSession but no route contributions
|
||||
|
||||
- **WHEN** `createJwtSessionResolver({ jwksUrl: "..." })` is called
|
||||
- **THEN** the returned adapter has `resolveSession` AND no `contributeRoutes` method AND `securitySchemeContribution()` returns a Bearer JWT entry
|
||||
|
||||
**Verified by:** `src/factory/create-jwt-session-resolver.test.ts::"exposes resolveSession and no route contributions"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: JWT verification against JWKS or static key
|
||||
|
||||
The package SHALL verify tokens using `@suaveplan/jws` against either a JWKS URL (with TTL + ETag caching) or a single static `JsonWebKey`. Algorithms MUST be restricted to the allowlist in `options.algorithms`; any token signed with a non-allowlisted algorithm MUST be rejected with `AUTH_JWT_ALGORITHM_NOT_ALLOWED`.
|
||||
|
||||
#### Scenario: token signed with disallowed alg is rejected
|
||||
|
||||
- **WHEN** a token signed with `HS256` is presented to a resolver whose `algorithms: ["RS256"]`
|
||||
- **THEN** `resolveSession()` returns `null` AND emits `AUTH_JWT_ALGORITHM_NOT_ALLOWED` on the failure counter
|
||||
|
||||
#### Scenario: JWKS `kid` miss triggers refresh
|
||||
|
||||
- **WHEN** a token's `kid` is not in the cached JWKS AND the cache is older than 0ms
|
||||
- **THEN** the resolver refetches the JWKS exactly once (in-flight dedup) AND retries verification
|
||||
|
||||
**Verified by:** `src/factory/create-jwt-session-resolver.test.ts::"rejects tokens signed with non-allowlisted algorithms"` AND `src/jwks/jwks-cache.test.ts::"kid miss triggers a single in-flight JWKS refresh"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Direct and worker-proxy surfaces both pass conformance
|
||||
|
||||
The adapter SHALL pass `runAuthSessionConformance` from `@suaveplan/api-auth/testing` under BOTH `createJwtSessionResolver` (direct) AND `createJwtSessionResolverWorkerProxy` (proxy). Neither surface may skip an invariant.
|
||||
|
||||
#### Scenario: direct surface conforms
|
||||
|
||||
- **WHEN** `runAuthSessionConformance("jwt-direct", () => createJwtSessionResolver(...))` runs
|
||||
- **THEN** every invariant passes
|
||||
|
||||
#### Scenario: worker-proxy surface conforms
|
||||
|
||||
- **WHEN** `runAuthSessionConformance("jwt-worker-proxy", () => createJwtSessionResolverWorkerProxy(channel.port2, ...))` runs over a real `MessageChannel`
|
||||
- **THEN** every invariant passes
|
||||
|
||||
**Verified by:** `src/factory/create-jwt-session-resolver.spec-conformance.test.ts::"jwt-direct conforms to AuthSession contract"` AND `src/proxy/create-jwt-session-resolver-worker-proxy.spec-conformance.test.ts::"jwt-worker-proxy conforms to AuthSession contract"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Claim → Principal projection is overridable
|
||||
|
||||
The package SHALL provide `defaultClaimToPrincipal` mapping `sub → id`, `scope`/`scopes` → `scopes[]`, `tenant_id`/`tid` → `tenantId`, remaining claims into `claims`. Callers MAY override via `options.claimToPrincipal`.
|
||||
|
||||
#### Scenario: custom mapper supplies tenantId from a non-standard claim
|
||||
|
||||
- **WHEN** `options.claimToPrincipal` reads `org_id` instead of `tenant_id`
|
||||
- **THEN** the produced `Principal.tenantId` reflects `org_id`
|
||||
|
||||
**Verified by:** `src/claim-mapping/default-claim-to-principal.test.ts::"custom claimToPrincipal overrides default tenantId extraction"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Token extraction honours header and cookie sources
|
||||
|
||||
The package SHALL extract the token from the configured header (default `Authorization: Bearer <jwt>`) or cookie (when `cookieName` is set). If both are present, header wins.
|
||||
|
||||
#### Scenario: cookie source produces a Principal
|
||||
|
||||
- **WHEN** `cookieName: "session"` is configured AND a request carries `Cookie: session=<jwt>`
|
||||
- **THEN** the resolver returns the projected `Principal`
|
||||
|
||||
#### Scenario: header takes precedence over cookie
|
||||
|
||||
- **WHEN** a request carries BOTH a valid Bearer header AND a valid cookie
|
||||
- **THEN** the Principal reflects the header token's claims
|
||||
|
||||
**Verified by:** `src/factory/create-jwt-session-resolver.test.ts::"extracts token from cookie when configured"` AND `src/factory/create-jwt-session-resolver.test.ts::"header source wins over cookie when both present"`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Options Zod-validated
|
||||
|
||||
`JwtSessionResolverOptions` MUST be Zod-validated. Constructing the resolver with no `jwksUrl` AND no `staticKey` MUST throw `AUTH_JWT_INVALID_OPTIONS` synchronously.
|
||||
|
||||
#### Scenario: missing key material throws
|
||||
|
||||
- **WHEN** `createJwtSessionResolver({} as never)`
|
||||
- **THEN** a `SuaveplanError` with code `AUTH_JWT_INVALID_OPTIONS` is thrown synchronously
|
||||
|
||||
**Verified by:** `src/options/jwt-session-resolver-options.test.ts::"throws when neither jwksUrl nor staticKey is supplied"`
|
||||
|
||||
<!-- markdownlint-enable MD024 -->
|
||||
73
openspec/archive/2026-05-26-api-auth-jwt/tasks.md
Normal file
73
openspec/archive/2026-05-26-api-auth-jwt/tasks.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# Tasks — `@suaveplan/api-auth-jwt`
|
||||
|
||||
> Every checkbox MUST reflect work actually done in this change.
|
||||
|
||||
## 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
|
||||
|
||||
- [x] 1.1 Read design doc (§2.3, §5.2a, §13.4)
|
||||
- [x] 1.2 Read `openspec/changes/api-auth/` for upstream contract
|
||||
- [x] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
|
||||
- [x] 1.4 Draft `proposal.md`
|
||||
- [x] 1.5 Draft `specs/api-auth-jwt/spec.md`
|
||||
- [x] 1.6 Every requirement carries `**Verified by:**`
|
||||
|
||||
## 2. Implementation
|
||||
|
||||
- [ ] 2.1 Scaffold `packages/api/api-auth-jwt/` (`"version": "0.1.0"`, `"sideEffects": false`, deps: api-auth, api-types, api-worker-rpc, jws, error, zod)
|
||||
- [ ] 2.2 `src/options/jwt-session-resolver-options.ts` — Zod schema
|
||||
- [ ] 2.3 `src/factory/create-jwt-session-resolver.ts` — direct surface
|
||||
- [ ] 2.4 `src/proxy/create-jwt-session-resolver-worker-proxy.ts` — proxy surface
|
||||
- [ ] 2.5 `src/jwks/jwks-cache.ts` — TTL + ETag + `kid` miss refresh
|
||||
- [ ] 2.6 `src/claim-mapping/default-claim-to-principal.ts` — `claims → Principal`
|
||||
- [ ] 2.7 `src/security-scheme/security-scheme-contribution.ts` — OpenAPI securitySchemes block
|
||||
- [ ] 2.8 `src/error-codes.ts` — `AUTH_JWT_*` codes via `defineCodes`
|
||||
- [ ] 2.9 `src/index.ts` — explicit named re-exports
|
||||
|
||||
## 3. Tests
|
||||
|
||||
- [ ] 3.1 `src/factory/create-jwt-session-resolver.test.ts`
|
||||
- [ ] 3.2 `src/factory/create-jwt-session-resolver.spec-conformance.test.ts` — `runAuthSessionConformance("jwt-direct", ...)`
|
||||
- [ ] 3.3 `src/proxy/create-jwt-session-resolver-worker-proxy.test.ts`
|
||||
- [ ] 3.4 `src/proxy/create-jwt-session-resolver-worker-proxy.spec-conformance.test.ts` — `runAuthSessionConformance("jwt-worker-proxy", ...)`
|
||||
- [ ] 3.5 `src/jwks/jwks-cache.test.ts`
|
||||
- [ ] 3.6 `src/claim-mapping/default-claim-to-principal.test.ts`
|
||||
- [ ] 3.7 `src/security-scheme/security-scheme-contribution.test.ts`
|
||||
- [ ] 3.8 `tests/integration/integration.test.ts`
|
||||
- [ ] 3.9 Every `it(...)` carries `{ timeout: 5000 }` (30000 if genuinely async)
|
||||
|
||||
## 4. Documentation
|
||||
|
||||
- [ ] 4.1 Sibling `.md` per implementation `.ts` (≥200 words, basic + advanced)
|
||||
- [ ] 4.2 README links co-located `.md` files
|
||||
- [ ] 4.3 Document the pair-with-IdP usage pattern (Clerk/Auth0/Cognito)
|
||||
|
||||
## 5. Pre-archive verification (5-gate triple)
|
||||
|
||||
- [ ] 5.1 `bun run check` — clean
|
||||
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/api-auth-jwt` — green
|
||||
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-auth-jwt` — 100/100/100/100
|
||||
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/api-auth-jwt` — exit 0
|
||||
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/api-auth-jwt` — green
|
||||
|
||||
## 6. Pre-archive 7-row checklist
|
||||
|
||||
- [ ] 6.1 Generics on `AuthAdapter` signature; `expectTypeOf` assertions on `Principal` projection
|
||||
- [ ] 6.2 Zod schema at the `JwtSessionResolverOptions` boundary
|
||||
- [ ] 6.3 Every `AUTH_JWT_*` code thrown by at least one production path
|
||||
- [ ] 6.4 Strict-mode behaviors (audience/issuer required vs optional) tested both on and off
|
||||
- [ ] 6.5 OTel instruments (`api.auth.resolve_duration_ms`, `api.auth.failures_total{reason}`) asserted with in-memory `MeterProvider`
|
||||
- [ ] 6.6 JWKS in-flight refresh dedup tested (concurrent `kid` misses → one network fetch)
|
||||
- [ ] 6.7 No retroactive tick
|
||||
|
||||
## 7. Archive
|
||||
|
||||
- [ ] 7.1 Fold into `openspec/specs/api-auth-jwt/spec.md`
|
||||
- [ ] 7.2 Move to `openspec/archive/<yyyy-mm-dd>-api-auth-jwt/`
|
||||
- [ ] 7.3 Tick Stage 4 box in umbrella tasks
|
||||
- [ ] 7.4 Refresh `MANIFEST.md`
|
||||
Reference in New Issue
Block a user