From 7bc96f23ddac56fb3c92a5227fa9afe5bb7f3ce4 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:10 +0530 Subject: [PATCH 01/11] chore(deps): apply non-breaking npm audit fixes, install the coverage 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) --- package-lock.json | 2329 +++++++++++++++++++++++++++------------------ package.json | 5 +- vitest.config.ts | 4 +- 3 files changed, 1411 insertions(+), 927 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0a2f2d0..7235962 100644 --- a/package-lock.json +++ b/package-lock.json @@ -93,6 +93,7 @@ "@types/supertest": "^7.2.0", "@types/uuid": "^10.0.0", "@vitejs/plugin-react-swc": "^3.11.0", + "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.4.21", "eslint": "^9.32.0", "eslint-plugin-react-hooks": "^5.2.0", @@ -135,15 +136,41 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/@babel/runtime": { "version": "7.28.6", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz", @@ -153,98 +180,55 @@ "node": ">=6.9.0" } }, - "node_modules/@chevrotain/cst-dts-gen": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-10.5.0.tgz", - "integrity": "sha512-lhmC/FyqQ2o7pGK4Om+hzuDrm9rhFYIJ/AXoQBeongmn870Xeb0L6oGEiuR8nohFNL5sMaQEJWCxr1oIVIVXrw==", - "license": "Apache-2.0", + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "devOptional": true, + "license": "MIT", "dependencies": { - "@chevrotain/gast": "10.5.0", - "@chevrotain/types": "10.5.0", - "lodash": "4.17.21" + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@chevrotain/gast": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-10.5.0.tgz", - "integrity": "sha512-pXdMJ9XeDAbgOWKuD1Fldz4ieCs6+nLNmyVhe2gZVqoO7v8HXuHYs5OV2EzUtbuai37TlOAQHrTDvxMnvMJz3A==", - "license": "Apache-2.0", - "dependencies": { - "@chevrotain/types": "10.5.0", - "lodash": "4.17.21" + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" } }, - "node_modules/@chevrotain/types": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-10.5.0.tgz", - "integrity": "sha512-f1MAia0x/pAVPWH/T73BJVyO2XU5tI4/iE7cnxb7tqdNTNhQI3Uq3XkqcoteTmD4t1aM0LbHCJOhgIDn07kl2A==", - "license": "Apache-2.0" - }, - "node_modules/@chevrotain/utils": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-10.5.0.tgz", - "integrity": "sha512-hBzuU5+JjB2cqNZyszkDHZgOSrUUT8V3dhgRl8Q9Gp6dAj/H5+KILGjbhDpc3Iy9qmqlm/akuOI2ut9VUtzJxQ==", - "license": "Apache-2.0" - }, "node_modules/@electric-sql/pglite": { - "version": "0.3.15", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.3.15.tgz", - "integrity": "sha512-Cj++n1Mekf9ETfdc16TlDi+cDDQF0W7EcbyRHYOAeZdsAe8M/FJg18itDTSwyHfar2WIezawM9o0EKaRGVKygQ==", + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.3.tgz", + "integrity": "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ==", "license": "Apache-2.0" }, "node_modules/@electric-sql/pglite-socket": { - "version": "0.0.20", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.0.20.tgz", - "integrity": "sha512-J5nLGsicnD9wJHnno9r+DGxfcZWh+YJMCe0q/aCgtG6XOm9Z7fKeite8IZSNXgZeGltSigM9U/vAWZQWdgcSFg==", + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.1.3.tgz", + "integrity": "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ==", "license": "Apache-2.0", "bin": { "pglite-server": "dist/scripts/server.js" }, "peerDependencies": { - "@electric-sql/pglite": "0.3.15" + "@electric-sql/pglite": "0.4.3" } }, "node_modules/@electric-sql/pglite-tools": { - "version": "0.2.20", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite-tools/-/pglite-tools-0.2.20.tgz", - "integrity": "sha512-BK50ZnYa3IG7ztXhtgYf0Q7zijV32Iw1cYS8C+ThdQlwx12V5VZ9KRJ42y82Hyb4PkTxZQklVQA9JHyUlex33A==", + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite-tools/-/pglite-tools-0.3.3.tgz", + "integrity": "sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg==", "license": "Apache-2.0", "peerDependencies": { - "@electric-sql/pglite": "0.3.15" - } - }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "@electric-sql/pglite": "0.4.3" } }, "node_modules/@esbuild/aix-ppc64": { @@ -912,18 +896,6 @@ "@hapi/hoek": "^11.0.2" } }, - "node_modules/@hono/node-server": { - "version": "1.19.9", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz", - "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==", - "license": "MIT", - "engines": { - "node": ">=18.14.1" - }, - "peerDependencies": { - "hono": "^4" - } - }, "node_modules/@hookform/resolvers": { "version": "3.10.0", "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz", @@ -934,29 +906,43 @@ } }, "node_modules/@humanfs/core": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", - "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", "dev": true, "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, "engines": { "node": ">=18.18.0" } }, "node_modules/@humanfs/node": { - "version": "0.16.7", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", - "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@humanfs/core": "^0.19.1", + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" }, "engines": { "node": ">=18.18.0" } }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, "node_modules/@humanwhocodes/module-importer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", @@ -1020,36 +1006,21 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@mrleebo/prisma-ast": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/@mrleebo/prisma-ast/-/prisma-ast-0.13.1.tgz", - "integrity": "sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw==", - "license": "MIT", - "dependencies": { - "chevrotain": "^10.5.0", - "lilconfig": "^2.1.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", - "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" } }, "node_modules/@noble/hashes": { @@ -1101,13 +1072,13 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.133.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz", - "integrity": "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==", + "version": "0.153.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", + "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", "dev": true, "license": "MIT", "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" } }, "node_modules/@paralleldrive/cuid2": { @@ -1162,14 +1133,14 @@ "license": "Apache-2.0" }, "node_modules/@prisma/config": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@prisma/config/-/config-7.3.0.tgz", - "integrity": "sha512-QyMV67+eXF7uMtKxTEeQqNu/Be7iH+3iDZOQZW5ttfbSwBamCSdwPszA0dum+Wx27I7anYTPLmRmMORKViSW1A==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-7.10.0.tgz", + "integrity": "sha512-Rcg828gIRE3HOQ3pOATFjV5d/P0U9OIobxhd/IMxlfWjA4vru0eGwb0AIwFw0rmcLMVShohZYWPixVxkBHsxUA==", "license": "Apache-2.0", "dependencies": { - "c12": "3.1.0", + "c12": "3.3.4", "deepmerge-ts": "7.1.5", - "effect": "3.18.4", + "effect": "3.20.0", "empathic": "2.0.0" } }, @@ -1180,27 +1151,25 @@ "license": "Apache-2.0" }, "node_modules/@prisma/dev": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@prisma/dev/-/dev-0.20.0.tgz", - "integrity": "sha512-ovlBYwWor0OzG+yH4J3Ot+AneD818BttLA+Ii7wjbcLHUrnC4tbUPVGyNd3c/+71KETPKZfjhkTSpdS15dmXNQ==", + "version": "0.24.17", + "resolved": "https://registry.npmjs.org/@prisma/dev/-/dev-0.24.17.tgz", + "integrity": "sha512-UvdZzmpFwknnfreh6Jije84ekkYGPYEJhXG1tFzCsCfQyzJifrOo38eZc0qajzvaC6OLUOrN9ML5XfCnEZL9DA==", "license": "ISC", "dependencies": { - "@electric-sql/pglite": "0.3.15", - "@electric-sql/pglite-socket": "0.0.20", - "@electric-sql/pglite-tools": "0.2.20", - "@hono/node-server": "1.19.9", - "@mrleebo/prisma-ast": "0.13.1", + "@electric-sql/pglite": "0.4.3", + "@electric-sql/pglite-socket": "0.1.3", + "@electric-sql/pglite-tools": "0.3.3", "@prisma/get-platform": "7.2.0", "@prisma/query-plan-executor": "7.2.0", + "@prisma/streams-local": "0.1.11", + "find-my-way": "9.7.0", "foreground-child": "3.3.1", "get-port-please": "3.2.0", - "hono": "4.11.4", - "http-status-codes": "2.3.0", "pathe": "2.0.3", "proper-lockfile": "4.1.2", "remeda": "2.33.4", "std-env": "3.10.0", - "valibot": "1.2.0", + "valibot": "1.4.2", "zeptomatch": "2.1.0" } }, @@ -1214,51 +1183,63 @@ } }, "node_modules/@prisma/engines": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.3.0.tgz", - "integrity": "sha512-cWRQoPDXPtR6stOWuWFZf9pHdQ/o8/QNWn0m0zByxf5Kd946Q875XdEJ52pEsX88vOiXUmjuPG3euw82mwQNMg==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.10.0.tgz", + "integrity": "sha512-KNumN6NHFwybvfdYzTee9pqwx5PvknpWAaHn6L5NsbrKdl+SQrsVZs9opKs6U6SAsvB26HDt3WybRjOhgoWOYQ==", "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "@prisma/debug": "7.3.0", - "@prisma/engines-version": "7.3.0-16.9d6ad21cbbceab97458517b147a6a09ff43aa735", - "@prisma/fetch-engine": "7.3.0", - "@prisma/get-platform": "7.3.0" + "@prisma/debug": "7.10.0", + "@prisma/engines-version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "@prisma/fetch-engine": "7.10.0", + "@prisma/get-platform": "7.10.0" } }, "node_modules/@prisma/engines-version": { - "version": "7.3.0-16.9d6ad21cbbceab97458517b147a6a09ff43aa735", - "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.3.0-16.9d6ad21cbbceab97458517b147a6a09ff43aa735.tgz", - "integrity": "sha512-IH2va2ouUHihyiTTRW889LjKAl1CusZOvFfZxCDNpjSENt7g2ndFsK0vdIw/72v7+jCN6YgkHmdAP/BI7SDgyg==", + "version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3.tgz", + "integrity": "sha512-8OJ6RuZTZ06eFUOtBwxVmv8XMmOW6HWN5F+uxUbZkGxR0Bfab1dfAdXaHPmR5mb59E+fmUo8IOzXlbLY1SClbw==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines/node_modules/@prisma/debug": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.10.0.tgz", + "integrity": "sha512-caygJKtltmRIgdJ3jRpkOr7yM4DW6zxo5uOmojKWFb3asnxWoRkQOwZmXBgD8FZp4htrX+nMpcWqDwzlQ1+Y4g==", "license": "Apache-2.0" }, "node_modules/@prisma/engines/node_modules/@prisma/get-platform": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.3.0.tgz", - "integrity": "sha512-N7c6m4/I0Q6JYmWKP2RCD/sM9eWiyCPY98g5c0uEktObNSZnugW2U/PO+pwL0UaqzxqTXt7gTsYsb0FnMnJNbg==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.10.0.tgz", + "integrity": "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w==", "license": "Apache-2.0", "dependencies": { - "@prisma/debug": "7.3.0" + "@prisma/debug": "7.10.0" } }, "node_modules/@prisma/fetch-engine": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-7.3.0.tgz", - "integrity": "sha512-Mm0F84JMqM9Vxk70pzfNpGJ1lE4hYjOeLMu7nOOD1i83nvp8MSAcFYBnHqLvEZiA6onUR+m8iYogtOY4oPO5lQ==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-7.10.0.tgz", + "integrity": "sha512-Zqyu8DY14t6W/xwmAxUYWCXtHrvQnSvT644EAZSsdM8NSmCS74vJJbBKdVsK3ucFpnUWkEpbO1a0CxJXrg130g==", "license": "Apache-2.0", "dependencies": { - "@prisma/debug": "7.3.0", - "@prisma/engines-version": "7.3.0-16.9d6ad21cbbceab97458517b147a6a09ff43aa735", - "@prisma/get-platform": "7.3.0" + "@prisma/debug": "7.10.0", + "@prisma/engines-version": "7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3", + "@prisma/get-platform": "7.10.0" } }, + "node_modules/@prisma/fetch-engine/node_modules/@prisma/debug": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.10.0.tgz", + "integrity": "sha512-caygJKtltmRIgdJ3jRpkOr7yM4DW6zxo5uOmojKWFb3asnxWoRkQOwZmXBgD8FZp4htrX+nMpcWqDwzlQ1+Y4g==", + "license": "Apache-2.0" + }, "node_modules/@prisma/fetch-engine/node_modules/@prisma/get-platform": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.3.0.tgz", - "integrity": "sha512-N7c6m4/I0Q6JYmWKP2RCD/sM9eWiyCPY98g5c0uEktObNSZnugW2U/PO+pwL0UaqzxqTXt7gTsYsb0FnMnJNbg==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.10.0.tgz", + "integrity": "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w==", "license": "Apache-2.0", "dependencies": { - "@prisma/debug": "7.3.0" + "@prisma/debug": "7.10.0" } }, "node_modules/@prisma/get-platform": { @@ -1282,11 +1263,78 @@ "integrity": "sha512-EOZmNzcV8uJ0mae3DhTsiHgoNCuu1J9mULQpGCh62zN3PxPTd+qI9tJvk5jOst8WHKQNwJWR3b39t0XvfBB0WQ==", "license": "Apache-2.0" }, + "node_modules/@prisma/streams-local": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/@prisma/streams-local/-/streams-local-0.1.11.tgz", + "integrity": "sha512-0TcebL559MByKqTJ+SsrFIEg228iw8UCVRFckzgfRSiJqczhs+MuAgWOF9lnOIV/IVqvu+KMnFTH0eDeTQMpUg==", + "license": "Apache-2.0", + "dependencies": { + "ajv": "^8.12.0", + "better-result": "^2.7.0", + "env-paths": "^3.0.0", + "proper-lockfile": "^4.1.2" + }, + "engines": { + "bun": ">=1.2.0", + "node": ">=22.0.0" + } + }, + "node_modules/@prisma/streams-local/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@prisma/streams-local/node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@prisma/streams-local/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, "node_modules/@prisma/studio-core": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/@prisma/studio-core/-/studio-core-0.13.1.tgz", - "integrity": "sha512-agdqaPEePRHcQ7CexEfkX1RvSH9uWDb6pXrZnhCRykhDFAV0/0P3d07WtfiY8hZWb7oRU4v+NkT4cGFHkQJIPg==", + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/@prisma/studio-core/-/studio-core-0.33.0.tgz", + "integrity": "sha512-V2fX/nKEymNTrHXwfP26PGjoLStO35Ogu+ex7CFJbLrMYEcZxxZpiSNOs7px23Hk5mzLWvM5RsqG6Ka+rha+wg==", "license": "Apache-2.0", + "dependencies": { + "@radix-ui/react-toggle": "1.1.10", + "@visx/curve": "4.0.1-alpha.0", + "@visx/event": "4.0.1-alpha.0", + "@visx/grid": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/responsive": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/shape": "4.0.1-alpha.0", + "d3-array": "3.2.4", + "d3-shape": "3.2.0", + "elkjs": "0.11.1" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24.0", + "pnpm": "8" + }, "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", @@ -2981,18 +3029,35 @@ "license": "MIT" }, "node_modules/@remix-run/router": { - "version": "1.23.2", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz", - "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==", + "version": "1.23.4", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz", + "integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==", "license": "MIT", "engines": { "node": ">=14.0.0" } }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", + "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz", - "integrity": "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", + "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", "cpu": [ "arm64" ], @@ -3007,9 +3072,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.3.tgz", - "integrity": "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", + "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", "cpu": [ "arm64" ], @@ -3024,9 +3089,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.3.tgz", - "integrity": "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", + "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", "cpu": [ "x64" ], @@ -3041,9 +3106,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.3.tgz", - "integrity": "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", + "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", "cpu": [ "x64" ], @@ -3058,9 +3123,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.3.tgz", - "integrity": "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", + "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", "cpu": [ "arm" ], @@ -3075,9 +3140,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.3.tgz", - "integrity": "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", + "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", "cpu": [ "arm64" ], @@ -3092,9 +3157,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.3.tgz", - "integrity": "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", + "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", "cpu": [ "arm64" ], @@ -3109,9 +3174,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.3.tgz", - "integrity": "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", + "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", "cpu": [ "ppc64" ], @@ -3126,9 +3191,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.3.tgz", - "integrity": "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", + "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", "cpu": [ "s390x" ], @@ -3143,9 +3208,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.3.tgz", - "integrity": "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", + "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", "cpu": [ "x64" ], @@ -3160,9 +3225,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.3.tgz", - "integrity": "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", "cpu": [ "x64" ], @@ -3177,9 +3242,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.3.tgz", - "integrity": "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", + "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", "cpu": [ "arm64" ], @@ -3193,29 +3258,10 @@ "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.3.tgz", - "integrity": "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.10.0", - "@emnapi/runtime": "1.10.0", - "@napi-rs/wasm-runtime": "^1.1.4" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.3.tgz", - "integrity": "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", + "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", "cpu": [ "arm64" ], @@ -3230,9 +3276,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.3.tgz", - "integrity": "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", + "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", "cpu": [ "x64" ], @@ -3254,9 +3300,9 @@ "license": "MIT" }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.0.tgz", - "integrity": "sha512-tPgXB6cDTndIe1ah7u6amCI1T0SsnlOuKgg10Xh3uizJk4e5M1JGaUMk7J4ciuAUcFpbOiNhm2XIjP9ON0dUqA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.4.tgz", + "integrity": "sha512-7sdQKCYk/JCWa7rlXOgIa7AEAfZnUu/twNX4m4ECouPWsYhzxHfslKCFpOs43J8uux356TUU8NCuQus3XISCbQ==", "cpu": [ "arm" ], @@ -3268,9 +3314,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.0.tgz", - "integrity": "sha512-sa4LyseLLXr1onr97StkU1Nb7fWcg6niokTwEVNOO7awaKaoRObQ54+V/hrF/BP1noMEaaAW6Fg2d/CfLiq3Mg==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.4.tgz", + "integrity": "sha512-iV5jlPMChTQgD0UCTcT9rLHN4DNce34v5Mw0IN7csTSg4RDaKq9AximXPL35k+sGXcfrR4OeQMvFNe+OmV1rhw==", "cpu": [ "arm64" ], @@ -3282,9 +3328,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.0.tgz", - "integrity": "sha512-/NNIj9A7yLjKdmkx5dC2XQ9DmjIECpGpwHoGmA5E1AhU0fuICSqSWScPhN1yLCkEdkCwJIDu2xIeLPs60MNIVg==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.4.tgz", + "integrity": "sha512-a0Sswc+5v8BVkjHGOaJCTbFArZZUJCGFi2y39FWGdiplOToMNzr1tE4v3l67DW+vGyYD2sS5PfhDdUCyrr3mjA==", "cpu": [ "arm64" ], @@ -3296,9 +3342,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.0.tgz", - "integrity": "sha512-xoh8abqgPrPYPr7pTYipqnUi1V3em56JzE/HgDgitTqZBZ3yKCWI+7KUkceM6tNweyUKYru1UMi7FC060RyKwA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.4.tgz", + "integrity": "sha512-qHH6RSwVPuNkqbOv0hgZKonHBW/ZIaHpd3bgH5LRPJ/8oRE+6Dl36OfS7wUQyeSeqQsAh1NrpwmUemgH1fh1WQ==", "cpu": [ "x64" ], @@ -3310,9 +3356,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.0.tgz", - "integrity": "sha512-PCkMh7fNahWSbA0OTUQ2OpYHpjZZr0hPr8lId8twD7a7SeWrvT3xJVyza+dQwXSSq4yEQTMoXgNOfMCsn8584g==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.4.tgz", + "integrity": "sha512-hs9CVjHH9WPGfeHZ5yvHYEiEm7hhm7M/16ytRTxrir7q+KnGaQ6EO1JYcrGooVIHYN1Z3H7sLIwxe97NNBYg6A==", "cpu": [ "arm64" ], @@ -3324,9 +3370,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.0.tgz", - "integrity": "sha512-1j3stGx+qbhXql4OCDZhnK7b01s6rBKNybfsX+TNrEe9JNq4DLi1yGiR1xW+nL+FNVvI4D02PUnl6gJ/2y6WJA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.4.tgz", + "integrity": "sha512-4UYtjV0FBOToshUTYvwoTbfvig9Ec94EcE56WehhqaFZK43rK9sLNYO+vRMnJ9GTOxanFkKB/IvBKt96VmCYiA==", "cpu": [ "x64" ], @@ -3338,9 +3384,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.0.tgz", - "integrity": "sha512-eyrr5W08Ms9uM0mLcKfM/Uzx7hjhz2bcjv8P2uynfj0yU8GGPdz8iYrBPhiLOZqahoAMB8ZiolRZPbbU2MAi6Q==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.4.tgz", + "integrity": "sha512-Md2BnPCGXVtoyaqPCxxahW4f8r5h8e1Iago6LFQRf+b9m8YOnkfW2L9l1KK9UsQa2gXYoVAVTi6mQgkVNSrOuQ==", "cpu": [ "arm" ], @@ -3352,9 +3398,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.0.tgz", - "integrity": "sha512-Xds90ITXJCNyX9pDhqf85MKWUI4lqjiPAipJ8OLp8xqI2Ehk+TCVhF9rvOoN8xTbcafow3QOThkNnrM33uCFQA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.4.tgz", + "integrity": "sha512-oBAOMLpMKggD7Z9oTZCVUp4dDMa84Br/PV5mm6IL1kykBgk5Kp3gyu2buW8KFzvkktyFj+NdZdZCxpRqNgO71A==", "cpu": [ "arm" ], @@ -3366,9 +3412,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.0.tgz", - "integrity": "sha512-Xws2KA4CLvZmXjy46SQaXSejuKPhwVdaNinldoYfqruZBaJHqVo6hnRa8SDo9z7PBW5x84SH64+izmldCgbezw==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.4.tgz", + "integrity": "sha512-KYgCzHJjmFhXb7kPv6ih9c6HdY/4JXr6MmLtWFRmK0hAgXxLBx2tI24J1OYJyFl7DfxnzREWSLDj3FxKHfPHjQ==", "cpu": [ "arm64" ], @@ -3380,9 +3426,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.0.tgz", - "integrity": "sha512-hrKXKbX5FdaRJj7lTMusmvKbhMJSGWJ+w++4KmjiDhpTgNlhYobMvKfDoIWecy4O60K6yA4SnztGuNTQF+Lplw==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.4.tgz", + "integrity": "sha512-xpeOpK+6OQfqZL3HQ1leCKM/JFZz0BmpVGkeydWRBdjYYgDlry7a2RWZ0rxnoJ29wMUK/xa/e1CSnnjV7UnxBw==", "cpu": [ "arm64" ], @@ -3394,9 +3440,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.0.tgz", - "integrity": "sha512-6A+nccfSDGKsPm00d3xKcrsBcbqzCTAukjwWK6rbuAnB2bHaL3r9720HBVZ/no7+FhZLz/U3GwwZZEh6tOSI8Q==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.4.tgz", + "integrity": "sha512-Iju/GGedDha6/e8lseZIxO2i3xPg+aJFw+l07QijRsEkGiUzQbsdNGaouTZwa6N1nu4q9WVJUbc/ejwPN24i+Q==", "cpu": [ "loong64" ], @@ -3408,9 +3454,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.0.tgz", - "integrity": "sha512-4P1VyYUe6XAJtQH1Hh99THxr0GKMMwIXsRNOceLrJnaHTDgk1FTcTimDgneRJPvB3LqDQxUmroBclQ1S0cIJwQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.4.tgz", + "integrity": "sha512-v3fNKbpq8uHqlMayTSaRCX9GVa/OECoY5beetD1qa5MKeRmrlgWve98UpcxgQAqGKQpqhcflDAe1AvjIUMenWQ==", "cpu": [ "loong64" ], @@ -3422,9 +3468,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.0.tgz", - "integrity": "sha512-8Vv6pLuIZCMcgXre6c3nOPhE0gjz1+nZP6T+hwWjr7sVH8k0jRkH+XnfjjOTglyMBdSKBPPz54/y1gToSKwrSQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.4.tgz", + "integrity": "sha512-ngxCMEz/wPVGkB/Fx7yGW8LkkL1mtg/V/KOYZQytTUe/MCh/w3nsvS0CnjhdS6YEJb98StA2aUnPaQZte0uCZg==", "cpu": [ "ppc64" ], @@ -3436,9 +3482,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.0.tgz", - "integrity": "sha512-r1te1M0Sm2TBVD/RxBPC6RZVwNqUTwJTA7w+C/IW5v9Ssu6xmxWEi+iJQlpBhtUiT1raJ5b48pI8tBvEjEFnFA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.4.tgz", + "integrity": "sha512-ob/5q9wu+GPAIJvqOzcr0tUo7vIuczYoVmxgfCjbSCE2zwbi/rxkR35b/fnQKGrI5fCua7ULhnB7w7wHseLlNQ==", "cpu": [ "ppc64" ], @@ -3450,9 +3496,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.0.tgz", - "integrity": "sha512-say0uMU/RaPm3CDQLxUUTF2oNWL8ysvHkAjcCzV2znxBr23kFfaxocS9qJm+NdkRhF8wtdEEAJuYcLPhSPbjuQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.4.tgz", + "integrity": "sha512-FsFK/3sO22/ogdbJ1TtWFyZAfru07l+4ya1OHn0L7renzB7qoQp0gaaTya7zKezubV5OoG9mSek1Z4qcT5rdew==", "cpu": [ "riscv64" ], @@ -3464,9 +3510,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.0.tgz", - "integrity": "sha512-/MU7/HizQGsnBREtRpcSbSV1zfkoxSTR7wLsRmBPQ8FwUj5sykrP1MyJTvsxP5KBq9SyE6kH8UQQQwa0ASeoQQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.4.tgz", + "integrity": "sha512-id50wkt+Jt20/66TkMr04OXdUB64Sj4W3WVhMVf/KuTiy5NFQLGgmCwE0RBobDPr22zyKxEE1U6zMAeBTgnZaQ==", "cpu": [ "riscv64" ], @@ -3478,9 +3524,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.0.tgz", - "integrity": "sha512-Q9eh+gUGILIHEaJf66aF6a414jQbDnn29zeu0eX3dHMuysnhTvsUvZTCAyZ6tJhUjnvzBKE4FtuaYxutxRZpOg==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.4.tgz", + "integrity": "sha512-WinoPEOOZz+rKnluSytyemucpXtygq1LJaU+HBxclUXPz7IVBJIjcdDH9V4nN/yvYjyiVeb/fH32HSX2acLmrw==", "cpu": [ "s390x" ], @@ -3492,9 +3538,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.0.tgz", - "integrity": "sha512-OR5p5yG5OKSxHReWmwvM0P+VTPMwoBS45PXTMYaskKQqybkS3Kmugq1W+YbNWArF8/s7jQScgzXUhArzEQ7x0A==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.4.tgz", + "integrity": "sha512-Fs5AqGrSuvXIPSGpZQAUHyM+7eRpKkWvIxN8eTf/8hoTCiKybb2FeqBnB5R9OyVOYI3/vP+VgSBOHT1zkYkKSA==", "cpu": [ "x64" ], @@ -3506,9 +3552,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.0.tgz", - "integrity": "sha512-XeatKzo4lHDsVEbm1XDHZlhYZZSQYym6dg2X/Ko0kSFgio+KXLsxwJQprnR48GvdIKDOpqWqssC3iBCjoMcMpw==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.4.tgz", + "integrity": "sha512-EdzYVEpaQG2YSRW/qi/uHcersoPi119NmUK/hgBQJdAZvk7HjlSKHsBWQvofZ8ZoL98R9SUNJUAtBwRlAsZ7WA==", "cpu": [ "x64" ], @@ -3520,9 +3566,9 @@ ] }, "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.0.tgz", - "integrity": "sha512-Lu71y78F5qOfYmubYLHPcJm74GZLU6UJ4THkf/a1K7Tz2ycwC2VUbsqbJAXaR6Bx70SRdlVrt2+n5l7F0agTUw==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.4.tgz", + "integrity": "sha512-FZarHZsoTVzvMfCS0hDWcybs+VvkC5TPEYREZhuyD93GGMBBYKa413z2zUsXJEGU7hHJ7EEr4mUUMV1WfHIVmA==", "cpu": [ "x64" ], @@ -3534,9 +3580,9 @@ ] }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.0.tgz", - "integrity": "sha512-v5xwKDWcu7qhAEcsUubiav7r+48Uk/ENWdr82MBZZRIm7zThSxCIVDfb3ZeRRq9yqk+oIzMdDo6fCcA5DHfMyA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.4.tgz", + "integrity": "sha512-A+nCwcEGR1r2MET1kikO4O9nkq6bjpA4gGwZiyZ8CsL3FMqPvh4OREYyZHv/WJjl8eCgfUqh9dFUc01qBOUOgQ==", "cpu": [ "arm64" ], @@ -3548,9 +3594,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.0.tgz", - "integrity": "sha512-XnaaaSMGSI6Wk8F4KK3QP7GfuuhjGchElsVerCplUuxRIzdvZ7hRBpLR0omCmw+kI2RFJB80nenhOoGXlJ5TfQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.4.tgz", + "integrity": "sha512-9dS3eF2HL38ItWUF6wbStGGoLALgh3e+BbBfq5VEAm/NKhnEibz/B+D719uTET83+E1lZL2TKlv6idlzOorrgA==", "cpu": [ "arm64" ], @@ -3562,9 +3608,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.0.tgz", - "integrity": "sha512-3K1lP+3BXY4t4VihLw5MEg6IZD3ojSYzqzBG571W3kNQe4G4CcFpSUQVgurYgib5d+YaCjeFow8QivWp8vuSvA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.4.tgz", + "integrity": "sha512-n2waAp+bsaATQlfM0dSsFWG+Juj3GBGYI5MS4prChfjn3z+PvijnWZT9FmRtcK6Db0F4rfGzMJUP5VENvb7wig==", "cpu": [ "ia32" ], @@ -3576,9 +3622,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.0.tgz", - "integrity": "sha512-MDk610P/vJGc5L5ImE4k5s+GZT3en0KoK1MKPXCRgzmksAMk79j4h3k1IerxTNqwDLxsGxStEZVBqG0gIqZqoA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.4.tgz", + "integrity": "sha512-kXMhVM8CVi/jRZAN8+SPVTdd1kl71WCVAajeu5JaVwsmjmAO40MiEj4QBDJeoWkLICE3b7jnRQK/mBQyhh0BCw==", "cpu": [ "x64" ], @@ -3590,9 +3636,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.0.tgz", - "integrity": "sha512-Zv7v6q6aV+VslnpwzqKAmrk5JdVkLUzok2208ZXGipjb+msxBr/fJPZyeEXiFgH7k62Ak0SLIfxQRZQvTuf7rQ==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.4.tgz", + "integrity": "sha512-OWiFOGLjX+ZPsRJjo9yQpU3rq5wBNxyPjB9Sc6PmSPVQgUKVSHQu2zR5y1YkZ+HFzy4rHfYhwnT2PQSUgatnJA==", "cpu": [ "x64" ], @@ -3883,16 +3929,16 @@ } }, "node_modules/@tailwindcss/typography": { - "version": "0.5.19", - "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.19.tgz", - "integrity": "sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==", + "version": "0.5.20", + "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.20.tgz", + "integrity": "sha512-hwbzQuNUfcPvbegQFatVPl/MY/tcM9KLl963hQ5laJKPh81TEZ1+dNG9PirGvcaDBkp+BCshExAyKVPW91dozw==", "dev": true, "license": "MIT", "dependencies": { "postcss-selector-parser": "6.0.10" }, "peerDependencies": { - "tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1" + "tailwindcss": ">=3.0.0 || >=4.0.0 || insiders" } }, "node_modules/@tanstack/query-core": { @@ -3927,17 +3973,6 @@ "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", "license": "MIT" }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", - "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@types/bcryptjs": { "version": "2.4.6", "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", @@ -4002,12 +4037,33 @@ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", "license": "MIT" }, + "node_modules/@types/d3-delaunay": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz", + "integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==", + "license": "MIT" + }, "node_modules/@types/d3-ease": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", "license": "MIT" }, + "node_modules/@types/d3-format": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz", + "integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==", + "license": "MIT" + }, + "node_modules/@types/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==", + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, "node_modules/@types/d3-interpolate": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", @@ -4047,6 +4103,12 @@ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", "license": "MIT" }, + "node_modules/@types/d3-time-format": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz", + "integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==", + "license": "MIT" + }, "node_modules/@types/d3-timer": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", @@ -4061,9 +4123,9 @@ "license": "MIT" }, "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "dev": true, "license": "MIT" }, @@ -4090,6 +4152,12 @@ "@types/send": "*" } }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -4114,6 +4182,12 @@ "@types/node": "*" } }, + "node_modules/@types/lodash": { + "version": "4.17.26", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.26.tgz", + "integrity": "sha512-48NWfiY6oNcKOh47Z4h+sIvwcQR91h6KPhaYKgeMIrkT2jV82Gy90SErj60vW8jQbeMSOSbhIv3bZ7JoqPPVhA==", + "license": "MIT" + }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -4451,9 +4525,9 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -4461,13 +4535,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", "dev": true, "license": "ISC", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^2.0.2" }, "engines": { "node": ">=16 || 14 >=14.17" @@ -4476,19 +4550,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/@typescript-eslint/utils": { "version": "8.53.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.53.1.tgz", @@ -4531,6 +4592,201 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@visx/curve": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz", + "integrity": "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg==", + "license": "MIT", + "dependencies": { + "@visx/vendor": "4.0.0-alpha.0" + } + }, + "node_modules/@visx/event": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/event/-/event-4.0.1-alpha.0.tgz", + "integrity": "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g==", + "license": "MIT", + "dependencies": { + "@types/react": "*", + "@visx/point": "4.0.1-alpha.0" + } + }, + "node_modules/@visx/grid": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/grid/-/grid-4.0.1-alpha.0.tgz", + "integrity": "sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg==", + "license": "MIT", + "dependencies": { + "@types/react": "*", + "@visx/curve": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/point": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/shape": "4.0.1-alpha.0", + "classnames": "^2.3.1" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/group": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/group/-/group-4.0.1-alpha.0.tgz", + "integrity": "sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w==", + "license": "MIT", + "dependencies": { + "@types/react": "*", + "classnames": "^2.3.1" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/point": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/point/-/point-4.0.1-alpha.0.tgz", + "integrity": "sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg==", + "license": "MIT" + }, + "node_modules/@visx/responsive": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/responsive/-/responsive-4.0.1-alpha.0.tgz", + "integrity": "sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA==", + "license": "MIT", + "dependencies": { + "@types/lodash": "^4.17.13", + "@types/react": "*", + "lodash": "^4.17.21" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/scale": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/scale/-/scale-4.0.1-alpha.0.tgz", + "integrity": "sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A==", + "license": "MIT", + "dependencies": { + "@visx/vendor": "4.0.0-alpha.0" + } + }, + "node_modules/@visx/shape": { + "version": "4.0.1-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/shape/-/shape-4.0.1-alpha.0.tgz", + "integrity": "sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA==", + "license": "MIT", + "dependencies": { + "@types/lodash": "^4.17.13", + "@types/react": "*", + "@visx/curve": "4.0.1-alpha.0", + "@visx/group": "4.0.1-alpha.0", + "@visx/scale": "4.0.1-alpha.0", + "@visx/vendor": "4.0.0-alpha.0", + "classnames": "^2.3.1", + "lodash": "^4.17.21" + }, + "peerDependencies": { + "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" + } + }, + "node_modules/@visx/vendor": { + "version": "4.0.0-alpha.0", + "resolved": "https://registry.npmjs.org/@visx/vendor/-/vendor-4.0.0-alpha.0.tgz", + "integrity": "sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ==", + "license": "MIT and ISC", + "dependencies": { + "@types/d3-array": "3.0.3", + "@types/d3-color": "3.1.0", + "@types/d3-delaunay": "6.0.1", + "@types/d3-format": "3.0.1", + "@types/d3-geo": "3.1.0", + "@types/d3-interpolate": "3.0.1", + "@types/d3-path": "3.1.1", + "@types/d3-scale": "4.0.2", + "@types/d3-shape": "3.1.7", + "@types/d3-time": "3.0.0", + "@types/d3-time-format": "2.1.0", + "d3-array": "3.2.1", + "d3-color": "3.1.0", + "d3-delaunay": "6.0.2", + "d3-format": "3.1.0", + "d3-geo": "3.1.0", + "d3-interpolate": "3.0.1", + "d3-path": "3.1.0", + "d3-scale": "4.0.2", + "d3-shape": "3.2.0", + "d3-time": "3.1.0", + "d3-time-format": "4.1.0", + "internmap": "2.0.3" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-array": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz", + "integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/@types/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/@types/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-shape": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz", + "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-time": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz", + "integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/d3-array": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz", + "integrity": "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@visx/vendor/node_modules/d3-format": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz", + "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/@vitejs/plugin-react-swc": { "version": "3.11.0", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react-swc/-/plugin-react-swc-3.11.0.tgz", @@ -4584,17 +4840,55 @@ } } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz", + "integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.11", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.1.11", + "vitest": "4.1.11" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, "node_modules/@vitest/expect": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz", - "integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.9", - "@vitest/utils": "4.1.9", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -4603,9 +4897,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.9.tgz", - "integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", "dev": true, "license": "MIT", "dependencies": { @@ -4616,13 +4910,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.9.tgz", - "integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.9", + "@vitest/utils": "4.1.11", "pathe": "^2.0.3" }, "funding": { @@ -4630,14 +4924,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.9.tgz", - "integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.9", - "@vitest/utils": "4.1.9", + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -4646,9 +4940,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.9.tgz", - "integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", "dev": true, "license": "MIT", "funding": { @@ -4656,13 +4950,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.9.tgz", - "integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.9", + "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -4671,9 +4965,9 @@ } }, "node_modules/@xmldom/xmldom": { - "version": "0.8.11", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz", - "integrity": "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==", + "version": "0.8.15", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz", + "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==", "license": "MIT", "engines": { "node": ">=10.0.0" @@ -4750,9 +5044,9 @@ } }, "node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", "dev": true, "license": "MIT", "dependencies": { @@ -4862,6 +5156,25 @@ "node": ">=4" } }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz", + "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -4916,17 +5229,45 @@ } }, "node_modules/axios": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.14.0.tgz", - "integrity": "sha512-3Y8yrqLSwjuzpXuZ0oIYZ/XGgLwUIBU3uLvbcpb0pidD9ctpShJd43KSlEEkVQg6DS0G9NKyzOvBfUtDKEyHvQ==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", "dev": true, "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", - "form-data": "^4.0.5", + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, + "node_modules/axios/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/axios/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/axios/node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -4979,19 +5320,22 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.9.17", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.17.tgz", - "integrity": "sha512-agD0MgJFUP/4nvjqzIB29zRPUuCF7Ge6mEv9s8dHrtYD7QWXRcx75rOADE/d5ah1NI+0vkDl0yorDd5U852IQQ==", + "version": "2.11.28", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.28.tgz", + "integrity": "sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA==", "dev": true, "license": "Apache-2.0", "bin": { - "baseline-browser-mapping": "dist/cli.js" + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" } }, "node_modules/basic-ftp": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.1.0.tgz", - "integrity": "sha512-RkaJzeJKDbaDWTIPiJwubyljaEPwpVWkm9Rt5h9Nd6h7tEXTJ3VB4qxdZBioV7JO5yLUaOKwz7vDOzlncUsegw==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz", + "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==", "license": "MIT", "engines": { "node": ">=10.0.0" @@ -5006,6 +5350,12 @@ "bcrypt": "bin/bcrypt" } }, + "node_modules/better-result": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/better-result/-/better-result-2.10.0.tgz", + "integrity": "sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==", + "license": "MIT" + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -5018,27 +5368,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/bluebird": { - "version": "3.4.7", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", - "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", - "license": "MIT" - }, "node_modules/body-parser": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", - "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^1.0.5", + "content-type": "^2.0.0", "debug": "^4.4.3", - "http-errors": "^2.0.0", - "iconv-lite": "^0.7.0", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", - "qs": "^6.14.1", - "raw-body": "^3.0.1", - "type-is": "^2.0.1" + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" }, "engines": { "node": ">=18" @@ -5048,10 +5392,23 @@ "url": "https://opencollective.com/express" } }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -5072,9 +5429,9 @@ } }, "node_modules/browserslist": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", - "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "version": "4.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", "dev": true, "funding": [ { @@ -5092,11 +5449,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.9.0", - "caniuse-lite": "^1.0.30001759", - "electron-to-chromium": "^1.5.263", - "node-releases": "^2.0.27", - "update-browserslist-db": "^1.2.0" + "baseline-browser-mapping": "^2.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" }, "bin": { "browserslist": "cli.js" @@ -5154,26 +5511,26 @@ } }, "node_modules/c12": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz", - "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==", - "license": "MIT", - "dependencies": { - "chokidar": "^4.0.3", - "confbox": "^0.2.2", - "defu": "^6.1.4", - "dotenv": "^16.6.1", - "exsolve": "^1.0.7", - "giget": "^2.0.0", - "jiti": "^2.4.2", + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", + "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "confbox": "^0.2.4", + "defu": "^6.1.6", + "dotenv": "^17.3.1", + "exsolve": "^1.0.8", + "giget": "^3.2.0", + "jiti": "^2.6.1", "ohash": "^2.0.11", "pathe": "^2.0.3", - "perfect-debounce": "^1.0.0", - "pkg-types": "^2.2.0", - "rc9": "^2.1.2" + "perfect-debounce": "^2.1.0", + "pkg-types": "^2.3.0", + "rc9": "^3.0.1" }, "peerDependencies": { - "magicast": "^0.3.5" + "magicast": "*" }, "peerDependenciesMeta": { "magicast": { @@ -5181,18 +5538,6 @@ } } }, - "node_modules/c12/node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", @@ -5241,9 +5586,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001765", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001765.tgz", - "integrity": "sha512-LWcNtSyZrakjECqmpP4qdg0MMGdN368D7X8XvvAqOcqMv0RxnlqVKZl2V6/mBR68oYMxOZPLw/gO7DuisMHUvQ==", + "version": "1.0.30001815", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001815.tgz", + "integrity": "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==", "dev": true, "funding": [ { @@ -5262,9 +5607,9 @@ "license": "CC-BY-4.0" }, "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, "license": "MIT", "engines": { @@ -5287,30 +5632,16 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/chevrotain": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-10.5.0.tgz", - "integrity": "sha512-Pkv5rBY3+CsHOYfV5g/Vs5JY9WTHHDEKOlohI2XeygaZhUeqhAlldZ8Hz9cRmxu709bvS08YzxHdTPHhffc13A==", - "license": "Apache-2.0", - "dependencies": { - "@chevrotain/cst-dts-gen": "10.5.0", - "@chevrotain/gast": "10.5.0", - "@chevrotain/types": "10.5.0", - "@chevrotain/utils": "10.5.0", - "lodash": "4.17.21", - "regexp-to-ast": "0.5.0" - } - }, "node_modules/chokidar": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", - "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", "license": "MIT", "dependencies": { - "readdirp": "^4.0.1" + "readdirp": "^5.0.0" }, "engines": { - "node": ">= 14.16.0" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" @@ -5329,15 +5660,6 @@ "devtools-protocol": "*" } }, - "node_modules/citty": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", - "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", - "license": "MIT", - "dependencies": { - "consola": "^3.2.3" - } - }, "node_modules/class-variance-authority": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", @@ -5350,6 +5672,12 @@ "url": "https://polar.sh/cva" } }, + "node_modules/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", + "license": "MIT" + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -5447,14 +5775,14 @@ "license": "MIT" }, "node_modules/concurrently": { - "version": "9.2.1", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz", - "integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==", + "version": "9.2.5", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.5.tgz", + "integrity": "sha512-YMZlvWrTPQEhjKp60XSmMGt60+pffbv6DyRnOMvVO98+J7aF8w8Ui9FhdcOwvSixc/kyR6SoVvmejcn/2lZBqg==", "license": "MIT", "dependencies": { "chalk": "4.1.2", "rxjs": "7.8.2", - "shell-quote": "1.8.3", + "shell-quote": "1.12.0", "supports-color": "8.1.1", "tree-kill": "1.2.2", "yargs": "17.7.2" @@ -5486,20 +5814,11 @@ } }, "node_modules/confbox": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz", - "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==", + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", "license": "MIT" }, - "node_modules/consola": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", - "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", - "license": "MIT", - "engines": { - "node": "^14.18.0 || >=16.10.0" - } - }, "node_modules/content-disposition": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", @@ -5665,6 +5984,18 @@ "node": ">=12" } }, + "node_modules/d3-delaunay": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz", + "integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==", + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/d3-ease": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", @@ -5683,6 +6014,18 @@ "node": ">=12" } }, + "node_modules/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/d3-interpolate": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", @@ -5833,9 +6176,9 @@ } }, "node_modules/defu": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz", - "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==", + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", "license": "MIT" }, "node_modules/degenerator": { @@ -5852,6 +6195,15 @@ "node": ">= 14" } }, + "node_modules/delaunator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", + "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -5963,24 +6315,6 @@ "undici-types": "~7.16.0" } }, - "node_modules/docx/node_modules/nanoid": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.6.tgz", - "integrity": "sha512-c7+7RQ+dMB5dPwwCp4ee1/iV/q2P6aK1mTZcfr1BTuVlyW9hJYiMPybJCcnBlQtuSmTIWNeazm/zqNoZSSElBg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.js" - }, - "engines": { - "node": "^18 || >=20" - } - }, "node_modules/docx/node_modules/undici-types": { "version": "7.16.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", @@ -5998,9 +6332,9 @@ } }, "node_modules/dotenv": { - "version": "17.2.3", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", - "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", "license": "BSD-2-Clause", "engines": { "node": ">=12" @@ -6048,9 +6382,9 @@ "license": "MIT" }, "node_modules/effect": { - "version": "3.18.4", - "resolved": "https://registry.npmjs.org/effect/-/effect-3.18.4.tgz", - "integrity": "sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==", + "version": "3.20.0", + "resolved": "https://registry.npmjs.org/effect/-/effect-3.20.0.tgz", + "integrity": "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==", "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.0.0", @@ -6058,12 +6392,18 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.267", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", - "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "version": "1.5.452", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.452.tgz", + "integrity": "sha512-cVvk1YBSj6571VmV6hdJTqj94Y79xSu8cj6Y9t6ae4Y4431z8/7EJFvu3rVp90xhfuv9BpPKUmaLfTo4+FOGBg==", "dev": true, "license": "ISC" }, + "node_modules/elkjs": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.11.1.tgz", + "integrity": "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==", + "license": "EPL-2.0" + }, "node_modules/embla-carousel": { "version": "8.6.0", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", @@ -6606,9 +6946,9 @@ } }, "node_modules/exsolve": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", - "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.3.tgz", + "integrity": "sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==", "license": "MIT" }, "node_modules/extract-zip": { @@ -6653,11 +6993,16 @@ "node": ">=8.0.0" } }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "license": "MIT" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-equals": { @@ -6675,6 +7020,34 @@ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", "license": "MIT" }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -6689,6 +7062,15 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, "node_modules/fast-safe-stringify": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", @@ -6702,6 +7084,22 @@ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense" }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fastq": { "version": "1.20.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", @@ -6766,6 +7164,20 @@ "url": "https://opencollective.com/express" } }, + "node_modules/find-my-way": { + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.7.0.tgz", + "integrity": "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -6798,16 +7210,16 @@ } }, "node_modules/flatted": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", - "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", "dev": true, "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", + "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", "dev": true, "funding": [ { @@ -6842,17 +7254,17 @@ } }, "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -7071,18 +7483,10 @@ } }, "node_modules/giget": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", - "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", + "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", "license": "MIT", - "dependencies": { - "citty": "^0.1.6", - "consola": "^3.4.0", - "defu": "^6.1.4", - "node-fetch-native": "^1.6.6", - "nypm": "^0.6.0", - "pathe": "^2.0.3" - }, "bin": { "giget": "dist/cli.mjs" } @@ -7131,15 +7535,16 @@ "license": "ISC" }, "node_modules/grammex": { - "version": "3.1.12", - "resolved": "https://registry.npmjs.org/grammex/-/grammex-3.1.12.tgz", - "integrity": "sha512-6ufJOsSA7LcQehIJNCO7HIBykfM7DXQual0Ny780/DEcJIpBlHRvcqEBWGPYd7hrXL2GJ3oJI1MIhaXjWmLQOQ==", + "version": "3.1.13", + "resolved": "https://registry.npmjs.org/grammex/-/grammex-3.1.13.tgz", + "integrity": "sha512-LnPnhOBLEJEVKS8WFDVaA397L9Kq55Q9oSITJiVLHVdhAclfUkWzQv74KhvZHKL2Q09Pb1XdsrOsZ4LfTFFTEg==", "license": "MIT" }, "node_modules/graphmatch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/graphmatch/-/graphmatch-1.1.0.tgz", - "integrity": "sha512-0E62MaTW5rPZVRLyIJZG/YejmdA/Xr1QydHEw3Vt+qOKkMIOE8WDLc9ZX2bmAjtJFZcId4lEdrdmASsEy7D1QA==" + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/graphmatch/-/graphmatch-1.1.1.tgz", + "integrity": "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg==", + "license": "MIT" }, "node_modules/has-flag": { "version": "4.0.0", @@ -7189,9 +7594,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -7212,14 +7617,12 @@ "url": "https://github.com/sponsors/EvanHahn" } }, - "node_modules/hono": { - "version": "4.11.4", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz", - "integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==", - "license": "MIT", - "engines": { - "node": ">=16.9.0" - } + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" }, "node_modules/http-errors": { "version": "2.0.1", @@ -7254,12 +7657,6 @@ "node": ">= 14" } }, - "node_modules/http-status-codes": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/http-status-codes/-/http-status-codes-2.3.0.tgz", - "integrity": "sha512-RJ8XvFvpPM/Dmc5SV+dC4y5PCeOhT3x1Hq0NU3rjGeg5a/CqlhZ7uudknPwZFz4aeAXDcbAyaeP7GAo9lvngtA==", - "license": "MIT" - }, "node_modules/https-proxy-agent": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", @@ -7386,9 +7783,9 @@ } }, "node_modules/ip-address": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", - "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", + "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", "license": "MIT", "engines": { "node": ">= 12" @@ -7493,6 +7890,45 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "license": "ISC" }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/jiti": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", @@ -7503,9 +7939,9 @@ } }, "node_modules/joi": { - "version": "18.1.2", - "resolved": "https://registry.npmjs.org/joi/-/joi-18.1.2.tgz", - "integrity": "sha512-rF5MAmps5esSlhCA+N1b6IYHDw9j/btzGaqfgie522jS02Ju/HXBxamlXVlKEHAxoMKQL77HWI8jlqWsFuekZA==", + "version": "18.2.9", + "resolved": "https://registry.npmjs.org/joi/-/joi-18.2.9.tgz", + "integrity": "sha512-2mD929bUVKUhOLQQEVhlf6EZ0Mlo0DeRb5MO7cViR9AXLtBauuccEtB1py9Ocxpo/P7ucnh442iY/iOwrh3IQw==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -7528,9 +7964,19 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -7588,18 +8034,6 @@ "npm": ">=6" } }, - "node_modules/jsonwebtoken/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/jszip": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", @@ -7667,9 +8101,9 @@ } }, "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", "dependencies": { @@ -7683,23 +8117,23 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" } }, "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", "cpu": [ "arm64" ], @@ -7718,9 +8152,9 @@ } }, "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", "cpu": [ "arm64" ], @@ -7739,9 +8173,9 @@ } }, "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", "cpu": [ "x64" ], @@ -7760,9 +8194,9 @@ } }, "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", "cpu": [ "x64" ], @@ -7781,9 +8215,9 @@ } }, "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", "cpu": [ "arm" ], @@ -7802,9 +8236,9 @@ } }, "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", "cpu": [ "arm64" ], @@ -7823,9 +8257,9 @@ } }, "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", "cpu": [ "arm64" ], @@ -7844,9 +8278,9 @@ } }, "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", "cpu": [ "x64" ], @@ -7865,9 +8299,9 @@ } }, "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", "cpu": [ "x64" ], @@ -7886,9 +8320,9 @@ } }, "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", "cpu": [ "arm64" ], @@ -7907,9 +8341,9 @@ } }, "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", "cpu": [ "x64" ], @@ -7927,15 +8361,6 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/lilconfig": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", - "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -7959,9 +8384,9 @@ } }, "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "license": "MIT" }, "node_modules/lodash.includes": { @@ -8085,20 +8510,46 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/mammoth": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/mammoth/-/mammoth-1.11.0.tgz", - "integrity": "sha512-BcEqqY/BOwIcI1iR5tqyVlqc3KIaMRa4egSoK83YAVrBf6+yqdAAbtUcFDCWX8Zef8/fgNZ6rl4VUv+vVX8ddQ==", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/mammoth/-/mammoth-1.13.0.tgz", + "integrity": "sha512-2cawcYFcP7ISfXbBcL9lmVgTNWo88v/52ND1gnywHtVT/pX0//puPnf0iMPV9ZgmuvNOE+zkIhDgZ9M2c2dDDg==", "license": "BSD-2-Clause", "dependencies": { "@xmldom/xmldom": "^0.8.6", "argparse": "~1.0.3", "base64-js": "^1.5.1", - "bluebird": "~3.4.0", "dingbat-to-unicode": "^1.0.1", "jszip": "^3.7.1", "lop": "^0.4.2", - "path-is-absolute": "^1.0.0", "underscore": "^1.13.1", "xmlbuilder": "^10.0.0" }, @@ -8223,9 +8674,9 @@ "license": "ISC" }, "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -8322,9 +8773,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.15", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz", - "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==", + "version": "5.1.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz", + "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==", "funding": [ { "type": "github", @@ -8333,10 +8784,10 @@ ], "license": "MIT", "bin": { - "nanoid": "bin/nanoid.cjs" + "nanoid": "bin/nanoid.js" }, "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + "node": "^18 || >=20" } }, "node_modules/natural-compare": { @@ -8394,18 +8845,15 @@ } } }, - "node_modules/node-fetch-native": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", - "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", - "license": "MIT" - }, "node_modules/node-releases": { - "version": "2.0.27", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", - "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "version": "2.0.58", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.58.tgz", + "integrity": "sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/normalize-path": { "version": "3.0.0", @@ -8416,29 +8864,6 @@ "node": ">=0.10.0" } }, - "node_modules/nypm": { - "version": "0.6.4", - "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.4.tgz", - "integrity": "sha512-1TvCKjZyyklN+JJj2TS3P4uSQEInrM/HkkuSXsEzm1ApPgBffOn8gFguNnZf07r/1X6vlryfIqMUkJKQMzlZiw==", - "license": "MIT", - "dependencies": { - "citty": "^0.2.0", - "pathe": "^2.0.3", - "tinyexec": "^1.0.2" - }, - "bin": { - "nypm": "dist/cli.mjs" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/nypm/node_modules/citty": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.0.tgz", - "integrity": "sha512-8csy5IBFI2ex2hTVpaHN2j+LNE199AgiI7y4dMintrr8i0lQiFn+0AWMZrWdHKIgMOer65f8IThysYhoReqjWA==", - "license": "MIT" - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -8484,9 +8909,9 @@ } }, "node_modules/ohash": { - "version": "2.0.11", - "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", - "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", "license": "MIT" }, "node_modules/on-finished": { @@ -8674,15 +9099,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -8699,9 +9115,9 @@ "license": "MIT" }, "node_modules/path-to-regexp": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", - "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", "license": "MIT", "funding": { "type": "opencollective", @@ -8721,9 +9137,9 @@ "license": "MIT" }, "node_modules/perfect-debounce": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", - "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", "license": "MIT" }, "node_modules/pg": { @@ -8831,9 +9247,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "license": "MIT", "engines": { "node": ">=8.6" @@ -8861,16 +9277,22 @@ } }, "node_modules/pkg-types": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", - "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", + "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", "license": "MIT", "dependencies": { - "confbox": "^0.2.2", - "exsolve": "^1.0.7", + "confbox": "^0.3.1", + "exsolve": "^1.1.1", "pathe": "^2.0.3" } }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", + "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", + "license": "MIT" + }, "node_modules/postal-mime": { "version": "2.7.4", "resolved": "https://registry.npmjs.org/postal-mime/-/postal-mime-2.7.4.tgz", @@ -8878,9 +9300,9 @@ "license": "MIT-0" }, "node_modules/postcss": { - "version": "8.5.15", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", - "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", "funding": [ { "type": "opencollective", @@ -8897,9 +9319,9 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.12", + "nanoid": "^3.3.19", "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=14" @@ -9027,9 +9449,9 @@ } }, "node_modules/postcss-nested/node_modules/postcss-selector-parser": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", - "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", + "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -9059,6 +9481,24 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, + "node_modules/postcss/node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/postgres": { "version": "3.4.7", "resolved": "https://registry.npmjs.org/postgres/-/postgres-3.4.7.tgz", @@ -9122,16 +9562,16 @@ } }, "node_modules/prisma": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/prisma/-/prisma-7.3.0.tgz", - "integrity": "sha512-ApYSOLHfMN8WftJA+vL6XwAPOh/aZ0BgUyyKPwUFgjARmG6EBI9LzDPf6SWULQMSAxydV9qn5gLj037nPNlg2w==", + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-7.10.0.tgz", + "integrity": "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw==", "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "@prisma/config": "7.3.0", - "@prisma/dev": "0.20.0", - "@prisma/engines": "7.3.0", - "@prisma/studio-core": "0.13.1", + "@prisma/config": "7.10.0", + "@prisma/dev": "0.24.17", + "@prisma/engines": "7.10.0", + "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, @@ -9198,9 +9638,9 @@ "license": "ISC" }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -9208,6 +9648,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-agent": { @@ -9352,12 +9796,13 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.14.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", - "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.1.0" + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" @@ -9411,13 +9856,13 @@ } }, "node_modules/rc9": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", - "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", + "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", "license": "MIT", "dependencies": { - "defu": "^6.1.4", - "destr": "^2.0.3" + "defu": "^6.1.7", + "destr": "^2.0.5" } }, "node_modules/react": { @@ -9539,12 +9984,12 @@ } }, "node_modules/react-router": { - "version": "6.30.3", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz", - "integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==", + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz", + "integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.2" + "@remix-run/router": "1.23.4" }, "engines": { "node": ">=14.0.0" @@ -9554,13 +9999,13 @@ } }, "node_modules/react-router-dom": { - "version": "6.30.3", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz", - "integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==", + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz", + "integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.2", - "react-router": "6.30.3" + "@remix-run/router": "1.23.4", + "react-router": "6.30.6" }, "engines": { "node": ">=14.0.0" @@ -9660,12 +10105,12 @@ "license": "MIT" }, "node_modules/readdirp": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", - "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", "license": "MIT", "engines": { - "node": ">= 14.18.0" + "node": ">= 20.19.0" }, "funding": { "type": "individual", @@ -9710,12 +10155,6 @@ "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", "license": "MIT" }, - "node_modules/regexp-to-ast": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/regexp-to-ast/-/regexp-to-ast-0.5.0.tgz", - "integrity": "sha512-tlbJqcMHnPKI9zSrystikWKwHkBqu2a/Sgw01h3zFjvYrMxEDYHzzoMZnUrbIfpTFEsoRnnviOXNCzFiSc54Qw==", - "license": "MIT" - }, "node_modules/remeda": { "version": "2.33.4", "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", @@ -9734,6 +10173,15 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resend": { "version": "6.14.0", "resolved": "https://registry.npmjs.org/resend/-/resend-6.14.0.tgz", @@ -9794,6 +10242,15 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/ret": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", + "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", @@ -9813,14 +10270,20 @@ "node": ">=0.10.0" } }, + "node_modules/robust-predicates": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", + "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", + "license": "Unlicense" + }, "node_modules/rolldown": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", - "integrity": "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==", + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", + "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.133.0", + "@oxc-project/types": "=0.153.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -9830,21 +10293,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.3", - "@rolldown/binding-darwin-arm64": "1.0.3", - "@rolldown/binding-darwin-x64": "1.0.3", - "@rolldown/binding-freebsd-x64": "1.0.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", - "@rolldown/binding-linux-arm64-gnu": "1.0.3", - "@rolldown/binding-linux-arm64-musl": "1.0.3", - "@rolldown/binding-linux-ppc64-gnu": "1.0.3", - "@rolldown/binding-linux-s390x-gnu": "1.0.3", - "@rolldown/binding-linux-x64-gnu": "1.0.3", - "@rolldown/binding-linux-x64-musl": "1.0.3", - "@rolldown/binding-openharmony-arm64": "1.0.3", - "@rolldown/binding-wasm32-wasi": "1.0.3", - "@rolldown/binding-win32-arm64-msvc": "1.0.3", - "@rolldown/binding-win32-x64-msvc": "1.0.3" + "@rolldown/binding-android-arm-eabi": "1.2.13", + "@rolldown/binding-android-arm64": "1.2.13", + "@rolldown/binding-darwin-arm64": "1.2.13", + "@rolldown/binding-darwin-x64": "1.2.13", + "@rolldown/binding-freebsd-x64": "1.2.13", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", + "@rolldown/binding-linux-arm64-gnu": "1.2.13", + "@rolldown/binding-linux-arm64-musl": "1.2.13", + "@rolldown/binding-linux-ppc64-gnu": "1.2.13", + "@rolldown/binding-linux-s390x-gnu": "1.2.13", + "@rolldown/binding-linux-x64-gnu": "1.2.13", + "@rolldown/binding-linux-x64-musl": "1.2.13", + "@rolldown/binding-openharmony-arm64": "1.2.13", + "@rolldown/binding-win32-arm64-msvc": "1.2.13", + "@rolldown/binding-win32-x64-msvc": "1.2.13" } }, "node_modules/rolldown/node_modules/@rolldown/pluginutils": { @@ -9855,13 +10318,13 @@ "license": "MIT" }, "node_modules/rollup": { - "version": "4.57.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.0.tgz", - "integrity": "sha512-e5lPJi/aui4TO1LpAXIRLySmwXSE8k3b9zoGfd42p67wzxog4WHjiZF3M2uheQih4DGyc25QEV4yRBbpueNiUA==", + "version": "4.64.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.4.tgz", + "integrity": "sha512-1DTowQbct6FOZTjZoYrZ8BwsjIwsB89HxwOn2pWPEyEKWWvKI8OrpTgmicB3fUbQzhlooCQRIn6JLUPhE0CZUA==", "dev": true, "license": "MIT", "dependencies": { - "@types/estree": "1.0.8" + "@types/estree": "1.0.9" }, "bin": { "rollup": "dist/bin/rollup" @@ -9871,31 +10334,32 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.57.0", - "@rollup/rollup-android-arm64": "4.57.0", - "@rollup/rollup-darwin-arm64": "4.57.0", - "@rollup/rollup-darwin-x64": "4.57.0", - "@rollup/rollup-freebsd-arm64": "4.57.0", - "@rollup/rollup-freebsd-x64": "4.57.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.57.0", - "@rollup/rollup-linux-arm-musleabihf": "4.57.0", - "@rollup/rollup-linux-arm64-gnu": "4.57.0", - "@rollup/rollup-linux-arm64-musl": "4.57.0", - "@rollup/rollup-linux-loong64-gnu": "4.57.0", - "@rollup/rollup-linux-loong64-musl": "4.57.0", - "@rollup/rollup-linux-ppc64-gnu": "4.57.0", - "@rollup/rollup-linux-ppc64-musl": "4.57.0", - "@rollup/rollup-linux-riscv64-gnu": "4.57.0", - "@rollup/rollup-linux-riscv64-musl": "4.57.0", - "@rollup/rollup-linux-s390x-gnu": "4.57.0", - "@rollup/rollup-linux-x64-gnu": "4.57.0", - "@rollup/rollup-linux-x64-musl": "4.57.0", - "@rollup/rollup-openbsd-x64": "4.57.0", - "@rollup/rollup-openharmony-arm64": "4.57.0", - "@rollup/rollup-win32-arm64-msvc": "4.57.0", - "@rollup/rollup-win32-ia32-msvc": "4.57.0", - "@rollup/rollup-win32-x64-gnu": "4.57.0", - "@rollup/rollup-win32-x64-msvc": "4.57.0", + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.4", + "@rollup/rollup-android-arm64": "4.64.4", + "@rollup/rollup-darwin-arm64": "4.64.4", + "@rollup/rollup-darwin-x64": "4.64.4", + "@rollup/rollup-freebsd-arm64": "4.64.4", + "@rollup/rollup-freebsd-x64": "4.64.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.4", + "@rollup/rollup-linux-arm-musleabihf": "4.64.4", + "@rollup/rollup-linux-arm64-gnu": "4.64.4", + "@rollup/rollup-linux-arm64-musl": "4.64.4", + "@rollup/rollup-linux-loong64-gnu": "4.64.4", + "@rollup/rollup-linux-loong64-musl": "4.64.4", + "@rollup/rollup-linux-ppc64-gnu": "4.64.4", + "@rollup/rollup-linux-ppc64-musl": "4.64.4", + "@rollup/rollup-linux-riscv64-gnu": "4.64.4", + "@rollup/rollup-linux-riscv64-musl": "4.64.4", + "@rollup/rollup-linux-s390x-gnu": "4.64.4", + "@rollup/rollup-linux-x64-gnu": "4.64.4", + "@rollup/rollup-linux-x64-musl": "4.64.4", + "@rollup/rollup-openbsd-x64": "4.64.4", + "@rollup/rollup-openharmony-arm64": "4.64.4", + "@rollup/rollup-win32-arm64-msvc": "4.64.4", + "@rollup/rollup-win32-ia32-msvc": "4.64.4", + "@rollup/rollup-win32-x64-gnu": "4.64.4", + "@rollup/rollup-win32-x64-msvc": "4.64.4", "fsevents": "~2.3.2" } }, @@ -9967,6 +10431,28 @@ ], "license": "MIT" }, + "node_modules/safe-regex2": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz", + "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -9991,6 +10477,18 @@ "loose-envify": "^1.1.0" } }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/send": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", @@ -10100,9 +10598,9 @@ } }, "node_modules/shell-quote": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", - "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", "license": "MIT", "engines": { "node": ">= 0.4" @@ -10112,14 +10610,14 @@ } }, "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -10131,13 +10629,13 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -10261,9 +10759,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -10564,34 +11062,6 @@ "node": ">= 6" } }, - "node_modules/tailwindcss/node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/tailwindcss/node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/tailwindcss/node_modules/jiti": { "version": "1.21.7", "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", @@ -10614,9 +11084,9 @@ } }, "node_modules/tailwindcss/node_modules/postcss-selector-parser": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", - "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", + "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -10741,6 +11211,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -10792,9 +11263,9 @@ } }, "node_modules/tinyrainbow": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", - "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", "dev": true, "license": "MIT", "engines": { @@ -10896,17 +11367,34 @@ } }, "node_modules/type-is": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", - "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", "license": "MIT", "dependencies": { - "content-type": "^1.0.5", + "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" }, "engines": { - "node": ">= 0.6" + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/type-is/node_modules/mime-db": { @@ -10983,9 +11471,9 @@ } }, "node_modules/underscore": { - "version": "1.13.7", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", - "integrity": "sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==", + "version": "1.13.8", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz", + "integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==", "license": "MIT" }, "node_modules/undici-types": { @@ -11004,9 +11492,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", "dev": true, "funding": [ { @@ -11109,9 +11597,9 @@ "license": "MIT" }, "node_modules/uuid": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", - "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.2.tgz", + "integrity": "sha512-vzi9uRZ926x4XV73S/4qQaTwPXM2JBj6/6lI/byHH1jOpCzb0zDbfytgA9LcN/hzb2l7WQSQnxITOVx5un/wGw==", "funding": [ "https://github.com/sponsors/broofa", "https://github.com/sponsors/ctavan" @@ -11122,9 +11610,9 @@ } }, "node_modules/valibot": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.2.0.tgz", - "integrity": "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.4.2.tgz", + "integrity": "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==", "license": "MIT", "peerDependencies": { "typescript": ">=5" @@ -11670,19 +12158,19 @@ } }, "node_modules/vitest": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.9.tgz", - "integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.9", - "@vitest/mocker": "4.1.9", - "@vitest/pretty-format": "4.1.9", - "@vitest/runner": "4.1.9", - "@vitest/snapshot": "4.1.9", - "@vitest/spy": "4.1.9", - "@vitest/utils": "4.1.9", + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -11710,12 +12198,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.9", - "@vitest/browser-preview": "4.1.9", - "@vitest/browser-webdriverio": "4.1.9", - "@vitest/coverage-istanbul": "4.1.9", - "@vitest/coverage-v8": "4.1.9", - "@vitest/ui": "4.1.9", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" @@ -11760,13 +12248,13 @@ } }, "node_modules/vitest/node_modules/@vitest/mocker": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.9.tgz", - "integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.9", + "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -11787,9 +12275,9 @@ } }, "node_modules/vitest/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -11807,16 +12295,16 @@ "license": "MIT" }, "node_modules/vitest/node_modules/vite": { - "version": "8.0.16", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", - "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", + "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", "dev": true, "license": "MIT", "dependencies": { - "lightningcss": "^1.32.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.15", - "rolldown": "1.0.3", + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.29", + "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "bin": { @@ -11833,7 +12321,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.18", + "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -11904,13 +12392,6 @@ "node": ">=20.0.0" } }, - "node_modules/wait-on/node_modules/lodash": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", - "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", - "dev": true, - "license": "MIT" - }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -11993,9 +12474,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.19.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", - "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/package.json b/package.json index ceac0f4..eea3113 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,9 @@ "test:coverage": "vitest run --coverage", "typecheck": "tsc --noEmit", "seed": "tsx prisma/seed.ts", - "backfill:embeddings": "tsx scripts/backfill-embeddings.ts" + "backfill:embeddings": "tsx scripts/backfill-embeddings.ts", + "check:rls": "tsx scripts/check-rls.ts", + "set-passwords": "tsx scripts/migrate-auth.ts" }, "dependencies": { "@hookform/resolvers": "^3.10.0", @@ -104,6 +106,7 @@ "@types/supertest": "^7.2.0", "@types/uuid": "^10.0.0", "@vitejs/plugin-react-swc": "^3.11.0", + "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.4.21", "eslint": "^9.32.0", "eslint-plugin-react-hooks": "^5.2.0", diff --git a/vitest.config.ts b/vitest.config.ts index 21f1a7a..cd7d9cb 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,12 +1,12 @@ import { defineConfig } from 'vitest/config'; -import path from 'path'; +import { fileURLToPath } from 'node:url'; // Vitest config kept separate from vite.config.ts so the app build and the // test runner stay decoupled. API/business-logic tests run in a Node env. export default defineConfig({ resolve: { alias: { - '@': path.resolve(__dirname, './src'), + '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, test: { From 17dc91f28bba903ab8e8f31ccce6de141a54b89f Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:12 +0530 Subject: [PATCH 02/11] feat(auth): add AUTH_MODE=login multi-user mode 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. --- prisma/manual/multi_user.sql | 28 +++ scripts/migrate-auth.ts | 257 ++++++++++++------------- src/api/auth.ts | 50 +++-- src/api/lib/authConfig.ts | 67 +++++++ src/api/middleware/auth.ts | 109 ++++++++--- src/api/users.ts | 94 +++++++-- tests/loginMode.test.ts | 363 +++++++++++++++++++++++++++++++++++ 7 files changed, 772 insertions(+), 196 deletions(-) create mode 100644 prisma/manual/multi_user.sql create mode 100644 src/api/lib/authConfig.ts create mode 100644 tests/loginMode.test.ts diff --git a/prisma/manual/multi_user.sql b/prisma/manual/multi_user.sql new file mode 100644 index 0000000..9601cc2 --- /dev/null +++ b/prisma/manual/multi_user.sql @@ -0,0 +1,28 @@ +-- Multi-user support (AUTH_MODE=login). Run ONCE against your Supabase Postgres +-- (Supabase Studio โ†’ SQL editor, or: +-- npx prisma db execute --file prisma/manual/multi_user.sql +-- ). Idempotent / safe to re-run. Not needed for the default single-user demo mode. + +-- 1. Which company a user belongs to. The API already reads this column when it +-- exists (users without it simply have no company), and POST/PATCH /api/users +-- writes it. Proposal.company_id is added by semantic_search.sql. +alter table "User" add column if not exists company_id text; +alter table "Proposal" add column if not exists company_id text; + +-- 2. Indexes for the lookups the API makes on every list/search request. +create index if not exists user_company_idx on "User" (company_id); +create index if not exists proposal_company_idx on "Proposal" (company_id); +create index if not exists proposal_user_idx on "Proposal" ("userId"); +create index if not exists integration_user_idx on "Integration" ("userId"); + +-- 3. Emails are matched case-insensitively at sign-in and registration, so make the +-- database agree: no two accounts that differ only by letter case. Skipped (with +-- a notice) if such duplicates already exist โ€” merge them first, then re-run. +do $$ +begin + if exists (select 1 from "User" group by lower(email) having count(*) > 1) then + raise notice 'Skipping unique lower(email) index: users that differ only by case exist. Merge them and re-run.'; + else + create unique index if not exists user_email_lower_idx on "User" (lower(email)); + end if; +end $$; diff --git a/scripts/migrate-auth.ts b/scripts/migrate-auth.ts index 135789d..6468ac4 100644 --- a/scripts/migrate-auth.ts +++ b/scripts/migrate-auth.ts @@ -1,132 +1,125 @@ -/** - * Migration script to add password field to User table - * and update existing users with hashed passwords - */ - -import { supabase } from '../src/lib/supabase'; -import bcrypt from 'bcryptjs'; - -const SALT_ROUNDS = 10; -const DEFAULT_PASSWORD = 'ChangeMe@123'; // Default password for existing users - -async function runMigration() { - console.log('๐Ÿ”„ Starting authentication migration...\n'); - - try { - // Fetch all existing users - console.log('๐Ÿ“‹ Fetching existing users...'); - const { data: users, error: fetchError } = await supabase - .from('User') - .select('id, email, password, role'); - - if (fetchError) { - console.error('โŒ Error fetching users:', fetchError); - throw fetchError; - } - - if (!users || users.length === 0) { - console.log('โ„น๏ธ No existing users found. Creating default admin...'); - } else { - console.log(`โœ… Found ${users.length} existing user(s)\n`); - - // Update existing users without passwords - const usersWithoutPassword = users.filter(u => !u.password); - - if (usersWithoutPassword.length > 0) { - console.log(`๐Ÿ” Updating ${usersWithoutPassword.length} user(s) with default passwords...\n`); - - const hashedPassword = await bcrypt.hash(DEFAULT_PASSWORD, SALT_ROUNDS); - - for (const user of usersWithoutPassword) { - console.log(` Updating: ${user.email} (${user.role})`); - - const { error: updateError } = await supabase - .from('User') - .update({ password: hashedPassword }) - .eq('id', user.id); - - if (updateError) { - console.error(` โŒ Failed to update ${user.email}:`, updateError); - } else { - console.log(` โœ… Updated successfully`); - } - } - - console.log(`\nโœ… Updated existing users with default password: ${DEFAULT_PASSWORD}`); - console.log('โš ๏ธ Users should change their passwords after first login!\n'); - } else { - console.log('โœ… All existing users already have passwords\n'); - } - } - - // Check if admin exists - const { data: existingAdmin } = await supabase - .from('User') - .select('id, email') - .eq('role', 'ADMIN') - .limit(1); - - if (!existingAdmin || existingAdmin.length === 0) { - // Create default admin user - console.log('๐Ÿ“ Creating default admin user...'); - - const defaultEmail = 'admin@dealsentry.com'; - const defaultPassword = 'Admin@123'; - const hashedPassword = await bcrypt.hash(defaultPassword, SALT_ROUNDS); - - const { error: createError } = await supabase - .from('User') - .insert({ - id: crypto.randomUUID(), - email: defaultEmail, - password: hashedPassword, - name: 'System Administrator', - role: 'ADMIN', - updatedAt: new Date().toISOString(), - }) - .select() - .single(); - - if (createError) { - console.error('โŒ Error creating admin user:', createError); - throw createError; - } - - console.log('โœ… Admin user created successfully!\n'); - console.log('๐Ÿ“‹ Admin Credentials:'); - console.log(` Email: ${defaultEmail}`); - console.log(` Password: ${defaultPassword}\n`); - } else { - console.log(`โœ… Admin user already exists: ${existingAdmin[0].email}\n`); - } - - console.log('โœ… Migration completed successfully!\n'); - console.log('โ”'.repeat(60)); - console.log('๐Ÿ“ SUMMARY:'); - console.log('โ”'.repeat(60)); - - const { data: allUsers } = await supabase - .from('User') - .select('email, role, password') - .order('role'); - - if (allUsers && allUsers.length > 0) { - console.log(`\nTotal users: ${allUsers.length}\n`); - allUsers.forEach(u => { - const hasPassword = !!u.password; - console.log(` ${hasPassword ? '๐Ÿ”' : 'โš ๏ธ '} ${u.email} (${u.role})`); - }); - } - - console.log('\nโ”'.repeat(60)); - console.log('โš ๏ธ IMPORTANT: All users should change their passwords!'); - console.log('โ”'.repeat(60)); - console.log(); - - } catch (error) { - console.error('\nโŒ Migration failed:', error); - process.exit(1); - } -} - -runMigration(); +/** + * Give users passwords so they can sign in when the server runs with + * AUTH_MODE=login. (In the default demo mode nobody signs in, so this is not needed.) + * + * npx tsx scripts/migrate-auth.ts # set a password for every user that has none + * npx tsx scripts/migrate-auth.ts --dry-run # show who would get one, change nothing + * npx tsx scripts/migrate-auth.ts --reset user@x.com # issue a fresh password for one user + * + * Every password is random and different per user. They are printed ONCE at the + * end and never stored in clear text โ€” copy them to a password manager or hand + * them to the users, who should change them under Settings. If no ADMIN exists, + * one (admin@dealsentry.ai) is created the same way. + */ + +import 'dotenv/config'; +import { randomBytes } from 'node:crypto'; +import bcrypt from 'bcryptjs'; +import { supabase } from '../src/lib/supabase'; + +const SALT_ROUNDS = 10; +const DEFAULT_ADMIN_EMAIL = 'admin@dealsentry.ai'; + +const args = process.argv.slice(2); +const dryRun = args.includes('--dry-run'); +const resetIndex = args.indexOf('--reset'); +const resetEmail = resetIndex >= 0 ? args[resetIndex + 1]?.trim().toLowerCase() : undefined; + +/** 16 URL-safe characters from a CSPRNG. */ +const generatePassword = () => randomBytes(12).toString('base64url'); + +interface Issued { + email: string; + role: string; + password: string; + note: string; +} + +async function issuePassword(userId: string): Promise<{ password: string; error: string | null }> { + const password = generatePassword(); + const { error } = await supabase + .from('User') + .update({ password: await bcrypt.hash(password, SALT_ROUNDS), updatedAt: new Date().toISOString() }) + .eq('id', userId); + return { password, error: error?.message ?? null }; +} + +async function main() { + if (resetIndex >= 0 && !resetEmail) { + throw new Error('--reset needs an email address'); + } + + const { data: users, error: fetchError } = await supabase.from('User').select('id, email, role, password'); + if (fetchError) throw fetchError; + + const issued: Issued[] = []; + const failed: string[] = []; + + if (resetEmail) { + const user = (users || []).find((u) => u.email.toLowerCase() === resetEmail); + if (!user) throw new Error(`No user with email ${resetEmail}`); + if (dryRun) { + console.log(`[dry run] would issue a new password for ${user.email}`); + return; + } + const { password, error } = await issuePassword(user.id); + if (error) throw new Error(`Could not update ${user.email}: ${error}`); + issued.push({ email: user.email, role: user.role, password, note: 'reset' }); + } else { + const needPassword = (users || []).filter((u) => !u.password); + console.log(`${users?.length ?? 0} user(s); ${needPassword.length} without a password.`); + + for (const user of needPassword) { + if (dryRun) { + console.log(`[dry run] would issue a password for ${user.email} (${user.role})`); + continue; + } + const { password, error } = await issuePassword(user.id); + if (error) { + failed.push(`${user.email}: ${error}`); + } else { + issued.push({ email: user.email, role: user.role, password, note: 'new' }); + } + } + + const hasAdmin = (users || []).some((u) => u.role === 'ADMIN'); + if (!hasAdmin) { + if (dryRun) { + console.log(`[dry run] would create an ADMIN ${DEFAULT_ADMIN_EMAIL}`); + } else { + const password = generatePassword(); + const { error } = await supabase.from('User').insert({ + id: crypto.randomUUID(), + email: DEFAULT_ADMIN_EMAIL, + password: await bcrypt.hash(password, SALT_ROUNDS), + name: 'System Administrator', + role: 'ADMIN', + updatedAt: new Date().toISOString(), + }); + if (error) failed.push(`${DEFAULT_ADMIN_EMAIL}: ${error.message}`); + else issued.push({ email: DEFAULT_ADMIN_EMAIL, role: 'ADMIN', password, note: 'created' }); + } + } + } + + if (dryRun) return; + + if (issued.length > 0) { + console.log('\nPasswords issued โ€” shown once, not stored anywhere in clear text:\n'); + console.table(issued.map(({ email, role, password, note }) => ({ email, role, password, note }))); + console.log('Ask each user to change theirs in Settings after the first sign-in.'); + } else if (failed.length === 0) { + console.log('Nothing to do: every user already has a password.'); + } + + if (failed.length > 0) { + console.error('\nFailed:'); + for (const line of failed) console.error(` ${line}`); + process.exitCode = 1; + } +} + +main().catch((err) => { + console.error('Failed:', err instanceof Error ? err.message : err); + process.exit(1); +}); diff --git a/src/api/auth.ts b/src/api/auth.ts index bf69a50..7a16d61 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -4,14 +4,21 @@ import bcrypt from 'bcryptjs'; import { supabase } from '../lib/supabase'; import { requireAuth } from './middleware/auth'; import { authLimiter } from './middleware/rateLimit'; +import { allowSelfRegistration, getAuthMode, getJwtSecret } from './lib/authConfig'; +import { logger } from './lib/logger'; const router = Router(); -const JWT_SECRET = process.env.NEXTAUTH_SECRET || 'default-secret-change-in-production'; const SALT_ROUNDS = 10; -// GET current session. There is no login screen, so this reports whichever user -// requireAuth resolved (a valid token if one was sent, otherwise the default user). +// Public: tells the SPA whether to show a sign-in screen. No secrets, no user data. +router.get('/config', (_req: Request, res: Response) => { + res.json({ mode: getAuthMode(), allowRegistration: allowSelfRegistration() }); +}); + +// GET current session: whichever user requireAuth resolved. In demo mode that is +// the default user when no token is sent; in login mode a valid token is required +// (401 AUTH_REQUIRED otherwise). router.get('/session', requireAuth, (req: Request, res: Response) => { res.json({ user: req.user }); }); @@ -53,7 +60,7 @@ router.post('/login', authLimiter, async (req: Request, res: Response) => { const token = jwt.sign( { userId: user.id, email: user.email, role: user.role, companyId }, - JWT_SECRET, + getJwtSecret(), { expiresIn: '7d' } ); @@ -68,41 +75,43 @@ router.post('/login', authLimiter, async (req: Request, res: Response) => { }, }); } catch (error) { - console.error('Error during login:', error); + logger.error('Error during login:', error); res.status(500).json({ error: 'Failed to login' }); } }); -// POST register +// POST register โ€” self-service sign-up, off unless ALLOW_SELF_REGISTRATION=true. +// New accounts are always SALES_REP with no company: a client-supplied companyId +// would let anyone join (and read) any tenant, so companies are assigned by an +// administrator (POST/PATCH /api/users) instead. router.post('/register', authLimiter, async (req: Request, res: Response) => { try { - const { email, name, password } = req.body; + if (!allowSelfRegistration()) { + return res.status(403).json({ error: 'Self-registration is disabled. Ask an administrator to create your account.' }); + } + + const { name, password } = req.body; + const email = typeof req.body.email === 'string' ? req.body.email.trim().toLowerCase() : ''; if (!email || !password) { return res.status(400).json({ error: 'Email and password are required' }); } // Validate password strength - if (password.length < 8) { + if (typeof password !== 'string' || password.length < 8) { return res.status(400).json({ error: 'Password must be at least 8 characters long' }); } - // Check if user already exists - const { data: existing } = await supabase - .from('User') - .select('id') - .eq('email', email) - .single(); + // Check if user already exists (limit(1), not single(): single() errors on duplicates and would let them through) + const { data: existing } = await supabase.from('User').select('id').eq('email', email).limit(1); - if (existing) { + if (existing && existing.length > 0) { return res.status(409).json({ error: 'User already exists' }); } // Hash the password const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS); - const companyId = (req.body.companyId as string) || null; - const insertPayload: Record = { id: crypto.randomUUID(), email, @@ -111,7 +120,6 @@ router.post('/register', authLimiter, async (req: Request, res: Response) => { role: 'SALES_REP', updatedAt: new Date().toISOString(), }; - if (companyId) insertPayload.company_id = companyId; const { data: user, error } = await supabase .from('User') @@ -125,7 +133,7 @@ router.post('/register', authLimiter, async (req: Request, res: Response) => { const token = jwt.sign( { userId: user.id, email: user.email, role: user.role, companyId: userCompanyId }, - JWT_SECRET, + getJwtSecret(), { expiresIn: '7d' } ); @@ -140,7 +148,7 @@ router.post('/register', authLimiter, async (req: Request, res: Response) => { }, }); } catch (error) { - console.error('Error during registration:', error); + logger.error('Error during registration:', error); res.status(500).json({ error: 'Failed to register' }); } }); @@ -205,7 +213,7 @@ router.post('/change-password', authLimiter, requireAuth, async (req: Request, r res.json({ message: 'Password changed successfully' }); } catch (error) { - console.error('Error changing password:', error); + logger.error('Error changing password:', error); res.status(500).json({ error: 'Failed to change password' }); } }); diff --git a/src/api/lib/authConfig.ts b/src/api/lib/authConfig.ts new file mode 100644 index 0000000..0d660a4 --- /dev/null +++ b/src/api/lib/authConfig.ts @@ -0,0 +1,67 @@ +/** + * Authentication mode and secrets. + * + * demo (default) โ€” no login screen. Every request without a valid token is + * served as one default user (DEMO_USER_EMAIL, else the first + * ADMIN). This is what the hosted demo runs. + * login โ€” real multi-user mode (AUTH_MODE=login). A valid bearer token + * is required for every protected route; there is no default + * identity, and data is isolated per company / per owner. + * + * Read from the environment on every call so tests (and a restarted dev server) + * can switch modes without re-importing modules. + */ + +export type AuthMode = 'demo' | 'login'; + +/** Placeholder previously used when NEXTAUTH_SECRET was unset. Never trusted in login mode. */ +const INSECURE_DEFAULT_SECRET = 'default-secret-change-in-production'; + +export function getAuthMode(): AuthMode { + return process.env.AUTH_MODE === 'login' ? 'login' : 'demo'; +} + +export function isLoginMode(): boolean { + return getAuthMode() === 'login'; +} + +/** + * Whether anyone may create their own account via POST /api/auth/register. + * Off unless ALLOW_SELF_REGISTRATION=true: accounts are otherwise created by an + * administrator (POST /api/users) or scripts/migrate-auth.ts. + */ +export function allowSelfRegistration(): boolean { + return process.env.ALLOW_SELF_REGISTRATION === 'true'; +} + +/** + * The secret used to sign and verify session tokens. In login mode a missing or + * placeholder secret is a hard error โ€” anyone could otherwise mint a token for + * any user. In demo mode the placeholder is tolerated (tokens only choose which + * user a request acts as, and every visitor is already the default admin). + */ +export function getJwtSecret(): string { + const secret = process.env.NEXTAUTH_SECRET; + if (secret && secret !== INSECURE_DEFAULT_SECRET) return secret; + if (isLoginMode()) { + throw new Error('AUTH_MODE=login requires NEXTAUTH_SECRET to be set to a long random value'); + } + return INSECURE_DEFAULT_SECRET; +} + +/** + * Fail fast at startup on an unsafe configuration instead of failing on the + * first request. Returns warnings for configurations that are legal but risky. + */ +export function checkAuthConfig(): string[] { + const warnings: string[] = []; + if (isLoginMode()) { + getJwtSecret(); // throws if unsafe + } else if (process.env.NODE_ENV === 'production') { + if (!process.env.NEXTAUTH_SECRET || process.env.NEXTAUTH_SECRET === INSECURE_DEFAULT_SECRET) { + warnings.push('NEXTAUTH_SECRET is not set; session tokens are signed with a public placeholder.'); + } + warnings.push('AUTH_MODE is "demo": every visitor is served as the default user. Set AUTH_MODE=login for multi-user deployments.'); + } + return warnings; +} diff --git a/src/api/middleware/auth.ts b/src/api/middleware/auth.ts index 7bb01a2..e765dbb 100644 --- a/src/api/middleware/auth.ts +++ b/src/api/middleware/auth.ts @@ -1,13 +1,17 @@ /** * Auth middleware helpers for multi-tenant access. * Admin (Company A) = role ADMIN, sees all. Other users see only their company's data. + * + * Two modes (see lib/authConfig.ts): + * - demo (default): a missing/unusable token is served as the default user. + * - login: a valid token is required; there is no default identity. */ import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { supabase } from '../../lib/supabase'; - -const JWT_SECRET = process.env.NEXTAUTH_SECRET || 'default-secret-change-in-production'; +import { getJwtSecret, isLoginMode } from '../lib/authConfig'; +import { logger } from '../lib/logger'; export interface AuthUser { id: string; @@ -33,8 +37,8 @@ export function resetDefaultUser(): void { } /** - * The app has no login screen: requests arrive without a token and are served as - * a single default identity. Preference order: DEMO_USER_EMAIL, then any ADMIN + * Demo mode has no login screen: requests arrive without a token and are served + * as a single default identity. Preference order: DEMO_USER_EMAIL, then any ADMIN * (sees all companies), then the first user in the table. */ async function resolveDefaultUser(): Promise<{ user: AuthUser | null; dbError: string | null }> { @@ -62,7 +66,7 @@ async function resolveDefaultUser(): Promise<{ user: AuthUser | null; dbError: s if (error) { dbError = error.message; - console.error('Default user lookup failed:', error.message); + logger.error('Default user lookup failed:', error.message); continue; } @@ -81,23 +85,40 @@ async function resolveDefaultUser(): Promise<{ user: AuthUser | null; dbError: s return { user: null, dbError }; } -/** Resolve the user a bearer token points at, or null if the token is unusable. */ -async function userFromToken(token: string): Promise { - let decoded: { userId: string }; +/** + * Resolve the user a session token points at. `user` is null when the token is + * unusable (bad signature, expired, unknown user, or not a session token at all); + * `dbError` is set only when the token itself was fine but the database could not + * be reached. + */ +async function userFromToken(token: string): Promise<{ user: AuthUser | null; dbError: string | null }> { + let decoded: { userId?: unknown }; try { - decoded = jwt.verify(token, JWT_SECRET) as { userId: string }; + decoded = jwt.verify(token, getJwtSecret()) as { userId?: unknown }; } catch (err) { - console.warn('Ignoring unusable token:', (err as Error).message); - return null; + logger.warn('Ignoring unusable token:', (err as Error).message); + return { user: null, dbError: null }; + } + + // OAuth start/state tokens are signed with the same secret but carry no userId; + // they must never be accepted as a session. + if (typeof decoded.userId !== 'string' || !decoded.userId) { + logger.warn('Ignoring token that is not a session token'); + return { user: null, dbError: null }; } + return loadUserById(decoded.userId); +} + +/** Load a user row by id as an AuthUser. See userFromToken for the result shape. */ +export async function loadUserById(id: string): Promise<{ user: AuthUser | null; dbError: string | null }> { // select('*') so missing columns (e.g. company_id) don't cause the query to fail. - // Rejections are folded into `error` so an unreachable DB falls through to the - // default-user path (and its clearer 503) rather than throwing. + // Rejections are folded into `error` so an unreachable DB is reported cleanly + // (demo mode then falls through to the default user, login mode to a 503). const { data: user, error } = await supabase .from('User') .select('*') - .eq('id', decoded.userId) + .eq('id', id) .single() .then( (r) => r, @@ -105,27 +126,31 @@ async function userFromToken(token: string): Promise { ); if (error || !user) { - console.warn('Token user lookup failed:', error?.message || 'no user'); - return null; + logger.warn('Token user lookup failed:', error?.message || 'no user'); + // PostgREST's "no rows" is a missing user (PGRST116); anything else is the database failing. + const missing = !user && (!error || (error as { code?: string }).code === 'PGRST116'); + return { user: null, dbError: missing ? null : error?.message ?? null }; } const u = user as { id: string; email: string; role: string; company_id?: string }; - return { id: u.id, email: u.email, role: u.role, companyId: u.company_id ?? null }; + return { user: { id: u.id, email: u.email, role: u.role, companyId: u.company_id ?? null }, dbError: null }; } /** * Resolve who a request is acting as. * - * Login was removed from the product, so a missing, expired, or otherwise - * unusable token is not an error โ€” the caller is served as the default user - * (see resolveDefaultUser). A valid token still wins, so any session issued - * before login was removed keeps its own identity. + * Demo mode: a missing, expired, or otherwise unusable token is not an error โ€” + * the caller is served as the default user (see resolveDefaultUser). A valid + * token still wins, so a real session keeps its own identity. + * + * Login mode: only a valid token resolves; there is no fallback identity. */ export async function resolveSessionUser( token?: string ): Promise<{ user: AuthUser | null; dbError: string | null }> { - const tokenUser = token ? await userFromToken(token) : null; - if (tokenUser) return { user: tokenUser, dbError: null }; + const fromToken = token ? await userFromToken(token) : { user: null, dbError: null }; + if (fromToken.user) return fromToken; + if (isLoginMode()) return fromToken; return resolveDefaultUser(); } @@ -143,6 +168,10 @@ export async function requireAuth(req: Request, res: Response, next: NextFunctio const { user, dbError } = await resolveSessionUser(token); if (!user) { + if (isLoginMode() && !dbError) { + res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' }); + return; + } res.status(503).json({ error: noSessionUserMessage(dbError), code: 'NO_SESSION_USER' }); return; } @@ -150,7 +179,7 @@ export async function requireAuth(req: Request, res: Response, next: NextFunctio req.user = user; next(); } catch (err) { - console.error('Auth middleware error:', err); + logger.error('Auth middleware error:', err); res.status(500).json({ error: 'Failed to resolve session' }); } } @@ -166,3 +195,35 @@ export function canAccessCompany(companyId: string | null, req: Request): boolea if (companyId == null) return true; // backward compat: no company = allow return req.user?.companyId === companyId; } + +/** + * Stricter per-resource check that also considers ownership. + * + * A resource that belongs to a company is visible to that company's members (and + * admins). A resource with no company is legacy single-tenant data: open to + * everyone in demo mode (every visitor is the admin anyway), but in login mode + * visible only to its owner โ€” otherwise any signed-in user could read it by id. + */ +export function canAccessResource( + resource: { companyId?: string | null; ownerId?: string | null }, + req: Request +): boolean { + if (isAdmin(req)) return true; + const companyId = resource.companyId ?? null; + if (companyId !== null) return req.user?.companyId === companyId; + if (!isLoginMode()) return true; + return resource.ownerId != null && resource.ownerId === req.user?.id; +} + +/** + * How a non-admin's list queries must be narrowed: to their company, or โ€” in + * login mode, when they have no company โ€” to rows they own. Returns null when no + * narrowing applies (admins, and legacy demo behaviour). + */ +export function listScope(req: Request): { column: 'company_id' | 'userId'; value: string } | null { + if (isAdmin(req)) return null; + const user = req.user; + if (user?.companyId) return { column: 'company_id', value: user.companyId }; + if (isLoginMode() && user) return { column: 'userId', value: user.id }; + return null; +} diff --git a/src/api/users.ts b/src/api/users.ts index 0492b9d..e633e01 100644 --- a/src/api/users.ts +++ b/src/api/users.ts @@ -1,9 +1,16 @@ import { Router, Request, Response } from 'express'; +import bcrypt from 'bcryptjs'; import { supabase } from '../lib/supabase'; import { requireAuth, isAdmin } from './middleware/auth'; +import { isLoginMode } from './lib/authConfig'; +import { logger } from './lib/logger'; const router = Router(); +const SALT_ROUNDS = 10; +const VALID_ROLES = ['SALES_REP', 'SALES_MANAGER', 'LEGAL', 'REVOPS', 'ADMIN', 'AUDITOR']; +const MIN_PASSWORD_LENGTH = 8; + // select('*') tolerates schema drift (e.g. missing company_id), so strip // sensitive columns here instead of relying on a column list. function sanitizeUser(user: T): Omit { @@ -11,9 +18,27 @@ function sanitizeUser(user: T): Omit (error as { code?: string } | null)?.code === '23505'; + +/** Validation shared by create and update. Returns an error message, or null if fine. */ +function validateUserInput(body: { role?: unknown; password?: unknown }): string | null { + if (body.role !== undefined && (typeof body.role !== 'string' || !VALID_ROLES.includes(body.role))) { + return `Invalid role. Expected one of: ${VALID_ROLES.join(', ')}`; + } + if (body.password !== undefined && (typeof body.password !== 'string' || body.password.length < MIN_PASSWORD_LENGTH)) { + return `Password must be at least ${MIN_PASSWORD_LENGTH} characters long`; + } + return null; +} + +// GET all users. In login mode only administrators may list everyone. router.get('/', requireAuth, async (req: Request, res: Response) => { try { + if (isLoginMode() && !isAdmin(req)) { + return res.status(403).json({ error: 'Only administrators can list users' }); + } + const { data: users, error } = await supabase .from('User') .select('*') @@ -23,16 +48,20 @@ router.get('/', requireAuth, async (req: Request, res: Response) => { res.json((users || []).map(sanitizeUser)); } catch (error) { - console.error('Error fetching users:', error); + logger.error('Error fetching users:', error); res.status(500).json({ error: 'Failed to fetch users' }); } }); -// GET single user +// GET single user. In login mode a non-admin may only read themselves. router.get('/:id', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; + if (isLoginMode() && !isAdmin(req) && id !== req.user?.id) { + return res.status(403).json({ error: 'You can only view your own user record' }); + } + const { data: user, error } = await supabase .from('User') .select('*') @@ -46,46 +75,59 @@ router.get('/:id', requireAuth, async (req: Request, res: Response) => { res.json(sanitizeUser(user)); } catch (error) { - console.error('Error fetching user:', error); + logger.error('Error fetching user:', error); res.status(500).json({ error: 'Failed to fetch user' }); } }); -// POST create user (admin only โ€” can assign roles) +// POST create user (admin only โ€” can assign roles, an initial password and a company) router.post('/', requireAuth, async (req: Request, res: Response) => { try { if (!isAdmin(req)) { return res.status(403).json({ error: 'Only administrators can create users' }); } - const { email, name, role } = req.body; + const { name, role, password, companyId } = req.body; + const email = typeof req.body.email === 'string' ? req.body.email.trim().toLowerCase() : ''; if (!email) { return res.status(400).json({ error: 'Email is required' }); } + const invalid = validateUserInput({ role, password }); + if (invalid) { + return res.status(400).json({ error: invalid }); + } + + const insertPayload: Record = { + id: crypto.randomUUID(), + email, + name: name || null, + role: role || 'SALES_REP', + updatedAt: new Date().toISOString(), + }; + if (password) insertPayload.password = await bcrypt.hash(password, SALT_ROUNDS); + // Needs the User.company_id column (prisma/manual/multi_user.sql). + if (companyId) insertPayload.company_id = companyId; const { data: user, error } = await supabase .from('User') - .insert({ - id: crypto.randomUUID(), - email, - name: name || null, - role: role || 'SALES_REP', - updatedAt: new Date().toISOString(), - }) + .insert(insertPayload) .select() .single(); + if (isDuplicateKey(error)) { + return res.status(409).json({ error: 'A user with that email already exists' }); + } if (error) throw error; res.status(201).json(sanitizeUser(user)); } catch (error) { - console.error('Error creating user:', error); + logger.error('Error creating user:', error); res.status(500).json({ error: 'Failed to create user' }); } }); -// PATCH update user (admin only โ€” role changes are privilege changes) +// PATCH update user (admin only โ€” role/company changes are privilege changes) router.patch('/:id', requireAuth, async (req: Request, res: Response) => { try { if (!isAdmin(req)) { @@ -93,12 +135,19 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { } const { id } = req.params; - const { email, name, role } = req.body; + const { email, name, role, password, companyId } = req.body; + + const invalid = validateUserInput({ role, password }); + if (invalid) { + return res.status(400).json({ error: invalid }); + } const updates: Record = { updatedAt: new Date().toISOString() }; - if (email !== undefined) updates.email = email; + if (email !== undefined) updates.email = typeof email === 'string' ? email.trim().toLowerCase() : email; if (name !== undefined) updates.name = name; if (role !== undefined) updates.role = role; + if (password !== undefined) updates.password = await bcrypt.hash(password, SALT_ROUNDS); + if (companyId !== undefined) updates.company_id = companyId || null; const { data: user, error } = await supabase .from('User') @@ -107,6 +156,9 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { .select() .single(); + if (isDuplicateKey(error)) { + return res.status(409).json({ error: 'A user with that email already exists' }); + } if (error) throw error; if (!user) { return res.status(404).json({ error: 'User not found' }); @@ -114,7 +166,7 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { res.json(sanitizeUser(user)); } catch (error) { - console.error('Error updating user:', error); + logger.error('Error updating user:', error); res.status(500).json({ error: 'Failed to update user' }); } }); @@ -128,6 +180,10 @@ router.delete('/:id', requireAuth, async (req: Request, res: Response) => { const { id } = req.params; + if (id === req.user?.id) { + return res.status(400).json({ error: 'You cannot delete your own account' }); + } + const { error } = await supabase .from('User') .delete() @@ -137,7 +193,7 @@ router.delete('/:id', requireAuth, async (req: Request, res: Response) => { res.status(204).send(); } catch (error) { - console.error('Error deleting user:', error); + logger.error('Error deleting user:', error); res.status(500).json({ error: 'Failed to delete user' }); } }); diff --git a/tests/loginMode.test.ts b/tests/loginMode.test.ts new file mode 100644 index 0000000..6908a53 --- /dev/null +++ b/tests/loginMode.test.ts @@ -0,0 +1,363 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; + +// Chainable Supabase mock; each terminal returns a single controllable result. +const { mockSingle, mockLimit, mockOrder, mockInsert, supabaseMock } = vi.hoisted(() => { + const mockSingle = vi.fn(); + const mockLimit = vi.fn(); + const mockOrder = vi.fn(); + const builder: Record = {}; + const mockInsert = vi.fn(() => builder); + builder.select = vi.fn(() => builder); + builder.eq = vi.fn(() => builder); + builder.insert = mockInsert; + builder.update = vi.fn(() => builder); + builder.delete = vi.fn(() => builder); + builder.order = mockOrder; + builder.single = mockSingle; + builder.limit = mockLimit; + const supabaseMock = { from: vi.fn(() => builder) }; + return { mockSingle, mockLimit, mockOrder, mockInsert, supabaseMock }; +}); +vi.mock('../src/lib/supabase', () => ({ supabase: supabaseMock, default: supabaseMock })); + +import { + canAccessResource, + listScope, + requireAuth, + resetDefaultUser, +} from '../src/api/middleware/auth'; +import { checkAuthConfig, getAuthMode, getJwtSecret } from '../src/api/lib/authConfig'; +import authRouter from '../src/api/auth'; +import usersRouter from '../src/api/users'; + +const SECRET = process.env.NEXTAUTH_SECRET as string; +const ENV_KEYS = ['AUTH_MODE', 'ALLOW_SELF_REGISTRATION', 'NEXTAUTH_SECRET', 'NODE_ENV'] as const; +let savedEnv: Record; + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/auth', authRouter); + app.use('/api/users', usersRouter); + app.get('/protected', requireAuth, (req, res) => { + res.json({ user: req.user }); + }); + return app; +} + +const tokenFor = (userId = 'u1') => jwt.sign({ userId }, SECRET, { expiresIn: '1h' }); + +const userRow = (over: Record = {}) => ({ + id: 'u1', + email: 'rep@b.com', + role: 'SALES_REP', + company_id: null, + ...over, +}); + +beforeEach(() => { + savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + mockSingle.mockReset(); + mockLimit.mockReset(); + mockOrder.mockReset(); + mockInsert.mockClear(); + // A default admin exists, so a leak into demo behaviour would be visible. + mockLimit.mockResolvedValue({ data: [userRow({ id: 'admin1', role: 'ADMIN' })], error: null }); + resetDefaultUser(); +}); + +afterEach(() => { + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } +}); + +describe('authConfig', () => { + it('defaults to demo mode and switches on AUTH_MODE=login', () => { + delete process.env.AUTH_MODE; + expect(getAuthMode()).toBe('demo'); + process.env.AUTH_MODE = 'login'; + expect(getAuthMode()).toBe('login'); + process.env.AUTH_MODE = 'anything-else'; + expect(getAuthMode()).toBe('demo'); + }); + + it('refuses a missing or placeholder secret in login mode', () => { + process.env.AUTH_MODE = 'login'; + delete process.env.NEXTAUTH_SECRET; + expect(() => getJwtSecret()).toThrow(/NEXTAUTH_SECRET/); + process.env.NEXTAUTH_SECRET = 'default-secret-change-in-production'; + expect(() => getJwtSecret()).toThrow(/NEXTAUTH_SECRET/); + expect(() => checkAuthConfig()).toThrow(); + }); + + it('tolerates a missing secret in demo mode, and warns in production', () => { + process.env.AUTH_MODE = 'demo'; + delete process.env.NEXTAUTH_SECRET; + expect(getJwtSecret()).toBeTruthy(); + expect(checkAuthConfig()).toEqual([]); + process.env.NODE_ENV = 'production'; + expect(checkAuthConfig().join(' ')).toMatch(/NEXTAUTH_SECRET/); + }); + + it('accepts a real secret in login mode', () => { + process.env.AUTH_MODE = 'login'; + process.env.NEXTAUTH_SECRET = 'a-long-random-secret-for-testing-only'; + expect(getJwtSecret()).toBe('a-long-random-secret-for-testing-only'); + expect(() => checkAuthConfig()).not.toThrow(); + }); +}); + +describe('requireAuth in login mode', () => { + beforeEach(() => { + process.env.AUTH_MODE = 'login'; + }); + + it('401s with AUTH_REQUIRED when no token is sent, and never serves the default user', async () => { + const res = await request(buildApp()).get('/protected'); + expect(res.status).toBe(401); + expect(res.body.code).toBe('AUTH_REQUIRED'); + expect(mockLimit).not.toHaveBeenCalled(); + }); + + it('401s for a garbage token', async () => { + const res = await request(buildApp()).get('/protected').set('Authorization', 'Bearer nope'); + expect(res.status).toBe(401); + expect(res.body.code).toBe('AUTH_REQUIRED'); + }); + + it('401s for an expired token', async () => { + const expired = jwt.sign({ userId: 'u1' }, SECRET, { expiresIn: -10 }); + const res = await request(buildApp()).get('/protected').set('Authorization', `Bearer ${expired}`); + expect(res.status).toBe(401); + }); + + it('401s for a token signed with another secret', async () => { + const forged = jwt.sign({ userId: 'u1' }, 'not-the-real-secret', { expiresIn: '1h' }); + const res = await request(buildApp()).get('/protected').set('Authorization', `Bearer ${forged}`); + expect(res.status).toBe(401); + }); + + it('401s when the token is valid but the user no longer exists', async () => { + mockSingle.mockResolvedValue({ data: null, error: { code: 'PGRST116', message: 'no rows' } }); + const res = await request(buildApp()).get('/protected').set('Authorization', `Bearer ${tokenFor()}`); + expect(res.status).toBe(401); + }); + + it('503s (not 401) when the token is valid but the database is failing', async () => { + mockSingle.mockResolvedValue({ data: null, error: { message: 'fetch failed' } }); + const res = await request(buildApp()).get('/protected').set('Authorization', `Bearer ${tokenFor()}`); + expect(res.status).toBe(503); + expect(res.body.error).toMatch(/database unavailable/i); + }); + + it('accepts a valid token and loads the user', async () => { + mockSingle.mockResolvedValue({ data: userRow({ company_id: 'c1' }), error: null }); + const res = await request(buildApp()).get('/protected').set('Authorization', `Bearer ${tokenFor()}`); + expect(res.status).toBe(200); + expect(res.body.user).toMatchObject({ id: 'u1', role: 'SALES_REP', companyId: 'c1' }); + }); + + it('demo mode is unchanged: no token still resolves the default user', async () => { + process.env.AUTH_MODE = 'demo'; + const res = await request(buildApp()).get('/protected'); + expect(res.status).toBe(200); + expect(res.body.user).toMatchObject({ id: 'admin1', role: 'ADMIN' }); + }); +}); + +describe('canAccessResource', () => { + const asReq = (user: Record) => ({ user }) as never; + const admin = asReq({ id: 'a', role: 'ADMIN', companyId: null }); + const rep = asReq({ id: 'r1', role: 'SALES_REP', companyId: 'c1' }); + const loner = asReq({ id: 'r2', role: 'SALES_REP', companyId: null }); + + it('admins can access anything in either mode', () => { + for (const mode of ['demo', 'login']) { + process.env.AUTH_MODE = mode; + expect(canAccessResource({ companyId: 'c9', ownerId: 'x' }, admin)).toBe(true); + expect(canAccessResource({ companyId: null, ownerId: 'x' }, admin)).toBe(true); + } + }); + + it('a company resource is visible only to that company', () => { + for (const mode of ['demo', 'login']) { + process.env.AUTH_MODE = mode; + expect(canAccessResource({ companyId: 'c1', ownerId: 'x' }, rep)).toBe(true); + expect(canAccessResource({ companyId: 'c2', ownerId: 'x' }, rep)).toBe(false); + expect(canAccessResource({ companyId: 'c1', ownerId: 'x' }, loner)).toBe(false); + } + }); + + it('legacy no-company data is open in demo mode but owner-only in login mode', () => { + process.env.AUTH_MODE = 'demo'; + expect(canAccessResource({ companyId: null, ownerId: 'someone-else' }, rep)).toBe(true); + + process.env.AUTH_MODE = 'login'; + expect(canAccessResource({ companyId: null, ownerId: 'someone-else' }, rep)).toBe(false); + expect(canAccessResource({ companyId: null, ownerId: 'r1' }, rep)).toBe(true); + expect(canAccessResource({ companyId: null, ownerId: null }, rep)).toBe(false); + }); +}); + +describe('listScope', () => { + const asReq = (user: Record) => ({ user }) as never; + + it('does not narrow admins', () => { + process.env.AUTH_MODE = 'login'; + expect(listScope(asReq({ id: 'a', role: 'ADMIN', companyId: 'c1' }))).toBeNull(); + }); + + it('narrows a company member to their company', () => { + expect(listScope(asReq({ id: 'r', role: 'SALES_REP', companyId: 'c1' }))).toEqual({ + column: 'company_id', + value: 'c1', + }); + }); + + it('narrows a company-less user to their own rows in login mode only', () => { + const loner = asReq({ id: 'r2', role: 'SALES_REP', companyId: null }); + process.env.AUTH_MODE = 'demo'; + expect(listScope(loner)).toBeNull(); + process.env.AUTH_MODE = 'login'; + expect(listScope(loner)).toEqual({ column: 'userId', value: 'r2' }); + }); +}); + +describe('GET /api/auth/config', () => { + it('reports the mode and registration flag without authentication', async () => { + process.env.AUTH_MODE = 'login'; + process.env.ALLOW_SELF_REGISTRATION = 'true'; + const res = await request(buildApp()).get('/api/auth/config'); + expect(res.status).toBe(200); + expect(res.body).toEqual({ mode: 'login', allowRegistration: true }); + }); + + it('defaults to demo with registration closed', async () => { + delete process.env.AUTH_MODE; + delete process.env.ALLOW_SELF_REGISTRATION; + const res = await request(buildApp()).get('/api/auth/config'); + expect(res.body).toEqual({ mode: 'demo', allowRegistration: false }); + }); +}); + +describe('POST /api/auth/register', () => { + const body = { email: ' New.User@Example.COM ', password: 'long-enough-pw', name: 'New User' }; + + it('is closed unless ALLOW_SELF_REGISTRATION=true', async () => { + delete process.env.ALLOW_SELF_REGISTRATION; + const res = await request(buildApp()).post('/api/auth/register').send(body); + expect(res.status).toBe(403); + expect(mockInsert).not.toHaveBeenCalled(); + }); + + describe('when enabled', () => { + beforeEach(() => { + process.env.ALLOW_SELF_REGISTRATION = 'true'; + }); + + it('creates a SALES_REP with a normalised email and ignores a client-supplied companyId', async () => { + mockLimit.mockResolvedValue({ data: [], error: null }); // no existing user + mockSingle.mockResolvedValue({ + data: { id: 'new1', email: 'new.user@example.com', name: 'New User', role: 'SALES_REP' }, + error: null, + }); + + const res = await request(buildApp()) + .post('/api/auth/register') + .send({ ...body, companyId: 'victim-company', role: 'ADMIN' }); + + expect(res.status).toBe(201); + expect(res.body.token).toBeTruthy(); + expect(res.body.user.role).toBe('SALES_REP'); + + const inserted = (mockInsert.mock.calls[0] as unknown[])[0] as Record; + expect(inserted.email).toBe('new.user@example.com'); + expect(inserted.role).toBe('SALES_REP'); + expect(inserted).not.toHaveProperty('company_id'); + // The password is stored hashed, never in the clear. + expect(inserted.password).not.toBe(body.password); + expect(String(inserted.password)).toMatch(/^\$2[aby]\$/); + }); + + it('409s when the email is already registered', async () => { + mockLimit.mockResolvedValue({ data: [{ id: 'existing' }], error: null }); + const res = await request(buildApp()).post('/api/auth/register').send(body); + expect(res.status).toBe(409); + expect(mockInsert).not.toHaveBeenCalled(); + }); + + it('400s on a short password and on a missing email', async () => { + const short = await request(buildApp()).post('/api/auth/register').send({ ...body, password: 'short' }); + expect(short.status).toBe(400); + const noEmail = await request(buildApp()).post('/api/auth/register').send({ password: 'long-enough-pw' }); + expect(noEmail.status).toBe(400); + }); + }); +}); + +describe('users routes in login mode', () => { + beforeEach(() => { + process.env.AUTH_MODE = 'login'; + }); + + it('does not let a non-admin list every user', async () => { + mockSingle.mockResolvedValueOnce({ data: userRow(), error: null }); + const res = await request(buildApp()).get('/api/users').set('Authorization', `Bearer ${tokenFor()}`); + expect(res.status).toBe(403); + }); + + it('does not let a non-admin read another user, but allows reading themselves', async () => { + mockSingle.mockResolvedValueOnce({ data: userRow(), error: null }); + const other = await request(buildApp()).get('/api/users/someone-else').set('Authorization', `Bearer ${tokenFor()}`); + expect(other.status).toBe(403); + + mockSingle + .mockResolvedValueOnce({ data: userRow(), error: null }) // requireAuth + .mockResolvedValueOnce({ data: userRow({ password: 'hash' }), error: null }); // the route + const self = await request(buildApp()).get('/api/users/u1').set('Authorization', `Bearer ${tokenFor()}`); + expect(self.status).toBe(200); + expect(self.body).not.toHaveProperty('password'); + }); + + it('lets an admin create a user with a hashed password and a company', async () => { + mockSingle + .mockResolvedValueOnce({ data: userRow({ id: 'adm', role: 'ADMIN' }), error: null }) // requireAuth + .mockResolvedValueOnce({ data: userRow({ id: 'n1', email: 'n@b.com', password: 'x' }), error: null }); // insert + const res = await request(buildApp()) + .post('/api/users') + .set('Authorization', `Bearer ${tokenFor('adm')}`) + .send({ email: 'N@B.com', password: 'initial-password', companyId: 'c7', role: 'LEGAL' }); + + expect(res.status).toBe(201); + expect(res.body).not.toHaveProperty('password'); + const inserted = (mockInsert.mock.calls[0] as unknown[])[0] as Record; + expect(inserted).toMatchObject({ email: 'n@b.com', role: 'LEGAL', company_id: 'c7' }); + expect(String(inserted.password)).toMatch(/^\$2[aby]\$/); + }); + + it('rejects an unknown role and a weak password', async () => { + mockSingle.mockResolvedValue({ data: userRow({ id: 'adm', role: 'ADMIN' }), error: null }); + const badRole = await request(buildApp()) + .post('/api/users') + .set('Authorization', `Bearer ${tokenFor('adm')}`) + .send({ email: 'a@b.com', role: 'SUPERUSER' }); + expect(badRole.status).toBe(400); + + const weak = await request(buildApp()) + .post('/api/users') + .set('Authorization', `Bearer ${tokenFor('adm')}`) + .send({ email: 'a@b.com', password: '123' }); + expect(weak.status).toBe(400); + }); + + it('stops an admin deleting their own account', async () => { + mockSingle.mockResolvedValue({ data: userRow({ id: 'adm', role: 'ADMIN' }), error: null }); + const res = await request(buildApp()).delete('/api/users/adm').set('Authorization', `Bearer ${tokenFor('adm')}`); + expect(res.status).toBe(400); + }); +}); From 5746c20c9305e2fdbb79cf28ca19f58b184c2c92 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:13 +0530 Subject: [PATCH 03/11] feat(ai): provider-agnostic LLM client, rule-based analysis fallback, 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. --- prisma/manual/semantic_search.sql | 16 +- scripts/backfill-embeddings.ts | 25 +- src/api/analytics.ts | 10 +- src/api/analyze.ts | 294 ++--- src/api/lib/analysisService.ts | 254 ++++ src/api/lib/compliance.test.ts | 41 +- src/api/lib/compliance.ts | 24 +- src/api/lib/embeddings.test.ts | 132 ++ src/api/lib/embeddings.ts | 86 +- src/api/lib/gemini.ts | 2 + src/api/lib/llm.test.ts | 129 ++ src/api/lib/llm.ts | 77 +- src/api/lib/proposalGeneration.test.ts | 105 ++ src/api/lib/proposalGeneration.ts | 153 +++ src/api/lib/proposalPdf.test.ts | 184 +++ src/api/lib/proposalPdf.ts | 687 ++++++++++ src/api/lib/proposalStore.ts | 102 ++ src/api/lib/ruleAnalysis.test.ts | 280 ++++ src/api/lib/ruleAnalysis.ts | 415 ++++++ src/api/middleware/rateLimit.ts | 9 + src/api/proposals.ts | 1643 +++++++----------------- tests/analyze.test.ts | 372 ++++++ tests/helpers/supabaseMock.ts | 158 +++ tests/proposals.test.ts | 428 ++++++ 24 files changed, 4156 insertions(+), 1470 deletions(-) create mode 100644 src/api/lib/analysisService.ts create mode 100644 src/api/lib/embeddings.test.ts create mode 100644 src/api/lib/gemini.ts create mode 100644 src/api/lib/llm.test.ts create mode 100644 src/api/lib/proposalGeneration.test.ts create mode 100644 src/api/lib/proposalGeneration.ts create mode 100644 src/api/lib/proposalPdf.test.ts create mode 100644 src/api/lib/proposalPdf.ts create mode 100644 src/api/lib/proposalStore.ts create mode 100644 src/api/lib/ruleAnalysis.test.ts create mode 100644 src/api/lib/ruleAnalysis.ts create mode 100644 tests/analyze.test.ts create mode 100644 tests/helpers/supabaseMock.ts create mode 100644 tests/proposals.test.ts diff --git a/prisma/manual/semantic_search.sql b/prisma/manual/semantic_search.sql index 68528b4..e91a7b7 100644 --- a/prisma/manual/semantic_search.sql +++ b/prisma/manual/semantic_search.sql @@ -8,7 +8,10 @@ -- 1. pgvector extension create extension if not exists vector; --- 2. Embedding column on Proposal (text-embedding-ada-002 => 1536 dims) +-- 2. Embedding column on Proposal. 1536 dims = Azure text-embedding-ada-002, and +-- Gemini gemini-embedding-001 requested at 1536 dimensions (see +-- src/api/lib/embeddings.ts). Changing model width means changing this and +-- EMBEDDING_DIM together. alter table "Proposal" add column if not exists embedding vector(1536); -- 2b. Tenant column referenced by match_proposals below. The API writes it @@ -17,9 +20,14 @@ alter table "Proposal" add column if not exists embedding vector(1536); alter table "Proposal" add column if not exists company_id text; -- 3. Approximate-nearest-neighbour index (cosine distance). --- Tune `lists` upward as the table grows (โ‰ˆ rows/1000). -create index if not exists proposal_embedding_idx - on "Proposal" using ivfflat (embedding vector_cosine_ops) with (lists = 100); +-- HNSW needs no training step and keeps good recall on small tables. The +-- previous ivfflat index (lists = 100) probes a single list by default, so on +-- a table with only a handful of rows it can return few or no matches. +-- Requires pgvector >= 0.5 (Supabase ships 0.8). Safe to re-run: this replaces +-- the old ivfflat index if present. +drop index if exists proposal_embedding_idx; +create index if not exists proposal_embedding_hnsw_idx + on "Proposal" using hnsw (embedding vector_cosine_ops); -- 4. Similarity search function used by GET /api/proposals/search. -- filter_company NULL => no company filter (admins see all). diff --git a/scripts/backfill-embeddings.ts b/scripts/backfill-embeddings.ts index ef23b75..a094545 100644 --- a/scripts/backfill-embeddings.ts +++ b/scripts/backfill-embeddings.ts @@ -2,9 +2,16 @@ * Backfill content embeddings for existing proposals (Phase 4 semantic search). * * Prerequisite: run prisma/manual/semantic_search.sql first (adds the pgvector - * column + index + RPC). Then: npm run backfill:embeddings + * column + index + RPC). Then: * - * Idempotent: proposals that already have an embedding are skipped. + * npm run backfill:embeddings # only proposals with no embedding yet + * npm run backfill:embeddings -- --all # re-embed everything + * + * Use --all after switching embedding provider/model (e.g. Azure ada-002 -> + * Gemini): vectors from different models are not comparable, so a mixed table + * gives meaningless rankings. + * + * Idempotent: without --all, proposals that already have an embedding are skipped. */ import { config } from 'dotenv'; @@ -13,6 +20,12 @@ config(); import { supabase } from '../src/lib/supabase'; import { generateEmbedding } from '../src/api/lib/embeddings'; +const reembedAll = process.argv.includes('--all'); +/** Pause between provider calls to stay under free-tier rate limits. */ +const THROTTLE_MS = 250; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + async function main() { const { data: rows, error } = await supabase .from('Proposal') @@ -23,12 +36,14 @@ async function main() { process.exit(1); } + console.log(`${rows?.length ?? 0} proposal(s); mode: ${reembedAll ? 're-embed all' : 'fill missing only'}`); + let embedded = 0; let skipped = 0; let failed = 0; for (const p of rows || []) { - if (p.embedding) { + if (p.embedding && !reembedAll) { skipped++; continue; } @@ -46,13 +61,15 @@ async function main() { } embedded++; console.log(`Embedded ${p.id} (${embedded})`); + await sleep(THROTTLE_MS); } console.log(`\nDone. embedded=${embedded} skipped=${skipped} failed=${failed}`); + if (failed > 0) process.exitCode = 1; } main() - .then(() => process.exit(0)) + .then(() => process.exit(process.exitCode ?? 0)) .catch((err) => { console.error(err); process.exit(1); diff --git a/src/api/analytics.ts b/src/api/analytics.ts index 486f48e..4fdff3e 100644 --- a/src/api/analytics.ts +++ b/src/api/analytics.ts @@ -1,7 +1,8 @@ import { Router, Request, Response } from 'express'; import { supabase } from '../lib/supabase'; -import { requireAuth, isAdmin } from './middleware/auth'; +import { requireAuth, listScope } from './middleware/auth'; import { buildAnalyticsSummary, type AnalyticsProposal } from './lib/analytics'; +import { logger } from './lib/logger'; const router = Router(); @@ -29,8 +30,9 @@ router.get('/summary', requireAuth, async (req: Request, res: Response) => { RiskReport (readinessScore, legalRisk, pricingRisk, structuralRisk) `); - if (!isAdmin(req) && req.user?.companyId) { - query = query.eq('company_id', req.user.companyId); + const scope = listScope(req); + if (scope) { + query = query.eq(scope.column, scope.value); } const { data: rows, error } = await query; @@ -55,7 +57,7 @@ router.get('/summary', requireAuth, async (req: Request, res: Response) => { res.json(buildAnalyticsSummary(proposals)); } catch (error) { - console.error('Error building analytics summary:', error); + logger.error('Error building analytics summary:', error); res.status(500).json({ error: 'Failed to build analytics summary' }); } }); diff --git a/src/api/analyze.ts b/src/api/analyze.ts index 1212d90..f860bcf 100644 --- a/src/api/analyze.ts +++ b/src/api/analyze.ts @@ -1,220 +1,112 @@ import { Router, Request, Response } from 'express'; import { supabase } from '../lib/supabase'; -import { requireAuth, canAccessCompany } from './middleware/auth'; -import { normalizeAnalysis, shouldAutoReview } from './lib/compliance'; -import { llmClient as client, llmModel as deployment, llmExtraParams } from './lib/llm'; +import { requireAuth, canAccessResource } from './middleware/auth'; +import { analyzeAndSave, type AnalysisOutcome, type ProposalForAnalysis } from './lib/analysisService'; +import { getLlm } from './lib/llm'; +import { logger } from './lib/logger'; const router = Router(); -// Analyze a proposal (admin or same company only) -router.post('/:proposalId', requireAuth, async (req: Request, res: Response) => { - try { - const { proposalId } = req.params; - - const { data: proposal, error: proposalError } = await supabase - .from('Proposal') - .select('*') - .eq('id', proposalId) - .single(); - - if (proposalError || !proposal) { - return res.status(404).json({ error: 'Proposal not found' }); - } - - const proposalCompanyId = (proposal as { company_id?: string }).company_id ?? null; - if (!canAccessCompany(proposalCompanyId, req)) { - return res.status(403).json({ error: 'You do not have access to this proposal' }); - } - - // Get compliance rules - const { data: rules } = await supabase - .from('Rule') - .select('*') - .eq('isActive', true); - - const rulesText = (rules || []).map((r: { name: string; description: string }) => - `- ${r.name}: ${r.description}` - ).join('\n'); - - const metadata = proposal.metadata as Record; - - // Build the prompt - metadata is optional; AI must extract/verify from document content - const metadataDiscount = metadata?.discount != null ? Number(metadata.discount) : null; - const metadataDealSize = metadata?.dealSize != null ? Number(metadata.dealSize) : null; - const hasMetadataDiscount = metadataDiscount !== null && !Number.isNaN(metadataDiscount); - const hasMetadataDealSize = metadataDealSize !== null && !Number.isNaN(metadataDealSize); - - const prompt = `You are a proposal review assistant. Analyze the following proposal against the compliance rules and provide a risk assessment. - -## Proposal Details (from form โ€“ optional; verify against document) -Title: ${proposal.title} -Client: ${metadata?.clientName || 'Unknown'} -Deal Size (form): ${hasMetadataDealSize ? `$${metadataDealSize}` : 'Not provided โ€“ extract from document'} -Discount % (form): ${hasMetadataDiscount ? `${metadataDiscount}%` : 'Not provided โ€“ extract from document'} -Region: ${metadata?.region || 'Unknown'} -Industry: ${metadata?.industry || 'Unknown'} - -## Proposal Content (source of truth for numbers) -${proposal.content.substring(0, 4000)} - -## Compliance Rules -${rulesText || 'No specific rules defined'} - -## Critical Analysis Requirements - -### Discount Analysis (IMPORTANT): -- FIRST: Extract the actual discount from the proposal content (look for percentages, "discount", "off", "reduction", etc.). -- If the document states a discount, use that value for compliance. If the form provided a value that differs from the document, prefer the document. -- If no discount is found in the document, you may use the form value if provided. -- Maximum allowed discount threshold: 25% -- If discount is ABOVE 25%, flag as CRITICAL with "DISCOUNT VIOLATION" -- If discount is 25% or BELOW, do NOT flag any discount issues - -### Pricing Risk Calculation: -Calculate pricing risk based on the discount you determined (from document first): -- 0-10% discount = 10-15% pricing risk (LOW) -- 11-15% discount = 25-35% pricing risk (MEDIUM) -- 16-20% discount = 40-50% pricing risk (MEDIUM-HIGH) -- 21-25% discount = 60-70% pricing risk (HIGH - near limit) -- 26%+ discount = 90-100% pricing risk (CRITICAL - VIOLATION) - -### Deal Size Analysis: -- FIRST: Extract deal size / contract value from the proposal content if present. -- If the document states an amount, use that for compliance. If the form value differs, prefer the document. -- Minimum deal size: $10,000 -- If below minimum, flag as CRITICAL violation -- Assess if appropriate approvals are in place for this amount +/** Most proposals one bulk request may analyze (each can be an AI call). */ +export const MAX_BULK_ANALYSIS = 10; -### Content Analysis: -- Check for required legal clauses: indemnification, liability limitation, termination rights -- Verify payment terms don't exceed 90 days -- Check for proper contract structure +type AnalyzeResult = + | { ok: true; outcome: AnalysisOutcome } + | { ok: false; status: number; error: string }; -## Instructions -Analyze this proposal carefully using the ACTUAL values provided above and respond: -1. A readiness score (0-100) - higher if compliant -2. Legal risk percentage (0-100) - based on missing clauses -3. Pricing risk percentage (0-100) - based on discount vs threshold -4. Structural risk percentage (0-100) - based on content structure -5. List of findings (ONLY flag issues that actually exist based on the data) -6. List of recommendations (specific to the actual issues found) +/** Load a proposal, check the caller may see it, then analyze and persist. */ +async function analyzeForRequest(proposalId: string, req: Request): Promise { + const { data: proposal, error: proposalError } = await supabase + .from('Proposal') + .select('*') + .eq('id', proposalId) + .single(); -IMPORTANT: Base your analysis on the discount and deal size you extract from the proposal content. If the form provided values that conflict with the document, use the document values for compliance and risk. - -Respond in JSON format: -{ - "readinessScore": number, - "legalRisk": number, - "pricingRisk": number, - "structuralRisk": number, - "findings": [ - { "type": "string", "level": "CRITICAL|HIGH|MEDIUM|LOW", "message": "string", "location": "string" } - ], - "recommendations": [ - { "paragraphId": "string", "suggestion": "string", "reason": "string" } - ] -}`; - - // Call Azure OpenAI - const completion = await client.chat.completions.create({ - model: deployment, - messages: [ - { role: 'system', content: 'You are a proposal compliance analyst. Respond only with valid JSON.' }, - { role: 'user', content: prompt } - ], - temperature: 0.3, - max_tokens: 4000, - response_format: { type: 'json_object' }, - ...llmExtraParams, - }); - - const responseContent = completion.choices[0]?.message?.content; - if (!responseContent) { - throw new Error('No response from AI'); - } + if (proposalError || !proposal) { + return { ok: false, status: 404, error: 'Proposal not found' }; + } - const analysis = normalizeAnalysis(JSON.parse(responseContent)); + const row = proposal as { company_id?: string | null; userId?: string | null }; + if (!canAccessResource({ companyId: row.company_id ?? null, ownerId: row.userId ?? null }, req)) { + return { ok: false, status: 403, error: 'You do not have access to this proposal' }; + } - // Check if risk report already exists - const { data: existingReport } = await supabase - .from('RiskReport') - .select('id') - .eq('proposalId', proposalId) - .single(); + try { + const outcome = await analyzeAndSave(proposal as ProposalForAnalysis); + return { ok: true, outcome }; + } catch (error) { + logger.error('Error analyzing proposal:', error); + return { ok: false, status: 500, error: 'Failed to analyze proposal' }; + } +} + +function formatOutcome(outcome: AnalysisOutcome) { + const { riskReport } = outcome; + return { + proposalId: outcome.proposalId, + analysisSource: outcome.analysisSource, + statusAdvanced: outcome.statusAdvanced, + riskReport: { + id: riskReport.id, + readinessScore: riskReport.readinessScore, + legalRisk: riskReport.legalRisk, + pricingRisk: riskReport.pricingRisk, + structuralRisk: riskReport.structuralRisk, + findings: riskReport.findings, + recommendations: riskReport.recommendations, + }, + }; +} + +// Which engine a new analysis will use: the configured AI, or the built-in rule +// checker (no AI configured, or ANALYSIS_MODE=rules). +router.get('/mode', requireAuth, (_req: Request, res: Response) => { + const llm = process.env.ANALYSIS_MODE === 'rules' ? null : getLlm(); + res.json({ mode: llm ? 'ai' : 'rules', provider: llm?.provider ?? null, model: llm?.model ?? null }); +}); - let riskReport; - - if (existingReport) { - // Update existing report - const { data, error: updateError } = await supabase - .from('RiskReport') - .update({ - readinessScore: analysis.readinessScore, - legalRisk: analysis.legalRisk, - pricingRisk: analysis.pricingRisk, - structuralRisk: analysis.structuralRisk, - findings: analysis.findings, - recommendations: analysis.recommendations, - }) - .eq('id', existingReport.id) - .select() - .single(); - - if (updateError) throw updateError; - riskReport = data; - } else { - // Create new report - const { data, error: insertError } = await supabase - .from('RiskReport') - .insert({ - id: crypto.randomUUID(), - proposalId, - readinessScore: analysis.readinessScore, - legalRisk: analysis.legalRisk, - pricingRisk: analysis.pricingRisk, - structuralRisk: analysis.structuralRisk, - findings: analysis.findings, - recommendations: analysis.recommendations, - }) - .select() - .single(); +// Analyze several proposals in one request (sequentially, to respect provider +// rate limits). Declared before '/:proposalId' so "bulk" is not read as an id. +router.post('/bulk', requireAuth, async (req: Request, res: Response) => { + const raw: unknown = req.body?.ids; + const ids = Array.isArray(raw) + ? [...new Set(raw.filter((id): id is string => typeof id === 'string' && id.length > 0))] + : []; - if (insertError) throw insertError; - riskReport = data; - } + if (ids.length === 0) { + return res.status(400).json({ error: 'Provide a non-empty "ids" array of proposal ids' }); + } + if (ids.length > MAX_BULK_ANALYSIS) { + return res.status(400).json({ error: `At most ${MAX_BULK_ANALYSIS} proposals can be analyzed per request` }); + } - // Update proposal with readiness score and status - const updateData: { readinessScore: number; updatedAt: string; status?: string } = { - readinessScore: analysis.readinessScore, - updatedAt: new Date().toISOString(), - }; + const results = []; + for (const id of ids) { + const result = await analyzeForRequest(id, req); + results.push( + result.ok + ? { + proposalId: id, + ok: true, + analysisSource: result.outcome.analysisSource, + readinessScore: result.outcome.riskReport.readinessScore, + statusAdvanced: result.outcome.statusAdvanced, + } + : { proposalId: id, ok: false, error: result.error } + ); + } - // Auto-advance to review once the proposal is healthy enough. - if (shouldAutoReview(analysis.readinessScore)) { - updateData.status = 'IN_REVIEW'; - } - - await supabase - .from('Proposal') - .update(updateData) - .eq('id', proposalId); + const analyzed = results.filter((r) => r.ok).length; + res.json({ results, summary: { requested: ids.length, analyzed, failed: ids.length - analyzed } }); +}); - res.json({ - proposalId, - riskReport: { - id: riskReport.id, - readinessScore: riskReport.readinessScore, - legalRisk: riskReport.legalRisk, - pricingRisk: riskReport.pricingRisk, - structuralRisk: riskReport.structuralRisk, - findings: riskReport.findings, - recommendations: riskReport.recommendations, - }, - }); - } catch (error) { - console.error('Error analyzing proposal:', error); - res.status(500).json({ error: 'Failed to analyze proposal' }); +// Analyze a proposal (admin or same company only) +router.post('/:proposalId', requireAuth, async (req: Request, res: Response) => { + const result = await analyzeForRequest(String(req.params.proposalId), req); + if (!result.ok) { + return res.status(result.status).json({ error: result.error }); } + res.json(formatOutcome(result.outcome)); }); export default router; diff --git a/src/api/lib/analysisService.ts b/src/api/lib/analysisService.ts new file mode 100644 index 0000000..b79505f --- /dev/null +++ b/src/api/lib/analysisService.ts @@ -0,0 +1,254 @@ +/** + * Proposal analysis: prompt construction, the AI call, the deterministic + * fallback, and persisting the resulting RiskReport. + * + * The router (analyze.ts) owns HTTP concerns โ€” auth, access checks, status codes. + * Everything here is reusable by both the single and bulk endpoints. + */ + +import { supabase } from '../../lib/supabase'; +import { normalizeAnalysis, shouldAutoReview, type NormalizedAnalysis } from './compliance'; +import { getLlm } from './llm'; +import { logger } from './logger'; +import { analyzeByRules } from './ruleAnalysis'; + +/** How much of the document is sent to the model. */ +export const ANALYSIS_MAX_CONTENT_CHARS = 4000; + +/** Give up on a slow provider and use the rule checker instead. */ +const AI_TIMEOUT_MS = 45_000; + +export type AnalysisSource = 'ai' | 'rules'; + +export interface ProposalForAnalysis { + id: string; + title: string; + content: string; + status?: string; + metadata?: Record | null; +} + +export interface RuleRow { + name: string; + description: string; + logic?: unknown; +} + +export interface RiskReportRow { + id: string; + readinessScore: number; + legalRisk: number; + pricingRisk: number; + structuralRisk: number; + findings: unknown[]; + recommendations: unknown[]; +} + +export function buildAnalysisPrompt(proposal: ProposalForAnalysis, rules: RuleRow[]): string { + const rulesText = rules.map((r) => `- ${r.name}: ${r.description}`).join('\n'); + const metadata = proposal.metadata ?? {}; + + // Metadata is optional; the AI must extract/verify the numbers from the document. + const metadataDiscount = metadata.discount != null ? Number(metadata.discount) : null; + const metadataDealSize = metadata.dealSize != null ? Number(metadata.dealSize) : null; + const hasMetadataDiscount = metadataDiscount !== null && !Number.isNaN(metadataDiscount); + const hasMetadataDealSize = metadataDealSize !== null && !Number.isNaN(metadataDealSize); + + return `You are a proposal review assistant. Analyze the following proposal against the compliance rules and provide a risk assessment. + +## Proposal Details (from form โ€“ optional; verify against document) +Title: ${proposal.title} +Client: ${metadata.clientName || 'Unknown'} +Deal Size (form): ${hasMetadataDealSize ? `$${metadataDealSize}` : 'Not provided โ€“ extract from document'} +Discount % (form): ${hasMetadataDiscount ? `${metadataDiscount}%` : 'Not provided โ€“ extract from document'} +Region: ${metadata.region || 'Unknown'} +Industry: ${metadata.industry || 'Unknown'} + +## Proposal Content (source of truth for numbers) +${proposal.content.substring(0, ANALYSIS_MAX_CONTENT_CHARS)} + +## Compliance Rules +${rulesText || 'No specific rules defined'} + +## Critical Analysis Requirements + +### Discount Analysis (IMPORTANT): +- FIRST: Extract the actual discount from the proposal content (look for percentages, "discount", "off", "reduction", etc.). +- If the document states a discount, use that value for compliance. If the form provided a value that differs from the document, prefer the document. +- If no discount is found in the document, you may use the form value if provided. +- Maximum allowed discount threshold: 25% +- If discount is ABOVE 25%, flag as CRITICAL with "DISCOUNT VIOLATION" +- If discount is 25% or BELOW, do NOT flag any discount issues + +### Pricing Risk Calculation: +Calculate pricing risk based on the discount you determined (from document first): +- 0-10% discount = 10-15% pricing risk (LOW) +- 11-15% discount = 25-35% pricing risk (MEDIUM) +- 16-20% discount = 40-50% pricing risk (MEDIUM-HIGH) +- 21-25% discount = 60-70% pricing risk (HIGH - near limit) +- 26%+ discount = 90-100% pricing risk (CRITICAL - VIOLATION) + +### Deal Size Analysis: +- FIRST: Extract deal size / contract value from the proposal content if present. +- If the document states an amount, use that for compliance. If the form value differs, prefer the document. +- Minimum deal size: $10,000 +- If below minimum, flag as CRITICAL violation +- Assess if appropriate approvals are in place for this amount + +### Content Analysis: +- Check for required legal clauses: indemnification, liability limitation, termination rights +- Verify payment terms don't exceed 90 days +- Check for proper contract structure + +## Instructions +Analyze this proposal carefully using the ACTUAL values provided above and respond: +1. A readiness score (0-100) - higher if compliant +2. Legal risk percentage (0-100) - based on missing clauses +3. Pricing risk percentage (0-100) - based on discount vs threshold +4. Structural risk percentage (0-100) - based on content structure +5. List of findings (ONLY flag issues that actually exist based on the data) +6. List of recommendations (specific to the actual issues found) + +IMPORTANT: Base your analysis on the discount and deal size you extract from the proposal content. If the form provided values that conflict with the document, use the document values for compliance and risk. + +Respond in JSON format: +{ + "readinessScore": number, + "legalRisk": number, + "pricingRisk": number, + "structuralRisk": number, + "findings": [ + { "type": "string", "level": "CRITICAL|HIGH|MEDIUM|LOW", "message": "string", "location": "string" } + ], + "recommendations": [ + { "paragraphId": "string", "suggestion": "string", "reason": "string" } + ] +}`; +} + +/** Ask the configured model. Throws on any failure (network, quota, bad JSON). */ +async function analyzeWithAi(proposal: ProposalForAnalysis, rules: RuleRow[]): Promise { + const llm = getLlm(); + if (!llm) throw new Error('No AI provider configured'); + + const completion = await llm.client.chat.completions.create( + { + model: llm.model, + messages: [ + { role: 'system', content: 'You are a proposal compliance analyst. Respond only with valid JSON.' }, + { role: 'user', content: buildAnalysisPrompt(proposal, rules) }, + ], + temperature: 0.3, + max_tokens: 4000, + response_format: { type: 'json_object' }, + ...llm.extraParams, + }, + { timeout: AI_TIMEOUT_MS, maxRetries: 1 } + ); + + const responseContent = completion.choices[0]?.message?.content; + if (!responseContent) throw new Error('No response from AI'); + return normalizeAnalysis(JSON.parse(responseContent)); +} + +/** + * Analyze a proposal. Uses the AI when it is configured and answers; otherwise + * (or with ANALYSIS_MODE=rules) uses the deterministic rule checker so the + * workflow never dead-ends on an AI outage. + */ +export async function analyzeProposal( + proposal: ProposalForAnalysis, + rules: RuleRow[] +): Promise<{ analysis: NormalizedAnalysis; source: AnalysisSource }> { + if (process.env.ANALYSIS_MODE !== 'rules' && getLlm()) { + try { + return { analysis: await analyzeWithAi(proposal, rules), source: 'ai' }; + } catch (err) { + logger.warn( + `AI analysis failed for proposal ${proposal.id}; using the rule checker instead:`, + (err as Error).message + ); + } + } + + const { extracted: _extracted, ...analysis } = analyzeByRules({ + title: proposal.title, + content: proposal.content, + metadata: proposal.metadata, + rules, + }); + return { analysis, source: 'rules' }; +} + +/** Active compliance rules, or an empty list if the lookup fails. */ +export async function loadActiveRules(): Promise { + const { data, error } = await supabase.from('Rule').select('*').eq('isActive', true); + if (error) { + logger.warn('Could not load compliance rules:', error.message); + return []; + } + return (data || []) as RuleRow[]; +} + +/** Insert or update the proposal's single RiskReport. */ +export async function saveRiskReport(proposalId: string, analysis: NormalizedAnalysis): Promise { + const fields = { + readinessScore: analysis.readinessScore, + legalRisk: analysis.legalRisk, + pricingRisk: analysis.pricingRisk, + structuralRisk: analysis.structuralRisk, + findings: analysis.findings, + recommendations: analysis.recommendations, + }; + + // limit(1) rather than single(): single() errors when duplicate reports exist, + // which would then insert yet another one. + const { data: existing } = await supabase.from('RiskReport').select('id').eq('proposalId', proposalId).limit(1); + const existingId = (existing as Array<{ id: string }> | null)?.[0]?.id; + + const query = existingId + ? supabase.from('RiskReport').update(fields).eq('id', existingId) + : supabase.from('RiskReport').insert({ id: crypto.randomUUID(), proposalId, ...fields }); + + const { data, error } = await query.select().single(); + if (error) throw error; + return data as RiskReportRow; +} + +/** + * Touch the proposal after analysis and advance PENDING -> IN_REVIEW when it is + * healthy enough. Never moves an already-reviewed proposal (APPROVED/REJECTED/ + * IN_REVIEW) backwards. Returns whether the status advanced. + */ +export async function recordAnalysisOnProposal( + proposal: Pick, + readinessScore: number +): Promise { + const update: { updatedAt: string; status?: string } = { updatedAt: new Date().toISOString() }; + const advance = proposal.status === 'PENDING' && shouldAutoReview(readinessScore); + if (advance) update.status = 'IN_REVIEW'; + + const { error } = await supabase.from('Proposal').update(update).eq('id', proposal.id); + if (error) { + // The report itself is already saved; don't fail the request over bookkeeping. + logger.warn(`Could not update proposal ${proposal.id} after analysis:`, error.message); + return false; + } + return advance; +} + +export interface AnalysisOutcome { + proposalId: string; + riskReport: RiskReportRow; + analysisSource: AnalysisSource; + statusAdvanced: boolean; +} + +/** Analyze, persist, and update the proposal. The full single-proposal workflow. */ +export async function analyzeAndSave(proposal: ProposalForAnalysis): Promise { + const rules = await loadActiveRules(); + const { analysis, source } = await analyzeProposal(proposal, rules); + const riskReport = await saveRiskReport(proposal.id, analysis); + const statusAdvanced = await recordAnalysisOnProposal(proposal, riskReport.readinessScore); + return { proposalId: proposal.id, riskReport, analysisSource: source, statusAdvanced }; +} diff --git a/src/api/lib/compliance.test.ts b/src/api/lib/compliance.test.ts index c6b725e..5b02d59 100644 --- a/src/api/lib/compliance.test.ts +++ b/src/api/lib/compliance.test.ts @@ -65,11 +65,46 @@ describe('normalizeAnalysis', () => { expect(result.recommendations).toHaveLength(1); }); - it('falls back to defaults when a score is zero/falsy (documented behaviour)', () => { - // 0 is falsy so it defaults โ€” this mirrors the original `x || default` logic. - const result = normalizeAnalysis({ readinessScore: 0, legalRisk: 0 }); + it('keeps a genuine zero score instead of replacing it with a default', () => { + const result = normalizeAnalysis({ readinessScore: 0, legalRisk: 0, pricingRisk: 0, structuralRisk: 0 }); + expect(result.readinessScore).toBe(0); + expect(result.legalRisk).toBe(0); + expect(result.pricingRisk).toBe(0); + expect(result.structuralRisk).toBe(0); + }); + + it('falls back to defaults for missing or non-numeric scores', () => { + const result = normalizeAnalysis({ + readinessScore: 'high' as unknown as number, + legalRisk: null as unknown as number, + pricingRisk: NaN, + }); expect(result.readinessScore).toBe(50); expect(result.legalRisk).toBe(20); + expect(result.pricingRisk).toBe(20); + expect(result.structuralRisk).toBe(20); + }); + + it('accepts numeric strings and clamps scores to 0-100', () => { + const result = normalizeAnalysis({ + readinessScore: '85' as unknown as number, + legalRisk: 140, + pricingRisk: -5, + structuralRisk: 33.6, + }); + expect(result.readinessScore).toBe(85); + expect(result.legalRisk).toBe(100); + expect(result.pricingRisk).toBe(0); + expect(result.structuralRisk).toBe(34); + }); + + it('ignores findings/recommendations that are not arrays', () => { + const result = normalizeAnalysis({ + findings: { oops: true } as unknown as unknown[], + recommendations: 'none' as unknown as unknown[], + }); + expect(result.findings).toEqual([]); + expect(result.recommendations).toEqual([]); }); }); diff --git a/src/api/lib/compliance.ts b/src/api/lib/compliance.ts index 0eb1dba..62e157e 100644 --- a/src/api/lib/compliance.ts +++ b/src/api/lib/compliance.ts @@ -48,20 +48,28 @@ export interface NormalizedAnalysis { recommendations: unknown[]; } +/** A 0-100 score from a possibly-garbled value; `fallback` when it isn't a number. */ +function toScore(value: unknown, fallback: number): number { + const n = typeof value === 'string' ? Number(value) : value; + if (typeof n !== 'number' || !Number.isFinite(n)) return fallback; + return Math.min(100, Math.max(0, Math.round(n))); +} + /** * Apply safe defaults to a raw AI analysis object so a partial/garbled LLM - * response never persists null/undefined scores. Mirrors the historical - * `analysis.x || default` behaviour in one place. + * response never persists null/undefined scores. A real 0 is kept (a proposal + * can legitimately score 0 readiness or carry 0% risk); only missing, + * non-numeric values fall back to a default. Scores are clamped to 0-100. */ export function normalizeAnalysis(raw: RawAnalysis | null | undefined): NormalizedAnalysis { const a = raw ?? {}; return { - readinessScore: a.readinessScore || 50, - legalRisk: a.legalRisk || 20, - pricingRisk: a.pricingRisk || 20, - structuralRisk: a.structuralRisk || 20, - findings: a.findings || [], - recommendations: a.recommendations || [], + readinessScore: toScore(a.readinessScore, 50), + legalRisk: toScore(a.legalRisk, 20), + pricingRisk: toScore(a.pricingRisk, 20), + structuralRisk: toScore(a.structuralRisk, 20), + findings: Array.isArray(a.findings) ? a.findings : [], + recommendations: Array.isArray(a.recommendations) ? a.recommendations : [], }; } diff --git a/src/api/lib/embeddings.test.ts b/src/api/lib/embeddings.test.ts new file mode 100644 index 0000000..339de18 --- /dev/null +++ b/src/api/lib/embeddings.test.ts @@ -0,0 +1,132 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +const { create, openAiCtor, azureCtor } = vi.hoisted(() => ({ + create: vi.fn(), + openAiCtor: vi.fn(), + azureCtor: vi.fn(), +})); + +vi.mock('openai', () => { + class OpenAI { + embeddings = { create }; + constructor(opts: unknown) { + openAiCtor(opts); + } + } + class AzureOpenAI { + embeddings = { create }; + constructor(opts: unknown) { + azureCtor(opts); + } + } + return { default: OpenAI, AzureOpenAI }; +}); + +import { EMBEDDING_DIM, generateEmbedding, l2Normalize } from './embeddings'; + +const vectorOf = (value: number, length = EMBEDDING_DIM) => Array.from({ length }, () => value); +const ENV_KEYS = ['GEMINI_API_KEY', 'GEMINI_EMBEDDING_MODEL', 'AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] as const; + +let saved: Record; + +beforeEach(() => { + saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + for (const k of ENV_KEYS) delete process.env[k]; + create.mockReset(); + openAiCtor.mockReset(); + azureCtor.mockReset(); +}); + +afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } +}); + +describe('l2Normalize', () => { + it('scales a vector to unit length', () => { + const out = l2Normalize([3, 4]); + expect(out[0]).toBeCloseTo(0.6); + expect(out[1]).toBeCloseTo(0.8); + }); + + it('leaves the zero vector alone instead of dividing by zero', () => { + expect(l2Normalize([0, 0, 0])).toEqual([0, 0, 0]); + }); +}); + +describe('generateEmbedding', () => { + it('returns null without calling the provider for blank input', async () => { + expect(await generateEmbedding(' ')).toBeNull(); + expect(create).not.toHaveBeenCalled(); + }); + + it('uses Gemini at the column width when GEMINI_API_KEY is set', async () => { + process.env.GEMINI_API_KEY = 'gem-key-1'; + create.mockResolvedValue({ data: [{ embedding: vectorOf(2) }] }); + + const out = await generateEmbedding('payment terms'); + + expect(openAiCtor).toHaveBeenCalledWith( + expect.objectContaining({ apiKey: 'gem-key-1', baseURL: expect.stringContaining('generativelanguage') }) + ); + expect(azureCtor).not.toHaveBeenCalled(); + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + model: 'gemini-embedding-001', + input: 'payment terms', + dimensions: EMBEDDING_DIM, + }) + ); + // Returned vector is unit length. + expect(out).not.toBeNull(); + const norm = Math.sqrt(out!.reduce((s, x) => s + x * x, 0)); + expect(norm).toBeCloseTo(1); + }); + + it('honours GEMINI_EMBEDDING_MODEL', async () => { + process.env.GEMINI_API_KEY = 'gem-key-2'; + process.env.GEMINI_EMBEDDING_MODEL = 'gemini-embedding-custom'; + create.mockResolvedValue({ data: [{ embedding: vectorOf(1) }] }); + + await generateEmbedding('hello'); + + expect(create).toHaveBeenCalledWith(expect.objectContaining({ model: 'gemini-embedding-custom' })); + }); + + it('falls back to the Azure deployment (no dimensions param) without a Gemini key', async () => { + process.env.AZURE_OPENAI_EMBEDDING_DEPLOYMENT = 'my-ada'; + create.mockResolvedValue({ data: [{ embedding: vectorOf(1) }] }); + + await generateEmbedding('hello'); + + expect(azureCtor).toHaveBeenCalled(); + const params = create.mock.calls[0][0]; + expect(params.model).toBe('my-ada'); + expect(params).not.toHaveProperty('dimensions'); + }); + + it('rejects a vector whose width does not match the pgvector column', async () => { + process.env.GEMINI_API_KEY = 'gem-key-3'; + create.mockResolvedValue({ data: [{ embedding: vectorOf(1, 768) }] }); + + expect(await generateEmbedding('hello')).toBeNull(); + }); + + it('truncates very long input before sending it', async () => { + process.env.GEMINI_API_KEY = 'gem-key-4'; + create.mockResolvedValue({ data: [{ embedding: vectorOf(1) }] }); + + await generateEmbedding('x'.repeat(20_000)); + + expect(create.mock.calls[0][0].input).toHaveLength(8000); + }); + + it('returns null instead of throwing when the provider fails', async () => { + process.env.GEMINI_API_KEY = 'gem-key-5'; + create.mockRejectedValue(new Error('429 quota')); + + await expect(generateEmbedding('hello')).resolves.toBeNull(); + }); +}); diff --git a/src/api/lib/embeddings.ts b/src/api/lib/embeddings.ts index d100edf..fa9c01e 100644 --- a/src/api/lib/embeddings.ts +++ b/src/api/lib/embeddings.ts @@ -1,32 +1,70 @@ /** - * Azure OpenAI embedding generation for semantic search (Phase 4). + * Embedding generation for semantic search (Phase 4). + * + * Provider: Google Gemini (`gemini-embedding-001`, through its OpenAI-compatible + * endpoint) when GEMINI_API_KEY is set, otherwise Azure OpenAI. Either way the + * vector is EMBEDDING_DIM wide to match the pgvector column. * * Returns null on any failure so callers can degrade gracefully โ€” semantic * search is an enhancement layered on top of the existing substring filter, and * proposal create/update must never fail just because embedding did. * - * Requires AZURE_OPENAI_EMBEDDING_DEPLOYMENT and the pgvector column/migration - * (see docs/SEMANTIC_SEARCH.md). text-embedding-ada-002 produces 1536-dim vectors. + * Every instance that shares a database must use the same embedding model: + * vectors from different models are not comparable. After switching provider, + * re-embed everything with `npm run backfill:embeddings -- --all`. + * See docs/SEMANTIC_SEARCH.md. */ -import { AzureOpenAI } from 'openai'; +import OpenAI, { AzureOpenAI } from 'openai'; +import { GEMINI_BASE_URL } from './gemini'; import { logger } from './logger'; export const EMBEDDING_DIM = 1536; const MAX_CHARS = 8000; -const deployment = process.env.AZURE_OPENAI_EMBEDDING_DEPLOYMENT || 'text-embedding-ada-002'; +interface EmbeddingProvider { + client: OpenAI; + model: string; + /** Gemini models can emit several widths; ask for the column's width. */ + dimensions?: number; +} -let client: AzureOpenAI | null = null; -function getClient(): AzureOpenAI { - if (!client) { - client = new AzureOpenAI({ - endpoint: process.env.AZURE_OPENAI_ENDPOINT, - apiKey: process.env.OPENAI_API_KEY, - apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview', - }); - } - return client; +let provider: EmbeddingProvider | null = null; +let providerKey = ''; + +/** Resolve (and cache) the embedding client for the current environment. */ +function getProvider(): EmbeddingProvider { + const geminiKey = process.env.GEMINI_API_KEY; + const key = geminiKey ? `gemini:${geminiKey}` : 'azure'; + if (provider && providerKey === key) return provider; + + provider = geminiKey + ? { + client: new OpenAI({ apiKey: geminiKey, baseURL: GEMINI_BASE_URL }), + model: process.env.GEMINI_EMBEDDING_MODEL || 'gemini-embedding-001', + dimensions: EMBEDDING_DIM, + } + : { + client: new AzureOpenAI({ + endpoint: process.env.AZURE_OPENAI_ENDPOINT, + apiKey: process.env.OPENAI_API_KEY, + apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview', + }), + model: process.env.AZURE_OPENAI_EMBEDDING_DEPLOYMENT || 'text-embedding-ada-002', + }; + providerKey = key; + return provider; +} + +/** + * Scale a vector to unit length. Gemini returns un-normalised vectors when asked + * for fewer than its native 3072 dimensions; cosine distance ignores magnitude, + * but unit vectors keep similarity scores comparable and the index well-behaved. + */ +export function l2Normalize(vector: number[]): number[] { + const norm = Math.sqrt(vector.reduce((sum, x) => sum + x * x, 0)); + if (!norm) return vector; + return vector.map((x) => x / norm); } /** Embed a single string. Returns the vector, or null on failure. */ @@ -34,8 +72,22 @@ export async function generateEmbedding(text: string): Promise const input = (text || '').trim().slice(0, MAX_CHARS); if (!input) return null; try { - const res = await getClient().embeddings.create({ model: deployment, input }); - return res.data[0]?.embedding ?? null; + const { client, model, dimensions } = getProvider(); + const res = await client.embeddings.create({ + model, + input, + ...(dimensions ? { dimensions } : {}), + }); + const embedding = res.data[0]?.embedding; + if (!embedding) return null; + if (embedding.length !== EMBEDDING_DIM) { + logger.error( + `[embeddings] expected ${EMBEDDING_DIM} dimensions, got ${embedding.length}; ` + + 'the pgvector column width and the embedding model must match' + ); + return null; + } + return l2Normalize(embedding); } catch (err) { logger.error('[embeddings] generation failed', err); return null; diff --git a/src/api/lib/gemini.ts b/src/api/lib/gemini.ts new file mode 100644 index 0000000..f76fcc4 --- /dev/null +++ b/src/api/lib/gemini.ts @@ -0,0 +1,2 @@ +/** Gemini's OpenAI-compatible endpoint, shared by the chat and embedding clients. */ +export const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta/openai/'; diff --git a/src/api/lib/llm.test.ts b/src/api/lib/llm.test.ts new file mode 100644 index 0000000..308782a --- /dev/null +++ b/src/api/lib/llm.test.ts @@ -0,0 +1,129 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +const { openAiCtor, azureCtor } = vi.hoisted(() => ({ openAiCtor: vi.fn(), azureCtor: vi.fn() })); + +vi.mock('openai', () => { + class OpenAI { + kind = 'gemini-client'; + constructor(opts: unknown) { + openAiCtor(opts); + } + } + class AzureOpenAI { + kind = 'azure-client'; + constructor(opts: unknown) { + azureCtor(opts); + } + } + return { default: OpenAI, AzureOpenAI }; +}); + +import { getLlm, isLlmConfigured } from './llm'; + +const ENV_KEYS = [ + 'GEMINI_API_KEY', + 'GEMINI_MODEL', + 'AZURE_OPENAI_ENDPOINT', + 'OPENAI_API_KEY', + 'AZURE_OPENAI_DEPLOYMENT', + 'AZURE_OPENAI_API_VERSION', +] as const; +let saved: Record; + +beforeEach(() => { + saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + for (const k of ENV_KEYS) delete process.env[k]; + openAiCtor.mockClear(); + azureCtor.mockClear(); +}); + +afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } +}); + +describe('getLlm', () => { + it('is null โ€” not a crash โ€” when nothing is configured', () => { + expect(getLlm()).toBeNull(); + expect(isLlmConfigured()).toBe(false); + expect(openAiCtor).not.toHaveBeenCalled(); + expect(azureCtor).not.toHaveBeenCalled(); + }); + + it('uses Gemini through its OpenAI-compatible endpoint, with thinking off', () => { + process.env.GEMINI_API_KEY = 'gem-1'; + + const llm = getLlm(); + + expect(llm).toMatchObject({ + provider: 'gemini', + model: 'gemini-2.5-flash', + extraParams: { reasoning_effort: 'none' }, + }); + expect(openAiCtor).toHaveBeenCalledWith( + expect.objectContaining({ apiKey: 'gem-1', baseURL: expect.stringContaining('generativelanguage.googleapis.com') }) + ); + expect(isLlmConfigured()).toBe(true); + }); + + it('honours GEMINI_MODEL', () => { + process.env.GEMINI_API_KEY = 'gem-2'; + process.env.GEMINI_MODEL = 'gemini-custom'; + expect(getLlm()?.model).toBe('gemini-custom'); + }); + + it('falls back to Azure OpenAI when only its endpoint and key are set', () => { + process.env.AZURE_OPENAI_ENDPOINT = 'https://res.openai.azure.com/'; + process.env.OPENAI_API_KEY = 'az-key'; + + const llm = getLlm(); + + expect(llm).toMatchObject({ provider: 'azure', model: 'gpt-4o', extraParams: {} }); + expect(azureCtor).toHaveBeenCalledWith( + expect.objectContaining({ endpoint: 'https://res.openai.azure.com/', apiKey: 'az-key', apiVersion: '2024-12-01-preview' }) + ); + }); + + it('honours the Azure deployment and API version', () => { + process.env.AZURE_OPENAI_ENDPOINT = 'https://res2.openai.azure.com/'; + process.env.OPENAI_API_KEY = 'az-key-2'; + process.env.AZURE_OPENAI_DEPLOYMENT = 'my-deployment'; + process.env.AZURE_OPENAI_API_VERSION = '2025-01-01'; + + expect(getLlm()?.model).toBe('my-deployment'); + expect(azureCtor).toHaveBeenCalledWith(expect.objectContaining({ apiVersion: '2025-01-01' })); + }); + + it('needs both Azure settings: either one alone is "not configured"', () => { + process.env.AZURE_OPENAI_ENDPOINT = 'https://only-endpoint.openai.azure.com/'; + expect(getLlm()).toBeNull(); + + delete process.env.AZURE_OPENAI_ENDPOINT; + process.env.OPENAI_API_KEY = 'only-key'; + expect(getLlm()).toBeNull(); + }); + + it('prefers Gemini when both providers are configured', () => { + process.env.GEMINI_API_KEY = 'gem-3'; + process.env.AZURE_OPENAI_ENDPOINT = 'https://res3.openai.azure.com/'; + process.env.OPENAI_API_KEY = 'az-key-3'; + + expect(getLlm()?.provider).toBe('gemini'); + expect(azureCtor).not.toHaveBeenCalled(); + }); + + it('reuses the client while the environment is unchanged, and rebuilds when it changes', () => { + process.env.GEMINI_API_KEY = 'gem-4'; + const first = getLlm(); + const again = getLlm(); + expect(again).toBe(first); + expect(openAiCtor).toHaveBeenCalledTimes(1); + + process.env.GEMINI_API_KEY = 'gem-5'; + const rebuilt = getLlm(); + expect(rebuilt).not.toBe(first); + expect(openAiCtor).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/api/lib/llm.ts b/src/api/lib/llm.ts index 3e27a4b..78e75db 100644 --- a/src/api/lib/llm.ts +++ b/src/api/lib/llm.ts @@ -2,29 +2,66 @@ * Chat-completion client shared by the analysis and generation routes. * * Uses Google Gemini (via its OpenAI-compatible endpoint) when GEMINI_API_KEY - * is set, otherwise Azure OpenAI. Both speak the same chat.completions API. + * is set, otherwise Azure OpenAI when its endpoint and key are set. Both speak + * the same chat.completions API. + * + * Resolved lazily so the server still boots with no AI configured: callers get + * `null` from getLlm() and degrade (analysis falls back to the rule checker, + * generation reports 503) instead of the process crashing at import time. */ import OpenAI, { AzureOpenAI } from 'openai'; +import { GEMINI_BASE_URL } from './gemini'; -const geminiKey = process.env.GEMINI_API_KEY; +export interface Llm { + provider: 'gemini' | 'azure'; + client: OpenAI; + model: string; + /** + * Extra completion params. Gemini 2.5 "thinks" by default and those tokens + * count against max_tokens, truncating the JSON answer; turn thinking off. + */ + extraParams: Record; +} -export const llmClient: OpenAI = geminiKey - ? new OpenAI({ - apiKey: geminiKey, - baseURL: 'https://generativelanguage.googleapis.com/v1beta/openai/', - }) - : new AzureOpenAI({ - endpoint: process.env.AZURE_OPENAI_ENDPOINT, - apiKey: process.env.OPENAI_API_KEY, - apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview', - }); +let cached: { key: string; llm: Llm | null } | null = null; -/** - * Extra completion params. Gemini 2.5 "thinks" by default and those tokens count - * against max_tokens, truncating the JSON answer; turn thinking off. - */ -export const llmExtraParams = geminiKey ? ({ reasoning_effort: 'none' } as Record) : {}; +/** The configured LLM, or null when neither Gemini nor Azure OpenAI is set up. */ +export function getLlm(): Llm | null { + const geminiKey = process.env.GEMINI_API_KEY; + const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT; + const azureKey = process.env.OPENAI_API_KEY; + + const key = geminiKey + ? `gemini:${geminiKey}:${process.env.GEMINI_MODEL ?? ''}` + : `azure:${azureEndpoint ?? ''}:${azureKey ?? ''}:${process.env.AZURE_OPENAI_DEPLOYMENT ?? ''}`; + if (cached && cached.key === key) return cached.llm; + + let llm: Llm | null = null; + if (geminiKey) { + llm = { + provider: 'gemini', + client: new OpenAI({ apiKey: geminiKey, baseURL: GEMINI_BASE_URL }), + model: process.env.GEMINI_MODEL || 'gemini-2.5-flash', + extraParams: { reasoning_effort: 'none' }, + }; + } else if (azureEndpoint && azureKey) { + llm = { + provider: 'azure', + client: new AzureOpenAI({ + endpoint: azureEndpoint, + apiKey: azureKey, + apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview', + }), + model: process.env.AZURE_OPENAI_DEPLOYMENT || 'gpt-4o', + extraParams: {}, + }; + } + + cached = { key, llm }; + return llm; +} -export const llmModel: string = geminiKey - ? process.env.GEMINI_MODEL || 'gemini-2.5-flash' - : process.env.AZURE_OPENAI_DEPLOYMENT || 'gpt-4o'; +/** True when an LLM provider is configured (it may still be unreachable). */ +export function isLlmConfigured(): boolean { + return getLlm() !== null; +} diff --git a/src/api/lib/proposalGeneration.test.ts b/src/api/lib/proposalGeneration.test.ts new file mode 100644 index 0000000..2229ff9 --- /dev/null +++ b/src/api/lib/proposalGeneration.test.ts @@ -0,0 +1,105 @@ +import { describe, it, expect } from 'vitest'; +import { + GENERATION_SYSTEM_PROMPT, + buildGenerationPrompt, + clampDiscount, + normalizeGenerated, +} from './proposalGeneration'; + +describe('clampDiscount', () => { + it('passes through values inside 0-25', () => { + expect(clampDiscount(0)).toBe(0); + expect(clampDiscount(12.5)).toBe(12.5); + expect(clampDiscount(25)).toBe(25); + }); + + it('caps anything above the maximum and floors negatives', () => { + expect(clampDiscount(26)).toBe(25); + expect(clampDiscount(500)).toBe(25); + expect(clampDiscount(-10)).toBe(0); + }); + + it('accepts numeric strings', () => { + expect(clampDiscount('15')).toBe(15); + expect(clampDiscount('40')).toBe(25); + }); + + it('treats missing or non-numeric input as no discount (never NaN)', () => { + for (const bad of [undefined, null, '', 'lots', NaN, Infinity, {}]) { + expect(clampDiscount(bad)).toBe(0); + } + }); +}); + +describe('normalizeGenerated', () => { + const valid = { + companyName: 'Acme', + title: 'Acme Proposal', + content: '## Summary\nText', + metadata: { clientName: 'Acme Ltd', dealSize: 60000, discount: 10, region: 'APAC', currency: 'AUD', industry: 'Mining' }, + }; + + it('returns a fully-populated proposal for good input', () => { + expect(normalizeGenerated(valid)).toEqual({ + title: 'Acme Proposal', + content: '## Summary\nText', + metadata: { clientName: 'Acme Ltd', dealSize: 60000, discount: 10, region: 'APAC', currency: 'AUD', industry: 'Mining' }, + }); + }); + + it('fills defaults when optional metadata is missing', () => { + const out = normalizeGenerated({ companyName: 'Acme', title: 'T', content: 'C' }); + expect(out?.metadata).toEqual({ + clientName: 'Acme', + dealSize: null, + discount: 0, + region: 'North America', + currency: 'USD', + industry: 'General', + }); + }); + + it('clamps the discount and sanitises the deal size', () => { + const out = normalizeGenerated({ ...valid, metadata: { discount: 80, dealSize: -5 } }); + expect(out?.metadata.discount).toBe(25); + expect(out?.metadata.dealSize).toBeNull(); + }); + + it('trims text fields', () => { + expect(normalizeGenerated({ ...valid, title: ' Padded ' })?.title).toBe('Padded'); + }); + + it('rejects an answer missing any required field', () => { + expect(normalizeGenerated({ ...valid, companyName: '' })).toBeNull(); + expect(normalizeGenerated({ ...valid, title: undefined })).toBeNull(); + expect(normalizeGenerated({ ...valid, content: ' ' })).toBeNull(); + }); + + it('rejects non-object answers', () => { + for (const bad of [null, undefined, 'text', 42, []]) { + expect(normalizeGenerated(bad as unknown)).toBeNull(); + } + }); + + it('ignores a metadata value that is not an object', () => { + const out = normalizeGenerated({ ...valid, metadata: 'oops' }); + expect(out?.metadata.discount).toBe(0); + }); +}); + +describe('prompts', () => { + it('embeds the user request and the compliance limits', () => { + const prompt = buildGenerationPrompt('A website for Globex, $30k'); + expect(prompt).toContain('A website for Globex, $30k'); + expect(prompt).toContain('MAXIMUM 90 days'); + expect(prompt).toContain('MAXIMUM 25% discount'); + expect(prompt).toContain('Indemnification'); + expect(prompt).toContain('Respond in JSON format'); + }); + + it('keeps the system prompt demanding JSON and the hard limits', () => { + expect(GENERATION_SYSTEM_PROMPT).toMatch(/valid JSON/); + expect(GENERATION_SYSTEM_PROMPT).toMatch(/90 days/); + expect(GENERATION_SYSTEM_PROMPT).toMatch(/25%/); + }); +}); diff --git a/src/api/lib/proposalGeneration.ts b/src/api/lib/proposalGeneration.ts new file mode 100644 index 0000000..1ab2cd7 --- /dev/null +++ b/src/api/lib/proposalGeneration.ts @@ -0,0 +1,153 @@ +/** + * Natural-language proposal generation: the prompt sent to the model and the + * deterministic clean-up applied to whatever comes back. + * + * The model is asked to respect the compliance limits, but its answer is never + * trusted: discount is clamped to the allowed range and numbers are validated + * here, in code, before anything is stored. + */ + +import { MAX_DISCOUNT_PERCENT } from './compliance'; + +export const GENERATION_SYSTEM_PROMPT = + 'You are a professional proposal writer with expertise in compliance and legal requirements. Generate complete, compliance-ready business proposals that include all required legal clauses and adhere to organizational policies. Always ensure proposals meet regulatory standards including payment terms limits (90 days max), discount thresholds (25% max), and required legal clauses (indemnification, liability limitation, termination rights, confidentiality, intellectual property). Respond only with valid JSON.'; + +/** The user prompt for a free-text request such as "proposal for Acme, $50k website redesign". */ +export function buildGenerationPrompt(naturalLanguageQuery: string): string { + return `You are a professional proposal generation assistant. Extract structured proposal information from the following natural language request and generate a COMPLETE, COMPLIANCE-READY business proposal. + +User Request: +${naturalLanguageQuery} + +## COMPLIANCE REQUIREMENTS (MUST FOLLOW): +1. **Payment Terms**: MAXIMUM 90 days allowed. If user specifies more, adjust to 90 days and note this in the proposal. +2. **Discount**: If no discount mentioned, set to 0%. MAXIMUM 25% discount allowed. +3. **Legal Clauses**: MUST include ALL of the following in Terms and Conditions: + - Indemnification clause + - Liability limitation clause + - Termination rights clause + - Confidentiality clause + - Intellectual property clause +4. **Minimum Deal Size**: $10,000 + +## Extract and generate: +1. Company name (required) +2. Proposal title (required) - create a professional title if not explicitly stated +3. Client name (if different from company name) +4. Deal size (if mentioned, extract as number without currency symbols) +5. Discount percentage (if mentioned, extract as number without % symbol, otherwise 0) +6. Region (if mentioned, otherwise "North America") +7. Currency (if mentioned, otherwise "USD") +8. Industry (if mentioned, otherwise "General") + +## Generate comprehensive proposal content with these sections: + +### 1. Executive Summary +Professional overview of the proposal and key value proposition. + +### 2. Proposed Solution +Detailed description of services, deliverables, and approach. + +### 3. Investment & Pricing +- Total project value +- Payment terms (MAXIMUM 90 days - adjust if user specified more) +- Any applicable discounts (0-25% range only) +- Payment schedule if applicable + +### 4. Timeline & Milestones +Project timeline with key milestones and deliverables. + +### 5. Terms & Conditions (CRITICAL - MUST INCLUDE ALL): +**Indemnification**: "Each party agrees to indemnify and hold harmless the other party from any claims, damages, or losses arising from their own negligence or breach of this agreement." + +**Liability Limitation**: "Neither party shall be liable for any indirect, incidental, special, or consequential damages. Total liability under this agreement shall not exceed the total contract value." + +**Termination Rights**: "Either party may terminate this agreement with 30 days written notice. Upon termination, client shall pay for all work completed to date." + +**Confidentiality**: "Both parties agree to maintain confidentiality of all proprietary information disclosed during this engagement." + +**Intellectual Property**: "Upon full payment, all deliverables and work product shall become the property of the client, subject to any pre-existing intellectual property rights." + +**Payment Terms**: "Payment is due within [X] days of invoice date, not exceeding 90 days." + +### 6. Acceptance & Next Steps +Clear process for proposal acceptance and project kickoff. + +Format the content with proper markdown headings (## and ###) for sections and subsections. + +Respond in JSON format: +{ + "companyName": "string (required)", + "title": "string (required)", + "content": "string (required - full proposal text with ALL sections above including complete Terms & Conditions)", + "metadata": { + "clientName": "string", + "dealSize": number or null, + "discount": number (0-25 range, default 0), + "region": "string", + "currency": "string", + "industry": "string" + } +}`; +} + +/** Fields a stored proposal needs, derived from the model's JSON answer. */ +export interface GeneratedProposal { + title: string; + content: string; + metadata: { + clientName: string; + dealSize: number | null; + discount: number; + region: string; + currency: string; + industry: string; + }; +} + +/** Clamp a discount to 0..MAX_DISCOUNT_PERCENT; anything non-numeric becomes 0. */ +export function clampDiscount(value: unknown): number { + if (value === null || value === undefined || value === '') return 0; + const n = Number(value); + if (!Number.isFinite(n)) return 0; + return Math.min(MAX_DISCOUNT_PERCENT, Math.max(0, n)); +} + +/** A finite, non-negative deal size, or null when the model gave none. */ +function toDealSize(value: unknown): number | null { + if (value === null || value === undefined || value === '') return null; + const n = Number(value); + return Number.isFinite(n) && n >= 0 ? n : null; +} + +const text = (value: unknown, fallback: string): string => + typeof value === 'string' && value.trim() ? value.trim() : fallback; + +/** + * Validate and normalise the model's JSON. Returns null when the required + * fields (company name, title, content) are missing so the caller can ask the + * user for more detail instead of storing an empty proposal. + */ +export function normalizeGenerated(raw: unknown): GeneratedProposal | null { + if (!raw || typeof raw !== 'object') return null; + const g = raw as Record; + const meta = (g.metadata && typeof g.metadata === 'object' ? g.metadata : {}) as Record; + + const companyName = text(g.companyName, ''); + const title = text(g.title, ''); + const content = text(g.content, ''); + if (!companyName || !title || !content) return null; + + return { + title, + content, + metadata: { + clientName: text(meta.clientName, companyName), + dealSize: toDealSize(meta.dealSize), + discount: clampDiscount(meta.discount), + region: text(meta.region, 'North America'), + currency: text(meta.currency, 'USD'), + industry: text(meta.industry, 'General'), + }, + }; +} diff --git a/src/api/lib/proposalPdf.test.ts b/src/api/lib/proposalPdf.test.ts new file mode 100644 index 0000000..f01ee72 --- /dev/null +++ b/src/api/lib/proposalPdf.test.ts @@ -0,0 +1,184 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +const { launchMock } = vi.hoisted(() => ({ launchMock: vi.fn() })); +vi.mock('puppeteer', () => ({ default: { launch: launchMock } })); + +import { buildProposalHtml, escapeHtml, renderPdf, type ProposalPdfInput } from './proposalPdf'; + +const input = (over: Partial = {}): ProposalPdfInput => ({ + id: 'abcdef12-3456-7890-abcd-ef1234567890', + title: 'Cloud Migration Proposal', + content: '## Scope\nMove **everything** to the cloud.\n- Assess\n- Migrate', + createdAt: '2026-03-15T10:00:00.000Z', + metadata: { clientName: 'Acme Corp', dealSize: 120000, discount: 10, region: 'EMEA', industry: 'Retail' }, + createdBy: 'Pat Seller', + riskReport: null, + rules: [], + ...over, +}); + +describe('escapeHtml', () => { + it('escapes the five HTML-significant characters', () => { + expect(escapeHtml(`&`)).toBe( + '<a href="x" onclick='y'>&</a>' + ); + }); + + it('renders null and undefined as empty, and stringifies numbers', () => { + expect(escapeHtml(null)).toBe(''); + expect(escapeHtml(undefined)).toBe(''); + expect(escapeHtml(42)).toBe('42'); + }); +}); + +describe('buildProposalHtml', () => { + it('produces a complete document with the proposal details on the cover page', () => { + const html = buildProposalHtml(input()); + expect(html).toContain(''); + expect(html).toContain('Cloud Migration Proposal'); + expect(html).toContain('Acme Corp'); + expect(html).toContain('Retail'); + expect(html).toContain('EMEA'); + expect(html).toContain('Pat Seller'); + expect(html).toContain('PRO-ABCDEF12'); + expect(html).toContain('March 15, 2026'); + }); + + it('formats the deal size and discount in the investment table', () => { + const html = buildProposalHtml(input()); + expect(html).toContain('$120,000'); + expect(html).toContain('10% discount applied'); + }); + + it('renders the proposal body as HTML', () => { + const html = buildProposalHtml(input()); + expect(html).toContain('

Scope

'); + expect(html).toContain('everything'); + expect(html).toContain('
  • Assess
  • '); + }); + + it('escapes user-controlled fields so a malicious title or client cannot inject markup', () => { + const html = buildProposalHtml( + input({ title: '', metadata: { clientName: '">' } }) + ); + expect(html).not.toContain(''); + expect(html).not.toContain(' { + expect(buildProposalHtml(input())).not.toContain('APPENDIX A'); + }); + + it('includes scores, review notes and policies when there is a risk report', () => { + const html = buildProposalHtml( + input({ + riskReport: { + readinessScore: 82, + legalRisk: 20, + pricingRisk: 10, + structuralRisk: 30, + findings: [{ message: 'Add an indemnification clause' }, { title: 'Pricing note' }, {}, { message: 'fourth, dropped' }], + }, + rules: [{ name: 'Max discount', description: 'No more than 25%' }], + }) + ); + expect(html).toContain('APPENDIX A'); + expect(html).toContain('82/100'); + expect(html).toContain('80/100'); // 100 - legalRisk + expect(html).toContain('Add an indemnification clause'); + expect(html).toContain('Pricing note'); + expect(html).toContain('Quality review note'); // fallback label for an empty finding + expect(html).not.toContain('fourth, dropped'); // only the first three notes + expect(html).toContain('Max discount'); + }); + + it('copes with missing metadata', () => { + const html = buildProposalHtml(input({ metadata: {} })); + expect(html).toContain('Client Name'); + expect(html).not.toContain('Investment Overview'); + }); + + it('keeps the list styles: no stray declarations between the table and list rules', () => { + const html = buildProposalHtml(input()); + // A leftover declaration block here made browsers discard the `ol, ul` rule. + expect(html).toMatch(/tr:nth-child\(even\)\s*\{[^}]*\}\s*ol, ul \{/); + }); +}); + +describe('renderPdf', () => { + const fakeBrowser = (opts: { pdfError?: Error } = {}) => { + const page = { + setContent: vi.fn().mockResolvedValue(undefined), + pdf: opts.pdfError ? vi.fn().mockRejectedValue(opts.pdfError) : vi.fn().mockResolvedValue(new Uint8Array([37, 80, 68, 70])), + }; + const browser = { newPage: vi.fn().mockResolvedValue(page), close: vi.fn().mockResolvedValue(undefined) }; + return { browser, page }; + }; + + beforeEach(() => { + launchMock.mockReset(); + }); + + it('launches memory-lean headless Chrome and returns the PDF bytes', async () => { + const { browser, page } = fakeBrowser(); + launchMock.mockResolvedValue(browser); + + const pdf = await renderPdf(''); + + expect(Buffer.isBuffer(pdf)).toBe(true); + expect(pdf.toString()).toBe('%PDF'); + const launchOpts = launchMock.mock.calls[0][0]; + expect(launchOpts.headless).toBe('new'); + expect(launchOpts.args).toEqual(expect.arrayContaining(['--no-sandbox', '--single-process'])); + expect(page.pdf).toHaveBeenCalledWith(expect.objectContaining({ format: 'A4', printBackground: true })); + expect(browser.close).toHaveBeenCalledTimes(1); + }); + + it('closes the browser even when rendering fails (no leaked Chrome)', async () => { + const { browser } = fakeBrowser({ pdfError: new Error('page crashed') }); + launchMock.mockResolvedValue(browser); + + await expect(renderPdf('')).rejects.toThrow('page crashed'); + expect(browser.close).toHaveBeenCalledTimes(1); + }); + + it('renders one document at a time, and keeps going after a failure', async () => { + const order: string[] = []; + let release!: () => void; + const gate = new Promise((resolve) => (release = resolve)); + + const first = fakeBrowser(); + first.page.pdf.mockImplementation(async () => { + order.push('first:start'); + await gate; + order.push('first:end'); + return new Uint8Array([1]); + }); + const second = fakeBrowser({ pdfError: new Error('boom') }); + second.page.pdf.mockImplementation(async () => { + order.push('second:start'); + throw new Error('boom'); + }); + const third = fakeBrowser(); + third.page.pdf.mockImplementation(async () => { + order.push('third:start'); + return new Uint8Array([3]); + }); + launchMock.mockResolvedValueOnce(first.browser).mockResolvedValueOnce(second.browser).mockResolvedValueOnce(third.browser); + + const p1 = renderPdf('1'); + const p2 = renderPdf('2'); + const p3 = renderPdf('3'); + const settled2 = p2.catch((e: Error) => e.message); + + await new Promise((r) => setTimeout(r, 20)); + expect(order).toEqual(['first:start']); // the others are waiting, not racing + + release(); + await p1; + expect(await settled2).toBe('boom'); + await p3; + expect(order).toEqual(['first:start', 'first:end', 'second:start', 'third:start']); + }); +}); diff --git a/src/api/lib/proposalPdf.ts b/src/api/lib/proposalPdf.ts new file mode 100644 index 0000000..c480be7 --- /dev/null +++ b/src/api/lib/proposalPdf.ts @@ -0,0 +1,687 @@ +/** + * Proposal PDF export: the HTML document builder and the headless-Chrome renderer. + * + * Split out of the proposals router so the (large) template is easy to find and + * the builder is a pure function that can be unit-tested without a browser. + */ + +import puppeteer from 'puppeteer'; +import { markdownToHtml } from './compliance'; + +/** HTML-escape a value for safe interpolation into the document. */ +export function escapeHtml(str: unknown): string { + if (str === null || str === undefined) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export interface PdfFinding { + message?: string; + title?: string; +} + +export interface ProposalPdfInput { + id: string; + title: string; + content: string; + createdAt: string; + metadata: Record; + /** Display name of the proposal's author. */ + createdBy: string; + riskReport: { + readinessScore: number; + legalRisk: number; + pricingRisk: number; + structuralRisk: number; + findings: PdfFinding[]; + } | null; + /** Active compliance rules, listed in the appendix. */ + rules: Array<{ name: string; description: string }>; +} + +/** Build the full HTML document that is rendered to PDF. */ +export function buildProposalHtml(input: ProposalPdfInput): string { + const proposal = { id: input.id }; + const meta = input.metadata || {}; + const clientName = String(meta.clientName ?? ''); + const dealSize = meta.dealSize != null ? `$${Number(meta.dealSize).toLocaleString()}` : ''; + const discount = meta.discount != null ? `${meta.discount}%` : ''; + const region = String(meta.region ?? ''); + const industry = String(meta.industry ?? ''); + const title = input.title || 'Proposal'; + const content = input.content || ''; + + const riskReport = input.riskReport; + const readinessScore = riskReport?.readinessScore || 0; + const legalRisk = riskReport?.legalRisk || 0; + const pricingRisk = riskReport?.pricingRisk || 0; + const structuralRisk = riskReport?.structuralRisk || 0; + const findings = riskReport?.findings ?? []; + + const createdBy = input.createdBy; + const rules = input.rules; + + const formattedDate = new Date(input.createdAt).toLocaleDateString('en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + }); + + return ` + + + + + + ${escapeHtml(title)} + + + + +
    +
    ${escapeHtml(title)}
    +
    Business Proposal
    + +
    +
    + Prepared For: + ${escapeHtml(clientName || 'Client Name')} +
    + ${industry ? ` +
    + Industry: + ${escapeHtml(industry)} +
    + ` : ''} + ${region ? ` +
    + Region: + ${escapeHtml(region)} +
    + ` : ''} +
    + Proposal Date: + ${escapeHtml(formattedDate)} +
    +
    + Reference Number: + PRO-${proposal.id.slice(0, 8).toUpperCase()} +
    +
    + Prepared By: + ${escapeHtml(createdBy)} +
    +
    + +
    + CONFIDENTIAL & PROPRIETARY
    + This proposal contains confidential business information intended solely for ${escapeHtml(clientName || 'the intended recipient')}. + Unauthorized disclosure, copying, or distribution is strictly prohibited. +
    +
    + + +
    +

    EXECUTIVE SUMMARY

    +

    + This proposal outlines a comprehensive solution designed specifically for ${escapeHtml(clientName || 'your organization')}. + Our team has carefully evaluated your requirements and developed an approach that addresses your key business objectives + while delivering measurable value and sustainable results. +

    + + ${dealSize || discount ? ` +

    Investment Overview

    + + + + + + ${dealSize ? ` + + + + + ` : ''} + ${discount ? ` + + + + + ` : ''} + ${region ? ` + + + + + ` : ''} +
    ItemDetails
    Project Investment${escapeHtml(dealSize)}
    Special Offer${escapeHtml(discount)} discount applied
    Service Region${escapeHtml(region)}
    + ` : ''} + +

    Why Partner With Us

    +

    + We bring extensive experience in ${escapeHtml(industry || 'your industry')}, combining technical expertise with + practical business understanding. Our approach is designed to minimize disruption while maximizing return on investment, + ensuring that your organization achieves its strategic goals efficiently and effectively. +

    +
    + + +
    +

    PROPOSAL OVERVIEW

    + +

    Scope of Engagement

    +

    + This section provides a high-level overview of the proposed engagement. The detailed specifications, + deliverables, and implementation approach are outlined in the following sections. +

    + + ${dealSize || discount ? ` +

    Commercial Terms Summary

    +
    + ${dealSize ? `

    Total Project Value: ${escapeHtml(dealSize)}

    ` : ''} + ${discount ? `

    Discount: ${escapeHtml(discount)} special pricing applied

    ` : ''} +

    Payment Terms: As per standard commercial agreements or as mutually agreed

    +

    Validity: This proposal is valid for 90 days from the date of issue

    +
    + ` : ''} +
    + + +
    +

    DETAILED PROPOSAL

    +
    ${markdownToHtml(content)}
    +
    + +
    + + +
    +

    IMPLEMENTATION & DELIVERY

    + +

    Project Approach

    +

    + Our implementation methodology follows industry best practices, ensuring systematic execution, + clear communication, and measurable progress throughout the engagement lifecycle. +

    + +

    Quality Assurance

    +

    + All deliverables undergo rigorous quality assurance processes to ensure they meet or exceed + established standards and specifications. We maintain comprehensive documentation throughout + the project lifecycle. +

    + +

    Project Management

    +

    + A dedicated project manager will serve as your primary point of contact, ensuring seamless + coordination, regular status updates, and proactive issue resolution throughout the engagement. +

    +
    + +
    + + +
    +

    TERMS & CONDITIONS

    + +

    Proposal Validity

    +

    + This proposal remains valid for ninety (90) days from the date of issuance. All pricing, scope, and terms + are subject to review and adjustment after this period. +

    + +

    Agreement

    +

    + This document constitutes a proposal and not a binding contractual agreement. A formal contract will be + executed upon mutual agreement of terms, signed by authorized representatives of both parties. +

    + +

    Confidentiality

    +

    + All information contained within this proposal is confidential and proprietary. Recipients agree to + maintain confidentiality and restrict disclosure to authorized decision-makers only. +

    + +

    Intellectual Property

    +

    + All intellectual property rights, including but not limited to methodologies, processes, and deliverables, + shall be addressed in the formal service agreement following proposal acceptance. +

    + +

    Changes & Modifications

    +

    + Any changes to the scope, timeline, or terms outlined in this proposal must be mutually agreed upon in + writing by authorized representatives of both parties. +

    +
    + +
    + + + ${riskReport ? ` +
    +

    APPENDIX A: QUALITY ASSURANCE & COMPLIANCE

    + +
    +

    Quality Standards

    +

    + This proposal has been developed in accordance with our quality management frameworks and + organizational standards. All recommendations and specifications align with industry best practices. +

    +
    + +

    Quality Assessment Summary

    +

    + Our internal quality review process evaluates all proposals across multiple dimensions to ensure + completeness, accuracy, and alignment with client requirements. +

    + + + + + + + + + + + + + + + + + + + + + + +
    Assessment AreaStatus
    Overall Quality Score${readinessScore}/100
    Legal & Contractual Review${100 - legalRisk}/100
    Commercial Terms Review${100 - pricingRisk}/100
    Technical Completeness${100 - structuralRisk}/100
    + + ${findings.length > 0 ? ` +

    Review Notes

    + ${findings.slice(0, 3).map((finding, idx) => ` +

    Note ${idx + 1}: ${escapeHtml(finding.message || finding.title || 'Quality review note')}

    + `).join('')} + ` : ''} + + ${rules.length > 0 ? ` +

    Applicable Standards & Policies

    +

    + This proposal has been developed in alignment with the following organizational standards: +

    +
      + ${rules.slice(0, 5).map((rule) => ` +
    • ${escapeHtml(rule.name)}: ${escapeHtml(rule.description)}
    • + `).join('')} +
    + ` : ''} +
    + ` : ''} + + +
    +

    NEXT STEPS

    + +

    + We appreciate your consideration of this proposal and look forward to the opportunity to partner with + ${escapeHtml(clientName || 'your organization')} on this initiative. +

    + +

    Proposal Review Process

    +
      +
    1. Review & Questions: Please review this proposal thoroughly. We welcome any questions or requests for clarification.
    2. +
    3. Discussion: Schedule a meeting with our team to discuss the proposal details, timeline, and any specific requirements.
    4. +
    5. Contract Execution: Upon acceptance, we will prepare formal agreements for execution by authorized signatories.
    6. +
    7. Project Kickoff: Following contract execution, we will schedule a project kickoff meeting to commence work.
    8. +
    + +
    +

    Contact Information

    +

    + For questions regarding this proposal, please contact:
    + ${escapeHtml(createdBy)}
    + Proposal Reference: PRO-${proposal.id.slice(0, 8).toUpperCase()} +

    +
    + +

    + Thank you for considering our proposal. We look forward to working with you. +

    + + +
    + + +`; +} + +/** + * Chromium flags that let headless Chrome fit constrained hosts (e.g. Render's + * 512MB free tier). --single-process is the biggest saver. + */ +const CHROME_ARGS = [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu', + '--no-zygote', + '--single-process', + '--disable-extensions', +]; + +async function renderPdfOnce(html: string): Promise { + const browser = await puppeteer.launch({ + args: CHROME_ARGS, + // 'new' headless runs the regular Chrome binary; `true` (old headless) + // makes Puppeteer look for the separate chrome-headless-shell install, + // which breaks local dev where only Chrome is downloaded. + headless: 'new', + }); + try { + const page = await browser.newPage(); + await page.setContent(html, { waitUntil: 'networkidle0' }); + const pdf = await page.pdf({ + format: 'A4', + printBackground: true, + margin: { top: '25mm', bottom: '25mm', left: '20mm', right: '20mm' }, + displayHeaderFooter: true, + headerTemplate: '
    ', + footerTemplate: ` +
    + Page of +
    + `, + preferCSSPageSize: false, + }); + return Buffer.from(pdf); + } finally { + // Always release Chrome: a leaked process per failed export would exhaust a small host. + await browser.close(); + } +} + +/** Exports run one at a time: two concurrent Chromes would not fit in 512MB. */ +let renderQueue: Promise = Promise.resolve(); + +/** Render an HTML document to a PDF buffer. */ +export function renderPdf(html: string): Promise { + const run = renderQueue.then(() => renderPdfOnce(html)); + renderQueue = run.catch(() => undefined); + return run; +} diff --git a/src/api/lib/proposalStore.ts b/src/api/lib/proposalStore.ts new file mode 100644 index 0000000..5550355 --- /dev/null +++ b/src/api/lib/proposalStore.ts @@ -0,0 +1,102 @@ +/** + * Shared persistence for creating proposals, used by both the manual create + * route and the AI generation route: insert, audit entry, best-effort embedding. + */ + +import { supabase } from '../../lib/supabase'; +import type { AuthUser } from '../middleware/auth'; +import { generateEmbedding } from './embeddings'; +import { logger } from './logger'; + +export interface ProposalRow { + id: string; + title: string; + content: string; + status: string; + metadata: Record; + userId: string; + createdAt: string; + updatedAt: string; +} + +/** + * Best-effort: compute and store a content embedding for semantic search. + * Silently no-ops if embeddings or the pgvector column aren't available yet, + * so it never breaks proposal create/generate. See docs/SEMANTIC_SEARCH.md. + */ +export async function storeProposalEmbedding(id: string, text: string): Promise { + try { + const embedding = await generateEmbedding(text); + if (!embedding) return; + const { error } = await supabase.from('Proposal').update({ embedding }).eq('id', id); + if (error) { + logger.warn('Embedding not stored (run the pgvector migration):', error.message); + } + } catch (err) { + logger.warn('Embedding store skipped:', (err as Error).message); + } +} + +export interface NewProposalInput { + title: string; + content: string; + metadata?: Record; +} + +/** + * Insert a PENDING proposal owned by `user` (and their company, if any), write + * the audit entry, and queue its embedding. Throws if the insert fails. + */ +export async function createProposalRecord( + user: AuthUser, + input: NewProposalInput, + audit: { action: string; after?: Record } +): Promise { + const insertPayload: Record = { + id: crypto.randomUUID(), + title: input.title, + content: input.content, + status: 'PENDING', + metadata: input.metadata || {}, + lockedSections: [], + userId: user.id, + updatedAt: new Date().toISOString(), + }; + if (user.companyId) insertPayload.company_id = user.companyId; + + const { data: proposal, error } = await supabase + .from('Proposal') + .insert(insertPayload) + .select() + .single(); + + if (error) throw error; + + const { error: auditError } = await supabase.from('AuditLog').insert({ + id: crypto.randomUUID(), + actorId: user.id, + proposalId: proposal.id, + action: audit.action, + after: audit.after ?? { title: input.title, status: 'PENDING' }, + }); + if (auditError) logger.warn('Audit entry not written:', auditError.message); + + await storeProposalEmbedding(proposal.id, `${proposal.title}\n\n${proposal.content}`); + + return proposal as ProposalRow; +} + +/** The response shape the SPA expects for a freshly created proposal. */ +export function toCreatedResponse(proposal: ProposalRow) { + return { + id: proposal.id, + title: proposal.title, + content: proposal.content, + status: proposal.status, + metadata: proposal.metadata, + userId: proposal.userId, + readinessScore: 0, + createdAt: proposal.createdAt, + updatedAt: proposal.updatedAt, + }; +} diff --git a/src/api/lib/ruleAnalysis.test.ts b/src/api/lib/ruleAnalysis.test.ts new file mode 100644 index 0000000..b8187ad --- /dev/null +++ b/src/api/lib/ruleAnalysis.test.ts @@ -0,0 +1,280 @@ +import { describe, it, expect } from 'vitest'; +import { + analyzeByRules, + extractDealSize, + extractDiscountPercent, + extractPaymentDays, + findMissingClauses, + pricingRiskForDiscount, + thresholdsFromRules, +} from './ruleAnalysis'; + +/** The seeded "bad" sample: over-discounted, tiny, long payment terms, no legal clauses. */ +const BAD_PROPOSAL = `Website Update Proposal + +Overview + +Quick website update for SmallBiz LLC. + +What We Will Do + +Update homepage design, refresh color scheme, and add a contact form. Work will be completed within 3 weeks. + +Pricing + +Total Cost: $8,500 + +Special Discount: 35% + +Final Price: $5,525 USD + +Payment Terms: Net 120 days + +Basic Terms + +Standard terms and conditions apply. Work begins upon receipt of signed agreement.`; + +const GOOD_PROPOSAL = `# Cloud Migration Proposal + +## Executive Summary +We will migrate your infrastructure to the cloud with minimal downtime. + +## Scope of Work +Assessment, migration waves, validation and hand-over of all deliverables. + +## Timeline & Milestones +Discovery in weeks 1-2, migration in weeks 3-10, hyper-care in weeks 11-12. + +## Investment & Pricing +Total Investment: $120,000 +Discount: 10% volume discount applied. +Payment is due within 30 days of invoice date. + +## Terms & Conditions +**Indemnification**: Each party agrees to indemnify and hold harmless the other. +**Liability Limitation**: Neither party shall be liable for indirect damages; total liability is capped at the contract value. +**Termination Rights**: Either party may terminate with 30 days written notice. +**Confidentiality**: Both parties will protect proprietary information. +**Intellectual Property**: Deliverables transfer to the client on full payment.`; + +describe('extractDiscountPercent', () => { + it('reads "Special Discount: 35%"', () => { + expect(extractDiscountPercent('Special Discount: 35%')).toBe(35); + }); + + it('reads "20% discount" and "15% off"', () => { + expect(extractDiscountPercent('We offer a 20% discount.')).toBe(20); + expect(extractDiscountPercent('Sign this month for 15% off.')).toBe(15); + }); + + it('reads "discount of 12.5 percent"', () => { + expect(extractDiscountPercent('A discount of 12.5 percent applies.')).toBe(12.5); + }); + + it('returns the largest when several are stated (the conservative choice)', () => { + expect(extractDiscountPercent('Early-bird 10% discount, plus a further 30% discount on renewal')).toBe(30); + }); + + it('ignores percentages that are not discounts and impossible values', () => { + expect(extractDiscountPercent('Our uptime is 99.9% and growth was 40%.')).toBeNull(); + expect(extractDiscountPercent('discount: 250%')).toBeNull(); + }); + + it('returns null when no discount is mentioned', () => { + expect(extractDiscountPercent('No incentives here.')).toBeNull(); + }); +}); + +describe('extractDealSize', () => { + it('prefers the labelled final price over the pre-discount total', () => { + expect(extractDealSize(BAD_PROPOSAL)).toBe(5525); + }); + + it('uses a labelled total when there is no final price', () => { + expect(extractDealSize('Total Investment: $120,000')).toBe(120000); + }); + + it('understands k and M suffixes', () => { + expect(extractDealSize('Total price: $50k')).toBe(50000); + expect(extractDealSize('Contract value: $1.2M')).toBe(1_200_000); + }); + + it('ignores unlabelled dollar amounts such as hourly rates', () => { + expect(extractDealSize('Our rate is $150 per hour for consulting.')).toBeNull(); + }); + + it('returns null when there is no amount', () => { + expect(extractDealSize('Pricing to be agreed.')).toBeNull(); + }); +}); + +describe('extractPaymentDays', () => { + it('reads Net terms', () => { + expect(extractPaymentDays('Payment Terms: Net 120 days')).toBe(120); + expect(extractPaymentDays('terms are net-45')).toBe(45); + }); + + it('reads "due within N days"', () => { + expect(extractPaymentDays('Invoices are due within 30 days.')).toBe(30); + }); + + it('reads "N days of invoice"', () => { + expect(extractPaymentDays('Payment is due 60 days from invoice date')).toBe(60); + }); + + it('takes the longest term when several are stated', () => { + expect(extractPaymentDays('Net 30 for services; payment for hardware within 75 days')).toBe(75); + }); + + it('returns null when no term is stated', () => { + expect(extractPaymentDays('Payment on delivery.')).toBeNull(); + }); +}); + +describe('findMissingClauses', () => { + it('finds nothing missing in a full set of clauses', () => { + expect( + findMissingClauses(GOOD_PROPOSAL, [ + 'indemnification', + 'limitation_of_liability', + 'termination', + 'confidentiality', + 'intellectual_property', + ]) + ).toEqual([]); + }); + + it('lists the labels of absent clauses', () => { + expect(findMissingClauses('We agree to keep things confidential.', ['indemnification', 'confidentiality'])).toEqual([ + 'Indemnification', + ]); + }); + + it('treats unknown required terms as plain substrings', () => { + expect(findMissingClauses('Includes a force majeure clause.', ['force majeure'])).toEqual([]); + expect(findMissingClauses('Nothing special.', ['force majeure'])).toEqual(['force majeure']); + }); +}); + +describe('thresholdsFromRules', () => { + it('defaults when there are no rules', () => { + expect(thresholdsFromRules([])).toMatchObject({ maxDiscount: 25, minDealSize: 10000, maxPaymentDays: 90 }); + }); + + it('applies the strictest limits across rules', () => { + const t = thresholdsFromRules([ + { logic: { maxDiscount: 20 } }, + { logic: { maxDiscount: 15, minDealSize: 50000 } }, + { logic: { maxPaymentDays: 60 } }, + ]); + expect(t.maxDiscount).toBe(15); + expect(t.minDealSize).toBe(50000); + expect(t.maxPaymentDays).toBe(60); + }); + + it('never loosens a limit beyond the built-in defaults', () => { + const t = thresholdsFromRules([{ logic: { maxDiscount: 50, minDealSize: 100, maxPaymentDays: 365 } }]); + expect(t).toMatchObject({ maxDiscount: 25, minDealSize: 10000, maxPaymentDays: 90 }); + }); + + it('maps required terms onto canonical clauses and keeps custom ones', () => { + const t = thresholdsFromRules([ + { logic: { requiredTerms: ['indemnification', 'limitation of liability', 'confidentiality', 'Force Majeure'] } }, + ]); + expect(t.requiredTerms).toEqual( + expect.arrayContaining(['indemnification', 'limitation_of_liability', 'termination', 'confidentiality', 'force majeure']) + ); + }); + + it('tolerates logic stored as a JSON string, and malformed logic', () => { + expect(thresholdsFromRules([{ logic: '{"maxDiscount": 10}' }]).maxDiscount).toBe(10); + expect(thresholdsFromRules([{ logic: 'not json' }, { logic: null }, {}]).maxDiscount).toBe(25); + }); +}); + +describe('pricingRiskForDiscount', () => { + it('follows the AI prompt bands', () => { + expect(pricingRiskForDiscount(0)).toBe(12); + expect(pricingRiskForDiscount(10)).toBe(12); + expect(pricingRiskForDiscount(12)).toBe(30); + expect(pricingRiskForDiscount(18)).toBe(45); + expect(pricingRiskForDiscount(25)).toBe(65); + expect(pricingRiskForDiscount(26)).toBe(95); + }); +}); + +describe('analyzeByRules', () => { + it('flags the three hard-limit violations in the seeded bad proposal', () => { + const result = analyzeByRules({ title: 'Website Update Proposal', content: BAD_PROPOSAL }); + + expect(result.extracted).toMatchObject({ discountPercent: 35, dealSize: 5525, paymentDays: 120 }); + + const critical = result.findings.filter((f) => f.level === 'CRITICAL').map((f) => f.type); + expect(critical).toEqual(expect.arrayContaining(['DISCOUNT VIOLATION', 'DEAL SIZE', 'PAYMENT TERMS'])); + + expect(result.pricingRisk).toBeGreaterThanOrEqual(90); + expect(result.readinessScore).toBeLessThanOrEqual(55); + expect(result.recommendations.length).toBeGreaterThan(0); + }); + + it('flags the missing legal clauses in the bad proposal', () => { + const result = analyzeByRules({ content: BAD_PROPOSAL }); + expect(result.extracted.missingClauses).toEqual( + expect.arrayContaining(['Indemnification', 'Limitation of liability']) + ); + expect(result.legalRisk).toBeGreaterThan(40); + }); + + it('scores a compliant proposal as ready, with no critical findings', () => { + const result = analyzeByRules({ content: GOOD_PROPOSAL }); + expect(result.findings.filter((f) => f.level === 'CRITICAL')).toEqual([]); + expect(result.extracted).toMatchObject({ discountPercent: 10, dealSize: 120000, paymentDays: 30 }); + expect(result.extracted.missingClauses).toEqual([]); + expect(result.readinessScore).toBeGreaterThanOrEqual(80); + }); + + it('falls back to form metadata when the document states no numbers', () => { + const result = analyzeByRules({ + content: 'A short proposal without any figures.', + metadata: { discount: 40, dealSize: 5000 }, + }); + expect(result.extracted).toMatchObject({ discountPercent: 40, dealSize: 5000 }); + expect(result.findings.some((f) => f.type === 'DISCOUNT VIOLATION')).toBe(true); + }); + + it('prefers document values over conflicting form metadata', () => { + const result = analyzeByRules({ + content: 'Discount: 5%\nTotal Investment: $90,000', + metadata: { discount: 40, dealSize: 1000 }, + }); + expect(result.extracted).toMatchObject({ discountPercent: 5, dealSize: 90000 }); + expect(result.findings.some((f) => f.type === 'DISCOUNT VIOLATION')).toBe(false); + }); + + it('honours stricter limits from active rules', () => { + const result = analyzeByRules({ + content: GOOD_PROPOSAL, + rules: [{ logic: { maxDiscount: 5 } }], + }); + expect(result.findings.some((f) => f.type === 'DISCOUNT VIOLATION')).toBe(true); + }); + + it('notes when no deal value can be found rather than inventing a violation', () => { + const result = analyzeByRules({ content: 'We will build a website. Terms to follow.' }); + const dealFinding = result.findings.find((f) => f.type === 'DEAL SIZE'); + expect(dealFinding?.level).toBe('LOW'); + }); + + it('always labels the report as produced by the rule checker', () => { + const result = analyzeByRules({ content: GOOD_PROPOSAL }); + expect(result.findings.some((f) => f.type === 'ANALYSIS MODE')).toBe(true); + }); + + it('returns scores within 0-100 for empty content', () => { + const result = analyzeByRules({ content: '' }); + for (const score of [result.readinessScore, result.legalRisk, result.pricingRisk, result.structuralRisk]) { + expect(score).toBeGreaterThanOrEqual(0); + expect(score).toBeLessThanOrEqual(100); + } + }); +}); diff --git a/src/api/lib/ruleAnalysis.ts b/src/api/lib/ruleAnalysis.ts new file mode 100644 index 0000000..caeaea0 --- /dev/null +++ b/src/api/lib/ruleAnalysis.ts @@ -0,0 +1,415 @@ +/** + * Deterministic compliance analysis: the same questions the AI prompt asks + * (discount cap, minimum deal size, payment terms, required legal clauses, + * document structure), answered with plain text extraction and arithmetic. + * + * Used when the AI provider is unconfigured, unreachable, or returns an + * unusable answer (see analysisService), and when ANALYSIS_MODE=rules. It is + * deliberately conservative and explainable: every finding names the number it + * found and the limit it was checked against. + */ + +import { MAX_DISCOUNT_PERCENT, MIN_DEAL_SIZE, type NormalizedAnalysis } from './compliance'; + +/** Longest payment term (days) allowed before a proposal is a violation. */ +export const MAX_PAYMENT_DAYS = 90; + +export type FindingLevel = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW'; + +export interface Finding { + type: string; + level: FindingLevel; + message: string; + location: string; +} + +export interface Recommendation { + paragraphId: string; + suggestion: string; + reason: string; +} + +export interface RuleThresholds { + maxDiscount: number; + minDealSize: number; + maxPaymentDays: number; + /** Canonical clause keys (see CLAUSES) or free-text terms from custom rules. */ + requiredTerms: string[]; +} + +export interface RuleAnalysisInput { + title?: string; + content: string; + metadata?: Record | null; + /** Active rows from the Rule table; only their `logic` JSON is read. */ + rules?: Array<{ logic?: unknown }>; +} + +export interface RuleAnalysisResult extends NormalizedAnalysis { + findings: Finding[]; + recommendations: Recommendation[]; + /** What the checker extracted, for display and tests. */ + extracted: { + discountPercent: number | null; + dealSize: number | null; + paymentDays: number | null; + missingClauses: string[]; + missingSections: string[]; + }; +} + +// --------------------------------------------------------------------------- +// Thresholds +// --------------------------------------------------------------------------- + +/** Clauses checked when no rule says otherwise (matches the AI prompt). */ +const DEFAULT_REQUIRED = ['indemnification', 'limitation_of_liability', 'termination']; + +interface ClauseSpec { + label: string; + /** Substrings of a rule's free-text term that map it to this clause. */ + aliases: string[]; + test: RegExp; +} + +const CLAUSES: Record = { + indemnification: { + label: 'Indemnification', + aliases: ['indemn'], + test: /indemnif/i, + }, + limitation_of_liability: { + label: 'Limitation of liability', + aliases: ['liabil'], + test: /limitation of liability|limit(?:s|ed|ation)?\s+(?:of\s+|on\s+)?(?:its\s+|their\s+|total\s+|our\s+)?liabilit|liability\s+(?:cap|limit)|shall not be liable|not be liable for any (?:indirect|consequential)/i, + }, + termination: { + label: 'Termination rights', + aliases: ['terminat'], + test: /terminat(?:e|es|ed|ion|ing)\b/i, + }, + confidentiality: { + label: 'Confidentiality', + aliases: ['confiden', 'non-disclosure', 'nondisclosure', 'nda'], + test: /confidential|non-?disclosure|\bNDA\b/i, + }, + intellectual_property: { + label: 'Intellectual property', + aliases: ['intellectual', 'ip rights', 'work product'], + test: /intellectual property|\bIP\b rights|ownership of (?:all )?(?:deliverables|work product)|work product/i, + }, +}; + +/** Map a rule's free-text term ("limitation of liability") to a canonical clause key. */ +function canonicalTerm(term: string): string { + const normalized = term.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(); + for (const [key, spec] of Object.entries(CLAUSES)) { + if (spec.aliases.some((alias) => normalized.includes(alias))) return key; + } + return normalized; // custom term: matched as a plain substring +} + +function asLogic(value: unknown): Record { + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; + } catch { + return {}; + } + } + return value && typeof value === 'object' ? (value as Record) : {}; +} + +const finiteNumber = (v: unknown): number | null => { + const n = typeof v === 'string' ? Number(v) : (v as number); + return typeof n === 'number' && Number.isFinite(n) ? n : null; +}; + +/** + * Combine the active rules into one set of limits: the strictest discount cap + * and payment term, the largest minimum deal size, and the union of required + * clauses. Anything no rule specifies falls back to the built-in defaults. + */ +export function thresholdsFromRules(rules: Array<{ logic?: unknown }> = []): RuleThresholds { + let maxDiscount = MAX_DISCOUNT_PERCENT; + let minDealSize = MIN_DEAL_SIZE; + let maxPaymentDays = MAX_PAYMENT_DAYS; + const required = new Set(DEFAULT_REQUIRED); + + for (const rule of rules) { + const logic = asLogic(rule.logic); + const discount = finiteNumber(logic.maxDiscount); + if (discount !== null) maxDiscount = Math.min(maxDiscount, discount); + const minSize = finiteNumber(logic.minDealSize); + if (minSize !== null) minDealSize = Math.max(minDealSize, minSize); + const days = finiteNumber(logic.maxPaymentDays); + if (days !== null) maxPaymentDays = Math.min(maxPaymentDays, days); + if (Array.isArray(logic.requiredTerms)) { + for (const term of logic.requiredTerms) { + if (typeof term === 'string' && term.trim()) required.add(canonicalTerm(term)); + } + } + } + + return { maxDiscount, minDealSize, maxPaymentDays, requiredTerms: [...required] }; +} + +// --------------------------------------------------------------------------- +// Extraction +// --------------------------------------------------------------------------- + +/** Largest discount percentage the document states, or null if it states none. */ +export function extractDiscountPercent(text: string): number | null { + const patterns = [ + /(\d{1,3}(?:\.\d+)?)\s*%\s*(?:[a-z-]+\s+)?(?:discount|off|reduction|rebate)/gi, + /(?:discount|rebate)[^\d\n%]{0,40}?(\d{1,3}(?:\.\d+)?)\s*(?:%|percent)/gi, + ]; + const found: number[] = []; + for (const pattern of patterns) { + for (const match of text.matchAll(pattern)) { + const value = Number(match[1]); + if (Number.isFinite(value) && value >= 0 && value <= 100) found.push(value); + } + } + return found.length ? Math.max(...found) : null; +} + +/** Parse "$8,500", "$1.2M", "$50k" into a number of dollars. */ +function parseAmount(whole: string, suffix?: string): number { + const base = Number(whole.replace(/,/g, '')); + switch ((suffix || '').toLowerCase()) { + case 'k': + case 'thousand': + return base * 1_000; + case 'm': + case 'million': + return base * 1_000_000; + default: + return base; + } +} + +const AMOUNT_RE = /\$\s?(\d[\d,]*(?:\.\d+)?)\s*(k|m|million|thousand)?\b/gi; + +/** + * The document's deal value: the largest "final / net / after discount" amount + * if one is labelled, otherwise the largest "total / investment / price" amount. + * Returns null when no amount is labelled โ€” a stray "$100/hour" is not a deal. + */ +export function extractDealSize(text: string): number | null { + const finals: number[] = []; + const totals: number[] = []; + for (const line of text.split(/\r?\n/)) { + const amounts = [...line.matchAll(AMOUNT_RE)].map((m) => parseAmount(m[1], m[2])); + if (amounts.length === 0) continue; + if (/\b(final|net|grand total|after discount|discounted)\b/i.test(line)) { + finals.push(...amounts); + } else if (/\b(total|investment|contract value|deal size|project cost|price|pricing|fees?)\b/i.test(line)) { + totals.push(...amounts); + } + } + const pool = finals.length ? finals : totals; + return pool.length ? Math.max(...pool) : null; +} + +/** Longest payment term (in days) the document states, or null. */ +export function extractPaymentDays(text: string): number | null { + const patterns = [ + /\bnet\s*-?\s*(\d{1,3})\b/gi, + /payment[^.\n]{0,80}?(\d{1,3})\s*(?:calendar\s+|business\s+|working\s+)?days/gi, + /(\d{1,3})\s*(?:calendar\s+|business\s+|working\s+)?days\s+(?:of|from|after|following)\s+(?:the\s+)?(?:invoice|receipt|delivery)/gi, + /due\s+within\s+(\d{1,3})\s*days/gi, + ]; + const found: number[] = []; + for (const pattern of patterns) { + for (const match of text.matchAll(pattern)) { + const value = Number(match[1]); + if (Number.isFinite(value)) found.push(value); + } + } + return found.length ? Math.max(...found) : null; +} + +/** Labels of the required clauses the text does not contain. */ +export function findMissingClauses(text: string, required: string[]): string[] { + const missing: string[] = []; + for (const term of required) { + const spec = CLAUSES[term]; + const present = spec ? spec.test.test(text) : text.toLowerCase().includes(term.toLowerCase()); + if (!present) missing.push(spec ? spec.label : term); + } + return missing; +} + +const SECTIONS: Array<{ label: string; test: RegExp }> = [ + { label: 'Overview / executive summary', test: /executive summary|overview|introduction|background/i }, + { label: 'Scope / solution', test: /scope|solution|services|deliverables|approach|what we will do/i }, + { label: 'Pricing', test: /pricing|investment|fees?\b|cost|price/i }, + { label: 'Timeline', test: /timeline|schedule|milestones|duration|\d+\s*(?:weeks?|months?)/i }, + { label: 'Terms & conditions', test: /terms\s*(?:&|and)?\s*conditions|terms of|conditions|payment terms/i }, +]; + +// --------------------------------------------------------------------------- +// Analysis +// --------------------------------------------------------------------------- + +const clamp = (n: number, lo = 0, hi = 100) => Math.max(lo, Math.min(hi, n)); + +/** Pricing risk implied by a discount, mirroring the AI prompt's table. */ +export function pricingRiskForDiscount(discount: number, maxDiscount = MAX_DISCOUNT_PERCENT): number { + if (discount > maxDiscount) return 95; + if (discount > 20) return 65; + if (discount > 15) return 45; + if (discount > 10) return 30; + return 12; +} + +export function analyzeByRules(input: RuleAnalysisInput): RuleAnalysisResult { + const content = input.content || ''; + const metadata = input.metadata ?? {}; + const limits = thresholdsFromRules(input.rules); + const findings: Finding[] = []; + const recommendations: Recommendation[] = []; + + // Document values win over form values, as in the AI prompt. + const docDiscount = extractDiscountPercent(content); + const metaDiscount = finiteNumber(metadata.discount); + const discount = docDiscount ?? metaDiscount; + + const docDealSize = extractDealSize(content); + const metaDealSize = finiteNumber(metadata.dealSize); + const dealSize = docDealSize ?? (metaDealSize && metaDealSize > 0 ? metaDealSize : null); + + const paymentDays = extractPaymentDays(content); + const missingClauses = findMissingClauses(content, limits.requiredTerms); + const missingSections = SECTIONS.filter((s) => !s.test.test(content)).map((s) => s.label); + + // --- Pricing ----------------------------------------------------------- + let pricingRisk = 12; + if (discount !== null) { + pricingRisk = pricingRiskForDiscount(discount, limits.maxDiscount); + if (discount > limits.maxDiscount) { + findings.push({ + type: 'DISCOUNT VIOLATION', + level: 'CRITICAL', + message: `The proposed discount of ${discount}% exceeds the maximum allowed discount of ${limits.maxDiscount}%.`, + location: 'Pricing', + }); + recommendations.push({ + paragraphId: 'pricing', + suggestion: `Reduce the discount to ${limits.maxDiscount}% or less, or obtain executive approval before sending.`, + reason: `Discounts above ${limits.maxDiscount}% violate the pricing policy.`, + }); + } + } + + if (dealSize !== null && dealSize < limits.minDealSize) { + pricingRisk = Math.max(pricingRisk, 70); + findings.push({ + type: 'DEAL SIZE', + level: 'CRITICAL', + message: `The deal size of $${dealSize.toLocaleString('en-US')} is below the minimum required deal size of $${limits.minDealSize.toLocaleString('en-US')}.`, + location: 'Pricing', + }); + recommendations.push({ + paragraphId: 'pricing', + suggestion: `Expand the scope to reach at least $${limits.minDealSize.toLocaleString('en-US')}, or get a small-deal exception approved.`, + reason: 'Deals under the minimum size require explicit approval.', + }); + } else if (dealSize === null) { + findings.push({ + type: 'DEAL SIZE', + level: 'LOW', + message: 'No deal value could be identified in the document, so the minimum deal size was not checked.', + location: 'Pricing', + }); + recommendations.push({ + paragraphId: 'pricing', + suggestion: 'State the total investment explicitly (for example "Total Investment: $25,000").', + reason: 'A clearly stated deal value lets reviewers verify the minimum deal size.', + }); + } + + if (paymentDays !== null && paymentDays > limits.maxPaymentDays) { + pricingRisk = Math.max(pricingRisk, 60); + findings.push({ + type: 'PAYMENT TERMS', + level: 'CRITICAL', + message: `Payment terms of ${paymentDays} days exceed the maximum allowed payment term of ${limits.maxPaymentDays} days.`, + location: 'Payment Terms', + }); + recommendations.push({ + paragraphId: 'payment-terms', + suggestion: `Shorten payment terms to ${limits.maxPaymentDays} days or fewer (for example Net 30).`, + reason: `Terms longer than ${limits.maxPaymentDays} days create unacceptable cash-flow risk.`, + }); + } + + // --- Legal ------------------------------------------------------------- + let legalRisk = 10; + if (missingClauses.length > 0) { + legalRisk = clamp(10 + missingClauses.length * 25, 10, 95); + for (const clause of missingClauses) { + findings.push({ + type: 'MISSING CLAUSE', + level: 'HIGH', + message: `The proposal does not contain a ${clause.toLowerCase()} clause.`, + location: 'Terms & Conditions', + }); + recommendations.push({ + paragraphId: 'terms', + suggestion: `Add a ${clause.toLowerCase()} clause to the Terms & Conditions.`, + reason: `${clause} is a required legal protection.`, + }); + } + } + + // --- Structure --------------------------------------------------------- + let structuralRisk = 15 + missingSections.length * 12; + if (content.trim().length < 400) structuralRisk += 15; + structuralRisk = clamp(structuralRisk, 10, 90); + if (missingSections.length > 0) { + findings.push({ + type: 'STRUCTURE', + level: 'MEDIUM', + message: `The document appears to be missing: ${missingSections.join(', ')}.`, + location: 'Document', + }); + recommendations.push({ + paragraphId: 'structure', + suggestion: `Add the missing section${missingSections.length > 1 ? 's' : ''}: ${missingSections.join(', ')}.`, + reason: 'A complete structure makes the proposal easier to review and approve.', + }); + } + + findings.push({ + type: 'ANALYSIS MODE', + level: 'LOW', + message: + 'AI analysis was unavailable, so this report comes from the built-in rule checker ' + + '(discount, deal size, payment terms, required clauses and document structure). Re-run the analysis for a full AI review.', + location: 'Report', + }); + + // --- Scores ------------------------------------------------------------ + let readinessScore = Math.round(100 - (0.4 * legalRisk + 0.4 * pricingRisk + 0.2 * structuralRisk)); + readinessScore = clamp(readinessScore); + if (findings.some((f) => f.level === 'CRITICAL')) readinessScore = Math.min(readinessScore, 55); + + return { + readinessScore, + legalRisk: Math.round(legalRisk), + pricingRisk: Math.round(pricingRisk), + structuralRisk: Math.round(structuralRisk), + findings, + recommendations, + extracted: { + discountPercent: discount, + dealSize, + paymentDays, + missingClauses, + missingSections, + }, + }; +} diff --git a/src/api/middleware/rateLimit.ts b/src/api/middleware/rateLimit.ts index 3991f17..8bc2a6d 100644 --- a/src/api/middleware/rateLimit.ts +++ b/src/api/middleware/rateLimit.ts @@ -20,6 +20,15 @@ export const authLimiter = rateLimit({ message: { error: 'Too many attempts. Please try again later.' }, }); +/** Limiter for PDF export: each request launches headless Chrome, which is memory-hungry. */ +export const exportLimiter = rateLimit({ + windowMs: 60 * 1000, // 1 minute + max: isProduction ? 10 : 1000, + standardHeaders: true, + legacyHeaders: false, + message: { error: 'Too many PDF exports. Please wait a moment and try again.' }, +}); + /** Limiter for AI generation/analysis endpoints (cost protection). */ export const aiLimiter = rateLimit({ windowMs: 60 * 1000, // 1 minute diff --git a/src/api/proposals.ts b/src/api/proposals.ts index b733eac..0b50379 100644 --- a/src/api/proposals.ts +++ b/src/api/proposals.ts @@ -1,1209 +1,434 @@ -import { Router, Request, Response } from 'express'; -import { supabase } from '../lib/supabase'; -import puppeteer from 'puppeteer'; -import { requireAuth, isAdmin, canAccessCompany } from './middleware/auth'; -import { aiLimiter } from './middleware/rateLimit'; -import { markdownToHtml } from './lib/compliance'; -import { sendEmail } from './lib/email'; -import { buildStatusChangeEmail } from './lib/emailTemplates'; -import { generateEmbedding } from './lib/embeddings'; -import { llmClient as client, llmModel as deployment, llmExtraParams } from './lib/llm'; - -const router = Router(); - -/** - * Best-effort: compute and store a content embedding for semantic search. - * Silently no-ops if embeddings or the pgvector column aren't available yet, - * so it never breaks proposal create/generate. See docs/SEMANTIC_SEARCH.md. - */ -async function storeProposalEmbedding(id: string, text: string): Promise { - try { - const embedding = await generateEmbedding(text); - if (!embedding) return; - const { error } = await supabase.from('Proposal').update({ embedding }).eq('id', id); - if (error) { - console.warn('Embedding not stored (run the pgvector migration):', error.message); - } - } catch (err) { - console.warn('Embedding store skipped:', (err as Error).message); - } -} - -// Types for database rows -interface ProposalRow { - id: string; - title: string; - content: string; - status: string; - metadata: Record; - userId: string; - createdAt: string; - updatedAt: string; -} - -interface RiskReportRow { - id: string; - proposalId: string; - readinessScore: number; - legalRisk: number; - pricingRisk: number; - structuralRisk: number; - findings: unknown[]; - recommendations: unknown[]; -} - -interface UserRow { - id: string; - name: string | null; - email: string; -} - -// GET all proposals (admin: all; others: own company only) -router.get('/', requireAuth, async (req: Request, res: Response) => { - try { - let query = supabase - .from('Proposal') - .select(` - *, - User:userId (name, email), - RiskReport (readinessScore, legalRisk, pricingRisk, structuralRisk, findings, recommendations) - `) - .order('createdAt', { ascending: false }); - - if (!isAdmin(req) && req.user?.companyId) { - query = query.eq('company_id', req.user.companyId); - } - - const { data: proposals, error } = await query; - - if (error) throw error; - - const formatted = (proposals || []).map((p: ProposalRow & { User: UserRow; RiskReport: RiskReportRow[] }) => { - const riskReport = p.RiskReport?.[0]; - - return { - id: p.id, - title: p.title, - content: p.content, - status: p.status, - metadata: p.metadata || {}, - userId: p.userId, - readinessScore: riskReport?.readinessScore || 0, - riskReport: riskReport - ? { - legalRisk: riskReport.legalRisk, - pricingRisk: riskReport.pricingRisk, - structuralRisk: riskReport.structuralRisk, - findings: riskReport.findings, - recommendations: riskReport.recommendations, - } - : undefined, - createdAt: p.createdAt, - updatedAt: p.updatedAt, - }; - }); - - res.json(formatted); - } catch (error) { - console.error('Error fetching proposals:', error); - res.status(500).json({ error: 'Failed to fetch proposals' }); - } -}); - -// GET semantic search over proposal content (Phase 4). -// Returns ranked proposal ids; `available:false` when pgvector/embeddings are -// not set up yet, so the client falls back to substring search. -// NOTE: must precede GET '/:id'. -router.get('/search', requireAuth, async (req: Request, res: Response) => { - try { - const q = typeof req.query.q === 'string' ? req.query.q.trim() : ''; - if (q.length < 3) { - return res.json({ available: true, results: [] }); - } - - const queryEmbedding = await generateEmbedding(q); - if (!queryEmbedding) { - return res.json({ available: false, results: [] }); - } - - // Company scoping: admins search everything, others their company only. - const filterCompany = isAdmin(req) ? null : req.user?.companyId ?? null; - - const { data, error } = await supabase.rpc('match_proposals', { - query_embedding: queryEmbedding, - match_count: 20, - filter_company: filterCompany, - }); - - if (error) { - // RPC/extension/column not present yet โ€” signal graceful fallback. - console.warn('Semantic search unavailable (run the pgvector migration):', error.message); - return res.json({ available: false, results: [] }); - } - - const results = (data || []).map((r: { id: string; similarity: number }) => ({ - id: r.id, - similarity: r.similarity, - })); - res.json({ available: true, results }); - } catch (error) { - console.error('Error in semantic search:', error); - res.status(500).json({ error: 'Search failed' }); - } -}); - -// POST create proposal (owned by current user's company) -router.post('/', requireAuth, async (req: Request, res: Response) => { - try { - const { title, content, metadata } = req.body; - const user = req.user!; - - if (!title || !content) { - return res.status(400).json({ error: 'Title and content are required' }); - } - - const insertPayload: Record = { - id: crypto.randomUUID(), - title, - content, - status: 'PENDING', - metadata: metadata || {}, - lockedSections: [], - userId: user.id, - updatedAt: new Date().toISOString(), - }; - if (user.companyId) insertPayload.company_id = user.companyId; - - const { data: proposal, error } = await supabase - .from('Proposal') - .insert(insertPayload) - .select() - .single(); - - if (error) throw error; - - await supabase.from('AuditLog').insert({ - id: crypto.randomUUID(), - actorId: user.id, - proposalId: proposal.id, - action: 'Created proposal', - after: { title, status: 'PENDING' }, - }); - - await storeProposalEmbedding(proposal.id, `${title}\n\n${content}`); - - res.status(201).json({ - id: proposal.id, - title: proposal.title, - content: proposal.content, - status: proposal.status, - metadata: proposal.metadata, - userId: proposal.userId, - readinessScore: 0, - createdAt: proposal.createdAt, - updatedAt: proposal.updatedAt, - }); - } catch (error) { - console.error('Error creating proposal:', error); - res.status(500).json({ error: 'Failed to create proposal' }); - } -}); - -// POST generate proposal from natural language using AI -router.post('/generate', aiLimiter, requireAuth, async (req: Request, res: Response) => { - try { - const { naturalLanguageQuery } = req.body; - const user = req.user!; - - if (!naturalLanguageQuery || !naturalLanguageQuery.trim()) { - return res.status(400).json({ error: 'Natural language query is required' }); - } - - // Use AI to extract proposal details from natural language - const prompt = `You are a professional proposal generation assistant. Extract structured proposal information from the following natural language request and generate a COMPLETE, COMPLIANCE-READY business proposal. - -User Request: -${naturalLanguageQuery} - -## COMPLIANCE REQUIREMENTS (MUST FOLLOW): -1. **Payment Terms**: MAXIMUM 90 days allowed. If user specifies more, adjust to 90 days and note this in the proposal. -2. **Discount**: If no discount mentioned, set to 0%. MAXIMUM 25% discount allowed. -3. **Legal Clauses**: MUST include ALL of the following in Terms and Conditions: - - Indemnification clause - - Liability limitation clause - - Termination rights clause - - Confidentiality clause - - Intellectual property clause -4. **Minimum Deal Size**: $10,000 - -## Extract and generate: -1. Company name (required) -2. Proposal title (required) - create a professional title if not explicitly stated -3. Client name (if different from company name) -4. Deal size (if mentioned, extract as number without currency symbols) -5. Discount percentage (if mentioned, extract as number without % symbol, otherwise 0) -6. Region (if mentioned, otherwise "North America") -7. Currency (if mentioned, otherwise "USD") -8. Industry (if mentioned, otherwise "General") - -## Generate comprehensive proposal content with these sections: - -### 1. Executive Summary -Professional overview of the proposal and key value proposition. - -### 2. Proposed Solution -Detailed description of services, deliverables, and approach. - -### 3. Investment & Pricing -- Total project value -- Payment terms (MAXIMUM 90 days - adjust if user specified more) -- Any applicable discounts (0-25% range only) -- Payment schedule if applicable - -### 4. Timeline & Milestones -Project timeline with key milestones and deliverables. - -### 5. Terms & Conditions (CRITICAL - MUST INCLUDE ALL): -**Indemnification**: "Each party agrees to indemnify and hold harmless the other party from any claims, damages, or losses arising from their own negligence or breach of this agreement." - -**Liability Limitation**: "Neither party shall be liable for any indirect, incidental, special, or consequential damages. Total liability under this agreement shall not exceed the total contract value." - -**Termination Rights**: "Either party may terminate this agreement with 30 days written notice. Upon termination, client shall pay for all work completed to date." - -**Confidentiality**: "Both parties agree to maintain confidentiality of all proprietary information disclosed during this engagement." - -**Intellectual Property**: "Upon full payment, all deliverables and work product shall become the property of the client, subject to any pre-existing intellectual property rights." - -**Payment Terms**: "Payment is due within [X] days of invoice date, not exceeding 90 days." - -### 6. Acceptance & Next Steps -Clear process for proposal acceptance and project kickoff. - -Format the content with proper markdown headings (## and ###) for sections and subsections. - -Respond in JSON format: -{ - "companyName": "string (required)", - "title": "string (required)", - "content": "string (required - full proposal text with ALL sections above including complete Terms & Conditions)", - "metadata": { - "clientName": "string", - "dealSize": number or null, - "discount": number (0-25 range, default 0), - "region": "string", - "currency": "string", - "industry": "string" - } -}`; - - // Call Azure OpenAI - const completion = await client.chat.completions.create({ - model: deployment, - messages: [ - { role: 'system', content: 'You are a professional proposal writer with expertise in compliance and legal requirements. Generate complete, compliance-ready business proposals that include all required legal clauses and adhere to organizational policies. Always ensure proposals meet regulatory standards including payment terms limits (90 days max), discount thresholds (25% max), and required legal clauses (indemnification, liability limitation, termination rights, confidentiality, intellectual property). Respond only with valid JSON.' }, - { role: 'user', content: prompt } - ], - temperature: 0.7, - max_tokens: 4000, - response_format: { type: 'json_object' }, - ...llmExtraParams, - }); - - const responseContent = completion.choices[0]?.message?.content; - if (!responseContent) { - throw new Error('No response from AI'); - } - - const generated = JSON.parse(responseContent); - - if (!generated.companyName || !generated.title || !generated.content) { - return res.status(400).json({ - error: 'AI could not extract required fields (company name, title, content) from the query. Please provide more details.' - }); - } - - // Enforce compliance rules on generated data - let discount = generated.metadata?.discount != null ? Number(generated.metadata.discount) : 0; - const dealSize = generated.metadata?.dealSize != null ? Number(generated.metadata.dealSize) : null; - - // Cap discount at 25% maximum - if (discount > 25) { - discount = 25; - } - - // Ensure discount is at least 0 - if (discount < 0) { - discount = 0; - } - - // Create the proposal with generated data - const insertPayload: Record = { - id: crypto.randomUUID(), - title: generated.title, - content: generated.content, - status: 'PENDING', - metadata: { - clientName: generated.metadata?.clientName || generated.companyName, - dealSize: dealSize, - discount: discount, // Enforced 0-25% range - region: generated.metadata?.region || 'North America', - currency: generated.metadata?.currency || 'USD', - industry: generated.metadata?.industry || 'General', - }, - lockedSections: [], - userId: user.id, - updatedAt: new Date().toISOString(), - }; - if (user.companyId) insertPayload.company_id = user.companyId; - - const { data: proposal, error } = await supabase - .from('Proposal') - .insert(insertPayload) - .select() - .single(); - - if (error) throw error; - - await supabase.from('AuditLog').insert({ - id: crypto.randomUUID(), - actorId: user.id, - proposalId: proposal.id, - action: 'Created proposal from AI generation', - after: { title: generated.title, status: 'PENDING', source: 'ai-generated' }, - }); - - await storeProposalEmbedding(proposal.id, `${proposal.title}\n\n${proposal.content}`); - - res.status(201).json({ - id: proposal.id, - title: proposal.title, - content: proposal.content, - status: proposal.status, - metadata: proposal.metadata, - userId: proposal.userId, - readinessScore: 0, - createdAt: proposal.createdAt, - updatedAt: proposal.updatedAt, - }); - } catch (error) { - console.error('Error generating proposal from AI:', error); - res.status(500).json({ error: 'Failed to generate proposal from natural language' }); - } -}); - -// PUT update proposal status (admin only) -router.put('/:id/status', requireAuth, async (req: Request, res: Response) => { - try { - if (!isAdmin(req)) { - return res.status(403).json({ error: 'Only administrators can approve, reject, or mark proposals in review' }); - } - - const { id } = req.params; - const { status } = req.body; - - if (!['PENDING', 'IN_REVIEW', 'APPROVED', 'REJECTED'].includes(status)) { - return res.status(400).json({ error: 'Invalid status' }); - } - - const { data: proposal, error } = await supabase - .from('Proposal') - .update({ status, updatedAt: new Date().toISOString() }) - .eq('id', id) - .select() - .single(); - - if (error) throw error; - - await supabase.from('AuditLog').insert({ - id: crypto.randomUUID(), - actorId: req.user!.id, - proposalId: id, - action: `Changed status to ${status}`, - after: { status }, - }); - - // Notify the proposal owner of the status change (gated + best-effort). - try { - const { data: owner } = await supabase - .from('User') - .select('name, email') - .eq('id', proposal.userId) - .single(); - if (owner?.email) { - await sendEmail( - owner.email, - buildStatusChangeEmail({ - proposalTitle: proposal.title, - status, - recipientName: owner.name, - }) - ); - } - } catch (mailErr) { - console.error('Status-change email failed (non-fatal):', mailErr); - } - - res.json({ id: proposal.id, status: proposal.status }); - } catch (error) { - console.error('Error updating proposal:', error); - res.status(500).json({ error: 'Failed to update proposal' }); - } -}); - -// DELETE proposal (admin or same company) -router.delete('/:id', requireAuth, async (req: Request, res: Response) => { - try { - const { id } = req.params; - - const { data: proposal } = await supabase.from('Proposal').select('company_id').eq('id', id).single(); - if (proposal && !canAccessCompany((proposal as { company_id?: string }).company_id ?? null, req)) { - return res.status(403).json({ error: 'You do not have access to this proposal' }); - } - - await supabase.from('RiskReport').delete().eq('proposalId', id); - await supabase.from('AuditLog').delete().eq('proposalId', id); - const { error } = await supabase.from('Proposal').delete().eq('id', id); - if (error) throw error; - - res.json({ success: true }); - } catch (error) { - console.error('Error deleting proposal:', error); - res.status(500).json({ error: 'Failed to delete proposal' }); - } -}); - -// Export proposal to PDF (admin or same company) -router.get('/:id/export/pdf', requireAuth, async (req: Request, res: Response) => { - try { - const { id } = req.params; - - const { data: proposal, error } = await supabase - .from('Proposal') - .select(`*, User:userId (name, email), RiskReport (*)`) - .eq('id', id) - .single(); - - if (error || !proposal) { - return res.status(404).json({ error: 'Proposal not found' }); - } - - const proposalCompanyId = (proposal as { company_id?: string }).company_id ?? null; - if (!canAccessCompany(proposalCompanyId, req)) { - return res.status(403).json({ error: 'You do not have access to this proposal' }); - } - - const filename = `proposal-${(proposal.title || id).replace(/[^a-zA-Z0-9._-]/g, '_')}.pdf`; - - const meta = (proposal.metadata || {}) as Record; - const clientName = String(meta.clientName ?? ''); - const dealSize = meta.dealSize != null ? `$${Number(meta.dealSize).toLocaleString()}` : ''; - const discount = meta.discount != null ? `${meta.discount}%` : ''; - const region = String(meta.region ?? ''); - const industry = String(meta.industry ?? ''); - const title = proposal.title || 'Proposal'; - const date = proposal.createdAt; - const content = proposal.content || ''; - - // Extract risk report data - const riskReport = (proposal.RiskReport as RiskReportRow[])?.[0]; - const readinessScore = riskReport?.readinessScore || 0; - const legalRisk = riskReport?.legalRisk || 0; - const pricingRisk = riskReport?.pricingRisk || 0; - const structuralRisk = riskReport?.structuralRisk || 0; - const findings = (riskReport?.findings as any[]) || []; - - // Get current user info - const userInfo = proposal.User as UserRow; - const createdBy = userInfo?.name || userInfo?.email || 'System'; - - // Format date - const formattedDate = new Date(date).toLocaleDateString('en-US', { - year: 'numeric', - month: 'long', - day: 'numeric' - }); - - // Fetch active compliance rules - const { data: complianceRules } = await supabase - .from('Rule') - .select('*') - .eq('isActive', true) - .order('name'); - - const rules = (complianceRules || []) as Array<{ - name: string; - description: string; - category?: string; - severity?: string; - }>; - - const plainHtml = ` - - - - - - ${escapeHtml(title)} - - - - -
    -
    ${escapeHtml(title)}
    -
    Business Proposal
    - -
    -
    - Prepared For: - ${escapeHtml(clientName || 'Client Name')} -
    - ${industry ? ` -
    - Industry: - ${escapeHtml(industry)} -
    - ` : ''} - ${region ? ` -
    - Region: - ${escapeHtml(region)} -
    - ` : ''} -
    - Proposal Date: - ${escapeHtml(formattedDate)} -
    -
    - Reference Number: - PRO-${proposal.id.slice(0, 8).toUpperCase()} -
    -
    - Prepared By: - ${escapeHtml(createdBy)} -
    -
    - -
    - CONFIDENTIAL & PROPRIETARY
    - This proposal contains confidential business information intended solely for ${escapeHtml(clientName || 'the intended recipient')}. - Unauthorized disclosure, copying, or distribution is strictly prohibited. -
    -
    - - -
    -

    EXECUTIVE SUMMARY

    -

    - This proposal outlines a comprehensive solution designed specifically for ${escapeHtml(clientName || 'your organization')}. - Our team has carefully evaluated your requirements and developed an approach that addresses your key business objectives - while delivering measurable value and sustainable results. -

    - - ${dealSize || discount ? ` -

    Investment Overview

    - - - - - - ${dealSize ? ` - - - - - ` : ''} - ${discount ? ` - - - - - ` : ''} - ${region ? ` - - - - - ` : ''} -
    ItemDetails
    Project Investment${escapeHtml(dealSize)}
    Special Offer${escapeHtml(discount)} discount applied
    Service Region${escapeHtml(region)}
    - ` : ''} - -

    Why Partner With Us

    -

    - We bring extensive experience in ${escapeHtml(industry || 'your industry')}, combining technical expertise with - practical business understanding. Our approach is designed to minimize disruption while maximizing return on investment, - ensuring that your organization achieves its strategic goals efficiently and effectively. -

    -
    - - -
    -

    PROPOSAL OVERVIEW

    - -

    Scope of Engagement

    -

    - This section provides a high-level overview of the proposed engagement. The detailed specifications, - deliverables, and implementation approach are outlined in the following sections. -

    - - ${dealSize || discount ? ` -

    Commercial Terms Summary

    -
    - ${dealSize ? `

    Total Project Value: ${escapeHtml(dealSize)}

    ` : ''} - ${discount ? `

    Discount: ${escapeHtml(discount)} special pricing applied

    ` : ''} -

    Payment Terms: As per standard commercial agreements or as mutually agreed

    -

    Validity: This proposal is valid for 90 days from the date of issue

    -
    - ` : ''} -
    - - -
    -

    DETAILED PROPOSAL

    -
    ${markdownToHtml(content)}
    -
    - -
    - - -
    -

    IMPLEMENTATION & DELIVERY

    - -

    Project Approach

    -

    - Our implementation methodology follows industry best practices, ensuring systematic execution, - clear communication, and measurable progress throughout the engagement lifecycle. -

    - -

    Quality Assurance

    -

    - All deliverables undergo rigorous quality assurance processes to ensure they meet or exceed - established standards and specifications. We maintain comprehensive documentation throughout - the project lifecycle. -

    - -

    Project Management

    -

    - A dedicated project manager will serve as your primary point of contact, ensuring seamless - coordination, regular status updates, and proactive issue resolution throughout the engagement. -

    -
    - -
    - - -
    -

    TERMS & CONDITIONS

    - -

    Proposal Validity

    -

    - This proposal remains valid for ninety (90) days from the date of issuance. All pricing, scope, and terms - are subject to review and adjustment after this period. -

    - -

    Agreement

    -

    - This document constitutes a proposal and not a binding contractual agreement. A formal contract will be - executed upon mutual agreement of terms, signed by authorized representatives of both parties. -

    - -

    Confidentiality

    -

    - All information contained within this proposal is confidential and proprietary. Recipients agree to - maintain confidentiality and restrict disclosure to authorized decision-makers only. -

    - -

    Intellectual Property

    -

    - All intellectual property rights, including but not limited to methodologies, processes, and deliverables, - shall be addressed in the formal service agreement following proposal acceptance. -

    - -

    Changes & Modifications

    -

    - Any changes to the scope, timeline, or terms outlined in this proposal must be mutually agreed upon in - writing by authorized representatives of both parties. -

    -
    - -
    - - - ${riskReport ? ` -
    -

    APPENDIX A: QUALITY ASSURANCE & COMPLIANCE

    - -
    -

    Quality Standards

    -

    - This proposal has been developed in accordance with our quality management frameworks and - organizational standards. All recommendations and specifications align with industry best practices. -

    -
    - -

    Quality Assessment Summary

    -

    - Our internal quality review process evaluates all proposals across multiple dimensions to ensure - completeness, accuracy, and alignment with client requirements. -

    - - - - - - - - - - - - - - - - - - - - - - -
    Assessment AreaStatus
    Overall Quality Score${readinessScore}/100
    Legal & Contractual Review${100 - legalRisk}/100
    Commercial Terms Review${100 - pricingRisk}/100
    Technical Completeness${100 - structuralRisk}/100
    - - ${findings.length > 0 ? ` -

    Review Notes

    - ${findings.slice(0, 3).map((finding: any, idx: number) => ` -

    Note ${idx + 1}: ${escapeHtml(finding.message || finding.title || 'Quality review note')}

    - `).join('')} - ` : ''} - - ${rules.length > 0 ? ` -

    Applicable Standards & Policies

    -

    - This proposal has been developed in alignment with the following organizational standards: -

    -
      - ${rules.slice(0, 5).map((rule) => ` -
    • ${escapeHtml(rule.name)}: ${escapeHtml(rule.description)}
    • - `).join('')} -
    - ` : ''} -
    - ` : ''} - - -
    -

    NEXT STEPS

    - -

    - We appreciate your consideration of this proposal and look forward to the opportunity to partner with - ${escapeHtml(clientName || 'your organization')} on this initiative. -

    - -

    Proposal Review Process

    -
      -
    1. Review & Questions: Please review this proposal thoroughly. We welcome any questions or requests for clarification.
    2. -
    3. Discussion: Schedule a meeting with our team to discuss the proposal details, timeline, and any specific requirements.
    4. -
    5. Contract Execution: Upon acceptance, we will prepare formal agreements for execution by authorized signatories.
    6. -
    7. Project Kickoff: Following contract execution, we will schedule a project kickoff meeting to commence work.
    8. -
    - -
    -

    Contact Information

    -

    - For questions regarding this proposal, please contact:
    - ${escapeHtml(createdBy)}
    - Proposal Reference: PRO-${proposal.id.slice(0, 8).toUpperCase()} -

    -
    - -

    - Thank you for considering our proposal. We look forward to working with you. -

    - - -
    - - - `; - - const browser = await puppeteer.launch({ - // Memory-reduction flags so headless Chromium fits constrained hosts - // (e.g. Render free tier, 512MB). --single-process is the biggest saver. - args: [ - '--no-sandbox', - '--disable-setuid-sandbox', - '--disable-dev-shm-usage', - '--disable-gpu', - '--no-zygote', - '--single-process', - '--disable-extensions', - ], - // 'new' headless runs the regular Chrome binary; `true` (old headless) - // makes Puppeteer look for the separate chrome-headless-shell install, - // which breaks local dev where only Chrome is downloaded. - headless: 'new' - }); - const page = await browser.newPage(); - await page.setContent(plainHtml, { waitUntil: 'networkidle0' }); - const pdfBuffer = await page.pdf({ - format: 'A4', - printBackground: true, - margin: { top: '25mm', bottom: '25mm', left: '20mm', right: '20mm' }, - displayHeaderFooter: true, - headerTemplate: '
    ', - footerTemplate: ` -
    - Page of -
    - `, - preferCSSPageSize: false, - }); - await browser.close(); - - res.setHeader('Content-Type', 'application/pdf'); - res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); - res.send(pdfBuffer); - } catch (err: any) { - console.error('PDF export error:', err); - res.status(500).json({ error: 'Failed to export PDF' }); - } -}); - -// GET single proposal (admin or same company only) - MUST BE AFTER SPECIFIC ROUTES -router.get('/:id', requireAuth, async (req: Request, res: Response) => { - try { - const { id } = req.params; - - const { data: proposal, error } = await supabase - .from('Proposal') - .select(` - *, - User:userId (name, email), - RiskReport (*) - `) - .eq('id', id) - .single(); - - if (error) throw error; - if (!proposal) { - return res.status(404).json({ error: 'Proposal not found' }); - } - - const proposalCompanyId = (proposal as { company_id?: string }).company_id ?? null; - if (!canAccessCompany(proposalCompanyId, req)) { - return res.status(403).json({ error: 'You do not have access to this proposal' }); - } - - const riskReport = proposal.RiskReport?.[0]; - - res.json({ - id: proposal.id, - title: proposal.title, - content: proposal.content, - status: proposal.status, - metadata: proposal.metadata || {}, - userId: proposal.userId, - readinessScore: riskReport?.readinessScore || 0, - riskReport: riskReport ? { - legalRisk: riskReport.legalRisk, - pricingRisk: riskReport.pricingRisk, - structuralRisk: riskReport.structuralRisk, - findings: riskReport.findings, - recommendations: riskReport.recommendations, - } : null, - createdAt: proposal.createdAt, - updatedAt: proposal.updatedAt, - }); - } catch (error) { - console.error('Error fetching proposal:', error); - res.status(500).json({ error: 'Failed to fetch proposal' }); - } -}); - -export default router; - -// Simple HTML escape helper used for plain-text exports -function escapeHtml(str: any) { - if (str === null || str === undefined) return ''; - return String(str) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - +import { Router, Request, Response } from 'express'; +import { supabase } from '../lib/supabase'; +import { requireAuth, isAdmin, canAccessResource, listScope } from './middleware/auth'; +import { aiLimiter, exportLimiter } from './middleware/rateLimit'; +import { sendEmail } from './lib/email'; +import { buildStatusChangeEmail } from './lib/emailTemplates'; +import { generateEmbedding } from './lib/embeddings'; +import { getLlm } from './lib/llm'; +import { logger } from './lib/logger'; +import { buildProposalHtml, renderPdf } from './lib/proposalPdf'; +import { GENERATION_SYSTEM_PROMPT, buildGenerationPrompt, normalizeGenerated } from './lib/proposalGeneration'; +import { createProposalRecord, toCreatedResponse, type ProposalRow } from './lib/proposalStore'; + +const router = Router(); + +const STATUSES = ['PENDING', 'IN_REVIEW', 'APPROVED', 'REJECTED']; + +interface RiskReportRow { + id: string; + proposalId: string; + readinessScore: number; + legalRisk: number; + pricingRisk: number; + structuralRisk: number; + findings: unknown[]; + recommendations: unknown[]; +} + +interface UserRow { + id: string; + name: string | null; + email: string; +} + +/** The ownership fields canAccessResource needs, read off a `select('*')` row. */ +const ownership = (row: { company_id?: string | null; userId?: string | null }) => ({ + companyId: row.company_id ?? null, + ownerId: row.userId ?? null, +}); + +// GET all proposals (admin: all; others: own company, or own proposals in login mode) +router.get('/', requireAuth, async (req: Request, res: Response) => { + try { + let query = supabase + .from('Proposal') + .select(` + *, + User:userId (name, email), + RiskReport (readinessScore, legalRisk, pricingRisk, structuralRisk, findings, recommendations) + `) + .order('createdAt', { ascending: false }); + + const scope = listScope(req); + if (scope) { + query = query.eq(scope.column, scope.value); + } + + const { data: proposals, error } = await query; + + if (error) throw error; + + const formatted = (proposals || []).map((p: ProposalRow & { User: UserRow; RiskReport: RiskReportRow[] }) => { + const riskReport = p.RiskReport?.[0]; + + return { + id: p.id, + title: p.title, + content: p.content, + status: p.status, + metadata: p.metadata || {}, + userId: p.userId, + readinessScore: riskReport?.readinessScore || 0, + riskReport: riskReport + ? { + legalRisk: riskReport.legalRisk, + pricingRisk: riskReport.pricingRisk, + structuralRisk: riskReport.structuralRisk, + findings: riskReport.findings, + recommendations: riskReport.recommendations, + } + : undefined, + createdAt: p.createdAt, + updatedAt: p.updatedAt, + }; + }); + + res.json(formatted); + } catch (error) { + logger.error('Error fetching proposals:', error); + res.status(500).json({ error: 'Failed to fetch proposals' }); + } +}); + +// GET semantic search over proposal content (Phase 4). +// Returns ranked proposal ids; `available:false` when pgvector/embeddings are +// not set up yet, so the client falls back to substring search. +// NOTE: must precede GET '/:id'. +router.get('/search', requireAuth, async (req: Request, res: Response) => { + try { + const q = typeof req.query.q === 'string' ? req.query.q.trim() : ''; + if (q.length < 3) { + return res.json({ available: true, results: [] }); + } + + const queryEmbedding = await generateEmbedding(q); + if (!queryEmbedding) { + return res.json({ available: false, results: [] }); + } + + // Company scoping: admins search everything, others their company only. + const scope = listScope(req); + const filterCompany = scope?.column === 'company_id' ? scope.value : null; + + const { data, error } = await supabase.rpc('match_proposals', { + query_embedding: queryEmbedding, + match_count: 20, + filter_company: filterCompany, + }); + + if (error) { + // RPC/extension/column not present yet โ€” signal graceful fallback. + logger.warn('Semantic search unavailable (run the pgvector migration):', error.message); + return res.json({ available: false, results: [] }); + } + + let results = (data || []).map((r: { id: string; similarity: number }) => ({ + id: r.id, + similarity: r.similarity, + })); + + // Users with no company (login mode) may only see what they own. + if (scope?.column === 'userId') { + const { data: owned } = await supabase.from('Proposal').select('id').eq('userId', scope.value); + const ownedIds = new Set((owned || []).map((p: { id: string }) => p.id)); + results = results.filter((r: { id: string }) => ownedIds.has(r.id)); + } + + res.json({ available: true, results }); + } catch (error) { + logger.error('Error in semantic search:', error); + res.status(500).json({ error: 'Search failed' }); + } +}); + +// POST create proposal (owned by current user's company) +router.post('/', requireAuth, async (req: Request, res: Response) => { + try { + const { title, content, metadata } = req.body; + + if (!title || !content) { + return res.status(400).json({ error: 'Title and content are required' }); + } + + const proposal = await createProposalRecord( + req.user!, + { title, content, metadata }, + { action: 'Created proposal', after: { title, status: 'PENDING' } } + ); + + res.status(201).json(toCreatedResponse(proposal)); + } catch (error) { + logger.error('Error creating proposal:', error); + res.status(500).json({ error: 'Failed to create proposal' }); + } +}); + +// POST generate proposal from natural language using AI +router.post('/generate', aiLimiter, requireAuth, async (req: Request, res: Response) => { + try { + const { naturalLanguageQuery } = req.body; + + if (typeof naturalLanguageQuery !== 'string' || !naturalLanguageQuery.trim()) { + return res.status(400).json({ error: 'Natural language query is required' }); + } + + const llm = getLlm(); + if (!llm) { + return res.status(424).json({ + error: 'AI generation is not configured on this server. Set GEMINI_API_KEY (or the Azure OpenAI variables).', + code: 'AI_UNAVAILABLE', + }); + } + + let responseContent: string | null | undefined; + try { + const completion = await llm.client.chat.completions.create( + { + model: llm.model, + messages: [ + { role: 'system', content: GENERATION_SYSTEM_PROMPT }, + { role: 'user', content: buildGenerationPrompt(naturalLanguageQuery) }, + ], + temperature: 0.7, + max_tokens: 4000, + response_format: { type: 'json_object' }, + ...llm.extraParams, + }, + { timeout: 60_000, maxRetries: 1 } + ); + responseContent = completion.choices[0]?.message?.content; + } catch (aiError) { + logger.error('AI provider call failed during generation:', aiError); + return res.status(424).json({ + error: 'The AI provider could not be reached. Please try again shortly.', + code: 'AI_UNAVAILABLE', + }); + } + + if (!responseContent) { + throw new Error('No response from AI'); + } + + let raw: unknown; + try { + raw = JSON.parse(responseContent); + } catch { + return res.status(502).json({ error: 'The AI returned an unreadable response. Please try again.' }); + } + + // Never trust the model's numbers: validate and clamp them in code. + const generated = normalizeGenerated(raw); + if (!generated) { + return res.status(400).json({ + error: 'AI could not extract required fields (company name, title, content) from the query. Please provide more details.', + }); + } + + const proposal = await createProposalRecord( + req.user!, + { title: generated.title, content: generated.content, metadata: generated.metadata }, + { + action: 'Created proposal from AI generation', + after: { title: generated.title, status: 'PENDING', source: 'ai-generated' }, + } + ); + + res.status(201).json(toCreatedResponse(proposal)); + } catch (error) { + logger.error('Error generating proposal from AI:', error); + res.status(500).json({ error: 'Failed to generate proposal from natural language' }); + } +}); + +// PUT update proposal status (admin only) +router.put('/:id/status', requireAuth, async (req: Request, res: Response) => { + try { + if (!isAdmin(req)) { + return res.status(403).json({ error: 'Only administrators can approve, reject, or mark proposals in review' }); + } + + const { id } = req.params; + const { status } = req.body; + + if (!STATUSES.includes(status)) { + return res.status(400).json({ error: 'Invalid status' }); + } + + const { data: proposal, error } = await supabase + .from('Proposal') + .update({ status, updatedAt: new Date().toISOString() }) + .eq('id', id) + .select() + .single(); + + if (error) throw error; + + await supabase.from('AuditLog').insert({ + id: crypto.randomUUID(), + actorId: req.user!.id, + proposalId: id, + action: `Changed status to ${status}`, + after: { status }, + }); + + // Notify the proposal owner of the status change (gated + best-effort). + try { + const { data: owner } = await supabase + .from('User') + .select('name, email') + .eq('id', proposal.userId) + .single(); + if (owner?.email) { + await sendEmail( + owner.email, + buildStatusChangeEmail({ + proposalTitle: proposal.title, + status, + recipientName: owner.name, + }) + ); + } + } catch (mailErr) { + logger.error('Status-change email failed (non-fatal):', mailErr); + } + + res.json({ id: proposal.id, status: proposal.status }); + } catch (error) { + logger.error('Error updating proposal:', error); + res.status(500).json({ error: 'Failed to update proposal' }); + } +}); + +// DELETE proposal (admin or same company; the owner in login mode) +router.delete('/:id', requireAuth, async (req: Request, res: Response) => { + try { + const { id } = req.params; + + const { data: proposal } = await supabase.from('Proposal').select('*').eq('id', id).single(); + if (proposal && !canAccessResource(ownership(proposal), req)) { + return res.status(403).json({ error: 'You do not have access to this proposal' }); + } + + await supabase.from('RiskReport').delete().eq('proposalId', id); + await supabase.from('AuditLog').delete().eq('proposalId', id); + const { error } = await supabase.from('Proposal').delete().eq('id', id); + if (error) throw error; + + res.json({ success: true }); + } catch (error) { + logger.error('Error deleting proposal:', error); + res.status(500).json({ error: 'Failed to delete proposal' }); + } +}); + +// Export proposal to PDF (admin or same company) +router.get('/:id/export/pdf', exportLimiter, requireAuth, async (req: Request, res: Response) => { + try { + const { id } = req.params; + + const { data: proposal, error } = await supabase + .from('Proposal') + .select(`*, User:userId (name, email), RiskReport (*)`) + .eq('id', id) + .single(); + + if (error || !proposal) { + return res.status(404).json({ error: 'Proposal not found' }); + } + + if (!canAccessResource(ownership(proposal), req)) { + return res.status(403).json({ error: 'You do not have access to this proposal' }); + } + + const { data: complianceRules } = await supabase + .from('Rule') + .select('*') + .eq('isActive', true) + .order('name'); + + const riskReport = (proposal.RiskReport as RiskReportRow[] | null)?.[0]; + const author = proposal.User as UserRow | null; + + const html = buildProposalHtml({ + id: proposal.id, + title: proposal.title, + content: proposal.content, + createdAt: proposal.createdAt, + metadata: (proposal.metadata || {}) as Record, + createdBy: author?.name || author?.email || 'System', + riskReport: riskReport + ? { + readinessScore: riskReport.readinessScore, + legalRisk: riskReport.legalRisk, + pricingRisk: riskReport.pricingRisk, + structuralRisk: riskReport.structuralRisk, + findings: (riskReport.findings || []) as Array<{ message?: string; title?: string }>, + } + : null, + rules: (complianceRules || []) as Array<{ name: string; description: string }>, + }); + + const pdfBuffer = await renderPdf(html); + + const filename = `proposal-${(proposal.title || id).replace(/[^a-zA-Z0-9._-]/g, '_')}.pdf`; + res.setHeader('Content-Type', 'application/pdf'); + res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); + res.send(pdfBuffer); + } catch (err) { + logger.error('PDF export error:', err); + res.status(500).json({ error: 'Failed to export PDF' }); + } +}); + +// GET single proposal (admin or same company only) - MUST BE AFTER SPECIFIC ROUTES +router.get('/:id', requireAuth, async (req: Request, res: Response) => { + try { + const { id } = req.params; + + const { data: proposal, error } = await supabase + .from('Proposal') + .select(` + *, + User:userId (name, email), + RiskReport (*) + `) + .eq('id', id) + .single(); + + if (error) throw error; + if (!proposal) { + return res.status(404).json({ error: 'Proposal not found' }); + } + + if (!canAccessResource(ownership(proposal), req)) { + return res.status(403).json({ error: 'You do not have access to this proposal' }); + } + + const riskReport = proposal.RiskReport?.[0]; + + res.json({ + id: proposal.id, + title: proposal.title, + content: proposal.content, + status: proposal.status, + metadata: proposal.metadata || {}, + userId: proposal.userId, + readinessScore: riskReport?.readinessScore || 0, + riskReport: riskReport ? { + legalRisk: riskReport.legalRisk, + pricingRisk: riskReport.pricingRisk, + structuralRisk: riskReport.structuralRisk, + findings: riskReport.findings, + recommendations: riskReport.recommendations, + } : null, + createdAt: proposal.createdAt, + updatedAt: proposal.updatedAt, + }); + } catch (error) { + logger.error('Error fetching proposal:', error); + res.status(500).json({ error: 'Failed to fetch proposal' }); + } +}); + +export default router; diff --git a/tests/analyze.test.ts b/tests/analyze.test.ts new file mode 100644 index 0000000..83cbc41 --- /dev/null +++ b/tests/analyze.test.ts @@ -0,0 +1,372 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +const { getLlmMock, createMock } = vi.hoisted(() => ({ getLlmMock: vi.fn(), createMock: vi.fn() })); +vi.mock('../src/api/lib/llm', () => ({ getLlm: getLlmMock })); + +import * as supabaseModule from '../src/lib/supabase'; +import analyzeRouter from '../src/api/analyze'; +import { resetDefaultUser } from '../src/api/middleware/auth'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; + +const BAD_CONTENT = `Website Update Proposal + +Overview +Quick website update for SmallBiz LLC. + +Pricing +Total Cost: $8,500 +Special Discount: 35% +Final Price: $5,525 USD +Payment Terms: Net 120 days`; + +const GOOD_AI_ANALYSIS = { + readinessScore: 92, + legalRisk: 8, + pricingRisk: 12, + structuralRisk: 10, + findings: [{ type: 'INFO', level: 'LOW', message: 'Looks fine', location: 'Document' }], + recommendations: [], +}; + +const ADMIN = { id: 'admin1', email: 'admin@b.com', role: 'ADMIN', company_id: null }; +const REP_C1 = { id: 'rep1', email: 'rep@b.com', role: 'SALES_REP', company_id: 'c1' }; + +function proposal(over: Record = {}) { + return { + id: 'p1', + title: 'Website Update Proposal', + content: BAD_CONTENT, + status: 'PENDING', + metadata: { clientName: 'SmallBiz LLC' }, + userId: 'owner1', + company_id: null, + ...over, + }; +} + +/** Wire the mock database: who is signed in, which proposals exist, and any existing report. */ +function seed(opts: { + user?: Record; + proposals?: Record>; + existingReportId?: string; + rules?: unknown[]; +}) { + const user = opts.user ?? ADMIN; + const proposals = opts.proposals ?? { p1: proposal() }; + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select') return { data: [user] }; + if (ctx.table === 'Proposal' && ctx.op === 'select') { + const id = ctx.filters.find(([, col]) => col === 'id')?.[2] as string; + return proposals[id] ? { data: proposals[id] } : { data: null, error: { code: 'PGRST116', message: 'no rows' } }; + } + if (ctx.table === 'Rule' && ctx.op === 'select') return { data: opts.rules ?? [] }; + if (ctx.table === 'RiskReport' && ctx.op === 'select') { + return { data: opts.existingReportId ? [{ id: opts.existingReportId }] : [] }; + } + if (ctx.table === 'RiskReport' && (ctx.op === 'insert' || ctx.op === 'update')) { + return { data: { id: opts.existingReportId ?? 'rr-new', ...(ctx.payload as object) } }; + } + return undefined; + }); +} + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/analyze', analyzeRouter); + return app; +} + +const useAi = (reply: unknown) => { + createMock.mockResolvedValue({ + choices: [{ message: { content: typeof reply === 'string' ? reply : JSON.stringify(reply) } }], + }); +}; + +const savedMode = process.env.ANALYSIS_MODE; + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + createMock.mockReset(); + getLlmMock.mockReset(); + getLlmMock.mockReturnValue({ + provider: 'gemini', + model: 'test-model', + client: { chat: { completions: { create: createMock } } }, + extraParams: { reasoning_effort: 'none' }, + }); + delete process.env.ANALYSIS_MODE; + delete process.env.AUTH_MODE; +}); + +afterEach(() => { + if (savedMode === undefined) delete process.env.ANALYSIS_MODE; + else process.env.ANALYSIS_MODE = savedMode; +}); + +describe('POST /api/analyze/:id with a working AI', () => { + it('stores the AI report and labels it as AI-generated', async () => { + seed({}); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(200); + expect(res.body.analysisSource).toBe('ai'); + expect(res.body.riskReport).toMatchObject({ readinessScore: 92, legalRisk: 8, pricingRisk: 12 }); + + const sent = createMock.mock.calls[0][0]; + expect(sent.model).toBe('test-model'); + expect(sent.response_format).toEqual({ type: 'json_object' }); + expect(sent.reasoning_effort).toBe('none'); + expect(sent.messages[1].content).toContain('Website Update Proposal'); + + const insert = sb.callsFor('RiskReport', 'insert')[0]; + expect(insert.payload).toMatchObject({ proposalId: 'p1', readinessScore: 92 }); + }); + + it('updates the existing report instead of inserting a duplicate', async () => { + seed({ existingReportId: 'rr-1' }); + useAi(GOOD_AI_ANALYSIS); + + await request(buildApp()).post('/api/analyze/p1'); + + expect(sb.callsFor('RiskReport', 'insert')).toHaveLength(0); + const update = sb.callsFor('RiskReport', 'update')[0]; + expect(update.filters).toContainEqual(['eq', 'id', 'rr-1']); + }); + + it('never writes a readinessScore column to Proposal (it does not exist there)', async () => { + seed({}); + useAi(GOOD_AI_ANALYSIS); + + await request(buildApp()).post('/api/analyze/p1'); + + const update = sb.callsFor('Proposal', 'update')[0]; + expect(update.payload).not.toHaveProperty('readinessScore'); + expect(update.payload).toHaveProperty('updatedAt'); + }); + + it('advances a healthy PENDING proposal to IN_REVIEW', async () => { + seed({}); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.statusAdvanced).toBe(true); + expect(sb.callsFor('Proposal', 'update')[0].payload).toMatchObject({ status: 'IN_REVIEW' }); + }); + + it('does not move an already-approved proposal back to IN_REVIEW', async () => { + seed({ proposals: { p1: proposal({ status: 'APPROVED' }) } }); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.statusAdvanced).toBe(false); + expect(sb.callsFor('Proposal', 'update')[0].payload).not.toHaveProperty('status'); + }); + + it('does not advance a low-scoring proposal', async () => { + seed({}); + useAi({ ...GOOD_AI_ANALYSIS, readinessScore: 40 }); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.statusAdvanced).toBe(false); + }); + + it('keeps a genuine zero risk score instead of replacing it with a default', async () => { + seed({}); + useAi({ ...GOOD_AI_ANALYSIS, legalRisk: 0, pricingRisk: 0 }); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.riskReport).toMatchObject({ legalRisk: 0, pricingRisk: 0 }); + }); + + it('puts the active rules into the prompt', async () => { + seed({ rules: [{ name: 'Max discount', description: 'No more than 25%', logic: { maxDiscount: 25 } }] }); + useAi(GOOD_AI_ANALYSIS); + + await request(buildApp()).post('/api/analyze/p1'); + + expect(createMock.mock.calls[0][0].messages[1].content).toContain('- Max discount: No more than 25%'); + }); +}); + +describe('POST /api/analyze/:id when the AI is unavailable', () => { + it('falls back to the rule checker when the provider errors', async () => { + seed({}); + createMock.mockRejectedValue(new Error('getaddrinfo ENOTFOUND')); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(200); + expect(res.body.analysisSource).toBe('rules'); + const types = (res.body.riskReport.findings as Array<{ type: string; level: string }>).map((f) => f.type); + expect(types).toEqual(expect.arrayContaining(['DISCOUNT VIOLATION', 'DEAL SIZE', 'PAYMENT TERMS', 'ANALYSIS MODE'])); + // The 35% discount / $5,525 / Net 120 proposal must not look ready. + expect(res.body.riskReport.readinessScore).toBeLessThan(60); + expect(res.body.statusAdvanced).toBe(false); + }); + + it('falls back when the model returns truncated or invalid JSON', async () => { + seed({}); + useAi('{"readinessScore": 80, "findings": [{"message": "unterminated'); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(200); + expect(res.body.analysisSource).toBe('rules'); + }); + + it('falls back when the model returns an empty body', async () => { + seed({}); + createMock.mockResolvedValue({ choices: [{ message: { content: '' } }] }); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.analysisSource).toBe('rules'); + }); + + it('uses the rule checker when no AI is configured, without calling anything', async () => { + seed({}); + getLlmMock.mockReturnValue(null); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(200); + expect(res.body.analysisSource).toBe('rules'); + expect(createMock).not.toHaveBeenCalled(); + }); + + it('honours ANALYSIS_MODE=rules even when an AI is configured', async () => { + seed({}); + process.env.ANALYSIS_MODE = 'rules'; + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.body.analysisSource).toBe('rules'); + expect(createMock).not.toHaveBeenCalled(); + }); + + it('applies thresholds from the active rules in fallback mode', async () => { + seed({ + proposals: { p1: proposal({ content: 'Pricing\nTotal Investment: $80,000\nDiscount: 12%\nPayment due within 30 days.' }) }, + rules: [{ name: 'Strict discount', description: 'Max 10%', logic: { maxDiscount: 10 } }], + }); + getLlmMock.mockReturnValue(null); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + const types = (res.body.riskReport.findings as Array<{ type: string }>).map((f) => f.type); + expect(types).toContain('DISCOUNT VIOLATION'); + }); +}); + +describe('access control', () => { + it('404s for an unknown proposal', async () => { + seed({}); + const res = await request(buildApp()).post('/api/analyze/missing'); + expect(res.status).toBe(404); + }); + + it("403s for another company's proposal", async () => { + seed({ user: REP_C1, proposals: { p1: proposal({ company_id: 'c2' }) } }); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(403); + expect(createMock).not.toHaveBeenCalled(); + }); + + it('allows a member of the proposalโ€™s company', async () => { + seed({ user: REP_C1, proposals: { p1: proposal({ company_id: 'c1' }) } }); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/p1'); + + expect(res.status).toBe(200); + }); +}); + +describe('POST /api/analyze/bulk', () => { + it('rejects a missing or empty id list', async () => { + seed({}); + expect((await request(buildApp()).post('/api/analyze/bulk').send({})).status).toBe(400); + expect((await request(buildApp()).post('/api/analyze/bulk').send({ ids: [] })).status).toBe(400); + expect((await request(buildApp()).post('/api/analyze/bulk').send({ ids: [1, null, ''] })).status).toBe(400); + }); + + it('rejects more than the per-request limit', async () => { + seed({}); + const ids = Array.from({ length: 11 }, (_, i) => `p${i}`); + const res = await request(buildApp()).post('/api/analyze/bulk').send({ ids }); + expect(res.status).toBe(400); + expect(res.body.error).toMatch(/at most 10/i); + }); + + it('analyzes each proposal and reports per-item results, including failures', async () => { + seed({ proposals: { p1: proposal({ id: 'p1' }), p2: proposal({ id: 'p2', status: 'APPROVED' }) } }); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/bulk').send({ ids: ['p1', 'p2', 'ghost'] }); + + expect(res.status).toBe(200); + expect(res.body.summary).toEqual({ requested: 3, analyzed: 2, failed: 1 }); + expect(res.body.results).toEqual([ + expect.objectContaining({ proposalId: 'p1', ok: true, analysisSource: 'ai', readinessScore: 92, statusAdvanced: true }), + expect.objectContaining({ proposalId: 'p2', ok: true, statusAdvanced: false }), + { proposalId: 'ghost', ok: false, error: 'Proposal not found' }, + ]); + }); + + it('analyzes a repeated id once', async () => { + seed({}); + useAi(GOOD_AI_ANALYSIS); + + const res = await request(buildApp()).post('/api/analyze/bulk').send({ ids: ['p1', 'p1', 'p1'] }); + + expect(res.body.summary.requested).toBe(1); + expect(createMock).toHaveBeenCalledTimes(1); + }); + + it('is not shadowed by the /:proposalId route', async () => { + seed({}); + const res = await request(buildApp()).post('/api/analyze/bulk').send({ ids: ['p1'] }); + expect(res.status).toBe(200); + expect(res.body).toHaveProperty('results'); + }); +}); + +describe('GET /api/analyze/mode', () => { + it('reports the AI provider when configured', async () => { + seed({}); + const res = await request(buildApp()).get('/api/analyze/mode'); + expect(res.body).toEqual({ mode: 'ai', provider: 'gemini', model: 'test-model' }); + }); + + it('reports rules when no AI is configured or ANALYSIS_MODE=rules', async () => { + seed({}); + getLlmMock.mockReturnValue(null); + expect((await request(buildApp()).get('/api/analyze/mode')).body.mode).toBe('rules'); + + getLlmMock.mockReturnValue({ provider: 'azure', model: 'x', client: {}, extraParams: {} }); + process.env.ANALYSIS_MODE = 'rules'; + expect((await request(buildApp()).get('/api/analyze/mode')).body.mode).toBe('rules'); + }); +}); diff --git a/tests/helpers/supabaseMock.ts b/tests/helpers/supabaseMock.ts new file mode 100644 index 0000000..4a79c98 --- /dev/null +++ b/tests/helpers/supabaseMock.ts @@ -0,0 +1,158 @@ +/** + * A table-aware stand-in for the Supabase client. + * + * Every query-builder method returns the same thenable builder, so any chain the + * code under test writes (`.from('X').select().eq().order().limit()` ...) works, + * and awaiting it โ€” or calling `.single()` / `.maybeSingle()` โ€” resolves with + * whatever the test's handler returns for that query. + * + * const sb = createSupabaseMock(); + * sb.handle(({ table, op }) => (table === 'Rule' && op === 'select' ? { data: [rule] } : undefined)); + * + * A handler that returns `undefined` falls through to the next handler; with none + * left the query resolves to `{ data: [], error: null }` (or `data: null` for + * `.single()`/`.maybeSingle()`), i.e. "no rows". + */ + +import { vi } from 'vitest'; + +export type Op = 'select' | 'insert' | 'update' | 'upsert' | 'delete' | 'rpc'; + +export interface QueryContext { + table: string; + op: Op; + /** Columns passed to the *first* select(); '*' if none. */ + columns: string; + /** Every `.eq/.neq/.in/.is/.not/.or` call, as [method, column, value]. */ + filters: Array<[string, string, unknown]>; + payload?: unknown; + single: boolean; + limit?: number; + order?: Array<[string, unknown]>; +} + +export interface Result { + data?: unknown; + error?: unknown; +} + +export type Handler = (ctx: QueryContext) => Result | undefined | Promise; + +/** The fluent query builder; filter methods (eq, in, ...) are attached dynamically. */ +interface Builder extends PromiseLike<{ data: unknown; error: unknown }> { + select(columns?: string): Builder; + order(column: string, opts?: unknown): Builder; + limit(n: number): Builder; + single(): Builder; + maybeSingle(): Builder; + [filter: string]: unknown; +} + +export function createSupabaseMock() { + const handlers: Handler[] = []; + const calls: QueryContext[] = []; + + async function resolve(ctx: QueryContext): Promise<{ data: unknown; error: unknown }> { + calls.push(ctx); + for (let i = handlers.length - 1; i >= 0; i--) { + const result = await handlers[i](ctx); + if (result !== undefined) return { data: result.data ?? null, error: result.error ?? null }; + } + return { data: ctx.single ? null : [], error: null }; + } + + function makeBuilder(table: string, op: Op, payload?: unknown) { + const ctx: QueryContext = { table, op, columns: '*', filters: [], payload, single: false }; + let selectedOnce = false; + // The real client's builder is fluent: every method hands back the same object. + const builder = {} as Builder; + + builder.select = (columns?: string) => { + if (!selectedOnce && op === 'select') ctx.columns = columns ?? '*'; + selectedOnce = true; + return builder; + }; + for (const m of ['eq', 'neq', 'in', 'is', 'not', 'or', 'gt', 'gte', 'lt', 'lte', 'ilike', 'like', 'contains']) { + builder[m] = (column: string, ...rest: unknown[]) => { + ctx.filters.push([m, column, rest.length > 1 ? rest : rest[0]]); + return builder; + }; + } + builder.order = (column: string, opts?: unknown) => { + (ctx.order ||= []).push([column, opts]); + return builder; + }; + builder.limit = (n: number) => { + ctx.limit = n; + return builder; + }; + builder.single = () => { + ctx.single = true; + return builder; + }; + builder.maybeSingle = builder.single; + builder.then = (onFulfilled: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) => + resolve(ctx).then(onFulfilled, onRejected); + return builder; + } + + // Storage: spies with working defaults; tests override per case with mockResolvedValueOnce etc. + const storage = { + upload: vi.fn(), + download: vi.fn(), + remove: vi.fn(), + createSignedUrl: vi.fn(), + getPublicUrl: vi.fn(), + from: vi.fn(), + }; + const installStorageDefaults = () => { + storage.upload.mockImplementation(async (path: string) => ({ data: { path }, error: null })); + storage.download.mockImplementation(async () => ({ data: new Blob(['file bytes']), error: null })); + storage.remove.mockImplementation(async () => ({ data: [], error: null })); + storage.createSignedUrl.mockImplementation(async (path: string) => ({ + data: { signedUrl: `https://signed.example/${path}?token=t` }, + error: null, + })); + storage.getPublicUrl.mockImplementation((path: string) => ({ + data: { publicUrl: `https://public.example/${path}` }, + })); + storage.from.mockImplementation(() => storage); + }; + installStorageDefaults(); + + const client = { + from: (table: string) => ({ + select: (columns?: string) => makeBuilder(table, 'select').select(columns), + insert: (payload: unknown) => makeBuilder(table, 'insert', payload), + update: (payload: unknown) => makeBuilder(table, 'update', payload), + upsert: (payload: unknown) => makeBuilder(table, 'upsert', payload), + delete: () => makeBuilder(table, 'delete'), + }), + rpc: (name: string, args?: unknown) => makeBuilder(`rpc:${name}`, 'rpc', args), + storage, + }; + + return { + client, + calls, + /** The storage spies (`upload`, `download`, ...) behind `client.storage.from(bucket)`. */ + storage, + /** Add a handler; later handlers take precedence over earlier ones. */ + handle(handler: Handler) { + handlers.push(handler); + }, + /** Forget handlers and recorded calls, and restore the default storage behaviour. */ + reset() { + handlers.length = 0; + calls.length = 0; + for (const spy of Object.values(storage)) spy.mockReset(); + installStorageDefaults(); + }, + /** Recorded calls matching a table (and optionally an op). */ + callsFor(table: string, op?: Op) { + return calls.filter((c) => c.table === table && (!op || c.op === op)); + }, + }; +} + +export type SupabaseMock = ReturnType; diff --git a/tests/proposals.test.ts b/tests/proposals.test.ts new file mode 100644 index 0000000..8f6c0d4 --- /dev/null +++ b/tests/proposals.test.ts @@ -0,0 +1,428 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import type { SupabaseMock, QueryContext } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +const { getLlmMock, createMock, embedMock, sendEmailMock, renderPdfMock } = vi.hoisted(() => ({ + getLlmMock: vi.fn(), + createMock: vi.fn(), + embedMock: vi.fn(), + sendEmailMock: vi.fn(), + renderPdfMock: vi.fn(), +})); +vi.mock('../src/api/lib/llm', () => ({ getLlm: getLlmMock })); +vi.mock('../src/api/lib/embeddings', () => ({ generateEmbedding: embedMock, EMBEDDING_DIM: 1536 })); +vi.mock('../src/api/lib/email', () => ({ sendEmail: sendEmailMock })); +vi.mock('../src/api/lib/proposalPdf', async (importOriginal) => ({ + ...(await importOriginal()), + renderPdf: renderPdfMock, +})); + +import * as supabaseModule from '../src/lib/supabase'; +import proposalsRouter from '../src/api/proposals'; +import { resetDefaultUser } from '../src/api/middleware/auth'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; + +const ADMIN = { id: 'admin1', email: 'admin@b.com', role: 'ADMIN', company_id: null }; +const REP_C1 = { id: 'rep1', email: 'rep@b.com', role: 'SALES_REP', company_id: 'c1' }; +const LONER = { id: 'loner1', email: 'l@b.com', role: 'SALES_REP', company_id: null }; + +const row = (over: Record = {}) => ({ + id: 'p1', + title: 'Cloud Migration', + content: 'Body text', + status: 'PENDING', + metadata: { clientName: 'Acme', dealSize: 50000, discount: 10 }, + userId: 'owner1', + company_id: null, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-02T00:00:00.000Z', + ...over, +}); + +/** Mock database: the signed-in (default) user plus a map of proposals by id. */ +function seed(user: Record = ADMIN, proposals: Record> = { p1: row() }) { + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select' && !ctx.single) return { data: [user] }; + if (ctx.table === 'Proposal' && ctx.op === 'select' && ctx.single) { + const id = ctx.filters.find(([, col]) => col === 'id')?.[2] as string; + return proposals[id] + ? { data: { ...proposals[id], User: { name: 'Owner', email: 'owner@b.com' }, RiskReport: [] } } + : { data: null, error: { code: 'PGRST116', message: 'no rows' } }; + } + if (ctx.table === 'Proposal' && ctx.op === 'select') return { data: Object.values(proposals) }; + if (ctx.table === 'Proposal' && ctx.op === 'insert') { + return { data: { ...(ctx.payload as object), createdAt: '2026-02-01T00:00:00.000Z' } }; + } + if (ctx.table === 'Proposal' && ctx.op === 'update' && ctx.single) { + const id = ctx.filters.find(([, col]) => col === 'id')?.[2] as string; + return { data: { ...proposals[id], ...(ctx.payload as object) } }; + } + return undefined; + }); +} + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/proposals', proposalsRouter); + return app; +} + +const lastCall = (table: string, op: QueryContext['op']) => sb.callsFor(table, op).at(-1); + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + for (const m of [getLlmMock, createMock, embedMock, sendEmailMock, renderPdfMock]) m.mockReset(); + getLlmMock.mockReturnValue({ + provider: 'gemini', + model: 'test-model', + client: { chat: { completions: { create: createMock } } }, + extraParams: {}, + }); + embedMock.mockResolvedValue(null); // embeddings off unless a test turns them on + delete process.env.AUTH_MODE; +}); + +afterEach(() => { + delete process.env.AUTH_MODE; +}); + +describe('GET /api/proposals', () => { + it('returns every proposal to an admin, unfiltered', async () => { + seed(ADMIN); + const res = await request(buildApp()).get('/api/proposals'); + expect(res.status).toBe(200); + expect(res.body).toHaveLength(1); + expect(lastCall('Proposal', 'select')!.filters).toEqual([]); + }); + + it('narrows a company member to their company', async () => { + seed(REP_C1); + await request(buildApp()).get('/api/proposals'); + expect(lastCall('Proposal', 'select')!.filters).toContainEqual(['eq', 'company_id', 'c1']); + }); + + it('keeps legacy behaviour for a company-less non-admin in demo mode (no filter)', async () => { + seed(LONER); + await request(buildApp()).get('/api/proposals'); + expect(lastCall('Proposal', 'select')!.filters).toEqual([]); + }); + + it('narrows a company-less user to their own proposals in login mode', async () => { + process.env.AUTH_MODE = 'login'; + const jwt = (await import('jsonwebtoken')).default; + // requireAuth loads the token user with .single() on the User table. + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.single) return { data: LONER }; + if (ctx.table === 'Proposal' && ctx.op === 'select') return { data: [] }; + return undefined; + }); + const token = jwt.sign({ userId: 'loner1' }, process.env.NEXTAUTH_SECRET as string, { expiresIn: '1h' }); + + const res = await request(buildApp()).get('/api/proposals').set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(lastCall('Proposal', 'select')!.filters).toContainEqual(['eq', 'userId', 'loner1']); + }); + + it('maps the risk report into the response', async () => { + sb.handle((ctx) => { + if (ctx.table === 'User') return { data: [ADMIN] }; + if (ctx.table === 'Proposal' && ctx.op === 'select') { + return { + data: [ + { + ...row(), + User: { name: 'Owner', email: 'o@b.com' }, + RiskReport: [{ readinessScore: 77, legalRisk: 1, pricingRisk: 2, structuralRisk: 3, findings: [], recommendations: [] }], + }, + ], + }; + } + return undefined; + }); + const res = await request(buildApp()).get('/api/proposals'); + expect(res.body[0]).toMatchObject({ id: 'p1', readinessScore: 77, riskReport: { legalRisk: 1, pricingRisk: 2 } }); + }); +}); + +describe('GET /api/proposals/search', () => { + it('returns an empty, available result for very short queries without embedding', async () => { + seed(); + const res = await request(buildApp()).get('/api/proposals/search?q=ab'); + expect(res.body).toEqual({ available: true, results: [] }); + expect(embedMock).not.toHaveBeenCalled(); + }); + + it('reports unavailable when embeddings cannot be generated', async () => { + seed(); + embedMock.mockResolvedValue(null); + const res = await request(buildApp()).get('/api/proposals/search?q=payment+terms'); + expect(res.body).toEqual({ available: false, results: [] }); + }); + + it('returns ranked ids from match_proposals, scoped to the company', async () => { + seed(REP_C1); + embedMock.mockResolvedValue([0.1, 0.2]); + sb.handle((ctx) => (ctx.table === 'rpc:match_proposals' ? { data: [{ id: 'p1', similarity: 0.91 }] } : undefined)); + + const res = await request(buildApp()).get('/api/proposals/search?q=payment+terms'); + + expect(res.body).toEqual({ available: true, results: [{ id: 'p1', similarity: 0.91 }] }); + expect(sb.callsFor('rpc:match_proposals')[0].payload).toMatchObject({ filter_company: 'c1', match_count: 20 }); + }); + + it('degrades to unavailable when the pgvector function is missing', async () => { + seed(); + embedMock.mockResolvedValue([0.1]); + sb.handle((ctx) => (ctx.table === 'rpc:match_proposals' ? { error: { message: 'function does not exist' } } : undefined)); + const res = await request(buildApp()).get('/api/proposals/search?q=payment+terms'); + expect(res.body.available).toBe(false); + }); +}); + +describe('POST /api/proposals', () => { + it('400s without a title or content', async () => { + seed(); + expect((await request(buildApp()).post('/api/proposals').send({ title: 'x' })).status).toBe(400); + expect((await request(buildApp()).post('/api/proposals').send({ content: 'x' })).status).toBe(400); + }); + + it('creates a PENDING proposal owned by the caller and writes an audit entry', async () => { + seed(REP_C1); + const res = await request(buildApp()) + .post('/api/proposals') + .send({ title: 'New', content: 'Hello', metadata: { clientName: 'Acme' } }); + + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ title: 'New', status: 'PENDING', userId: 'rep1', readinessScore: 0 }); + + const insert = lastCall('Proposal', 'insert')!; + expect(insert.payload).toMatchObject({ title: 'New', status: 'PENDING', userId: 'rep1', company_id: 'c1' }); + expect(lastCall('AuditLog', 'insert')!.payload).toMatchObject({ + actorId: 'rep1', + action: 'Created proposal', + }); + }); + + it('omits company_id for a user without a company', async () => { + seed(ADMIN); + await request(buildApp()).post('/api/proposals').send({ title: 'New', content: 'Hello' }); + expect(lastCall('Proposal', 'insert')!.payload).not.toHaveProperty('company_id'); + }); + + it('stores the embedding when one is produced, and survives when it cannot be stored', async () => { + seed(); + embedMock.mockResolvedValue([0.5, 0.5]); + const ok = await request(buildApp()).post('/api/proposals').send({ title: 'T', content: 'C' }); + expect(ok.status).toBe(201); + expect(sb.callsFor('Proposal', 'update').some((c) => (c.payload as { embedding?: unknown }).embedding)).toBe(true); + + sb.handle((ctx) => (ctx.table === 'Proposal' && ctx.op === 'update' ? { error: { message: 'column embedding does not exist' } } : undefined)); + const failed = await request(buildApp()).post('/api/proposals').send({ title: 'T', content: 'C' }); + expect(failed.status).toBe(201); + }); + + it('500s when the insert itself fails', async () => { + seed(); + sb.handle((ctx) => (ctx.table === 'Proposal' && ctx.op === 'insert' ? { error: { message: 'boom' } } : undefined)); + const res = await request(buildApp()).post('/api/proposals').send({ title: 'T', content: 'C' }); + expect(res.status).toBe(500); + }); +}); + +describe('POST /api/proposals/generate', () => { + const aiReply = (obj: unknown) => + createMock.mockResolvedValue({ choices: [{ message: { content: typeof obj === 'string' ? obj : JSON.stringify(obj) } }] }); + + const generated = { + companyName: 'Acme Corp', + title: 'Acme Website Redesign', + content: '## Executive Summary\nWe will redesign the site.', + metadata: { clientName: 'Acme Corp', dealSize: 45000, discount: 10, region: 'EMEA', currency: 'EUR', industry: 'Retail' }, + }; + + it('400s on a blank query', async () => { + seed(); + expect((await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: ' ' })).status).toBe(400); + expect((await request(buildApp()).post('/api/proposals/generate').send({})).status).toBe(400); + }); + + it('424s with AI_UNAVAILABLE when no AI is configured', async () => { + seed(); + getLlmMock.mockReturnValue(null); + const res = await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'a proposal' }); + expect(res.status).toBe(424); + expect(res.body.code).toBe('AI_UNAVAILABLE'); + }); + + it('424s with AI_UNAVAILABLE when the provider cannot be reached', async () => { + seed(); + createMock.mockRejectedValue(new Error('ENOTFOUND')); + const res = await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'a proposal' }); + expect(res.status).toBe(424); + expect(res.body.code).toBe('AI_UNAVAILABLE'); + }); + + it('502s when the model answers with something that is not JSON', async () => { + seed(); + aiReply('Sure! Here is your proposal: ...'); + const res = await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'a proposal' }); + expect(res.status).toBe(502); + }); + + it('400s when the model omits required fields', async () => { + seed(); + aiReply({ title: 'Only a title' }); + const res = await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'a proposal' }); + expect(res.status).toBe(400); + expect(sb.callsFor('Proposal', 'insert')).toHaveLength(0); + }); + + it('stores the generated proposal with the model metadata', async () => { + seed(); + aiReply(generated); + + const res = await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'redesign for Acme' }); + + expect(res.status).toBe(201); + expect(createMock.mock.calls[0][0].messages[1].content).toContain('redesign for Acme'); + expect(lastCall('Proposal', 'insert')!.payload).toMatchObject({ + title: 'Acme Website Redesign', + metadata: { clientName: 'Acme Corp', dealSize: 45000, discount: 10, region: 'EMEA', currency: 'EUR', industry: 'Retail' }, + }); + expect(lastCall('AuditLog', 'insert')!.payload).toMatchObject({ + action: 'Created proposal from AI generation', + after: { source: 'ai-generated' }, + }); + }); + + it('clamps an over-limit discount the model produced to 25%', async () => { + seed(); + aiReply({ ...generated, metadata: { ...generated.metadata, discount: 60 } }); + await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'huge discount please' }); + expect((lastCall('Proposal', 'insert')!.payload as { metadata: { discount: number } }).metadata.discount).toBe(25); + }); + + it('turns a nonsense discount or deal size into safe values', async () => { + seed(); + aiReply({ ...generated, metadata: { discount: 'lots', dealSize: 'a fortune' } }); + await request(buildApp()).post('/api/proposals/generate').send({ naturalLanguageQuery: 'x' }); + const meta = (lastCall('Proposal', 'insert')!.payload as { metadata: Record }).metadata; + expect(meta.discount).toBe(0); + expect(meta.dealSize).toBeNull(); + expect(meta.region).toBe('North America'); + }); +}); + +describe('PUT /api/proposals/:id/status', () => { + it('is admin-only', async () => { + seed(REP_C1); + const res = await request(buildApp()).put('/api/proposals/p1/status').send({ status: 'APPROVED' }); + expect(res.status).toBe(403); + expect(sb.callsFor('Proposal', 'update')).toHaveLength(0); + }); + + it('rejects an unknown status', async () => { + seed(ADMIN); + const res = await request(buildApp()).put('/api/proposals/p1/status').send({ status: 'DONE' }); + expect(res.status).toBe(400); + }); + + it('updates the status, audits it, and emails the owner', async () => { + seed(ADMIN); + sb.handle((ctx) => (ctx.table === 'User' && ctx.single ? { data: { name: 'Owner', email: 'owner@b.com' } } : undefined)); + + const res = await request(buildApp()).put('/api/proposals/p1/status').send({ status: 'APPROVED' }); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ id: 'p1', status: 'APPROVED' }); + expect(lastCall('AuditLog', 'insert')!.payload).toMatchObject({ action: 'Changed status to APPROVED' }); + expect(sendEmailMock).toHaveBeenCalledWith('owner@b.com', expect.anything()); + }); + + it('still succeeds when the notification email fails', async () => { + seed(ADMIN); + sb.handle((ctx) => (ctx.table === 'User' && ctx.single ? { data: { name: 'Owner', email: 'owner@b.com' } } : undefined)); + sendEmailMock.mockRejectedValue(new Error('smtp down')); + const res = await request(buildApp()).put('/api/proposals/p1/status').send({ status: 'REJECTED' }); + expect(res.status).toBe(200); + }); +}); + +describe('DELETE /api/proposals/:id', () => { + it("refuses another company's proposal", async () => { + seed(REP_C1, { p1: row({ company_id: 'c2' }) }); + const res = await request(buildApp()).delete('/api/proposals/p1'); + expect(res.status).toBe(403); + expect(sb.callsFor('Proposal', 'delete')).toHaveLength(0); + }); + + it('deletes the report, audit trail and proposal for an authorised caller', async () => { + seed(REP_C1, { p1: row({ company_id: 'c1' }) }); + const res = await request(buildApp()).delete('/api/proposals/p1'); + expect(res.body).toEqual({ success: true }); + expect(sb.callsFor('RiskReport', 'delete')).toHaveLength(1); + expect(sb.callsFor('AuditLog', 'delete')).toHaveLength(1); + expect(sb.callsFor('Proposal', 'delete')).toHaveLength(1); + }); +}); + +describe('GET /api/proposals/:id', () => { + it('404s for an unknown id', async () => { + seed(); + sb.handle((ctx) => + ctx.table === 'Proposal' && ctx.single ? { data: null, error: null } : undefined + ); + const res = await request(buildApp()).get('/api/proposals/missing'); + expect(res.status).toBe(404); + }); + + it("403s for another company's proposal and 200s for your own", async () => { + seed(REP_C1, { other: row({ id: 'other', company_id: 'c2' }), mine: row({ id: 'mine', company_id: 'c1' }) }); + expect((await request(buildApp()).get('/api/proposals/other')).status).toBe(403); + const ok = await request(buildApp()).get('/api/proposals/mine'); + expect(ok.status).toBe(200); + expect(ok.body).toMatchObject({ id: 'mine', riskReport: null }); + }); +}); + +describe('GET /api/proposals/:id/export/pdf', () => { + it('renders the proposal and returns a PDF attachment', async () => { + seed(ADMIN); + renderPdfMock.mockResolvedValue(Buffer.from('%PDF-1.4 fake')); + + const res = await request(buildApp()).get('/api/proposals/p1/export/pdf').buffer(true); + + expect(res.status).toBe(200); + expect(res.headers['content-type']).toContain('application/pdf'); + expect(res.headers['content-disposition']).toContain('proposal-Cloud_Migration.pdf'); + const html = renderPdfMock.mock.calls[0][0] as string; + expect(html).toContain('Cloud Migration'); + expect(html).toContain('Acme'); + }); + + it('403s for another companyโ€™s proposal without launching a browser', async () => { + seed(REP_C1, { p1: row({ company_id: 'c2' }) }); + const res = await request(buildApp()).get('/api/proposals/p1/export/pdf'); + expect(res.status).toBe(403); + expect(renderPdfMock).not.toHaveBeenCalled(); + }); + + it('500s cleanly when rendering fails', async () => { + seed(ADMIN); + renderPdfMock.mockRejectedValue(new Error('Chrome not found')); + const res = await request(buildApp()).get('/api/proposals/p1/export/pdf'); + expect(res.status).toBe(500); + expect(res.body.error).toBe('Failed to export PDF'); + }); +}); From a174d02ad37b4e8173bd47b29fe317c7c3742683 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:15 +0530 Subject: [PATCH 04/11] feat(integrations): split CRM sync into connectors, stop leaking OAuth 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). --- src/api/integrations.ts | 900 ++++--------------------------- src/api/lib/integrationStore.ts | 66 +++ src/api/lib/oauthState.test.ts | 66 +++ src/api/lib/oauthState.ts | 41 ++ src/api/lib/sync/common.ts | 113 ++++ src/api/lib/sync/demo.ts | 56 ++ src/api/lib/sync/gmail.ts | 246 +++++++++ src/api/lib/sync/hubspot.ts | 140 +++++ src/api/lib/sync/index.ts | 33 ++ src/api/lib/sync/salesforce.ts | 186 +++++++ src/api/oauth.ts | 911 ++++++++++++-------------------- tests/integrations.test.ts | 242 +++++++++ tests/oauth.test.ts | 332 ++++++++++++ tests/sync.test.ts | 530 +++++++++++++++++++ 14 files changed, 2512 insertions(+), 1350 deletions(-) create mode 100644 src/api/lib/integrationStore.ts create mode 100644 src/api/lib/oauthState.test.ts create mode 100644 src/api/lib/oauthState.ts create mode 100644 src/api/lib/sync/common.ts create mode 100644 src/api/lib/sync/demo.ts create mode 100644 src/api/lib/sync/gmail.ts create mode 100644 src/api/lib/sync/hubspot.ts create mode 100644 src/api/lib/sync/index.ts create mode 100644 src/api/lib/sync/salesforce.ts create mode 100644 tests/integrations.test.ts create mode 100644 tests/oauth.test.ts create mode 100644 tests/sync.test.ts diff --git a/src/api/integrations.ts b/src/api/integrations.ts index b18a03a..76289b0 100644 --- a/src/api/integrations.ts +++ b/src/api/integrations.ts @@ -2,19 +2,47 @@ import { Router, Request, Response } from 'express'; import { supabase } from '../lib/supabase'; import { requireAuth } from './middleware/auth'; import { logger } from './lib/logger'; +import { HUBSPOT_DEALS_URL } from './lib/sync/hubspot'; +import { runSync, type IntegrationRow } from './lib/sync'; const router = Router(); +const INTEGRATION_TYPES = ['SALESFORCE', 'HUBSPOT', 'GMAIL', 'GOOGLE_DRIVE', 'DOCUSIGN', 'SHAREPOINT']; + +/** + * An integration as the browser may see it. OAuth access and refresh tokens never + * leave the server: `credentials` is replaced by a placeholder that is non-empty + * only when the integration is connected (older clients decide "connected" from + * that), plus an explicit `hasCredentials` flag. + */ +function toPublicIntegration(row: T) { + const credentials = row.credentials; + const connected = + !!credentials && typeof credentials === 'object' && Object.keys(credentials as object).length > 0; + const demo = connected && (credentials as { demo?: boolean }).demo === true; + return { + ...row, + hasCredentials: connected, + credentials: connected ? { connected: true, ...(demo ? { demo: true } : {}) } : {}, + }; +} + +/** The signed-in user's id, or a 401 response already sent (returns null). */ +function currentUserId(req: Request, res: Response): string | null { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ error: 'User not authenticated' }); + return null; + } + return userId; +} + // GET all integrations (only show current user's integrations) router.get('/', requireAuth, async (req: Request, res: Response) => { try { - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; - // Fetch only integrations belonging to the current user const { data: integrations, error } = await supabase .from('Integration') .select('*, SyncLog(*)') @@ -23,20 +51,9 @@ router.get('/', requireAuth, async (req: Request, res: Response) => { if (error) throw error; - logger.debug('GET /api/integrations - Returning:', { - userId, - count: integrations?.length || 0, - integrations: integrations?.map((i: any) => ({ - id: i.id, - type: i.type, - name: i.name, - isActive: i.isActive, - })), - }); - - res.json(integrations || []); + res.json((integrations || []).map(toPublicIntegration)); } catch (error) { - console.error('Error fetching integrations:', error); + logger.error('Error fetching integrations:', error); res.status(500).json({ error: 'Failed to fetch integrations' }); } }); @@ -45,11 +62,8 @@ router.get('/', requireAuth, async (req: Request, res: Response) => { router.get('/:id', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; const { data: integration, error } = await supabase .from('Integration') @@ -63,9 +77,9 @@ router.get('/:id', requireAuth, async (req: Request, res: Response) => { return res.status(404).json({ error: 'Integration not found' }); } - res.json(integration); + res.json(toPublicIntegration(integration)); } catch (error) { - console.error('Error fetching integration:', error); + logger.error('Error fetching integration:', error); res.status(500).json({ error: 'Failed to fetch integration' }); } }); @@ -74,15 +88,15 @@ router.get('/:id', requireAuth, async (req: Request, res: Response) => { router.post('/', requireAuth, async (req: Request, res: Response) => { try { const { type, name, credentials, config } = req.body; - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; if (!type || !name) { return res.status(400).json({ error: 'Type and name are required' }); } + if (!INTEGRATION_TYPES.includes(type)) { + return res.status(400).json({ error: `Unknown integration type. Expected one of: ${INTEGRATION_TYPES.join(', ')}` }); + } const { data: integration, error } = await supabase .from('Integration') @@ -93,7 +107,7 @@ router.post('/', requireAuth, async (req: Request, res: Response) => { credentials: credentials || {}, config: config || {}, isActive: true, - userId: userId, + userId, updatedAt: new Date().toISOString(), }) .select() @@ -101,9 +115,9 @@ router.post('/', requireAuth, async (req: Request, res: Response) => { if (error) throw error; - res.status(201).json(integration); + res.status(201).json(toPublicIntegration(integration)); } catch (error) { - console.error('Error creating integration:', error); + logger.error('Error creating integration:', error); res.status(500).json({ error: 'Failed to create integration' }); } }); @@ -113,11 +127,8 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; const { name, credentials, config, isActive } = req.body; - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; // Verify the integration belongs to the current user const { data: existing } = await supabase @@ -130,7 +141,7 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { return res.status(403).json({ error: 'You do not have access to this integration' }); } - const updates: any = { updatedAt: new Date().toISOString() }; + const updates: Record = { updatedAt: new Date().toISOString() }; if (name !== undefined) updates.name = name; if (credentials !== undefined) updates.credentials = credentials; if (config !== undefined) updates.config = config; @@ -148,9 +159,9 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { return res.status(404).json({ error: 'Integration not found' }); } - res.json(integration); + res.json(toPublicIntegration(integration)); } catch (error) { - console.error('Error updating integration:', error); + logger.error('Error updating integration:', error); res.status(500).json({ error: 'Failed to update integration' }); } }); @@ -159,11 +170,8 @@ router.patch('/:id', requireAuth, async (req: Request, res: Response) => { router.delete('/:id', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; // Verify the integration belongs to the current user const { data: existing } = await supabase @@ -178,23 +186,15 @@ router.delete('/:id', requireAuth, async (req: Request, res: Response) => { // SyncLog rows reference this integration; without a DB-level cascade the // delete fails for any integration that has ever synced. - const { error: logError } = await supabase - .from('SyncLog') - .delete() - .eq('integrationId', id); - + const { error: logError } = await supabase.from('SyncLog').delete().eq('integrationId', id); if (logError) throw logError; - const { error } = await supabase - .from('Integration') - .delete() - .eq('id', id); - + const { error } = await supabase.from('Integration').delete().eq('id', id); if (error) throw error; res.status(204).send(); } catch (error) { - console.error('Error deleting integration:', error); + logger.error('Error deleting integration:', error); res.status(500).json({ error: 'Failed to delete integration' }); } }); @@ -203,13 +203,8 @@ router.delete('/:id', requireAuth, async (req: Request, res: Response) => { router.post('/:id/sync', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; - const userId = req.user?.id; - // Imported proposals inherit the integration owner's company for tenant scoping. - const intCompanyId = req.user?.companyId ?? null; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; const { data: integration, error: intError } = await supabase .from('Integration') @@ -222,695 +217,21 @@ router.post('/:id/sync', requireAuth, async (req: Request, res: Response) => { return res.status(404).json({ error: 'Integration not found' }); } - let recordsAffected = 0; - let syncDetails: any = { message: 'Manual sync triggered' }; - let syncFailed = false; - - // Perform actual sync based on integration type. - // Demo-mode connections (credentials.demo, set by the *_DEMO_MODE OAuth - // flows) import canned deals so connect โ†’ sync โ†’ review is fully - // demonstrable without real CRM credentials. - if ((integration.credentials as { demo?: boolean } | null)?.demo === true) { - const sourceKey = String(integration.type || 'crm').toLowerCase(); - const sampleDeals = [ - { id: `demo-${sourceKey}-001`, name: 'Acme Corp โ€” Platform Renewal', amount: 120000, stage: 'Negotiation', client: 'Acme Corp' }, - { id: `demo-${sourceKey}-002`, name: 'Globex โ€” Data Migration', amount: 45000, stage: 'Proposal Sent', client: 'Globex Inc' }, - { id: `demo-${sourceKey}-003`, name: 'Initech โ€” Annual Support Contract', amount: 24000, stage: 'Qualification', client: 'Initech LLC' }, - ]; - - const { data: existingProposals } = await supabase - .from('Proposal') - .select('metadata') - .not('metadata->dealId', 'is', null); - const existingIds = new Set( - (existingProposals || []).map((p: any) => p.metadata?.dealId).filter(Boolean) - ); - const newDeals = sampleDeals.filter((d) => !existingIds.has(d.id)); - - if (newDeals.length > 0) { - const proposals = newDeals.map((deal) => ({ - id: crypto.randomUUID(), - title: deal.name, - content: `Deal imported from ${integration.name} (demo mode)\n\nClient: ${deal.client}\nAmount: $${deal.amount.toLocaleString()}\nStage: ${deal.stage}\n\nThis record was generated by the demo integration to showcase the CRM import flow.`, - status: 'PENDING' as const, - userId, - lockedSections: [], - updatedAt: new Date().toISOString(), - ...(intCompanyId ? { company_id: intCompanyId } : {}), - metadata: { - clientName: deal.client, - dealSize: deal.amount, - source: `${sourceKey}-demo`, - dealId: deal.id, - stageName: deal.stage, - importedAt: new Date().toISOString(), - }, - })); - - const { data: inserted, error: insertError } = await supabase - .from('Proposal') - .insert(proposals) - .select(); - - if (insertError) { - syncFailed = true; - syncDetails = { error: insertError.message, message: 'Sync failed' }; - } else { - recordsAffected = inserted?.length || 0; - syncDetails = { - message: `Demo sync imported ${recordsAffected} sample deals from ${integration.name}`, - demo: true, - proposalsCreated: recordsAffected, - }; - } - } else { - syncDetails = { - message: 'Demo sync complete โ€” all sample deals already imported.', - demo: true, - proposalsCreated: 0, - }; - } - } else if (integration.type === 'HUBSPOT' && integration.credentials) { - try { - // Fetch deals from HubSpot API directly - const credentials = integration.credentials as any; - let accessToken = credentials?.accessToken || credentials?.access_token; - const refreshToken = credentials?.refreshToken || credentials?.refresh_token; - - if (!accessToken) { - throw new Error('No access token found'); - } - - // Try API call - let response = await fetch( - 'https://api.hubapi.com/crm/v3/objects/deals?limit=100&properties=dealname,amount,dealstage,pipeline,closedate,createdate,hs_lastmodifieddate,description', - { - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - } - } - ); - - // If unauthorized and we have a refresh token, try to refresh - if (response.status === 401 && refreshToken) { - logger.debug('Access token expired, refreshing...'); - - const tokenResponse = await fetch('https://api.hubapi.com/oauth/v1/token', { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'refresh_token', - client_id: process.env.HUBSPOT_CLIENT_ID!, - client_secret: process.env.HUBSPOT_CLIENT_SECRET!, - refresh_token: refreshToken, - }), - }); - - if (tokenResponse.ok) { - const tokenData = await tokenResponse.json(); - accessToken = tokenData.access_token; - - // Update credentials in database - await supabase - .from('Integration') - .update({ - credentials: { - ...credentials, - accessToken: tokenData.access_token, - refreshToken: tokenData.refresh_token, - expiresIn: tokenData.expires_in, - }, - updatedAt: new Date().toISOString(), - }) - .eq('id', id); - - logger.debug('Token refreshed successfully'); - - // Retry the API call with new token - response = await fetch( - 'https://api.hubapi.com/crm/v3/objects/deals?limit=100&properties=dealname,amount,dealstage,pipeline,closedate,createdate,hs_lastmodifieddate,description', - { - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - } - } - ); - } else { - throw new Error('Failed to refresh token. Please reconnect HubSpot.'); - } - } - - if (!response.ok) { - throw new Error(`HubSpot API error: ${response.statusText}`); - } - - const data = await response.json(); - const deals = data.results || []; - - if (deals.length > 0) { - // Check which deals already exist - const { data: existingProposals } = await supabase - .from('Proposal') - .select('metadata') - .not('metadata->dealId', 'is', null); - - const existingDealIds = new Set( - (existingProposals || []).map((p: any) => p.metadata?.dealId).filter(Boolean) - ); - - // Only import new deals - const newDeals = deals.filter((deal: any) => !existingDealIds.has(deal.id)); - - if (newDeals.length > 0) { - // Use the first available user - const { data: users } = await supabase.from('User').select('id').limit(1); - const defaultUserId = users?.[0]?.id; - - if (!defaultUserId) { - throw new Error('No users found in database. Please seed the database first.'); - } - - const proposals = newDeals.map((deal: any) => ({ - id: crypto.randomUUID(), - title: deal.properties.dealname || 'Untitled Deal', - content: deal.properties.description || `Deal imported from HubSpot\n\nAmount: $${deal.properties.amount || '0'}\nStage: ${deal.properties.dealstage || 'Unknown'}`, - status: 'PENDING' as const, - userId: defaultUserId, - lockedSections: [], - createdAt: deal.properties.createdate || new Date().toISOString(), - updatedAt: new Date().toISOString(), - ...(intCompanyId ? { company_id: intCompanyId } : {}), - metadata: { - clientName: deal.properties.dealname, - dealSize: parseFloat(deal.properties.amount || '0'), - source: 'hubspot', - dealId: deal.id, - dealStage: deal.properties.dealstage, - pipeline: deal.properties.pipeline, - closeDate: deal.properties.closedate, - importedAt: new Date().toISOString() - } - })); - - const { data: insertedProposals, error: insertError } = await supabase - .from('Proposal') - .insert(proposals) - .select(); - - if (insertError) { - console.error('Error inserting proposals:', insertError); - throw insertError; - } - - recordsAffected = insertedProposals?.length || 0; - syncDetails = { - message: `Successfully synced ${recordsAffected} new deals from HubSpot`, - dealsProcessed: deals.length, - dealsAlreadyImported: deals.length - newDeals.length, - proposalsCreated: recordsAffected - }; - } else { - syncDetails = { - message: 'No new deals to sync. All deals have already been imported.', - dealsProcessed: deals.length, - dealsAlreadyImported: deals.length, - proposalsCreated: 0 - }; - } - } else { - syncDetails = { - message: 'No deals found in HubSpot', - dealsProcessed: 0, - proposalsCreated: 0 - }; - } - } catch (syncError: any) { - console.error('HubSpot sync error:', syncError); - - // If credentials are missing or invalid, mark integration as inactive - if (syncError.message?.includes('No access token') || - syncError.message?.includes('expired') || - syncError.message?.includes('revoked')) { - await supabase - .from('Integration') - .update({ - isActive: false, - updatedAt: new Date().toISOString(), - }) - .eq('id', id); - } - - syncDetails = { - error: syncError.message || 'Failed to sync with HubSpot', - message: 'Sync failed' - }; - syncFailed = true; - } - } else if (integration.type === 'GMAIL' && integration.credentials) { - try { - const credentials = integration.credentials as any; - let accessToken = credentials?.accessToken || credentials?.access_token; - const refreshToken = credentials?.refreshToken || credentials?.refresh_token; - - if (!accessToken) { - throw new Error('No access token found. Please reconnect Gmail in Integrations.'); - } - - // Search for proposal-related emails in INBOX only (last 30 days) - const thirtyDaysAgo = new Date(); - thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); - const afterDate = Math.floor(thirtyDaysAgo.getTime() / 1000); - - const query = `in:inbox (proposal OR quote OR agreement OR contract) after:${afterDate}`; - - const gmailHeaders = () => ({ - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }); - - let searchResponse = await fetch( - `https://gmail.googleapis.com/gmail/v1/users/me/messages?q=${encodeURIComponent(query)}&maxResults=50`, - { headers: gmailHeaders() } - ); - - // If unauthorized, try to refresh the token (requires refresh_token + env vars) - if (searchResponse.status === 401) { - const clientId = process.env.GOOGLE_CLIENT_ID; - const clientSecret = process.env.GOOGLE_CLIENT_SECRET; - if (refreshToken && clientId && clientSecret) { - logger.debug('Gmail access token expired, refreshing...'); - const tokenResponse = await fetch('https://oauth2.googleapis.com/token', { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'refresh_token', - refresh_token: refreshToken, - client_id: clientId, - client_secret: clientSecret, - }), - }); - - const tokenBody = await tokenResponse.json(); - - if (tokenResponse.ok && tokenBody.access_token) { - accessToken = tokenBody.access_token; - await supabase - .from('Integration') - .update({ - credentials: { - ...credentials, - accessToken: tokenBody.access_token, - refreshToken: tokenBody.refresh_token ?? refreshToken, - expiresIn: tokenBody.expires_in, - }, - updatedAt: new Date().toISOString(), - }) - .eq('id', id); - logger.debug('Gmail token refreshed successfully'); - searchResponse = await fetch( - `https://gmail.googleapis.com/gmail/v1/users/me/messages?q=${encodeURIComponent(query)}&maxResults=50`, - { headers: gmailHeaders() } - ); - } else { - console.error('Gmail token refresh failed:', tokenBody.error || tokenResponse.status, tokenBody); - } - } else if (!refreshToken) { - console.warn('Gmail: No refresh token stored. User must disconnect and reconnect Gmail (with prompt=consent) to get one.'); - } else if (!clientId || !clientSecret) { - console.warn('Gmail: GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET not set. Cannot refresh token.'); - } - } - - if (!searchResponse.ok) { - const hint = searchResponse.status === 401 - ? ' Authorization may have expired or been revoked. Please reconnect Gmail in Integrations.' - : ''; - throw new Error(`Gmail API error: ${searchResponse.statusText}.${hint}`); - } - - const searchData = await searchResponse.json(); - const messages = searchData.messages || []; - - if (messages.length > 0) { - // Fetch full message details for each email - const emailThreads = await Promise.all( - messages.slice(0, 10).map(async (msg: any) => { // Limit to 10 most recent - const msgResponse = await fetch( - `https://gmail.googleapis.com/gmail/v1/users/me/messages/${msg.id}`, - { - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - } - } - ); - - if (msgResponse.ok) { - const msgData = await msgResponse.json(); - // Only import messages that are actually in the inbox - const labelIds = msgData.labelIds || []; - if (!labelIds.includes('INBOX')) { - return null; - } - const headers = msgData.payload.headers; - - // Extract email body - let body = ''; - if (msgData.payload.body?.data) { - body = Buffer.from(msgData.payload.body.data, 'base64').toString('utf-8'); - } else if (msgData.payload.parts) { - for (const part of msgData.payload.parts) { - if (part.mimeType === 'text/plain' && part.body?.data) { - body = Buffer.from(part.body.data, 'base64').toString('utf-8'); - break; - } - } - } - - return { - id: msgData.id, - threadId: msgData.threadId, - subject: headers.find((h: any) => h.name === 'Subject')?.value || 'No Subject', - from: headers.find((h: any) => h.name === 'From')?.value || '', - to: headers.find((h: any) => h.name === 'To')?.value || '', - date: new Date(parseInt(msgData.internalDate)).toISOString(), - snippet: msgData.snippet, - body: body || msgData.snippet, - }; - } - return null; - }) - ); - - const validEmails = emailThreads.filter(e => e !== null); - - if (validEmails.length > 0) { - // Check which email threads already exist as proposals - const { data: existingProposals } = await supabase - .from('Proposal') - .select('metadata') - .not('metadata->emailThreadId', 'is', null); - - const existingThreadIds = new Set( - (existingProposals || []).map((p: any) => p.metadata?.emailThreadId).filter(Boolean) - ); - - // Only import new email threads - const newEmails = validEmails.filter((email: any) => !existingThreadIds.has(email.threadId)); - - if (newEmails.length > 0) { - // Get the first available user - const { data: users } = await supabase.from('User').select('id').limit(1); - const defaultUserId = users?.[0]?.id; - - if (!defaultUserId) { - throw new Error('No users found in database. Please seed the database first.'); - } - - // Create proposals from email threads - const proposals = newEmails.map((email: any) => { - // Extract deal size from email body - const body = email.body || ''; - const dealSizeMatch = body.match(/Investment:?\s*\$?([\d,]+(?:\.\d{2})?)/i) || - body.match(/\$\s*([\d,]+(?:\.\d{2})?)/); - const dealSize = dealSizeMatch ? parseFloat(dealSizeMatch[1].replace(/,/g, '')) : 0; - - // Extract client name from "to" field or email - const clientNameMatch = email.to.match(/([^<]+) ({ - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }); - - let response = await fetch( - `${instanceUrl}/services/data/${apiVersion}/query?q=${encodeURIComponent(query)}`, - { headers: sfHeaders() } - ); - - // If unauthorized and we have a refresh token, try to refresh - if (response.status === 401 && refreshToken) { - const clientId = process.env.SALESFORCE_CLIENT_ID; - const clientSecret = process.env.SALESFORCE_CLIENT_SECRET; - const isSandbox = process.env.SALESFORCE_SANDBOX === 'true'; - const baseUrl = isSandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com'; - const tokenUrl = `${baseUrl}/services/oauth2/token`; - - logger.debug('Salesforce access token expired, refreshing...'); - const tokenResponse = await fetch(tokenUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'refresh_token', - refresh_token: refreshToken, - client_id: clientId!, - client_secret: clientSecret!, - }), - }); - - if (tokenResponse.ok) { - const tokenData = await tokenResponse.json(); - accessToken = tokenData.access_token; - const newInstanceUrl = tokenData.instance_url || instanceUrl; - await supabase - .from('Integration') - .update({ - credentials: { - ...credentials, - accessToken: tokenData.access_token, - refreshToken: tokenData.refresh_token ?? refreshToken, - expiresIn: tokenData.expires_in, - instanceUrl: newInstanceUrl, - }, - updatedAt: new Date().toISOString(), - }) - .eq('id', id); - logger.debug('Salesforce token refreshed successfully'); - response = await fetch( - `${newInstanceUrl}/services/data/${apiVersion}/query?q=${encodeURIComponent(query)}`, - { headers: sfHeaders() } - ); - } else { - throw new Error('Failed to refresh token. Please reconnect Salesforce.'); - } - } - - if (!response.ok) { - const hint = response.status === 401 - ? ' Authorization may have expired or been revoked. Please reconnect Salesforce.' - : ''; - throw new Error(`Salesforce API error: ${response.statusText}.${hint}`); - } - - const data = await response.json(); - const opportunities = data.records || []; - - if (opportunities.length > 0) { - // Check which opportunities already exist - const { data: existingProposals } = await supabase - .from('Proposal') - .select('metadata') - .not('metadata->opportunityId', 'is', null); - - const existingOppIds = new Set( - (existingProposals || []).map((p: any) => p.metadata?.opportunityId).filter(Boolean) - ); - - // Only import new opportunities - const newOpportunities = opportunities.filter((opp: any) => !existingOppIds.has(opp.Id)); - - if (newOpportunities.length > 0) { - const { data: users } = await supabase.from('User').select('id').limit(1); - const defaultUserId = users?.[0]?.id || 'cmktbfc2w0000gks37adtbu7o'; - - const proposals = newOpportunities.map((opp: any) => ({ - id: crypto.randomUUID(), - title: opp.Name || 'Untitled Opportunity', - content: opp.Description || `Opportunity imported from Salesforce\n\nAmount: $${opp.Amount || '0'}\nStage: ${opp.StageName || 'Unknown'}\nAccount: ${opp.Account?.Name || 'N/A'}`, - status: 'PENDING' as const, - userId: defaultUserId, - lockedSections: [], - createdAt: opp.CreatedDate || new Date().toISOString(), - updatedAt: new Date().toISOString(), - ...(intCompanyId ? { company_id: intCompanyId } : {}), - metadata: { - clientName: opp.Account?.Name || opp.Name, - dealSize: opp.Amount ? parseFloat(String(opp.Amount)) : 0, - source: 'salesforce', - opportunityId: opp.Id, - stageName: opp.StageName, - closeDate: opp.CloseDate, - accountName: opp.Account?.Name, - importedAt: new Date().toISOString() - } - })); - - const { data: insertedProposals, error: insertError } = await supabase - .from('Proposal') - .insert(proposals) - .select(); - - if (insertError) { - console.error('Error inserting proposals from Salesforce:', insertError); - throw insertError; - } + // Imported proposals belong to the integration's owner and inherit their company. + const result = await runSync({ + integration: integration as IntegrationRow, + userId, + companyId: req.user?.companyId ?? null, + }); - recordsAffected = insertedProposals?.length || 0; - syncDetails = { - message: `Successfully synced ${recordsAffected} new opportunities from Salesforce`, - opportunitiesProcessed: opportunities.length, - opportunitiesAlreadyImported: opportunities.length - newOpportunities.length, - proposalsCreated: recordsAffected - }; - } else { - syncDetails = { - message: 'No new opportunities to sync. All opportunities have already been imported.', - opportunitiesProcessed: opportunities.length, - opportunitiesAlreadyImported: opportunities.length, - proposalsCreated: 0 - }; - } - } else { - syncDetails = { - message: 'No open opportunities found in Salesforce', - opportunitiesProcessed: 0, - proposalsCreated: 0 - }; - } - } catch (syncError: any) { - console.error('Salesforce sync error:', syncError); - - // If credentials are missing or invalid, mark integration as inactive - if (syncError.message?.includes('No access token') || - syncError.message?.includes('No instance URL') || - syncError.message?.includes('expired') || - syncError.message?.includes('revoked')) { - await supabase - .from('Integration') - .update({ - isActive: false, - updatedAt: new Date().toISOString(), - }) - .eq('id', id); - } - - syncDetails = { - error: syncError.message || 'Failed to sync with Salesforce', - message: 'Sync failed' - }; - syncFailed = true; - } + // A revoked/expired connection is switched off so the UI asks the user to reconnect. + if (result.deactivate) { + await supabase + .from('Integration') + .update({ isActive: false, updatedAt: new Date().toISOString() }) + .eq('id', id); } - // Log sync attempt const { data: syncLog, error: logError } = await supabase .from('SyncLog') .insert({ @@ -918,32 +239,42 @@ router.post('/:id/sync', requireAuth, async (req: Request, res: Response) => { integrationId: id, action: 'SYNC', // A sync with nothing new to import is still a success, not a failure. - status: syncFailed ? 'FAILURE' : 'SUCCESS', - recordsAffected, - details: syncDetails, + status: result.failed ? 'FAILURE' : 'SUCCESS', + recordsAffected: result.recordsAffected, + details: result.details, }) .select() .single(); if (logError) throw logError; - // Update last sync time + if (result.failed) { + // 424 (not 5xx): the CRM failed, not this server, and the SPA's HTTP client + // would otherwise retry a 502/503 and trigger the sync again. + return res.status(424).json({ + success: false, + error: result.details.error, + message: result.details.message, + needsReconnect: result.deactivate, + code: 'SYNC_FAILED', + recordsAffected: 0, + syncLog, + }); + } + await supabase .from('Integration') - .update({ - lastSyncAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }) + .update({ lastSyncAt: new Date().toISOString(), updatedAt: new Date().toISOString() }) .eq('id', id); res.json({ - success: !syncFailed, - message: syncDetails.message, - recordsAffected, - syncLog + success: true, + message: result.details.message, + recordsAffected: result.recordsAffected, + syncLog, }); } catch (error) { - console.error('Error triggering sync:', error); + logger.error('Error triggering sync:', error); res.status(500).json({ error: 'Failed to trigger sync' }); } }); @@ -952,12 +283,9 @@ router.post('/:id/sync', requireAuth, async (req: Request, res: Response) => { router.get('/:id/logs', requireAuth, async (req: Request, res: Response) => { try { const { id } = req.params; - const limit = parseInt(req.query.limit as string) || 50; - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const limit = Math.min(Math.max(Number.parseInt(req.query.limit as string, 10) || 50, 1), 200); + const userId = currentUserId(req, res); + if (!userId) return; // Verify the integration belongs to the current user const { data: integration } = await supabase @@ -981,7 +309,7 @@ router.get('/:id/logs', requireAuth, async (req: Request, res: Response) => { res.json(logs || []); } catch (error) { - console.error('Error fetching sync logs:', error); + logger.error('Error fetching sync logs:', error); res.status(500).json({ error: 'Failed to fetch sync logs' }); } }); @@ -989,11 +317,8 @@ router.get('/:id/logs', requireAuth, async (req: Request, res: Response) => { // GET HubSpot deals (if current user has HubSpot integration active) router.get('/hubspot/deals', requireAuth, async (req: Request, res: Response) => { try { - const userId = req.user?.id; - - if (!userId) { - return res.status(401).json({ error: 'User not authenticated' }); - } + const userId = currentUserId(req, res); + if (!userId) return; // Get user's HubSpot integration const { data: integration, error } = await supabase @@ -1002,13 +327,15 @@ router.get('/hubspot/deals', requireAuth, async (req: Request, res: Response) => .eq('type', 'HUBSPOT') .eq('userId', userId) .eq('isActive', true) - .single(); + .order('createdAt', { ascending: false }) + .limit(1) + .maybeSingle(); if (error || !integration) { return res.status(404).json({ error: 'HubSpot integration not found or not active' }); } - const credentials = integration.credentials as any; + const credentials = integration.credentials as { accessToken?: string; access_token?: string } | null; const accessToken = credentials?.accessToken || credentials?.access_token; if (!accessToken) { @@ -1016,26 +343,21 @@ router.get('/hubspot/deals', requireAuth, async (req: Request, res: Response) => } // Fetch deals from HubSpot API - const response = await fetch( - 'https://api.hubapi.com/crm/v3/objects/deals?limit=100&properties=dealname,amount,dealstage,pipeline,closedate,createdate,hs_lastmodifieddate,description', - { - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - } - } - ); + const response = await fetch(HUBSPOT_DEALS_URL, { + headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, + signal: AbortSignal.timeout(20_000), + }); if (!response.ok) { const errorText = await response.text(); - console.error('HubSpot API error:', errorText); + logger.error('HubSpot API error:', errorText); return res.status(response.status).json({ error: 'Failed to fetch deals from HubSpot', details: errorText }); } const data = await response.json(); res.json(data.results || []); } catch (error) { - console.error('Error fetching HubSpot deals:', error); + logger.error('Error fetching HubSpot deals:', error); res.status(500).json({ error: 'Failed to fetch HubSpot deals' }); } }); diff --git a/src/api/lib/integrationStore.ts b/src/api/lib/integrationStore.ts new file mode 100644 index 0000000..24829ec --- /dev/null +++ b/src/api/lib/integrationStore.ts @@ -0,0 +1,66 @@ +/** + * Find-or-create an OAuth integration for a user. Used by every connect/callback + * flow, which previously each carried their own copy of this block. + */ + +import { supabase } from '../../lib/supabase'; + +export type OAuthProvider = 'SALESFORCE' | 'HUBSPOT' | 'GMAIL'; + +export interface UpsertIntegrationOptions { + userId: string; + type: OAuthProvider; + name: string; + /** Build the credentials to store; receives the existing ones (empty on first connect). */ + credentials: (existing: Record) => Record; + /** Also reset the display name on reconnect (demo flows do; real flows keep the user's name). */ + resetName?: boolean; +} + +/** + * Store credentials for the user's integration of this type, reactivating it if + * it already exists. Tolerates duplicate rows from before this upsert existed: + * `.single()` errors on more than one row, which made every reconnect insert yet + * another copy, so it picks the newest instead. Throws if the database write fails. + */ +export async function upsertIntegration(opts: UpsertIntegrationOptions): Promise { + const { userId, type, name } = opts; + + const { data: existing } = await supabase + .from('Integration') + .select('*') + .eq('type', type) + .eq('userId', userId) + .order('createdAt', { ascending: false }) + .limit(1) + .maybeSingle(); + + const now = new Date().toISOString(); + const credentials = opts.credentials((existing?.credentials ?? {}) as Record); + + if (existing) { + const { error } = await supabase + .from('Integration') + .update({ + ...(opts.resetName ? { name } : {}), + credentials, + isActive: true, + updatedAt: now, + }) + .eq('id', existing.id); + if (error) throw error; + return; + } + + const { error } = await supabase.from('Integration').insert({ + id: crypto.randomUUID(), + type, + name, + credentials, + config: {}, + isActive: true, + userId, + updatedAt: now, + }); + if (error) throw error; +} diff --git a/src/api/lib/oauthState.test.ts b/src/api/lib/oauthState.test.ts new file mode 100644 index 0000000..033e278 --- /dev/null +++ b/src/api/lib/oauthState.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect } from 'vitest'; +import jwt from 'jsonwebtoken'; +import { signOAuthStart, signOAuthState, verifyOAuthStart, verifyOAuthState } from './oauthState'; + +const SECRET = process.env.NEXTAUTH_SECRET as string; + +describe('OAuth start tokens', () => { + it('round-trips a user id', () => { + expect(verifyOAuthStart(signOAuthStart('user-1'))).toBe('user-1'); + }); + + it('rejects junk, empty and non-string input', () => { + for (const bad of ['nope', '', undefined, null, 42, {}]) { + expect(verifyOAuthStart(bad)).toBeNull(); + } + }); + + it('rejects an expired token', () => { + const expired = jwt.sign({ purpose: 'oauth-start', uid: 'u1' }, SECRET, { expiresIn: -5 }); + expect(verifyOAuthStart(expired)).toBeNull(); + }); + + it('rejects a token signed with a different secret', () => { + const forged = jwt.sign({ purpose: 'oauth-start', uid: 'u1' }, 'attacker-secret'); + expect(verifyOAuthStart(forged)).toBeNull(); + }); +}); + +describe('OAuth state', () => { + it('round-trips a user id', () => { + expect(verifyOAuthState(signOAuthState('user-1'))).toBe('user-1'); + }); + + it('rejects the old raw-user-id state, which anyone could forge', () => { + expect(verifyOAuthState('user-1')).toBeNull(); + expect(verifyOAuthState('9c6ca796-855a-4118-ac3c-774202eb3afb')).toBeNull(); + }); + + it('rejects a tampered token', () => { + const token = signOAuthState('user-1'); + const [header, , signature] = token.split('.'); + const payload = Buffer.from(JSON.stringify({ purpose: 'oauth-state', uid: 'victim' })).toString('base64url'); + expect(verifyOAuthState(`${header}.${payload}.${signature}`)).toBeNull(); + }); +}); + +describe('token purposes are not interchangeable', () => { + it('a start token is not a valid state, and vice versa', () => { + expect(verifyOAuthState(signOAuthStart('u1'))).toBeNull(); + expect(verifyOAuthStart(signOAuthState('u1'))).toBeNull(); + }); + + it('a session token is neither', () => { + const session = jwt.sign({ userId: 'u1' }, SECRET, { expiresIn: '7d' }); + expect(verifyOAuthStart(session)).toBeNull(); + expect(verifyOAuthState(session)).toBeNull(); + }); + + it('neither can be replayed as a session token', async () => { + // Decode what a session check would read: there must be no userId claim. + for (const token of [signOAuthStart('u1'), signOAuthState('u1')]) { + const claims = jwt.verify(token, SECRET) as Record; + expect(claims).not.toHaveProperty('userId'); + } + }); +}); diff --git a/src/api/lib/oauthState.ts b/src/api/lib/oauthState.ts new file mode 100644 index 0000000..aa5105c --- /dev/null +++ b/src/api/lib/oauthState.ts @@ -0,0 +1,41 @@ +/** + * Short-lived, single-purpose tokens for the OAuth redirect dance. + * + * OAuth steps are top-level browser navigations, so there is no Authorization + * header โ€” the identity has to travel in the URL. Putting the 7-day session token + * there would leak it into server logs, browser history and Referer headers, so: + * + * - "start" token: minted by an authenticated API call, valid ~2 minutes, only + * accepted by the /authorize redirect endpoints. + * - "state" token: round-tripped through the provider as the OAuth `state` + * parameter. It is signed, so a callback cannot be forged for someone else's + * user id (the old state was the raw user id), and it expires in 10 minutes. + * + * Each carries a `purpose` claim, and neither carries `userId`, so neither can be + * replayed as a session token (or as each other). + */ + +import jwt from 'jsonwebtoken'; +import { getJwtSecret } from './authConfig'; + +type Purpose = 'oauth-start' | 'oauth-state'; + +function sign(purpose: Purpose, userId: string, expiresIn: jwt.SignOptions['expiresIn']): string { + return jwt.sign({ purpose, uid: userId }, getJwtSecret(), { expiresIn }); +} + +function verify(purpose: Purpose, token: unknown): string | null { + if (typeof token !== 'string' || !token) return null; + try { + const decoded = jwt.verify(token, getJwtSecret()) as { purpose?: string; uid?: unknown }; + return decoded.purpose === purpose && typeof decoded.uid === 'string' && decoded.uid ? decoded.uid : null; + } catch { + return null; + } +} + +export const signOAuthStart = (userId: string): string => sign('oauth-start', userId, '2m'); +export const verifyOAuthStart = (token: unknown): string | null => verify('oauth-start', token); + +export const signOAuthState = (userId: string): string => sign('oauth-state', userId, '10m'); +export const verifyOAuthState = (state: unknown): string | null => verify('oauth-state', state); diff --git a/src/api/lib/sync/common.ts b/src/api/lib/sync/common.ts new file mode 100644 index 0000000..415530f --- /dev/null +++ b/src/api/lib/sync/common.ts @@ -0,0 +1,113 @@ +/** + * Types and helpers shared by the CRM sync connectors. + */ + +import { supabase } from '../../../lib/supabase'; + +export interface IntegrationRow { + id: string; + type: string; + name: string; + userId: string; + credentials: Record | null; + isActive?: boolean; +} + +export interface SyncContext { + integration: IntegrationRow; + /** The integration's owner: imported records belong to them. */ + userId: string; + /** The owner's company; imported records inherit it for tenant scoping. */ + companyId: string | null; +} + +export interface SyncResult { + recordsAffected: number; + failed: boolean; + /** The connection is unusable (revoked/expired/missing token): mark it inactive. */ + deactivate: boolean; + details: { message: string; error?: string } & Record; +} + +/** Give up on a CRM that does not answer rather than hanging the request. */ +export const SYNC_TIMEOUT_MS = 20_000; +export const timeoutSignal = (): AbortSignal => AbortSignal.timeout(SYNC_TIMEOUT_MS); + +/** Error text that means "the user must reconnect", not "try again later". */ +const RECONNECT_HINTS = ['No access token', 'No instance URL', 'expired', 'revoked', 'reconnect']; + +/** Build the result for a connector that threw. */ +export function failureResult(err: unknown, fallbackMessage: string): SyncResult { + const message = (err as Error | undefined)?.message || fallbackMessage; + return { + recordsAffected: 0, + failed: true, + deactivate: RECONNECT_HINTS.some((hint) => message.includes(hint)), + details: { error: message, message: 'Sync failed' }, + }; +} + +export const successResult = ( + recordsAffected: number, + details: SyncResult['details'] +): SyncResult => ({ recordsAffected, failed: false, deactivate: false, details }); + +/** A money amount from a CRM field ("50000", "9,500.50", "$1,200"); 0 when it is not a number. */ +export function parseMoney(value: unknown): number { + const n = Number.parseFloat(String(value ?? '').replace(/[$,\s]/g, '')); + return Number.isFinite(n) ? n : 0; +} + +/** Read an OAuth token field that may be stored camelCase or snake_case. */ +export function credentialField(credentials: Record | null, ...names: string[]): string | undefined { + for (const name of names) { + const value = credentials?.[name]; + if (typeof value === 'string' && value) return value; + } + return undefined; +} + +/** + * Identifiers (stored under `metadata.`) of records this user has already + * imported, so a re-sync only adds what is new. + */ +export async function importedIds(userId: string, key: string): Promise> { + const { data } = await supabase + .from('Proposal') + .select('metadata') + .eq('userId', userId) + .not(`metadata->${key}`, 'is', null); + + const ids = new Set(); + for (const row of (data || []) as Array<{ metadata?: Record | null }>) { + const value = row.metadata?.[key]; + if (value !== undefined && value !== null && value !== '') ids.add(String(value)); + } + return ids; +} + +/** Insert imported proposals and return how many were stored. Throws on failure. */ +export async function insertProposals(rows: Array>): Promise { + const { data, error } = await supabase.from('Proposal').insert(rows).select(); + if (error) throw error; + return data?.length || 0; +} + +/** Persist refreshed OAuth credentials on the integration. */ +export async function saveCredentials(integrationId: string, credentials: Record): Promise { + await supabase + .from('Integration') + .update({ credentials, updatedAt: new Date().toISOString() }) + .eq('id', integrationId); +} + +/** Fields every imported proposal shares. */ +export function baseProposal(ctx: SyncContext) { + return { + status: 'PENDING' as const, + userId: ctx.userId, + lockedSections: [], + updatedAt: new Date().toISOString(), + ...(ctx.companyId ? { company_id: ctx.companyId } : {}), + }; +} diff --git a/src/api/lib/sync/demo.ts b/src/api/lib/sync/demo.ts new file mode 100644 index 0000000..6a3974a --- /dev/null +++ b/src/api/lib/sync/demo.ts @@ -0,0 +1,56 @@ +/** + * Demo-mode sync: connections made through the *_DEMO_MODE OAuth flows store + * `credentials.demo = true` and import canned deals, so connect โ†’ sync โ†’ review + * is fully demonstrable without real CRM credentials. + */ + +import { baseProposal, importedIds, insertProposals, failureResult, successResult, type SyncContext, type SyncResult } from './common'; + +export const sampleDeals = (sourceKey: string) => [ + { id: `demo-${sourceKey}-001`, name: 'Acme Corp โ€” Platform Renewal', amount: 120000, stage: 'Negotiation', client: 'Acme Corp' }, + { id: `demo-${sourceKey}-002`, name: 'Globex โ€” Data Migration', amount: 45000, stage: 'Proposal Sent', client: 'Globex Inc' }, + { id: `demo-${sourceKey}-003`, name: 'Initech โ€” Annual Support Contract', amount: 24000, stage: 'Qualification', client: 'Initech LLC' }, +]; + +export async function syncDemo(ctx: SyncContext): Promise { + const { integration } = ctx; + const sourceKey = String(integration.type || 'crm').toLowerCase(); + + try { + const existing = await importedIds(ctx.userId, 'dealId'); + const newDeals = sampleDeals(sourceKey).filter((d) => !existing.has(d.id)); + + if (newDeals.length === 0) { + return successResult(0, { + message: 'Demo sync complete โ€” all sample deals already imported.', + demo: true, + proposalsCreated: 0, + }); + } + + const created = await insertProposals( + newDeals.map((deal) => ({ + id: crypto.randomUUID(), + title: deal.name, + content: `Deal imported from ${integration.name} (demo mode)\n\nClient: ${deal.client}\nAmount: $${deal.amount.toLocaleString()}\nStage: ${deal.stage}\n\nThis record was generated by the demo integration to showcase the CRM import flow.`, + ...baseProposal(ctx), + metadata: { + clientName: deal.client, + dealSize: deal.amount, + source: `${sourceKey}-demo`, + dealId: deal.id, + stageName: deal.stage, + importedAt: new Date().toISOString(), + }, + })) + ); + + return successResult(created, { + message: `Demo sync imported ${created} sample deals from ${integration.name}`, + demo: true, + proposalsCreated: created, + }); + } catch (err) { + return failureResult(err, 'Demo sync failed'); + } +} diff --git a/src/api/lib/sync/gmail.ts b/src/api/lib/sync/gmail.ts new file mode 100644 index 0000000..a3e1073 --- /dev/null +++ b/src/api/lib/sync/gmail.ts @@ -0,0 +1,246 @@ +/** + * Gmail connector: imports recent proposal-related inbox threads as proposals, + * refreshing the access token once when Google answers 401. + */ + +import { logger } from '../logger'; +import { + baseProposal, + credentialField, + failureResult, + importedIds, + insertProposals, + saveCredentials, + successResult, + timeoutSignal, + type SyncContext, + type SyncResult, +} from './common'; + +const GMAIL_API = 'https://gmail.googleapis.com/gmail/v1/users/me/messages'; +const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'; +/** Newest messages fetched in full per sync. */ +const MAX_MESSAGES = 10; + +interface GmailHeader { + name: string; + value: string; +} + +interface GmailPart { + mimeType?: string; + body?: { data?: string }; +} + +interface GmailMessage { + id: string; + threadId: string; + labelIds?: string[]; + internalDate: string; + snippet?: string; + payload: GmailPart & { headers: GmailHeader[]; parts?: GmailPart[] }; +} + +export interface EmailThread { + id: string; + threadId: string; + subject: string; + from: string; + to: string; + date: string; + snippet: string; + body: string; +} + +const decode = (data: string) => Buffer.from(data, 'base64').toString('utf-8'); + +/** Plain-text body of a message (single-part, or the first text/plain part). */ +export function extractBody(payload: GmailMessage['payload']): string { + if (payload.body?.data) return decode(payload.body.data); + for (const part of payload.parts || []) { + if (part.mimeType === 'text/plain' && part.body?.data) return decode(part.body.data); + } + return ''; +} + +/** The figure after "Investment:", else the first dollar amount in the email (0 if none). */ +export function extractDealSize(body: string): number { + const match = body.match(/Investment:?\s*\$?([\d,]+(?:\.\d{2})?)/i) || body.match(/\$\s*([\d,]+(?:\.\d{2})?)/); + return match ? Number.parseFloat(match[1].replace(/,/g, '')) || 0 : 0; +} + +/** Display name from a "Name " header, else the address's local part. */ +export function extractClientName(toHeader: string): string { + const named = toHeader.match(/([^<]+) + message.payload.headers.find((h) => h.name === name)?.value; + +export async function syncGmail(ctx: SyncContext): Promise { + try { + const credentials = ctx.integration.credentials; + let accessToken = credentialField(credentials, 'accessToken', 'access_token'); + const refreshToken = credentialField(credentials, 'refreshToken', 'refresh_token'); + + if (!accessToken) { + throw new Error('No access token found. Please reconnect Gmail in Integrations.'); + } + + // Inbox only, last 30 days, proposal-ish subjects. + const thirtyDaysAgo = new Date(); + thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); + const afterDate = Math.floor(thirtyDaysAgo.getTime() / 1000); + const query = `in:inbox (proposal OR quote OR agreement OR contract) after:${afterDate}`; + const searchUrl = `${GMAIL_API}?q=${encodeURIComponent(query)}&maxResults=50`; + + const authHeaders = () => ({ Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }); + let searchResponse = await fetch(searchUrl, { headers: authHeaders(), signal: timeoutSignal() }); + + // Expired access token: refresh it (needs a refresh token and the Google client env). + if (searchResponse.status === 401) { + const clientId = process.env.GOOGLE_CLIENT_ID; + const clientSecret = process.env.GOOGLE_CLIENT_SECRET; + + if (refreshToken && clientId && clientSecret) { + logger.debug('Gmail access token expired, refreshing...'); + const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + client_id: clientId, + client_secret: clientSecret, + }), + signal: timeoutSignal(), + }); + const tokenBody = await tokenResponse.json(); + + if (tokenResponse.ok && tokenBody.access_token) { + accessToken = tokenBody.access_token as string; + await saveCredentials(ctx.integration.id, { + ...credentials, + accessToken: tokenBody.access_token, + refreshToken: tokenBody.refresh_token ?? refreshToken, + expiresIn: tokenBody.expires_in, + }); + logger.debug('Gmail token refreshed successfully'); + searchResponse = await fetch(searchUrl, { headers: authHeaders(), signal: timeoutSignal() }); + } else { + logger.error('Gmail token refresh failed:', tokenBody.error || tokenResponse.status); + } + } else if (!refreshToken) { + logger.warn('Gmail: no refresh token stored. Disconnect and reconnect Gmail (with prompt=consent) to get one.'); + } else { + logger.warn('Gmail: GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET not set. Cannot refresh token.'); + } + } + + if (!searchResponse.ok) { + const hint = + searchResponse.status === 401 + ? ' Authorization may have expired or been revoked. Please reconnect Gmail in Integrations.' + : ''; + throw new Error(`Gmail API error: ${searchResponse.statusText}.${hint}`); + } + + const searchData = (await searchResponse.json()) as { messages?: Array<{ id: string }> }; + const messages = searchData.messages || []; + + if (messages.length === 0) { + return successResult(0, { + message: 'No proposal-related emails found in the last 30 days', + emailsProcessed: 0, + emailThreads: [], + }); + } + + // Fetch the newest messages in full; skip anything that is not actually in the inbox. + const fetched = await Promise.all( + messages.slice(0, MAX_MESSAGES).map(async (msg): Promise => { + const msgResponse = await fetch(`${GMAIL_API}/${msg.id}`, { headers: authHeaders(), signal: timeoutSignal() }); + if (!msgResponse.ok) return null; + + const data = (await msgResponse.json()) as GmailMessage; + if (!(data.labelIds || []).includes('INBOX')) return null; + + return { + id: data.id, + threadId: data.threadId, + subject: header(data, 'Subject') || 'No Subject', + from: header(data, 'From') || '', + to: header(data, 'To') || '', + date: new Date(Number.parseInt(data.internalDate, 10)).toISOString(), + snippet: data.snippet || '', + body: extractBody(data.payload) || data.snippet || '', + }; + }) + ); + const emails = fetched.filter((e): e is EmailThread => e !== null); + + // The sync log keeps the email's envelope, not its body: bodies can be large + // and private, and the UI only needs to say what was found. + const summaries = emails.map(({ body: _body, ...envelope }) => envelope); + + if (emails.length === 0) { + return successResult(0, { + message: 'No valid email threads found', + emailsProcessed: messages.length, + emailThreads: [], + }); + } + + const existing = await importedIds(ctx.userId, 'emailThreadId'); + // Several messages can share a thread; import each thread once. + const seenThreads = new Set(); + const newEmails = emails.filter((email) => { + if (existing.has(email.threadId) || seenThreads.has(email.threadId)) return false; + seenThreads.add(email.threadId); + return true; + }); + + if (newEmails.length === 0) { + return successResult(0, { + message: 'No new email threads to sync. All emails have already been imported.', + emailsProcessed: messages.length, + emailsAlreadyImported: emails.length, + proposalsCreated: 0, + emailThreads: summaries, + }); + } + + const created = await insertProposals( + newEmails.map((email) => ({ + id: crypto.randomUUID(), + title: email.subject || 'Email Proposal', + content: email.body || email.snippet, + ...baseProposal(ctx), + createdAt: email.date, + metadata: { + source: 'gmail', + emailThreadId: email.threadId, + emailId: email.id, + from: email.from, + to: email.to, + subject: email.subject, + clientName: extractClientName(email.to), + dealSize: extractDealSize(email.body), + importedAt: new Date().toISOString(), + }, + })) + ); + + return successResult(created, { + message: `Successfully synced ${created} new email threads as proposals`, + emailsProcessed: messages.length, + emailsAlreadyImported: emails.length - newEmails.length, + proposalsCreated: created, + emailThreads: summaries, + }); + } catch (err) { + logger.error('Gmail sync error:', err); + return failureResult(err, 'Failed to sync with Gmail'); + } +} diff --git a/src/api/lib/sync/hubspot.ts b/src/api/lib/sync/hubspot.ts new file mode 100644 index 0000000..17fc8a1 --- /dev/null +++ b/src/api/lib/sync/hubspot.ts @@ -0,0 +1,140 @@ +/** + * HubSpot connector: imports open deals as proposals, refreshing the access + * token once when HubSpot answers 401. + */ + +import { logger } from '../logger'; +import { + baseProposal, + credentialField, + failureResult, + importedIds, + insertProposals, + parseMoney, + saveCredentials, + successResult, + timeoutSignal, + type SyncContext, + type SyncResult, +} from './common'; + +export const HUBSPOT_DEALS_URL = + 'https://api.hubapi.com/crm/v3/objects/deals?limit=100&properties=dealname,amount,dealstage,pipeline,closedate,createdate,hs_lastmodifieddate,description'; +const HUBSPOT_TOKEN_URL = 'https://api.hubapi.com/oauth/v1/token'; + +interface HubspotDeal { + id: string; + properties: Record; +} + +const fetchDeals = (accessToken: string) => + fetch(HUBSPOT_DEALS_URL, { + headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, + signal: timeoutSignal(), + }); + +export async function syncHubspot(ctx: SyncContext): Promise { + try { + const credentials = ctx.integration.credentials; + let accessToken = credentialField(credentials, 'accessToken', 'access_token'); + const refreshToken = credentialField(credentials, 'refreshToken', 'refresh_token'); + + if (!accessToken) { + throw new Error('No access token found. Please reconnect HubSpot.'); + } + + let response = await fetchDeals(accessToken); + + // Expired access token: swap it for a new one using the refresh token. + if (response.status === 401 && refreshToken) { + logger.debug('HubSpot access token expired, refreshing...'); + + const tokenResponse = await fetch(HUBSPOT_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'refresh_token', + client_id: process.env.HUBSPOT_CLIENT_ID ?? '', + client_secret: process.env.HUBSPOT_CLIENT_SECRET ?? '', + refresh_token: refreshToken, + }), + signal: timeoutSignal(), + }); + + if (!tokenResponse.ok) { + throw new Error('Failed to refresh token. Please reconnect HubSpot.'); + } + + const tokenData = await tokenResponse.json(); + accessToken = tokenData.access_token as string; + await saveCredentials(ctx.integration.id, { + ...credentials, + accessToken: tokenData.access_token, + refreshToken: tokenData.refresh_token, + expiresIn: tokenData.expires_in, + }); + logger.debug('HubSpot token refreshed successfully'); + + response = await fetchDeals(accessToken); + } + + if (!response.ok) { + const hint = + response.status === 401 + ? ' The access token was rejected (expired or revoked). Please reconnect HubSpot.' + : ''; + throw new Error(`HubSpot API error: ${response.statusText}.${hint}`); + } + + const data = (await response.json()) as { results?: HubspotDeal[] }; + const deals = data.results || []; + + if (deals.length === 0) { + return successResult(0, { message: 'No deals found in HubSpot', dealsProcessed: 0, proposalsCreated: 0 }); + } + + const existing = await importedIds(ctx.userId, 'dealId'); + const newDeals = deals.filter((deal) => !existing.has(String(deal.id))); + + if (newDeals.length === 0) { + return successResult(0, { + message: 'No new deals to sync. All deals have already been imported.', + dealsProcessed: deals.length, + dealsAlreadyImported: deals.length, + proposalsCreated: 0, + }); + } + + const created = await insertProposals( + newDeals.map((deal) => ({ + id: crypto.randomUUID(), + title: deal.properties.dealname || 'Untitled Deal', + content: + deal.properties.description || + `Deal imported from HubSpot\n\nAmount: $${deal.properties.amount || '0'}\nStage: ${deal.properties.dealstage || 'Unknown'}`, + ...baseProposal(ctx), + createdAt: deal.properties.createdate || new Date().toISOString(), + metadata: { + clientName: deal.properties.dealname, + dealSize: parseMoney(deal.properties.amount), + source: 'hubspot', + dealId: deal.id, + dealStage: deal.properties.dealstage, + pipeline: deal.properties.pipeline, + closeDate: deal.properties.closedate, + importedAt: new Date().toISOString(), + }, + })) + ); + + return successResult(created, { + message: `Successfully synced ${created} new deals from HubSpot`, + dealsProcessed: deals.length, + dealsAlreadyImported: deals.length - newDeals.length, + proposalsCreated: created, + }); + } catch (err) { + logger.error('HubSpot sync error:', err); + return failureResult(err, 'Failed to sync with HubSpot'); + } +} diff --git a/src/api/lib/sync/index.ts b/src/api/lib/sync/index.ts new file mode 100644 index 0000000..42d1595 --- /dev/null +++ b/src/api/lib/sync/index.ts @@ -0,0 +1,33 @@ +/** + * CRM sync dispatcher: picks the connector for an integration. + */ + +import { successResult, type SyncContext, type SyncResult } from './common'; +import { syncDemo } from './demo'; +import { syncGmail } from './gmail'; +import { syncHubspot } from './hubspot'; +import { syncSalesforce } from './salesforce'; + +export type { IntegrationRow, SyncContext, SyncResult } from './common'; + +/** Run one sync for the integration in `ctx`. Never throws: failures come back in the result. */ +export async function runSync(ctx: SyncContext): Promise { + const { integration } = ctx; + + // Demo connections import canned deals (see demo.ts) regardless of type. + if (integration.credentials?.demo === true) return syncDemo(ctx); + + if (integration.credentials) { + switch (integration.type) { + case 'HUBSPOT': + return syncHubspot(ctx); + case 'GMAIL': + return syncGmail(ctx); + case 'SALESFORCE': + return syncSalesforce(ctx); + } + } + + // Types without a connector (or without credentials) just record the attempt. + return successResult(0, { message: 'Manual sync triggered' }); +} diff --git a/src/api/lib/sync/salesforce.ts b/src/api/lib/sync/salesforce.ts new file mode 100644 index 0000000..7d1afa1 --- /dev/null +++ b/src/api/lib/sync/salesforce.ts @@ -0,0 +1,186 @@ +/** + * Salesforce connector: imports open opportunities as proposals, refreshing the + * access token once when Salesforce answers 401. + */ + +import { logger } from '../logger'; +import { + baseProposal, + credentialField, + failureResult, + importedIds, + insertProposals, + parseMoney, + saveCredentials, + successResult, + timeoutSignal, + type SyncContext, + type SyncResult, +} from './common'; + +/** Salesforce API version used for queries. */ +const API_VERSION = 'v60.0'; + +const QUERY = + 'SELECT Id, Name, Amount, StageName, CloseDate, Description, Account.Name, CreatedDate, LastModifiedDate ' + + 'FROM Opportunity WHERE IsClosed = false ORDER BY LastModifiedDate DESC LIMIT 100'; + +/** Domains Salesforce serves orgs from (instance, My Domain, sandbox, Government Cloud). */ +const SALESFORCE_DOMAINS = ['salesforce.com', 'force.com', 'cloudforce.com', 'salesforce.mil']; + +/** + * Whether `url` is an https Salesforce org URL. The instance URL is stored in + * credentials that users can edit, and the server calls it with the user's token + * attached โ€” without this check it would be a server-side request forgery vector + * (e.g. pointing it at http://169.254.169.254 or an internal service). + */ +export function isSalesforceUrl(url: string): boolean { + try { + const parsed = new URL(url); + if (parsed.protocol !== 'https:' || parsed.username || parsed.password) return false; + const host = parsed.hostname.toLowerCase(); + return SALESFORCE_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`)); + } catch { + return false; + } +} + +interface Opportunity { + Id: string; + Name?: string; + Amount?: number | null; + StageName?: string; + CloseDate?: string; + Description?: string; + CreatedDate?: string; + Account?: { Name?: string } | null; +} + +export async function syncSalesforce(ctx: SyncContext): Promise { + try { + const credentials = ctx.integration.credentials; + let accessToken = credentialField(credentials, 'accessToken', 'access_token'); + const refreshToken = credentialField(credentials, 'refreshToken', 'refresh_token'); + let instanceUrl = credentialField(credentials, 'instanceUrl', 'instance_url'); + + if (!accessToken) { + throw new Error('No access token found. Please reconnect Salesforce.'); + } + if (!instanceUrl) { + throw new Error('No instance URL found. Please reconnect Salesforce.'); + } + if (!isSalesforceUrl(instanceUrl)) { + throw new Error('The stored Salesforce instance URL is not a Salesforce address. Please reconnect Salesforce.'); + } + + const queryUrl = (base: string) => `${base}/services/data/${API_VERSION}/query?q=${encodeURIComponent(QUERY)}`; + const authHeaders = () => ({ Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }); + + let response = await fetch(queryUrl(instanceUrl), { headers: authHeaders(), signal: timeoutSignal() }); + + // Expired access token: swap it for a new one using the refresh token. + if (response.status === 401 && refreshToken) { + const isSandbox = process.env.SALESFORCE_SANDBOX === 'true'; + const loginHost = isSandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com'; + + logger.debug('Salesforce access token expired, refreshing...'); + const tokenResponse = await fetch(`${loginHost}/services/oauth2/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + client_id: process.env.SALESFORCE_CLIENT_ID ?? '', + client_secret: process.env.SALESFORCE_CLIENT_SECRET ?? '', + }), + signal: timeoutSignal(), + }); + + if (!tokenResponse.ok) { + throw new Error('Failed to refresh token. Please reconnect Salesforce.'); + } + + const tokenData = await tokenResponse.json(); + accessToken = tokenData.access_token as string; + const newInstanceUrl: string = tokenData.instance_url || instanceUrl; + if (!isSalesforceUrl(newInstanceUrl)) { + throw new Error('Salesforce returned an unexpected instance URL. Please reconnect Salesforce.'); + } + instanceUrl = newInstanceUrl; + + await saveCredentials(ctx.integration.id, { + ...credentials, + accessToken: tokenData.access_token, + refreshToken: tokenData.refresh_token ?? refreshToken, + expiresIn: tokenData.expires_in, + instanceUrl, + }); + logger.debug('Salesforce token refreshed successfully'); + + response = await fetch(queryUrl(instanceUrl), { headers: authHeaders(), signal: timeoutSignal() }); + } + + if (!response.ok) { + const hint = + response.status === 401 + ? ' Authorization may have expired or been revoked. Please reconnect Salesforce.' + : ''; + throw new Error(`Salesforce API error: ${response.statusText}.${hint}`); + } + + const data = (await response.json()) as { records?: Opportunity[] }; + const opportunities = data.records || []; + + if (opportunities.length === 0) { + return successResult(0, { + message: 'No open opportunities found in Salesforce', + opportunitiesProcessed: 0, + proposalsCreated: 0, + }); + } + + const existing = await importedIds(ctx.userId, 'opportunityId'); + const fresh = opportunities.filter((opp) => !existing.has(String(opp.Id))); + + if (fresh.length === 0) { + return successResult(0, { + message: 'No new opportunities to sync. All opportunities have already been imported.', + opportunitiesProcessed: opportunities.length, + opportunitiesAlreadyImported: opportunities.length, + proposalsCreated: 0, + }); + } + + const created = await insertProposals( + fresh.map((opp) => ({ + id: crypto.randomUUID(), + title: opp.Name || 'Untitled Opportunity', + content: + opp.Description || + `Opportunity imported from Salesforce\n\nAmount: $${opp.Amount || '0'}\nStage: ${opp.StageName || 'Unknown'}\nAccount: ${opp.Account?.Name || 'N/A'}`, + ...baseProposal(ctx), + createdAt: opp.CreatedDate || new Date().toISOString(), + metadata: { + clientName: opp.Account?.Name || opp.Name, + dealSize: parseMoney(opp.Amount), + source: 'salesforce', + opportunityId: opp.Id, + stageName: opp.StageName, + closeDate: opp.CloseDate, + accountName: opp.Account?.Name, + importedAt: new Date().toISOString(), + }, + })) + ); + + return successResult(created, { + message: `Successfully synced ${created} new opportunities from Salesforce`, + opportunitiesProcessed: opportunities.length, + opportunitiesAlreadyImported: opportunities.length - fresh.length, + proposalsCreated: created, + }); + } catch (err) { + logger.error('Salesforce sync error:', err); + return failureResult(err, 'Failed to sync with Salesforce'); + } +} diff --git a/src/api/oauth.ts b/src/api/oauth.ts index 7cd8f31..4db5367 100644 --- a/src/api/oauth.ts +++ b/src/api/oauth.ts @@ -1,561 +1,350 @@ -import { Router, Request, Response, NextFunction } from 'express'; -import { supabase } from '../lib/supabase'; -import { resolveSessionUser } from './middleware/auth'; -import { logger } from './lib/logger'; - -const router = Router(); - -// Frontend URL for OAuth redirects -const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:8080'; - -/** - * Auth for OAuth redirects. These are top-level browser navigations, so no - * Authorization header is available โ€” the token (when there is one) rides in the - * query string. With login removed there usually isn't one, and the request - * falls back to the default user, same as every other route. - */ -const requireAuthFromQuery = async (req: Request, res: Response, next: NextFunction) => { - try { - const { user } = await resolveSessionUser(req.query.token as string | undefined); - if (!user) { - return res.redirect(`${FRONTEND_URL}/integrations?error=unauthorized`); - } - req.user = user; - next(); - } catch (error) { - logger.error('OAuth session lookup failed', error as Error); - return res.redirect(`${FRONTEND_URL}/integrations?error=unauthorized`); - } -}; - -// Salesforce OAuth flow -router.get('/salesforce/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { - const isDemoMode = process.env.SALESFORCE_DEMO_MODE === 'true'; - const userId = req.user?.id; - - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=not_authenticated`); - } - - if (isDemoMode) { - try { - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'SALESFORCE') - .eq('userId', userId) - // Tolerate duplicate rows from before this upsert existed: .single() - // errors on >1 rows, which made every reconnect insert another copy. - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - const credentials = { demo: true, accessToken: 'demo_token' }; - - if (existing) { - await supabase - .from('Integration') - .update({ - name: 'Salesforce', - credentials, - isActive: true, - updatedAt: new Date().toISOString() - }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'SALESFORCE', - name: 'Salesforce', - credentials, - config: {}, - isActive: true, - userId: userId, - updatedAt: new Date().toISOString(), - }); - } - } catch (err) { - console.error('Failed to create Salesforce demo integration:', err); - } - - res.redirect(`${FRONTEND_URL}/integrations?salesforce=demo&success=true`); - return; - } - - const clientId = process.env.SALESFORCE_CLIENT_ID; - const redirectUri = process.env.SALESFORCE_REDIRECT_URI || 'http://localhost:3001/api/oauth/salesforce/callback'; - const isSandbox = process.env.SALESFORCE_SANDBOX === 'true'; - - const state = userId; // Use userId as state to identify the user on callback - const baseUrl = isSandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com'; - let authUrl = `${baseUrl}/services/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=api%20refresh_token`; - if (state) authUrl += `&state=${encodeURIComponent(state)}`; - res.redirect(authUrl); -}); - -router.get('/salesforce/callback', async (req: Request, res: Response) => { - try { - const { code, state } = req.query; - - if (!code) { - return res.redirect(`${FRONTEND_URL}/integrations?error=no_code`); - } - - const userId = state as string; // userId passed from authorize - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=not_authenticated`); - } - - // Exchange code for token - const clientId = process.env.SALESFORCE_CLIENT_ID; - const clientSecret = process.env.SALESFORCE_CLIENT_SECRET; - const redirectUri = process.env.SALESFORCE_REDIRECT_URI || 'http://localhost:3001/api/oauth/salesforce/callback'; - const isSandbox = process.env.SALESFORCE_SANDBOX === 'true'; - - const baseUrl = isSandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com'; - const tokenUrl = `${baseUrl}/services/oauth2/token`; - - const response = await fetch(tokenUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'authorization_code', - code: code as string, - client_id: clientId!, - client_secret: clientSecret!, - redirect_uri: redirectUri, - }), - }); - - if (!response.ok) { - const errorText = await response.text(); - console.error('Salesforce token exchange failed:', errorText); - return res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - - const data = await response.json(); - - if (data.access_token) { - try { - const credentials = { - accessToken: data.access_token, - refreshToken: data.refresh_token, - expiresIn: data.expires_in, - instanceUrl: data.instance_url, - }; - - const { data: existing } = await supabase - .from('Integration') - .select('id') - .eq('type', 'SALESFORCE') - .eq('userId', userId) - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - if (existing) { - await supabase - .from('Integration') - .update({ - credentials, - isActive: true, - updatedAt: new Date().toISOString(), - }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'SALESFORCE', - name: 'Salesforce', - credentials, - config: {}, - isActive: true, - userId: userId, - updatedAt: new Date().toISOString(), - }); - } - } catch (err) { - console.error('Failed to upsert Salesforce integration:', err); - } - - res.redirect(`${FRONTEND_URL}/integrations?salesforce=connected&success=true`); - } else { - res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - } catch (error) { - console.error('Salesforce OAuth error:', error); - res.redirect(`${FRONTEND_URL}/integrations?error=oauth_failed`); - } -}); - -// HubSpot OAuth flow -router.get('/hubspot/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { - const isDemoMode = process.env.HUBSPOT_DEMO_MODE === 'true'; - const userId = req.user?.id; - - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=not_authenticated`); - } - - if (isDemoMode) { - try { - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'HUBSPOT') - .eq('userId', userId) - // Tolerate duplicate rows from before this upsert existed: .single() - // errors on >1 rows, which made every reconnect insert another copy. - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - const credentials = { demo: true, accessToken: 'demo_token' }; - - if (existing) { - await supabase - .from('Integration') - .update({ - name: 'HubSpot', - credentials, - isActive: true, - updatedAt: new Date().toISOString() - }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'HUBSPOT', - name: 'HubSpot', - credentials, - config: {}, - isActive: true, - userId: userId, - updatedAt: new Date().toISOString(), - }); - } - } catch (err) { - console.error('Failed to create HubSpot demo integration:', err); - } - - res.redirect(`${FRONTEND_URL}/integrations?hubspot=demo&success=true`); - return; - } - - // Check if using Private App (access token) instead of OAuth - const accessToken = process.env.HUBSPOT_ACCESS_TOKEN; - if (accessToken) { - try { - // Upsert Integration record into Supabase - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'HUBSPOT') - .eq('userId', userId) - // Tolerate duplicate rows from before this upsert existed: .single() - // errors on >1 rows, which made every reconnect insert another copy. - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - if (existing) { - await supabase - .from('Integration') - .update({ credentials: { accessToken }, isActive: true, updatedAt: new Date().toISOString() }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'HUBSPOT', - name: 'HubSpot', - credentials: { accessToken }, - config: {}, - isActive: true, - userId: userId, - }); - } - } catch (err) { - console.error('Failed to upsert HubSpot integration:', err); - } - - // Private App - directly mark as connected - res.redirect(`${FRONTEND_URL}/integrations?hubspot=connected&success=true&type=private`); - return; - } - - // OAuth flow for Public Apps - const clientId = process.env.HUBSPOT_CLIENT_ID; - if (!clientId) { - res.redirect(`${FRONTEND_URL}/integrations?error=no_client_id`); - return; - } - - const redirectUri = process.env.HUBSPOT_REDIRECT_URI || 'http://localhost:3001/api/oauth/hubspot/callback'; - const state = userId; // Use userId as state - const scopes = 'crm.objects.contacts.read crm.objects.deals.read'; - let authUrl = `https://app.hubspot.com/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scopes)}`; - if (state) authUrl += `&state=${encodeURIComponent(state)}`; - res.redirect(authUrl); -}); - -router.get('/hubspot/callback', async (req: Request, res: Response) => { - try { - const { code, error: hubspotError, state } = req.query; - - if (hubspotError) { - console.error('HubSpot OAuth denied or error:', hubspotError); - return res.redirect(`${FRONTEND_URL}/integrations?error=${encodeURIComponent(String(hubspotError))}`); - } - - if (!code) { - return res.redirect(`${FRONTEND_URL}/integrations?error=no_code`); - } - - const userId = state as string; - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=not_authenticated`); - } - const clientId = process.env.HUBSPOT_CLIENT_ID; - const clientSecret = process.env.HUBSPOT_CLIENT_SECRET; - const redirectUri = process.env.HUBSPOT_REDIRECT_URI || 'http://localhost:3001/api/oauth/hubspot/callback'; - - const tokenUrl = 'https://api.hubapi.com/oauth/v1/token'; - - const response = await fetch(tokenUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'authorization_code', - code: code as string, - client_id: clientId!, - client_secret: clientSecret!, - redirect_uri: redirectUri, - }), - }); - - if (!response.ok) { - const errorText = await response.text(); - console.error('HubSpot token exchange failed:', errorText); - return res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - - const data = await response.json(); - - if (data.access_token) { - try { - const credentials = { - accessToken: data.access_token, - refreshToken: data.refresh_token, - expiresIn: data.expires_in, - }; - - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'HUBSPOT') - .eq('userId', userId) - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - if (existing) { - logger.debug('Updating existing HubSpot integration:', existing.id); - - const { error: updateError } = await supabase - .from('Integration') - .update({ - credentials, - isActive: true, - updatedAt: new Date().toISOString(), - }) - .eq('id', existing.id) - .select() - .single(); - - if (updateError) throw updateError; - logger.debug('HubSpot integration updated successfully'); - } else { - logger.debug('Creating new HubSpot integration for user:', userId); - - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'HUBSPOT', - name: 'HubSpot', - credentials, - config: {}, - isActive: true, - userId: userId, - updatedAt: new Date().toISOString(), - }); - - logger.debug('HubSpot integration created successfully'); - } - } catch (err) { - console.error('Failed to upsert HubSpot integration:', err); - return res.redirect(`${FRONTEND_URL}/integrations?error=hubspot_save_failed`); - } - - res.redirect(`${FRONTEND_URL}/integrations?hubspot=connected&success=true`); - } else { - res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - } catch (error) { - console.error('HubSpot OAuth error:', error); - res.redirect(`${FRONTEND_URL}/integrations?error=oauth_failed`); - } -}); - -// Gmail OAuth flow -router.get('/gmail/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { - const userId = req.user?.id; - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=unauthorized`); - } - - const isDemoMode = process.env.GMAIL_DEMO_MODE === 'true'; - - if (isDemoMode) { - try { - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'GMAIL') - .eq('userId', userId) - // Tolerate duplicate rows from before this upsert existed: .single() - // errors on >1 rows, which made every reconnect insert another copy. - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - const credentials = { demo: true, accessToken: 'demo_token' }; - - if (existing) { - await supabase - .from('Integration') - .update({ - name: 'Gmail', - credentials, - isActive: true, - updatedAt: new Date().toISOString() - }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'GMAIL', - name: 'Gmail', - userId, - credentials, - config: {}, - isActive: true, - updatedAt: new Date().toISOString(), - }); - } - } catch (err) { - console.error('Failed to create Gmail demo integration:', err); - } - - res.redirect(`${FRONTEND_URL}/integrations?gmail=demo&success=true`); - return; - } - - const clientId = process.env.GOOGLE_CLIENT_ID; - const redirectUri = process.env.GOOGLE_REDIRECT_URI || 'http://localhost:3001/api/oauth/gmail/callback'; - const scopes = 'https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/gmail.readonly'; - const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent(scopes)}&access_type=offline&prompt=consent&state=${encodeURIComponent(userId)}`; - res.redirect(authUrl); -}); - -router.get('/gmail/callback', async (req: Request, res: Response) => { - try { - const { code, state } = req.query; - const userId = state as string; - - if (!code) { - return res.redirect(`${FRONTEND_URL}/integrations?error=no_code`); - } - - if (!userId) { - return res.redirect(`${FRONTEND_URL}/integrations?error=unauthorized`); - } - - const clientId = process.env.GOOGLE_CLIENT_ID; - const clientSecret = process.env.GOOGLE_CLIENT_SECRET; - const redirectUri = process.env.GOOGLE_REDIRECT_URI || 'http://localhost:3001/api/oauth/gmail/callback'; - - const tokenUrl = 'https://oauth2.googleapis.com/token'; - - const response = await fetch(tokenUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - grant_type: 'authorization_code', - code: code as string, - client_id: clientId!, - client_secret: clientSecret!, - redirect_uri: redirectUri, - }), - }); - - if (!response.ok) { - const errorText = await response.text(); - console.error('Gmail token exchange failed:', errorText); - return res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - - const data = await response.json(); - - if (data.access_token) { - try { - const { data: existing } = await supabase - .from('Integration') - .select('*') - .eq('type', 'GMAIL') - .eq('userId', userId) - .order('createdAt', { ascending: false }) - .limit(1) - .maybeSingle(); - - const prevCreds = (existing?.credentials || {}) as Record; - const credentials = { - accessToken: data.access_token, - refreshToken: data.refresh_token || prevCreds.refreshToken || prevCreds.refresh_token, - expiresIn: data.expires_in, - }; - - if (existing) { - await supabase - .from('Integration') - .update({ - credentials, - isActive: true, - updatedAt: new Date().toISOString() - }) - .eq('id', existing.id); - } else { - await supabase.from('Integration').insert({ - id: (crypto as any).randomUUID(), - type: 'GMAIL', - name: 'Gmail', - userId, - credentials, - config: {}, - isActive: true, - updatedAt: new Date().toISOString(), - }); - } - } catch (err) { - console.error('Failed to upsert Gmail integration:', err); - } - - res.redirect(`${FRONTEND_URL}/integrations?gmail=connected&success=true`); - } else { - res.redirect(`${FRONTEND_URL}/integrations?error=token_exchange_failed`); - } - } catch (error) { - console.error('Gmail OAuth error:', error); - res.redirect(`${FRONTEND_URL}/integrations?error=oauth_failed`); - } -}); - -export default router; +import { Router, Request, Response, NextFunction } from 'express'; +import { loadUserById, requireAuth, resolveSessionUser } from './middleware/auth'; +import { isLoginMode } from './lib/authConfig'; +import { upsertIntegration, type OAuthProvider } from './lib/integrationStore'; +import { signOAuthStart, signOAuthState, verifyOAuthStart, verifyOAuthState } from './lib/oauthState'; +import { logger } from './lib/logger'; + +const router = Router(); + +// Frontend URL for OAuth redirects +const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:8080'; + +const redirectToIntegrations = (res: Response, query: string) => + res.redirect(`${FRONTEND_URL}/integrations?${query}`); + +// The SPA calls this (with its normal Authorization header) just before it +// navigates the browser to an /authorize endpoint, which cannot carry a header. +// The token is good for two minutes and only for the /authorize redirects. +router.post('/start-token', requireAuth, (req: Request, res: Response) => { + res.json({ token: signOAuthStart(req.user!.id) }); +}); + +/** + * Auth for the /authorize redirects (top-level browser navigations, so no header). + * The identity is a short-lived start token from POST /start-token. In demo mode โ€” + * where there are no sessions โ€” a request without one is served as the default + * user, as before. In login mode a start token is required. + */ +const requireAuthFromQuery = async (req: Request, res: Response, next: NextFunction) => { + try { + const token = typeof req.query.token === 'string' ? req.query.token : undefined; + + const startUserId = verifyOAuthStart(token); + let user = startUserId ? (await loadUserById(startUserId)).user : null; + + if (!user && !isLoginMode()) { + user = (await resolveSessionUser(token)).user; + } + + if (!user) { + return redirectToIntegrations(res, 'error=unauthorized'); + } + req.user = user; + next(); + } catch (error) { + logger.error('OAuth session lookup failed', error as Error); + return redirectToIntegrations(res, 'error=unauthorized'); + } +}; + +/** Store (or refresh) the connection, or redirect with an error. Returns true on success. */ +async function saveConnection( + res: Response, + opts: Parameters[0] +): Promise { + try { + await upsertIntegration(opts); + return true; + } catch (err) { + logger.error(`Failed to save ${opts.type} integration:`, err); + redirectToIntegrations(res, 'error=integration_save_failed'); + return false; + } +} + +const DEMO_CREDENTIALS = { demo: true, accessToken: 'demo_token' }; + +/** Demo-mode connect: store `{demo: true}` credentials and return to the SPA. */ +async function connectDemo(res: Response, userId: string, type: OAuthProvider, name: string, param: string) { + const saved = await saveConnection(res, { + userId, + type, + name, + credentials: () => DEMO_CREDENTIALS, + resetName: true, + }); + if (saved) redirectToIntegrations(res, `${param}=demo&success=true`); +} + +/** The fields of an OAuth token response this app uses. */ +interface TokenResponse { + access_token?: string; + refresh_token?: string; + expires_in?: number; + instance_url?: string; +} + +/** POST to a provider's token endpoint with the authorization code. */ +async function exchangeCode( + tokenUrl: string, + params: Record, + provider: string +): Promise { + const response = await fetch(tokenUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(params), + signal: AbortSignal.timeout(20_000), + }); + + if (!response.ok) { + logger.error(`${provider} token exchange failed:`, response.status, await response.text()); + return null; + } + return response.json(); +} + +// --------------------------------------------------------------------------- +// Salesforce +// --------------------------------------------------------------------------- + +const salesforceBase = () => + process.env.SALESFORCE_SANDBOX === 'true' ? 'https://test.salesforce.com' : 'https://login.salesforce.com'; +const salesforceRedirectUri = () => + process.env.SALESFORCE_REDIRECT_URI || 'http://localhost:3001/api/oauth/salesforce/callback'; + +router.get('/salesforce/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { + const userId = req.user?.id; + if (!userId) { + return redirectToIntegrations(res, 'error=not_authenticated'); + } + + if (process.env.SALESFORCE_DEMO_MODE === 'true') { + return connectDemo(res, userId, 'SALESFORCE', 'Salesforce', 'salesforce'); + } + + const authUrl = + `${salesforceBase()}/services/oauth2/authorize?response_type=code` + + `&client_id=${encodeURIComponent(process.env.SALESFORCE_CLIENT_ID ?? '')}` + + `&redirect_uri=${encodeURIComponent(salesforceRedirectUri())}` + + `&scope=api%20refresh_token&state=${encodeURIComponent(signOAuthState(userId))}`; + res.redirect(authUrl); +}); + +router.get('/salesforce/callback', async (req: Request, res: Response) => { + try { + const { code, state } = req.query; + + if (!code) { + return redirectToIntegrations(res, 'error=no_code'); + } + const userId = verifyOAuthState(state); + if (!userId) { + return redirectToIntegrations(res, 'error=invalid_state'); + } + + const data = await exchangeCode( + `${salesforceBase()}/services/oauth2/token`, + { + grant_type: 'authorization_code', + code: code as string, + client_id: process.env.SALESFORCE_CLIENT_ID ?? '', + client_secret: process.env.SALESFORCE_CLIENT_SECRET ?? '', + redirect_uri: salesforceRedirectUri(), + }, + 'Salesforce' + ); + + if (!data?.access_token) { + return redirectToIntegrations(res, 'error=token_exchange_failed'); + } + + const saved = await saveConnection(res, { + userId, + type: 'SALESFORCE', + name: 'Salesforce', + credentials: () => ({ + accessToken: data.access_token, + refreshToken: data.refresh_token, + expiresIn: data.expires_in, + instanceUrl: data.instance_url, + }), + }); + if (saved) redirectToIntegrations(res, 'salesforce=connected&success=true'); + } catch (error) { + logger.error('Salesforce OAuth error:', error); + redirectToIntegrations(res, 'error=oauth_failed'); + } +}); + +// --------------------------------------------------------------------------- +// HubSpot +// --------------------------------------------------------------------------- + +const hubspotRedirectUri = () => + process.env.HUBSPOT_REDIRECT_URI || 'http://localhost:3001/api/oauth/hubspot/callback'; + +router.get('/hubspot/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { + const userId = req.user?.id; + if (!userId) { + return redirectToIntegrations(res, 'error=not_authenticated'); + } + + if (process.env.HUBSPOT_DEMO_MODE === 'true') { + return connectDemo(res, userId, 'HUBSPOT', 'HubSpot', 'hubspot'); + } + + // Private App: one server-wide access token instead of per-user OAuth. In + // login mode that token is shared company access, so only admins may attach it. + const privateAppToken = process.env.HUBSPOT_ACCESS_TOKEN; + if (privateAppToken) { + if (isLoginMode() && req.user?.role !== 'ADMIN') { + return redirectToIntegrations(res, 'error=forbidden'); + } + const saved = await saveConnection(res, { + userId, + type: 'HUBSPOT', + name: 'HubSpot', + credentials: () => ({ accessToken: privateAppToken }), + }); + if (saved) redirectToIntegrations(res, 'hubspot=connected&success=true&type=private'); + return; + } + + // OAuth flow for Public Apps + const clientId = process.env.HUBSPOT_CLIENT_ID; + if (!clientId) { + return redirectToIntegrations(res, 'error=no_client_id'); + } + + const scopes = 'crm.objects.contacts.read crm.objects.deals.read'; + const authUrl = + `https://app.hubspot.com/oauth/authorize?client_id=${encodeURIComponent(clientId)}` + + `&redirect_uri=${encodeURIComponent(hubspotRedirectUri())}` + + `&scope=${encodeURIComponent(scopes)}&state=${encodeURIComponent(signOAuthState(userId))}`; + res.redirect(authUrl); +}); + +router.get('/hubspot/callback', async (req: Request, res: Response) => { + try { + const { code, error: hubspotError, state } = req.query; + + if (hubspotError) { + logger.error('HubSpot OAuth denied or error:', hubspotError); + return redirectToIntegrations(res, `error=${encodeURIComponent(String(hubspotError))}`); + } + if (!code) { + return redirectToIntegrations(res, 'error=no_code'); + } + const userId = verifyOAuthState(state); + if (!userId) { + return redirectToIntegrations(res, 'error=invalid_state'); + } + + const data = await exchangeCode( + 'https://api.hubapi.com/oauth/v1/token', + { + grant_type: 'authorization_code', + code: code as string, + client_id: process.env.HUBSPOT_CLIENT_ID ?? '', + client_secret: process.env.HUBSPOT_CLIENT_SECRET ?? '', + redirect_uri: hubspotRedirectUri(), + }, + 'HubSpot' + ); + + if (!data?.access_token) { + return redirectToIntegrations(res, 'error=token_exchange_failed'); + } + + const saved = await saveConnection(res, { + userId, + type: 'HUBSPOT', + name: 'HubSpot', + credentials: () => ({ + accessToken: data.access_token, + refreshToken: data.refresh_token, + expiresIn: data.expires_in, + }), + }); + if (saved) redirectToIntegrations(res, 'hubspot=connected&success=true'); + } catch (error) { + logger.error('HubSpot OAuth error:', error); + redirectToIntegrations(res, 'error=oauth_failed'); + } +}); + +// --------------------------------------------------------------------------- +// Gmail +// --------------------------------------------------------------------------- + +const gmailRedirectUri = () => + process.env.GOOGLE_REDIRECT_URI || 'http://localhost:3001/api/oauth/gmail/callback'; + +router.get('/gmail/authorize', requireAuthFromQuery, async (req: Request, res: Response) => { + const userId = req.user?.id; + if (!userId) { + return redirectToIntegrations(res, 'error=unauthorized'); + } + + if (process.env.GMAIL_DEMO_MODE === 'true') { + return connectDemo(res, userId, 'GMAIL', 'Gmail', 'gmail'); + } + + const scopes = 'https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/gmail.readonly'; + const authUrl = + `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(process.env.GOOGLE_CLIENT_ID ?? '')}` + + `&redirect_uri=${encodeURIComponent(gmailRedirectUri())}&response_type=code` + + `&scope=${encodeURIComponent(scopes)}&access_type=offline&prompt=consent` + + `&state=${encodeURIComponent(signOAuthState(userId))}`; + res.redirect(authUrl); +}); + +router.get('/gmail/callback', async (req: Request, res: Response) => { + try { + const { code, state } = req.query; + + if (!code) { + return redirectToIntegrations(res, 'error=no_code'); + } + const userId = verifyOAuthState(state); + if (!userId) { + return redirectToIntegrations(res, 'error=invalid_state'); + } + + const data = await exchangeCode( + 'https://oauth2.googleapis.com/token', + { + grant_type: 'authorization_code', + code: code as string, + client_id: process.env.GOOGLE_CLIENT_ID ?? '', + client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '', + redirect_uri: gmailRedirectUri(), + }, + 'Gmail' + ); + + if (!data?.access_token) { + return redirectToIntegrations(res, 'error=token_exchange_failed'); + } + + const saved = await saveConnection(res, { + userId, + type: 'GMAIL', + name: 'Gmail', + // Google only sends a refresh token on first consent; keep the one we already have. + credentials: (existing) => ({ + accessToken: data.access_token, + refreshToken: data.refresh_token || existing.refreshToken || existing.refresh_token, + expiresIn: data.expires_in, + }), + }); + if (saved) redirectToIntegrations(res, 'gmail=connected&success=true'); + } catch (error) { + logger.error('Gmail OAuth error:', error); + redirectToIntegrations(res, 'error=oauth_failed'); + } +}); + +export default router; diff --git a/tests/integrations.test.ts b/tests/integrations.test.ts new file mode 100644 index 0000000..074f35a --- /dev/null +++ b/tests/integrations.test.ts @@ -0,0 +1,242 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +const { runSyncMock } = vi.hoisted(() => ({ runSyncMock: vi.fn() })); +vi.mock('../src/api/lib/sync', () => ({ runSync: runSyncMock })); + +import * as supabaseModule from '../src/lib/supabase'; +import integrationsRouter from '../src/api/integrations'; +import { resetDefaultUser } from '../src/api/middleware/auth'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; + +const USER = { id: 'u1', email: 'u@b.com', role: 'SALES_REP', company_id: 'c1' }; + +const row = (over: Record = {}) => ({ + id: 'int1', + type: 'HUBSPOT', + name: 'HubSpot', + userId: 'u1', + isActive: true, + credentials: { accessToken: 'SECRET-ACCESS', refreshToken: 'SECRET-REFRESH' }, + config: {}, + lastSyncAt: null, + ...over, +}); + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/integrations', integrationsRouter); + return app; +} + +/** The signed-in default user, plus the integration row(s) the routes will find. */ +function seed(integration: Record | null = row(), user = USER) { + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select') return { data: [user] }; + if (ctx.table === 'Integration' && ctx.op === 'select') { + return ctx.single ? { data: integration } : { data: integration ? [integration] : [] }; + } + if (ctx.table === 'Integration' && (ctx.op === 'insert' || ctx.op === 'update')) { + return { data: { ...integration, ...(ctx.payload as object) } }; + } + if (ctx.table === 'SyncLog' && ctx.op === 'insert') return { data: { id: 'log1', ...(ctx.payload as object) } }; + return undefined; + }); +} + +const syncOk = (over: Record = {}) => ({ + recordsAffected: 2, + failed: false, + deactivate: false, + details: { message: 'Synced 2 new deals' }, + ...over, +}); + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + runSyncMock.mockReset(); + delete process.env.AUTH_MODE; +}); + +describe('credentials never reach the browser', () => { + const SECRETS = ['SECRET-ACCESS', 'SECRET-REFRESH']; + + it('redacts tokens from the list but still says the integration is connected', async () => { + seed(); + const res = await request(buildApp()).get('/api/integrations'); + + expect(res.status).toBe(200); + expect(res.body[0]).toMatchObject({ id: 'int1', hasCredentials: true, credentials: { connected: true } }); + for (const secret of SECRETS) expect(JSON.stringify(res.body)).not.toContain(secret); + }); + + it('shows empty credentials for a disconnected integration', async () => { + seed(row({ credentials: {}, isActive: false })); + const res = await request(buildApp()).get('/api/integrations'); + expect(res.body[0]).toMatchObject({ hasCredentials: false, credentials: {} }); + }); + + it('flags demo connections', async () => { + seed(row({ credentials: { demo: true, accessToken: 'demo_token' } })); + const res = await request(buildApp()).get('/api/integrations'); + expect(res.body[0].credentials).toEqual({ connected: true, demo: true }); + }); + + it('redacts a single integration, a create, and an update too', async () => { + seed(); + const single = await request(buildApp()).get('/api/integrations/int1'); + const created = await request(buildApp()) + .post('/api/integrations') + .send({ type: 'HUBSPOT', name: 'HubSpot', credentials: { accessToken: 'SECRET-ACCESS' } }); + const updated = await request(buildApp()).patch('/api/integrations/int1').send({ name: 'Renamed' }); + + for (const res of [single, created, updated]) { + expect(res.status).toBeLessThan(300); + for (const secret of SECRETS) expect(JSON.stringify(res.body)).not.toContain(secret); + } + }); + + it('still lets the SPA disconnect by clearing credentials', async () => { + seed(); + const res = await request(buildApp()).patch('/api/integrations/int1').send({ isActive: false, credentials: {} }); + expect(res.status).toBe(200); + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ isActive: false, credentials: {} }); + }); +}); + +describe('ownership', () => { + it("only lists the caller's integrations", async () => { + seed(); + await request(buildApp()).get('/api/integrations'); + expect(sb.callsFor('Integration', 'select')[0].filters).toContainEqual(['eq', 'userId', 'u1']); + }); + + it("403s when touching someone else's integration", async () => { + seed(row({ userId: 'someone-else' })); + expect((await request(buildApp()).patch('/api/integrations/int1').send({ name: 'x' })).status).toBe(403); + expect((await request(buildApp()).delete('/api/integrations/int1')).status).toBe(403); + expect((await request(buildApp()).get('/api/integrations/int1/logs')).status).toBe(403); + expect(sb.callsFor('Integration', 'update')).toHaveLength(0); + expect(sb.callsFor('Integration', 'delete')).toHaveLength(0); + }); + + it('404s a sync for an integration that is not yours', async () => { + seed(null); + const res = await request(buildApp()).post('/api/integrations/int1/sync'); + expect(res.status).toBe(404); + expect(runSyncMock).not.toHaveBeenCalled(); + }); +}); + +describe('POST /api/integrations', () => { + it('requires a type and name, and rejects unknown types', async () => { + seed(); + expect((await request(buildApp()).post('/api/integrations').send({ name: 'x' })).status).toBe(400); + expect((await request(buildApp()).post('/api/integrations').send({ type: 'HUBSPOT' })).status).toBe(400); + const unknown = await request(buildApp()).post('/api/integrations').send({ type: 'MYSPACE', name: 'x' }); + expect(unknown.status).toBe(400); + expect(unknown.body.error).toMatch(/Unknown integration type/); + }); +}); + +describe('DELETE /api/integrations/:id', () => { + it('removes the sync logs before the integration (no DB cascade)', async () => { + seed(); + const res = await request(buildApp()).delete('/api/integrations/int1'); + expect(res.status).toBe(204); + const order = sb.calls.filter((c) => c.op === 'delete').map((c) => c.table); + expect(order).toEqual(['SyncLog', 'Integration']); + }); +}); + +describe('POST /api/integrations/:id/sync', () => { + it('runs the sync for the owner and records success', async () => { + seed(); + runSyncMock.mockResolvedValue(syncOk()); + + const res = await request(buildApp()).post('/api/integrations/int1/sync'); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ success: true, message: 'Synced 2 new deals', recordsAffected: 2 }); + expect(runSyncMock).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'u1', companyId: 'c1', integration: expect.objectContaining({ id: 'int1' }) }) + ); + expect(sb.callsFor('SyncLog', 'insert')[0].payload).toMatchObject({ + integrationId: 'int1', + status: 'SUCCESS', + recordsAffected: 2, + }); + // lastSyncAt is bumped on success. + expect(sb.callsFor('Integration', 'update').some((c) => 'lastSyncAt' in (c.payload as object))).toBe(true); + }); + + it('counts a sync with nothing new as a success', async () => { + seed(); + runSyncMock.mockResolvedValue(syncOk({ recordsAffected: 0, details: { message: 'No new deals' } })); + const res = await request(buildApp()).post('/api/integrations/int1/sync'); + expect(res.body.success).toBe(true); + expect(sb.callsFor('SyncLog', 'insert')[0].payload).toMatchObject({ status: 'SUCCESS' }); + }); + + it('answers a failed sync with 424, the reason, and a log entry โ€” not a 200', async () => { + seed(); + runSyncMock.mockResolvedValue({ + recordsAffected: 0, + failed: true, + deactivate: false, + details: { error: 'HubSpot API error: Service Unavailable.', message: 'Sync failed' }, + }); + + const res = await request(buildApp()).post('/api/integrations/int1/sync'); + + expect(res.status).toBe(424); + expect(res.body).toMatchObject({ + success: false, + error: 'HubSpot API error: Service Unavailable.', + needsReconnect: false, + code: 'SYNC_FAILED', + }); + expect(sb.callsFor('SyncLog', 'insert')[0].payload).toMatchObject({ status: 'FAILURE' }); + // A failed sync must not claim a fresh "last synced" time. + expect(sb.callsFor('Integration', 'update').some((c) => 'lastSyncAt' in (c.payload as object))).toBe(false); + }); + + it('switches off a revoked connection and tells the client to reconnect', async () => { + seed(); + runSyncMock.mockResolvedValue({ + recordsAffected: 0, + failed: true, + deactivate: true, + details: { error: 'No access token found. Please reconnect HubSpot.', message: 'Sync failed' }, + }); + + const res = await request(buildApp()).post('/api/integrations/int1/sync'); + + expect(res.status).toBe(424); + expect(res.body.needsReconnect).toBe(true); + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ isActive: false }); + }); +}); + +describe('GET /api/integrations/:id/logs', () => { + it('clamps the limit to a sane range', async () => { + seed(); + await request(buildApp()).get('/api/integrations/int1/logs?limit=100000'); + expect(sb.callsFor('SyncLog', 'select')[0].limit).toBe(200); + + sb.calls.length = 0; + await request(buildApp()).get('/api/integrations/int1/logs?limit=abc'); + expect(sb.callsFor('SyncLog', 'select')[0].limit).toBe(50); + }); +}); diff --git a/tests/oauth.test.ts b/tests/oauth.test.ts new file mode 100644 index 0000000..04e5e83 --- /dev/null +++ b/tests/oauth.test.ts @@ -0,0 +1,332 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +import * as supabaseModule from '../src/lib/supabase'; +import oauthRouter from '../src/api/oauth'; +import { resetDefaultUser } from '../src/api/middleware/auth'; +import { signOAuthStart, signOAuthState, verifyOAuthState } from '../src/api/lib/oauthState'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; +const fetchMock = vi.fn(); + +const ENV_KEYS = [ + 'AUTH_MODE', 'HUBSPOT_DEMO_MODE', 'SALESFORCE_DEMO_MODE', 'GMAIL_DEMO_MODE', 'HUBSPOT_ACCESS_TOKEN', + 'HUBSPOT_CLIENT_ID', 'HUBSPOT_CLIENT_SECRET', 'SALESFORCE_CLIENT_ID', 'SALESFORCE_CLIENT_SECRET', + 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', +] as const; +let savedEnv: Record; + +const ADMIN = { id: 'admin1', email: 'a@b.com', role: 'ADMIN', company_id: null }; +const REP = { id: 'rep1', email: 'r@b.com', role: 'SALES_REP', company_id: null }; + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/oauth', oauthRouter); + return app; +} + +/** Everyone resolves to `user`; `existing` is the Integration row an upsert finds (if any). */ +function seed(user: Record = ADMIN, existing: Record | null = null) { + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select') return { data: ctx.single ? user : [user] }; + if (ctx.table === 'Integration' && ctx.op === 'select') return { data: existing }; + return undefined; + }); +} + +const redirect = (res: request.Response) => new URL(res.headers.location, 'http://app.test'); +const integrationInsert = () => sb.callsFor('Integration', 'insert').at(-1)?.payload as Record | undefined; +const tokenResponse = (body: Record, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + for (const k of ENV_KEYS) delete process.env[k]; + process.env.HUBSPOT_CLIENT_ID = 'hs-client'; + process.env.HUBSPOT_CLIENT_SECRET = 'hs-secret'; + process.env.SALESFORCE_CLIENT_ID = 'sf-client'; + process.env.SALESFORCE_CLIENT_SECRET = 'sf-secret'; + process.env.GOOGLE_CLIENT_ID = 'g-client'; + process.env.GOOGLE_CLIENT_SECRET = 'g-secret'; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } +}); + +describe('POST /api/oauth/start-token', () => { + it('issues a short-lived token for the signed-in user', async () => { + seed(REP); + const res = await request(buildApp()).post('/api/oauth/start-token'); + expect(res.status).toBe(200); + const claims = jwt.decode(res.body.token) as { purpose: string; uid: string; exp: number; iat: number }; + expect(claims).toMatchObject({ purpose: 'oauth-start', uid: 'rep1' }); + expect(claims.exp - claims.iat).toBeLessThanOrEqual(120); + }); + + it('requires a session in login mode', async () => { + process.env.AUTH_MODE = 'login'; + seed(REP); + const res = await request(buildApp()).post('/api/oauth/start-token'); + expect(res.status).toBe(401); + }); +}); + +describe('authorize redirects', () => { + it('demo mode, no token: connects the default user (as before)', async () => { + process.env.HUBSPOT_DEMO_MODE = 'true'; + seed(ADMIN); + + const res = await request(buildApp()).get('/api/oauth/hubspot/authorize'); + + expect(res.status).toBe(302); + expect(redirect(res).searchParams.get('hubspot')).toBe('demo'); + expect(integrationInsert()).toMatchObject({ + type: 'HUBSPOT', + userId: 'admin1', + isActive: true, + credentials: { demo: true }, + }); + }); + + it('login mode: refuses a request with no token', async () => { + process.env.AUTH_MODE = 'login'; + process.env.HUBSPOT_DEMO_MODE = 'true'; + seed(REP); + + const res = await request(buildApp()).get('/api/oauth/hubspot/authorize'); + + expect(redirect(res).searchParams.get('error')).toBe('unauthorized'); + expect(sb.callsFor('Integration', 'insert')).toHaveLength(0); + }); + + it('login mode: accepts a start token and connects that user', async () => { + process.env.AUTH_MODE = 'login'; + process.env.HUBSPOT_DEMO_MODE = 'true'; + seed(REP); + + const res = await request(buildApp()).get(`/api/oauth/hubspot/authorize?token=${signOAuthStart('rep1')}`); + + expect(redirect(res).searchParams.get('hubspot')).toBe('demo'); + expect(integrationInsert()).toMatchObject({ userId: 'rep1' }); + }); + + it('login mode: a session token in the URL is not accepted', async () => { + process.env.AUTH_MODE = 'login'; + process.env.HUBSPOT_DEMO_MODE = 'true'; + seed(REP); + const session = jwt.sign({ userId: 'rep1' }, process.env.NEXTAUTH_SECRET as string, { expiresIn: '7d' }); + + const res = await request(buildApp()).get(`/api/oauth/hubspot/authorize?token=${session}`); + + expect(redirect(res).searchParams.get('error')).toBe('unauthorized'); + }); + + it('login mode: an OAuth state token cannot stand in for a start token', async () => { + process.env.AUTH_MODE = 'login'; + process.env.HUBSPOT_DEMO_MODE = 'true'; + seed(REP); + const res = await request(buildApp()).get(`/api/oauth/hubspot/authorize?token=${signOAuthState('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('unauthorized'); + }); + + it('sends the user to HubSpot with a signed state that identifies them', async () => { + seed(REP); + const res = await request(buildApp()).get('/api/oauth/hubspot/authorize'); + + const url = redirect(res); + expect(url.host).toBe('app.hubspot.com'); + expect(url.searchParams.get('client_id')).toBe('hs-client'); + expect(verifyOAuthState(url.searchParams.get('state'))).toBe('rep1'); + }); + + it('does the same for Salesforce and Gmail', async () => { + seed(REP); + const sf = redirect(await request(buildApp()).get('/api/oauth/salesforce/authorize')); + expect(sf.host).toBe('login.salesforce.com'); + expect(verifyOAuthState(sf.searchParams.get('state'))).toBe('rep1'); + + const gm = redirect(await request(buildApp()).get('/api/oauth/gmail/authorize')); + expect(gm.host).toBe('accounts.google.com'); + expect(gm.searchParams.get('access_type')).toBe('offline'); + expect(verifyOAuthState(gm.searchParams.get('state'))).toBe('rep1'); + }); + + it('reports a missing HubSpot client id', async () => { + delete process.env.HUBSPOT_CLIENT_ID; + seed(REP); + const res = await request(buildApp()).get('/api/oauth/hubspot/authorize'); + expect(redirect(res).searchParams.get('error')).toBe('no_client_id'); + }); + + it('reports a database failure instead of claiming success', async () => { + process.env.GMAIL_DEMO_MODE = 'true'; + seed(REP); + sb.handle((ctx) => (ctx.table === 'Integration' && ctx.op === 'insert' ? { error: { message: 'db down' } } : undefined)); + const res = await request(buildApp()).get('/api/oauth/gmail/authorize'); + expect(redirect(res).searchParams.get('error')).toBe('integration_save_failed'); + expect(redirect(res).searchParams.get('success')).toBeNull(); + }); +}); + +describe('HubSpot private app token', () => { + beforeEach(() => { + process.env.HUBSPOT_ACCESS_TOKEN = 'private-app-token'; + }); + + it('connects in demo mode', async () => { + seed(REP); + const res = await request(buildApp()).get('/api/oauth/hubspot/authorize'); + expect(redirect(res).searchParams.get('hubspot')).toBe('connected'); + expect(integrationInsert()).toMatchObject({ credentials: { accessToken: 'private-app-token' } }); + }); + + it('is admin-only in login mode, since the token is shared company access', async () => { + process.env.AUTH_MODE = 'login'; + seed(REP); + const denied = await request(buildApp()).get(`/api/oauth/hubspot/authorize?token=${signOAuthStart('rep1')}`); + expect(redirect(denied).searchParams.get('error')).toBe('forbidden'); + expect(sb.callsFor('Integration', 'insert')).toHaveLength(0); + + sb.reset(); + seed(ADMIN); + const allowed = await request(buildApp()).get(`/api/oauth/hubspot/authorize?token=${signOAuthStart('admin1')}`); + expect(redirect(allowed).searchParams.get('hubspot')).toBe('connected'); + }); +}); + +describe('callbacks', () => { + it('refuses the old forgeable state (a bare user id) without contacting the provider', async () => { + seed(REP); + const res = await request(buildApp()).get('/api/oauth/hubspot/callback?code=abc&state=rep1'); + expect(redirect(res).searchParams.get('error')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(sb.callsFor('Integration', 'insert')).toHaveLength(0); + }); + + it('refuses a state signed for a different purpose', async () => { + seed(REP); + const res = await request(buildApp()).get(`/api/oauth/hubspot/callback?code=abc&state=${signOAuthStart('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('invalid_state'); + }); + + it('needs a code', async () => { + seed(REP); + const res = await request(buildApp()).get(`/api/oauth/salesforce/callback?state=${signOAuthState('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('no_code'); + }); + + it('passes a provider-side denial back to the SPA', async () => { + seed(REP); + const res = await request(buildApp()).get('/api/oauth/hubspot/callback?error=access_denied'); + expect(redirect(res).searchParams.get('error')).toBe('access_denied'); + }); + + it('HubSpot: exchanges the code and stores the tokens for the user named in the state', async () => { + seed(REP); + fetchMock.mockResolvedValueOnce(tokenResponse({ access_token: 'at', refresh_token: 'rt', expires_in: 1800 })); + + const res = await request(buildApp()).get(`/api/oauth/hubspot/callback?code=the-code&state=${signOAuthState('rep1')}`); + + expect(redirect(res).searchParams.get('hubspot')).toBe('connected'); + expect(fetchMock.mock.calls[0][0]).toBe('https://api.hubapi.com/oauth/v1/token'); + const body = new URLSearchParams(String(fetchMock.mock.calls[0][1].body)); + expect(body.get('code')).toBe('the-code'); + expect(body.get('client_secret')).toBe('hs-secret'); + expect(integrationInsert()).toMatchObject({ + type: 'HUBSPOT', + userId: 'rep1', + credentials: { accessToken: 'at', refreshToken: 'rt', expiresIn: 1800 }, + }); + }); + + it('reports a failed token exchange without storing anything', async () => { + seed(REP); + fetchMock.mockResolvedValueOnce(new Response('bad code', { status: 400 })); + const res = await request(buildApp()).get(`/api/oauth/hubspot/callback?code=x&state=${signOAuthState('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('token_exchange_failed'); + expect(sb.callsFor('Integration', 'insert')).toHaveLength(0); + }); + + it('reports a provider reply with no access token', async () => { + seed(REP); + fetchMock.mockResolvedValueOnce(tokenResponse({ error: 'invalid_grant' })); + const res = await request(buildApp()).get(`/api/oauth/gmail/callback?code=x&state=${signOAuthState('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('token_exchange_failed'); + }); + + it('reuses the newest existing integration instead of adding another copy', async () => { + seed(REP, { id: 'existing-newest', credentials: { accessToken: 'old' } }); + fetchMock.mockResolvedValueOnce(tokenResponse({ access_token: 'new-at', refresh_token: 'new-rt' })); + + await request(buildApp()).get(`/api/oauth/hubspot/callback?code=x&state=${signOAuthState('rep1')}`); + + expect(sb.callsFor('Integration', 'insert')).toHaveLength(0); + const update = sb.callsFor('Integration', 'update')[0]; + expect(update.filters).toContainEqual(['eq', 'id', 'existing-newest']); + expect(update.payload).toMatchObject({ isActive: true, credentials: { accessToken: 'new-at' } }); + // The lookup tolerates duplicates: newest first, one row, no .single(). + const lookup = sb.callsFor('Integration', 'select')[0]; + expect(lookup.order?.[0]?.[0]).toBe('createdAt'); + expect(lookup.limit).toBe(1); + }); + + it('keeps the userโ€™s own integration name on reconnect', async () => { + seed(REP, { id: 'existing', name: 'My HubSpot', credentials: {} }); + fetchMock.mockResolvedValueOnce(tokenResponse({ access_token: 'at' })); + await request(buildApp()).get(`/api/oauth/hubspot/callback?code=x&state=${signOAuthState('rep1')}`); + expect(sb.callsFor('Integration', 'update')[0].payload).not.toHaveProperty('name'); + }); + + it('Gmail: keeps the stored refresh token when Google does not send a new one', async () => { + seed(REP, { id: 'g1', credentials: { accessToken: 'old', refreshToken: 'keep-me' } }); + fetchMock.mockResolvedValueOnce(tokenResponse({ access_token: 'fresh', expires_in: 3600 })); + + const res = await request(buildApp()).get(`/api/oauth/gmail/callback?code=x&state=${signOAuthState('rep1')}`); + + expect(redirect(res).searchParams.get('gmail')).toBe('connected'); + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ + credentials: { accessToken: 'fresh', refreshToken: 'keep-me' }, + }); + }); + + it('Salesforce: stores the instance URL it was given', async () => { + seed(REP); + fetchMock.mockResolvedValueOnce( + tokenResponse({ access_token: 'at', refresh_token: 'rt', instance_url: 'https://acme.my.salesforce.com' }) + ); + + const res = await request(buildApp()).get(`/api/oauth/salesforce/callback?code=x&state=${signOAuthState('rep1')}`); + + expect(redirect(res).searchParams.get('salesforce')).toBe('connected'); + expect(integrationInsert()).toMatchObject({ + type: 'SALESFORCE', + credentials: { instanceUrl: 'https://acme.my.salesforce.com', accessToken: 'at' }, + }); + }); + + it('turns an unexpected exception into an error redirect', async () => { + seed(REP); + fetchMock.mockRejectedValueOnce(new Error('network down')); + const res = await request(buildApp()).get(`/api/oauth/salesforce/callback?code=x&state=${signOAuthState('rep1')}`); + expect(redirect(res).searchParams.get('error')).toBe('oauth_failed'); + }); +}); diff --git a/tests/sync.test.ts b/tests/sync.test.ts new file mode 100644 index 0000000..7f5f406 --- /dev/null +++ b/tests/sync.test.ts @@ -0,0 +1,530 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +import * as supabaseModule from '../src/lib/supabase'; +import { runSync } from '../src/api/lib/sync'; +import type { SyncContext } from '../src/api/lib/sync'; +import { sampleDeals } from '../src/api/lib/sync/demo'; +import { extractBody, extractClientName, extractDealSize } from '../src/api/lib/sync/gmail'; +import { isSalesforceUrl } from '../src/api/lib/sync/salesforce'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; +const fetchMock = vi.fn(); + +const ENV_KEYS = ['HUBSPOT_CLIENT_ID', 'HUBSPOT_CLIENT_SECRET', 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', 'SALESFORCE_CLIENT_ID', 'SALESFORCE_CLIENT_SECRET'] as const; +let savedEnv: Record; + +const ctx = (type: string, credentials: Record | null, over: Partial = {}): SyncContext => ({ + integration: { id: 'int1', type, name: type, userId: 'owner1', credentials }, + userId: 'owner1', + companyId: null, + ...over, +}); + +const json = (body: unknown, init: ResponseInit = {}) => + new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init }); + +/** Make Proposal inserts succeed (echoing the rows) and report which ids were imported earlier. */ +function seedDb(opts: { imported?: Array>; insertError?: string } = {}) { + sb.handle((c) => { + if (c.table === 'Proposal' && c.op === 'select') { + return { data: (opts.imported ?? []).map((metadata) => ({ metadata })) }; + } + if (c.table === 'Proposal' && c.op === 'insert') { + return opts.insertError ? { error: { message: opts.insertError } } : { data: c.payload }; + } + return undefined; + }); +} + +/** A proposal row as the connectors insert it (only the fields these tests read). */ +interface ImportedProposal { + title: string; + userId: string; + status: string; + company_id?: string; + createdAt?: string; + metadata: Record; +} + +const insertedProposals = () => sb.callsFor('Proposal', 'insert').flatMap((c) => c.payload as ImportedProposal[]); + +beforeEach(() => { + sb.reset(); + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + process.env.HUBSPOT_CLIENT_ID = 'hs-id'; + process.env.HUBSPOT_CLIENT_SECRET = 'hs-secret'; + process.env.GOOGLE_CLIENT_ID = 'g-id'; + process.env.GOOGLE_CLIENT_SECRET = 'g-secret'; + process.env.SALESFORCE_CLIENT_ID = 'sf-id'; + process.env.SALESFORCE_CLIENT_SECRET = 'sf-secret'; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } +}); + +describe('runSync dispatch', () => { + it('records the attempt for types without a connector', async () => { + const result = await runSync(ctx('DOCUSIGN', { accessToken: 'x' })); + expect(result).toMatchObject({ failed: false, recordsAffected: 0, details: { message: 'Manual sync triggered' } }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('records the attempt when a known type has no credentials', async () => { + const result = await runSync(ctx('HUBSPOT', null)); + expect(result.details.message).toBe('Manual sync triggered'); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +describe('demo sync', () => { + const demoCtx = (over: Partial = {}) => ctx('SALESFORCE', { demo: true, accessToken: 'demo_token' }, over); + + it('imports the sample deals for the integration owner, not whoever is first in the User table', async () => { + seedDb(); + const result = await runSync(demoCtx({ userId: 'owner1', companyId: 'c1' })); + + expect(result).toMatchObject({ failed: false, recordsAffected: 3 }); + const rows = insertedProposals(); + expect(rows).toHaveLength(3); + for (const row of rows) { + expect(row).toMatchObject({ userId: 'owner1', company_id: 'c1', status: 'PENDING' }); + } + expect(rows[0].metadata).toMatchObject({ source: 'salesforce-demo', dealId: 'demo-salesforce-001' }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('does not re-import deals this user already has', async () => { + seedDb({ imported: sampleDeals('salesforce').slice(0, 2).map((d) => ({ dealId: d.id })) }); + const result = await runSync(demoCtx()); + expect(result.recordsAffected).toBe(1); + expect(insertedProposals().map((r) => r.metadata.dealId)).toEqual(['demo-salesforce-003']); + }); + + it('says so when everything is already imported', async () => { + seedDb({ imported: sampleDeals('salesforce').map((d) => ({ dealId: d.id })) }); + const result = await runSync(demoCtx()); + expect(result).toMatchObject({ failed: false, recordsAffected: 0 }); + expect(result.details.message).toMatch(/already imported/); + expect(sb.callsFor('Proposal', 'insert')).toHaveLength(0); + }); + + it('scopes the "already imported" lookup to the owner', async () => { + seedDb(); + await runSync(demoCtx({ userId: 'owner1' })); + const lookup = sb.callsFor('Proposal', 'select')[0]; + expect(lookup.filters).toContainEqual(['eq', 'userId', 'owner1']); + }); + + it('reports a failed insert', async () => { + seedDb({ insertError: 'permission denied' }); + const result = await runSync(demoCtx()); + expect(result).toMatchObject({ failed: true, deactivate: false }); + expect(result.details.error).toBe('permission denied'); + }); +}); + +describe('HubSpot sync', () => { + const hs = (credentials: Record | null = { accessToken: 'tok', refreshToken: 'ref' }, over: Partial = {}) => + ctx('HUBSPOT', credentials, over); + const deal = (id: string, props: Record = {}) => ({ + id, + properties: { dealname: `Deal ${id}`, amount: '50000', dealstage: 'qualified', createdate: '2026-01-02T00:00:00Z', ...props }, + }); + + it('imports new deals as the owner, inheriting the company', async () => { + seedDb(); + fetchMock.mockResolvedValueOnce( + json({ results: [deal('1'), deal('2', { amount: 'n/a' }), deal('3', { amount: '9,500.50' })] }) + ); + + const result = await runSync(hs({ accessToken: 'tok' }, { companyId: 'c1' })); + + expect(result).toMatchObject({ failed: false, recordsAffected: 3 }); + expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer tok'); + const rows = insertedProposals(); + expect(rows[0]).toMatchObject({ + title: 'Deal 1', + userId: 'owner1', + company_id: 'c1', + createdAt: '2026-01-02T00:00:00Z', + metadata: { source: 'hubspot', dealId: '1', dealSize: 50000 }, + }); + // Unparseable amounts become 0 (never NaN); formatted ones are read in full. + expect(rows[1].metadata.dealSize).toBe(0); + expect(rows[2].metadata.dealSize).toBe(9500.5); + }); + + it('skips deals already imported by this user', async () => { + seedDb({ imported: [{ dealId: '1' }] }); + fetchMock.mockResolvedValueOnce(json({ results: [deal('1'), deal('2')] })); + + const result = await runSync(hs()); + + expect(result.recordsAffected).toBe(1); + expect(result.details).toMatchObject({ dealsProcessed: 2, dealsAlreadyImported: 1 }); + expect(insertedProposals().map((r) => r.metadata.dealId)).toEqual(['2']); + }); + + it('handles an empty account and an up-to-date re-sync', async () => { + seedDb(); + fetchMock.mockResolvedValueOnce(json({ results: [] })); + expect((await runSync(hs())).details.message).toBe('No deals found in HubSpot'); + + seedDb({ imported: [{ dealId: '1' }] }); + fetchMock.mockResolvedValueOnce(json({ results: [deal('1')] })); + const again = await runSync(hs()); + expect(again).toMatchObject({ failed: false, recordsAffected: 0 }); + expect(again.details.message).toMatch(/No new deals/); + }); + + it('fails and asks for a reconnect when there is no access token', async () => { + const result = await runSync(hs({ refreshToken: 'ref' })); + expect(result).toMatchObject({ failed: true, deactivate: true }); + expect(result.details.error).toMatch(/No access token/); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refreshes an expired token, stores it, and retries', async () => { + seedDb(); + fetchMock + .mockResolvedValueOnce(new Response('', { status: 401, statusText: 'Unauthorized' })) + .mockResolvedValueOnce(json({ access_token: 'new-tok', refresh_token: 'new-ref', expires_in: 1800 })) + .mockResolvedValueOnce(json({ results: [deal('1')] })); + + const result = await runSync(hs()); + + expect(result).toMatchObject({ failed: false, recordsAffected: 1 }); + expect(fetchMock.mock.calls[1][0]).toContain('oauth/v1/token'); + expect(String(fetchMock.mock.calls[1][1].body)).toContain('grant_type=refresh_token'); + expect(fetchMock.mock.calls[2][1].headers.Authorization).toBe('Bearer new-tok'); + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ + credentials: { accessToken: 'new-tok', refreshToken: 'new-ref', expiresIn: 1800 }, + }); + }); + + it('asks for a reconnect when the refresh itself is rejected', async () => { + fetchMock + .mockResolvedValueOnce(new Response('', { status: 401 })) + .mockResolvedValueOnce(new Response('{}', { status: 400 })); + + const result = await runSync(hs()); + + expect(result).toMatchObject({ failed: true, deactivate: true }); + expect(result.details.error).toMatch(/reconnect HubSpot/); + }); + + it('asks for a reconnect on a 401 when there is no refresh token to try', async () => { + fetchMock.mockResolvedValueOnce(new Response('', { status: 401, statusText: 'Unauthorized' })); + const result = await runSync(hs({ accessToken: 'tok' })); + expect(result).toMatchObject({ failed: true, deactivate: true }); + }); + + it('keeps the connection on a transient server error', async () => { + fetchMock.mockResolvedValueOnce(new Response('', { status: 503, statusText: 'Service Unavailable' })); + const result = await runSync(hs()); + expect(result).toMatchObject({ failed: true, deactivate: false }); + expect(result.details.error).toMatch(/Service Unavailable/); + }); + + it('turns a network failure or timeout into a failed result instead of throwing', async () => { + fetchMock.mockRejectedValueOnce(new Error('The operation was aborted due to timeout')); + const result = await runSync(hs()); + expect(result).toMatchObject({ failed: true, deactivate: false }); + expect(result.details.error).toMatch(/timeout/); + }); + + it('attaches a timeout signal to every request', async () => { + seedDb(); + fetchMock.mockResolvedValueOnce(json({ results: [] })); + await runSync(hs()); + expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal); + }); +}); + +describe('Gmail sync', () => { + const gm = (credentials: Record | null = { accessToken: 'tok', refreshToken: 'ref' }, over: Partial = {}) => + ctx('GMAIL', credentials, over); + + const b64 = (text: string) => Buffer.from(text).toString('base64url'); + const message = (id: string, threadId: string, over: Record = {}) => ({ + id, + threadId, + labelIds: ['INBOX'], + internalDate: String(Date.UTC(2026, 0, 5)), + snippet: `snippet ${id}`, + payload: { + headers: [ + { name: 'Subject', value: `Proposal ${id}` }, + { name: 'From', value: 'Pat ' }, + { name: 'To', value: 'Dana Buyer ' }, + ], + body: { data: b64(`Hello.\nInvestment: $12,500.00\nThanks`) }, + }, + ...over, + }); + + /** Search returns `ids`; each message fetch returns the matching entry. */ + function mockInbox(messages: Array>) { + fetchMock.mockImplementation(async (url: string) => { + if (url.includes('/messages?q=')) return json({ messages: messages.map((m) => ({ id: m.id })) }); + const found = messages.find((m) => url.endsWith(`/messages/${m.id}`)); + return found ? json(found) : new Response('', { status: 404 }); + }); + } + + it('imports each new thread once, as the owner, with the company and parsed details', async () => { + seedDb(); + mockInbox([message('m1', 't1'), message('m2', 't1'), message('m3', 't2')]); + + const result = await runSync(gm(undefined, { companyId: 'c1' })); + + expect(result).toMatchObject({ failed: false, recordsAffected: 2 }); + const rows = insertedProposals(); + expect(rows.map((r) => r.metadata.emailThreadId)).toEqual(['t1', 't2']); + expect(rows[0]).toMatchObject({ + title: 'Proposal m1', + userId: 'owner1', + company_id: 'c1', + metadata: { source: 'gmail', clientName: 'Dana Buyer', dealSize: 12500 }, + }); + }); + + it('does not put email bodies in the sync log details', async () => { + seedDb(); + mockInbox([message('m1', 't1')]); + + const result = await runSync(gm()); + + const threads = result.details.emailThreads as Array>; + expect(threads).toHaveLength(1); + expect(threads[0]).toMatchObject({ subject: 'Proposal m1', from: 'Pat ' }); + expect(threads[0]).not.toHaveProperty('body'); + expect(JSON.stringify(result.details)).not.toContain('Investment'); + }); + + it('skips messages that are not in the inbox and threads already imported', async () => { + seedDb({ imported: [{ emailThreadId: 't1' }] }); + mockInbox([message('m1', 't1'), message('m2', 't2', { labelIds: ['SENT'] }), message('m3', 't3')]); + + const result = await runSync(gm()); + + expect(insertedProposals().map((r) => r.metadata.emailThreadId)).toEqual(['t3']); + expect(result.details).toMatchObject({ emailsProcessed: 3, emailsAlreadyImported: 1 }); + }); + + it('reports an empty inbox', async () => { + fetchMock.mockResolvedValueOnce(json({})); + const result = await runSync(gm()); + expect(result).toMatchObject({ failed: false, recordsAffected: 0 }); + expect(result.details.message).toMatch(/No proposal-related emails/); + }); + + it('fails with a reconnect request when there is no access token', async () => { + const result = await runSync(gm({ refreshToken: 'ref' })); + expect(result).toMatchObject({ failed: true, deactivate: true }); + }); + + it('refreshes an expired token and retries the search', async () => { + seedDb(); + const msg = message('m1', 't1'); + let searches = 0; + fetchMock.mockImplementation(async (url: string, init?: { method?: string }) => { + if (url.includes('oauth2.googleapis.com/token')) return json({ access_token: 'fresh', expires_in: 3600 }); + if (url.includes('/messages?q=')) { + searches++; + return searches === 1 ? new Response('', { status: 401, statusText: 'Unauthorized' }) : json({ messages: [{ id: 'm1' }] }); + } + return init?.method === 'POST' ? new Response('', { status: 500 }) : json(msg); + }); + + const result = await runSync(gm()); + + expect(result).toMatchObject({ failed: false, recordsAffected: 1 }); + // A refresh response without a new refresh token keeps the old one. + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ + credentials: { accessToken: 'fresh', refreshToken: 'ref' }, + }); + }); + + it('asks for a reconnect when it cannot refresh', async () => { + fetchMock.mockResolvedValue(new Response('', { status: 401, statusText: 'Unauthorized' })); + const result = await runSync(gm({ accessToken: 'tok' })); // no refresh token + expect(result).toMatchObject({ failed: true, deactivate: true }); + expect(result.details.error).toMatch(/reconnect Gmail/i); + }); + + describe('parsing helpers', () => { + it('reads a single-part body and a multipart text/plain body', () => { + expect(extractBody({ headers: [], body: { data: b64('single') } })).toBe('single'); + expect( + extractBody({ + headers: [], + parts: [ + { mimeType: 'text/html', body: { data: b64('html') } }, + { mimeType: 'text/plain', body: { data: b64('plain') } }, + ], + }) + ).toBe('plain'); + expect(extractBody({ headers: [] })).toBe(''); + }); + + it('finds the deal size after "Investment" or falls back to the first dollar figure', () => { + expect(extractDealSize('Investment: $1,200')).toBe(1200); + expect(extractDealSize('We charge $3,400.50 in total')).toBe(3400.5); + expect(extractDealSize('no figures here')).toBe(0); + }); + + it('takes the client name from the To header', () => { + expect(extractClientName('Dana Buyer ')).toBe('Dana Buyer'); + expect(extractClientName('dana@acme.com')).toBe('dana'); + }); + }); +}); + +describe('Salesforce sync', () => { + const sfCreds = { accessToken: 'tok', refreshToken: 'ref', instanceUrl: 'https://acme.my.salesforce.com' }; + const sf = (credentials: Record | null = sfCreds, over: Partial = {}) => + ctx('SALESFORCE', credentials, over); + const opp = (id: string, over: Record = {}) => ({ + Id: id, + Name: `Opportunity ${id}`, + Amount: 75000, + StageName: 'Negotiation', + CloseDate: '2026-06-30', + Account: { Name: 'Acme' }, + CreatedDate: '2026-01-03T00:00:00Z', + ...over, + }); + + describe('isSalesforceUrl', () => { + it('accepts https Salesforce org URLs', () => { + for (const url of [ + 'https://na1.salesforce.com', + 'https://acme.my.salesforce.com', + 'https://acme--sandbox.sandbox.my.salesforce.com', + 'https://acme.my.site.force.com', + 'https://org.cloudforce.com', + 'https://salesforce.com', + ]) { + expect(isSalesforceUrl(url), url).toBe(true); + } + }); + + it('rejects everything else, including look-alikes and internal addresses', () => { + for (const url of [ + 'http://acme.my.salesforce.com', // not https + 'https://salesforce.com.evil.example', + 'https://evilsalesforce.com', + 'https://evil.example/?x=.salesforce.com', + 'https://user:pw@acme.my.salesforce.com', + 'https://169.254.169.254', + 'http://localhost:3001', + 'https://localhost', + 'not a url', + '', + ]) { + expect(isSalesforceUrl(url), url).toBe(false); + } + }); + }); + + it('imports opportunities as the owner โ€” there is no hard-coded fallback user', async () => { + seedDb(); + fetchMock.mockResolvedValueOnce(json({ records: [opp('006A'), opp('006B', { Amount: null })] })); + + const result = await runSync(sf(sfCreds, { companyId: 'c9' })); + + expect(result).toMatchObject({ failed: false, recordsAffected: 2 }); + expect(fetchMock.mock.calls[0][0]).toMatch(/^https:\/\/acme\.my\.salesforce\.com\/services\/data\/v60\.0\/query\?q=/); + const rows = insertedProposals(); + expect(rows[0]).toMatchObject({ + title: 'Opportunity 006A', + userId: 'owner1', + company_id: 'c9', + metadata: { source: 'salesforce', opportunityId: '006A', dealSize: 75000, clientName: 'Acme' }, + }); + expect(rows[1].metadata.dealSize).toBe(0); + }); + + it('never calls a stored instance URL that is not a Salesforce address', async () => { + const result = await runSync(sf({ ...sfCreds, instanceUrl: 'http://169.254.169.254/latest/meta-data' })); + expect(result).toMatchObject({ failed: true, deactivate: true }); + expect(result.details.error).toMatch(/not a Salesforce address/); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('requires an instance URL and an access token', async () => { + expect((await runSync(sf({ accessToken: 'tok' }))).details.error).toMatch(/No instance URL/); + expect((await runSync(sf({ instanceUrl: sfCreds.instanceUrl }))).details.error).toMatch(/No access token/); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('skips opportunities already imported', async () => { + seedDb({ imported: [{ opportunityId: '006A' }] }); + fetchMock.mockResolvedValueOnce(json({ records: [opp('006A'), opp('006B')] })); + const result = await runSync(sf()); + expect(insertedProposals().map((r) => r.metadata.opportunityId)).toEqual(['006B']); + expect(result.details).toMatchObject({ opportunitiesProcessed: 2, opportunitiesAlreadyImported: 1 }); + }); + + it('refreshes an expired token, keeping the validated instance URL', async () => { + seedDb(); + fetchMock + .mockResolvedValueOnce(new Response('', { status: 401 })) + .mockResolvedValueOnce(json({ access_token: 'fresh', instance_url: 'https://acme2.my.salesforce.com' })) + .mockResolvedValueOnce(json({ records: [opp('006A')] })); + + const result = await runSync(sf()); + + expect(result).toMatchObject({ failed: false, recordsAffected: 1 }); + expect(fetchMock.mock.calls[2][0]).toContain('https://acme2.my.salesforce.com'); + expect(sb.callsFor('Integration', 'update')[0].payload).toMatchObject({ + credentials: { accessToken: 'fresh', refreshToken: 'ref', instanceUrl: 'https://acme2.my.salesforce.com' }, + }); + }); + + it('refuses a refreshed instance URL that points somewhere else', async () => { + fetchMock + .mockResolvedValueOnce(new Response('', { status: 401 })) + .mockResolvedValueOnce(json({ access_token: 'fresh', instance_url: 'https://evil.example' })); + + const result = await runSync(sf()); + + expect(result).toMatchObject({ failed: true }); + expect(fetchMock).toHaveBeenCalledTimes(2); // no query was sent to evil.example + }); + + it('uses the sandbox login host to refresh when SALESFORCE_SANDBOX=true', async () => { + process.env.SALESFORCE_SANDBOX = 'true'; + try { + fetchMock + .mockResolvedValueOnce(new Response('', { status: 401 })) + .mockResolvedValueOnce(new Response('{}', { status: 400 })); + const result = await runSync(sf()); + expect(fetchMock.mock.calls[1][0]).toBe('https://test.salesforce.com/services/oauth2/token'); + expect(result).toMatchObject({ failed: true, deactivate: true }); + } finally { + delete process.env.SALESFORCE_SANDBOX; + } + }); + + it('reports no open opportunities', async () => { + fetchMock.mockResolvedValueOnce(json({ records: [] })); + const result = await runSync(sf()); + expect(result.details.message).toBe('No open opportunities found in Salesforce'); + }); +}); From 58d6d2cc68d709318b778b30646221392353ff5c Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:18 +0530 Subject: [PATCH 05/11] feat(files): per-user storage folders, type and size limits, signed links 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//_; 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. --- src/api/files.ts | 369 ++++++++++++++++++++++++++------------------ tests/files.test.ts | 282 +++++++++++++++++++++++++++++++++ 2 files changed, 499 insertions(+), 152 deletions(-) create mode 100644 tests/files.test.ts diff --git a/src/api/files.ts b/src/api/files.ts index 9fc8c86..7ceb093 100644 --- a/src/api/files.ts +++ b/src/api/files.ts @@ -1,152 +1,217 @@ -import { Router, Request, Response } from 'express'; -import { supabase } from '../lib/supabase'; -import mammoth from 'mammoth'; -import { requireAuth } from './middleware/auth'; - -const router = Router(); - -// POST upload file -router.post('/upload', requireAuth, async (req: Request, res: Response) => { - try { - const { file, fileName } = req.body; - - if (!file || !fileName) { - return res.status(400).json({ error: 'File and fileName are required' }); - } - - // Decode base64 file if needed - const fileBuffer = Buffer.from(file, 'base64'); - - // Generate unique file path - const timestamp = Date.now(); - const sanitizedFileName = fileName.replace(/[^a-zA-Z0-9.-]/g, '_'); - const filePath = `proposals/${timestamp}_${sanitizedFileName}`; - - // Upload to Supabase Storage - const { data, error } = await supabase.storage - .from('proposal-files') - .upload(filePath, fileBuffer, { - contentType: 'application/octet-stream', - upsert: false, - }); - - if (error) { - console.error('Supabase storage error:', error); - - // If bucket doesn't exist, return a helpful error - if (error.message?.includes('not found')) { - return res.status(500).json({ - error: 'Storage bucket not configured. Please create a "proposal-files" bucket in Supabase Storage.', - details: error.message - }); - } - - throw error; - } - - // Get public URL - const { data: urlData } = supabase.storage - .from('proposal-files') - .getPublicUrl(filePath); - - // Extract text from DOCX if applicable - let extractedText = null; - if (fileName.endsWith('.docx')) { - try { - const result = await mammoth.extractRawText({ buffer: fileBuffer }); - extractedText = result.value; - } catch (extractError) { - console.error('Error extracting text from DOCX:', extractError); - } - } - - res.json({ - success: true, - fileUrl: urlData.publicUrl, - filePath: data.path, - extractedText, - }); - } catch (error) { - console.error('Error uploading file:', error); - res.status(500).json({ error: 'Failed to upload file' }); - } -}); - -// GET file -router.get('/download/:filename', requireAuth, async (req: Request, res: Response) => { - try { - const { filename } = req.params; - const filePath = `proposals/${filename}`; - - const { data, error } = await supabase.storage - .from('proposal-files') - .download(filePath); - - if (error) throw error; - - if (!data) { - return res.status(404).json({ error: 'File not found' }); - } - - // Convert blob to buffer and send - const buffer = await data.arrayBuffer(); - res.send(Buffer.from(buffer)); - } catch (error) { - console.error('Error downloading file:', error); - res.status(500).json({ error: 'Failed to download file' }); - } -}); - -// DELETE file -router.delete('/delete/:filename', requireAuth, async (req: Request, res: Response) => { - try { - const { filename } = req.params; - const filePath = `proposals/${filename}`; - - const { error } = await supabase.storage - .from('proposal-files') - .remove([filePath]); - - if (error) throw error; - - res.json({ success: true, message: 'File deleted successfully' }); - } catch (error) { - console.error('Error deleting file:', error); - res.status(500).json({ error: 'Failed to delete file' }); - } -}); - -// POST extract text from document -router.post('/extract-text', requireAuth, async (req: Request, res: Response) => { - try { - const { file, fileName } = req.body; - - if (!file) { - return res.status(400).json({ error: 'File is required' }); - } - - const fileBuffer = Buffer.from(file, 'base64'); - let extractedText = ''; - - if (fileName.endsWith('.docx')) { - const result = await mammoth.extractRawText({ buffer: fileBuffer }); - extractedText = result.value; - } else if (fileName.endsWith('.txt')) { - extractedText = fileBuffer.toString('utf-8'); - } else { - return res.status(400).json({ error: 'Unsupported file type. Please upload .docx or .txt files.' }); - } - - res.json({ - success: true, - extractedText, - wordCount: extractedText.split(/\s+/).length, - charCount: extractedText.length, - }); - } catch (error) { - console.error('Error extracting text:', error); - res.status(500).json({ error: 'Failed to extract text from file' }); - } -}); - -export default router; +import { Router, Request, Response } from 'express'; +import mammoth from 'mammoth'; +import { supabase } from '../lib/supabase'; +import { requireAuth, isAdmin } from './middleware/auth'; +import { isLoginMode } from './lib/authConfig'; +import { logger } from './lib/logger'; + +const router = Router(); + +const BUCKET = 'proposal-files'; +const KEY_ROOT = 'proposals'; + +/** Largest decoded upload accepted (the JSON body limit is 10 MB, base64 inflates ~33%). */ +export const MAX_FILE_BYTES = 7 * 1024 * 1024; + +/** Lifetime of the download link returned after an upload. */ +const SIGNED_URL_SECONDS = 60 * 60; + +/** Document types the app can store, with the Content-Type they are served as. */ +const CONTENT_TYPES: Record = { + pdf: 'application/pdf', + docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + doc: 'application/msword', + txt: 'text/plain; charset=utf-8', + md: 'text/markdown; charset=utf-8', + rtf: 'application/rtf', +}; + +const extensionOf = (fileName: string): string => fileName.split('.').pop()?.toLowerCase() ?? ''; + +/** Storage folder holding one user's files. */ +const userFolder = (userId: string): string => `${KEY_ROOT}/${userId}/`; + +/** + * Turn the URL tail into a storage key, or null if it is not a plausible one. + * Keys are `proposals//_`; the older `` form + * (before per-user folders) is accepted and mapped under `proposals/`. + */ +export function toStorageKey(segments: string[] | string | undefined): string | null { + const parts = (Array.isArray(segments) ? segments : [segments ?? '']).flatMap((s) => s.split('/')); + if (parts.length === 0 || parts.some((p) => p === '' || p === '.' || p === '..')) return null; + return parts[0] === KEY_ROOT ? parts.join('/') : `${KEY_ROOT}/${parts.join('/')}`; +} + +/** + * May the caller touch this stored file? Admins can reach everything. Everyone + * else is confined to their own folder; legacy flat keys are open in demo mode + * (single-tenant) but admin-only once real sign-in is on. + */ +export function canAccessFile(key: string, req: Request): boolean { + if (isAdmin(req)) return true; + if (req.user && key.startsWith(userFolder(req.user.id))) return true; + return !isLoginMode() && key.split('/').length === 2; +} + +/** Plain-text extraction for the formats we can read server-side. */ +async function extractText(buffer: Buffer, fileName: string): Promise { + const ext = extensionOf(fileName); + if (ext === 'docx') return (await mammoth.extractRawText({ buffer })).value; + if (ext === 'txt' || ext === 'md') return buffer.toString('utf-8'); + return null; +} + +// POST upload file +router.post('/upload', requireAuth, async (req: Request, res: Response) => { + try { + const { file, fileName } = req.body; + + if (typeof file !== 'string' || !file || typeof fileName !== 'string' || !fileName) { + return res.status(400).json({ error: 'File and fileName are required' }); + } + + const ext = extensionOf(fileName); + if (!CONTENT_TYPES[ext]) { + return res.status(400).json({ error: `Unsupported file type. Allowed: ${Object.keys(CONTENT_TYPES).join(', ')}` }); + } + + // Decode base64 file + const fileBuffer = Buffer.from(file, 'base64'); + if (fileBuffer.length === 0) { + return res.status(400).json({ error: 'The file is empty' }); + } + if (fileBuffer.length > MAX_FILE_BYTES) { + return res.status(413).json({ error: `File is too large (limit ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MB)` }); + } + + // Per-user folder + timestamp keeps names unique and keeps users apart. + const sanitizedFileName = fileName.replace(/[^a-zA-Z0-9.-]/g, '_'); + const filePath = `${userFolder(req.user!.id)}${Date.now()}_${sanitizedFileName}`; + + const { data, error } = await supabase.storage + .from(BUCKET) + .upload(filePath, fileBuffer, { contentType: CONTENT_TYPES[ext], upsert: false }); + + if (error) { + logger.error('Supabase storage error:', error); + + // If bucket doesn't exist, return a helpful error + if (error.message?.includes('not found')) { + return res.status(500).json({ + error: 'Storage bucket not configured. Run prisma/manual/storage_bucket.sql or create a "proposal-files" bucket in Supabase Storage.', + details: error.message, + }); + } + + throw error; + } + + // A signed link works whether the bucket is public or private. + const { data: signed } = await supabase.storage.from(BUCKET).createSignedUrl(filePath, SIGNED_URL_SECONDS); + const fileUrl = signed?.signedUrl ?? supabase.storage.from(BUCKET).getPublicUrl(filePath).data.publicUrl; + + // Extract text from DOCX if applicable + let extractedText: string | null = null; + if (ext === 'docx') { + try { + extractedText = await extractText(fileBuffer, fileName); + } catch (extractError) { + logger.error('Error extracting text from DOCX:', extractError); + } + } + + res.json({ + success: true, + fileUrl, + filePath: data.path, + extractedText, + }); + } catch (error) { + logger.error('Error uploading file:', error); + res.status(500).json({ error: 'Failed to upload file' }); + } +}); + +// GET file. The path is the `filePath` returned by upload. +router.get('/download/*filePath', requireAuth, async (req: Request, res: Response) => { + try { + const key = toStorageKey(req.params.filePath); + if (!key) { + return res.status(400).json({ error: 'Invalid file path' }); + } + if (!canAccessFile(key, req)) { + return res.status(403).json({ error: 'You do not have access to this file' }); + } + + const { data, error } = await supabase.storage.from(BUCKET).download(key); + + if (error) throw error; + + if (!data) { + return res.status(404).json({ error: 'File not found' }); + } + + const name = key.split('/').pop() ?? 'file'; + res.setHeader('Content-Type', CONTENT_TYPES[extensionOf(name)] ?? 'application/octet-stream'); + res.setHeader('Content-Disposition', `attachment; filename="${name.replace(/"/g, '')}"`); + res.send(Buffer.from(await data.arrayBuffer())); + } catch (error) { + logger.error('Error downloading file:', error); + res.status(500).json({ error: 'Failed to download file' }); + } +}); + +// DELETE file. The path is the `filePath` returned by upload. +router.delete('/delete/*filePath', requireAuth, async (req: Request, res: Response) => { + try { + const key = toStorageKey(req.params.filePath); + if (!key) { + return res.status(400).json({ error: 'Invalid file path' }); + } + if (!canAccessFile(key, req)) { + return res.status(403).json({ error: 'You do not have access to this file' }); + } + + const { error } = await supabase.storage.from(BUCKET).remove([key]); + + if (error) throw error; + + res.json({ success: true, message: 'File deleted successfully' }); + } catch (error) { + logger.error('Error deleting file:', error); + res.status(500).json({ error: 'Failed to delete file' }); + } +}); + +// POST extract text from document +router.post('/extract-text', requireAuth, async (req: Request, res: Response) => { + try { + const { file, fileName } = req.body; + + if (typeof file !== 'string' || !file || typeof fileName !== 'string') { + return res.status(400).json({ error: 'File and fileName are required' }); + } + + const fileBuffer = Buffer.from(file, 'base64'); + if (fileBuffer.length > MAX_FILE_BYTES) { + return res.status(413).json({ error: `File is too large (limit ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MB)` }); + } + + const extractedText = await extractText(fileBuffer, fileName); + if (extractedText === null) { + return res.status(400).json({ error: 'Unsupported file type. Please upload .docx, .txt or .md files.' }); + } + + res.json({ + success: true, + extractedText, + wordCount: extractedText.split(/\s+/).filter(Boolean).length, + charCount: extractedText.length, + }); + } catch (error) { + logger.error('Error extracting text:', error); + res.status(500).json({ error: 'Failed to extract text from file' }); + } +}); + +export default router; diff --git a/tests/files.test.ts b/tests/files.test.ts new file mode 100644 index 0000000..8429d04 --- /dev/null +++ b/tests/files.test.ts @@ -0,0 +1,282 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import express from 'express'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +const { extractRawText } = vi.hoisted(() => ({ extractRawText: vi.fn() })); +vi.mock('mammoth', () => ({ default: { extractRawText } })); + +import * as supabaseModule from '../src/lib/supabase'; +import filesRouter, { MAX_FILE_BYTES, canAccessFile, toStorageKey } from '../src/api/files'; +import { resetDefaultUser } from '../src/api/middleware/auth'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; + +const ADMIN = { id: 'admin1', email: 'a@b.com', role: 'ADMIN', company_id: null }; +const REP = { id: 'rep1', email: 'r@b.com', role: 'SALES_REP', company_id: null }; + +function buildApp() { + const app = express(); + app.use(express.json({ limit: '20mb' })); + app.use('/api/files', filesRouter); + return app; +} + +const b64 = (text: string | Buffer) => Buffer.from(text).toString('base64'); + +/** GET `path` exactly as written (no URL normalisation) and resolve with the status code. */ +function rawGet(app: express.Express, path: string, headers: Record): Promise { + return new Promise((resolve, reject) => { + const server = app.listen(0, () => { + const { port } = server.address() as AddressInfo; + http + .get({ host: '127.0.0.1', port, path, headers }, (res) => { + res.resume(); + res.on('end', () => { + server.close(); + resolve(res.statusCode ?? 0); + }); + }) + .on('error', (err) => { + server.close(); + reject(err); + }); + }); + }); +} + +/** Demo mode: the default user is whoever we seed. Login mode: a token for them. */ +function signInAs(user: Record, mode: 'demo' | 'login') { + process.env.AUTH_MODE = mode; + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select') return { data: ctx.single ? user : [user] }; + return undefined; + }); + return mode === 'login' ? { Authorization: `Bearer ${jwt.sign({ userId: user.id }, process.env.NEXTAUTH_SECRET as string)}` } : {}; +} + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + extractRawText.mockReset(); + delete process.env.AUTH_MODE; +}); + +afterEach(() => { + delete process.env.AUTH_MODE; +}); + +describe('toStorageKey', () => { + it('maps a new-style path onto itself', () => { + expect(toStorageKey(['proposals', 'u1', '123_a.pdf'])).toBe('proposals/u1/123_a.pdf'); + }); + + it('prefixes a legacy flat name with proposals/', () => { + expect(toStorageKey(['123_a.pdf'])).toBe('proposals/123_a.pdf'); + }); + + it('rejects traversal and empty segments', () => { + expect(toStorageKey(['proposals', '..', 'x'])).toBeNull(); + expect(toStorageKey(['proposals', '.', 'x'])).toBeNull(); + expect(toStorageKey(['proposals', '', 'x'])).toBeNull(); + expect(toStorageKey([])).toBeNull(); + expect(toStorageKey(undefined)).toBeNull(); + }); +}); + +describe('canAccessFile', () => { + const asReq = (user: Record) => ({ user }) as never; + + it('lets admins reach anything', () => { + process.env.AUTH_MODE = 'login'; + expect(canAccessFile('proposals/other/1_x.pdf', asReq({ id: 'a', role: 'ADMIN' }))).toBe(true); + }); + + it('confines others to their own folder', () => { + const rep = asReq({ id: 'rep1', role: 'SALES_REP' }); + expect(canAccessFile('proposals/rep1/1_x.pdf', rep)).toBe(true); + expect(canAccessFile('proposals/rep2/1_x.pdf', rep)).toBe(false); + // A user id that merely starts with another's must not match. + expect(canAccessFile('proposals/rep10/1_x.pdf', rep)).toBe(false); + }); + + it('opens legacy flat files in demo mode only', () => { + const rep = asReq({ id: 'rep1', role: 'SALES_REP' }); + process.env.AUTH_MODE = 'demo'; + expect(canAccessFile('proposals/1_old.pdf', rep)).toBe(true); + process.env.AUTH_MODE = 'login'; + expect(canAccessFile('proposals/1_old.pdf', rep)).toBe(false); + }); +}); + +describe('POST /api/files/upload', () => { + it('400s without a file or name', async () => { + signInAs(REP, 'demo'); + expect((await request(buildApp()).post('/api/files/upload').send({})).status).toBe(400); + expect((await request(buildApp()).post('/api/files/upload').send({ file: b64('x') })).status).toBe(400); + expect((await request(buildApp()).post('/api/files/upload').send({ file: b64('x'), fileName: 42 })).status).toBe(400); + }); + + it('rejects file types outside the allow-list', async () => { + signInAs(REP, 'demo'); + for (const fileName of ['evil.html', 'run.exe', 'noextension', 'archive.zip']) { + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64('x'), fileName }); + expect(res.status).toBe(400); + } + expect(sb.storage.upload).not.toHaveBeenCalled(); + }); + + it('rejects an empty file and an oversized one', async () => { + signInAs(REP, 'demo'); + expect((await request(buildApp()).post('/api/files/upload').send({ file: '', fileName: 'a.pdf' })).status).toBe(400); + + const tooBig = Buffer.alloc(MAX_FILE_BYTES + 1, 1); + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64(tooBig), fileName: 'a.pdf' }); + expect(res.status).toBe(413); + expect(sb.storage.upload).not.toHaveBeenCalled(); + }); + + it('stores the file in the userโ€™s folder with a proper content type and returns a signed link', async () => { + signInAs(REP, 'demo'); + + const res = await request(buildApp()) + .post('/api/files/upload') + .send({ file: b64('%PDF-1.4'), fileName: 'My Proposal (v2).pdf' }); + + expect(res.status).toBe(200); + const [key, , options] = sb.storage.upload.mock.calls[0]; + expect(key).toMatch(/^proposals\/rep1\/\d+_My_Proposal__v2_\.pdf$/); + expect(options).toMatchObject({ contentType: 'application/pdf', upsert: false }); + expect(res.body).toMatchObject({ success: true, filePath: key, extractedText: null }); + expect(res.body.fileUrl).toContain('signed.example'); + }); + + it('falls back to the public URL if signing fails', async () => { + signInAs(REP, 'demo'); + sb.storage.createSignedUrl.mockResolvedValue({ data: null, error: { message: 'nope' } }); + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64('hi'), fileName: 'a.txt' }); + expect(res.body.fileUrl).toContain('public.example'); + }); + + it('extracts text from a .docx', async () => { + signInAs(REP, 'demo'); + extractRawText.mockResolvedValue({ value: 'Hello from Word' }); + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64('PK'), fileName: 'a.docx' }); + expect(res.body.extractedText).toBe('Hello from Word'); + }); + + it('still succeeds when .docx text extraction fails', async () => { + signInAs(REP, 'demo'); + extractRawText.mockRejectedValue(new Error('corrupt')); + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64('PK'), fileName: 'a.docx' }); + expect(res.status).toBe(200); + expect(res.body.extractedText).toBeNull(); + }); + + it('explains how to fix a missing bucket', async () => { + signInAs(REP, 'demo'); + sb.storage.upload.mockResolvedValue({ data: null, error: { message: 'Bucket not found' } }); + const res = await request(buildApp()).post('/api/files/upload').send({ file: b64('hi'), fileName: 'a.txt' }); + expect(res.status).toBe(500); + expect(res.body.error).toMatch(/storage_bucket\.sql/); + }); +}); + +describe('GET /api/files/download/*', () => { + it('serves your own file as an attachment', async () => { + const headers = signInAs(REP, 'login'); + const res = await request(buildApp()) + .get('/api/files/download/proposals/rep1/1_plan.pdf') + .set(headers) + .buffer(true); + + expect(res.status).toBe(200); + expect(sb.storage.download).toHaveBeenCalledWith('proposals/rep1/1_plan.pdf'); + expect(res.headers['content-type']).toContain('application/pdf'); + expect(res.headers['content-disposition']).toContain('attachment; filename="1_plan.pdf"'); + }); + + it('refuses another userโ€™s file in login mode', async () => { + const headers = signInAs(REP, 'login'); + const res = await request(buildApp()).get('/api/files/download/proposals/rep2/1_plan.pdf').set(headers); + expect(res.status).toBe(403); + expect(sb.storage.download).not.toHaveBeenCalled(); + }); + + it('lets an admin download anyoneโ€™s file', async () => { + const headers = signInAs(ADMIN, 'login'); + const res = await request(buildApp()).get('/api/files/download/proposals/rep2/1_plan.pdf').set(headers); + expect(res.status).toBe(200); + }); + + it('keeps the old flat URL working in demo mode', async () => { + signInAs(REP, 'demo'); + const res = await request(buildApp()).get('/api/files/download/1_old.pdf'); + expect(res.status).toBe(200); + expect(sb.storage.download).toHaveBeenCalledWith('proposals/1_old.pdf'); + }); + + it('rejects path traversal (sent raw, as a hostile client would)', async () => { + const headers = signInAs(ADMIN, 'login'); + // supertest/superagent resolve "%2e%2e" into a real ".." and collapse it before + // sending, so talk to the server with a bare http request instead. + const status = await rawGet(buildApp(), '/api/files/download/proposals/%2e%2e/secret', headers); + expect(status).toBe(400); + expect(sb.storage.download).not.toHaveBeenCalled(); + }); + + it('401s without a token in login mode', async () => { + signInAs(REP, 'login'); + const res = await request(buildApp()).get('/api/files/download/proposals/rep1/1_plan.pdf'); + expect(res.status).toBe(401); + }); +}); + +describe('DELETE /api/files/delete/*', () => { + it('deletes your own file', async () => { + const headers = signInAs(REP, 'login'); + const res = await request(buildApp()).delete('/api/files/delete/proposals/rep1/1_plan.pdf').set(headers); + expect(res.status).toBe(200); + expect(sb.storage.remove).toHaveBeenCalledWith(['proposals/rep1/1_plan.pdf']); + }); + + it('refuses to delete another userโ€™s file', async () => { + const headers = signInAs(REP, 'login'); + const res = await request(buildApp()).delete('/api/files/delete/proposals/rep2/1_plan.pdf').set(headers); + expect(res.status).toBe(403); + expect(sb.storage.remove).not.toHaveBeenCalled(); + }); +}); + +describe('POST /api/files/extract-text', () => { + it('reads .txt and .md directly', async () => { + signInAs(REP, 'demo'); + const res = await request(buildApp()) + .post('/api/files/extract-text') + .send({ file: b64('one two three'), fileName: 'notes.txt' }); + expect(res.body).toMatchObject({ success: true, extractedText: 'one two three', wordCount: 3, charCount: 13 }); + }); + + it('reads .docx through mammoth', async () => { + signInAs(REP, 'demo'); + extractRawText.mockResolvedValue({ value: 'From Word' }); + const res = await request(buildApp()).post('/api/files/extract-text').send({ file: b64('PK'), fileName: 'a.docx' }); + expect(res.body.extractedText).toBe('From Word'); + }); + + it('rejects unsupported types and missing input', async () => { + signInAs(REP, 'demo'); + expect((await request(buildApp()).post('/api/files/extract-text').send({ file: b64('x'), fileName: 'a.pdf' })).status).toBe(400); + expect((await request(buildApp()).post('/api/files/extract-text').send({ fileName: 'a.txt' })).status).toBe(400); + expect((await request(buildApp()).post('/api/files/extract-text').send({ file: b64('x') })).status).toBe(400); + }); +}); From d34bad5bb9150e251366d0354146b3947e48d111 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:20 +0530 Subject: [PATCH 06/11] refactor(server): build the app separately from listening, safer errors 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 --- server.ts | 252 +++++++++----------------- src/api/app.ts | 149 ++++++++++++++++ src/api/audit.ts | 3 +- src/api/notifications.ts | 3 +- src/api/rules.ts | 291 +++++++++++++++--------------- src/api/templates.ts | 117 ++++++------ tests/app.test.ts | 163 +++++++++++++++++ tests/routers.test.ts | 372 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 976 insertions(+), 374 deletions(-) create mode 100644 src/api/app.ts create mode 100644 tests/app.test.ts create mode 100644 tests/routers.test.ts diff --git a/server.ts b/server.ts index 02a0072..f10935f 100644 --- a/server.ts +++ b/server.ts @@ -1,169 +1,83 @@ -import express from 'express'; -import cors from 'cors'; -import helmet from 'helmet'; -import { config } from 'dotenv'; -import path from 'path'; -import { fileURLToPath } from 'url'; - -import { aiLimiter } from './src/api/middleware/rateLimit'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -// Load environment variables -config(); - -// Import routes -import proposalsRouter from './src/api/proposals'; -import rulesRouter from './src/api/rules'; -import templatesRouter from './src/api/templates'; -import auditRouter from './src/api/audit'; -import analyzeRouter from './src/api/analyze'; -import usersRouter from './src/api/users'; -import integrationsRouter from './src/api/integrations'; -import authRouter from './src/api/auth'; -import oauthRouter from './src/api/oauth'; -import filesRouter from './src/api/files'; -import analyticsRouter from './src/api/analytics'; -import notificationsRouter from './src/api/notifications'; - -const app = express(); -// Render (and most PaaS) inject PORT; fall back to API_PORT for local dev. -const PORT = process.env.PORT || process.env.API_PORT || 3001; - -// CORS configuration - restrict to production domain in production -// In development: allows localhost origins for local testing -// In production: only allows PRODUCTION_URL from environment variable -const isDevelopment = process.env.NODE_ENV !== 'production'; -const allowedOrigins = isDevelopment - ? [ - 'http://localhost:3000', - 'http://localhost:5173', - 'http://localhost:8080', - 'http://127.0.0.1:3000', - 'http://127.0.0.1:5173', - 'http://127.0.0.1:8080', - ] - : [process.env.PRODUCTION_URL || 'https://your-production-domain.com']; - -// Security headers. crossOriginResourcePolicy is relaxed so the SPA/API can -// serve cross-origin assets (e.g. PDF/file downloads) without being blocked. -app.use(helmet({ - contentSecurityPolicy: false, - crossOriginResourcePolicy: { policy: 'cross-origin' }, -})); - -// Middleware -app.use(cors({ - origin: (origin, callback) => { - // Allow requests with no origin (like mobile apps, Postman, or curl) - if (!origin) return callback(null, true); - - if (allowedOrigins.indexOf(origin) !== -1) { - callback(null, true); - } else { - // Don't throw: an unknown origin should just miss the CORS headers, not turn - // every request into a 500. In production the SPA is served by this same - // process, so same-origin calls must keep working even if PRODUCTION_URL - // is unset or misconfigured in the dashboard. - console.warn(`CORS: origin not in allow list: ${origin}`); - callback(null, false); - } - }, - credentials: true, -})); -app.use(express.json({ limit: '10mb' })); - -// Health check -app.get('/api/health', (req, res) => { - res.json({ status: 'ok', timestamp: new Date().toISOString() }); -}); - -// Routes -// authLimiter is applied per-route inside the router so the read-only /session -// lookup the SPA makes on every load isn't throttled alongside credential posts. -app.use('/api/auth', authRouter); -app.use('/api/proposals', proposalsRouter); -app.use('/api/rules', rulesRouter); -app.use('/api/templates', templatesRouter); -app.use('/api/audit', auditRouter); -app.use('/api/analyze', aiLimiter, analyzeRouter); -app.use('/api/users', usersRouter); -app.use('/api/integrations', integrationsRouter); -app.use('/api/oauth', oauthRouter); -app.use('/api/files', filesRouter); -app.use('/api/analytics', analyticsRouter); -app.use('/api/notifications', notificationsRouter); - -// In production, serve the built SPA from dist/ and let client-side routing -// handle any non-API path (Express 5: use a catch-all middleware, not '*'). -if (process.env.NODE_ENV === 'production') { - const distPath = path.join(__dirname, 'dist'); - app.use(express.static(distPath)); - app.use((req, res, next) => { - if (req.path.startsWith('/api')) return next(); - res.sendFile(path.join(distPath, 'index.html')); - }); -} - -// Error handler -// The unused 4th parameter is required: Express only treats 4-arg middleware as an error handler. -app.use((err: Error, req: express.Request, res: express.Response, _next: express.NextFunction) => { - console.error('API Error:', err); - res.status(500).json({ error: err.message || 'Internal server error' }); -}); - -// Start server with error handling -const server = app.listen(PORT, () => { - console.log(`๐Ÿš€ API Server running on http://localhost:${PORT}`); - console.log(`๐Ÿ“Š Health check: http://localhost:${PORT}/api/health`); - console.log(`๐ŸŽจ Frontend dev server: http://localhost:8080`); - console.log('โœ… Server started successfully'); -}).on('error', (err: NodeJS.ErrnoException) => { - if (err.code === 'EADDRINUSE') { - console.error(`โŒ Port ${PORT} is already in use. Please close the other server or use a different port.`); - } else { - console.error('โŒ Server error:', err); - } - process.exit(1); -}); - -// Graceful shutdown handling -const gracefulShutdown = (signal: string) => { - console.log(`\n${signal} received. Starting graceful shutdown...`); - server.close(() => { - console.log('โœ… Server closed successfully'); - process.exit(0); - }); - - // Force shutdown after 10 seconds - setTimeout(() => { - console.error('โš ๏ธ Forced shutdown after timeout'); - process.exit(1); - }, 10000); -}; - -// Handle various termination signals -process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); -process.on('SIGINT', () => gracefulShutdown('SIGINT')); - -// Handle uncaught errors to prevent crashes -process.on('uncaughtException', (err) => { - console.error('โŒ Uncaught Exception:', err); - console.error('Stack:', err.stack); - // Don't exit in development to allow for debugging - if (process.env.NODE_ENV === 'production') { - gracefulShutdown('uncaughtException'); - } -}); - -process.on('unhandledRejection', (reason, promise) => { - console.error('โŒ Unhandled Rejection at:', promise); - console.error('Reason:', reason); - // Don't exit in development to allow for debugging - if (process.env.NODE_ENV === 'production') { - gracefulShutdown('unhandledRejection'); - } -}); - -export default app; +// Load environment variables before anything else reads them. +import 'dotenv/config'; + +import path from 'path'; +import { fileURLToPath } from 'url'; + +import { createApp } from './src/api/app'; +import { checkAuthConfig } from './src/api/lib/authConfig'; +import { logger } from './src/api/lib/logger'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Render (and most PaaS) inject PORT; fall back to API_PORT for local dev. +const PORT = process.env.PORT || process.env.API_PORT || 3001; + +// Refuse to start with an unsafe auth setup (e.g. AUTH_MODE=login without a real +// NEXTAUTH_SECRET) rather than failing on the first request. +try { + for (const warning of checkAuthConfig()) logger.warn(`โš ๏ธ ${warning}`); +} catch (err) { + logger.error(`โŒ ${(err as Error).message}`); + process.exit(1); +} + +const app = createApp({ distPath: path.join(__dirname, 'dist') }); + +// Start server with error handling +const server = app.listen(PORT, () => { + logger.info(`๐Ÿš€ API Server running on http://localhost:${PORT}`); + logger.info(`๐Ÿ“Š Health check: http://localhost:${PORT}/api/health`); + if (process.env.NODE_ENV !== 'production') { + logger.info('๐ŸŽจ Frontend dev server: http://localhost:8080'); + } + logger.info('โœ… Server started successfully'); +}).on('error', (err: NodeJS.ErrnoException) => { + if (err.code === 'EADDRINUSE') { + logger.error(`โŒ Port ${PORT} is already in use. Please close the other server or use a different port.`); + } else { + logger.error('โŒ Server error:', err); + } + process.exit(1); +}); + +// Graceful shutdown handling +const gracefulShutdown = (signal: string) => { + logger.info(`\n${signal} received. Starting graceful shutdown...`); + server.close(() => { + logger.info('โœ… Server closed successfully'); + process.exit(0); + }); + + // Force shutdown after 10 seconds + setTimeout(() => { + logger.error('โš ๏ธ Forced shutdown after timeout'); + process.exit(1); + }, 10000); +}; + +// Handle various termination signals +process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); +process.on('SIGINT', () => gracefulShutdown('SIGINT')); + +// Handle uncaught errors to prevent crashes +process.on('uncaughtException', (err) => { + logger.error('โŒ Uncaught Exception:', err); + logger.error('Stack:', err.stack); + // Don't exit in development to allow for debugging + if (process.env.NODE_ENV === 'production') { + gracefulShutdown('uncaughtException'); + } +}); + +process.on('unhandledRejection', (reason, promise) => { + logger.error('โŒ Unhandled Rejection at:', promise); + logger.error('Reason:', reason); + // Don't exit in development to allow for debugging + if (process.env.NODE_ENV === 'production') { + gracefulShutdown('unhandledRejection'); + } +}); + +export default app; diff --git a/src/api/app.ts b/src/api/app.ts new file mode 100644 index 0000000..e583d83 --- /dev/null +++ b/src/api/app.ts @@ -0,0 +1,149 @@ +/** + * The Express application: middleware, routes, static SPA serving and the error + * handler. Building it is separate from listening (server.ts) so tests can mount + * the real thing without opening a port. + */ + +import express from 'express'; +import cors from 'cors'; +import helmet from 'helmet'; +import path from 'path'; + +import { aiLimiter } from './middleware/rateLimit'; +import { logger } from './lib/logger'; + +import proposalsRouter from './proposals'; +import rulesRouter from './rules'; +import templatesRouter from './templates'; +import auditRouter from './audit'; +import analyzeRouter from './analyze'; +import usersRouter from './users'; +import integrationsRouter from './integrations'; +import authRouter from './auth'; +import oauthRouter from './oauth'; +import filesRouter from './files'; +import analyticsRouter from './analytics'; +import notificationsRouter from './notifications'; + +/** + * Express "trust proxy" from TRUST_PROXY: a hop count ("1"), "true"/"false", or a + * subnet list. Behind a platform proxy (Render, Heroku, ...) the client's address + * arrives in X-Forwarded-For; without trusting exactly one hop every visitor looks + * like the proxy, so the per-IP rate limits would be shared by everyone โ€” ten + * failed logins from anywhere would lock all users out. Defaults to one hop in + * production, off elsewhere. + */ +export function parseTrustProxy(value: string | undefined, isProduction: boolean): boolean | number | string { + if (value === undefined || value === '') return isProduction ? 1 : false; + if (value === 'true') return true; + if (value === 'false') return false; + const hops = Number(value); + return Number.isInteger(hops) && hops >= 0 ? hops : value; +} + +export interface AppOptions { + /** Built SPA directory; served (with an index.html fallback) when NODE_ENV=production. */ + distPath?: string; +} + +export function createApp(options: AppOptions = {}): express.Express { + const app = express(); + const isProduction = process.env.NODE_ENV === 'production'; + + app.set('trust proxy', parseTrustProxy(process.env.TRUST_PROXY, isProduction)); + + // CORS configuration - restrict to production domain in production + // In development: allows localhost origins for local testing + // In production: only allows PRODUCTION_URL from environment variable + const allowedOrigins = isProduction + ? [process.env.PRODUCTION_URL || 'https://your-production-domain.com'] + : [ + 'http://localhost:3000', + 'http://localhost:5173', + 'http://localhost:8080', + 'http://127.0.0.1:3000', + 'http://127.0.0.1:5173', + 'http://127.0.0.1:8080', + ]; + + // Security headers. crossOriginResourcePolicy is relaxed so the SPA/API can + // serve cross-origin assets (e.g. PDF/file downloads) without being blocked. + app.use(helmet({ + contentSecurityPolicy: false, + crossOriginResourcePolicy: { policy: 'cross-origin' }, + })); + + app.use(cors({ + origin: (origin, callback) => { + // Allow requests with no origin (like mobile apps, Postman, or curl) + if (!origin) return callback(null, true); + + if (allowedOrigins.indexOf(origin) !== -1) { + callback(null, true); + } else { + // Don't throw: an unknown origin should just miss the CORS headers, not turn + // every request into a 500. In production the SPA is served by this same + // process, so same-origin calls must keep working even if PRODUCTION_URL + // is unset or misconfigured in the dashboard. + logger.warn(`CORS: origin not in allow list: ${origin}`); + callback(null, false); + } + }, + credentials: true, + })); + app.use(express.json({ limit: '10mb' })); + + // Health check + app.get('/api/health', (_req, res) => { + res.json({ status: 'ok', timestamp: new Date().toISOString() }); + }); + + // Routes + // authLimiter is applied per-route inside the router so the read-only /session + // lookup the SPA makes on every load isn't throttled alongside credential posts. + app.use('/api/auth', authRouter); + app.use('/api/proposals', proposalsRouter); + app.use('/api/rules', rulesRouter); + app.use('/api/templates', templatesRouter); + app.use('/api/audit', auditRouter); + app.use('/api/analyze', aiLimiter, analyzeRouter); + app.use('/api/users', usersRouter); + app.use('/api/integrations', integrationsRouter); + app.use('/api/oauth', oauthRouter); + app.use('/api/files', filesRouter); + app.use('/api/analytics', analyticsRouter); + app.use('/api/notifications', notificationsRouter); + + // Unknown API paths answer in JSON, like every other API response (not an HTML 404). + app.use('/api', (_req, res) => { + res.status(404).json({ error: 'Not found' }); + }); + + // In production, serve the built SPA from dist/ and let client-side routing + // handle any non-API path (Express 5: use a catch-all middleware, not '*'). + if (isProduction && options.distPath) { + const distPath = options.distPath; + app.use(express.static(distPath)); + app.use((req, res) => { + res.sendFile(path.join(distPath, 'index.html')); + }); + } + + // Error handler + // The unused 4th parameter is required: Express only treats 4-arg middleware as an error handler. + app.use((err: Error & { status?: number; statusCode?: number; expose?: boolean }, _req: express.Request, res: express.Response, _next: express.NextFunction) => { + const status = err.status ?? err.statusCode ?? 500; + + // Client errors raised by Express/body-parser (malformed JSON -> 400, body too + // large -> 413) carry messages that are safe to show. + if (status >= 400 && status < 500) { + return res.status(status).json({ error: err.expose ? err.message : 'Bad request' }); + } + + logger.error('API Error:', err); + // Never leak internals (database errors, stack details) from a production server. + res.status(500).json({ error: isProduction ? 'Internal server error' : err.message || 'Internal server error' }); + }); + + return app; +} diff --git a/src/api/audit.ts b/src/api/audit.ts index 8b29477..d1cda9b 100644 --- a/src/api/audit.ts +++ b/src/api/audit.ts @@ -1,5 +1,6 @@ import { Router, Request, Response } from 'express'; import { requireAuth } from './middleware/auth'; +import { logger } from './lib/logger'; import { getScopedAuditLogs } from './lib/auditQuery'; const router = Router(); @@ -10,7 +11,7 @@ router.get('/', requireAuth, async (req: Request, res: Response) => { const logs = await getScopedAuditLogs(req, 100); res.json(logs); } catch (error) { - console.error('Error fetching audit logs:', error); + logger.error('Error fetching audit logs:', error); res.status(500).json({ error: 'Failed to fetch audit logs' }); } }); diff --git a/src/api/notifications.ts b/src/api/notifications.ts index fb8c0da..2c5c24d 100644 --- a/src/api/notifications.ts +++ b/src/api/notifications.ts @@ -1,5 +1,6 @@ import { Router, Request, Response } from 'express'; import { requireAuth } from './middleware/auth'; +import { logger } from './lib/logger'; import { getScopedAuditLogs } from './lib/auditQuery'; const router = Router(); @@ -19,7 +20,7 @@ router.get('/', requireAuth, async (req: Request, res: Response) => { res.json({ items, unreadCount }); } catch (error) { - console.error('Error fetching notifications:', error); + logger.error('Error fetching notifications:', error); res.status(500).json({ error: 'Failed to fetch notifications' }); } }); diff --git a/src/api/rules.ts b/src/api/rules.ts index b1ec775..f5d2368 100644 --- a/src/api/rules.ts +++ b/src/api/rules.ts @@ -1,145 +1,146 @@ -import { Router, Request, Response } from 'express'; -import { supabase } from '../lib/supabase'; -import { requireAuth, isAdmin } from './middleware/auth'; - -const router = Router(); - -/** Normalize rule from DB (supports snake_case or camelCase) to frontend shape. */ -function toRuleShape(r: Record | null): Record | null { - if (!r || !r.id) return null; - return { - id: r.id, - name: r.name ?? '', - type: r.type ?? 'STRUCTURAL', - description: r.description ?? '', - logic: r.logic ?? {}, - isActive: (r as any).isActive ?? (r as any).is_active ?? true, - createdAt: (r as any).createdAt ?? (r as any).created_at ?? new Date().toISOString(), - updatedAt: (r as any).updatedAt ?? (r as any).updated_at ?? new Date().toISOString(), - }; -} - -// GET all rules (authenticated users: read-only) -router.get('/', requireAuth, async (req: Request, res: Response) => { - try { - let result = await supabase.from('Rule').select('*').order('updatedAt', { ascending: false }); - if (result.error && result.error.message?.toLowerCase().includes('column')) { - result = await supabase.from('Rule').select('*').order('updated_at', { ascending: false }); - } - if (result.error && result.error.message?.toLowerCase().includes('column')) { - result = await supabase.from('Rule').select('*'); - } - const { data: rules, error } = result; - if (error) throw error; - - const normalized = (rules || []).map((r) => toRuleShape(r)).filter(Boolean); - res.json(normalized); - } catch (error) { - console.error('Error fetching rules:', error); - res.status(500).json({ error: 'Failed to fetch rules' }); - } -}); - -// POST create rule (admin only) -router.post('/', requireAuth, async (req: Request, res: Response) => { - try { - if (!isAdmin(req)) { - return res.status(403).json({ error: 'Only administrators can create compliance rules' }); - } - - const { name, type, description, logic, isActive } = req.body; - - if (!name || !type) { - return res.status(400).json({ error: 'Name and type are required' }); - } - - const now = new Date().toISOString(); - const id = crypto.randomUUID(); - const camelPayload = { - id, - name, - type, - description: description || '', - logic: logic || {}, - isActive: isActive ?? true, - updatedAt: now, - }; - let result = await supabase.from('Rule').insert(camelPayload).select().single(); - if (result.error && result.error.message?.includes('column')) { - const snakePayload = { - id, - name, - type, - description: description || '', - logic: logic || {}, - is_active: isActive ?? true, - updated_at: now, - }; - result = await supabase.from('Rule').insert(snakePayload).select().single(); - } - const { data: rule, error } = result; - if (error) throw error; - - const body = toRuleShape(rule); - if (!body) { - console.error('Create rule: insert did not return a row'); - return res.status(500).json({ error: 'Failed to create rule' }); - } - res.status(201).json(body); - } catch (error) { - console.error('Error creating rule:', error); - res.status(500).json({ error: 'Failed to create rule' }); - } -}); - -// PUT update rule (admin only) -router.put('/:id', requireAuth, async (req: Request, res: Response) => { - try { - if (!isAdmin(req)) { - return res.status(403).json({ error: 'Only administrators can update compliance rules' }); - } - - const { id } = req.params; - const { name, type, description, logic, isActive } = req.body; - - const { data: rule, error } = await supabase - .from('Rule') - .update({ - name, - type, - description, - logic, - isActive, - updatedAt: new Date().toISOString(), - }) - .eq('id', id) - .select() - .single(); - - if (error) throw error; - - res.json(toRuleShape(rule)); - } catch (error) { - console.error('Error updating rule:', error); - res.status(500).json({ error: 'Failed to update rule' }); - } -}); - -// DELETE rule (admin only) -router.delete('/:id', requireAuth, async (req: Request, res: Response) => { - try { - if (!isAdmin(req)) { - return res.status(403).json({ error: 'Only administrators can delete compliance rules' }); - } - - const { id } = req.params; - const { error } = await supabase.from('Rule').delete().eq('id', id); - if (error) throw error; - res.json({ success: true }); - } catch (error) { - console.error('Error deleting rule:', error); - res.status(500).json({ error: 'Failed to delete rule' }); - } -}); - -export default router; +import { Router, Request, Response } from 'express'; +import { supabase } from '../lib/supabase'; +import { requireAuth, isAdmin } from './middleware/auth'; +import { logger } from './lib/logger'; + +const router = Router(); + +/** Normalize rule from DB (supports snake_case or camelCase) to frontend shape. */ +function toRuleShape(r: Record | null): Record | null { + if (!r || !r.id) return null; + return { + id: r.id, + name: r.name ?? '', + type: r.type ?? 'STRUCTURAL', + description: r.description ?? '', + logic: r.logic ?? {}, + isActive: r.isActive ?? r.is_active ?? true, + createdAt: r.createdAt ?? r.created_at ?? new Date().toISOString(), + updatedAt: r.updatedAt ?? r.updated_at ?? new Date().toISOString(), + }; +} + +// GET all rules (authenticated users: read-only) +router.get('/', requireAuth, async (req: Request, res: Response) => { + try { + let result = await supabase.from('Rule').select('*').order('updatedAt', { ascending: false }); + if (result.error && result.error.message?.toLowerCase().includes('column')) { + result = await supabase.from('Rule').select('*').order('updated_at', { ascending: false }); + } + if (result.error && result.error.message?.toLowerCase().includes('column')) { + result = await supabase.from('Rule').select('*'); + } + const { data: rules, error } = result; + if (error) throw error; + + const normalized = (rules || []).map((r) => toRuleShape(r)).filter(Boolean); + res.json(normalized); + } catch (error) { + logger.error('Error fetching rules:', error); + res.status(500).json({ error: 'Failed to fetch rules' }); + } +}); + +// POST create rule (admin only) +router.post('/', requireAuth, async (req: Request, res: Response) => { + try { + if (!isAdmin(req)) { + return res.status(403).json({ error: 'Only administrators can create compliance rules' }); + } + + const { name, type, description, logic, isActive } = req.body; + + if (!name || !type) { + return res.status(400).json({ error: 'Name and type are required' }); + } + + const now = new Date().toISOString(); + const id = crypto.randomUUID(); + const camelPayload = { + id, + name, + type, + description: description || '', + logic: logic || {}, + isActive: isActive ?? true, + updatedAt: now, + }; + let result = await supabase.from('Rule').insert(camelPayload).select().single(); + if (result.error && result.error.message?.includes('column')) { + const snakePayload = { + id, + name, + type, + description: description || '', + logic: logic || {}, + is_active: isActive ?? true, + updated_at: now, + }; + result = await supabase.from('Rule').insert(snakePayload).select().single(); + } + const { data: rule, error } = result; + if (error) throw error; + + const body = toRuleShape(rule); + if (!body) { + logger.error('Create rule: insert did not return a row'); + return res.status(500).json({ error: 'Failed to create rule' }); + } + res.status(201).json(body); + } catch (error) { + logger.error('Error creating rule:', error); + res.status(500).json({ error: 'Failed to create rule' }); + } +}); + +// PUT update rule (admin only) +router.put('/:id', requireAuth, async (req: Request, res: Response) => { + try { + if (!isAdmin(req)) { + return res.status(403).json({ error: 'Only administrators can update compliance rules' }); + } + + const { id } = req.params; + const { name, type, description, logic, isActive } = req.body; + + const { data: rule, error } = await supabase + .from('Rule') + .update({ + name, + type, + description, + logic, + isActive, + updatedAt: new Date().toISOString(), + }) + .eq('id', id) + .select() + .single(); + + if (error) throw error; + + res.json(toRuleShape(rule)); + } catch (error) { + logger.error('Error updating rule:', error); + res.status(500).json({ error: 'Failed to update rule' }); + } +}); + +// DELETE rule (admin only) +router.delete('/:id', requireAuth, async (req: Request, res: Response) => { + try { + if (!isAdmin(req)) { + return res.status(403).json({ error: 'Only administrators can delete compliance rules' }); + } + + const { id } = req.params; + const { error } = await supabase.from('Rule').delete().eq('id', id); + if (error) throw error; + res.json({ success: true }); + } catch (error) { + logger.error('Error deleting rule:', error); + res.status(500).json({ error: 'Failed to delete rule' }); + } +}); + +export default router; diff --git a/src/api/templates.ts b/src/api/templates.ts index 42993e4..6619af4 100644 --- a/src/api/templates.ts +++ b/src/api/templates.ts @@ -1,58 +1,59 @@ -import { Router, Request, Response } from 'express'; -import { supabase } from '../lib/supabase'; -import { requireAuth } from './middleware/auth'; - -const router = Router(); - -// GET all templates -router.get('/', requireAuth, async (req: Request, res: Response) => { - try { - const { data: templates, error } = await supabase - .from('Template') - .select('*') - .eq('isActive', true) - .order('createdAt', { ascending: false }); - - if (error) throw error; - - res.json(templates || []); - } catch (error) { - console.error('Error fetching templates:', error); - res.status(500).json({ error: 'Failed to fetch templates' }); - } -}); - -// POST create template -router.post('/', requireAuth, async (req: Request, res: Response) => { - try { - const { name, description, type, content } = req.body; - - if (!name || !type || !content) { - return res.status(400).json({ error: 'Name, type, and content are required' }); - } - - const { data: template, error } = await supabase - .from('Template') - .insert({ - id: crypto.randomUUID(), - name, - description: description || '', - type, - content, - metadata: {}, - isActive: true, - updatedAt: new Date().toISOString(), - }) - .select() - .single(); - - if (error) throw error; - - res.status(201).json(template); - } catch (error) { - console.error('Error creating template:', error); - res.status(500).json({ error: 'Failed to create template' }); - } -}); - -export default router; +import { Router, Request, Response } from 'express'; +import { supabase } from '../lib/supabase'; +import { requireAuth } from './middleware/auth'; +import { logger } from './lib/logger'; + +const router = Router(); + +// GET all templates +router.get('/', requireAuth, async (req: Request, res: Response) => { + try { + const { data: templates, error } = await supabase + .from('Template') + .select('*') + .eq('isActive', true) + .order('createdAt', { ascending: false }); + + if (error) throw error; + + res.json(templates || []); + } catch (error) { + logger.error('Error fetching templates:', error); + res.status(500).json({ error: 'Failed to fetch templates' }); + } +}); + +// POST create template +router.post('/', requireAuth, async (req: Request, res: Response) => { + try { + const { name, description, type, content } = req.body; + + if (!name || !type || !content) { + return res.status(400).json({ error: 'Name, type, and content are required' }); + } + + const { data: template, error } = await supabase + .from('Template') + .insert({ + id: crypto.randomUUID(), + name, + description: description || '', + type, + content, + metadata: {}, + isActive: true, + updatedAt: new Date().toISOString(), + }) + .select() + .single(); + + if (error) throw error; + + res.status(201).json(template); + } catch (error) { + logger.error('Error creating template:', error); + res.status(500).json({ error: 'Failed to create template' }); + } +}); + +export default router; diff --git a/tests/app.test.ts b/tests/app.test.ts new file mode 100644 index 0000000..1687202 --- /dev/null +++ b/tests/app.test.ts @@ -0,0 +1,163 @@ +import { describe, it, expect, afterEach, beforeAll, afterAll, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import request from 'supertest'; +import express from 'express'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +// One route that blows up, to exercise the global error handler. +vi.mock('../src/api/templates', async () => { + const { Router } = await import('express'); + const router = Router(); + router.get('/boom', () => { + throw new Error('relation "Template" does not exist (secret db detail)'); + }); + return { default: router }; +}); + +import { createApp, parseTrustProxy } from '../src/api/app'; + +const savedEnv = { NODE_ENV: process.env.NODE_ENV, TRUST_PROXY: process.env.TRUST_PROXY }; + +afterEach(() => { + process.env.NODE_ENV = savedEnv.NODE_ENV; + if (savedEnv.TRUST_PROXY === undefined) delete process.env.TRUST_PROXY; + else process.env.TRUST_PROXY = savedEnv.TRUST_PROXY; +}); + +describe('parseTrustProxy', () => { + it('defaults to one hop in production and off elsewhere', () => { + expect(parseTrustProxy(undefined, true)).toBe(1); + expect(parseTrustProxy('', true)).toBe(1); + expect(parseTrustProxy(undefined, false)).toBe(false); + }); + + it('honours explicit settings', () => { + expect(parseTrustProxy('2', true)).toBe(2); + expect(parseTrustProxy('0', true)).toBe(0); + expect(parseTrustProxy('true', false)).toBe(true); + expect(parseTrustProxy('false', true)).toBe(false); + expect(parseTrustProxy('loopback, 10.0.0.0/8', false)).toBe('loopback, 10.0.0.0/8'); + }); + + it('is applied to the app', () => { + process.env.NODE_ENV = 'production'; + delete process.env.TRUST_PROXY; + expect(createApp().get('trust proxy')).toBe(1); + + process.env.NODE_ENV = 'test'; + expect(createApp().get('trust proxy')).toBe(false); + }); + + it('lets the real client IP through when one proxy hop is trusted', async () => { + process.env.TRUST_PROXY = '1'; + const app = createApp(); + // Same setting, probed with a tiny app: req.ip must come from X-Forwarded-For. + const probe = express(); + probe.set('trust proxy', app.get('trust proxy')); + probe.get('/ip', (req, res) => { + res.json({ ip: req.ip }); + }); + const res = await request(probe).get('/ip').set('X-Forwarded-For', '203.0.113.9'); + expect(res.body.ip).toBe('203.0.113.9'); + }); +}); + +describe('createApp', () => { + it('answers the health check', async () => { + const res = await request(createApp()).get('/api/health'); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + }); + + it('answers unknown API paths with a JSON 404', async () => { + const res = await request(createApp()).get('/api/does-not-exist'); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Not found' }); + }); + + it('sets security headers', async () => { + const res = await request(createApp()).get('/api/health'); + expect(res.headers['x-content-type-options']).toBe('nosniff'); + expect(res.headers['x-powered-by']).toBeUndefined(); + }); + + it('reports malformed JSON as a 400, not a 500', async () => { + const res = await request(createApp()) + .post('/api/auth/login') + .set('Content-Type', 'application/json') + .send('{"email": '); + expect(res.status).toBe(400); + expect(res.body).toHaveProperty('error'); + }); + + it('reports an oversized body as a 413', async () => { + const big = JSON.stringify({ file: 'x'.repeat(11 * 1024 * 1024) }); + const res = await request(createApp()).post('/api/auth/login').set('Content-Type', 'application/json').send(big); + expect(res.status).toBe(413); + }); +}); + +describe('error handler', () => { + it('shows the message outside production (useful while developing)', async () => { + process.env.NODE_ENV = 'test'; + const res = await request(createApp()).get('/api/templates/boom'); + expect(res.status).toBe(500); + expect(res.body.error).toContain('does not exist'); + }); + + it('hides internals in production', async () => { + process.env.NODE_ENV = 'production'; + const res = await request(createApp()).get('/api/templates/boom'); + expect(res.status).toBe(500); + expect(res.body).toEqual({ error: 'Internal server error' }); + expect(JSON.stringify(res.body)).not.toContain('secret db detail'); + }); +}); + +describe('serving the built SPA in production', () => { + let dist: string; + + beforeAll(() => { + dist = fs.mkdtempSync(path.join(os.tmpdir(), 'dealsentry-dist-')); + fs.writeFileSync(path.join(dist, 'index.html'), 'SPA shell'); + fs.mkdirSync(path.join(dist, 'assets')); + fs.writeFileSync(path.join(dist, 'assets', 'app.js'), 'console.log("app")'); + }); + + afterAll(() => { + fs.rmSync(dist, { recursive: true, force: true }); + }); + + it('serves static assets and falls back to index.html for client-side routes', async () => { + process.env.NODE_ENV = 'production'; + const app = createApp({ distPath: dist }); + + const asset = await request(app).get('/assets/app.js'); + expect(asset.status).toBe(200); + expect(asset.text).toContain('console.log'); + + const route = await request(app).get('/proposals/abc/review'); + expect(route.status).toBe(200); + expect(route.text).toContain('SPA shell'); + }); + + it('keeps API 404s as JSON rather than serving the shell', async () => { + process.env.NODE_ENV = 'production'; + const res = await request(createApp({ distPath: dist })).get('/api/nope'); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Not found' }); + }); + + it('does not serve the SPA outside production', async () => { + process.env.NODE_ENV = 'test'; + const res = await request(createApp({ distPath: dist })).get('/proposals'); + expect(res.status).toBe(404); + }); +}); diff --git a/tests/routers.test.ts b/tests/routers.test.ts new file mode 100644 index 0000000..1d6ac5c --- /dev/null +++ b/tests/routers.test.ts @@ -0,0 +1,372 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import bcrypt from 'bcryptjs'; +import type { SupabaseMock } from './helpers/supabaseMock'; + +vi.mock('../src/lib/supabase', async () => { + const { createSupabaseMock } = await import('./helpers/supabaseMock'); + const mock = createSupabaseMock(); + return { supabase: mock.client, default: mock.client, __mock: mock }; +}); + +import * as supabaseModule from '../src/lib/supabase'; +import rulesRouter from '../src/api/rules'; +import templatesRouter from '../src/api/templates'; +import auditRouter from '../src/api/audit'; +import notificationsRouter from '../src/api/notifications'; +import analyticsRouter from '../src/api/analytics'; +import authRouter from '../src/api/auth'; +import { resetDefaultUser } from '../src/api/middleware/auth'; + +const sb = (supabaseModule as unknown as { __mock: SupabaseMock }).__mock; + +const ADMIN = { id: 'admin1', email: 'a@b.com', role: 'ADMIN', company_id: null }; +const REP_C1 = { id: 'rep1', email: 'r@b.com', role: 'SALES_REP', company_id: 'c1' }; +const LONER = { id: 'loner1', email: 'l@b.com', role: 'SALES_REP', company_id: null }; + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/api/rules', rulesRouter); + app.use('/api/templates', templatesRouter); + app.use('/api/audit', auditRouter); + app.use('/api/notifications', notificationsRouter); + app.use('/api/analytics', analyticsRouter); + app.use('/api/auth', authRouter); + return app; +} + +/** Everyone is `user` (demo mode's default identity). */ +function signInAs(user: Record) { + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.op === 'select' && !ctx.single) return { data: [user] }; + return undefined; + }); +} + +beforeEach(() => { + sb.reset(); + resetDefaultUser(); + delete process.env.AUTH_MODE; +}); + +describe('rules', () => { + const dbRule = (over: Record = {}) => ({ + id: 'r1', + name: 'Max discount', + type: 'DISCOUNT', + description: 'No more than 25%', + logic: { maxDiscount: 25 }, + isActive: true, + createdAt: '2026-01-01T00:00:00Z', + updatedAt: '2026-01-02T00:00:00Z', + ...over, + }); + + it('lists rules in the shape the SPA expects, tolerating snake_case columns', async () => { + signInAs(REP_C1); + sb.handle((ctx) => + ctx.table === 'Rule' && ctx.op === 'select' + ? { + data: [ + dbRule(), + { id: 'r2', name: 'Legacy', type: 'PAYMENT', is_active: false, created_at: 'c', updated_at: 'u' }, + { name: 'no id, dropped' }, + ], + } + : undefined + ); + + const res = await request(buildApp()).get('/api/rules'); + + expect(res.status).toBe(200); + expect(res.body).toHaveLength(2); + expect(res.body[0]).toMatchObject({ id: 'r1', isActive: true, logic: { maxDiscount: 25 } }); + expect(res.body[1]).toMatchObject({ id: 'r2', isActive: false, createdAt: 'c', updatedAt: 'u', description: '' }); + }); + + it('falls back to a plain select when the order column does not exist', async () => { + signInAs(REP_C1); + sb.handle((ctx) => { + if (ctx.table !== 'Rule' || ctx.op !== 'select') return undefined; + return ctx.order ? { error: { message: 'column "updatedAt" does not exist' } } : { data: [dbRule()] }; + }); + const res = await request(buildApp()).get('/api/rules'); + expect(res.status).toBe(200); + expect(res.body).toHaveLength(1); + }); + + it('only lets administrators create, change or delete rules', async () => { + signInAs(REP_C1); + expect((await request(buildApp()).post('/api/rules').send({ name: 'x', type: 'DISCOUNT' })).status).toBe(403); + expect((await request(buildApp()).put('/api/rules/r1').send({ name: 'x' })).status).toBe(403); + expect((await request(buildApp()).delete('/api/rules/r1')).status).toBe(403); + expect(sb.callsFor('Rule', 'insert')).toHaveLength(0); + expect(sb.callsFor('Rule', 'update')).toHaveLength(0); + expect(sb.callsFor('Rule', 'delete')).toHaveLength(0); + }); + + it('creates a rule (camelCase columns first)', async () => { + signInAs(ADMIN); + sb.handle((ctx) => (ctx.table === 'Rule' && ctx.op === 'insert' ? { data: dbRule(ctx.payload as object) } : undefined)); + + const res = await request(buildApp()) + .post('/api/rules') + .send({ name: 'Min deal', type: 'PRICING', logic: { minDealSize: 10000 } }); + + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ name: 'Min deal', type: 'PRICING', isActive: true, logic: { minDealSize: 10000 } }); + expect(sb.callsFor('Rule', 'insert')[0].payload).toMatchObject({ isActive: true, description: '' }); + }); + + it('retries with snake_case columns when the table uses them', async () => { + signInAs(ADMIN); + sb.handle((ctx) => { + if (ctx.table !== 'Rule' || ctx.op !== 'insert') return undefined; + const payload = ctx.payload as Record; + return 'isActive' in payload + ? { error: { message: 'column "isActive" of relation "Rule" does not exist' } } + : { data: { ...payload, id: payload.id } }; + }); + + const res = await request(buildApp()).post('/api/rules').send({ name: 'Legacy', type: 'LEGAL' }); + + expect(res.status).toBe(201); + expect(sb.callsFor('Rule', 'insert')).toHaveLength(2); + expect(sb.callsFor('Rule', 'insert')[1].payload).toMatchObject({ is_active: true }); + }); + + it('validates required fields and reports a failed insert', async () => { + signInAs(ADMIN); + expect((await request(buildApp()).post('/api/rules').send({ name: 'no type' })).status).toBe(400); + + sb.handle((ctx) => (ctx.table === 'Rule' && ctx.op === 'insert' ? { error: { message: 'boom' } } : undefined)); + expect((await request(buildApp()).post('/api/rules').send({ name: 'x', type: 'LEGAL' })).status).toBe(500); + }); + + it('updates and deletes as an admin', async () => { + signInAs(ADMIN); + sb.handle((ctx) => + ctx.table === 'Rule' && ctx.op === 'update' ? { data: dbRule({ name: 'Renamed' }) } : undefined + ); + + const updated = await request(buildApp()).put('/api/rules/r1').send({ name: 'Renamed' }); + expect(updated.body).toMatchObject({ id: 'r1', name: 'Renamed' }); + expect(sb.callsFor('Rule', 'update')[0].filters).toContainEqual(['eq', 'id', 'r1']); + + const deleted = await request(buildApp()).delete('/api/rules/r1'); + expect(deleted.body).toEqual({ success: true }); + }); +}); + +describe('templates', () => { + it('lists active templates, newest first', async () => { + signInAs(REP_C1); + sb.handle((ctx) => (ctx.table === 'Template' ? { data: [{ id: 't1', name: 'MSA' }] } : undefined)); + + const res = await request(buildApp()).get('/api/templates'); + + expect(res.body).toEqual([{ id: 't1', name: 'MSA' }]); + const query = sb.callsFor('Template', 'select')[0]; + expect(query.filters).toContainEqual(['eq', 'isActive', true]); + expect(query.order?.[0]?.[0]).toBe('createdAt'); + }); + + it('validates and creates a template', async () => { + signInAs(REP_C1); + expect((await request(buildApp()).post('/api/templates').send({ name: 'x' })).status).toBe(400); + + sb.handle((ctx) => (ctx.table === 'Template' && ctx.op === 'insert' ? { data: ctx.payload } : undefined)); + const res = await request(buildApp()).post('/api/templates').send({ name: 'SOW', type: 'SOW', content: '# SOW' }); + + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ name: 'SOW', description: '', isActive: true }); + }); +}); + +describe('audit log and notifications', () => { + const log = (id: string, timestamp: string) => ({ + id, + action: 'Created proposal', + timestamp, + actorId: 'rep1', + proposalId: 'p1', + User: { name: 'Rep', email: 'r@b.com', role: 'SALES_REP' }, + Proposal: { title: 'Cloud Migration' }, + }); + + it('shows an admin everything, formatted for the SPA', async () => { + signInAs(ADMIN); + sb.handle((ctx) => (ctx.table === 'AuditLog' ? { data: [log('a1', '2026-02-01T00:00:00Z')] } : undefined)); + + const res = await request(buildApp()).get('/api/audit'); + + expect(res.body[0]).toEqual({ + id: 'a1', + action: 'Created proposal', + timestamp: '2026-02-01T00:00:00Z', + actorId: 'rep1', + actor: { name: 'Rep', email: 'r@b.com', role: 'SALES_REP' }, + proposalId: 'p1', + proposal: { title: 'Cloud Migration' }, + }); + const query = sb.callsFor('AuditLog', 'select')[0]; + expect(query.filters).toEqual([]); + expect(query.limit).toBe(100); + }); + + it('scopes a company member to their own actions plus their companyโ€™s proposals', async () => { + signInAs(REP_C1); + sb.handle((ctx) => { + if (ctx.table === 'Proposal') return { data: [{ id: 'p1' }, { id: 'p2' }] }; + if (ctx.table === 'AuditLog') return { data: [] }; + return undefined; + }); + + await request(buildApp()).get('/api/audit'); + + const orFilter = sb.callsFor('AuditLog', 'select')[0].filters.find(([m]) => m === 'or'); + expect(orFilter?.[1]).toBe('actorId.eq.rep1,proposalId.in.(p1,p2)'); + }); + + it('limits a user with no company to their own actions', async () => { + signInAs(LONER); + sb.handle((ctx) => (ctx.table === 'AuditLog' ? { data: [] } : undefined)); + + await request(buildApp()).get('/api/audit'); + + expect(sb.callsFor('AuditLog', 'select')[0].filters).toContainEqual(['eq', 'actorId', 'loner1']); + }); + + it('reports failures as a 500', async () => { + signInAs(ADMIN); + sb.handle((ctx) => (ctx.table === 'AuditLog' ? { error: { message: 'boom' } } : undefined)); + expect((await request(buildApp()).get('/api/audit')).status).toBe(500); + expect((await request(buildApp()).get('/api/notifications')).status).toBe(500); + }); + + it('counts notifications newer than the clientโ€™s `since` timestamp', async () => { + signInAs(ADMIN); + sb.handle((ctx) => + ctx.table === 'AuditLog' + ? { data: [log('new', '2026-03-02T00:00:00Z'), log('mid', '2026-03-01T12:00:00Z'), log('old', '2026-02-01T00:00:00Z')] } + : undefined + ); + + const since = await request(buildApp()).get('/api/notifications?since=2026-03-01T00:00:00Z'); + expect(since.body.items).toHaveLength(3); + expect(since.body.unreadCount).toBe(2); + + const noSince = await request(buildApp()).get('/api/notifications'); + expect(noSince.body.unreadCount).toBe(3); + + const badSince = await request(buildApp()).get('/api/notifications?since=not-a-date'); + expect(badSince.body.unreadCount).toBe(3); + }); +}); + +describe('analytics summary', () => { + const rows = [ + { status: 'PENDING', createdAt: '2026-03-01T00:00:00Z', metadata: { discount: 5, dealSize: 1000, region: 'EMEA' }, RiskReport: [{ readinessScore: 70, legalRisk: 10, pricingRisk: 20, structuralRisk: 30 }] }, + { status: 'APPROVED', createdAt: '2026-03-02T00:00:00Z', metadata: {}, RiskReport: [] }, + ]; + + it('returns the aggregates for an admin without filtering', async () => { + signInAs(ADMIN); + sb.handle((ctx) => (ctx.table === 'Proposal' && ctx.op === 'select' ? { data: rows } : undefined)); + + const res = await request(buildApp()).get('/api/analytics/summary'); + + expect(res.status).toBe(200); + expect(res.body.totals).toMatchObject({ total: 2, pending: 1, approved: 1 }); + expect(sb.callsFor('Proposal', 'select')[0].filters).toEqual([]); + }); + + it('narrows a company member to their company', async () => { + signInAs(REP_C1); + sb.handle((ctx) => (ctx.table === 'Proposal' && ctx.op === 'select' ? { data: [] } : undefined)); + await request(buildApp()).get('/api/analytics/summary'); + expect(sb.callsFor('Proposal', 'select')[0].filters).toContainEqual(['eq', 'company_id', 'c1']); + }); + + it('narrows a company-less user to their own proposals in login mode', async () => { + process.env.AUTH_MODE = 'login'; + const jwt = (await import('jsonwebtoken')).default; + sb.handle((ctx) => { + if (ctx.table === 'User' && ctx.single) return { data: LONER }; + if (ctx.table === 'Proposal') return { data: [] }; + return undefined; + }); + const token = jwt.sign({ userId: 'loner1' }, process.env.NEXTAUTH_SECRET as string); + + const res = await request(buildApp()).get('/api/analytics/summary').set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(sb.callsFor('Proposal', 'select')[0].filters).toContainEqual(['eq', 'userId', 'loner1']); + }); + + it('reports a database failure as a 500', async () => { + signInAs(ADMIN); + sb.handle((ctx) => (ctx.table === 'Proposal' ? { error: { message: 'boom' } } : undefined)); + expect((await request(buildApp()).get('/api/analytics/summary')).status).toBe(500); + }); +}); + +describe('POST /api/auth/change-password', () => { + const stored = async (password = 'old-password-123') => ({ + id: 'rep1', + email: 'r@b.com', + role: 'SALES_REP', + company_id: null, + password: await bcrypt.hash(password, 4), + }); + + function seedUser(row: Record | null) { + sb.handle((ctx) => { + if (ctx.table !== 'User') return undefined; + if (ctx.op === 'select') return { data: ctx.single ? row : row ? [row] : [] }; + return undefined; + }); + } + + it('validates the request', async () => { + seedUser(await stored()); + const app = buildApp(); + expect((await request(app).post('/api/auth/change-password').send({})).status).toBe(400); + expect( + (await request(app).post('/api/auth/change-password').send({ currentPassword: 'old-password-123', newPassword: 'short' })).status + ).toBe(400); + }); + + it('rejects a wrong current password without changing anything', async () => { + seedUser(await stored()); + const res = await request(buildApp()) + .post('/api/auth/change-password') + .send({ currentPassword: 'not-the-password', newPassword: 'a-brand-new-password' }); + expect(res.status).toBe(401); + expect(sb.callsFor('User', 'update')).toHaveLength(0); + }); + + it('refuses when the account has no password set', async () => { + seedUser({ ...(await stored()), password: null }); + const res = await request(buildApp()) + .post('/api/auth/change-password') + .send({ currentPassword: 'anything-long', newPassword: 'a-brand-new-password' }); + expect(res.status).toBe(400); + }); + + it('stores the new password hashed, never in the clear', async () => { + seedUser(await stored()); + + const res = await request(buildApp()) + .post('/api/auth/change-password') + .send({ currentPassword: 'old-password-123', newPassword: 'a-brand-new-password' }); + + expect(res.status).toBe(200); + const update = sb.callsFor('User', 'update')[0]; + const newHash = (update.payload as { password: string }).password; + expect(newHash).not.toBe('a-brand-new-password'); + expect(await bcrypt.compare('a-brand-new-password', newHash)).toBe(true); + }); +}); From 1f84c95f3e15edecd2c95c2d8934889d58eb5d4a Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:22 +0530 Subject: [PATCH 07/11] chore(web): split vendor chunks, collapse Vite proxy errors into one 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. --- vite.config.ts | 68 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/vite.config.ts b/vite.config.ts index 45fd0e5..08e47a2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,9 +1,35 @@ -import { defineConfig } from "vite"; +import { createLogger, defineConfig } from "vite"; import react from "@vitejs/plugin-react-swc"; -import path from "path"; +import { fileURLToPath } from "node:url"; + +const API_TARGET = "http://localhost:3001"; + +// While the API server (re)starts, every proxied request fails with ECONNREFUSED or +// ECONNRESET, and Vite logs a multi-line stack trace for each one โ€” a page makes +// about a dozen requests a second, so the terminal fills up. (A `proxy.on("error")` +// handler cannot prevent that: Vite registers its own logging handler *after* +// `configure` runs.) Collapse those traces into a single line per outage; every +// other proxy error is still logged in full. +const logger = createLogger(); +const logError = logger.error.bind(logger); +let apiUnreachable = false; + +logger.error = (msg, options) => { + if (msg.includes("http proxy error") && /ECONNREFUSED|ECONNRESET/.test(msg)) { + if (!apiUnreachable) { + apiUnreachable = true; + logger.warn(`API server (${API_TARGET}) is not reachable yet - requests fail until it is up`, { + timestamp: true, + }); + } + return; + } + logError(msg, options); +}; // https://vitejs.dev/config/ export default defineConfig(() => ({ + customLogger: logger, server: { host: "::", port: 8080, @@ -12,11 +38,12 @@ export default defineConfig(() => ({ }, proxy: { "/api": { - target: "http://localhost:3001", + target: API_TARGET, changeOrigin: true, configure: (proxy) => { - proxy.on("error", () => { - // suppress ECONNREFUSED noise during backend startup + // Any response from the API means it is back: re-arm the one-line notice. + proxy.on("proxyRes", () => { + apiUnreachable = false; }); }, }, @@ -25,7 +52,36 @@ export default defineConfig(() => ({ plugins: [react()], resolve: { alias: { - "@": path.resolve(__dirname, "./src"), + "@": fileURLToPath(new URL("./src", import.meta.url)), + }, + }, + build: { + rollupOptions: { + output: { + // Pages are lazy-loaded (see App.tsx); this groups the heavy third-party + // libraries into long-lived vendor chunks so an app deploy doesn't + // invalidate them in the browser cache, and so the chart library is only + // fetched by the pages that draw charts. + manualChunks(id: string) { + if (!id.includes("node_modules")) return undefined; + // Tiny helpers the app shell uses on every page (its cn() class helper) that + // recharts also depends on. Without naming them, Rollup parks them in the + // charts chunk and every page load then downloads the whole chart library. + if (/[\\/]node_modules[\\/](clsx|tailwind-merge|class-variance-authority)[\\/]/.test(id)) return "utils"; + if (/[\\/]node_modules[\\/](recharts|d3-[^\\/]+|victory-vendor|internmap|decimal\.js-light)[\\/]/.test(id)) { + return "charts"; + } + if (id.includes("framer-motion") || id.includes("motion-dom") || id.includes("motion-utils")) { + return "motion"; + } + if (id.includes("@radix-ui")) return "radix"; + if (/[\\/]node_modules[\\/](react-router|react-router-dom|@remix-run)[\\/]/.test(id)) { + return "router"; + } + if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) return "react"; + return undefined; + }, + }, }, }, })); From 9ab7974a41aa41e357649a3a188a652a963ef485 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:23 +0530 Subject: [PATCH 08/11] feat(web): sign-in page, lazy routes, run/bulk analysis, safer integrations 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. --- src/App.tsx | 112 +++++++++----- src/components/layout/ClientLayout.tsx | 17 ++- src/components/ui/RiskBar.tsx | 146 +++++++++---------- src/context/ProposalProvider.tsx | 22 ++- src/context/proposal-context.ts | 5 +- src/hooks/use-session.ts | 193 ++++++++++++++++++++----- src/lib/api-client.ts | 126 ++++++++++++++-- src/lib/auth-events.ts | 20 +++ src/pages/Compliance.tsx | 23 ++- src/pages/Integrations.tsx | 99 ++++++------- src/pages/Login.tsx | 139 ++++++++++++++++++ src/pages/ProposalReview.tsx | 64 ++++++-- src/pages/Proposals.tsx | 89 ++++++++++-- src/pages/Settings.tsx | 4 +- src/types/index.ts | 4 +- 15 files changed, 808 insertions(+), 255 deletions(-) create mode 100644 src/lib/auth-events.ts create mode 100644 src/pages/Login.tsx diff --git a/src/App.tsx b/src/App.tsx index dbb843d..db99dee 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,57 +1,97 @@ +import { lazy, Suspense } from "react"; import { Toaster } from "@/components/ui/toaster"; import { Toaster as Sonner } from "@/components/ui/sonner"; import { TooltipProvider } from "@/components/ui/tooltip"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"; +import { Loader2 } from "lucide-react"; import { ProposalProvider } from "@/context/ProposalProvider"; import { useApiConnection } from "@/hooks/use-api-connection"; -import { useSession } from "@/hooks/use-session"; +import { useAuth, useSession } from "@/hooks/use-session"; import ClientLayout from "@/components/layout/ClientLayout"; -import Home from "@/pages/Home"; -import Dashboard from "@/pages/Dashboard"; -import Proposals from "@/pages/Proposals"; -import UploadProposal from "@/pages/UploadProposal"; -import NewProposal from "@/pages/NewProposal"; -import CreateProposal from "@/pages/CreateProposal"; -import ProposalReview from "@/pages/ProposalReview"; -import Compliance from "@/pages/Compliance"; -import Integrations from "@/pages/Integrations"; -import Settings from "@/pages/Settings"; -import Audit from "@/pages/Audit"; -import Analytics from "@/pages/Analytics"; -import NotFound from "@/pages/NotFound"; + +// Every page is its own chunk, fetched when first visited, so the initial load +// carries only the shell. (Charts and animation libraries are split out in +// vite.config.ts and only load with the pages that use them.) +const Home = lazy(() => import("@/pages/Home")); +const Login = lazy(() => import("@/pages/Login")); +const Dashboard = lazy(() => import("@/pages/Dashboard")); +const Proposals = lazy(() => import("@/pages/Proposals")); +const UploadProposal = lazy(() => import("@/pages/UploadProposal")); +const NewProposal = lazy(() => import("@/pages/NewProposal")); +const CreateProposal = lazy(() => import("@/pages/CreateProposal")); +const ProposalReview = lazy(() => import("@/pages/ProposalReview")); +const Compliance = lazy(() => import("@/pages/Compliance")); +const Integrations = lazy(() => import("@/pages/Integrations")); +const Settings = lazy(() => import("@/pages/Settings")); +const Audit = lazy(() => import("@/pages/Audit")); +const Analytics = lazy(() => import("@/pages/Analytics")); +const NotFound = lazy(() => import("@/pages/NotFound")); const queryClient = new QueryClient(); +function PageFallback() { + return ( +
    + +
    + ); +} + +/** + * Old sign-in URLs (/login, /auth, /signup) lead to the dashboard โ€” but only once the + * session check has finished. Redirecting while it is still in flight would rewrite + * /login to /dashboard before we know a sign-in page is needed (in login mode the + * gate in AppContent shows it instead, and the URL should stay /login). + */ +function SignInRedirect() { + const { status } = useAuth(); + return status === "loading" ? : ; +} + function AppContent() { // Monitor API connection status useApiConnection(); - // No login screen: resolve the acting user once, up front. + // Resolve the acting user once, up front (also learns whether sign-in is required). useSession(); + const { status, mode } = useAuth(); + + // Login mode and no valid session: nothing but the sign-in page is reachable. + if (mode === "login" && status === "login-required") { + return ( + }> + + + ); + } return ( - - } /> - {/* Sign-in was removed โ€” old auth links land on the dashboard. */} - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - + }> + + } /> + {/* Demo mode has no sign-in: old auth links land on the dashboard. + In login mode a signed-in user is sent on, too (the Login page itself + is rendered above whenever a session is missing). */} + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + ); } @@ -70,4 +110,4 @@ const App = () => ( ); -export default App; \ No newline at end of file +export default App; diff --git a/src/components/layout/ClientLayout.tsx b/src/components/layout/ClientLayout.tsx index 903c9fc..95ea57f 100644 --- a/src/components/layout/ClientLayout.tsx +++ b/src/components/layout/ClientLayout.tsx @@ -13,9 +13,10 @@ import { User, Crown, Home as HomeIcon, + LogOut, Settings as SettingsIcon } from "lucide-react"; -import { useSession } from "@/hooks/use-session"; +import { signOut, useAuth } from "@/hooks/use-session"; import NotificationBell from "@/components/NotificationBell"; interface ClientLayoutProps { @@ -41,7 +42,7 @@ const navItems: NavItem[] = [ export default function ClientLayout({ children }: ClientLayoutProps) { const location = useLocation(); - const user = useSession(); + const { user, mode } = useAuth(); const userRole = user?.role || ""; const userName = user?.name || user?.email || "User"; @@ -148,6 +149,18 @@ export default function ClientLayout({ children }: ClientLayoutProps) { {userRole} + {/* Only meaningful when the server has real sign-in (login mode). */} + {mode === "login" && ( + + )} diff --git a/src/components/ui/RiskBar.tsx b/src/components/ui/RiskBar.tsx index ccfc8e5..244a64e 100644 --- a/src/components/ui/RiskBar.tsx +++ b/src/components/ui/RiskBar.tsx @@ -1,73 +1,73 @@ -import { cn } from "@/lib/utils"; -import { AlertTriangle, CheckCircle, AlertCircle } from "lucide-react"; - -interface RiskBarProps { - risk: number; - label: string; - className?: string; -} - -export function RiskBar({ risk, label, className }: RiskBarProps) { - // Clamp risk to 0-100 range for display - const displayRisk = Math.min(100, Math.max(0, risk)); - - const getRiskLevel = (risk: number): { label: string; color: string; bgColor: string; icon: any } => { - if (risk <= 20) return { - label: "Low Risk", - color: "text-emerald-600", - bgColor: "bg-emerald-500", - icon: CheckCircle - }; - if (risk <= 50) return { - label: "Medium Risk", - color: "text-amber-600", - bgColor: "bg-amber-500", - icon: AlertCircle - }; - if (risk <= 75) return { - label: "High Risk", - color: "text-orange-600", - bgColor: "bg-orange-500", - icon: AlertTriangle - }; - return { - label: "Critical Risk", - color: "text-red-600", - bgColor: "bg-red-500", - icon: AlertTriangle - }; - }; - - const riskLevel = getRiskLevel(risk); - const Icon = riskLevel.icon; - - return ( -
    -
    - {label} -
    - - - {risk > 100 ? "CRITICAL" : riskLevel.label} - -
    -
    - -
    -
    - {risk > 100 && ( -
    - )} -
    - -
    - - {Math.round(risk)}% - -
    -
    - ); -} +import { cn } from "@/lib/utils"; +import { AlertTriangle, CheckCircle, AlertCircle, type LucideIcon } from "lucide-react"; + +interface RiskBarProps { + risk: number; + label: string; + className?: string; +} + +export function RiskBar({ risk, label, className }: RiskBarProps) { + // Clamp risk to 0-100 range for display + const displayRisk = Math.min(100, Math.max(0, risk)); + + const getRiskLevel = (risk: number): { label: string; color: string; bgColor: string; icon: LucideIcon } => { + if (risk <= 20) return { + label: "Low Risk", + color: "text-emerald-600", + bgColor: "bg-emerald-500", + icon: CheckCircle + }; + if (risk <= 50) return { + label: "Medium Risk", + color: "text-amber-600", + bgColor: "bg-amber-500", + icon: AlertCircle + }; + if (risk <= 75) return { + label: "High Risk", + color: "text-orange-600", + bgColor: "bg-orange-500", + icon: AlertTriangle + }; + return { + label: "Critical Risk", + color: "text-red-600", + bgColor: "bg-red-500", + icon: AlertTriangle + }; + }; + + const riskLevel = getRiskLevel(risk); + const Icon = riskLevel.icon; + + return ( +
    +
    + {label} +
    + + + {risk > 100 ? "CRITICAL" : riskLevel.label} + +
    +
    + +
    +
    + {risk > 100 && ( +
    + )} +
    + +
    + + {Math.round(risk)}% + +
    +
    + ); +} diff --git a/src/context/ProposalProvider.tsx b/src/context/ProposalProvider.tsx index 338c563..3e6ad7a 100644 --- a/src/context/ProposalProvider.tsx +++ b/src/context/ProposalProvider.tsx @@ -3,6 +3,7 @@ import { useLocation } from "react-router-dom"; import { proposalsApi, Proposal } from "@/lib/api-client"; import { mockProposals } from "@/data/mockData"; import { useToast } from "@/hooks/use-toast"; +import { useAuth } from "@/hooks/use-session"; import { ProposalContext } from "@/context/proposal-context"; type ProposalStatus = "PENDING" | "IN_REVIEW" | "APPROVED" | "REJECTED"; @@ -17,8 +18,16 @@ export function ProposalProvider({ children }: { children: ReactNode }) { // Ref, not state: never rendered, and keeping it out of effect dependencies // means showing the warning doesn't restart the retry loop. const hasShownOfflineWarningRef = useRef(false); + // The server is reachable but wants a sign-in (login mode). That is not "offline": + // stop fetching, retrying and polling โ€” the sign-in page is on screen, and signing + // in reloads the app, which starts fresh. + const { status: authStatus } = useAuth(); + const signInRequired = authStatus === "login-required"; useEffect(() => { + if (signInRequired) { + return; + } let retryCount = 0; let cancelled = false; const maxRetries = 10; @@ -51,11 +60,11 @@ export function ProposalProvider({ children }: { children: ReactNode }) { return () => { cancelled = true; }; - // eslint-disable-next-line react-hooks/exhaustive-deps -- refetch only on navigation; fetchProposals/toast are stable - }, [location.pathname]); + // eslint-disable-next-line react-hooks/exhaustive-deps -- refetch only on navigation (or when sign-in becomes required); fetchProposals/toast are stable + }, [location.pathname, signInRequired]); useEffect(() => { - if (isApiConnected) { + if (isApiConnected || signInRequired) { return; } const interval = setInterval(async () => { @@ -71,7 +80,7 @@ export function ProposalProvider({ children }: { children: ReactNode }) { return () => clearInterval(interval); // eslint-disable-next-line react-hooks/exhaustive-deps -- poll only while disconnected; fetchProposals/toast are stable - }, [isApiConnected, location.pathname]); + }, [isApiConnected, location.pathname, signInRequired]); const fetchProposals = async (silent = false): Promise<"ok" | "offline"> => { if (!silent) { @@ -220,12 +229,13 @@ export function ProposalProvider({ children }: { children: ReactNode }) { const analyzeProposal = async (id: string) => { if (!isApiConnected) { - return; + return null; } - await proposalsApi.analyze(id); + const result = await proposalsApi.analyze(id); const updatedProposal = await proposalsApi.getById(id); setProposals((prev) => prev.map((p) => (p.id === id ? updatedProposal : p))); + return result; }; return ( diff --git a/src/context/proposal-context.ts b/src/context/proposal-context.ts index 8d1b31f..cb21ffe 100644 --- a/src/context/proposal-context.ts +++ b/src/context/proposal-context.ts @@ -1,5 +1,5 @@ import { createContext } from "react"; -import type { Proposal } from "@/lib/api-client"; +import type { AnalyzeResponse, Proposal } from "@/lib/api-client"; type ProposalStatus = "PENDING" | "IN_REVIEW" | "APPROVED" | "REJECTED"; @@ -13,7 +13,8 @@ export interface ProposalContextType { proposal: Omit ) => Promise; deleteProposal: (id: string) => Promise; - analyzeProposal: (id: string) => Promise; + /** Analyze (or re-analyze) a proposal; null when the API is offline. */ + analyzeProposal: (id: string) => Promise; refreshProposals: () => Promise<"ok" | "offline">; isApiConnected: boolean; } diff --git a/src/hooks/use-session.ts b/src/hooks/use-session.ts index 827c353..bbe2e5a 100644 --- a/src/hooks/use-session.ts +++ b/src/hooks/use-session.ts @@ -1,49 +1,174 @@ -import { useEffect, useState } from 'react'; -import { authApi } from '@/lib/api-client'; -import { AuthUser, cacheSessionUser, getCurrentUser } from '@/lib/auth-utils'; +import { useEffect, useSyncExternalStore } from 'react'; +import { ApiError, authApi, type AuthConfig } from '@/lib/api-client'; +import { onAuthRequired } from '@/lib/auth-events'; +import { AuthUser, cacheSessionUser, clearAuthData, getCurrentUser } from '@/lib/auth-utils'; /** - * The acting user, as reported by /api/auth/session. + * The app's authentication state, shared by every consumer. * - * There is no login screen โ€” the API resolves a default user โ€” so this is a - * one-shot fetch shared by every consumer. It starts from the localStorage cache - * so a reload renders the right name and role before the request lands. + * Two server modes (see GET /api/auth/config): + * - demo: no sign-in. The API serves every request as a default user, so the + * session is a one-shot fetch. + * - login: a token from login/register is required. When the server answers + * 401 AUTH_REQUIRED the status becomes "login-required" and App shows + * the sign-in page. + * + * It starts from the localStorage cache so a reload renders the right name and + * role before any request lands, and never blocks rendering in demo mode. */ -let cached: AuthUser | null = null; -let inflight: Promise | null = null; -const subscribers = new Set<(user: AuthUser | null) => void>(); -function loadSession(): Promise { +/** `unavailable`: the session check could not reach the API (offline, 5xx); it is retried later. */ +export type AuthStatus = 'loading' | 'authenticated' | 'login-required' | 'unavailable'; + +export interface AuthState { + status: AuthStatus; + mode: AuthConfig['mode']; + allowRegistration: boolean; + user: AuthUser | null; +} + +const MODE_KEY = 'authMode'; + +function readCachedMode(): AuthConfig['mode'] { + try { + return localStorage.getItem(MODE_KEY) === 'login' ? 'login' : 'demo'; + } catch { + return 'demo'; + } +} + +function cacheMode(mode: AuthConfig['mode']): void { + try { + localStorage.setItem(MODE_KEY, mode); + } catch { + /* storage unavailable (private window): the mode is re-fetched on next load */ + } +} + +let state: AuthState = { + status: 'loading', + mode: readCachedMode(), + allowRegistration: false, + user: getCurrentUser(), +}; +const subscribers = new Set<() => void>(); + +function setState(patch: Partial): void { + state = { ...state, ...patch }; + subscribers.forEach((notify) => notify()); +} + +const subscribe = (notify: () => void) => { + subscribers.add(notify); + return () => { + subscribers.delete(notify); + }; +}; +const getSnapshot = () => state; + +const RETURN_TO_KEY = 'returnTo'; +const AUTH_PATHS = ['/', '/login', '/auth', '/signup']; + +/** Remember where the visitor was headed so signing in can take them back there. */ +function rememberReturnTo(): void { + try { + const { pathname, search } = window.location; + if (!AUTH_PATHS.includes(pathname)) sessionStorage.setItem(RETURN_TO_KEY, pathname + search); + } catch { + /* storage unavailable: sign-in lands on the dashboard instead */ + } +} + +/** The remembered destination (same-site paths only), else the dashboard. Clears it. */ +function takeReturnTo(): string { + try { + const target = sessionStorage.getItem(RETURN_TO_KEY); + sessionStorage.removeItem(RETURN_TO_KEY); + // Only same-site absolute paths: "//evil.example" would be an open redirect. + if (target && target.startsWith('/') && !target.startsWith('//')) return target; + } catch { + /* fall through */ + } + return '/dashboard'; +} + +// The HTTP layer saw a 401 AUTH_REQUIRED: the stored token is dead or missing. +onAuthRequired(() => { + rememberReturnTo(); + cacheMode('login'); + setState({ status: 'login-required', mode: 'login', user: null }); +}); + +let inflight: Promise | null = null; + +/** Work out the mode and who is signed in. Safe to call repeatedly. */ +export function loadSession(): Promise { if (!inflight) { - inflight = authApi - .session() - .then(({ user }) => { - cached = user as AuthUser; - cacheSessionUser(cached); - subscribers.forEach((notify) => notify(cached)); - return cached; - }) - .catch((err) => { - console.warn('Could not load session:', err); - inflight = null; // allow a later mount to retry - return null; - }); + inflight = (async () => { + try { + const config = await authApi.config(); + cacheMode(config.mode); + setState({ mode: config.mode, allowRegistration: config.allowRegistration }); + } catch { + // An older or unreachable server: assume the mode we last saw. + } + + try { + const { user } = await authApi.session(); + cacheSessionUser(user as AuthUser); + setState({ status: 'authenticated', user: user as AuthUser }); + } catch (err) { + if (err instanceof ApiError && err.status === 401) { + rememberReturnTo(); + setState({ status: 'login-required', user: null }); + } else { + console.warn('Could not load session:', err); + setState({ status: 'unavailable' }); + inflight = null; // allow a later mount to retry + } + } + })(); } return inflight; } -export function useSession(): AuthUser | null { - const [user, setUser] = useState(() => cached ?? getCurrentUser()); +/** Sign in with a password; reloads into the app so no previous user's data lingers. */ +export async function signIn(email: string, password: string): Promise { + const { token, user } = await authApi.login(email, password); + finishSignIn(token, user as AuthUser); +} + +/** Create an account (when the server allows it) and sign in. */ +export async function signUp(data: { email: string; password: string; name?: string }): Promise { + const { token, user } = await authApi.register(data); + finishSignIn(token, user as AuthUser); +} + +function finishSignIn(token: string, user: AuthUser): void { + const destination = takeReturnTo(); + clearAuthData(); + localStorage.setItem('auth_token', token); + cacheSessionUser(user); + window.location.replace(destination); +} + +/** Forget the session and return to the sign-in page. */ +export function signOut(): void { + clearAuthData(); + window.location.replace('/login'); +} +/** Full auth state plus the actions that change it. */ +export function useAuth(): AuthState { + return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); +} + +/** The signed-in user (null before the session has loaded and there is no cache). */ +export function useSession(): AuthUser | null { + const { user } = useAuth(); + // Kick off the one-shot load on first use. useEffect(() => { - subscribers.add(setUser); - loadSession().then((resolved) => { - if (resolved) setUser(resolved); - }); - return () => { - subscribers.delete(setUser); - }; + void loadSession(); }, []); - return user; } diff --git a/src/lib/api-client.ts b/src/lib/api-client.ts index c9e5496..a624a3e 100644 --- a/src/lib/api-client.ts +++ b/src/lib/api-client.ts @@ -1,3 +1,6 @@ +import { clearAuthData } from './auth-utils'; +import { emitAuthRequired } from './auth-events'; + /** Thrown for non-OK HTTP responses so callers can distinguish 401 from network failures. */ export class ApiError extends Error { constructor( @@ -115,6 +118,35 @@ const RETRY_CONFIG = { // Helper function to wait/delay const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +/** The server said a sign-in is required (login mode): drop the dead session and tell the UI. */ +function handleAuthRequired(): void { + clearAuthData(); + emitAuthRequired(); +} + +/** + * fetch() for endpoints that return something other than JSON (PDF downloads, + * file blobs) or that a page wants to inspect itself. Adds the session token, + * points at the API host, and โ€” like apiCall โ€” reacts to 401 AUTH_REQUIRED. + * `path` is an API path such as "/api/proposals/1/export/pdf". + */ +export async function authFetch(path: string, init: RequestInit = {}): Promise { + const token = localStorage.getItem('auth_token'); + const response = await fetch(`${API_BASE_URL}${path}`, { + ...init, + headers: { + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...init.headers, + }, + }); + + if (response.status === 401) { + const body = (await response.clone().json().catch(() => null)) as { code?: string } | null; + if (body?.code === 'AUTH_REQUIRED') handleAuthRequired(); + } + return response; +} + // Health check function to verify API server is reachable export async function checkApiHealth(): Promise { try { @@ -179,6 +211,9 @@ async function apiCall( error?: string; code?: string; }; + if (response.status === 401 && error.code === 'AUTH_REQUIRED') { + handleAuthRequired(); + } throw new ApiError( error.error || `API error: ${response.status}`, response.status, @@ -189,6 +224,30 @@ async function apiCall( return response.json(); } +/** 'ai' = produced by the model; 'rules' = the built-in checker (AI unavailable). */ +export type AnalysisSource = 'ai' | 'rules'; + +export interface AnalyzeResponse { + proposalId: string; + analysisSource: AnalysisSource; + statusAdvanced: boolean; + riskReport: Proposal['riskReport']; +} + +export interface BulkAnalyzeResult { + proposalId: string; + ok: boolean; + analysisSource?: AnalysisSource; + readinessScore?: number; + statusAdvanced?: boolean; + error?: string; +} + +export interface BulkAnalyzeResponse { + results: BulkAnalyzeResult[]; + summary: { requested: number; analyzed: number; failed: number }; +} + // Proposals API export const proposalsApi = { getAll: () => apiCall('/api/proposals'), @@ -219,10 +278,21 @@ export const proposalsApi = { }), analyze: (id: string) => - apiCall<{ proposalId: string; riskReport: Proposal['riskReport'] }>(`/api/analyze/${id}`, { + apiCall(`/api/analyze/${id}`, { method: 'POST', }), + // Analyze several proposals in one request (at most 10). + analyzeBulk: (ids: string[]) => + apiCall('/api/analyze/bulk', { + method: 'POST', + body: JSON.stringify({ ids }), + }), + + // Which engine a new analysis will use: the AI, or the built-in rule checker. + analysisMode: () => + apiCall<{ mode: 'ai' | 'rules'; provider: string | null; model: string | null }>('/api/analyze/mode'), + // Semantic search. `available:false` => pgvector/embeddings not set up yet; // callers should fall back to client-side substring filtering. search: (q: string) => @@ -322,12 +392,13 @@ export interface User { export const usersApi = { getAll: () => apiCall('/api/users'), getById: (id: string) => apiCall(`/api/users/${id}`), - create: (data: { email: string; name?: string; role?: User['role'] }) => + // Admin only. `password` sets an initial password (needed to sign in under login mode). + create: (data: { email: string; name?: string; role?: User['role']; password?: string; companyId?: string }) => apiCall('/api/users', { method: 'POST', body: JSON.stringify(data), }), - update: (id: string, data: Partial) => + update: (id: string, data: Partial & { password?: string }) => apiCall(`/api/users/${id}`, { method: 'PATCH', body: JSON.stringify(data), @@ -338,9 +409,31 @@ export const usersApi = { }), }; -// Session API โ€” no login screen; the server resolves the acting user. +// Auth API. In "demo" mode there is no sign-in: the server resolves a default user. +// In "login" mode a session token (from login/register) is required. +export interface AuthConfig { + mode: 'demo' | 'login'; + allowRegistration: boolean; +} + +export interface AuthResponse { + token: string; + user: User; +} + export const authApi = { + config: () => apiCall('/api/auth/config'), session: () => apiCall<{ user: User }>('/api/auth/session'), + login: (email: string, password: string) => + apiCall('/api/auth/login', { + method: 'POST', + body: JSON.stringify({ email, password }), + }), + register: (data: { email: string; password: string; name?: string }) => + apiCall('/api/auth/register', { + method: 'POST', + body: JSON.stringify(data), + }), changePassword: (currentPassword: string, newPassword: string) => apiCall<{ message: string }>('/api/auth/change-password', { method: 'POST', @@ -348,12 +441,21 @@ export const authApi = { }), }; +// OAuth: the redirect endpoints cannot carry an Authorization header, so the SPA +// first asks for a short-lived single-purpose token to put in the URL. +export const oauthApi = { + startToken: () => apiCall<{ token: string }>('/api/oauth/start-token', { method: 'POST' }), +}; + // Integrations API export interface Integration { id: string; type: 'SALESFORCE' | 'HUBSPOT' | 'GMAIL' | 'GOOGLE_DRIVE' | 'DOCUSIGN' | 'SHAREPOINT'; name: string; + /** Redacted by the server: tokens never reach the browser; non-empty only when connected. */ credentials: Record; + /** True when the integration holds stored credentials (i.e. is connected). */ + hasCredentials?: boolean; config: Record; isActive: boolean; lastSyncAt: string | null; @@ -365,7 +467,7 @@ export interface SyncLog { id: string; integrationId: string; action: 'IMPORT' | 'EXPORT' | 'SYNC'; - status: 'SUCCESS' | 'FAILED' | 'PARTIAL'; + status: 'SUCCESS' | 'FAILURE' | 'FAILED' | 'PARTIAL'; recordsAffected: number; details: Record; createdAt: string; @@ -408,12 +510,14 @@ export const filesApi = { method: 'POST', body: JSON.stringify({ file, fileName }), }), - download: (path: string) => - fetch(`${API_BASE_URL}/api/files/download/${path}`).then(res => res.blob()), - delete: (path: string) => - apiCall<{ success: boolean; message: string }>(`/api/files/${path}`, { - method: 'DELETE', - }), + // `filePath` is the value returned by upload (e.g. "proposals//_"). + download: (filePath: string) => + authFetch(`/api/files/download/${filePath.split('/').map(encodeURIComponent).join('/')}`).then(res => res.blob()), + delete: (filePath: string) => + apiCall<{ success: boolean; message: string }>( + `/api/files/delete/${filePath.split('/').map(encodeURIComponent).join('/')}`, + { method: 'DELETE' } + ), }; // Health check diff --git a/src/lib/auth-events.ts b/src/lib/auth-events.ts new file mode 100644 index 0000000..d7ed921 --- /dev/null +++ b/src/lib/auth-events.ts @@ -0,0 +1,20 @@ +/** + * A tiny pub/sub so the HTTP layer can tell the session store that the server + * demanded a sign-in (401 AUTH_REQUIRED), without api-client importing React code. + */ + +type Listener = () => void; + +const listeners = new Set(); + +/** Subscribe to "sign-in required". Returns an unsubscribe function. */ +export function onAuthRequired(listener: Listener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function emitAuthRequired(): void { + listeners.forEach((listener) => listener()); +} diff --git a/src/pages/Compliance.tsx b/src/pages/Compliance.tsx index 55709cb..c375280 100644 --- a/src/pages/Compliance.tsx +++ b/src/pages/Compliance.tsx @@ -68,23 +68,20 @@ function getRuleTypeBadgeColor(type: string): string { /** Human-readable summary of rule logic for the card. */ function formatRuleLogic(rule: Rule): string { - const logic = rule.logic ?? {}; - if (rule.type === "DISCOUNT" && typeof (logic as any).maxDiscount === "number") { - return `Max discount: ${(logic as any).maxDiscount}%`; + const logic: Record = rule.logic ?? {}; + const { maxDiscount, minDealSize, approvalThreshold, maxPaymentDays, requiredTerms, requiredSections } = logic; + if (rule.type === "DISCOUNT" && typeof maxDiscount === "number") { + return `Max discount: ${maxDiscount}%`; } if (rule.type === "PRICING") { - const min = (logic as any).minDealSize; - const threshold = (logic as any).approvalThreshold; - if (typeof min === "number") return `Min deal size: $${min.toLocaleString()}`; - if (typeof threshold === "number") return `Approval threshold: $${threshold.toLocaleString()}`; + if (typeof minDealSize === "number") return `Min deal size: $${minDealSize.toLocaleString()}`; + if (typeof approvalThreshold === "number") return `Approval threshold: $${approvalThreshold.toLocaleString()}`; } - if (rule.type === "PAYMENT" && typeof (logic as any).maxPaymentDays === "number") { - return `Max payment terms: ${(logic as any).maxPaymentDays} days`; + if (rule.type === "PAYMENT" && typeof maxPaymentDays === "number") { + return `Max payment terms: ${maxPaymentDays} days`; } - const terms = (logic as any).requiredTerms; - const sections = (logic as any).requiredSections; - if (Array.isArray(terms) && terms.length) return `Required: ${terms.join(", ")}`; - if (Array.isArray(sections) && sections.length) return `Sections: ${sections.join(", ")}`; + if (Array.isArray(requiredTerms) && requiredTerms.length) return `Required: ${requiredTerms.join(", ")}`; + if (Array.isArray(requiredSections) && requiredSections.length) return `Sections: ${requiredSections.join(", ")}`; return JSON.stringify(logic); } diff --git a/src/pages/Integrations.tsx b/src/pages/Integrations.tsx index 25c4b55..3e7e926 100644 --- a/src/pages/Integrations.tsx +++ b/src/pages/Integrations.tsx @@ -6,7 +6,7 @@ import { mockIntegrations } from "@/data/mockData"; import { Integration } from "@/types"; import { useToast } from "@/hooks/use-toast"; import { useProposals } from "@/context/useProposals"; -import { getApiBaseUrl } from "@/lib/api-client"; +import { authFetch, getApiBaseUrl, oauthApi } from "@/lib/api-client"; import { formatDistanceToNowIST } from "@/lib/utils"; const integrationConfig = { @@ -30,6 +30,13 @@ const integrationConfig = { }, }; +/** An integration as returned by GET /api/integrations (credentials are redacted). */ +type ApiIntegration = Omit & { + credentials?: Record | null; + config?: Record | null; + hasCredentials?: boolean; +}; + // Load integration status from localStorage const loadIntegrationStatus = (): Record => { const stored = localStorage.getItem('integrationStatus'); @@ -59,17 +66,15 @@ export default function Integrations() { // Fetch integrations from API const fetchIntegrations = async () => { try { - const base = getApiBaseUrl(); - const token = localStorage.getItem('auth_token'); - const res = await fetch(`${base}/api/integrations`, { - headers: token ? { Authorization: `Bearer ${token}` } : {}, - }); + const res = await authFetch('/api/integrations'); if (!res.ok) throw new Error('Failed to load integrations'); - const data = await res.json(); + const data = (await res.json()) as ApiIntegration[]; - // Map DB records to UI shape - use database as source of truth - const dbIntegrations = data.map((d: any) => { - const hasCredentials = d.credentials && typeof d.credentials === 'object' && Object.keys(d.credentials).length > 0; + // Map DB records to UI shape - use database as source of truth. The server + // never sends the stored OAuth tokens, only whether credentials exist. + const dbIntegrations = data.map((d) => { + const hasCredentials = + d.hasCredentials ?? (!!d.credentials && typeof d.credentials === 'object' && Object.keys(d.credentials).length > 0); const isActive = d.isActive && hasCredentials; return { @@ -153,11 +158,17 @@ export default function Integrations() { ? 'Authorization was cancelled or no code was returned.' : error === 'token_exchange_failed' ? 'Could not get access token. Check redirect URI and app credentials.' - : error === 'hubspot_save_failed' + : error === 'hubspot_save_failed' || error === 'integration_save_failed' ? 'Connected but failed to save. Try again or check the Integration table has required columns.' : error === 'no_client_id' ? 'HubSpot client ID is not configured.' - : `Error: ${error}`; + : error === 'invalid_state' + ? 'The sign-in link expired or was tampered with. Please start the connection again.' + : error === 'unauthorized' || error === 'not_authenticated' + ? 'Your session expired. Please sign in and try again.' + : error === 'forbidden' + ? 'Only administrators can connect this integration.' + : `Error: ${error}`; toast({ title: "Connection failed", description: message, @@ -200,13 +211,24 @@ export default function Integrations() { const base = getApiBaseUrl(); const url = oauthUrls[integration.type]; - if (url) { - // Top-level navigation, so no Authorization header โ€” the server resolves - // the acting user itself now that there is no sign-in step. - window.location.href = `${base}${url}`; - } else { + if (!url) { setConnecting(null); + return; + } + + // The redirect is a top-level navigation, which cannot carry an Authorization + // header. Ask the API (which can verify our session) for a two-minute, + // single-purpose token to put in the URL instead of the session token itself. + // Servers without sign-in (demo mode) resolve the user themselves, so if the + // request fails for any other reason we still proceed. + let query = ''; + try { + const { token } = await oauthApi.startToken(); + query = `?token=${encodeURIComponent(token)}`; + } catch (err) { + console.warn('Could not get an OAuth start token:', err); } + window.location.href = `${base}${url}${query}`; }; const handleDisconnect = (integration: Integration) => { @@ -221,14 +243,9 @@ export default function Integrations() { // Update server-side Integration record (async () => { try { - const base = getApiBaseUrl(); - const token = localStorage.getItem('auth_token'); - const res = await fetch(`${base}/api/integrations/${integration.id}`, { + const res = await authFetch(`/api/integrations/${integration.id}`, { method: 'PATCH', - headers: { - 'Content-Type': 'application/json', - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isActive: false, credentials: {} }), }); if (!res.ok) throw new Error('Failed to disconnect'); @@ -249,43 +266,27 @@ export default function Integrations() { setSyncing(integration.id); try { - const base = getApiBaseUrl(); - const token = localStorage.getItem('auth_token'); - const res = await fetch(`${base}/api/integrations/${integration.id}/sync`, { - method: 'POST', - headers: token ? { Authorization: `Bearer ${token}` } : {}, - }); - + const res = await authFetch(`/api/integrations/${integration.id}/sync`, { method: 'POST' }); + const result = await res.json(); - + if (!res.ok) { - // If sync failed due to missing credentials, mark integration as inactive - if (result.error?.includes('No access token') || result.error?.includes('expired') || result.error?.includes('revoked')) { + // The server switches a revoked/expired connection off itself and says so + // with needsReconnect; mirror that in the UI so the card offers "Connect". + if (result.needsReconnect) { setIntegrations(integrations.map((i) => i.id === integration.id ? { ...i, isActive: false, lastSyncAt: null } : i )); - - // Update localStorage + const status = loadIntegrationStatus(); status[integration.type] = false; saveIntegrationStatus(status); - - // Update database - try { - await fetch(`${base}/api/integrations/${integration.id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ isActive: false }), - }); - } catch (updateErr) { - console.error('Failed to update integration status:', updateErr); - } - + toast({ title: "Sync failed - Reconnection required", - description: result.error || "Please reconnect Gmail in Integrations.", + description: result.error || `Please reconnect ${integration.name} in Integrations.`, variant: "destructive", }); return; diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx new file mode 100644 index 0000000..76a1710 --- /dev/null +++ b/src/pages/Login.tsx @@ -0,0 +1,139 @@ +import { FormEvent, useState } from "react"; +import { motion } from "framer-motion"; +import { Loader2, LogIn, Sparkles, UserPlus } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { useAuth, signIn, signUp } from "@/hooks/use-session"; + +/** + * Sign-in page, shown only when the server runs in login mode + * (GET /api/auth/config โ†’ mode "login") and there is no valid session. + */ +export default function Login() { + const { allowRegistration } = useAuth(); + const [creating, setCreating] = useState(false); + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault(); + setError(null); + + if (creating && password.length < 8) { + setError("Password must be at least 8 characters long."); + return; + } + + setSubmitting(true); + try { + if (creating) { + await signUp({ email, password, name: name.trim() || undefined }); + } else { + await signIn(email, password); + } + // signIn/signUp reload into the app on success. + } catch (err) { + setError(err instanceof Error && err.message ? err.message : "Could not sign in. Please try again."); + setSubmitting(false); + } + }; + + return ( +
    + +
    +
    + +
    +
    +

    DealSentry

    +

    {creating ? "Create your account" : "Sign in to continue"}

    +
    +
    + +
    + {creating && ( +
    + + setName(e.target.value)} + placeholder="Your name" + /> +
    + )} + +
    + + setEmail(e.target.value)} + placeholder="you@company.com" + /> +
    + +
    + + setPassword(e.target.value)} + /> +
    + + {error && ( +

    + {error} +

    + )} + + +
    + + {allowRegistration && ( +

    + {creating ? "Already have an account?" : "New here?"}{" "} + +

    + )} +
    +
    + ); +} diff --git a/src/pages/ProposalReview.tsx b/src/pages/ProposalReview.tsx index 7664012..e8ebf19 100644 --- a/src/pages/ProposalReview.tsx +++ b/src/pages/ProposalReview.tsx @@ -13,6 +13,8 @@ import { DollarSign, Percent, Calendar, + Loader2, + RefreshCw, TrendingUp, Trash2 } from "lucide-react"; @@ -30,7 +32,7 @@ import { } from "@/components/ui/alert-dialog"; import { StatusBadge } from "@/components/ui/StatusBadge"; import { RiskBar } from "@/components/ui/RiskBar"; -import { getApiBaseUrl } from "@/lib/api-client"; +import { authFetch } from "@/lib/api-client"; import { useProposals } from "@/context/useProposals"; import { useToast } from "@/hooks/use-toast"; import { formatIST } from "@/lib/utils"; @@ -47,8 +49,9 @@ export default function ProposalReview() { const { id } = useParams(); const navigate = useNavigate(); const { toast } = useToast(); - const { getProposal, updateProposalStatus, deleteProposal } = useProposals(); + const { getProposal, updateProposalStatus, deleteProposal, analyzeProposal } = useProposals(); const [isDeleting, setIsDeleting] = useState(false); + const [isAnalyzing, setIsAnalyzing] = useState(false); const proposal = getProposal(id || ""); @@ -116,20 +119,43 @@ export default function ProposalReview() { }); }; + const handleAnalyze = async () => { + setIsAnalyzing(true); + try { + const result = await analyzeProposal(proposal.id); + if (!result) { + toast({ + title: "Analysis unavailable", + description: "The API is offline. Try again once it reconnects.", + variant: "destructive", + }); + return; + } + toast({ + title: "Analysis complete", + description: + result.analysisSource === "rules" + ? "The AI was unavailable, so the built-in rule checker produced this report." + : result.statusAdvanced + ? "Report updated. The proposal looks healthy and moved to In Review." + : "Report updated.", + }); + } catch (error) { + toast({ + title: "Analysis failed", + description: error instanceof Error ? error.message : "Could not analyze this proposal", + variant: "destructive", + }); + } finally { + setIsAnalyzing(false); + } + }; + const handleExportPdf = async () => { try { - const base = getApiBaseUrl(); - const url = `${base}/api/proposals/${proposal.id}/export/pdf`; - const token = localStorage.getItem('auth_token'); - toast({ title: 'Exporting PDF', description: 'Generating your PDF...' }); - const response = await fetch(url, { - method: 'GET', - headers: { - ...(token ? { 'Authorization': `Bearer ${token}` } : {}), - }, - }); + const response = await authFetch(`/api/proposals/${proposal.id}/export/pdf`); if (!response.ok) { const error = await response.json().catch(() => ({ error: 'Failed to export PDF' })); @@ -416,6 +442,20 @@ export default function ProposalReview() { })()}
    + + <> + + + )}
    )} diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 95a7f4d..1b20ac6 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -62,10 +62,10 @@ export default function Settings() { setCurrentPassword(""); setNewPassword(""); setConfirmPassword(""); - } catch (error: any) { + } catch (error) { toast({ title: "Failed to change password", - description: error?.message || "Please check your current password and try again", + description: error instanceof Error && error.message ? error.message : "Please check your current password and try again", variant: "destructive", }); } finally { diff --git a/src/types/index.ts b/src/types/index.ts index 860e27c..5620764 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -53,7 +53,7 @@ export interface Rule { name: string; type: RuleType; description?: string; - logic: Record; + logic: Record; isActive: boolean; createdAt: string; updatedAt: string; @@ -85,7 +85,7 @@ export interface AuditLog { proposal?: { title: string; } | null; - metadata?: Record; + metadata?: Record; } export type TemplateType = "SALES_PROPOSAL" | "MSA" | "SOW" | "NDA" | "OTHER"; From 1568433e90139917e552b3d02defb61cfe086c6e Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:25 +0530 Subject: [PATCH 09/11] feat(db): row-level security migration with a pre-flight check 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. --- prisma/manual/enable_rls.sql | 51 +++++++++++++++++++ scripts/check-rls.ts | 99 ++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 prisma/manual/enable_rls.sql create mode 100644 scripts/check-rls.ts diff --git a/prisma/manual/enable_rls.sql b/prisma/manual/enable_rls.sql new file mode 100644 index 0000000..4f5e1ef --- /dev/null +++ b/prisma/manual/enable_rls.sql @@ -0,0 +1,51 @@ +-- Lock the database down with Row Level Security. +-- +-- WHY: Supabase exposes every table in the `public` schema over a REST API that +-- anyone holding the project's anon key can call. With RLS off, that key alone +-- can read the whole "User" table (password hashes) and "Integration" table (CRM +-- OAuth tokens) and write to any table. The anon key is designed to be public, so +-- it must not be what protects the data. +-- +-- HOW IT WORKS: enabling RLS with NO policies denies the `anon` and +-- `authenticated` roles everything. The API is unaffected only because it talks to +-- Supabase with the SERVICE-ROLE key, which bypasses RLS. +-- +-- !! BEFORE YOU RUN THIS !! +-- 1. Supabase Dashboard โ†’ Project Settings โ†’ API โ†’ copy the `service_role` key. +-- 2. Set it as SUPABASE_SERVICE_ROLE_KEY in your local .env AND in the Render +-- dashboard (Environment). Server-side only โ€” never in a VITE_ variable. +-- 3. Redeploy / restart the API so it picks the key up. +-- 4. npm run check:rls (must print "ready") +-- If you skip this, the API loses access to its own database the moment this runs. +-- +-- RUN: npx prisma db execute --file prisma/manual/enable_rls.sql +-- THEN: npm run check:rls -- --verify (confirms the anon key is now locked out) +-- +-- Idempotent / safe to re-run. To undo, `alter table "" disable row level security;` + +alter table "User" enable row level security; +alter table "Proposal" enable row level security; +alter table "RiskReport" enable row level security; +alter table "AuditLog" enable row level security; +alter table "Rule" enable row level security; +alter table "LegalClause" enable row level security; +alter table "Template" enable row level security; +alter table "Integration" enable row level security; +alter table "SyncLog" enable row level security; + +-- Semantic search RPC: only the API (service role) may call it. +do $$ +begin + if exists (select 1 from pg_proc where proname = 'match_proposals') then + revoke execute on function match_proposals(vector, integer, text) from public, anon, authenticated; + grant execute on function match_proposals(vector, integer, text) to service_role; + end if; +end $$; + +-- Storage: the API now reaches the bucket with the service role too, so the anon +-- read/insert/delete policies from storage_bucket.sql are no longer needed, and +-- the bucket no longer has to be public (uploads return signed links). +drop policy if exists "proposal-files anon read" on storage.objects; +drop policy if exists "proposal-files anon insert" on storage.objects; +drop policy if exists "proposal-files anon delete" on storage.objects; +update storage.buckets set public = false where id = 'proposal-files'; diff --git a/scripts/check-rls.ts b/scripts/check-rls.ts new file mode 100644 index 0000000..7f898d7 --- /dev/null +++ b/scripts/check-rls.ts @@ -0,0 +1,99 @@ +/** + * Safety check around enabling Row Level Security (prisma/manual/enable_rls.sql). + * + * npm run check:rls # BEFORE enabling RLS: is the API's service-role key good? + * npm run check:rls -- --verify # AFTER enabling RLS: is the public anon key now locked out? + * + * Enabling RLS with a missing or wrong service-role key would cut the API off from + * its own database, so run the first form and only proceed if it prints "ready". + * Keys are never printed. + */ + +import 'dotenv/config'; +import { createClient } from '@supabase/supabase-js'; + +const verifyMode = process.argv.includes('--verify'); + +const url = process.env.SUPABASE_URL ?? ''; +const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY ?? ''; +const anonKey = process.env.SUPABASE_ANON_KEY ?? ''; + +let failures = 0; +const pass = (msg: string) => console.log(` ok ${msg}`); +const fail = (msg: string) => { + failures++; + console.log(` FAIL ${msg}`); +}; + +/** The unverified claims of a Supabase API key (a JWT): enough to tell anon from service_role. */ +function claimsOf(key: string): { role?: string; ref?: string } | null { + try { + return JSON.parse(Buffer.from(key.split('.')[1], 'base64url').toString('utf8')); + } catch { + return null; + } +} + +const projectRef = (() => { + try { + return new URL(url).hostname.split('.')[0]; + } catch { + return ''; + } +})(); + +async function main() { + console.log(verifyMode ? 'Verifying RLS is enforced...' : 'Checking the service-role key is ready...'); + + if (!url) fail('SUPABASE_URL is not set'); + + // --- the service-role key (used by the API) --------------------------------- + if (!serviceKey) { + fail('SUPABASE_SERVICE_ROLE_KEY is not set (get it from Supabase โ†’ Project Settings โ†’ API)'); + } else { + const claims = claimsOf(serviceKey); + if (!claims) fail('SUPABASE_SERVICE_ROLE_KEY is not a valid Supabase key (expected a JWT)'); + else if (claims.role !== 'service_role') fail(`SUPABASE_SERVICE_ROLE_KEY has role "${claims.role}", expected "service_role" (did you paste the anon key?)`); + else if (projectRef && claims.ref && claims.ref !== projectRef) fail('SUPABASE_SERVICE_ROLE_KEY belongs to a different project than SUPABASE_URL'); + else pass('service-role key is well-formed and matches this project'); + + if (url) { + const admin = createClient(url, serviceKey, { auth: { persistSession: false } }); + const { error } = await admin.from('User').select('id', { count: 'exact', head: true }); + if (error) fail(`the service-role key could not read the User table: ${error.message}`); + else pass('the service-role key can read the database'); + } + } + + // --- the anon key (public by design) --------------------------------------- + if (verifyMode) { + if (!anonKey) { + fail('SUPABASE_ANON_KEY is not set, so the lock-out cannot be tested'); + } else if (url) { + // Read-only probes (a write probe would insert a real row if RLS were off). + // With RLS on and no policies, a read returns no rows rather than an error. + const anon = createClient(url, anonKey, { auth: { persistSession: false } }); + for (const table of ['User', 'Integration', 'Proposal']) { + const { data, error } = await anon.from(table).select('id').limit(1); + if (!error && data && data.length > 0) fail(`the anon key can STILL read the ${table} table โ€” RLS is not enabled`); + else pass(`the anon key cannot read the ${table} table`); + } + } + } + + console.log(); + if (failures > 0) { + console.log(verifyMode ? 'NOT locked down.' : 'NOT ready โ€” do not run enable_rls.sql yet.'); + process.exit(1); + } + console.log( + verifyMode + ? 'Locked down: only the API (service role) can reach the data.' + : 'ready โ€” set the same key on Render, redeploy, then run prisma/manual/enable_rls.sql.' + ); +} + +main().catch((err) => { + console.error('Check failed:', err instanceof Error ? err.message : err); + process.exit(1); +}); From 4d56ee991c83e2fd534d40d67a1b7bf6ba45db9f Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:27 +0530 Subject: [PATCH 10/11] chore(lint): forbid explicit any 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. --- eslint.config.mjs | 4 ++-- scripts/migrate-integrations.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 70d8592..d763b21 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -25,8 +25,8 @@ export default tseslint.config( "warn", { allowConstantExport: true }, ], - // The API/JSON boundaries intentionally use `any`; keep it advisory. - "@typescript-eslint/no-explicit-any": "off", + // Use `unknown` and narrow (or a real interface) at API/JSON boundaries. + "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-unused-vars": [ "warn", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }, diff --git a/scripts/migrate-integrations.ts b/scripts/migrate-integrations.ts index 5d759aa..2427872 100644 --- a/scripts/migrate-integrations.ts +++ b/scripts/migrate-integrations.ts @@ -83,7 +83,7 @@ async function runMigration() { console.log(`\nTotal integrations: ${allIntegrations.length}\n`); // Group by user - const byUser: { [key: string]: any[] } = {}; + const byUser: Record = {}; allIntegrations.forEach(int => { const userId = int.userId || 'unassigned'; if (!byUser[userId]) byUser[userId] = []; From 893a8008536248c9f36c4052d217720835daad06 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Tue, 13 Oct 2026 13:19:29 +0530 Subject: [PATCH 11/11] docs: document AI providers, auth modes, RLS and the new architecture - 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") --- .env.example | 46 ++- ARCHITECTURE.md | 144 ++++--- BUG_REPORT.md | 273 -------------- README.md | 54 ++- SETUP.md | 803 ++++++++++++++++++++-------------------- docs/AUTH_QUICKSTART.md | 357 ++++-------------- docs/DEMO_SCRIPT.md | 12 +- docs/DEPLOYMENT.md | 59 ++- docs/SEMANTIC_SEARCH.md | 58 ++- render.yaml | 14 +- start.bat | 186 +++++----- 11 files changed, 871 insertions(+), 1135 deletions(-) delete mode 100644 BUG_REPORT.md diff --git a/.env.example b/.env.example index 202c25a..426f40b 100644 --- a/.env.example +++ b/.env.example @@ -20,18 +20,27 @@ SUPABASE_ANON_KEY="your-supabase-anon-key-here" # Server-side only โ€” never ship it to the browser. # SUPABASE_SERVICE_ROLE_KEY="your-supabase-service-role-key" -# Azure OpenAI Configuration (for AI-powered features) -# Required for proposal analysis and AI generation -AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" -OPENAI_API_KEY="your-azure-openai-api-key-here" -AZURE_OPENAI_DEPLOYMENT="gpt-4o" -AZURE_OPENAI_API_VERSION="2024-12-01-preview" -# Alternative: Google Gemini for analysis/generation. When GEMINI_API_KEY is set it -# takes precedence over the Azure settings above (embeddings still use Azure). +# AI provider โ€” set ONE of the two blocks below (Gemini wins if both are set). +# With neither, proposal analysis still works (built-in rule checker); proposal +# generation and semantic search need a provider. +# +# Option A: Google Gemini โ€” chat, analysis and embeddings. # GEMINI_API_KEY="your-gemini-api-key" # GEMINI_MODEL="gemini-2.5-flash" +# GEMINI_EMBEDDING_MODEL="gemini-embedding-001" +# +# Option B: Azure OpenAI +# (Left commented out on purpose: a placeholder endpoint would make every +# analysis wait for a failing network call before falling back.) +# AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" +# OPENAI_API_KEY="your-azure-openai-api-key-here" +# AZURE_OPENAI_DEPLOYMENT="gpt-4o" +# AZURE_OPENAI_API_VERSION="2024-12-01-preview" # Embedding deployment โ€” required only for semantic search (Phase 4) -AZURE_OPENAI_EMBEDDING_DEPLOYMENT="text-embedding-ada-002" +# AZURE_OPENAI_EMBEDDING_DEPLOYMENT="text-embedding-ada-002" + +# Force the built-in rule checker for analysis even when an AI is configured. +# ANALYSIS_MODE="rules" # Email Notifications (Optional) # Sending is OFF unless EMAIL_ENABLED="true" AND a provider key is set. @@ -43,13 +52,26 @@ EMAIL_FROM="DealSentry " # Authentication # Secret key for JWT token signing - CHANGE THIS IN PRODUCTION! +# Generate one: node -e "console.log(require('crypto').randomBytes(48).toString('base64'))" NEXTAUTH_SECRET="change-this-to-a-random-secure-string-in-production" -# There is no sign-in screen: every request is served as one default user. -# Optional - pick that user by email. Falls back to the first ADMIN, then to the -# first row in the User table. +# AUTH_MODE selects how people get in (see docs/AUTH_QUICKSTART.md): +# demo (default) - no sign-in screen: every request is served as one default user. +# login - real accounts: email + password, per-company data isolation. +# Requires a real NEXTAUTH_SECRET (the server refuses to start otherwise), +# prisma/manual/multi_user.sql, and `npm run set-passwords`. +# AUTH_MODE="demo" +# Let people create their own account on the sign-in page (login mode only). +# ALLOW_SELF_REGISTRATION="false" + +# Demo mode only. Pick the default user by email. Falls back to the first ADMIN, +# then to the first row in the User table. # DEMO_USER_EMAIL="admin@dealsentry.ai" +# Number of reverse-proxy hops to trust for the client IP (rate limiting). +# Default: 1 in production (right for Render), off otherwise. +# TRUST_PROXY="1" + # API Configuration # Port for the Express API server API_PORT=3001 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a4c5e26..969d66c 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -9,12 +9,13 @@ including the trade-offs that were made deliberately. ```mermaid flowchart LR subgraph Browser - SPA["React 18 SPA
    (Vite, Tailwind, shadcn/ui,
    TanStack Query)"] + SPA["React 18 SPA
    (Vite, Tailwind, shadcn/ui,
    TanStack Query,
    lazy-loaded routes)"] end subgraph "Express API (Node 20, tsx)" API["REST routers
    /api/proposals /rules /analyze
    /files /integrations /oauth ..."] - MW["Middleware
    helmet ยท CORS allowlist ยท
    rate limits ยท session resolver"] + MW["Middleware
    helmet ยท CORS allowlist ยท
    rate limits ยท session resolver
    (demo or login mode)"] + SVC["Services (src/api/lib)
    analysis ยท rule checker ยท
    CRM sync connectors"] PDF["PDF export
    (Puppeteer / headless Chrome)"] end @@ -24,20 +25,20 @@ flowchart LR STORE["Storage
    (proposal-files bucket)"] end - subgraph Azure["Azure OpenAI"] - GPT["gpt-4o
    (analysis + generation)"] - EMB["text-embedding-ada-002
    (semantic search)"] + subgraph LLM["LLM provider (one of)"] + GEM["Google Gemini
    gemini-2.5-flash ยท
    gemini-embedding-001"] + AZ["Azure OpenAI
    gpt-4o ยท ada-002"] end CRM["Salesforce ยท HubSpot ยท Gmail
    (OAuth 2.0, demo mode available)"] - SPA -- "/api/* (same-origin,
    Vite proxy in dev)" --> MW --> API - API -- "supabase-js (REST)" --> REST --> PG - API --> STORE - API --> GPT - API --> EMB - API <--> CRM - PDF --> API + SPA -- "/api/* (same-origin,
    Vite proxy in dev)" --> MW --> API --> SVC + SVC -- "supabase-js (REST)" --> REST --> PG + SVC --> STORE + SVC -. "analysis ยท generation ยท
    embeddings" .-> GEM + SVC -. "or" .-> AZ + SVC <--> CRM + API --> PDF ``` ## Key design decisions @@ -56,67 +57,120 @@ The trade-off: no compile-time query types at runtime (PostgREST returns untyped JSON). That's the price of running well on a free tier; the routers type their own row interfaces at the boundary instead. -### 2. Demo-first authentication - -There is deliberately **no login screen**: every request is served as a default -user (`DEMO_USER_EMAIL`, falling back to the first ADMIN). The full JWT + -bcrypt stack still exists (`/api/auth/login`, `/register`, -`/change-password`) and valid bearer tokens win over the default identity, so -real multi-user auth can be re-enabled by rendering the login page again. - -### 3. AI with guardrails, not AI instead of rules - -`/api/analyze` sends the proposal *content* (source of truth) plus the active -compliance rules to gpt-4o and asks for structured findings. Hard limits -(max 25% discount, 90-day payment terms, mandatory legal clauses, $10k minimum -deal) are enforced twice: stated in the prompt *and* re-checked/capped in -code after generation (`/api/proposals/generate` clamps the discount range). -Results are normalized (`normalizeAnalysis`) before they become a RiskReport. +### 2. Two authentication modes + +`AUTH_MODE` (read on every request, see `src/api/lib/authConfig.ts`) selects: + +- **`demo`** (default) โ€” deliberately **no login screen**: every request is served + as a default user (`DEMO_USER_EMAIL`, falling back to the first ADMIN). A valid + bearer token still wins over the default identity. +- **`login`** โ€” real multi-user mode. No default identity: a request without a valid + token gets `401 AUTH_REQUIRED` and the SPA shows a sign-in page. Data is isolated + per company, and users with no company only see what they own + (`canAccessResource` / `listScope` in `middleware/auth.ts`). The server refuses to + start in this mode without a real `NEXTAUTH_SECRET`. + +Both modes share the same routes and middleware; the mode only changes how a +request's user is resolved and how strictly rows are scoped. Details and the +hardening around OAuth redirects: `docs/AUTH_QUICKSTART.md`. + +### 3. AI with guardrails, and a fallback when the AI is gone + +`/api/analyze` (`src/api/lib/analysisService.ts`) sends the proposal *content* +(source of truth) plus the active compliance rules to the configured model and +asks for structured findings. Hard limits (max 25% discount, 90-day payment +terms, mandatory legal clauses, $10k minimum deal) are stated in the prompt, and +`/api/proposals/generate` additionally re-validates and clamps what the model +returns (`proposalGeneration.ts`). Results are normalized (`normalizeAnalysis`) +before they become a RiskReport. + +When the model is unconfigured, unreachable, times out, or returns unparseable +JSON, analysis does **not** fail: `ruleAnalysis.ts` answers the same questions +deterministically (it extracts the discount, deal value and payment term from the +text, checks for the required clauses and sections, and applies the thresholds from +the active `Rule` rows). The report carries an `ANALYSIS MODE` finding and the API +returns `analysisSource: "ai" | "rules"`, so the UI and reviewers can tell which +engine produced it. `ANALYSIS_MODE=rules` forces it. + +The provider is chosen by `src/api/lib/llm.ts`: Gemini (through its +OpenAI-compatible endpoint) if `GEMINI_API_KEY` is set, else Azure OpenAI, else +none โ€” resolved lazily so the server boots with no AI configured. ### 4. Semantic search via pgvector Every proposal gets a 1536-dim embedding on create (best-effort โ€” failures never block the write). Search calls the `match_proposals` SQL function -(cosine distance, ivfflat index). If the extension/function is missing the API +(cosine distance, HNSW index). If the extension/function is missing the API answers `available: false` and the client falls back to substring search โ€” the feature degrades, it doesn't break. -Setup lives in `prisma/manual/semantic_search.sql`; backfill with -`npm run backfill:embeddings`. +Vectors from different models are not comparable, so every instance sharing a +database must use the same embedding model; after changing it, re-embed with +`npm run backfill:embeddings -- --all`. Setup: `prisma/manual/semantic_search.sql`, +`docs/SEMANTIC_SEARCH.md`. ### 5. Integrations with a real demo mode Salesforce/HubSpot/Gmail connect over standard OAuth 2.0. With `*_DEMO_MODE=true`, connect stores `{demo: true}` credentials and **sync imports canned deals as proposals**, so the connect โ†’ sync โ†’ analyze โ†’ approve -story is demonstrable without any external accounts. Real-mode sync handles -token refresh and dedupes on the CRM record id. +story is demonstrable without any external accounts. + +Each CRM is its own connector under `src/api/lib/sync/` (`hubspot.ts`, +`gmail.ts`, `salesforce.ts`, `demo.ts`) behind one `runSync` dispatcher. They +refresh expired tokens, de-duplicate on the CRM record id *per user*, attach the +integration owner's user and company to everything they import, and time out +rather than hang. A failed sync is reported as `424` with the reason (and +`needsReconnect` when the connection is revoked), never as a silent `200`. + +OAuth tokens never leave the server: integration responses carry a `hasCredentials` +flag instead. The `state` parameter is a signed, expiring token, and the SPA starts +the redirect with a 2-minute single-purpose token rather than its session token. +The Salesforce instance URL is validated against Salesforce's domains before any +request is made (it lives in user-editable credentials, so it is an SSRF vector). ### 6. Deployment (Render, Docker) One container serves both the API and the built SPA (Express serves `dist/` in production, so CORS is a non-issue for same-origin traffic). The runtime image installs system Chromium for PDF export (`PUPPETEER_EXECUTABLE_PATH`), because -the free tier's 512 MB can't afford Puppeteer's bundled download at build time. +the free tier's 512 MB can't afford Puppeteer's bundled download at build time; +exports run one at a time and always close the browser. The server trusts one +proxy hop in production (`TRUST_PROXY`) so per-IP rate limits see real visitors. `render.yaml` is a full Blueprint โ€” secrets are dashboard-only (`sync: false`). +### 7. Frontend delivery + +Every page is a lazy route (`React.lazy` in `App.tsx`), and `vite.config.ts` groups +React, the router, Radix, animation and chart libraries into separate vendor +chunks โ€” so the first load carries the shell and the chart library is fetched only +by the pages that draw charts. + ## Security model (current state and roadmap) | Area | Today | Next step | | --- | --- | --- | -| API auth | Default-user demo mode; JWT honored when present | Re-enable login UI for multi-user | -| DB access | Server-side key via supabase-js; anon key works, service-role preferred when set | Enable RLS per table; drop anon write policies | -| Secrets | `.env` git-ignored; Render dashboard for prod | Rotate any key that was ever committed | -| Responses | Password hashes stripped from every user payload; mutations admin-gated | Field-level DTOs | +| API auth | `demo` (default) or `login` mode with email + password, signed 7-day tokens, per-company isolation | Password reset, email verification, 2FA, server-side token revocation | +| DB access | Server-side key via supabase-js; the service-role key is preferred when set | **Enable RLS** โ€” `prisma/manual/enable_rls.sql`, guarded by `npm run check:rls`. Until then the anon key can read every table | +| Secrets | `.env` git-ignored; Render dashboard for prod; OAuth tokens never sent to the browser | Rotate any key that was ever committed (`CREDENTIALS.md` is in git history) | +| Responses | Password hashes stripped everywhere; mutations admin-gated; production errors are generic | Field-level DTOs | +| Files | Per-user folders, type allow-list, size cap, signed links; traversal rejected | Virus scanning if untrusted users upload | +| Dependencies | `npm audit fix` applied; 0 critical | Major upgrades listed in `docs/DEPLOYMENT.md` ยง7 | ## Repository map ``` -server.ts Express bootstrap, static SPA serving, error handling -src/api/ One router per resource + middleware/ + lib/ -src/lib/ API client (frontend), supabase client (backend), utils -src/pages/ components/ React SPA -prisma/ schema.prisma, seed.ts, manual/*.sql (pgvector, storage) -scripts/ backfill-embeddings, cleanup-integrations, migrate-auth -tests/ Vitest + Supertest API tests +server.ts Process bootstrap: env, startup checks, listen, graceful shutdown +src/api/app.ts createApp(): middleware, routes, SPA serving, error handler (testable) +src/api/*.ts One router per resource +src/api/middleware/ Session resolution (demo/login), access helpers, rate limits +src/api/lib/ Services: analysisService, ruleAnalysis, llm, embeddings, + proposalPdf, proposalGeneration, proposalStore, oauthState, + integrationStore, authConfig, logger, sync/ (CRM connectors) +src/lib/ API client (frontend), supabase client (backend), utils +src/hooks/ use-session (auth state), use-api-connection +src/pages/ components/ React SPA +prisma/ schema.prisma, seed.ts, manual/*.sql (pgvector, storage, multi-user, RLS) +scripts/ backfill-embeddings, check-rls, migrate-auth (set-passwords), cleanup-integrations +tests/ Vitest + Supertest API tests (tests/helpers/supabaseMock.ts is the shared DB stand-in) ``` diff --git a/BUG_REPORT.md b/BUG_REPORT.md deleted file mode 100644 index 4bf63fb..0000000 --- a/BUG_REPORT.md +++ /dev/null @@ -1,273 +0,0 @@ -# Bug Report & Issues Analysis - -**Date**: February 9, 2026 -**Status**: โœ… No Critical Bugs Found - -## Summary - -The project has been thoroughly analyzed. **No critical bugs or blocking issues were found.** The application is functional with minor improvements recommended below. - ---- - -## โœ… What's Working Well - -1. **TypeScript Compilation**: No TypeScript errors -2. **Routing**: All routes properly configured -3. **Authentication**: JWT-based auth with role-based access control -4. **API Endpoints**: All endpoints properly defined and connected -5. **Database Schema**: Complete and consistent -6. **Frontend Components**: All UI components properly imported -7. **Error Handling**: Comprehensive try-catch blocks throughout -8. **Protected Routes**: Working authentication guards - ---- - -## ๐ŸŸก Minor Issues & Recommendations - -### 1. **Puppeteer Dependency Location** -- **Issue**: Puppeteer is in `devDependencies` but used in production code -- **Location**: `package.json` line 106 -- **Impact**: May cause PDF export failures in production builds -- **Fix**: Move puppeteer to `dependencies` - -```bash -npm install puppeteer --save -npm uninstall puppeteer --save-dev -``` - -### 2. **Debug Console Logs** -- **Issue**: Production code contains debug console.log statements -- **Locations**: - - `src/context/ProposalContext.tsx` (lines 109, 116, 119, 123, 196, 200, 204) - - `src/pages/Integrations.tsx` (lines 76, 123, 132, 139, 153, 206) -- **Impact**: Minor - clutters production console -- **Recommendation**: Remove or wrap in `if (process.env.NODE_ENV === 'development')` - -### 3. **Type Safety - Use of `any`** -- **Locations**: - - `src/pages/ProposalVersions.tsx` line 40: `useState([])` - - `src/context/ProposalContext.tsx` line 20: `Promise` -- **Impact**: Minor - reduces type safety -- **Recommendation**: Create proper TypeScript interfaces for version types - -### 4. **Environment Variable Documentation** -- **Status**: โœ… Well documented in SETUP.md -- **Missing**: No `.env.example` file for developers -- **Recommendation**: Create `.env.example` for easier setup - ---- - -## ๐ŸŸข Code Quality Observations - -### Strengths -- โœ… Consistent error handling patterns -- โœ… Proper async/await usage throughout -- โœ… Toast notifications for user feedback -- โœ… Loading states for all async operations -- โœ… Fallback to mock data when API unavailable -- โœ… Comprehensive API client with proper types -- โœ… Well-structured component hierarchy -- โœ… Proper use of React hooks -- โœ… Protected routes with authentication checks -- โœ… Multi-tenant support with company isolation - -### Architecture Highlights -- **Context API**: Proper state management with ProposalContext -- **API Layer**: Clean separation with api-client.ts -- **Middleware**: Auth middleware with role checks -- **Database**: Proper schema with relations -- **Type Safety**: 95%+ of code properly typed - ---- - -## ๐Ÿ“ Feature Completeness Checklist - -### โœ… Core Features (Complete) -- [x] User Authentication (Login/Register) -- [x] Protected Routes -- [x] Proposal Creation (Manual) -- [x] Proposal Creation (AI-powered from natural language) โญ NEW -- [x] Proposal Upload (DOCX/PDF) -- [x] AI Risk Analysis -- [x] Compliance Rules Management -- [x] Version Control -- [x] PDF Export -- [x] Audit Logging -- [x] User Settings -- [x] Dashboard with Analytics -- [x] Status Management (Approve/Reject) -- [x] Multi-tenant Support - -### โœ… Integration Features (Complete) -- [x] Salesforce Integration -- [x] HubSpot Integration -- [x] Gmail Integration -- [x] OAuth Flow -- [x] Demo Mode for Integrations - -### โœ… UI/UX (Complete) -- [x] Responsive Design -- [x] Loading States -- [x] Error Messages -- [x] Toast Notifications -- [x] Animations (Framer Motion) -- [x] Consistent Styling (Tailwind + shadcn/ui) - ---- - -## ๐Ÿ”’ Security Review - -### โœ… Good Practices Found -- Password hashing with bcrypt -- JWT token authentication -- Protected API endpoints -- Role-based access control (RBAC) -- Company-based data isolation -- Input validation on API endpoints -- SQL injection prevention (using Supabase client) - -### โš ๏ธ Security Recommendations -1. **JWT Secret**: Change default secret in production - - Currently: `'default-secret-change-in-production'` - - **Action**: Set strong `NEXTAUTH_SECRET` in `.env` - -2. **CORS Configuration**: โœ… **FIXED** - Now restricted based on environment - - Development: Allows localhost origins - - Production: Only allows PRODUCTION_URL from environment variable - - Logs blocked origins for monitoring - -3. **Password Requirements**: Basic validation present - - Current: Min 8 characters - - **Recommendation**: Enforce complexity (uppercase, lowercase, numbers, symbols) - ---- - -## ๐Ÿ” API Endpoint Coverage - -All endpoints properly implemented: - -### Auth (`/api/auth`) -- โœ… POST `/login` - User login -- โœ… POST `/register` - New user registration -- โœ… POST `/verify` - Token verification -- โœ… POST `/change-password` - Password change - -### Proposals (`/api/proposals`) -- โœ… GET `/` - List all proposals -- โœ… GET `/:id` - Get single proposal -- โœ… POST `/` - Create proposal (manual) -- โœ… POST `/generate` - AI-generated proposal โญ NEW -- โœ… PUT `/:id/status` - Update status -- โœ… PUT `/:id` - Update proposal -- โœ… DELETE `/:id` - Delete proposal -- โœ… GET `/:id/export/pdf` - Export to PDF -- โœ… GET `/:id/versions` - Version history -- โœ… POST `/:id/versions` - Create version -- โœ… POST `/:id/versions/:versionId/restore` - Restore version -- โœ… GET `/:id/compare/:v1/:v2` - Compare versions - -### Analysis (`/api/analyze`) -- โœ… POST `/:proposalId` - AI risk analysis - -### Rules (`/api/rules`) -- โœ… GET `/` - List rules -- โœ… POST `/` - Create rule -- โœ… PUT `/:id` - Update rule -- โœ… DELETE `/:id` - Delete rule - -### Integrations (`/api/integrations`) -- โœ… GET `/` - List integrations -- โœ… POST `/` - Create integration -- โœ… PUT `/:id` - Update integration -- โœ… GET `/:type/connect` - OAuth connect -- โœ… GET `/:type/sync` - Sync data - -### OAuth (`/api/oauth`) -- โœ… GET `/callback/:type` - OAuth callback handler - -### Audit (`/api/audit`) -- โœ… GET `/logs` - Audit log listing - ---- - -## ๐Ÿ“ฆ Dependencies Status - -### Production Dependencies -- โœ… All listed dependencies properly installed -- โœ… No conflicting versions -- โš ๏ธ puppeteer should be moved from devDependencies to dependencies - -### Dev Dependencies -- โœ… All build tools present -- โœ… TypeScript configuration correct -- โœ… Linting configured - ---- - -## ๐ŸŽฏ Recommended Next Steps - -### Priority 1 - Quick Fixes (15 minutes) -1. Move puppeteer to production dependencies -2. Create `.env.example` file - -### Priority 2 - Code Quality (1 hour) -1. Remove/control debug console.log statements -2. Add proper types for version-related functions -3. Add JSDoc comments to utility functions - -### Priority 3 - Production Readiness (2 hours) -1. Strengthen password requirements -2. Restrict CORS to production domain -3. Add rate limiting to API endpoints -4. Add request logging middleware -5. Set up error tracking (e.g., Sentry) - -### Priority 4 - Testing (Optional) -1. Add unit tests for utility functions -2. Add integration tests for API endpoints -3. Add E2E tests for critical user flows - ---- - -## ๐Ÿ’ก Recent Additions - -### AI-Powered Proposal Generation โญ -**Status**: โœ… Successfully Implemented - -The new feature allows users to create proposals from natural language: - -**Implementation**: -- New API endpoint: `POST /api/proposals/generate` -- Updated UI: Tabbed interface (AI Generation / Manual Entry) -- AI Integration: Uses Azure OpenAI to extract structured data -- Smart Parsing: Extracts company name, title, content, pricing, etc. - -**Example Usage**: -``` -Input: "Make a proposal for company named 'ASW' for a cloud migration -project worth $150,000 with a 15% discount." - -Output: Full proposal with sections including: -- Executive Summary -- Proposed Solution -- Pricing Details -- Timeline -- Terms & Conditions -``` - -**Files Modified**: -- `src/api/proposals.ts` - Added AI generation endpoint -- `src/lib/api-client.ts` - Added client method -- `src/pages/CreateProposal.tsx` - Redesigned with tabs - ---- - -## ๐ŸŽ‰ Conclusion - -**Overall Assessment**: **EXCELLENT** โญโญโญโญโญ - -The project is well-architected, properly typed, and functionally complete. No blocking bugs were found. The codebase follows React and TypeScript best practices with proper error handling, loading states, and user feedback. - -**Production Readiness**: 95% - -The application is production-ready with only minor improvements recommended above. diff --git a/README.md b/README.md index da6d591..4ff7d99 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Typical development time was about 2 to 4 focused hours per day during active im ### Requirements -- Node.js 18 or newer +- Node.js 20 or newer - PostgreSQL 14 or newer, or a Supabase project - npm @@ -53,6 +53,8 @@ npx prisma db push # sync the schema (this repo has no migration files) npm run seed ``` +Copy `.env.example` to `.env` and fill it in (Supabase URL/key, and an AI provider โ€” see below). + Then apply the one-time manual SQL (idempotent, safe to re-run): ```bash @@ -60,7 +62,7 @@ Then apply the one-time manual SQL (idempotent, safe to re-run): npx prisma db execute --file prisma/manual/semantic_search.sql npm run backfill:embeddings -# Storage bucket + policies (required for document upload) +# Storage bucket (only needed if you use the /api/files upload endpoints) npx prisma db execute --file prisma/manual/storage_bucket.sql ``` @@ -72,6 +74,54 @@ npm run dev:full On Windows, you can also use `start.bat` to launch the backend and frontend together. +## Configuration + +### AI provider + +Set **one** of these in `.env`: + +| Provider | Variables | +| --- | --- | +| Google Gemini (checked first) | `GEMINI_API_KEY`, optional `GEMINI_MODEL` (default `gemini-2.5-flash`) | +| Azure OpenAI | `AZURE_OPENAI_ENDPOINT`, `OPENAI_API_KEY`, `AZURE_OPENAI_DEPLOYMENT` | + +With **no** provider configured, or when the provider is unreachable or returns an unusable answer, +**analysis still works**: it falls back to a built-in rule checker (discount cap, minimum deal size, +payment terms, required clauses, document structure) and the report says so. Set `ANALYSIS_MODE=rules` +to force the rule checker. Proposal *generation* needs an AI provider and reports `AI_UNAVAILABLE` without one. + +Semantic search uses embeddings from the same provider (Gemini `gemini-embedding-001`, or the Azure +embedding deployment). After switching provider, re-embed everything: +`npm run backfill:embeddings -- --all`. + +### Authentication + +| `AUTH_MODE` | Behaviour | +| --- | --- | +| `demo` (default) | No sign-in. Every visitor is the default user (`DEMO_USER_EMAIL`, else the first admin). Ideal for demos. | +| `login` | Real multi-user mode. Every route needs a token; people sign in with email and password; data is isolated per company (or per owner for users without a company). | + +Going multi-user: + +1. Set `AUTH_MODE=login` and a long random `NEXTAUTH_SECRET` (the server refuses to start without one). +2. `npx prisma db execute --file prisma/manual/multi_user.sql` (adds `User.company_id` and indexes). +3. `npm run set-passwords` โ€” issues each user a random password, shown once. Admins can create users with a + password and company through `POST /api/users`; set `ALLOW_SELF_REGISTRATION=true` to let people sign up. + +### Hardening the database + +Row Level Security is **off** by default, which means the public Supabase anon key can read every table. +To lock it down, follow the steps at the top of `prisma/manual/enable_rls.sql` (set `SUPABASE_SERVICE_ROLE_KEY` +first, then `npm run check:rls`, run the SQL, and `npm run check:rls -- --verify`). + +## Testing + +```bash +npm run lint && npm run typecheck && npm test && npm run build +``` + +CI runs the same four steps on every push and pull request. + ## Documentation - [ARCHITECTURE.md](ARCHITECTURE.md) โ€” system design and trade-offs diff --git a/SETUP.md b/SETUP.md index acd8e13..de821e4 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,399 +1,404 @@ -# ๐Ÿš€ Quick Start Guide - DealSentry - -## โœ… System Status - -**Database**: PostgreSQL (Supabase) - Connected โœ… -**Backend API**: Express.js on port 3001 -**Frontend**: Vite + React on port 5173 -**Authentication**: JWT-based with role-based access control -**File Storage**: Supabase Storage (proposal-files bucket) - ---- - -## ๐ŸŽฏ Getting Started (5 Minutes) - -### 1. Start the Backend API Server - -```bash -npm run server -``` - -The API will start on `http://localhost:3001` - -### 2. Start the Frontend Development Server - -In a new terminal: - -```bash -npm run dev -``` - -The app will open at `http://localhost:5173` - -### 3. Login - -**Demo Accounts Available:** - -- **Admin User** - - Email: `admin@dealsentry.ai` - - Password: `demo` - - Access: Full system access, audit logs, user management - -- **Test Users** (5 users) - - Emails: `test1@dealsentry.ai` through `test5@dealsentry.ai` - - Password: `demo` (for all test users) - - Access: Create proposals, review, integrations - ---- - -## ๐Ÿ“Š Features Available - -### โœ… Fully Implemented - -1. **Proposal Management** - - Create, upload, and review proposals - - AI-powered risk analysis with Azure OpenAI - - Contract renewal tracking - -2. **Compliance Engine** - - 8+ pre-configured compliance rules - - Custom rule creation (PRICING, LEGAL, STRUCTURAL) - - Real-time validation - - Risk scoring (0-100%) - -3. **Authentication & Security** - - JWT-based authentication - - Role-based access control (6 roles) - - Secure API endpoints - - Audit logging - -4. **Database & Storage** - - PostgreSQL with Supabase - - Seeded with demo data - - File upload support (DOCX, PDF) - - Automatic text extraction - -5. **Integrations Framework** - - Salesforce OAuth (demo mode ready) - - HubSpot OAuth (demo mode ready) - - Gmail OAuth (demo mode ready) - - Sync logs and status tracking - -6. **Audit System** - - Complete action history - - User activity tracking - - Proposal change logs - -### ๐Ÿ“‹ Sample Data Included - -- **6 Users** (1 admin: admin@dealsentry.ai, 5 test users: test1-5@dealsentry.ai) -- **8 Compliance Rules** (discount limits, legal clauses, etc.) -- **4 Templates** (Sales Proposal, MSA, SOW, NDA) -- **3 Sample Proposals** (with risk reports) -- **5 Legal Clauses** (indemnification, liability, etc.) - ---- - -## ๐Ÿ”ง Configuration - -### Environment Variables (.env) - -All critical environment variables are already configured: - -```env -# Database (Supabase PostgreSQL) -DATABASE_URL="postgresql://..." -SUPABASE_URL="https://..." -SUPABASE_ANON_KEY="..." - -# Azure OpenAI (for AI risk analysis) -AZURE_OPENAI_ENDPOINT="https://..." -OPENAI_API_KEY="..." -AZURE_OPENAI_DEPLOYMENT="gpt-4o" - -# Authentication -NEXTAUTH_SECRET="..." # JWT secret key - -# Integrations (Demo Mode Enabled) -SALESFORCE_DEMO_MODE="true" -HUBSPOT_DEMO_MODE="false" -GMAIL_DEMO_MODE="false" -``` - -### Supabase Storage Setup - -**Required**: Create a storage bucket named `proposal-files` - -1. Go to [Supabase Dashboard](https://app.supabase.com) -2. Navigate to Storage -3. Create new bucket: `proposal-files` -4. Set to **Public** (for file URLs) - ---- - -## ๐Ÿ› ๏ธ Development Commands - -```bash -# Install dependencies -npm install - -# Start backend API server (port 3001) -npm run server - -# Start frontend dev server (port 5173) -npm run dev - -# Run both servers concurrently -npm run dev:full - -# Database commands -npm run seed # Seed database with demo data -npx prisma db push # Push schema changes -npx prisma studio # Open Prisma Studio GUI - -# Build for production -npm run build -``` - ---- - -## ๏ฟฝ Production Deployment - -### Environment Variables for Production - -Before deploying to production, set these critical environment variables: - -```bash -# Set Node environment to production -NODE_ENV=production - -# Set your production domain (REQUIRED for CORS security) -PRODUCTION_URL=https://your-production-domain.com - -# Use strong secrets (CHANGE THESE!) -NEXTAUTH_SECRET=your-strong-random-secret-here - -# Database and other configs... -DATABASE_URL=postgresql://... -AZURE_OPENAI_ENDPOINT=https://... -``` - -### CORS Security - -The application automatically restricts CORS based on environment: - -- **Development** (`NODE_ENV != production`): Allows localhost origins -- **Production** (`NODE_ENV = production`): Only allows `PRODUCTION_URL` - -**Important**: Set `PRODUCTION_URL` environment variable to your actual domain before deploying! - -### Production Checklist - -- [ ] Set `NODE_ENV=production` -- [ ] Set `PRODUCTION_URL` to your domain -- [ ] Change `NEXTAUTH_SECRET` to a strong random string -- [ ] Configure production database -- [ ] Set up Azure OpenAI credentials -- [ ] Configure real OAuth credentials (if using integrations) -- [ ] Test CORS is working correctly - ---- - -## ๏ฟฝ๐Ÿ“ Project Structure - -``` -dealsentry/ -โ”œโ”€โ”€ src/ -โ”‚ โ”œโ”€โ”€ api/ # Backend API routes -โ”‚ โ”‚ โ”œโ”€โ”€ auth.ts # Authentication endpoints -โ”‚ โ”‚ โ”œโ”€โ”€ proposals.ts # Proposal CRUD -โ”‚ โ”‚ โ”œโ”€โ”€ rules.ts # Compliance rules -โ”‚ โ”‚ โ”œโ”€โ”€ templates.ts # Proposal templates -โ”‚ โ”‚ โ”œโ”€โ”€ users.ts # User management -โ”‚ โ”‚ โ”œโ”€โ”€ integrations.ts # Integration management -โ”‚ โ”‚ โ”œโ”€โ”€ oauth.ts # OAuth flows -โ”‚ โ”‚ โ”œโ”€โ”€ files.ts # File upload/download -โ”‚ โ”‚ โ”œโ”€โ”€ analyze.ts # AI risk analysis -โ”‚ โ”‚ โ””โ”€โ”€ audit.ts # Audit logs -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ pages/ # Frontend pages -โ”‚ โ”‚ โ”œโ”€โ”€ Login.tsx # Authentication page -โ”‚ โ”‚ โ”œโ”€โ”€ Dashboard.tsx # Main dashboard -โ”‚ โ”‚ โ”œโ”€โ”€ Proposals.tsx # Proposal list -โ”‚ โ”‚ โ”œโ”€โ”€ ProposalReview.tsx # Review interface -โ”‚ โ”‚ โ”œโ”€โ”€ Compliance.tsx # Rules management -โ”‚ โ”‚ โ”œโ”€โ”€ Integrations.tsx # Integration setup -โ”‚ โ”‚ โ””โ”€โ”€ Audit.tsx # Audit logs (admin only) -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ components/ # Reusable UI components -โ”‚ โ”œโ”€โ”€ lib/ # Utilities and clients -โ”‚ โ”‚ โ”œโ”€โ”€ api-client.ts # Frontend API client -โ”‚ โ”‚ โ”œโ”€โ”€ supabase.ts # Supabase client -โ”‚ โ”‚ โ””โ”€โ”€ db.ts # Prisma client -โ”‚ โ”‚ -โ”‚ โ””โ”€โ”€ types/ # TypeScript definitions -โ”‚ -โ”œโ”€โ”€ prisma/ -โ”‚ โ””โ”€โ”€ schema.prisma # Database schema -โ”‚ -โ”œโ”€โ”€ scripts/ -โ”‚ โ””โ”€โ”€ seed-supabase.ts # Database seeding script -โ”‚ -โ””โ”€โ”€ server.ts # Express API server -``` - ---- - -## ๐Ÿ” API Endpoints - -### Authentication -- `POST /api/auth/login` - User login -- `POST /api/auth/register` - User registration -- `GET /api/auth/verify` - Verify JWT token - -### Proposals -- `GET /api/proposals` - List all proposals -- `GET /api/proposals/:id` - Get single proposal -- `POST /api/proposals` - Create proposal -- `PUT /api/proposals/:id/status` - Update status -- `DELETE /api/proposals/:id` - Delete proposal -- `POST /api/analyze/:id` - Analyze with AI - -### Rules & Templates -- `GET /api/rules` - List compliance rules -- `POST /api/rules` - Create rule -- `GET /api/templates` - List templates - -### Users -- `GET /api/users` - List users -- `POST /api/users` - Create user -- `PATCH /api/users/:id` - Update user - -### Integrations -- `GET /api/integrations` - List integrations -- `POST /api/integrations/:id/sync` - Trigger sync -- `GET /api/integrations/:id/logs` - Get sync logs - -### OAuth -- `GET /api/oauth/salesforce/authorize` - Start Salesforce OAuth -- `GET /api/oauth/hubspot/authorize` - Start HubSpot OAuth -- `GET /api/oauth/gmail/authorize` - Start Gmail OAuth - -### Files -- `POST /api/files/upload` - Upload file -- `POST /api/files/extract-text` - Extract text from document -- `GET /api/files/download/:path` - Download file - -### Audit -- `GET /api/audit` - Get audit logs (admin only) - ---- - -## ๐ŸŽจ Key Features by Page - -### Dashboard -- Proposal statistics -- Recent proposals -- Contract renewal alerts -- Quick actions - -### Proposals -- List view with filters -- Status badges -- Readiness scores -- Quick actions - -### Proposal Review -- Full proposal content -- AI risk analysis -- Compliance findings -- Edit and approve - -### Compliance -- Active rules list -- Rule creation -- Rule toggle - -### Integrations -- OAuth connection status -- Sync triggers -- Sync history -- Demo mode support - -### Audit (Admin Only) -- Complete action history -- User filtering -- Proposal filtering -- Timestamp tracking - ---- - -## ๐Ÿšจ Troubleshooting - -### API Server Won't Start -```bash -# Check if port 3001 is in use -netstat -ano | findstr :3001 - -# Kill process if needed -taskkill /PID /F -``` - -### Database Connection Issues -```bash -# Verify DATABASE_URL in .env -# Check Supabase dashboard for connection status -# Try pushing schema again -npx prisma db push -``` - -### Frontend Won't Connect to API -- Ensure backend is running on port 3001 -- Check console for CORS errors -- Verify VITE_API_URL in .env (default: http://localhost:3001) - -### File Upload Fails -- Create `proposal-files` bucket in Supabase Storage -- Ensure bucket is set to public -- Check SUPABASE_ANON_KEY in .env - ---- - -## ๐ŸŽฏ Next Steps - -1. **Create Supabase Storage Bucket** - - Name: `proposal-files` - - Access: Public - -2. **Test All Features** - - Login as admin and sales rep - - Create a proposal - - Run AI analysis - - Test integrations - - Review audit logs - -3. **Customize** - - Add more compliance rules - - Create custom templates - - Configure real OAuth credentials for integrations - -4. **Production Deployment** - - Update environment variables - - Configure domain - - Enable real OAuth apps - - Set up proper authentication with password hashing - ---- - -## ๐Ÿ“ž Support - -For issues or questions: -- Check the [TODO.md](TODO.md) for known issues -- Review [FRONTEND_DOCUMENTATION.md](FRONTEND_DOCUMENTATION.md) for frontend details -- See [HUBSPOT_SETUP.md](HUBSPOT_SETUP.md) for integration setup - ---- - -**Ready to go! ๐ŸŽ‰** - -Start both servers and login with the demo accounts to explore all features. +# ๐Ÿš€ Quick Start Guide - DealSentry + +## โœ… System Status + +**Database**: PostgreSQL (Supabase) - Connected โœ… +**Backend API**: Express.js on port 3001 +**Frontend**: Vite + React on port 5173 +**Authentication**: JWT-based with role-based access control +**File Storage**: Supabase Storage (proposal-files bucket) + +--- + +## ๐ŸŽฏ Getting Started (5 Minutes) + +### 1. Start the Backend API Server + +```bash +npm run server +``` + +The API will start on `http://localhost:3001` + +### 2. Start the Frontend Development Server + +In a new terminal: + +```bash +npm run dev +``` + +The app will open at `http://localhost:5173` + +### 3. Open the app + +By default (`AUTH_MODE=demo`) there is **no sign-in**: every visitor is served as the default user โ€” +`DEMO_USER_EMAIL`, else the first admin (the seed creates `admin@dealsentry.ai`). Nothing to type. + +For a real multi-user setup with email + password sign-in, see +[docs/AUTH_QUICKSTART.md](docs/AUTH_QUICKSTART.md) (`AUTH_MODE=login`, then `npm run set-passwords`). + +The seed also creates `test1@dealsentry.ai` โ€ฆ `test5@dealsentry.ai`. They have no passwords until you run +`npm run set-passwords`. + +--- + +## ๐Ÿ“Š Features Available + +### โœ… Fully Implemented + +1. **Proposal Management** + - Create, upload, and review proposals + - AI-powered risk analysis (Gemini or Azure OpenAI), with a built-in rule checker as a fallback + - Contract renewal tracking + +2. **Compliance Engine** + - 8+ pre-configured compliance rules + - Custom rule creation (PRICING, LEGAL, STRUCTURAL) + - Real-time validation + - Risk scoring (0-100%) + +3. **Authentication & Security** + - JWT-based authentication + - Role-based access control (6 roles) + - Secure API endpoints + - Audit logging + +4. **Database & Storage** + - PostgreSQL with Supabase + - Seeded with demo data + - File upload support (DOCX, PDF) + - Automatic text extraction + +5. **Integrations Framework** + - Salesforce OAuth (demo mode ready) + - HubSpot OAuth (demo mode ready) + - Gmail OAuth (demo mode ready) + - Sync logs and status tracking + +6. **Audit System** + - Complete action history + - User activity tracking + - Proposal change logs + +### ๐Ÿ“‹ Sample Data Included + +- **6 Users** (1 admin: admin@dealsentry.ai, 5 test users: test1-5@dealsentry.ai) +- **8 Compliance Rules** (discount limits, legal clauses, etc.) +- **4 Templates** (Sales Proposal, MSA, SOW, NDA) +- **3 Sample Proposals** (with risk reports) +- **5 Legal Clauses** (indemnification, liability, etc.) + +--- + +## ๐Ÿ”ง Configuration + +### Environment Variables (.env) + +All critical environment variables are already configured: + +```env +# Database (Supabase PostgreSQL) +DATABASE_URL="postgresql://..." +SUPABASE_URL="https://..." +SUPABASE_ANON_KEY="..." + +# AI provider (pick one). Without either, analysis falls back to the built-in rule checker. +GEMINI_API_KEY="..." # Google Gemini (default model gemini-2.5-flash) +# AZURE_OPENAI_ENDPOINT="https://..." # ...or Azure OpenAI +# OPENAI_API_KEY="..." +# AZURE_OPENAI_DEPLOYMENT="gpt-4o" + +# Authentication +NEXTAUTH_SECRET="..." # JWT secret key +# AUTH_MODE="login" # default "demo" = no sign-in; see docs/AUTH_QUICKSTART.md + +# Integrations (Demo Mode Enabled) +SALESFORCE_DEMO_MODE="true" +HUBSPOT_DEMO_MODE="false" +GMAIL_DEMO_MODE="false" +``` + +### Supabase Storage Setup + +**Optional** โ€” only the `/api/files/*` endpoints use storage (the proposal pages work without it). + +Create the `proposal-files` bucket by running the SQL (it also adds the policies the API needs): + +```bash +npx prisma db execute --file prisma/manual/storage_bucket.sql +``` + +Uploads return a time-limited signed link, so the bucket does not need to be public. If you later enable Row Level +Security (`prisma/manual/enable_rls.sql`) the bucket is made private and the API reaches it with the service-role key. + +--- + +## ๐Ÿ› ๏ธ Development Commands + +```bash +# Install dependencies +npm install + +# Start backend API server (port 3001) +npm run server + +# Start frontend dev server (port 5173) +npm run dev + +# Run both servers concurrently +npm run dev:full + +# Database commands +npm run seed # Seed database with demo data +npx prisma db push # Push schema changes +npx prisma studio # Open Prisma Studio GUI + +# Build for production +npm run build +``` + +--- + +## ๏ฟฝ Production Deployment + +### Environment Variables for Production + +Before deploying to production, set these critical environment variables: + +```bash +# Set Node environment to production +NODE_ENV=production + +# Set your production domain (REQUIRED for CORS security) +PRODUCTION_URL=https://your-production-domain.com + +# Use strong secrets (CHANGE THESE!) +NEXTAUTH_SECRET=your-strong-random-secret-here + +# Database and other configs... +DATABASE_URL=postgresql://... +AZURE_OPENAI_ENDPOINT=https://... +``` + +### CORS Security + +The application automatically restricts CORS based on environment: + +- **Development** (`NODE_ENV != production`): Allows localhost origins +- **Production** (`NODE_ENV = production`): Only allows `PRODUCTION_URL` + +**Important**: Set `PRODUCTION_URL` environment variable to your actual domain before deploying! + +### Production Checklist + +- [ ] Set `NODE_ENV=production` +- [ ] Set `PRODUCTION_URL` to your domain +- [ ] Change `NEXTAUTH_SECRET` to a strong random string +- [ ] Configure production database +- [ ] Configure an AI provider (`GEMINI_API_KEY` or the Azure OpenAI variables) โ€” analysis still works without one, via the rule checker +- [ ] Decide on `AUTH_MODE` (`demo` for a single shared user, `login` for real accounts) +- [ ] Set `SUPABASE_SERVICE_ROLE_KEY`, then enable Row Level Security (`prisma/manual/enable_rls.sql`) +- [ ] Configure real OAuth credentials (if using integrations) +- [ ] Test CORS is working correctly + +--- + +## ๏ฟฝ๐Ÿ“ Project Structure + +``` +dealsentry/ +โ”œโ”€โ”€ src/ +โ”‚ โ”œโ”€โ”€ api/ # Backend API routes +โ”‚ โ”‚ โ”œโ”€โ”€ auth.ts # Authentication endpoints +โ”‚ โ”‚ โ”œโ”€โ”€ proposals.ts # Proposal CRUD +โ”‚ โ”‚ โ”œโ”€โ”€ rules.ts # Compliance rules +โ”‚ โ”‚ โ”œโ”€โ”€ templates.ts # Proposal templates +โ”‚ โ”‚ โ”œโ”€โ”€ users.ts # User management +โ”‚ โ”‚ โ”œโ”€โ”€ integrations.ts # Integration management +โ”‚ โ”‚ โ”œโ”€โ”€ oauth.ts # OAuth flows +โ”‚ โ”‚ โ”œโ”€โ”€ files.ts # File upload/download +โ”‚ โ”‚ โ”œโ”€โ”€ analyze.ts # AI risk analysis +โ”‚ โ”‚ โ””โ”€โ”€ audit.ts # Audit logs +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ pages/ # Frontend pages +โ”‚ โ”‚ โ”œโ”€โ”€ Login.tsx # Authentication page +โ”‚ โ”‚ โ”œโ”€โ”€ Dashboard.tsx # Main dashboard +โ”‚ โ”‚ โ”œโ”€โ”€ Proposals.tsx # Proposal list +โ”‚ โ”‚ โ”œโ”€โ”€ ProposalReview.tsx # Review interface +โ”‚ โ”‚ โ”œโ”€โ”€ Compliance.tsx # Rules management +โ”‚ โ”‚ โ”œโ”€โ”€ Integrations.tsx # Integration setup +โ”‚ โ”‚ โ””โ”€โ”€ Audit.tsx # Audit logs (admin only) +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ components/ # Reusable UI components +โ”‚ โ”œโ”€โ”€ lib/ # Utilities and clients +โ”‚ โ”‚ โ”œโ”€โ”€ api-client.ts # Frontend API client +โ”‚ โ”‚ โ”œโ”€โ”€ supabase.ts # Supabase client +โ”‚ โ”‚ โ””โ”€โ”€ db.ts # Prisma client +โ”‚ โ”‚ +โ”‚ โ””โ”€โ”€ types/ # TypeScript definitions +โ”‚ +โ”œโ”€โ”€ prisma/ +โ”‚ โ””โ”€โ”€ schema.prisma # Database schema +โ”‚ +โ”œโ”€โ”€ scripts/ +โ”‚ โ””โ”€โ”€ seed-supabase.ts # Database seeding script +โ”‚ +โ””โ”€โ”€ server.ts # Express API server +``` + +--- + +## ๐Ÿ” API Endpoints + +### Authentication +- `POST /api/auth/login` - User login +- `POST /api/auth/register` - User registration +- `GET /api/auth/verify` - Verify JWT token + +### Proposals +- `GET /api/proposals` - List all proposals +- `GET /api/proposals/:id` - Get single proposal +- `POST /api/proposals` - Create proposal +- `PUT /api/proposals/:id/status` - Update status +- `DELETE /api/proposals/:id` - Delete proposal +- `POST /api/analyze/:id` - Analyze with AI + +### Rules & Templates +- `GET /api/rules` - List compliance rules +- `POST /api/rules` - Create rule +- `GET /api/templates` - List templates + +### Users +- `GET /api/users` - List users +- `POST /api/users` - Create user +- `PATCH /api/users/:id` - Update user + +### Integrations +- `GET /api/integrations` - List integrations +- `POST /api/integrations/:id/sync` - Trigger sync +- `GET /api/integrations/:id/logs` - Get sync logs + +### OAuth +- `GET /api/oauth/salesforce/authorize` - Start Salesforce OAuth +- `GET /api/oauth/hubspot/authorize` - Start HubSpot OAuth +- `GET /api/oauth/gmail/authorize` - Start Gmail OAuth + +### Files +- `POST /api/files/upload` - Upload file +- `POST /api/files/extract-text` - Extract text from document +- `GET /api/files/download/:path` - Download file + +### Audit +- `GET /api/audit` - Get audit logs (admin only) + +--- + +## ๐ŸŽจ Key Features by Page + +### Dashboard +- Proposal statistics +- Recent proposals +- Contract renewal alerts +- Quick actions + +### Proposals +- List view with filters +- Status badges +- Readiness scores +- Quick actions + +### Proposal Review +- Full proposal content +- AI risk analysis +- Compliance findings +- Edit and approve + +### Compliance +- Active rules list +- Rule creation +- Rule toggle + +### Integrations +- OAuth connection status +- Sync triggers +- Sync history +- Demo mode support + +### Audit (Admin Only) +- Complete action history +- User filtering +- Proposal filtering +- Timestamp tracking + +--- + +## ๐Ÿšจ Troubleshooting + +### API Server Won't Start +```bash +# Check if port 3001 is in use +netstat -ano | findstr :3001 + +# Kill process if needed +taskkill /PID /F +``` + +### Database Connection Issues +```bash +# Verify DATABASE_URL in .env +# Check Supabase dashboard for connection status +# Try pushing schema again +npx prisma db push +``` + +### Frontend Won't Connect to API +- Ensure backend is running on port 3001 +- Check console for CORS errors +- Verify VITE_API_URL in .env (default: http://localhost:3001) + +### File Upload Fails +- Create `proposal-files` bucket in Supabase Storage +- Ensure bucket is set to public +- Check SUPABASE_ANON_KEY in .env + +--- + +## ๐ŸŽฏ Next Steps + +1. **Create Supabase Storage Bucket** + - Name: `proposal-files` + - Access: Public + +2. **Test All Features** + - Login as admin and sales rep + - Create a proposal + - Run AI analysis + - Test integrations + - Review audit logs + +3. **Customize** + - Add more compliance rules + - Create custom templates + - Configure real OAuth credentials for integrations + +4. **Production Deployment** + - Update environment variables + - Configure domain + - Enable real OAuth apps + - Set up proper authentication with password hashing + +--- + +## ๐Ÿ“ž Support + +For issues or questions: +- Check the [TODO.md](TODO.md) for known issues +- Review [FRONTEND_DOCUMENTATION.md](FRONTEND_DOCUMENTATION.md) for frontend details +- See [HUBSPOT_SETUP.md](HUBSPOT_SETUP.md) for integration setup + +--- + +**Ready to go! ๐ŸŽ‰** + +Start both servers and login with the demo accounts to explore all features. diff --git a/docs/AUTH_QUICKSTART.md b/docs/AUTH_QUICKSTART.md index 132dac1..19606da 100644 --- a/docs/AUTH_QUICKSTART.md +++ b/docs/AUTH_QUICKSTART.md @@ -1,276 +1,81 @@ -# Authentication System - Quick Start Guide - -## What Was Implemented - -A complete, secure login/signup system with the following features: - -### โœ… Security Features -- **Password Hashing**: bcrypt with 10 salt rounds -- **JWT Tokens**: 7-day expiration, secure token-based auth -- **Protected Routes**: Automatic redirect for unauthorized access -- **Token Verification**: Backend validation on each request -- **Session Management**: Persistent login with localStorage - -### โœ… User Experience -- **Beautiful UI**: Modern, animated login/signup page -- **Password Strength**: Real-time validation with visual feedback -- **Form Validation**: Email, password requirements, confirmation -- **Error Handling**: Clear, user-friendly error messages -- **Role-Based Access**: Support for multiple user roles - -### โœ… Developer Tools -- **Auth Utilities**: Helper functions for common auth tasks -- **Protected Route Component**: Easy-to-use wrapper for protected pages -- **Centralized Auth**: All auth logic in one place -- **TypeScript Support**: Full type safety - -## Quick Setup - -### 1. Install Dependencies โœ… (Already Done) -```bash -npm install bcryptjs @types/bcryptjs -``` - -### 2. Update Database Schema โœ… (Already Done) - -The `User` model now includes a `password` field. Apply the changes: - -```bash -npx prisma db push -``` - -### 3. Create Default Admin User - -Run the migration script: - -```bash -npx tsx scripts/migrate-auth.ts -``` - -**Default Admin Credentials:** -- Email: `admin@dealsentry.com` -- Password: `Admin@123` - -โš ๏ธ **Change this password immediately after first login!** - -### 4. Set Environment Variable - -Make sure your `.env` file has: - -```env -NEXTAUTH_SECRET=your-secure-secret-key-here -``` - -Generate a secure secret: -```bash -node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" -``` - -### 5. Start the Application - -```bash -# Option 1: Start both frontend and backend -npm run dev:full - -# Option 2: Start separately -# Terminal 1: -npm run dev - -# Terminal 2: -npm run server -``` - -### 6. Test the System - -1. **Visit** http://localhost:5173 -2. **Navigate to** `/auth` or `/login` -3. **Login** with the default admin credentials -4. **Change password** (recommended!) -5. **Create new users** via the signup page - -## File Changes Summary - -### New Files Created -1. `src/components/ProtectedRoute.tsx` - Protected route wrapper -2. `src/lib/auth-utils.ts` - Auth helper functions -3. `scripts/migrate-auth.ts` - Database migration script -4. `docs/AUTHENTICATION.md` - Full authentication documentation - -### Modified Files -1. `prisma/schema.prisma` - Added password field to User model -2. `src/api/auth.ts` - Implemented bcrypt hashing -3. `src/App.tsx` - Added ProtectedRoute to protected pages -4. `src/pages/Auth.tsx` - Updated to use new auth utilities -5. `src/components/layout/ClientLayout.tsx` - Updated logout and auth checks -6. `src/lib/auth.ts` - Updated to use new auth utilities -7. `package.json` - Added bcryptjs dependency -8. `README.md` - Added authentication setup instructions - -## API Endpoints - -### Register New User -```http -POST /api/auth/register -Content-Type: application/json - -{ - "email": "user@example.com", - "password": "SecurePass123", - "name": "John Doe" -} -``` - -### Login -```http -POST /api/auth/login -Content-Type: application/json - -{ - "email": "user@example.com", - "password": "SecurePass123" -} -``` - -### Verify Token -```http -GET /api/auth/verify -Authorization: Bearer -``` - -## Password Requirements - -When signing up, passwords must meet these criteria: -- โœ… At least 8 characters -- โœ… One uppercase letter -- โœ… One lowercase letter -- โœ… One number - -## Using Auth in Your Code - -### Check if User is Logged In -```typescript -import { isAuthenticated, getCurrentUser } from '@/lib/auth-utils'; - -if (isAuthenticated()) { - const user = getCurrentUser(); - console.log('Logged in as:', user?.email); -} -``` - -### Protect a Route -```tsx -import ProtectedRoute from '@/components/ProtectedRoute'; - -} -/> -``` - -### Check User Role -```typescript -import { hasRole, isAdmin } from '@/lib/auth-utils'; - -if (isAdmin()) { - // Admin-only code -} - -if (hasRole(['ADMIN', 'MANAGER'])) { - // Admin or Manager code -} -``` - -### Logout User -```typescript -import { clearAuthData } from '@/lib/auth-utils'; -import { useNavigate } from 'react-router-dom'; - -const navigate = useNavigate(); - -const handleLogout = () => { - clearAuthData(); - navigate('/auth'); -}; -``` - -## Testing Checklist - -- [ ] Register a new user with valid credentials -- [ ] Register with weak password (should fail) -- [ ] Register with existing email (should fail) -- [ ] Login with correct credentials -- [ ] Login with wrong password (should fail) -- [ ] Access protected route without login (should redirect) -- [ ] Access protected route after login (should work) -- [ ] Logout and verify can't access protected routes -- [ ] Password strength indicator shows correctly -- [ ] Password confirmation validation works - -## Troubleshooting - -### "Cannot reach the server" error -Make sure both frontend and backend are running: -```bash -npm run dev:full -``` - -### Database connection errors -1. Check PostgreSQL is running -2. Verify DATABASE_URL in `.env` file -3. Run `npx prisma db push` again - -### Migration script errors -```bash -# Make sure Prisma client is generated -npx prisma generate - -# Then run migration -npx tsx scripts/migrate-auth.ts -``` - -### Token verification fails -1. Check NEXTAUTH_SECRET is set in `.env` -2. Clear browser localStorage -3. Login again - -## Next Steps - -After setting up authentication, you can: - -1. **Create more users** through the signup page -2. **Assign different roles** to users in the database -3. **Implement password reset** (future enhancement) -4. **Add email verification** (future enhancement) -5. **Enable 2FA** (future enhancement) - -## Security Reminders - -๐Ÿ”’ **Important Security Notes:** - -1. **Change default admin password** immediately -2. **Use strong NEXTAUTH_SECRET** in production -3. **Enable HTTPS** in production -4. **Never commit** `.env` file to version control -5. **Implement rate limiting** on auth endpoints in production -6. **Use secure password requirements** for all users -7. **Regularly rotate** JWT secrets - -## Support - -For more detailed information, see: -- [Full Authentication Documentation](./docs/AUTHENTICATION.md) -- [API Documentation](./docs/API.md) -- [Security Best Practices](./docs/SECURITY.md) - -## Summary - -You now have a fully functional, secure authentication system with: -- โœ… Password hashing (bcrypt) -- โœ… JWT token authentication -- โœ… Protected routes -- โœ… Beautiful UI with validation -- โœ… Role-based access control -- โœ… Session management -- โœ… Comprehensive error handling - -The system is production-ready with proper security measures in place! +# Authentication + +DealSentry has two authentication modes, chosen by the `AUTH_MODE` environment +variable. Both are implemented in `src/api/middleware/auth.ts` and +`src/api/lib/authConfig.ts`. + +| | `demo` (default) | `login` | +| --- | --- | --- | +| Sign-in screen | none | email + password | +| Request without a token | served as the **default user** | `401 AUTH_REQUIRED` | +| Who is the default user | `DEMO_USER_EMAIL`, else the first `ADMIN`, else the first user | โ€” | +| Data isolation | everyone is an admin, so everything is visible | per company; users with no company see only what they own | +| `NEXTAUTH_SECRET` | should be set (warning if not) | **required** โ€” the server refuses to start without a real one | +| Typical use | demos, a single team | real multi-user deployments | + +A valid bearer token is honoured in both modes and identifies the user. + +## Turning on multi-user mode + +1. **Secrets.** Generate a signing secret and set both variables: + + ```bash + node -e "console.log(require('crypto').randomBytes(48).toString('base64'))" + ``` + + ```env + AUTH_MODE=login + NEXTAUTH_SECRET= + ``` + + On Render, `NEXTAUTH_SECRET` is generated for you by `render.yaml`; add `AUTH_MODE=login` in the dashboard. + +2. **Database.** Add the company column and indexes (idempotent): + + ```bash + npx prisma db execute --file prisma/manual/multi_user.sql + ``` + +3. **Passwords.** The seed data creates users *without* passwords. Issue each one a random password + (printed once, never stored in clear text): + + ```bash + npm run set-passwords # everyone who has none + npm run set-passwords -- --dry-run # preview + npm run set-passwords -- --reset a@b.com # new password for one user + ``` + +4. **Start the server.** `npm run dev:full` (or deploy). People now land on the sign-in page. + +### Creating more users + +- **Admin:** `POST /api/users` with `{ email, name, role, password, companyId }` (admin only). `companyId` puts the + user in a tenant; users in the same company share proposals, users with no company only see their own. +- **Self-service:** set `ALLOW_SELF_REGISTRATION=true` and the sign-in page offers "Create an account". New accounts are + always `SALES_REP` with no company โ€” the API ignores a client-supplied company or role. +- **Password change:** Settings โ†’ Change password (`POST /api/auth/change-password`). + +## How it works + +- `POST /api/auth/login` checks the bcrypt hash and returns a 7-day JWT (`{ userId, ... }`), stored by the SPA as + `auth_token` in `localStorage`. The middleware **re-reads the user from the database on every request**, so role and + company changes and deleted accounts take effect immediately. +- `GET /api/auth/config` (public) tells the SPA which mode the server is in. +- When the API answers `401 AUTH_REQUIRED`, the SPA clears the session and shows the sign-in page. +- Login, registration and password-change are rate limited (10 attempts per 15 minutes per client in production). + Behind a proxy such as Render, `TRUST_PROXY` (default `1` in production) makes "per client" mean the real visitor. + +### OAuth redirects (Salesforce, HubSpot, Gmail) + +Browser redirects cannot carry an `Authorization` header, and the 7-day session token must not be put in a URL. So the SPA +calls `POST /api/oauth/start-token` first and navigates with the returned **2-minute, single-purpose** token. The +`state` parameter sent through the provider is a signed, 10-minute token too โ€” a callback cannot be forged for another +user's id. Neither token can be used as a session token. + +## Security notes + +- Passwords are bcrypt-hashed (10 rounds) and **never returned** by any endpoint. +- In login mode, `GET /api/users` is admin-only and non-admins can read only their own user record. +- Session tokens are signed with `NEXTAUTH_SECRET`; rotating it signs everyone out. +- Not implemented (would be natural next steps): password reset by email, email verification, 2FA, and server-side + session revocation (a token stays valid until it expires or the user is deleted). diff --git a/docs/DEMO_SCRIPT.md b/docs/DEMO_SCRIPT.md index 5e09eed..765aa83 100644 --- a/docs/DEMO_SCRIPT.md +++ b/docs/DEMO_SCRIPT.md @@ -42,7 +42,7 @@ DealSentry catches these before the proposal leaves the building." ## 5. Semantic search (45s) - Search "cloud migration" โ€” results rank by *meaning* (pgvector cosine - similarity over Azure OpenAI embeddings), not keywords. Mention the graceful + similarity over AI embeddings), not keywords. Mention the graceful fallback to substring search when embeddings are unavailable. ## 6. CRM integration (45s) @@ -59,14 +59,18 @@ DealSentry catches these before the proposal leaves the building." ## 8. Close (30s) -"React + Express + Supabase + Azure OpenAI, deployed on Render from a Docker +"React + Express + Supabase + Gemini/Azure OpenAI, deployed on Render from a Docker blueprint, CI-tested, with policy enforced in code and AI explaining the why. Everything you saw is in the repo โ€” including the architecture doc." ## Q&A cheat sheet -- **Why no login?** Demo mode by design; the JWT/bcrypt stack is live and - honored when a token is present (`docs/AUTH_QUICKSTART.md`). +- **Why no login?** Demo mode by design. Real multi-user mode ships too: + `AUTH_MODE=login` adds email + password sign-in and per-company data isolation + (`docs/AUTH_QUICKSTART.md`). +- **What if the AI is down?** Analysis falls back to a deterministic rule checker + (discount cap, minimum deal, payment terms, required clauses) and the report + says which engine produced it. - **What stops the AI hallucinating compliance?** Deterministic re-checks in code: discounts clamped, thresholds hardcoded, findings normalized. - **How would you scale it?** Enable RLS + service-role key (already diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 119ec93..299fbd1 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -2,12 +2,15 @@ DealSentry ships as a single Node service: the Express API also serves the built React SPA (on `NODE_ENV=production`). It depends on a Supabase project -(Postgres + storage) and Azure OpenAI. +(Postgres, plus storage if you use document upload) and, optionally, an AI +provider (Google Gemini or Azure OpenAI). Without an AI provider, proposal +analysis still works through the built-in rule checker; only proposal +*generation* and semantic search need one. ## 1. Prerequisites -- A Supabase project (database + a `proposal-files` storage bucket). -- An Azure OpenAI deployment (e.g. `gpt-4o`). +- A Supabase project. +- An AI provider key โ€” a Google Gemini API key, or an Azure OpenAI deployment (e.g. `gpt-4o`). Optional but recommended. - Node 20+ (for non-container runs) or Docker. ## 2. Configure environment @@ -24,8 +27,14 @@ Key variables (see `.env.example` for the full list): |---|---| | `DATABASE_URL` | Supabase Postgres connection string (used by Prisma migrations) | | `SUPABASE_URL`, `SUPABASE_ANON_KEY` | Supabase REST/storage client | -| `AZURE_OPENAI_ENDPOINT`, `OPENAI_API_KEY`, `AZURE_OPENAI_DEPLOYMENT` | AI generation & analysis | -| `NEXTAUTH_SECRET` | JWT signing secret โ€” generate a fresh 32+ byte value | +| `SUPABASE_SERVICE_ROLE_KEY` | Server-side key that keeps working once Row Level Security is on (see ยง6) | +| `GEMINI_API_KEY` (+ optional `GEMINI_MODEL`) | AI generation, analysis and embeddings via Google Gemini โ€” takes precedence | +| `AZURE_OPENAI_ENDPOINT`, `OPENAI_API_KEY`, `AZURE_OPENAI_DEPLOYMENT` | The same via Azure OpenAI, if no Gemini key is set | +| `ANALYSIS_MODE` | `rules` forces the built-in rule checker instead of the AI | +| `AUTH_MODE` | `demo` (default, no sign-in) or `login` (email + password) โ€” see `docs/AUTH_QUICKSTART.md` | +| `ALLOW_SELF_REGISTRATION` | `true` lets people create their own account (login mode) | +| `NEXTAUTH_SECRET` | JWT signing secret โ€” generate a fresh 32+ byte value (required in login mode) | +| `TRUST_PROXY` | Proxy hops to trust for client IPs (default `1` in production, which suits Render) | | `API_PORT` | Server port (default `3001`) | | `PRODUCTION_URL` | Allowed CORS origin in production | @@ -70,12 +79,13 @@ The server serves the API under `/api/*` and the SPA for all other paths. The repo ships a `render.yaml` Blueprint that runs the Dockerfile as a web service. -1. **Rotate secrets first** โ€” the Supabase password, Azure OpenAI key. (`NEXTAUTH_SECRET` - is auto-generated by Render via `generateValue`, so the old one is replaced.) +1. **Rotate secrets first** โ€” the Supabase password and any AI key that was ever shared in plaintext. + (`NEXTAUTH_SECRET` is auto-generated by Render via `generateValue`, so the old one is replaced.) 2. In Render: **New โ†’ Blueprint**, connect this GitHub repo, pick the branch. Render reads `render.yaml` and creates the `dealsentry` service. 3. Fill in the `sync: false` env vars in the dashboard: `DATABASE_URL`, `SUPABASE_URL`, - `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT`, `OPENAI_API_KEY`. + `SUPABASE_ANON_KEY`, and **`GEMINI_API_KEY`** (or `AZURE_OPENAI_ENDPOINT` + `OPENAI_API_KEY`). + Without an AI key the app still runs; analysis uses the rule checker. 4. Deploy. Once it's live, copy the service URL (e.g. `https://dealsentry.onrender.com`) into **both** `PRODUCTION_URL` and `FRONTEND_URL`, then redeploy so CORS + OAuth redirects use the real domain. @@ -97,10 +107,39 @@ curl -s http://localhost:3001/api/health # -> {"status":"ok",...} # On Render: curl -s https://.onrender.com/api/health ``` -Then open `http://localhost:3001`, log in (seeded `admin@dealsentry.ai`), -create a proposal, run analysis, and export a PDF โ€” the PDF path exercises the +Then open `http://localhost:3001` (in the default demo mode you are signed in +automatically as the seeded admin; with `AUTH_MODE=login`, sign in), create a +proposal, run analysis, and export a PDF โ€” the PDF path exercises the containerized Chromium, confirming the image is complete. +## 6. Lock down the database (recommended) + +Supabase serves every table over a REST API that anyone with the project's anon +key can call. Until Row Level Security is enabled, that key alone can read the +`User` table (password hashes) and the `Integration` table (CRM OAuth tokens). +Fix it once the API is using the service-role key: + +1. Copy the `service_role` key (Supabase โ†’ Project Settings โ†’ API) into + `SUPABASE_SERVICE_ROLE_KEY` locally **and** in Render, then redeploy. +2. `npm run check:rls` โ€” must print `ready`. +3. `npx prisma db execute --file prisma/manual/enable_rls.sql` +4. `npm run check:rls -- --verify` โ€” confirms the anon key is locked out. + +Do not run step 3 before steps 1โ€“2: the API would lose access to its database. + +## 7. Known dependency advisories + +`npm audit` still reports advisories whose only fix is a major-version upgrade: +`puppeteer` 21โ†’25 (browser-download and WebSocket helpers), `tailwindcss` 3โ†’4 +(build-time glob/watch helpers), `react-router-dom` 6โ†’7, and the Prisma CLI. +They sit in browser-download and proxy tooling, build-time tooling and the +Prisma CLI. A review of how the app uses them found no route from request input +to the affected code (Chrome is only launched by the PDF exporter, against HTML +the server builds, and Tailwind runs at build time) โ€” but that is a judgement, +not a guarantee. Plan these upgrades (each needs a visual/PDF regression pass) +rather than running `npm audit fix --force`, which would also *downgrade* Prisma +and Mammoth. + ## CI `.github/workflows/ci.yml` runs on every push/PR to `main`: install โ†’ diff --git a/docs/SEMANTIC_SEARCH.md b/docs/SEMANTIC_SEARCH.md index 4a21082..836b13e 100644 --- a/docs/SEMANTIC_SEARCH.md +++ b/docs/SEMANTIC_SEARCH.md @@ -1,8 +1,8 @@ # Semantic Search (Phase 4) -Meaning-based search over proposal content using Azure OpenAI embeddings + -pgvector. Until the setup below is done, the Proposals search box transparently -falls back to title/client substring matching โ€” nothing breaks. +Meaning-based search over proposal content using AI embeddings + pgvector. +Until the setup below is done, the Proposals search box transparently falls +back to title/client substring matching โ€” nothing breaks. ## How it works @@ -10,7 +10,8 @@ falls back to title/client substring matching โ€” nothing breaks. `title + content` and stores it in `Proposal.embedding` (best-effort). - `GET /api/proposals/search?q=...` embeds the query and ranks proposals by cosine similarity via the `match_proposals` Postgres function, scoped to the - caller's company (admins see all). + caller's company (admins see all; in login mode a user with no company sees + only their own proposals). - The frontend (`src/pages/Proposals.tsx`) calls this when the query is โ‰ฅ3 chars and ranks by similarity; if the endpoint reports `available:false`, it uses the substring filter instead. @@ -18,24 +19,43 @@ falls back to title/client substring matching โ€” nothing breaks. Code: `src/api/lib/embeddings.ts`, search route in `src/api/proposals.ts`, `proposalsApi.search` in `src/lib/api-client.ts`. +## Embedding provider + +`src/api/lib/embeddings.ts` picks the provider from the environment, exactly +like chat completions do: + +| Set | Embeddings come from | +| --- | --- | +| `GEMINI_API_KEY` | Google `gemini-embedding-001`, requested at 1536 dimensions (override with `GEMINI_EMBEDDING_MODEL`) | +| otherwise Azure OpenAI vars | the `AZURE_OPENAI_EMBEDDING_DEPLOYMENT` deployment (default `text-embedding-ada-002`, 1536 dimensions) | + +Vectors are normalised to unit length. A response that is not exactly 1536 +numbers is rejected (and search degrades) rather than stored. + +> **Every instance that shares a database must use the same embedding model.** +> Vectors from different models are not comparable, so a table that mixes them +> ranks nonsensically. After switching provider or model, re-embed everything +> with `npm run backfill:embeddings -- --all`. + ## One-time setup -1. **Configure the embedding deployment** in `.env`: - ``` - AZURE_OPENAI_EMBEDDING_DEPLOYMENT="text-embedding-ada-002" - ``` - (Endpoint + key are shared with the existing Azure OpenAI config.) +1. **Configure a provider** in `.env` (`GEMINI_API_KEY=...`, or the Azure variables + including `AZURE_OPENAI_EMBEDDING_DEPLOYMENT`). 2. **Run the SQL migration** against your Supabase Postgres โ€” Supabase Studio โ†’ - SQL editor, or psql. This enables pgvector, adds the `embedding` column + an - index, and creates the `match_proposals` function: - ``` - prisma/manual/semantic_search.sql + SQL editor, or psql. This enables pgvector, adds the `embedding` column, an + HNSW index, and the `match_proposals` function: + ```bash + npx prisma db execute --file prisma/manual/semantic_search.sql ``` + Re-running it is safe, and it replaces an older `ivfflat` index with HNSW + (the ivfflat default probes one list, so on a small table it can return few + or no matches). 3. **Backfill embeddings** for existing proposals: ```bash - npm run backfill:embeddings + npm run backfill:embeddings # only proposals that have none yet + npm run backfill:embeddings -- --all # re-embed everything (after a provider change) ``` 4. Restart the API. New proposals embed automatically; search now ranks by @@ -43,12 +63,12 @@ Code: `src/api/lib/embeddings.ts`, search route in `src/api/proposals.ts`, ## Notes -- `text-embedding-ada-002` โ†’ 1536-dim vectors. If you switch models, update the - dimension in both the SQL (`vector(1536)`) and `EMBEDDING_DIM` in - `src/api/lib/embeddings.ts`. -- The `ivfflat` index `lists` parameter (default 100) should grow roughly with - `rows / 1000` for best recall/speed. +- 1536 dimensions is fixed by the `vector(1536)` column and `EMBEDDING_DIM` in + `src/api/lib/embeddings.ts`. If you switch to a model with a different width, + change both together (and re-run the SQL and a full backfill). +- HNSW needs pgvector โ‰ฅ 0.5 (Supabase ships 0.8). - `Proposal.embedding` is declared in `schema.prisma` as `Unsupported("vector(1536)")` for documentation; the column is actually created by the manual SQL migration (the runtime uses the Supabase REST client, not the Prisma client, for data access). +- Free-tier Gemini keys are rate limited; the backfill pauses 250 ms between calls. diff --git a/render.yaml b/render.yaml index 1b7b680..b7c056f 100644 --- a/render.yaml +++ b/render.yaml @@ -6,8 +6,8 @@ # Free plan (512 MB). Note the trade-offs: # - Spins down after ~15 min idle โ†’ first request after a lull is slow (cold start). # - PDF export (headless Chromium) is the one feature that may OOM at 512 MB even -# with the memory flags in src/api/proposals.ts. If PDF exports fail, the only -# real fix is to bump `plan` to `starter`/`standard`. +# with the memory flags in src/api/lib/proposalPdf.ts (exports run one at a time). +# If PDF exports fail, the only real fix is to bump `plan` to `starter`/`standard`. services: - type: web name: dealsentry @@ -33,6 +33,10 @@ services: # Optional: preferred over the anon key when set (survives enabling RLS). - key: SUPABASE_SERVICE_ROLE_KEY sync: false + # AI provider: set GEMINI_API_KEY, or the two Azure variables below. With neither, + # analysis still works (built-in rule checker); generation and semantic search do not. + - key: GEMINI_API_KEY + sync: false - key: AZURE_OPENAI_ENDPOINT sync: false - key: OPENAI_API_KEY @@ -43,6 +47,12 @@ services: # the first ADMIN in the User table if unset. - key: DEMO_USER_EMAIL value: admin@reviewer.ai + # demo = no sign-in (everyone is the default user). Use "login" for real accounts: + # see docs/AUTH_QUICKSTART.md (needs prisma/manual/multi_user.sql + npm run set-passwords). + - key: AUTH_MODE + value: demo + - key: GEMINI_MODEL + value: gemini-2.5-flash - key: AZURE_OPENAI_DEPLOYMENT value: gpt-4o - key: AZURE_OPENAI_API_VERSION diff --git a/start.bat b/start.bat index 42fa316..f85e312 100644 --- a/start.bat +++ b/start.bat @@ -1,93 +1,93 @@ -@echo off -echo ======================================== -echo DealSentry - Complete Edition -echo ======================================== -echo. -echo Starting application servers... -echo. - -REM Check if Node.js is installed -where node >nul 2>&1 -if %errorlevel% neq 0 ( - echo ERROR: Node.js is not installed or not in PATH - echo Please install Node.js from https://nodejs.org/ - pause - exit /b 1 -) - -REM Check if node_modules exists -if not exist "node_modules" ( - echo WARNING: node_modules folder not found - echo Installing dependencies... - call npm install - if %errorlevel% neq 0 ( - echo ERROR: Failed to install dependencies - pause - exit /b 1 - ) -) - -REM Check if port 3001 is already in use (API server) -netstat -ano | findstr ":3001" >nul 2>&1 -if %errorlevel% equ 0 ( - echo WARNING: Port 3001 is already in use - echo Attempting to stop existing process... - for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3001') do ( - taskkill /F /PID %%a >nul 2>&1 - ) - timeout /t 2 /nobreak >nul -) - -REM Check if port 8080 is already in use (Frontend dev server) -netstat -ano | findstr ":8080" >nul 2>&1 -if %errorlevel% equ 0 ( - echo WARNING: Port 8080 is already in use - echo Attempting to stop existing process... - for /f "tokens=5" %%a in ('netstat -ano ^| findstr :8080') do ( - taskkill /F /PID %%a >nul 2>&1 - ) - timeout /t 2 /nobreak >nul -) - -echo. -echo Backend API: http://localhost:3001 -echo Frontend App: http://localhost:8080 -echo. -echo Login Credentials: -echo Admin: admin@dealsentry.ai / demo -echo Test Users: test1@dealsentry.ai through test5@dealsentry.ai / demo -echo. -echo ======================================== -echo. - -REM Start backend API server -start "API Server (Port 3001)" cmd /k "echo Starting API Server... && npm run server" -echo Backend API server starting... -timeout /t 5 /nobreak >nul - -REM Verify backend is running before starting frontend -echo Checking if API server started successfully... -curl -s http://localhost:3001/api/health >nul 2>&1 -if %errorlevel% neq 0 ( - echo WARNING: API server may not have started correctly - echo Please check the API Server window for errors - timeout /t 3 /nobreak >nul -) - -REM Start frontend dev server -start "Frontend Dev Server (Port 8080)" cmd /k "echo Starting Frontend Dev Server... && npm run dev" -echo Frontend dev server starting... - -echo. -echo ======================================== -echo Both servers are starting up! -echo. -echo If you see errors: -echo 1. Check the server windows for error messages -echo 2. Make sure ports 3001 and 8080 are not in use -echo 3. Run 'npm install' if you haven't already -echo. -echo Press any key to exit this window -echo (The servers will continue running in their own windows) -echo ======================================== -pause >nul +@echo off +echo ======================================== +echo DealSentry - Complete Edition +echo ======================================== +echo. +echo Starting application servers... +echo. + +REM Check if Node.js is installed +where node >nul 2>&1 +if %errorlevel% neq 0 ( + echo ERROR: Node.js is not installed or not in PATH + echo Please install Node.js from https://nodejs.org/ + pause + exit /b 1 +) + +REM Check if node_modules exists +if not exist "node_modules" ( + echo WARNING: node_modules folder not found + echo Installing dependencies... + call npm install + if %errorlevel% neq 0 ( + echo ERROR: Failed to install dependencies + pause + exit /b 1 + ) +) + +REM Check if port 3001 is already in use (API server) +netstat -ano | findstr ":3001" >nul 2>&1 +if %errorlevel% equ 0 ( + echo WARNING: Port 3001 is already in use + echo Attempting to stop existing process... + for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3001') do ( + taskkill /F /PID %%a >nul 2>&1 + ) + timeout /t 2 /nobreak >nul +) + +REM Check if port 8080 is already in use (Frontend dev server) +netstat -ano | findstr ":8080" >nul 2>&1 +if %errorlevel% equ 0 ( + echo WARNING: Port 8080 is already in use + echo Attempting to stop existing process... + for /f "tokens=5" %%a in ('netstat -ano ^| findstr :8080') do ( + taskkill /F /PID %%a >nul 2>&1 + ) + timeout /t 2 /nobreak >nul +) + +echo. +echo Backend API: http://localhost:3001 +echo Frontend App: http://localhost:8080 +echo. +echo Login Credentials: +echo No sign-in in the default demo mode (acts as the seeded admin, admin@dealsentry.ai). +echo For email + password accounts set AUTH_MODE=login - see docs/AUTH_QUICKSTART.md +echo. +echo ======================================== +echo. + +REM Start backend API server +start "API Server (Port 3001)" cmd /k "echo Starting API Server... && npm run server" +echo Backend API server starting... +timeout /t 5 /nobreak >nul + +REM Verify backend is running before starting frontend +echo Checking if API server started successfully... +curl -s http://localhost:3001/api/health >nul 2>&1 +if %errorlevel% neq 0 ( + echo WARNING: API server may not have started correctly + echo Please check the API Server window for errors + timeout /t 3 /nobreak >nul +) + +REM Start frontend dev server +start "Frontend Dev Server (Port 8080)" cmd /k "echo Starting Frontend Dev Server... && npm run dev" +echo Frontend dev server starting... + +echo. +echo ======================================== +echo Both servers are starting up! +echo. +echo If you see errors: +echo 1. Check the server windows for error messages +echo 2. Make sure ports 3001 and 8080 are not in use +echo 3. Run 'npm install' if you haven't already +echo. +echo Press any key to exit this window +echo (The servers will continue running in their own windows) +echo ======================================== +pause >nul