Token encryption already exists and uses enc:v1: semantics via isEncryptedTokenValue() in src/lib/security/token-encryption.ts.
Service tokens are stored through src/lib/database/service-accounts.ts, not through a guessed db.js module.
The Next.js app already has Clerk middleware in src/middleware.ts; do not replace it when adding headers or route protection.
The Fly.io client already supports Authorization: Bearer <apiKey> in src/lib/rclone/core/flyio-client.ts; verify whether the server enforces it.
Cron routes already use CRON_SECRET patterns and guardProductionCronRequest() in at least some handlers; audit consistency, not just presence.
Structured logging tables already exist under src/lib/database/schema/logging.ts; do not invent a duplicate audit table if the current schema can be extended safely.
Audit Workflow
Phase 1: Recon and Threat Model
Start by reading the existing implementation and writing down confirmed controls, gaps, and attack surfaces.
Focus on:
Authentication and session handling.
Authorization and IDOR risks.
Input validation and normalization.
Command injection and path traversal risks.
Secret handling and sensitive logging.
Network exposure and service-to-service trust.
Database connection security and unsafe query patterns.
Audit logging and incident investigation readiness.
Do not start by writing fixes. Start by producing a short evidence-backed finding list with file references.
Phase 2: Automated Audit Scripts
Create repo-aware scripts under scripts/security-audit/ only where they add signal. These scripts must match the real codebase:
Prefer static analysis for route scanning and configuration checks.
If a script needs to import TypeScript modules, use pnpm exec tsx rather than assuming .js sources exist.
If a script needs database access, use the current schema/table names from src/lib/database/schema.ts and src/lib/database/schema/**.
If a script checks token encryption, reuse isEncryptedTokenValue() or the enc:v1: prefix. Do not hard-code enc:.
If a script checks Fly auth, verify server-side enforcement of the same auth model the client already uses.
If a script checks middleware hardening, merge with the existing Clerk middleware model instead of proposing a replacement.
Add a single runner script that works in Git Bash and uses PNPM consistently.
Phase 3: Manual Review Checklist
Review these areas with concrete repo context:
Public route exceptions in src/middleware.ts, especially /api/google(.*), /api/onedrive(.*), /api/dropbox(.*), /api/rclone(.*), cron routes, SSE routes, and admin routes.
Route handlers that touch another user's resources or accept account IDs, job IDs, operation IDs, folder IDs, or file IDs.
DB reads and writes for missing userId scoping.
Any raw SQL or dynamic query construction.
Token reads, writes, and logs in src/lib/database/service-accounts.ts and auth/token refresh flows.
Cron endpoints for both bearer-token validation and environment gating.
Fly.io service endpoints for missing service authentication, weak trust assumptions, missing rate limiting, weak CORS, or command construction issues.
Any use of child_process, spawn, string-built shell arguments, or rclone path/config interpolation.
Logging paths that may capture tokens, secrets, API keys, passwords, raw configs, or provider credentials.
Existing audit log coverage for sensitive operations such as copy, move, delete, token refresh, account connect/disconnect, cron-triggered execution, and admin reads.
Phase 4: Implement Only Verified Fixes
If you confirm critical or high-severity issues, fix them with the existing architecture in mind:
Extend src/middleware.ts; do not replace Clerk middleware.
Reuse src/lib/security/token-encryption.ts for token encryption checks or migrations.
Reuse existing RBAC helpers in src/lib/auth/roles.ts and src/lib/auth/role-utils.ts.
Reuse response helpers from src/lib/api-response.ts.
Reuse or extend existing structured logging rather than introducing parallel logging systems.
Keep provider-specific handling inside adapters/services, not UI routes or components.
Add // Reason: comments only for non-obvious security trade-offs.
Potential fix categories:
Enforce service-to-service auth on Fly routes if missing.
Tighten public route exposure where handlers rely on middleware exemptions.
Add missing user ownership checks.
Harden validation for file IDs, path refs, and remote names.
Scrub sensitive data from logs.
Tighten DB bootstrap validation without breaking safe build-time imports.
Extend audit logging for sensitive operations.
If no critical or high issue is verified, say so explicitly and avoid unnecessary code churn.
Phase 5: Tests
Add or update focused tests near the code you touch:
Main app: use vitest.
Fly service: use jest.
Required coverage for any fix:
Unauthorized request rejected.
Cross-user access blocked.
Malformed input rejected.
Happy-path behavior preserved.
Sensitive values not exposed in logs or responses where applicable.
Prefer colocated tests in existing __tests__ directories instead of inventing a new test structure.
Phase 6: Reporting and Docs
Produce:
SECURITY_AUDIT_REPORT.md at the repo root.
public/docs/SECURITY.md if it does not exist, or update it if it does.