Repository navigation
Gemini + rule-based analysis fallback, login mode, security hardening - #6
Merged
Merged
Conversation
… 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")
|
| 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
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secret safely. Learn here the best practices.
- Revoke and rotate this secret.
- 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
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.mdlisted 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_MODEdefaults todemo(no sign-in), exactly as before.What's in it
11 commits, ordered by dependency. Each one passes
tsc,eslint --max-warnings 0and the test suite on its own (checked in throwaway worktrees), so it can be reviewed or bisected commit by commit.chore(deps)npm audit fix: 49 → 29 advisories, 0 critical. Installs the coverage provider thatnpm run test:coveragealways referenced.feat(auth)AUTH_MODE=login: token required everywhere, per-company/per-owner isolation, startup refuses a placeholderNEXTAUTH_SECRET. Registration closed by default and no longer accepts a client-chosen company.migrate-auth.tsstops issuing the shared hard-coded passwords.feat(ai)POST /api/analyze/bulk, proposals router split (1209 → 434 lines).feat(integrations)state; SSRF guard on the Salesforce instance URL.feat(files)refactor(server)createApp()separate fromlisten(); JSON 404s; no internal error text in production; trust one proxy hop; tests for the routers that had none.chore(web)feat(web)feat(db)npm run check:rlspre-flight. Not applied to any database.chore(lint)no-explicit-anyis now an error (about 50 → 0).docsBUG_REPORT.md.Bugs fixed along the way
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.GET /api/integrationsreturned stored OAuth access/refresh tokens to the browser.statewas a raw user id (forgeable); the Salesforce instance URL was an SSRF vector.POST /api/auth/registerlet anyone pick their own company; any signed-in user could read or delete any stored file.normalizeAnalysisturned a real score of 0 into a default.ol, ulrule, signed-out pages retrying the API forever and toasting "Offline Mode",test:coveragebeing unusable.Behaviour changes to know about
424(was200).integration.credentialsin API responses is a placeholder; usehasCredentials.stateformat changed; the window is 10 minutes) — just retry./api/*paths return JSON 404; production 500s say "Internal server error".proposals/<userId>/...); old flat keys stay readable in demo mode only. The SPA doesn't call these endpoints.Not done by this PR — needs a human
Nothing here touches a database or Render. In order:
GEMINI_API_KEYin the dashboard (and rotate the key that was pasted into chat).User(password hashes) andIntegration(OAuth tokens). SetSUPABASE_SERVICE_ROLE_KEYlocally and on Render first, then followdocs/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.docs/AUTH_QUICKSTART.md.CREDENTIALS.mdis 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 ofsrc/api.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
npm auditadvisories remain; each needs a major upgrade (puppeteer 21 → 25, tailwind 3 → 4, react-router 6 → 7) and a visual/PDF regression pass. Details indocs/DEPLOYMENT.md§7.