Skip to content

Gemini + rule-based analysis fallback, login mode, security hardening - #6

Merged
rogerdemello merged 11 commits into
mainfrom
chore/hardening-and-features
Oct 13, 2026
Merged

rogerdemello merged 11 commits into
mainfrom
chore/hardening-and-features

Conversation

@rogerdemello

Copy link
Copy Markdown
Owner

Why

The Azure OpenAI resource this app pointed at no longer resolves in DNS, so every Analyze request failed. Digging into that turned up real bugs and security gaps, and the big routers had no tests. This PR makes analysis work without an AI, adds the multi-user mode that ARCHITECTURE.md listed as the next step, fixes what I found, and takes the test count from 55 to 369 so those routers can be changed safely.

Default behaviour is unchanged — AUTH_MODE defaults to demo (no sign-in), exactly as before.

What's in it

11 commits, ordered by dependency. Each one passes tsc, eslint --max-warnings 0 and the test suite on its own (checked in throwaway worktrees), so it can be reviewed or bisected commit by commit.

Commit Summary
chore(deps) npm audit fix: 49 → 29 advisories, 0 critical. Installs the coverage provider that npm run test:coverage always referenced.
feat(auth) AUTH_MODE=login: token required everywhere, per-company/per-owner isolation, startup refuses a placeholder NEXTAUTH_SECRET. Registration closed by default and no longer accepts a client-chosen company. migrate-auth.ts stops issuing the shared hard-coded passwords.
feat(ai) Provider-agnostic LLM client (Gemini → Azure → none), Gemini embeddings, deterministic rule-based analysis fallback, POST /api/analyze/bulk, proposals router split (1209 → 434 lines).
feat(integrations) HubSpot / Gmail / Salesforce sync split into connectors; OAuth tokens no longer sent to the browser; signed OAuth state; SSRF guard on the Salesforce instance URL.
feat(files) Per-user storage folders, type allow-list, 7 MB cap, signed links, path-traversal guard.
refactor(server) createApp() separate from listen(); JSON 404s; no internal error text in production; trust one proxy hop; tests for the routers that had none.
chore(web) Vendor chunks, and the Vite dev proxy prints one line per API outage instead of a stack trace per request.
feat(web) Sign-in page, lazy routes (first-load JS 529 → 245 kB gzipped), "Run analysis" / "Analyze (n)", integrations UX fixes.
feat(db) Row-level-security migration + npm run check:rls pre-flight. Not applied to any database.
chore(lint) no-explicit-any is now an error (about 50 → 0).
docs README, SETUP, DEPLOYMENT, ARCHITECTURE, auth and semantic-search docs; removes the stale BUG_REPORT.md.

Bugs fixed along the way

  • Analysis never advanced a proposal to In Review. The handler wrote Proposal.readinessScore, a column that doesn't exist on the live table, and ignored the error — so the whole update silently failed. It would also have pushed APPROVED proposals back to IN_REVIEW.
  • A failed CRM sync answered HTTP 200, so the UI said "Sync complete" and its reconnect logic never ran.
  • CRM imports were assigned to the first user in the table (Salesforce fell back to a hard-coded id), and Gmail imports lost the company.
  • GET /api/integrations returned stored OAuth access/refresh tokens to the browser.
  • OAuth state was a raw user id (forgeable); the Salesforce instance URL was an SSRF vector.
  • POST /api/auth/register let anyone pick their own company; any signed-in user could read or delete any stored file.
  • normalizeAnalysis turned a real score of 0 into a default.
  • Without trusting the proxy, every Render visitor shared one rate-limit bucket (10 failed logins would lock everyone out).
  • Smaller: leaked Chrome process on a failed PDF export, a stray CSS block dropping the ol, ul rule, signed-out pages retrying the API forever and toasting "Offline Mode", test:coverage being unusable.

