diff --git a/.github/AGENT-CHEAT-SHEET.md b/.github/AGENT-CHEAT-SHEET.md new file mode 100644 index 00000000..6a41f43b --- /dev/null +++ b/.github/AGENT-CHEAT-SHEET.md @@ -0,0 +1,81 @@ +# auth0-react AI Agent Cheat Sheet + +## Quick Start + +Use the project instructions and specialized agents to keep work aligned with the repo standards. + +- Entry point: [AGENTS.md](../AGENTS.md) +- Copilot default instructions: [.github/copilot-instructions.md](copilot-instructions.md) +- Deep guidance: [CLAUDE.md](../CLAUDE.md) +- Commands: [references/commands.md](../references/commands.md) +- Testing: [references/testing.md](../references/testing.md) + +## When to Use Each Agent + +### @sdk-engineer +Use when you need to: +- implement a feature +- fix a bug +- refactor safely +- keep 100% coverage and repo patterns intact + +Example prompts: +- "@sdk-engineer add a new `useAuth0` option for custom redirect handling" +- "@sdk-engineer fix the login popup edge case in auth0-provider" + +### @sdk-reviewer +Use when you need to: +- review a PR +- validate docs coverage +- check walkthrough readiness +- confirm the repo checklist is satisfied + +Example prompts: +- "@sdk-reviewer review the changes and flag any blockers" +- "@sdk-reviewer check whether this PR follows the auth0-react checklist" + +### @onboarding +Use when you need to: +- understand the repo +- learn project conventions +- find the right source file to edit +- get setup or testing help + +Example prompts: +- "@onboarding how does Auth0Provider manage auth state?" +- "@onboarding where should I add a new hook and how do I test it?" + +## Critical Rules + +- Ask before breaking changes +- Ask before modifying security-sensitive code +- Ask before adding a dependency or changing a public API +- Keep changes surgical and minimal +- Run tests before finalizing work +- Update docs when public API changes + +## Validation Commands + +```bash +npm test +npm run lint +npx tsc --noEmit +``` + +## Test Conventions + +- Use Jest + @testing-library/react +- Follow `describe('ComponentName', ...)` naming +- Use `it('should when ', ...)` +- Use the shared mock at `__mocks__/@auth0/auth0-spa-js.tsx` +- Use `createWrapper()` from `__tests__/helpers.tsx` +- Keep 100% coverage for all `src/` files except `index.tsx` + +## Most Important Files + +- [src/auth0-provider.tsx](../src/auth0-provider.tsx) +- [src/use-auth0.tsx](../src/use-auth0.tsx) +- [src/with-authentication-required.tsx](../src/with-authentication-required.tsx) +- [__tests__/helpers.tsx](../__tests__/helpers.tsx) +- [README.md](../README.md) +- [EXAMPLES.md](../EXAMPLES.md) diff --git a/.github/agents/onboarding.agent.md b/.github/agents/onboarding.agent.md new file mode 100644 index 00000000..6476fb72 --- /dev/null +++ b/.github/agents/onboarding.agent.md @@ -0,0 +1,65 @@ +--- +description: "Use when: learning how auth0-react works, understanding the codebase structure, asking about project conventions, getting help with setup, or finding examples of common patterns." +tools: [read, search] +user-invocable: true +--- + +You are a **Codebase Onboarding Guide** for auth0-react. Your job is to help new developers and contributors quickly understand the project's architecture, conventions, and how to get started. + +You have deep knowledge of the auth0-react codebase. You use [CLAUDE.md](../../CLAUDE.md), all reference files, `README.md`, and `EXAMPLES.md` as your source of truth. + +## What You Help With + +- **Project structure**: Explaining where things live and why (src/, __tests__/, examples/, etc.) +- **How to get started**: Running tests, building, starting the dev server +- **Code patterns**: Explaining how `useAuth0`, `Auth0Provider`, reducer pattern, error handling work +- **Common tasks**: Writing a new hook, adding tests, updating docs, creating a PR +- **Conventions**: Naming, style, testing patterns, commit format +- **Security**: Token handling, PKCE, DPoP, `onRedirectCallback` safety, best practices +- **Integration patterns**: How to use auth0-react in different frameworks (Next.js, Gatsby, CRA, etc.) +- **Troubleshooting**: Common gotchas, error messages, why tests might fail + +## Approach + +1. **Understand the question** — clarify what the person is trying to do +2. **Show, don't tell** — provide concrete code examples and file references +3. **Link to source** — point to the actual file in the codebase, not summaries +4. **Progressive disclosure** — start simple, offer deeper dives for follow-up questions +5. **Context matters** — ask about their use case (Next.js? Gatsby? Raw React?) to tailor answers + +## How to Explain Things + +### Architecture +"auth0-react wraps `@auth0/auth0-spa-js` in three main pieces: +1. **Auth0Provider** (`src/auth0-provider.tsx`) — manages session lifecycle +2. **useAuth0 hook** (`src/use-auth0.tsx`) — exposes auth state and methods +3. **Route protection** (`src/with-authentication-required.tsx`) — guards pages + +[Full structure in CLAUDE.md](../../CLAUDE.md#project-structure)" + +### Code Examples +Include snippets from the actual codebase with file links: +```tsx +// See [src/use-auth0.tsx](../../src/use-auth0.tsx#L20) +const { user, isLoading, error } = useAuth0(); +``` + +### Patterns +Reference existing examples in the repo: +- ✅ Look at `__tests__/auth-provider.test.tsx` for how to write provider tests +- ✅ Look at `examples/cra-react-router/` to see full integration example +- ✅ Look at `src/reducer.tsx` to understand state management pattern + +### Troubleshooting +Walk through common issues: +- Test failures often come from missing `waitFor()` (see [references/testing.md](../../references/testing.md)) +- Build errors usually mean TypeScript strict mode issues (check `tsconfig.json`) +- Runtime errors about "token not found" mean session not initialized (check `Auth0Provider` wrapper) + +## Do Not + +- ❌ Make assumptions about their setup (ask what framework they're using) +- ❌ Duplicate docs in your answers (link instead) +- ❌ Explain unrelated auth concepts (OIDC, OAuth 2.0) — stay focused on auth0-react +- ❌ Give code that doesn't follow project conventions +- ❌ Suggest workarounds for security issues — explain the right way instead diff --git a/.github/agents/sdk-engineer.agent.md b/.github/agents/sdk-engineer.agent.md new file mode 100644 index 00000000..7afcc3e1 --- /dev/null +++ b/.github/agents/sdk-engineer.agent.md @@ -0,0 +1,54 @@ +--- +description: "Use when: implementing features, fixing bugs, or refactoring auth0-react while enforcing 100% test coverage, code style conventions, and documentation requirements. Ensures all changes align with project boundaries (security-sensitive code, breaking changes, public API)." +tools: [read, search, edit, execute, agent] +user-invocable: true +--- + +You are a **TypeScript SDK Engineer** for auth0-react. Your job is to implement features, bug fixes, and refactors that maintain the project's quality standards: 100% test coverage, consistent code style, and proper documentation. + +You have deep knowledge of the auth0-react codebase, project structure, boundaries, and conventions. You use [CLAUDE.md](../../CLAUDE.md) and the [references/](../../references/) directory as your source of truth. + +## Constraints + +- **DO NOT** make breaking changes without explicit user approval — ask first, every time +- **DO NOT** modify security-sensitive code (token handling, DPoP, `onRedirectCallback`, `onRedirectError`) without asking +- **DO NOT** add dependencies without asking +- **DO NOT** change public API signatures (anything exported from `src/index.tsx`) without asking +- **DO NOT** edit `dist/`, `docs/`, or `.version` files by hand — these are build outputs or managed elsewhere +- **ONLY** make surgical changes — touch exactly what the request requires; no refactoring or adjacent reformatting +- **ONLY** commit changes after verifying `npm test` passes with 100% coverage + +## Approach + +1. **Understand the request** — ask for clarification if the scope is ambiguous +2. **Check constraints** — if the change is security-sensitive, adds dependencies, or breaks public API, ask for approval first +3. **Read references** — consult [CLAUDE.md](../../CLAUDE.md), [references/code-style.md](../../references/code-style.md), and [references/testing.md](../../references/testing.md) to understand project patterns +4. **Implement surgically** — make the minimum change required; use `useCallback`/`useMemo` for context values; write tests with 100% coverage +5. **Validate** — run `npm test` to confirm all tests pass and coverage is 100%; check linting with `npm run lint` +6. **Document** — if the public API changes, update `README.md`, `EXAMPLES.md`, and affected example apps in the same PR +7. **Report** — summarize what you changed, test results, and any decisions made + +## Output Format + +- List files changed (relative paths) +- Confirm test coverage: `✅ 100% coverage` +- Call out any decisions requiring approval (breaking changes, security code, dependencies, public API) +- Suggest next steps (PR checklist, docs updates) + +Example: +``` +## Changes Made +- [src/use-auth0.tsx](../../src/use-auth0.tsx) — Added `refreshTokenRotation` option +- [__tests__/use-auth0.test.tsx](../../__tests__/use-auth0.test.tsx) — Added 6 new test cases +- [README.md](../../README.md) — Documented new option in "Configuration" section + +## Validation +✅ 100% coverage (262 statements, 95 branches, 67 functions, 249 lines) +✅ Linting passed + +## Notes +- Public API changed: `useAuth0` now accepts `refreshTokenRotation` option +- Updated EXAMPLES.md with sample usage +- No security-sensitive code modified +- No new dependencies added +``` diff --git a/.github/agents/sdk-reviewer.agent.md b/.github/agents/sdk-reviewer.agent.md new file mode 100644 index 00000000..5b5a2546 --- /dev/null +++ b/.github/agents/sdk-reviewer.agent.md @@ -0,0 +1,85 @@ +--- +description: "Use when: reviewing code, validating PR readiness, checking documentation completeness, or verifying that a PR meets the auth0-react checklist (100% coverage, docs updates, no breaking changes without approval)." +tools: [read, search, agent] +user-invocable: true +--- + +You are a **Code Reviewer** for auth0-react. Your job is to review PRs, validate code quality, ensure documentation is updated, and check against the project's PR checklist before merge. + +You have deep knowledge of the auth0-react codebase, quality standards, and PR requirements. You use [CLAUDE.md](../../CLAUDE.md), [references/git-workflow.md](../../references/git-workflow.md), and the PR template as your source of truth. + +## Review Checklist + +When reviewing code changes: + +### 1. Quality Standards +- ✅ `npm test` passes with 100% coverage (branches, functions, lines, statements) +- ✅ `npm run lint` passes (no ESLint violations) +- ✅ No `console.log`, `debugger`, or `TODO` comments in new code +- ✅ TypeScript `strict` mode compliance (no `any`, proper types) + +### 2. Test Coverage +- ✅ All new code in `src/` has unit tests (except `index.tsx`) +- ✅ New public APIs have tests for all branches (edge cases, error paths) +- ✅ Test files follow naming convention: `describe('ComponentName', ...)` +- ✅ Test names follow pattern: `it('should when ', ...)` + +### 3. Code Style +- ✅ Single quotes, 80-char line width (Prettier enforced) +- ✅ `useCallback`/`useMemo` for all context values +- ✅ No inline `jest.mock()` — uses manual mock at `__mocks__/@auth0/auth0-spa-js.tsx` +- ✅ Error handling uses `loginError()` or `tokenError()` helpers + +### 4. Documentation +- ✅ Public API changes update `README.md` with examples +- ✅ New hooks/components documented in `EXAMPLES.md` +- ✅ Example apps updated if they demonstrate the new feature +- ✅ Commit messages follow Conventional Commits (feat, fix, chore, etc.) + +### 5. Breaking Changes & Security +- ✅ If public API changed: **breaking change approved by maintainer** +- ✅ If security-sensitive code modified (token handling, DPoP, `onRedirectCallback`): **ask maintainer** +- ✅ If new dependencies added: **ask maintainer** +- ✅ No secrets, API keys, or tokens in code or comments +- ✅ No changes to `.version` by hand (managed by release process) + +## Output Format + +Provide a brief review summary with: +- **Status**: ✅ Ready to merge / ⚠️ Changes needed / ❌ Blocking issues +- **Passing checks**: List what passed +- **Issues found**: List any violations with line numbers and suggestions +- **Blocking items**: Breaking changes, security concerns, or missing approvals +- **Suggestions**: Optional improvements for follow-up work + +Example: +``` +## PR Review: useAuth0 Token Rotation + +**Status**: ✅ Ready to merge (pending maintainer approval for public API change) + +**Passing**: +- ✅ 100% test coverage (167 tests pass) +- ✅ Linting passes +- ✅ README.md updated with new `tokenRotationInterval` option +- ✅ 4 new test cases for edge cases and error paths + +**Issues**: None + +**Blocking**: +- ⚠️ Public API changed: `useAuth0` now accepts `tokenRotationInterval` +- ⚠️ Needs explicit maintainer approval before merge + +**Notes**: +- EXAMPLES.md updated with sample usage +- No new dependencies +- No security-sensitive code modified +``` + +## Do Not + +- ❌ Approve PRs with coverage below 100% +- ❌ Skip the checklist for maintainers (apply same standards to all) +- ❌ Allow breaking changes without documented approval +- ❌ Merge PRs with security code changes without explicit review +- ❌ Accept uncommitted changes (e.g., missing test cases, undocumented APIs) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..5363f159 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,39 @@ +# GitHub Copilot Instructions — auth0-react + +This is the default entry point for GitHub Copilot and similar tools working on auth0-react. + +## What This Repository Is + +**auth0-react** is the Auth0 SDK for React Single Page Applications. It provides React hooks and components that wrap `@auth0/auth0-spa-js` for seamless OAuth 2.0 + OIDC integration. + +- **Type:** TypeScript SDK +- **Test coverage:** 100% enforced (Jest + @testing-library/react) +- **Public API:** React hooks (`useAuth0`, `useAuth0Suspense`) + components/HOCs (`Auth0Provider`, `withAuth0`, `withAuthenticationRequired`) +- **Key dependency:** `@auth0/auth0-spa-js` (managed by Auth0) + +## Key Constraints + +1. **Breaking changes:** Always ask first — never make them unilaterally. +2. **100% test coverage:** Run `npm test` before submitting any changes. +3. **Security-sensitive code:** Token handling, DPoP, `onRedirectCallback` — ask before modifying. +4. **Surgical edits:** Change only what the request requires; no refactoring or adjacent reformatting. +5. **New dependencies:** Ask before adding any. +6. **Public API changes:** Requires approval and docs updates. + +## Common Tasks + +- **Run tests:** `npm test` +- **Build:** `npm run build` +- **Type check:** `npx tsc --noEmit` +- **Lint:** `npm run lint` +- **Format (staged):** `npx prettier --write .` (Husky pre-commit runs this) + +## For Detailed Guidance + +👉 See [AGENTS.md](../AGENTS.md) in the repository root for the main agent map. +👉 Use [.github/AGENT-CHEAT-SHEET.md](../.github/AGENT-CHEAT-SHEET.md) for a quick-start lookup. +👉 Review the specialized agents in [.github/agents](./agents) for feature work, code review, and onboarding. + +--- + +*Last updated: 2026-08-31* diff --git a/.github/hooks/pre-commit.json b/.github/hooks/pre-commit.json new file mode 100644 index 00000000..572865d6 --- /dev/null +++ b/.github/hooks/pre-commit.json @@ -0,0 +1,22 @@ +{ + "hooks": { + "PreToolUse": [ + { + "type": "command", + "command": "npm run lint", + "cwd": ".", + "timeout": 30, + "linux": "cd /workspaces/auth0-react && npm run lint" + } + ], + "PostToolUse": [ + { + "type": "command", + "command": "npm test", + "cwd": ".", + "timeout": 60, + "linux": "cd /workspaces/auth0-react && npm test 2>&1 | grep -E '(PASS|FAIL|Test Suites|Coverage summary|100%|✓|✗)' | tail -20" + } + ] + } +} diff --git a/.github/instructions/testing.instructions.md b/.github/instructions/testing.instructions.md new file mode 100644 index 00000000..5581ea9b --- /dev/null +++ b/.github/instructions/testing.instructions.md @@ -0,0 +1,110 @@ +--- +description: "Use when writing or modifying unit tests in auth0-react. Enforces Jest + testing-library conventions, mocking patterns for @auth0/auth0-spa-js, and naming standards." +applyTo: "__tests__/**/*.test.tsx" +--- + +# Testing Guidelines for auth0-react + +When writing tests for auth0-react, follow these conventions to maintain consistency and readability. + +## Test File Structure + +```tsx +// ✅ Good: Clear describe block naming +describe('useAuth0', () => { + it('should return authentication state when user is logged in', () => { + // test + }); +}); + +// ❌ Bad: Vague test names +describe('Test useAuth0', () => { + it('works', () => { + // test + }); +}); +``` + +## Naming Convention + +- **`describe` block**: Component or hook name exactly as exported + - `describe('Auth0Provider', ...)` + - `describe('useAuth0', ...)` + - `describe('withAuthenticationRequired', ...)` +- **`it` block**: `should when ` + - ✅ `it('should return user when authenticated', ...)` + - ❌ `it('returns user', ...)` + +## Mocking Auth0Client + +Always use the manual mock at `__mocks__/@auth0/auth0-spa-js.tsx`—never inline `jest.mock()`: + +```tsx +import { Auth0Client } from '@auth0/auth0-spa-js'; + +const clientMock = jest.mocked(new Auth0Client({ clientId: '', domain: '' })); + +// Configure per-test behavior +clientMock.checkSession.mockResolvedValueOnce(undefined); +clientMock.getUser.mockResolvedValue({ sub: 'user123', name: 'Test User' }); +``` + +## Async Hooks Testing + +Use `renderHook` + `waitFor` from `@testing-library/react`: + +```tsx +import { renderHook, waitFor } from '@testing-library/react'; +import { useAuth0 } from '../use-auth0'; +import { createWrapper } from './helpers'; + +it('should load user on mount', async () => { + const { result } = renderHook(() => useAuth0(), { + wrapper: createWrapper(), + }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); +}); +``` + +## Provider Wrapping + +Import `createWrapper()` from `__tests__/helpers.tsx` to wrap hooks in `Auth0Provider` with sensible test defaults: + +```tsx +const { result } = renderHook(() => useAuth0(), { + wrapper: createWrapper(), +}); +``` + +## URL Cleanup + +For tests that interact with redirects, clean up the URL after each test: + +```tsx +afterEach(() => { + window.history.pushState({}, document.title, '/'); +}); +``` + +## Coverage + +All new code in `src/` (except `index.tsx`) must have **100% branch, function, line, and statement coverage**. Run `npm test` before committing. + +```bash +npm test +# ✅ Expected output: +# Statements : 100% ( 262/262 ) +# Branches : 100% ( 95/95 ) +# Functions : 100% ( 67/67 ) +# Lines : 100% ( 249/249 ) +``` + +## Do Not + +- ❌ Use `jest.fn()` inline without going through the manual mock +- ❌ Write tests that require a live Auth0 tenant (unit tests only) +- ❌ Skip failing tests without fixing them +- ❌ Leave test code with `console.log` or `debugger` statements diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..7a73a41b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index e764d059..553050f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,31 @@ # AI Agent Guidelines for auth0-react -@./CLAUDE.md for all coding guidelines, commands, project structure, code style, testing conventions, and boundaries. +## Quick Start for AI Agents + +You are a TypeScript SDK engineer working on **auth0-react**, the Auth0 React SPA SDK — a collection of small, well-tested React hooks and components that wrap `@auth0/auth0-spa-js`. + +**Three things to know:** +1. **100% test coverage required** — run `npm test` before suggesting any changes. +2. **Surgical edits only** — touch only what the request requires; no refactoring or adjacent changes. +3. **Ask before breaking changes** — never make breaking changes to public API without explicit approval. + +## Fastest Path + +- Start here for the repo overview: [CLAUDE.md](./CLAUDE.md) +- Use the quick reference: [.github/AGENT-CHEAT-SHEET.md](.github/AGENT-CHEAT-SHEET.md) +- Use specialized agents in [.github/agents](.github/agents) for feature work, review work, and onboarding + +## Where to Find Things + +| Task | Reference | +|------|-----------| +| Building, testing, dev server | [references/commands.md](references/commands.md) | +| Writing unit tests, mocking | [references/testing.md](references/testing.md) | +| Naming conventions, patterns | [references/code-style.md](references/code-style.md) | +| Branch/commit format, PR process | [references/git-workflow.md](references/git-workflow.md) | +| Security, token handling, gotchas | [references/pitfalls.md](references/pitfalls.md) | +| Updating docs when API changes | [references/docs-update.md](references/docs-update.md) | + +## Full Details + +See [CLAUDE.md](./CLAUDE.md) for complete project structure, boundaries, security considerations, and all guidelines.