Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: give claude context
Tre Dubravad8b86e54577c
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 2803cbbb55..bdc0933426 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -22,4 +22,5 @@- [ ] Title follows the [conventional commit](https://www.conventionalcommits.org/en/v1.0.0/#summary) format: `type(scope): short description` (scope is optional, e.g., `fix: prevent crash on sync` or `fix(api): handle null response`).- [ ] Tested locally- [ ] Updated docs (if needed)+- [ ] Updated CLAUDE.md files (if needed)- [ ] Read the [contributing guide](https://infisical.com/docs/contributing/getting-started/overview)\ No newline at end of filediff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000000..4da4c7e3fa--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,68 @@+# CLAUDE.md++This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++## Essential Commands++- `make reviewable-api` / `make reviewable-ui` — lint:fix + type:check (run before PRs)+- `cd backend && npm run migration:new` — create new DB migration+- `cd backend && npm run generate:schema` — regenerate Zod types from DB after migration changes++Both backend and frontend use `@app/*` as path alias to `./src/*`.++## Repository Structure++Infisical is an open-source secret management platform. Monorepo layout:++```+infisical/+├── backend/ # Fastify 4 API server (see backend/CLAUDE.md)+├── frontend/ # React 18 SPA (see frontend/CLAUDE.md)+├── docs/ # Documentation site (Mintlify-based)+├── docker-compose.dev.yml # Local dev (PostgreSQL, Redis, backend, frontend, Nginx)+├── docker-compose.prod.yml # Production deployment stack+├── docker-compose.bdd.yml # BDD testing environment+├── docker-compose.e2e-dbs.yml # E2E test databases (Oracle, SAP, Snowflake, etc.)+├── Dockerfile.standalone-infisical # Standalone image (frontend + backend)+├── Dockerfile.fips.standalone-infisical # FIPS-compliant standalone image+├── .github/ # CI workflows, PR template+└── CLAUDE.md # This file+```++- **`backend/`** — Fastify 4 API server, TypeScript, PostgreSQL via Knex, BullMQ queues. See [`backend/CLAUDE.md`](backend/CLAUDE.md) for architecture, patterns, and commands.+- **`frontend/`** — React 18 SPA, Vite 6, TanStack Router + React Query, Tailwind CSS v4. See [`frontend/CLAUDE.md`](frontend/CLAUDE.md) for architecture, patterns, and commands.+- **`docs/`** — Product documentation site. Has its own Dockerfile for building. Reference docs for up-to-date feature descriptions and API usage.++Enterprise features live in `backend/src/ee/` (services and routes), registered before community routes so they can override/extend them.++### Self-Hosted Deployment++Infisical supports self-hosted deployment via Docker. Key considerations:+- **`Dockerfile.standalone-infisical`** — single-container image with both frontend and backend; used for simple deployments.+- **`Dockerfile.fips.standalone-infisical`** — FIPS 140-2 compliant variant for regulated environments. Be strict about not introducing dependencies that break FIPS compliance.+- **`docker-compose.prod.yml`** — production compose with backend, PostgreSQL, and Redis.+- New backend dependencies should be evaluated carefully — they affect container size, FIPS compliance, and the encryption boundary. Check `docs/` for self-hosted deployment documentation when in doubt.++## Cross-Cutting Patterns++### Auth & Permissions++Auth modes (JWT, IDENTITY_ACCESS_TOKEN, SCIM_TOKEN, MCP_JWT) are extracted in `backend/src/server/plugins/auth/`. Authorization uses CASL (`@casl/ability`) with project-level and org-level permission checks — see `backend/CLAUDE.md` for backend details and `frontend/CLAUDE.md` for frontend permission hooks/HOCs. Note: `API_KEY` and `SERVICE_TOKEN` auth modes are deprecated — do not use them in new code.++### Service Factory + Manual DI (Backend)++No IoC container. Every service is a factory function with explicit dependencies. The entire dependency graph is wired in `backend/src/server/routes/index.ts` — see `backend/CLAUDE.md` for the full wiring map and patterns.++### API Layer (Frontend)++React Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/CLAUDE.md` for conventions.++## Keeping CLAUDE.md Up to Date++When making significant changes to the codebase (new services, architectural shifts, new patterns, major refactors), update the relevant CLAUDE.md file(s) with high-level findings. This includes this root file for cross-cutting concerns, `backend/CLAUDE.md` for backend changes, and `frontend/CLAUDE.md` for frontend changes. The goal is to keep these files accurate as living documentation so future sessions start with correct context.++## Wiring a New Full-Stack Feature++1. **Backend**: Create service module, migration, wire DI, add routes — see checklist in `backend/CLAUDE.md`+2. **Frontend**: Add API hooks in `src/hooks/api/<domain>/`, create page/view, wire route — see `frontend/CLAUDE.md` for routing and component patterns+3. Run `make reviewable-api` and `make reviewable-ui` before submittingdiff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdnew file mode 100644index 0000000000..b6aff682cd--- /dev/null+++ b/backend/CLAUDE.md@@ -0,0 +1,185 @@+# CLAUDE.md++This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++This is the **backend** package of the Infisical monorepo — a Fastify 4 API server with TypeScript, PostgreSQL via Knex, and BullMQ queues.++## Essential Commands++All commands run from the `backend/` directory:++- `npm run dev` — start dev server with tsx watch + pino-pretty logging+- `npm run build` — production build via tsup with sourcemaps+- `npm run lint:fix` — ESLint autofix+- `npm run type:check` — TypeScript check (uses 8GB heap)+- `make reviewable-api` (from repo root) — runs `lint:fix` + `type:check` (run before PRs)++### Testing++- `npm run test:unit` — unit tests matching `./src/**/*.test.ts`+- `npm run test:e2e` — e2e tests matching `./e2e-test/**/*.spec.ts` (single-threaded, requires running DB/Redis)+- `npm run test:e2e-watch` — e2e tests in watch mode++Unit tests go next to source as `*.test.ts` and test pure functions with Vitest globals (`describe`, `test`, `expect`).++E2E tests live in `e2e-test/routes/`. The custom Vitest environment (`e2e-test/vitest-environment-knex.ts`) bootstraps a full server with DB, Redis, and encryption. Tests use injected globals: `testServer` (Fastify instance), `jwtAuthToken` (pre-authenticated JWT). Use `testServer.inject()` for HTTP assertions. Test helpers in `e2e-test/testUtils/` provide CRUD wrappers for secrets, folders, and secret imports. See `e2e-test/routes/v1/org.spec.ts` for a representative e2e test.++### Database++- `npm run migration:new` — create new migration (interactive prompt)+- `npm run migration:latest-dev` — run pending migrations (dev, uses `src/db/knexfile.ts`)+- `npm run migration:rollback-dev` — rollback last migration batch (dev)+- `npm run generate:schema` — regenerate Zod types from DB into `src/db/schemas/` (always run after migration changes)+- `npm run seed-dev` — run database seeds++### Scaffolding++- `npm run generate:component` — interactive generator that can create a service module (DAL + service + types), a standalone DAL, or a router++Path alias: `@app/*` maps to `./src/*`.++## ESLint & Import Ordering++Config in `.eslintrc.js`. Uses `simple-import-sort` with this group order:+1. Side-effect imports+2. `node:` builtins+3. Third-party packages+4. `@app/` imports+5. `@lib/` imports+6. `@server/` imports+7. Relative imports++## Architecture++### Service Factory + Manual DI++No IoC container. Every service is a factory function that receives explicit dependencies as a typed object and returns an object of methods. Dependencies are narrowed with TypeScript `Pick` to define minimal interface contracts.++The entire dependency graph is manually wired in `src/server/routes/index.ts`:+- **~line 480-646**: DAL instantiation — each DAL factory receives the `db` client+- **~line 649-2800**: Service instantiation — each factory receives its DALs + other services+- **~line 2831-2972**: `server.decorate("services", {...})` exposes ~100+ services as `server.services.*`+- **~line 3082-3098**: Route registration — EE routes registered before community routes per API version++See `src/services/secret/secret-service.ts:104-162` for a representative factory with ~20 dependencies. See `src/services/user/user-service.ts` for a simpler example (~8 dependencies).++### DAL Layer (Data Access)++Each service has a `*-dal.ts` that wraps `ormify()` (defined in `src/lib/knex/index.ts:155-326`). `ormify()` provides typed CRUD methods: `findById`, `find`, `findOne`, `create`, `insertMany`, `batchInsert`, `upsert`, `updateById`, `update`, `deleteById`, `delete`, `countDocuments`, `transaction`.++DALs extend these with custom queries — typically complex joins using Knex query builder and `sqlNestRelationships()` for nested entity mapping. All methods accept an optional `tx` parameter for transaction threading.++**Read replica pattern**: Read methods use `db.replicaNode()` (e.g., `(tx || db.replicaNode())(tableName)`), while writes always hit the primary (`(tx || db)(tableName)`). See any `ormify()` method in `src/lib/knex/index.ts` for the pattern.++`updateById` and `update` support atomic `$incr` and `$decr` operators alongside regular field updates.++See `src/services/secret/secret-dal.ts` for a DAL that overrides the base `update` to auto-increment version and adds complex join queries.++### Service Module Structure++Services live in `src/services/` (100+ modules). Each typically contains:+- `*-dal.ts` — data access via `ormify()` + custom queries+- `*-service.ts` — business logic factory+- `*-types.ts` — DTOs and type definitions+- `*-queue.ts` — BullMQ async job handlers (when needed)+- `*-fns.ts` — pure utility functions (when needed)++### Route Handler Pattern++Routes use Fastify's Zod type provider — schemas auto-generate OpenAPI docs. Each route specifies: `method`, `url`, `config.rateLimit` (using `readLimit` or `writeLimit` presets), `schema` (Zod schemas with `operationId` for OpenAPI), `onRequest: verifyAuth([AuthMode.*])`, and a `handler` that accesses business logic via `server.services.*`.++See `src/server/routes/v3/user-router.ts` for a representative router file.++### Auth System++Auth extraction happens in `src/server/plugins/auth/`:+- `inject-identity.ts` — detects auth mode from request headers and attaches identity to request+- `verify-auth.ts` — middleware that checks if the request's auth mode is in the route's allowed strategies+- `inject-permission.ts` — attaches permission context+- `inject-assume-privilege.ts` — privilege escalation support+- `superAdmin.ts` — super admin flag injection++**Auth modes** (defined in `AuthMode` enum):+- **JWT** — user browser sessions (decoded from `Authorization: Bearer` header)+- **IDENTITY_ACCESS_TOKEN** — machine-to-machine identity tokens+- **SCIM_TOKEN** — SCIM provisioning tokens+- **MCP_JWT** — MCP-specific JWTs (has `.mcp` field in payload)++**Deprecated auth modes (do not use in new code):**+- **API_KEY** — user API keys (from `x-api-key` header). Deprecated — use identity access tokens instead.+- **SERVICE_TOKEN** — service tokens (Bearer tokens starting with `st.` prefix). Deprecated — use identity access tokens instead.++If you encounter `API_KEY` or `SERVICE_TOKEN` in existing code, do not replicate them in new routes or services. All new machine authentication should use `IDENTITY_ACCESS_TOKEN`.++Token detection logic in `inject-identity.ts` checks `x-api-key` header first, then parses `Authorization: Bearer` and inspects JWT `authTokenType` field to determine mode.++### Permission System (CASL)++Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in `src/ee/services/permission/`:+- `permission-service.ts` — factory that builds CASL abilities from user/identity roles+- `project-permission.ts` — defines project-level permission actions and subjects+- `org-permission.ts` — defines org-level permission actions and subjects++**Project permission actions** include standard CRUD plus specialized ones like `DescribeSecret` (see metadata without value), `ReadValue`, `GrantPrivileges`, `AssumePrivileges`, `Lease` (for dynamic secrets). See `ProjectPermissionActions`, `ProjectPermissionSecretActions`, `ProjectPermissionDynamicSecretActions`, and `ProjectPermissionIdentityActions` enums in `project-permission.ts`.++Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpacked CASL rules stored in the database. Rules can include conditions with operators `$IN`, `$EQ`, `$NEQ`, `$GLOB` (for pattern matching like `prod-*`). See `PermissionConditionSchema` in `permission-types.ts`.++### Queue System (BullMQ)++Queue infrastructure in `src/queue/queue-service.ts`. Defines 30+ named queues via `QueueName` enum (e.g., `SecretRotation`, `AuditLog`, `IntegrationSync`, `SecretReplication`, `SecretSync`, `DynamicSecretRevocation`). Each queue has typed payloads defined in `TQueueJobTypes`.++Queue jobs support: delays, attempts with exponential/fixed backoff, cron-pattern repeats, and completion/failure cleanup. A `PersistenceQueueStatus` enum tracks durable job states (`Pending`, `Processing`, `Completed`, `Failed`, `Stuck`, `Dead`).++Queue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the same DI pattern as services — they receive DALs and services as dependencies.++### Error Handling++Custom error classes in `src/lib/errors/index.ts`:+- `BadRequestError` (400) — with optional `details` field+- `UnauthorizedError` (401)+- `ForbiddenRequestError` (403) — with optional `details`+- `PermissionBoundaryError` — extends `ForbiddenRequestError`+- `NotFoundError` (404)+- `DatabaseError` (500) — wraps original Knex error+- `GatewayTimeoutError` (504)+- `InternalServerError` (500)+- `RateLimitError`+- `ScimRequestError` — SCIM-specific formatting with schemas and status++Global error handler in `src/server/plugins/error-handler.ts` maps these to HTTP status codes and records OpenTelemetry error metrics.++### Enterprise (EE) Features++Enterprise code lives in `src/ee/`:+- `src/ee/services/` — 60+ service modules (access approval, audit log, dynamic secrets, external KMS, gateway, KMIP, LDAP, OIDC, PAM, PKI, SAML, SCIM, secret approval/rotation/replication, etc.)+- `src/ee/routes/v1/` — 63 EE route files; `src/ee/routes/v2/` — 10 v2 route files++EE routes register before community routes so they can override/extend endpoints. Feature gating via license service (`src/ee/services/license/license-service.ts`) which validates online/offline licenses, caches feature sets in keystore with 5-minute TTL, and exposes `getPlan()` to check feature availability.++### Server Plugins++Key plugins in `src/server/plugins/`:+- `error-handler.ts` — global error handling with OpenTelemetry metrics+- `fastify-zod.ts` — in-house Zod-to-OpenAPI transformation+- `audit-log.ts` — request audit logging to queue+- `api-metrics.ts` — OpenTelemetry metrics collection+- `inject-rate-limits.ts` — per-route rate limiting+- `secret-scanner.ts` / `secret-scanner-v2.ts` — secret scanning webhooks+- `serve-ui.ts` — frontend asset serving+- `swagger.ts` — Swagger/OpenAPI UI+- `maintenanceMode.ts` — maintenance mode middleware+- `ip.ts` — IP extraction and validation++### Database Configuration++Knex config in `src/db/knexfile.ts`. Loads `.env.migration` then `.env`. Supports `DB_CONNECTION_URI` or individual host/port/user/name/password fields. Optional SSL via `DB_ROOT_CERT` (base64-encoded CA cert). Connection pool: min 2, max 10. Migrations table: `infisical_migrations`. Separate audit log DB supported via `auditlog-migration:*` scripts. ClickHouse for analytics (optional).++Migrations in `src/db/migrations/`. Auto-generated Zod schemas in `src/db/schemas/`.++## Wiring a New Feature (Checklist)++1. Create service module in `src/services/<name>/` (or `src/ee/services/<name>/` for EE) with DAL, service, and types files+2. If adding DB tables: create migration via `npm run migration:new`, run it, then `npm run generate:schema`+3. Wire in `src/server/routes/index.ts`: instantiate DAL → instantiate service → add to `server.decorate("services", {...})`+4. Create router in `src/server/routes/v<N>/` (or `src/ee/routes/v<N>/` for EE) and register it+5. Run `make reviewable-api` to verify lint + typesdiff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.mdnew file mode 100644index 0000000000..3b277b3959--- /dev/null+++ b/frontend/CLAUDE.md@@ -0,0 +1,74 @@+# CLAUDE.md++This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++This is the **frontend** package of the Infisical monorepo — a React 18 SPA built with Vite 6, TanStack Router, React Query, and Tailwind CSS v4.++## Essential Commands++All commands run from the `frontend/` directory:++- `npm run dev` — start dev server on port 3000+- `npm run build` — TypeScript check + Vite production build+- `npm run lint:fix` — ESLint autofix (double quotes, simple-import-sort with 7 groups)+- `npm run type:check` — TypeScript type check only (`tsconfig.app.json`)+- `make reviewable-ui` (from repo root) — runs `lint:fix` + `type:check` (run before PRs)+- `npm run storybook` — Storybook on port 6006++Path alias: `@app/*` maps to `./src/*`.++## Architecture Overview++### Routing (TanStack Router v1)++Virtual file routes defined in `src/routes.ts` using a functional DSL (`route()`, `index()`, `layout()`, `middleware()`). The generated route tree is in `src/routeTree.gen.ts` (do not edit manually — regenerated on dev server start or when `src/routes.ts` changes).++Each page directory has a `route.tsx` that defines its route:+```tsx+createFileRoute(path)({ component, validateSearch: zodValidator(schema), beforeLoad })+```++Route middleware chain: root → `authenticate` → `inject-org-details` → org-layout → product-specific layouts (secret-manager-layout, cert-manager-layout, kms-layout, ssh-layout, etc.).++Middleware pages in `src/pages/middlewares/`: `authenticate.tsx` (auth guard + redirect), `inject-org-details.tsx` (org context), `restrict-login-signup.tsx` (prevents auth pages when logged in).++### Pages / Views / Components Hierarchy++- **`src/pages/`** — Route-level components organized by product feature (secret-manager, cert-manager, kms, ssh, pam, organization, project, admin, auth, ai). Each has `route.tsx` + page component + local `components/`.+- **`src/views/`** — Reusable page-level UI composed into multiple pages. Pages import views with configuration props.+- **`src/components/v3/`** — Latest shared UI component library (preferred). Contains `generic/` (Accordion, Alert, Button, Dialog, Select, Table, etc.) and `platform/` (domain-specific components). **Always use v3 components for new code.** Only use v2 components when a v3 equivalent does not exist.+- **`src/components/v2/`** — Legacy shared UI components built on Radix UI primitives + Tailwind. Uses `cva` (class-variance-authority) for variants and `tailwind-merge` for class conflict resolution. Being superseded by v3 — do not use for new features if a v3 alternative exists.++### API Layer (React Query + Axios)++Each API domain in `src/hooks/api/` (100+ domain folders) follows this structure:+- **`queries.tsx`** — Query key factory pattern: keys return `[{ params }, "domain-label"]`. Export named query hooks (`useGetSecrets`, etc.) and raw fetch functions.+- **`mutations.tsx`** — `useMutation` hooks that invalidate relevant query keys on success via `queryClient.invalidateQueries()`.+- **`types.tsx`** — Request/response DTOs.++HTTP client in `src/config/request.ts`: Axios instance with automatic token injection and 401/403 interceptors.++### State Management++- **Server state**: TanStack React Query (query key factories in each API domain)+- **Global app state**: React Context providers in `src/context/` — User, Organization, Project, OrgPermission, ProjectPermission, ServerConfig, Subscription+- **Local component state**: Zustand stores++### Permissions++CASL-based (`@casl/ability`). Contexts: `OrgPermissionContext` and `ProjectPermissionContext` in `src/context/`. Access via `useOrgPermission()` / `useProjectPermission()` hooks. HOC gates: `src/hoc/withPermission/` and `withProjectPermission/`.++### Styling++Tailwind CSS v4 with PostCSS. Dark theme configured via CSS custom properties in `src/index.css` (@theme directive). Custom breakpoint `dashboard: 1100px`. Font: Inter. Color palette: primary (blue), mineshaft (dark gray), bunker (darker bg), success/warning/danger/info.++### Layouts++13 layout components in `src/layouts/` — `AdminLayout`, `OrganizationLayout`, `SecretManagerLayout`, `CertManagerLayout`, `KmsLayout`, `SshLayout`, `PamLayout`, etc. Layouts handle sidebar navigation and page chrome for their product area.++## Conventions++- ESLint flat config (ESLint 9+) with airbnb-typescript + prettier. Double quotes enforced.+- Import ordering via `simple-import-sort`: node builtins → react/external packages → `@app/` → internal → relative → styles.+- Forms use `react-hook-form` with `@hookform/resolvers` (Zod schemas).+- Search params validated with `zodValidator()` from `@tanstack/zod-adapter`.