# AI Agent Prompt: Repo-Aware Security Audit for StratoFusion

## Objective

Conduct a comprehensive security audit of StratoFusion across these three layers:
1. Next.js application security
2. Fly.io rclone service security
3. Neon PostgreSQL data security

Your job is to find verified vulnerabilities, implement only justified fixes, add or update tests, and produce a report with evidence.

## Non-Negotiables

- Verify before claiming a vulnerability. Do not assume the repo is missing a control just because a generic checklist says it should exist.
- Use Git Bash-compatible commands and PNPM. Do not use or assume WSL.
- Do not deploy, rotate secrets, mutate production data, or run destructive commands unless explicitly asked.
- Treat rclone data safety as critical: use dry-run by default when validating destructive flows.
- Reuse existing repo primitives instead of creating duplicates.
- Keep UI rendering-only. Put business logic in domain or service layers.
- Keep files under 500 LOC. Split work if needed.

## Runtime Inputs

Provide these before executing the audit:
- `DATABASE_URL` for read-only verification queries.
- Admin user IDs or `ADMIN_USER_IDS`.
- Fly.io app name.
- Expected environment variable list by environment.
- Optional staging URLs for manual verification.

## Repo Map

Audit against the current repo structure, not against assumed file names:

- Next.js middleware and route protection: `src/middleware.ts`.
- API routes: `src/app/api/**/route.ts`.
- Auth and RBAC helpers: `src/lib/auth/**`.
- API response helpers: `src/lib/api-response.ts`.
- Cron environment guard: `src/lib/cron-environment.ts`.
- DB client bootstrap: `src/lib/database/client.ts`.
- DB schema: `src/lib/database/schema.ts`, `src/lib/database/schema/**`.
- Service account and token storage: `src/lib/database/service-accounts.ts`.
- Token encryption: `src/lib/security/token-encryption.ts`.
- Validation utilities: `src/lib/validation/**`.
- Fly.io client: `src/lib/rclone/core/flyio-client.ts`.
- Fly.io service entrypoint: `fly-rclone/server.js`.
- Fly.io input validation middleware: `fly-rclone/src/middleware/validation.js`.
- Fly.io routes and services: `fly-rclone/src/routes/**`, `fly-rclone/src/services/**`.
- Fly.io config: `fly-rclone/fly.prod.toml`.
- Existing audit logging schema: `src/lib/database/schema/logging.ts`.
- Existing audit log API: `src/app/api/logs/audit/route.ts`.

## Important Existing Behaviors To Verify

- 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.

Suggested script set:
- `scripts/security-audit/01-token-encryption.ts`.
- `scripts/security-audit/02-api-authz-scan.ts`.
- `scripts/security-audit/03-input-validation-scan.ts`.
- `scripts/security-audit/04-secrets-and-logging-scan.ts`.
- `scripts/security-audit/05-fly-rclone-scan.ts`.
- `scripts/security-audit/06-db-security-check.ts`.
- `scripts/security-audit/generate-report.ts`.

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.

The report must include:
- Executive summary.
- Findings grouped by severity.
- Evidence with file references.
- Which findings were fixed now vs deferred.
- Test results.
- Remaining risks and follow-up recommendations.

For each finding, include:
- Severity.
- Affected path(s).
- Why it matters.
- Reproduction or verification notes.
- Fix status.

## Suggested Commands

Use Git Bash-compatible commands like these:

```bash
# Isolated worktree
git worktree add ../stratofusion-security-audit main
cd ../stratofusion-security-audit
pnpm install

# Baseline checks
pnpm check
pnpm test

# Route inventory
find src/app/api -name "route.ts"

# Targeted scans
find src/app/api -name "route.ts" -print | xargs grep -n "auth\|currentUser\|CRON_SECRET"
find src -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" \) -print | xargs grep -n "dangerouslySetInnerHTML\|eval(\|spawn(\|exec("

# Audit scripts
pnpm exec tsx scripts/security-audit/01-token-encryption.ts
pnpm exec tsx scripts/security-audit/02-api-authz-scan.ts
pnpm exec tsx scripts/security-audit/03-input-validation-scan.ts
pnpm exec tsx scripts/security-audit/04-secrets-and-logging-scan.ts
pnpm exec tsx scripts/security-audit/05-fly-rclone-scan.ts
pnpm exec tsx scripts/security-audit/06-db-security-check.ts

# Tests after fixes
pnpm exec vitest run
cd fly-rclone && pnpm exec jest --runInBand
```

## Guardrails For Specific Areas

### Next.js Layer

- Audit both middleware-level and route-level enforcement.
- Do not assume a public route is safe just because middleware allows it through.
- Preserve Clerk auth flows and OAuth callback behavior.
- If adding security headers, merge them into the current middleware implementation.

### Fly.io rclone Layer

- Verify whether the service trusts network locality instead of authenticating callers.
- Inspect `server.js`, route registration, middleware, and command execution paths.
- If auth is missing, prefer aligning server enforcement with the existing client `Authorization: Bearer` behavior.
- Review CORS, allowed headers, health endpoint exposure, and operational endpoints.
- Do not run destructive rclone commands without explicit approval and a dry-run-first plan.

### Database Layer

- Audit `src/lib/database/client.ts` and query call sites for connection security and least-privilege assumptions.
- Verify user scoping in service account, job, log, quota, and operation access patterns.
- Use the current schema names; do not guess table names from old drafts.
- If you need read-only data verification, keep queries minimal and document them in the report.

## Deliverables

Complete the audit only when you have all of the following:

- A verified findings list with severity and evidence.
- Any critical or high-severity fixes implemented.
- Tests added or updated for each implemented fix.
- `SECURITY_AUDIT_REPORT.md` generated.
- `public/docs/SECURITY.md` added or updated.
- A concise summary of commands run, tests run, and anything intentionally not changed.

## Success Criteria

Success means:

- Findings are evidence-based and repo-specific.
- No fake fixes were applied to controls that already exist.
- Any implemented fixes preserve current behavior and architecture.
- Tests pass for changed areas.
- The report clearly separates verified issues, fixed issues, and deferred issues.

## Explicit Anti-Patterns To Avoid

Do not do any of the following:

- Do not assume files like `src/lib/database/db.js` exist when the repo uses `src/lib/database/client.ts`.
- Do not scan for `enc:` when the repo uses `enc:v1:`.
- Do not replace `src/middleware.ts` with a new middleware file.
- Do not invent a new audit table if `system_audit_logs` or existing logging can serve the need.
- Do not hard-code production app names, secrets, or environment values into source.
- Do not deploy to Fly.io, Vercel, or production databases unless explicitly asked after the audit.

## Final Output Format

Return your results in this order:
1. Findings by severity, with file references
2. Fixes implemented
3. Tests executed and results
4. Remaining risks or follow-up items

If you find no verified critical or high-severity issues, state that directly.
