Skip to content

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

LayerTechnology
RuntimeCloudflare Workers
DatabaseD1 (SQLite)
AuthenticationPBKDF2 (100k iterations, SHA-256) + JWT HS256 (jose)
ValidationZod schemas
TypesTypeScript with @neemias/schemas (shared package)

Entry Point

The workers/src/index.ts file is the entry point. It:

  1. Creates the router via createRouter() (imported from workers/src/router.ts)
  2. Exposes the fetch handler that dispatches request.method + pathname → registered handler
  3. Injects Env (Cloudflare bindings) and ExecutionContext

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

MiddlewareSourcePurpose
requireAuth()pipeline.tsExtracts the Bearer token, validates the JWT (or dev token), populates ctx.principal
requireRole(roles[])pipeline.tsChecks that ctx.principal.role is in the allowed list
rateLimit({ windowMs, maxRequests })rate-limit.tsIP/key rate limiting using D1

Request Flow

Request
  → rateLimit? (pre-auth)
  → requireAuth (JWT verify or dev token)
  → requireRole (permission check)
  → Handler (business logic)
  → Response

Main Modules

ModuleFileResponsibility
Authworkers/src/modules/auth/Login, refresh token, revocation, session validation
Passwordworkers/src/modules/auth/password.tsPBKDF2 hashing and verification
Session Tokensworkers/src/modules/auth/sessionTokens.tsJWT sign/verify + refresh token creation/rotation
Studentsworkers/src/modules/students/Student CRUD + soft-delete with justification
Attendanceworkers/src/routes/attendance.tsAttendance marking (MARK_PRESENT/MARK_ABSENT)
Syncworkers/src/modules/sync/Offline event processing + conflict resolution
EventReplayworkers/src/modules/sync/eventReplay.tsEvent-based conflict resolution
Idempotencyworkers/src/modules/idempotency.tsPayload hash for the idempotency ledger
Rate Limitworkers/src/middleware/rate-limit.tsRate limiting with D1
Studentsworkers/src/routes/students.tsREST handlers for /students
Usersworkers/src/routes/users.tsREST handlers for /users
Rolesworkers/src/routes/roles.tsREST handlers for /roles
Classesworkers/src/routes/classes.tsREST handlers for /classes
Nucleiworkers/src/routes/nuclei.tsREST handlers for /nuclei
Seedworkers/src/routes/seed.tsDemo data (POST /_seed, dev only)
Security.txtworkers/src/routes/security-txt.tsRFC 9116 (/.well-known/security.txt)

API Prefix

All API routes use the /api/v1 prefix.

Key Files

FilePurpose
workers/src/index.tsEntry point + router bootstrap
workers/src/router.tsDefinition of all routes
workers/src/schemas.tsZod schemas for all request bodies
workers/src/shared/types.tsUserRole, AuthPrincipal, ErrorEnvelope
workers/src/db/d1.tsD1 client factory
workers/src/db/queries.tsReusable queries (auth, idempotency)
workers/src/middleware/auth.tsJWT verification + dev mode + role guard
workers/src/middleware/pipeline.tsroute() helper + built-in middlewares
workers/src/middleware/rate-limit.tsRate limiting via D1
workers/src/shared/errors.tsHttpError class
migrations/0001_init.sqlCore schema (users, students, events, audit)
migrations/0002_auth_sessions.sqlRefresh token sessions
migrations/0007_rate_limits.sqlRate limiting

Source: workers/CONTEXT.md

Distributed under MIT License.