Behaviour changes to know about

  • After deploy, analysing a healthy (≥ 80) PENDING proposal will now actually move it to IN_REVIEW — the original intent, which never worked.
  • A failed sync is 424 (was 200). integration.credentials in API responses is a placeholder; use hasCredentials.
  • OAuth flows started before deploy fail once (the state format changed; the window is 10 minutes) — just retry.
  • Unknown /api/* paths return JSON 404; production 500s say "Internal server error".
  • Files: new key layout (proposals/<userId>/...); old flat keys stay readable in demo mode only. The SPA doesn't call these endpoints.
  • Embeddings now come from Gemini. Vectors from different models aren't comparable — see the steps below.

Not done by this PR — needs a human

Nothing here touches a database or Render. In order:

  1. Render: add GEMINI_API_KEY in the dashboard (and rotate the key that was pasted into chat).
  2. Semantic search — switch to the HNSW index and re-embed with Gemini:
    npx prisma db execute --file prisma/manual/semantic_search.sql
    npm run backfill:embeddings -- --all
  3. Row Level Security is off on all 9 tables, so the public anon key can read User (password hashes) and Integration (OAuth tokens). Set SUPABASE_SERVICE_ROLE_KEY locally and on Render first, then follow docs/DEPLOYMENT.md §6 (npm run check:rls → enable_rls.sql → npm run check:rls -- --verify). Running the SQL before the key is set would cut the API off from its own database.
  4. Multi-user mode (optional): docs/AUTH_QUICKSTART.md.
  5. CREDENTIALS.md is gone from the tree but still in git history; those credentials should be rotated.

Verification

  • npm run lint && npm run typecheck && npm test && npm run build — all pass; 369 tests (was 55), ~89 % line coverage of src/api.
  • Each of the 11 commits passes tsc + eslint + tests when checked out on its own.
  • The real frontend was driven in a browser against a fake-data stub API: demo mode, sign-in / sign-out, returning to a deep link after sign-in, bulk analysis, "Re-run analysis", a failed sync flipping the card back to Connect, and the OAuth start-token handshake.
  • The Vite proxy fix was checked against a dead and a live backend (one notice per outage, proxying still works).
  • The extracted PDF module was exercised with real headless Chrome (fake data, no DB): two concurrent exports were serialized, both came out as valid 10-page PDFs, no Chrome process was left behind, and the cover page and the numbered "Next Steps" list were inspected visually. (The unit tests mock Puppeteer.)

Not covered: nothing was exercised against a real Supabase project or a real CRM, and there are no automated browser tests. The route tests use a Supabase stand-in (tests/helpers/supabaseMock.ts).

Known gaps / follow-ups

  • Proposal version history isn't built: the app has no way to edit a proposal's content, so there's nothing to version yet.
  • Password reset, email verification and 2FA are not implemented.
  • 29 npm audit advisories remain; each needs a major upgrade (puppeteer 21 → 25, tailwind 3 → 4, react-router 6 → 7) and a visual/PDF regression pass. Details in docs/DEPLOYMENT.md §7.
  • Helmet's CSP is still disabled.

… provider

`npm audit fix` took the advisory count from 49 (4 critical) to 29 (0 critical).
The rest only fix via major upgrades or downgrades (puppeteer 21->25, tailwindcss
3->4, react-router 6->7, prisma and mammoth) and are documented rather than forced.

- install @vitest/coverage-v8: `npm run test:coverage` has always referenced it,
  but it was never installed
- vitest.config.ts: derive the alias path from import.meta.url instead of
  __dirname (Vite warns that __dirname in config files is going away)
- add `check:rls` and `set-passwords` npm scripts (the scripts themselves land in
  later commits)
The default stays `demo` (no sign-in; every visitor is the default user), so
nothing changes unless AUTH_MODE=login is set.

Login mode
- every protected route needs a valid bearer token and there is no default
  identity (401 AUTH_REQUIRED); a database outage with a valid token is a 503,
  not a 401
- the server refuses to start without a real NEXTAUTH_SECRET
- data is isolated per company; users without a company only see rows they own
  (canAccessResource / listScope)
- GET /api/auth/config (public) tells the SPA which mode it is talking to
- tokens that are not session tokens (OAuth start/state tokens) are never
  accepted as a session

Account handling
- POST /api/auth/register is closed unless ALLOW_SELF_REGISTRATION=true and no
  longer takes a client-supplied companyId (anyone could join any tenant);
  emails are normalised to lower case and duplicates are detected reliably
- users API: in login mode the list is admin-only and non-admins can read only
  themselves; admins can set a password and company on create/update; roles are
  validated; a duplicate email is a 409; admins cannot delete themselves
- scripts/migrate-auth.ts gave every user the same hard-coded password
  (ChangeMe@123) and created an admin with Admin@123. It now issues a different
  random password per user, printed once, and supports --dry-run and --reset
- prisma/manual/multi_user.sql: User.company_id, lookup indexes and a
  case-insensitive unique email

29 new tests.
… bulk analysis

The Azure OpenAI resource this app pointed at no longer resolves in DNS, so every
Analyze request failed. Analysis now survives that, and the AI provider is
swappable.

AI provider
- lib/llm.ts: Gemini (via its OpenAI-compatible endpoint) when GEMINI_API_KEY is
  set, else Azure OpenAI, else none. Resolved lazily, so the server boots with no
  AI configured. Gemini 2.5's hidden "thinking" tokens count against max_tokens and
  truncated the JSON answer, so reasoning_effort is "none".
- lib/embeddings.ts: Gemini gemini-embedding-001 at 1536 dimensions (the pgvector
  column width), unit-normalised, with a width check. After switching provider run
  `npm run backfill:embeddings -- --all`.
- semantic_search.sql: HNSW index instead of ivfflat (lists=100 probes a single
  list, which returns few or no rows on a small table)

Analysis
- lib/ruleAnalysis.ts: deterministic fallback. It extracts the discount, deal value
  and payment term from the text, checks the required clauses and sections, and
  applies the thresholds from the active Rule rows. Used when the AI is
  unconfigured, unreachable, slow (45s) or returns unusable JSON, and with
  ANALYSIS_MODE=rules. Reports say which engine produced them (analysisSource and
  an ANALYSIS MODE finding).
- lib/analysisService.ts + analyze.ts: POST /api/analyze/bulk (max 10 ids) and
  GET /api/analyze/mode
- fix: the handler updated Proposal.readinessScore, a column that does not exist on
  the live table, and ignored the error, so the whole update (including the
  auto-advance to IN_REVIEW) silently never happened. It now writes only real
  columns, checks the result, and only advances PENDING proposals (it would have
  pushed APPROVED ones back to IN_REVIEW).
- fix: normalizeAnalysis turned a genuine 0 into a default (readiness 0 became 50,
  0% risk became 20)

Proposals router (1209 -> 434 lines)
- the PDF template, the generation prompt and the create/audit/embedding
  persistence moved to lib/proposalPdf, proposalGeneration and proposalStore. The
  generation prompt text is byte-identical to the old one.
- generation validates and clamps what the model returns (NaN discount or deal
  size, missing fields) and answers 424 AI_UNAVAILABLE instead of 500 when the
  provider is down
- PDF export: Chrome is always closed (a failed export leaked a process), exports
  run one at a time and are rate limited, and a stray CSS block that made browsers
  drop the `ol, ul` rule is removed
- list, search and analytics scope non-admins by company, or by owner in login mode

Adds tests/helpers/supabaseMock.ts, a table-aware Supabase stand-in used by the
route tests.
…h tokens

integrations.ts (1043 lines) had the HubSpot, Gmail and Salesforce sync inlined in
one handler. Each CRM is now a connector under lib/sync/ behind a runSync
dispatcher, and oauth.ts's copy-pasted find-or-create block (about ten copies) is
one helper.

Bugs fixed along the way
- a failed sync answered HTTP 200, so the UI said "Sync complete" and its
  reconnect logic never ran. It now answers 424 with the reason and
  needsReconnect, and a failed sync no longer bumps lastSyncAt.
- imported records were assigned to the first user in the User table (Salesforce
  fell back to a hard-coded id from another database); they now belong to the
  integration's owner. Gmail imports also lost the company. "Already imported" is
  now per user.
- GET /api/integrations returned the stored OAuth access and refresh tokens to the
  browser; responses now carry hasCredentials and a placeholder instead
- the OAuth `state` was the raw user id, so a callback could be forged for another
  user. It is now a signed 10-minute token, and the /authorize redirects take a
  2-minute single-purpose start token (POST /api/oauth/start-token) instead of the
  7-day session token in the URL.
- the Salesforce instance URL lives in user-editable credentials and was fetched
  with the user's token attached: server-side request forgery. It must now be an
  https Salesforce domain, including after a token refresh.
- the Gmail sync stored full email bodies in the sync log; it now keeps the
  envelope only. Several messages of one thread no longer create several proposals.
- every CRM call has a 20s timeout, and a failed token refresh asks for a reconnect
- the HubSpot private-app token is admin-only in login mode (it is shared access)
- connect flows no longer redirect with success when the database write failed
- "9,500" was parsed as 9; amounts are now parsed properly

87 new tests (connectors with fetch stubbed, the routes, OAuth state).
…inks

Any signed-in user could download or delete any stored file by guessing its name,
and any file type could be uploaded.

- uploads go to proposals/<userId>/<timestamp>_<name>; downloads and deletes take
  the returned filePath and are confined to the caller's folder (admins can reach
  everything; the old flat keys stay readable in demo mode only)
- only pdf, docx, doc, txt, md and rtf, at most 7 MB, served with a matching
  Content-Type and as an attachment
- ".." and empty path segments are rejected
- uploads return a time-limited signed URL, so the bucket does not need to be
  public (prisma/manual/enable_rls.sql makes it private)

25 new tests.
server.ts started listening at import, so the app could not be mounted in a test.
src/api/app.ts now exports createApp(); server.ts is only the process bootstrap.

- unknown /api/* paths answer a JSON 404 (they fell through to an HTML page)
- the error handler no longer returns internal error messages in production
  (database errors included); malformed JSON is a 400 and an oversized body a 413
  instead of a 500
- trust one proxy hop in production (TRUST_PROXY): behind Render every visitor
  looked like the proxy, so the per-IP rate limits were shared by everyone and ten
  failed logins from anywhere would have locked every user out
- startup refuses an unsafe auth configuration
- the remaining console.* calls in the routers go through the logger, and rules.ts
  loses its `any`s
- tests for the app wiring and for the routers that had none: rules, templates,
  audit, notifications, analytics and password change
…line

Build
- group React, the router, Radix, motion and the chart library into vendor chunks,
  and pin the tiny cn() helpers (clsx, tailwind-merge, cva) to their own chunk.
  recharts depends on clsx too, and without that Rollup parked it in the charts
  chunk, so every page load downloaded the whole chart library. Together with the
  lazy routes in a later commit, first-load JavaScript goes from 529 kB to 245 kB
  gzipped.

Dev server
- while the API restarts, every proxied request logged a multi-line
  ECONNREFUSED/ECONNRESET stack trace (a page makes about a dozen requests a
  second). The old `proxy.on("error")` no-op could never silence them: Vite
  attaches its own logging handler after `configure` runs. A custom logger now
  prints one line per outage and re-arms when the API answers; every other proxy
  error is still logged in full.
…ations UX

Sign-in (shown only when the server runs AUTH_MODE=login)
- use-session is now the app's auth store: it learns the mode from
  /api/auth/config, flips to the sign-in page on 401 AUTH_REQUIRED, and signing in
  returns you to the page you were headed for (same-site paths only)
- Login page (with account creation when the server allows it) and a sign-out button
- ProposalProvider stops fetching, retrying and polling while sign-in is required.
  It retried every 2s, then polled, and finally toasted "Offline Mode" over the
  sign-in page.
- /login, /auth and /signup redirect to the dashboard only once the session check
  has finished, so /login is not rewritten to /dashboard in login mode
- authFetch() for non-JSON requests (PDF export, files); filesApi uses the new paths

Analysis
- "Run analysis" / "Re-run analysis" on the review page (it said "Run analysis" but
  offered no way to) and "Analyze (n)" for a selection on the proposals list; the
  toast says when the rule checker produced the report

Integrations
- the connected state comes from hasCredentials (tokens no longer reach the browser)
- Connect fetches the short-lived OAuth start token first
- a failed sync shows its reason and, when the connection was revoked, flips the card
  back to Connect (the server used to answer 200, so this never worked)
- readable messages for the new OAuth error codes

Every page is a lazy route. Also removes the last explicit `any`s from the pages and
types.
Row Level Security is off on all nine tables, so the public Supabase anon key can
read the User table (password hashes) and the Integration table (CRM OAuth tokens).

- prisma/manual/enable_rls.sql enables RLS with no policies (the API uses the
  service-role key, which bypasses it), restricts match_proposals to the service
  role, drops the anon storage policies and makes the bucket private
- scripts/check-rls.ts (`npm run check:rls`) must pass BEFORE the SQL is run: it
  checks that SUPABASE_SERVICE_ROLE_KEY is a service_role key for this project and
  can read the database. `-- --verify` afterwards confirms the anon key can no
  longer read User, Integration or Proposal. Read-only; keys are never printed.

This commit does not change any database.
Use `unknown` and narrow, or a real interface, at API/JSON boundaries. The roughly
fifty explicit anys the codebase started this work with are gone, so the rule is an
error rather than advisory.
- README, SETUP, DEPLOYMENT, ARCHITECTURE: AI provider options and the rule-checker
  fallback, AUTH_MODE and going multi-user, locking down the database, and the
  npm audit advisories that are deliberately left
- docs/AUTH_QUICKSTART.md is rewritten: it described an animated login page and a
  protected-route component that no longer exist
- SETUP.md and start.bat no longer claim a "demo" password for seeded accounts
  that have none
- docs/SEMANTIC_SEARCH.md: providers, HNSW, re-embedding after a provider change
- .env.example and render.yaml: GEMINI_*, AUTH_MODE, ANALYSIS_MODE, TRUST_PROXY. The
  Azure block in .env.example is commented out so a fresh copy has no placeholder
  endpoint to wait on.
- remove BUG_REPORT.md (February 2026, "no bugs found")
Copilot AI balanced review requested due to automatic review settings October 13, 2026 08:04
@gitguardian

gitguardian Bot commented Oct 13, 2026

Copy link
Copy Markdown

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
38157323 Triggered Generic High Entropy Secret a174d02 src/api/lib/oauthState.test.ts View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@rogerdemello
rogerdemello merged commit 0b4c40d into main Oct 13, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants