Workers Overview
The Neemias backend runs on Cloudflare Workers with D1 (SQLite) as its serverless database. The whole API is built on a declarative, strongly typed middleware pipeline.
Stack
| Layer | Technology |
|---|---|
| Runtime | Cloudflare Workers |
| Database | D1 (SQLite) |
| Authentication | PBKDF2 (100k iterations, SHA-256) + JWT HS256 (jose) |
| Validation | Zod schemas |
| Types | TypeScript with @neemias/schemas (shared package) |
Entry Point
The workers/src/index.ts file is the entry point. It:
- Creates the router via
createRouter()(imported fromworkers/src/router.ts) - Exposes the
fetchhandler that dispatchesrequest.method + pathname→ registered handler - Injects
Env(Cloudflare bindings) andExecutionContext
Router
The router (workers/src/router.ts) maps each route as a key in the "METHOD /path" format:
typescript
routes["POST /api/v1/students"] = {
handler: route(
"POST",
"/api/v1/students",
[pipelineRequireAuth(), pipelineRequireRole(["ADMIN", "CADASTRO"])],
handleCreateStudentPipeline,
).handler,
};Unknown routes return a 404 with body { error: "NOT_FOUND", message: "Route not found" }.
Middleware Pipeline
The route() helper (workers/src/middleware/pipeline.ts) accepts a declarative array of middlewares that run in sequence before the final handler:
MiddlewareContext
typescript
interface MiddlewareContext {
request: Request;
env: Env;
ctx: ExecutionContext;
principal: AuthPrincipal | null; // populated by requireAuth()
correlationId: string;
}Built-in Middlewares
| Middleware | Source | Purpose |
|---|---|---|
requireAuth() | pipeline.ts | Extracts the Bearer token, validates the JWT (or dev token), populates ctx.principal |
requireRole(roles[]) | pipeline.ts | Checks that ctx.principal.role is in the allowed list |
rateLimit({ windowMs, maxRequests }) | rate-limit.ts | IP/key rate limiting using D1 |
Request Flow
Request
→ rateLimit? (pre-auth)
→ requireAuth (JWT verify or dev token)
→ requireRole (permission check)
→ Handler (business logic)
→ ResponseMain Modules
| Module | File | Responsibility |
|---|---|---|
| Auth | workers/src/modules/auth/ | Login, refresh token, revocation, session validation |
| Password | workers/src/modules/auth/password.ts | PBKDF2 hashing and verification |
| Session Tokens | workers/src/modules/auth/sessionTokens.ts | JWT sign/verify + refresh token creation/rotation |
| Students | workers/src/modules/students/ | Student CRUD + soft-delete with justification |
| Attendance | workers/src/routes/attendance.ts | Attendance marking (MARK_PRESENT/MARK_ABSENT) |
| Sync | workers/src/modules/sync/ | Offline event processing + conflict resolution |
| EventReplay | workers/src/modules/sync/eventReplay.ts | Event-based conflict resolution |
| Idempotency | workers/src/modules/idempotency.ts | Payload hash for the idempotency ledger |
| Rate Limit | workers/src/middleware/rate-limit.ts | Rate limiting with D1 |
| Students | workers/src/routes/students.ts | REST handlers for /students |
| Users | workers/src/routes/users.ts | REST handlers for /users |
| Roles | workers/src/routes/roles.ts | REST handlers for /roles |
| Classes | workers/src/routes/classes.ts | REST handlers for /classes |
| Nuclei | workers/src/routes/nuclei.ts | REST handlers for /nuclei |
| Seed | workers/src/routes/seed.ts | Demo data (POST /_seed, dev only) |
| Security.txt | workers/src/routes/security-txt.ts | RFC 9116 (/.well-known/security.txt) |
API Prefix
All API routes use the /api/v1 prefix.
Key Files
| File | Purpose |
|---|---|
workers/src/index.ts | Entry point + router bootstrap |
workers/src/router.ts | Definition of all routes |
workers/src/schemas.ts | Zod schemas for all request bodies |
workers/src/shared/types.ts | UserRole, AuthPrincipal, ErrorEnvelope |
workers/src/db/d1.ts | D1 client factory |
workers/src/db/queries.ts | Reusable queries (auth, idempotency) |
workers/src/middleware/auth.ts | JWT verification + dev mode + role guard |
workers/src/middleware/pipeline.ts | route() helper + built-in middlewares |
workers/src/middleware/rate-limit.ts | Rate limiting via D1 |
workers/src/shared/errors.ts | HttpError class |
migrations/0001_init.sql | Core schema (users, students, events, audit) |
migrations/0002_auth_sessions.sql | Refresh token sessions |
migrations/0007_rate_limits.sql | Rate limiting |
Source: workers/CONTEXT.md