Skip to content

Commit c8ba311

Browse files
docs: add CLAUDE.md agent guidelines for auth0-spa-js (#1651)
## Summary Adds AI-agent onboarding docs for auth0-spa-js, generated by the `generating-claude-md` skill and tailored to this repo. **Note** : this repo was where we iterated on and finalised the CLAUDE.md template itself, so the branch carries many incremental commits from that back-and-forth. With the finished skill, regenerating CLAUDE.md now would land as a single commit. - **`CLAUDE.md`** — the canonical, lean guidelines file: a concrete agent persona, core commands, testing conventions (Jest unit + Cypress against a local mock OIDC provider), three-tier boundaries, browser-security notes (PKCE, web-worker token isolation, DPoP), and the `MIGRATION_GUIDE.md` breaking-change rule. - **`AGENTS.md`** — now references `@CLAUDE.md` so non-Claude agents (Codex, Gemini) read one source of truth (replaces the older standalone AGENTS.md; its architecture/tribal knowledge was folded into CLAUDE.md). ## Notes - Every command was verified against `package.json` and the CI workflows; every file path referenced in `CLAUDE.md` resolves on disk. - The telemetry rule is scoped to **new request paths** (not every feature) and points at the existing `src/api.ts` `Auth0-Client` header, preserving the `auth0Client` wrapping of `@auth0/auth0-auth-js`. - No `docs/` offload — `docs/` holds generated TypeDoc output and the SDK is a lean single package, so the file stays inline. - No source code touched — documentation only. ## Test plan - [ ] Review `CLAUDE.md` for accuracy against the current SDK surface - [ ] Confirm the boundaries/security notes match current DPoP + refresh-token behavior <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Consolidated contributor guidance into a single, more complete reference via a new AI Agent Guidelines document. * Replaced the prior project overview with a brief pointer to the new single source of coding guidelines. * Added a command reference with ready-to-run build, test (unit and Cypress), lint, and release/publish commands. * Added a “Common Pitfalls” guide focused on SPA security, browser constraints, and bundle/correctness gotchas. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Prince Mathew <17837162+pmathew92@users.noreply.github.com>
1 parent ef2ae8a commit c8ba311

8 files changed

Lines changed: 363 additions & 123 deletions

File tree

AGENTS.md

Lines changed: 3 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -1,125 +1,5 @@
1-
## Project Overview
1+
# AI Agent Guidelines for auth0-spa-js
22

3-
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE. This is a TypeScript library that provides authentication functionality for browser-based applications.
3+
@./CLAUDE.md for all coding guidelines, commands, project structure, code style, testing conventions, and boundaries.
44

5-
## Common Commands
6-
7-
```bash
8-
# Install dependencies
9-
npm install
10-
11-
# Development (starts dev server at http://localhost:3000 with live reload)
12-
npm start # or npm run dev
13-
14-
# Build production bundles
15-
npm run build
16-
17-
# Run unit tests
18-
npm run test
19-
20-
# Run a single test file
21-
npx jest __tests__/path/to/test.test.ts
22-
23-
# Run tests matching a pattern
24-
npx jest --testNamePattern="pattern"
25-
26-
# Run tests in watch mode
27-
npm run test:watch
28-
29-
# Run integration tests (Cypress)
30-
npm run test:integration
31-
32-
# Run integration tests in watch mode
33-
npm run test:watch:integration
34-
35-
# Lint
36-
npm run lint
37-
38-
# Generate documentation
39-
npm run docs
40-
```
41-
42-
## Project Structure
43-
44-
```
45-
src/
46-
├── Auth0Client.ts # Main SDK entry point and public API
47-
├── Auth0Client.utils.ts # Helper functions for Auth0Client
48-
├── api.ts # Token endpoint API calls
49-
├── cache/ # Token caching implementations (memory, localStorage)
50-
├── dpop/ # DPoP proof-of-possession implementation
51-
├── mfa/ # Multi-factor authentication client
52-
├── worker/ # Web worker for secure token refresh
53-
├── storage.ts # Cookie and session storage abstractions
54-
├── errors.ts # Custom error classes
55-
├── global.ts # TypeScript interfaces and types
56-
├── utils.ts # Crypto, encoding, and general utilities
57-
└── index.ts # Public exports
58-
59-
__tests__/ # Unit tests (Jest)
60-
├── Auth0Client/ # Tests organized by Auth0Client method
61-
├── cache/ # Cache implementation tests
62-
├── dpop/ # DPoP tests
63-
└── mfa/ # MFA client tests
64-
65-
cypress/ # Integration tests (Cypress)
66-
├── e2e/ # End-to-end test specs
67-
└── support/ # Test utilities and commands
68-
69-
scripts/ # Build and dev scripts
70-
└── oidc-provider.mjs # Mock OIDC server for integration tests
71-
72-
static/ # Static files for dev server testing
73-
dist/ # Build output (generated)
74-
```
75-
76-
## Architecture
77-
78-
### Core Components
79-
80-
- **Auth0Client** (`src/Auth0Client.ts`): Main client class that orchestrates all authentication operations. Uses PKCE for secure authorization code flow.
81-
82-
- **CacheManager** (`src/cache/`): Token caching system with multiple storage backends:
83-
- `InMemoryCache`: Default, stores tokens in memory
84-
- `LocalStorageCache`: Persists tokens to localStorage
85-
- Supports custom cache implementations via `ICache` interface
86-
87-
- **TransactionManager** (`src/transaction-manager.ts`): Manages state during redirect flows, storing PKCE verifiers and app state in session storage or cookies.
88-
89-
- **MfaApiClient** (`src/mfa/`): Multi-factor authentication operations (enroll, challenge, verify). Wraps `@auth0/auth0-auth-js` MFA client.
90-
91-
- **Dpop** (`src/dpop/`): DPoP (Demonstrating Proof of Possession) implementation for cryptographically binding tokens.
92-
93-
- **Fetcher** (`src/fetcher.ts`): HTTP client wrapper with automatic auth header injection and DPoP proof generation.
94-
95-
### Token Refresh Strategy
96-
97-
The SDK supports two token refresh mechanisms:
98-
1. **Refresh Tokens** (`useRefreshTokens: true`): Uses refresh_token grant with optional web worker for secure storage
99-
2. **Silent Authentication**: Uses hidden iframe with `prompt=none` (requires custom domain for third-party cookie issues)
100-
101-
### Web Worker
102-
103-
`src/worker/token.worker.ts`: Handles token refresh in a web worker when using refresh tokens with in-memory cache, preventing token exposure in main thread.
104-
105-
### Build Output
106-
107-
Rollup bundles the SDK into multiple formats:
108-
- UMD (browser): `dist/auth0-spa-js.production.js`
109-
- ESM: `dist/auth0-spa-js.production.esm.js`
110-
- CJS: `dist/lib/auth0-spa-js.cjs.js`
111-
- Worker: `dist/auth0-spa-js.worker.production.js`
112-
113-
## Testing
114-
115-
- **Unit tests**: `__tests__/` directory, using Jest with jsdom environment
116-
- **Integration tests**: `cypress/e2e/` directory, testing against a mock OIDC provider (`scripts/oidc-provider.mjs`)
117-
118-
Test files follow the pattern `__tests__/[module]/[feature].test.ts` or `__tests__/Auth0Client/[method].test.ts`.
119-
120-
## Key Dependencies
121-
122-
- `@auth0/auth0-auth-js`: Foundational OAuth/MFA client
123-
- `browser-tabs-lock`: Cross-tab locking for token refresh
124-
- `dpop`: DPoP proof generation (RFC 9449)
125-
- `es-cookie`: Cookie handling
5+
This file exists so that non-Claude AI agents (Codex CLI, Gemini CLI, etc.) read the same instructions. All guidelines are maintained in a single place (`CLAUDE.md`) to avoid duplication and drift.

CLAUDE.md

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# AI Agent Guidelines for auth0-spa-js
2+
3+
This document provides context and guidelines for AI coding assistants working with the auth0-spa-js codebase.
4+
5+
## Your Role
6+
7+
You are a TypeScript SDK engineer working on auth0-spa-js, the Auth0 authentication SDK for browser-based single-page applications. You write small, well-tested, tree-shakeable code, and you keep the browser SPA use case — where the SDK runs in a hostile environment — front of mind.
8+
9+
---
10+
11+
## Working Principles
12+
13+
Apply these on every task in this repo — they keep changes correct, small, and reviewable.
14+
15+
- **Think before coding.** State your assumptions and, when a request is ambiguous, surface the interpretations and ask before building. Recommend a simpler approach when you see one. A clarifying question up front beats a wrong implementation.
16+
- **Simplicity first.** Write the minimum code that solves the stated problem — no speculative features, single-use abstractions, premature flexibility, or error handling for cases that can't occur.
17+
- **Surgical changes.** Touch only what the request requires. Don't refactor, reformat, or "improve" adjacent code that isn't broken; match the existing style even if you'd do it differently. Every changed line should trace directly to the request. Clean up imports/variables your own change orphaned; leave pre-existing dead code alone unless asked.
18+
- **Goal-driven execution.** Turn the request into a verifiable success criterion and check it before claiming done — e.g. "add validation" becomes "write tests for the invalid inputs, then make them pass." Don't report success you haven't verified.
19+
20+
---
21+
22+
## Project Overview
23+
24+
**auth0-spa-js** is the Auth0 SDK for Single-Page Applications — authorization-code + PKCE login, token caching, and silent refresh in the browser.
25+
26+
- **Language:** TypeScript (compiled to ES2017 UMD/ESM/CJS + worker bundles via Rollup)
27+
- **Package manager:** npm (CI builds on Node 22)
28+
- **Test:** Jest (unit, jsdom) + Cypress (integration, against a local mock OIDC provider)
29+
- **Dependencies:** `@auth0/auth0-auth-js` (foundational OAuth/MFA client), `dpop` (RFC 9449 proofs), `browser-tabs-lock`, `es-cookie` — see `package.json` (the authoritative, never-stale source)
30+
31+
---
32+
33+
## Project Structure
34+
35+
```text
36+
src/
37+
├─ index.ts # entry point — createAuth0Client() factory + re-exports
38+
├─ Auth0Client.ts # main client; orchestrates PKCE authorization-code flow
39+
├─ global.ts # public types (Auth0ClientOptions, etc.)
40+
├─ api.ts # token endpoint calls + Auth0-Client telemetry header
41+
├─ cache/ # ICache + InMemoryCache / LocalStorageCache
42+
├─ transaction-manager.ts # PKCE verifier + app state across redirects
43+
├─ dpop/ # DPoP proof generation (RFC 9449)
44+
├─ mfa/ # MFA client (wraps @auth0/auth0-auth-js)
45+
├─ myaccount/ # MyAccount API client
46+
├─ passkey/ # passkey (WebAuthn) enrollment + login
47+
├─ http.ts # low-level fetch: timeout, retry, DPoP; switchFetch() worker/non-worker routing
48+
├─ fetcher.ts # HTTP wrapper: auth header + DPoP injection
49+
└─ worker/token.worker.ts # refreshes tokens off the main thread
50+
__tests__/ # Jest unit specs (mirror src/) cypress/ # e2e
51+
docs/ # generated TypeDoc output (do not hand-edit)
52+
```
53+
54+
Key files: `src/index.ts` (entry), `src/Auth0Client.ts` (core), `src/api.ts` (telemetry header lives here), `src/errors.ts` (error hierarchy, rooted at `GenericError`).
55+
56+
---
57+
58+
## Boundaries
59+
60+
### ✅ Always Do
61+
62+
- Run `npm test` and `npm run lint` before committing
63+
- Add Jest specs for new behavior; keep code ES2017-clean (`npm run test:es-check`) and tree-shakeable
64+
- Update `README.md` and `EXAMPLES.md` in the same PR when changing the public API, options, or supported integration patterns
65+
- Keep the version in sync across its sources — `.version`, `src/version.ts`, `package.json`, and the `README.md` / `FAQ.md` pins (wired via `.shiprc`). Reference these files rather than pasting a version number into prose.
66+
- When adding a **new request path to Auth0** (not every feature — most ride on the shared transport), route it through the existing `src/api.ts` fetch layer so it carries the `Auth0-Client` header (base64 `{name,version,env}`) — don't create a separate HTTP client. Since this SDK wraps `@auth0/auth0-auth-js`, preserve the `auth0Client` wrapping (this SDK's name/version, the wrapped lib under `env`) and the opt-out.
67+
68+
### ⚠️ Ask First
69+
70+
- **Any breaking change — always ask first.** Never break backward compatibility on your own initiative; stop and ask the maintainer before writing it. (On approval, document the upgrade path in the migration guide for the target major.)
71+
- Adding/bumping runtime dependencies (they ship in the browser bundle — watch bundle size)
72+
- Modifying the public API on `Auth0Client` / `createAuth0Client` / `global.ts`
73+
- Changes to token storage, DPoP proof generation, PKCE, or the web-worker refresh path
74+
- Changes to `.github/workflows/` or the Rollup build config
75+
76+
### 🚫 Never Do
77+
78+
- Commit secrets, API keys, or tokens
79+
- Log or expose `access_token` / `refresh_token` / `id_token` — especially not to the main thread when the web worker is in use
80+
- Disable PKCE, or weaken DPoP proofs
81+
- Hand-edit `dist/` or `docs/` (generated build/TypeDoc output)
82+
- Remove or skip failing tests instead of fixing them
83+
84+
---
85+
86+
## Security Considerations
87+
88+
- **PKCE:** always used for the authorization-code flow — never expose an option to disable it.
89+
- **Token storage:** in-memory by default (`InMemoryCache`); `LocalStorageCache` is opt-in and documented as higher-risk. With refresh tokens + in-memory cache, refresh happens in a **web worker** (`src/worker/token.worker.ts`) to keep tokens off the main thread.
90+
- **DPoP:** `src/dpop/` binds tokens to a key pair (RFC 9449); `fetcher.ts` attaches the proof. Don't bypass it when DPoP is enabled.
91+
- **Silent auth:** hidden-iframe `prompt=none` needs a custom domain to survive third-party-cookie restrictions.
92+
93+
---
94+
95+
> The sections below are **reference** — each keeps a one-line anchor inline and offloads its body to `references/*.md` behind a linked pointer. Read a pointer only when the task needs it.
96+
97+
## Commands
98+
99+
```bash
100+
# Unit tests (with coverage)
101+
npm test
102+
103+
# Lint
104+
npm run lint
105+
106+
# Dev server with live reload (http://localhost:3000)
107+
npm run dev
108+
109+
# Production build (UMD + ESM + CJS + worker bundles; runs test:es-check)
110+
npm run build
111+
```
112+
113+
See [references/commands.md](references/commands.md) for the full command list (integration/Cypress, es-check, bundle stats, security lint, docs, release). Read only when you need to run, build, or test something beyond the four above.
114+
115+
---
116+
117+
## Testing
118+
119+
The default `npm test` suite is **unit-only — no credentials required** (Jest + jsdom, in `__tests__/`). The Cypress integration tier runs against a **local** mock OIDC provider — not a live tenant.
120+
121+
See [references/testing.md](references/testing.md) for conventions, mocking utilities, the integration/Cypress commands, and coverage. Read when writing or debugging tests.
122+
123+
---
124+
125+
## Code Style
126+
127+
`PascalCase` types/classes, `camelCase` members; ESLint + Prettier (single quotes, no trailing commas, 80-col). Code must stay ES2017-clean and tree-shakeable.
128+
129+
See [references/code-style.md](references/code-style.md) for the full conventions — linter/formatter setup, naming, bundle discipline, and dominant patterns. Read when writing or reviewing code.
130+
131+
---
132+
133+
## Git Workflow
134+
135+
Conventional Commits, **enforced by commitlint** — a non-conforming message (or PR title) fails CI. Allowed types: `feat, fix, docs, chore, build, refactor, test, ci, perf, revert`.
136+
137+
See [references/git-workflow.md](references/git-workflow.md) for branch naming and PR requirements (template + required checks). Read when committing or opening a PR.
138+
139+
---
140+
141+
## Common Pitfalls
142+
143+
The high-frequency traps: **don't move worker-side token refresh onto the main thread**, silent-iframe auth needs a custom domain, and new code must stay ES2017-clean + tree-shakeable.
144+
145+
See [references/pitfalls.md](references/pitfalls.md) for the full list with fixes (web-worker token exposure, third-party-cookie silent auth, bundle/ES level, DPoP online-mode dual checks, wrapping `@auth0/auth0-auth-js`). Read when touching token handling, the web worker, DPoP, bundling, or the auth-js wrapping.
146+
147+
---
148+
149+
## Docs Update Rules
150+
151+
Tracked docs are `README.md` and `EXAMPLES.md`. A PR that changes the public API, configuration, or supported patterns is **not complete** until they're updated in the same PR (enforced by the Always Do boundary above).
152+
153+
See [references/docs-update.md](references/docs-update.md) for the full code-to-docs mapping — which doc to touch for each kind of change. Read when changing the public API, config, install requirements, token/cache/DPoP behavior, or adding an integration pattern.

