Implements all P0 features per OpenSpec change phase-1-mvp-implementation: - Agent Registry Service (CRUD) — full lifecycle management - OAuth 2.0 Token Service (Client Credentials flow) - Credential Management (generate, rotate, revoke) - Immutable Audit Log Service Tech: Node.js 18+, TypeScript 5.3+ strict, Express 4.18+, PostgreSQL 14+, Redis 7+ Standards: OpenAPI 3.0 specs, DRY/SOLID, zero `any` types Quality: 18 unit test suites, 244 tests passing, 97%+ coverage OpenAPI: 4 complete specs (14 endpoints total) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
9.4 KiB
9.4 KiB
1. Project Bootstrap & Infrastructure
- 1.1 Initialise
package.jsonwith all required dependencies (Express, TypeScript, Joi, jsonwebtoken, bcryptjs, uuid, pg, redis, pino, helmet, cors, dotenv, jest, supertest, ts-jest, ESLint, Prettier) - 1.2 Create
tsconfig.jsonwith strict mode enabled (all flags from README §6.4) - 1.3 Create
.eslintrc.jsonwith@typescript-eslintplugin and no-anyrule - 1.4 Create
.prettierrc - 1.5 Create
jest.config.tswithts-jestpreset and coverage thresholds (>80%) - 1.6 Create
docker-compose.ymlwithpostgres:14-alpineandredis:7-alpineservices - 1.7 Create
.env.exampledocumenting all required environment variables (DATABASE_URL,REDIS_URL,JWT_PRIVATE_KEY,JWT_PUBLIC_KEY,PORT, etc.)
2. Shared Infrastructure
- 2.1 Create
src/types/index.ts— all shared TypeScript interfaces (IAgent,ICredential,IAuditEvent,ITokenPayload,ICreateAgentRequest,IUpdateAgentRequest, etc.) - 2.2 Create
src/utils/errors.ts— fullSentryAgentErrorhierarchy (ValidationError,AgentNotFoundError,AgentAlreadyExistsError,CredentialError,AuthenticationError,AuthorizationError,RateLimitError,FreeTierLimitError) - 2.3 Create
src/utils/crypto.ts—generateClientSecret()(sk_live_ prefix + 64 hex),hashSecret(plain)(bcrypt 10 rounds),verifySecret(plain, hash)(bcrypt compare) - 2.4 Create
src/utils/jwt.ts—signToken(payload, privateKey)(RS256),verifyToken(token, publicKey)(returns typed payload),decodeToken(token)(no verification) - 2.5 Create
src/utils/validators.ts— Joi schemas forCreateAgentRequest,UpdateAgentRequest,TokenRequest,IntrospectRequest,RevokeRequest,GenerateCredentialRequest, list query params - 2.6 Create
src/db/pool.ts— typedpg.Poolsingleton, readsDATABASE_URLfrom env - 2.7 Create
src/cache/redis.ts— typed Redis client singleton, readsREDIS_URLfrom env - 2.8 Create
src/db/migrations/001_create_agents.sql—agentstable (all fields from OpenAPI spec,statusas varchar) - 2.9 Create
src/db/migrations/002_create_credentials.sql—credentialstable (credential_id,client_id,secret_hash,status,created_at,expires_at,revoked_at) - 2.10 Create
src/db/migrations/003_create_audit_events.sql—audit_eventstable (event_id,agent_id,action,outcome,ip_address,user_agent,metadataJSONB,timestamp) - 2.11 Create
src/db/migrations/004_create_tokens.sql—token_revocationstable (jti,expires_at) for soft revocation tracking (supplementary to Redis) - 2.12 Create
npm run db:migratescript to execute migrations in order
3. Middleware
- 3.1 Create
src/middleware/auth.ts— Bearer token extraction fromAuthorizationheader, RS256 JWT verification, Redis revocation check, attaches decoded payload toreq.user; throwsAuthenticationErroron failure - 3.2 Create
src/middleware/rateLimit.ts— Redis sliding window counter keyed byclient_id; injectsX-RateLimit-*headers on every response; throwsRateLimitErrorat 100 req/min - 3.3 Create
src/middleware/errorHandler.ts— Express error middleware; mapsSentryAgentErrorsubclasses to HTTP status codes andErrorResponseJSON; maps unknown errors to500
4. Agent Registry
- 4.1 Create
src/repositories/AgentRepository.ts— typed methods:create,findById,findByEmail,findAll(with filters + pagination),update,decommission,countByOwner; all SQL in this file only - 4.2 Create
src/services/AgentService.ts—registerAgent,getAgentById,listAgents,updateAgent,decommissionAgent; enforces free-tier 100-agent limit; validates immutable fields on update; callsAuditServicefor all write operations; JSDoc on all public methods - 4.3 Create
src/controllers/AgentController.ts— HTTP handlers for all 5 agent endpoints; Joi validation usingvalidators.ts; delegates toAgentService; no business logic - 4.4 Create
src/routes/agents.ts— Express router wiringAgentControllerhandlers to paths withauthandrateLimitmiddleware
5. OAuth 2.0 Token Service
- 5.1 Create
src/repositories/TokenRepository.ts—addToRevocationList(jti, expiresAt),isRevoked(jti)(checks Redis first, then DB);incrementMonthlyCount(clientId),getMonthlyCount(clientId)(Redis-backed) - 5.2 Create
src/services/OAuth2Service.ts—issueToken(validates client credentials via bcrypt, checks agent status, enforces 10k monthly limit, signs RS256 JWT, writes audit event),introspectToken(verifies + checks revocation),revokeToken(adds JTI to Redis + DB revocation list, writes audit event); JSDoc on all public methods - 5.3 Create
src/controllers/TokenController.ts— HTTP handlers forPOST /token,POST /token/introspect,POST /token/revoke; parsesapplication/x-www-form-urlencoded; delegates toOAuth2Service; returnsOAuth2ErrorResponsefor/tokenerrors,ErrorResponsefor introspect/revoke errors - 5.4 Create
src/routes/token.ts— Express router;/tokenuses no Bearer auth middleware (credentials are in body);/token/introspectand/token/revokeuseauthmiddleware
6. Credential Management
- 6.1 Create
src/repositories/CredentialRepository.ts—create,findById,findByAgentId(with pagination + status filter),updateHash,revoke,revokeAllForAgent; all SQL here only - 6.2 Create
src/services/CredentialService.ts—generateCredential(checks agent active status, generates secret viacrypto.ts, bcrypt-hashes, persists),listCredentials,rotateCredential(generates new secret, replaces hash, same credentialId),revokeCredential; callsAuditServicefor all write operations; JSDoc on all public methods - 6.3 Create
src/controllers/CredentialController.ts— HTTP handlers for all 4 credential endpoints; Joi validation; delegates toCredentialService - 6.4 Create
src/routes/credentials.ts— Express router under/agents/:agentId/credentialswithauthandrateLimitmiddleware
7. Audit Log Service
- 7.1 Create
src/repositories/AuditRepository.ts—create(event),findById(eventId),findAll(filters, pagination)with support foragentId,action,outcome,fromDate,toDatefiltering and 90-day retention window enforcement - 7.2 Create
src/services/AuditService.ts—logEvent(agentId, action, outcome, ipAddress, userAgent, metadata)(async insert, fire-and-forget for token endpoints);queryEvents(filters, pagination),getEventById(eventId); enforces 90-day retention on queries; JSDoc on all public methods - 7.3 Create
src/controllers/AuditController.ts— HTTP handlers forGET /auditandGET /audit/{eventId}; scope check foraudit:read; Joi validation of query params - 7.4 Create
src/routes/audit.ts— Express router withauthandrateLimitmiddleware
8. Application Assembly
- 8.1 Create
src/app.ts— Express app factory: registershelmet,cors,morgan/pino-http, JSON body parser,urlencodedbody parser (for token endpoints), all 4 route modules, anderrorHandlermiddleware; exported function (not called directly — testable) - 8.2 Create
src/server.ts— importsapp.ts, readsPORTfrom env, callsapp.listen; entry point only
9. Unit Tests
- 9.1 Write unit tests for
src/utils/crypto.ts— secret generation format, bcrypt hash/verify round-trip - 9.2 Write unit tests for
src/utils/jwt.ts— sign/verify/decode with RS256 test keys - 9.3 Write unit tests for
src/utils/validators.ts— valid and invalid inputs for every Joi schema - 9.4 Write unit tests for
src/services/AgentService.ts— mockAgentRepositoryandAuditService; cover all scenarios from agent-registry spec - 9.5 Write unit tests for
src/services/OAuth2Service.ts— mockTokenRepository,CredentialRepository,AuditService; cover all scenarios from oauth2-token spec - 9.6 Write unit tests for
src/services/CredentialService.ts— mockCredentialRepository,AgentRepository,AuditService; cover all scenarios from credential-management spec - 9.7 Write unit tests for
src/services/AuditService.ts— mockAuditRepository; cover query, filter, and retention logic - 9.8 Write unit tests for
src/middleware/auth.ts— valid token, expired token, revoked token, missing header - 9.9 Write unit tests for
src/middleware/errorHandler.ts— eachSentryAgentErrorsubclass maps to correct HTTP status and error code
10. Integration Tests
- 10.1 Write integration tests for Agent Registry (
tests/integration/agents.test.ts) — all 5 endpoints, all response codes, pagination, filtering; uses real Postgres (test DB) and Redis - 10.2 Write integration tests for OAuth2 Token Service (
tests/integration/token.test.ts) — all 3 endpoints, all response codes, token issuance and revocation flow, RFC compliance - 10.3 Write integration tests for Credential Management (
tests/integration/credentials.test.ts) — all 4 endpoints, all response codes, full rotate-then-revoke flow - 10.4 Write integration tests for Audit Log Service (
tests/integration/audit.test.ts) — query with all filter combinations, single event retrieval, retention window enforcement - 10.5 Verify test coverage meets >80% threshold across all services (
npm test -- --coverage)