references/code-style.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Code Style — auth0-spa-js
2+
3+
Read when writing or reviewing code so it matches the project's conventions.
4+
5+
## Linter & formatter
6+
7+
- **ESLint** over `src/`: `npm run lint` — but this covers `.jsx` and `.js` only (`eslint --ext .jsx,.js src/`). TypeScript files are **not** linted by it; editing a `.ts` file and running `npm run lint` passes regardless. `.ts` coverage comes from `npm run lint:security` (eslint-plugin-security, `eslint ./src --ext ts`).
8+
- **Prettier** (`.prettierrc`): single quotes, no trailing commas, arrow-parens avoided, 80-column width.
9+
10+
## Naming
11+
12+
- `PascalCase` for types and classes (`Auth0Client`, `CacheManager`).
13+
- `camelCase` for members and functions.
14+
- Public options are TypeScript interfaces declared in `global.ts`.
15+
16+
## Bundle discipline
17+
18+
- Code must stay **ES2017-clean**`npm run test:es-check` enforces it against both the classic and module bundles.
19+
- Keep the SDK **tree-shakeable**; avoid pulling heavy dependencies into the browser bundle (they inflate every consumer's build).
20+
21+
## Dominant patterns
22+
23+
- A `createAuth0Client()` async factory wrapping the `Auth0Client` class.
24+
- Pluggable `ICache` storage backends (`InMemoryCache`, `LocalStorageCache`).
25+
- Typed errors extending `GenericError` (`src/errors.ts`).
26+
- `@auth0/auth0-auth-js` wrapped for OAuth/MFA primitives.

0 commit comments

Comments
 (0)