From 466fcd402674b5514d3ab2aa5366f91220d3a3d4 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 24 Nov 2026 13:24:14 +0100 Subject: [PATCH 1/5] chore(backend): ESLint and Prettier like in the frontend, and TypeScript 6 for typescript-eslint (#112) --- backend/.gitattributes | 2 + backend/.prettierignore | 6 + backend/.prettierrc | 6 + backend/eslint.config.mjs | 19 + backend/package-lock.json | 1578 +++++++++++++++++++++++++++++-------- backend/package.json | 11 +- 6 files changed, 1302 insertions(+), 320 deletions(-) create mode 100644 backend/.gitattributes create mode 100644 backend/.prettierignore create mode 100644 backend/.prettierrc create mode 100644 backend/eslint.config.mjs diff --git a/backend/.gitattributes b/backend/.gitattributes new file mode 100644 index 0000000..627ba21 --- /dev/null +++ b/backend/.gitattributes @@ -0,0 +1,2 @@ +# Always LF in the working copy, also on Windows, so Prettier (endOfLine: lf) agrees everywhere. +* text=auto eol=lf \ No newline at end of file diff --git a/backend/.prettierignore b/backend/.prettierignore new file mode 100644 index 0000000..db668f8 --- /dev/null +++ b/backend/.prettierignore @@ -0,0 +1,6 @@ +node_modules +package-lock.json +dist +coverage +# X-Wines test data +data \ No newline at end of file diff --git a/backend/.prettierrc b/backend/.prettierrc new file mode 100644 index 0000000..29b814f --- /dev/null +++ b/backend/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": true, + "semi": true, + "printWidth": 100, + "trailingComma": "all" +} \ No newline at end of file diff --git a/backend/eslint.config.mjs b/backend/eslint.config.mjs new file mode 100644 index 0000000..7f3f620 --- /dev/null +++ b/backend/eslint.config.mjs @@ -0,0 +1,19 @@ +import js from '@eslint/js'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; +import { defineConfig, globalIgnores } from 'eslint/config'; +import prettier from 'eslint-config-prettier'; + +// The same rules as the frontend, without the React ones. .mjs because package.json says +// "commonjs", and this file uses import (the same reason vitest.config is .mts). +export default defineConfig([ + globalIgnores(['dist', 'coverage']), + { + files: ['**/*.{ts,mts}'], + extends: [js.configs.recommended, tseslint.configs.recommended], + languageOptions: { + globals: globals.node, + }, + }, + prettier, +]); \ No newline at end of file diff --git a/backend/package-lock.json b/backend/package-lock.json index 5af7aa2..1d23ada 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -17,13 +17,19 @@ "pg": "^8.23.1" }, "devDependencies": { + "@eslint/js": "^10.0.1", "@types/express": "^5.0.6", "@types/node": "^26.6.5", "@types/pg": "^8.23.1", "dotenv": "^18.0.10", + "eslint": "^10.15.0", + "eslint-config-prettier": "^10.1.8", + "globals": "^17.14.0", "node-pg-migrate": "^9.0.0", + "prettier": "^3.10.1", "tsx": "^4.23.15", - "typescript": "^7.0.2", + "typescript": "~6.0.2", + "typescript-eslint": "^8.74.0", "vitest": "^5.0.5" } }, @@ -277,6 +283,30 @@ "express": "^5.0.0" } }, + "node_modules/@cacheable/memory": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.5.0", + "@keyv/bigmap": "^1.3.1", + "hookified": "^1.15.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.5.1", + "keyv": "^5.6.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -719,6 +749,151 @@ "node": ">=18" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.6", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^11.0.5" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, "node_modules/@graphql-tools/merge": { "version": "9.2.8", "resolved": "https://registry.npmjs.org/@graphql-tools/merge/-/merge-9.2.8.tgz", @@ -779,6 +954,79 @@ "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, + "node_modules/@humanfs/core": { + "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.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.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", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -807,6 +1055,30 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, "node_modules/@oxc-project/types": { "version": "0.155.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", @@ -1198,6 +1470,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -1237,6 +1516,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/long": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", @@ -1300,344 +1586,257 @@ "@types/node": "*" } }, - "node_modules/@typescript/typescript-aix-ppc64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", - "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", - "cpu": [ - "ppc64" - ], + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz", + "integrity": "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "aix" - ], + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/type-utils": "8.74.0", + "@typescript-eslint/utils": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.74.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-darwin-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", - "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.16", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz", + "integrity": "sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], + "license": "MIT", "engines": { - "node": ">=16.20.0" + "node": ">= 4" } }, - "node_modules/@typescript/typescript-darwin-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", - "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/parser": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.74.0.tgz", + "integrity": "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "debug": "^4.4.3" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-freebsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", - "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/project-service": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.74.0.tgz", + "integrity": "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "freebsd" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.74.0", + "@typescript-eslint/types": "^8.74.0", + "debug": "^4.4.3" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-freebsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", - "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.74.0.tgz", + "integrity": "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "freebsd" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript/typescript-linux-arm": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", - "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", - "cpu": [ - "arm" - ], + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.74.0.tgz", + "integrity": "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], + "license": "MIT", "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-linux-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", - "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/type-utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.74.0.tgz", + "integrity": "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-linux-loong64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", - "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-mips64el": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", - "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-ppc64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", - "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-riscv64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", - "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-s390x": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", - "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-linux-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", - "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-netbsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", - "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/types": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.74.0.tgz", + "integrity": "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-netbsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", - "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/@typescript/typescript-openbsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", - "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "openbsd" - ], + "license": "MIT", "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript/typescript-openbsd-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", - "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.74.0.tgz", + "integrity": "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "openbsd" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.74.0", + "@typescript-eslint/tsconfig-utils": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/visitor-keys": "8.74.0", + "debug": "^4.4.3", + "minimatch": "^11.0.1", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", + "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } } }, - "node_modules/@typescript/typescript-sunos-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", - "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "sunos" - ], + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, "engines": { - "node": ">=16.20.0" + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@typescript/typescript-win32-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", - "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/utils": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.74.0.tgz", + "integrity": "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "win32" - ], + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.74.0", + "@typescript-eslint/types": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-win32-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", - "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.74.0.tgz", + "integrity": "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "win32" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.74.0", + "eslint-visitor-keys": "^5.0.0" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" } }, "node_modules/@vitest/mocker": { @@ -1703,6 +1902,46 @@ "node": ">= 0.6" } }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/ansi-regex": { "version": "6.6.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", @@ -1832,6 +2071,20 @@ "node": ">= 0.8" } }, + "node_modules/cacheable": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.2.0", + "@cacheable/utils": "^2.5.0", + "hookified": "^1.15.0", + "keyv": "^5.6.0", + "qified": "^0.10.1" + } + }, "node_modules/call-bind": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", @@ -1973,6 +2226,21 @@ "node": ">=16.0.0" } }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/dataloader": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/dataloader/-/dataloader-2.2.3.tgz", @@ -1996,6 +2264,13 @@ } } }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, "node_modules/define-data-property": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", @@ -2180,6 +2455,197 @@ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", "license": "MIT" }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.15.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "packages/*" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.6", + "@eslint/config-helpers": "^0.7.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.3", + "@humanfs/node": "^0.16.8", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "11.1.5 || >11.1.6 <12", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^11.0.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-prettier": { + "version": "10.1.8", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", + "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "funding": { + "url": "https://opencollective.com/eslint-config-prettier" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -2190,6 +2656,16 @@ "@types/estree": "^1.0.0" } }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", @@ -2252,6 +2728,27 @@ "url": "https://opencollective.com/express" } }, + "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-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2270,6 +2767,16 @@ } } }, + "node_modules/file-entry-cache": { + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^6.1.23" + } + }, "node_modules/finalhandler": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", @@ -2291,6 +2798,42 @@ "url": "https://opencollective.com/express" } }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" + } + }, + "node_modules/flatted": { + "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/for-each": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", @@ -2426,6 +2969,32 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2486,6 +3055,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/hashery": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^1.15.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/hasown": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", @@ -2498,6 +3080,13 @@ "node": ">= 0.4" } }, + "node_modules/hookified": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", + "dev": true, + "license": "MIT" + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -2534,6 +3123,26 @@ "url": "https://opencollective.com/express" } }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -2561,6 +3170,29 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -2588,6 +3220,13 @@ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", "license": "MIT" }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", @@ -2598,6 +3237,44 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -2871,6 +3548,22 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/lodash.sortby": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", @@ -3026,6 +3719,13 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, "node_modules/negotiator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", @@ -3138,6 +3838,56 @@ "wrappy": "1" } }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -3147,6 +3897,26 @@ "node": ">= 0.8" } }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-scurry": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", @@ -3362,6 +4132,32 @@ "node": ">=0.10.0" } }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.1.tgz", + "integrity": "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/proxy-addr": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", @@ -3379,6 +4175,36 @@ "url": "https://opencollective.com/express" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qified": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^2.1.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qified/node_modules/hookified": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", + "dev": true, + "license": "MIT" + }, "node_modules/qs": { "version": "6.17.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", @@ -3509,6 +4335,19 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "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", @@ -3597,6 +4436,29 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/side-channel": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", @@ -3799,6 +4661,19 @@ "node": ">=0.6" } }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -3824,6 +4699,19 @@ "fsevents": "~2.3.3" } }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/type-is": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", @@ -3870,38 +4758,41 @@ } }, "node_modules/typescript": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", - "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", "bin": { - "tsc": "bin/tsc" + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.74.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.74.0.tgz", + "integrity": "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.74.0", + "@typescript-eslint/parser": "8.74.0", + "@typescript-eslint/typescript-estree": "8.74.0", + "@typescript-eslint/utils": "8.74.0" }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.0.2", - "@typescript/typescript-darwin-arm64": "7.0.2", - "@typescript/typescript-darwin-x64": "7.0.2", - "@typescript/typescript-freebsd-arm64": "7.0.2", - "@typescript/typescript-freebsd-x64": "7.0.2", - "@typescript/typescript-linux-arm": "7.0.2", - "@typescript/typescript-linux-arm64": "7.0.2", - "@typescript/typescript-linux-loong64": "7.0.2", - "@typescript/typescript-linux-mips64el": "7.0.2", - "@typescript/typescript-linux-ppc64": "7.0.2", - "@typescript/typescript-linux-riscv64": "7.0.2", - "@typescript/typescript-linux-s390x": "7.0.2", - "@typescript/typescript-linux-x64": "7.0.2", - "@typescript/typescript-netbsd-arm64": "7.0.2", - "@typescript/typescript-netbsd-x64": "7.0.2", - "@typescript/typescript-openbsd-arm64": "7.0.2", - "@typescript/typescript-openbsd-x64": "7.0.2", - "@typescript/typescript-sunos-x64": "7.0.2", - "@typescript/typescript-win32-arm64": "7.0.2", - "@typescript/typescript-win32-x64": "7.0.2" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, "node_modules/undici-types": { @@ -3920,6 +4811,16 @@ "node": ">= 0.8" } }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -4100,6 +5001,22 @@ "node": ">=18" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/which-typed-array": { "version": "1.1.24", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", @@ -4134,6 +5051,16 @@ "node": ">=20.11" } }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/wrap-ansi": { "version": "9.0.2", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", @@ -4204,6 +5131,19 @@ "engines": { "node": "^20.19.0 || ^22.12.0 || >=23" } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/backend/package.json b/backend/package.json index 82e93f2..ce6dfb1 100644 --- a/backend/package.json +++ b/backend/package.json @@ -10,6 +10,9 @@ "dev": "tsx watch src/server.ts", "start": "tsx src/server.ts", "typecheck": "tsc --noEmit", + "lint": "eslint .", + "format": "prettier --write .", + "format:check": "prettier --check .", "test": "vitest run", "db:seed:test": "tsx src/scripts/seed-xwines.ts data/xwines-test/wines.csv data/xwines-test/ratings.csv", "db:seed:demo": "tsx src/scripts/seed-demo-user.ts", @@ -26,13 +29,19 @@ "pg": "^8.23.1" }, "devDependencies": { + "@eslint/js": "^10.0.1", "@types/express": "^5.0.6", "@types/node": "^26.6.5", "@types/pg": "^8.23.1", "dotenv": "^18.0.10", + "eslint": "^10.15.0", + "eslint-config-prettier": "^10.1.8", + "globals": "^17.14.0", "node-pg-migrate": "^9.0.0", + "prettier": "^3.10.1", "tsx": "^4.23.15", - "typescript": "^7.0.2", + "typescript": "~6.0.2", + "typescript-eslint": "^8.74.0", "vitest": "^5.0.5" } } From c49433d13fc18bc48f51b76b7064e2ebd708834e Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 24 Nov 2026 13:26:03 +0100 Subject: [PATCH 2/5] style(backend): format with Prettier (#112) --- backend/.prettierrc | 2 +- backend/eslint.config.mjs | 2 +- backend/src/auth/auth-api.test.ts | 294 ++++++------- backend/src/auth/auth-context.ts | 82 ++-- backend/src/auth/auth-service.test.ts | 242 ++++++----- backend/src/auth/auth-service.ts | 166 ++++---- backend/src/auth/cookies.test.ts | 53 +-- backend/src/auth/cookies.ts | 45 +- backend/src/auth/credentials.test.ts | 88 ++-- backend/src/auth/credentials.ts | 62 ++- backend/src/auth/errors.ts | 36 +- backend/src/auth/password.test.ts | 64 +-- backend/src/auth/password.ts | 83 ++-- backend/src/auth/rate-limit.test.ts | 56 +-- backend/src/auth/rate-limit.ts | 80 ++-- backend/src/auth/resolvers.ts | 42 +- backend/src/auth/session-token.test.ts | 40 +- backend/src/auth/session-token.ts | 6 +- backend/src/auth/user-store.db.test.ts | 106 ++--- backend/src/auth/user-store.ts | 114 ++--- backend/src/connection.test.ts | 70 ++-- backend/src/connection.ts | 56 +-- backend/src/context.ts | 22 +- backend/src/csv.test.ts | 26 +- backend/src/csv.ts | 88 ++-- backend/src/db-errors.test.ts | 25 +- backend/src/db-errors.ts | 8 +- backend/src/db.ts | 28 +- backend/src/demo/demo-user.db.test.ts | 169 ++++---- backend/src/demo/demo-user.ts | 98 ++--- backend/src/lists/lists-api.db.test.ts | 550 +++++++++++++------------ backend/src/lists/resolvers.ts | 147 +++---- backend/src/lists/wine-lists.ts | 149 ++++--- backend/src/loaders.ts | 200 ++++----- backend/src/rating-stats.ts | 2 +- backend/src/resolvers.ts | 393 +++++++++--------- backend/src/review-api.db.test.ts | 432 ++++++++++--------- backend/src/review-input.test.ts | 90 ++-- backend/src/review-input.ts | 54 +-- backend/src/scripts/seed-demo-user.ts | 34 +- backend/src/scripts/seed-xwines.ts | 84 ++-- backend/src/server.ts | 64 +-- backend/src/test/graphql-test-api.ts | 101 ++--- backend/src/test/memory-user-store.ts | 92 ++--- backend/src/wine-query.test.ts | 110 ++--- backend/src/wine-query.ts | 125 +++--- backend/src/xwines-parse.test.ts | 30 +- backend/src/xwines-parse.ts | 26 +- backend/tsconfig.json | 2 +- backend/vitest.config.mts | 14 +- 50 files changed, 2584 insertions(+), 2368 deletions(-) diff --git a/backend/.prettierrc b/backend/.prettierrc index 29b814f..521e271 100644 --- a/backend/.prettierrc +++ b/backend/.prettierrc @@ -3,4 +3,4 @@ "semi": true, "printWidth": 100, "trailingComma": "all" -} \ No newline at end of file +} diff --git a/backend/eslint.config.mjs b/backend/eslint.config.mjs index 7f3f620..280dd48 100644 --- a/backend/eslint.config.mjs +++ b/backend/eslint.config.mjs @@ -16,4 +16,4 @@ export default defineConfig([ }, }, prettier, -]); \ No newline at end of file +]); diff --git a/backend/src/auth/auth-api.test.ts b/backend/src/auth/auth-api.test.ts index 88f6f85..f998477 100644 --- a/backend/src/auth/auth-api.test.ts +++ b/backend/src/auth/auth-api.test.ts @@ -19,157 +19,171 @@ const ME = `query Me { me { ${USER_FIELDS} } }`; const CREDENTIALS = { username: 'ola_n', password: 'langt-nok-passord' }; function setup() { - const { store, users } = createMemoryUserStore(); - const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); - const server = new ApolloServer<{ auth: AuthContext }>({ - typeDefs: [typeDefs, authTypeDefs], - resolvers: authResolvers, - }); - - /** Like a browser: keeps the cookie the server sets and sends it with the next request. */ - function createBrowser() { - let cookie: string | undefined; - const jar: CookieJar = { - setSession: (token) => (cookie = token), - clearSession: () => (cookie = undefined), - }; - - async function request(query: string, variables?: Record) { - const response = await server.executeOperation( - { query, variables }, - { contextValue: { auth: createAuthContext(service, cookie, jar) } }, - ); - if (response.body.kind !== 'single') throw new Error('Expected a single result'); - return response.body.singleResult; - } - - return { request, cookie: () => cookie, setCookie: (value: string) => (cookie = value) }; + const { store, users } = createMemoryUserStore(); + const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); + const server = new ApolloServer<{ auth: AuthContext }>({ + typeDefs: [typeDefs, authTypeDefs], + resolvers: authResolvers, + }); + + /** Like a browser: keeps the cookie the server sets and sends it with the next request. */ + function createBrowser() { + let cookie: string | undefined; + const jar: CookieJar = { + setSession: (token) => (cookie = token), + clearSession: () => (cookie = undefined), + }; + + async function request(query: string, variables?: Record) { + const response = await server.executeOperation( + { query, variables }, + { contextValue: { auth: createAuthContext(service, cookie, jar) } }, + ); + if (response.body.kind !== 'single') throw new Error('Expected a single result'); + return response.body.singleResult; } - return { createBrowser, users }; + return { request, cookie: () => cookie, setCookie: (value: string) => (cookie = value) }; + } + + return { createBrowser, users }; } const codeOf = (result: { errors?: readonly { extensions?: Record }[] }) => - result.errors?.[0]?.extensions?.code; + result.errors?.[0]?.extensions?.code; describe('auth API', () => { - it('me is null for a visitor without a cookie', async () => { - const browser = setup().createBrowser(); - const result = await browser.request(ME); - expect(result.errors).toBeUndefined(); - expect(result.data).toEqual({ me: null }); - }); - - it('register sets a cookie, and me then returns the new user', async () => { - const browser = setup().createBrowser(); - const registered = await browser.request(REGISTER, { input: CREDENTIALS }); - expect(registered.data?.register).toMatchObject({ id: expect.any(String), username: 'ola_n' }); - expect(browser.cookie()).toBeDefined(); - - const me = await browser.request(ME); - expect(me.data?.me).toEqual(registered.data?.register); - }); - - it('returns createdAt as an ISO date', async () => { - const browser = setup().createBrowser(); - const result = await browser.request(REGISTER, { input: CREDENTIALS }); - const { createdAt } = result.data?.register as { createdAt: string }; - expect(new Date(createdAt).toISOString()).toBe(createdAt); - }); - - it('the schema has no field that can expose the password hash', async () => { - const browser = setup().createBrowser(); - const result = await browser.request(`query { me { passwordHash } }`); - expect(result.errors?.[0]?.message).toMatch(/Cannot query field "passwordHash"/); - }); - - it('login works from another browser, and both are logged in', async () => { - const { createBrowser } = setup(); - const laptop = createBrowser(); - const phone = createBrowser(); - await laptop.request(REGISTER, { input: CREDENTIALS }); - - const login = await phone.request(LOGIN, { input: CREDENTIALS }); - expect(login.data?.login).toMatchObject({ username: 'ola_n' }); - expect(phone.cookie()).not.toBe(laptop.cookie()); - expect((await laptop.request(ME)).data?.me).not.toBeNull(); - expect((await phone.request(ME)).data?.me).not.toBeNull(); - }); - - it('logout clears the cookie and ends only that session', async () => { - const { createBrowser } = setup(); - const laptop = createBrowser(); - const phone = createBrowser(); - await laptop.request(REGISTER, { input: CREDENTIALS }); - await phone.request(LOGIN, { input: CREDENTIALS }); - - expect((await phone.request(LOGOUT)).data).toEqual({ logout: true }); - expect(phone.cookie()).toBeUndefined(); - expect((await phone.request(ME)).data).toEqual({ me: null }); - expect((await laptop.request(ME)).data?.me).not.toBeNull(); - }); - - it('an old cookie stops working after logging in again', async () => { - const browser = setup().createBrowser(); - await browser.request(REGISTER, { input: CREDENTIALS }); - const oldCookie = browser.cookie(); - await browser.request(LOGIN, { input: CREDENTIALS }); - expect(browser.cookie()).not.toBe(oldCookie); - }); - - it('logout without a session still returns true', async () => { - const browser = setup().createBrowser(); - expect((await browser.request(LOGOUT)).data).toEqual({ logout: true }); - }); - - it.each([ - [{ username: 'x', password: 'langt-nok-passord' }, 'username', 'USERNAME_TOO_SHORT'], - [{ username: 'ola nordmann', password: 'langt-nok-passord' }, 'username', 'USERNAME_INVALID_CHARACTERS'], - [{ username: 'ola_n', password: 'kort' }, 'password', 'PASSWORD_TOO_SHORT'], - ])('register rejects %j with field and reason', async (input, field, reason) => { - const { createBrowser, users } = setup(); - const browser = createBrowser(); - const result = await browser.request(REGISTER, { input }); - expect(result.errors?.[0]?.extensions).toMatchObject({ code: 'BAD_USER_INPUT', field, reason }); - expect(browser.cookie()).toBeUndefined(); - expect(users).toHaveLength(0); + it('me is null for a visitor without a cookie', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(ME); + expect(result.errors).toBeUndefined(); + expect(result.data).toEqual({ me: null }); + }); + + it('register sets a cookie, and me then returns the new user', async () => { + const browser = setup().createBrowser(); + const registered = await browser.request(REGISTER, { input: CREDENTIALS }); + expect(registered.data?.register).toMatchObject({ id: expect.any(String), username: 'ola_n' }); + expect(browser.cookie()).toBeDefined(); + + const me = await browser.request(ME); + expect(me.data?.me).toEqual(registered.data?.register); + }); + + it('returns createdAt as an ISO date', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(REGISTER, { input: CREDENTIALS }); + const { createdAt } = result.data?.register as { createdAt: string }; + expect(new Date(createdAt).toISOString()).toBe(createdAt); + }); + + it('the schema has no field that can expose the password hash', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(`query { me { passwordHash } }`); + expect(result.errors?.[0]?.message).toMatch(/Cannot query field "passwordHash"/); + }); + + it('login works from another browser, and both are logged in', async () => { + const { createBrowser } = setup(); + const laptop = createBrowser(); + const phone = createBrowser(); + await laptop.request(REGISTER, { input: CREDENTIALS }); + + const login = await phone.request(LOGIN, { input: CREDENTIALS }); + expect(login.data?.login).toMatchObject({ username: 'ola_n' }); + expect(phone.cookie()).not.toBe(laptop.cookie()); + expect((await laptop.request(ME)).data?.me).not.toBeNull(); + expect((await phone.request(ME)).data?.me).not.toBeNull(); + }); + + it('logout clears the cookie and ends only that session', async () => { + const { createBrowser } = setup(); + const laptop = createBrowser(); + const phone = createBrowser(); + await laptop.request(REGISTER, { input: CREDENTIALS }); + await phone.request(LOGIN, { input: CREDENTIALS }); + + expect((await phone.request(LOGOUT)).data).toEqual({ logout: true }); + expect(phone.cookie()).toBeUndefined(); + expect((await phone.request(ME)).data).toEqual({ me: null }); + expect((await laptop.request(ME)).data?.me).not.toBeNull(); + }); + + it('an old cookie stops working after logging in again', async () => { + const browser = setup().createBrowser(); + await browser.request(REGISTER, { input: CREDENTIALS }); + const oldCookie = browser.cookie(); + await browser.request(LOGIN, { input: CREDENTIALS }); + expect(browser.cookie()).not.toBe(oldCookie); + }); + + it('logout without a session still returns true', async () => { + const browser = setup().createBrowser(); + expect((await browser.request(LOGOUT)).data).toEqual({ logout: true }); + }); + + it.each([ + [{ username: 'x', password: 'langt-nok-passord' }, 'username', 'USERNAME_TOO_SHORT'], + [ + { username: 'ola nordmann', password: 'langt-nok-passord' }, + 'username', + 'USERNAME_INVALID_CHARACTERS', + ], + [{ username: 'ola_n', password: 'kort' }, 'password', 'PASSWORD_TOO_SHORT'], + ])('register rejects %j with field and reason', async (input, field, reason) => { + const { createBrowser, users } = setup(); + const browser = createBrowser(); + const result = await browser.request(REGISTER, { input }); + expect(result.errors?.[0]?.extensions).toMatchObject({ code: 'BAD_USER_INPUT', field, reason }); + expect(browser.cookie()).toBeUndefined(); + expect(users).toHaveLength(0); + }); + + it('register rejects a taken username', async () => { + const { createBrowser } = setup(); + await createBrowser().request(REGISTER, { input: CREDENTIALS }); + const result = await createBrowser().request(REGISTER, { + input: { ...CREDENTIALS, username: 'OLA_N' }, }); - - it('register rejects a taken username', async () => { - const { createBrowser } = setup(); - await createBrowser().request(REGISTER, { input: CREDENTIALS }); - const result = await createBrowser().request(REGISTER, { input: { ...CREDENTIALS, username: 'OLA_N' } }); - expect(codeOf(result)).toBe('USERNAME_TAKEN'); - }); - - it('login with a wrong password gives INVALID_CREDENTIALS and no cookie', async () => { - const { createBrowser } = setup(); - await createBrowser().request(REGISTER, { input: CREDENTIALS }); - const browser = createBrowser(); - const result = await browser.request(LOGIN, { input: { ...CREDENTIALS, password: 'feil-passord' } }); - expect(codeOf(result)).toBe('INVALID_CREDENTIALS'); - expect(browser.cookie()).toBeUndefined(); - }); - - it('a forged or changed cookie is treated as logged out', async () => { - const { createBrowser } = setup(); - const owner = createBrowser(); - await owner.request(REGISTER, { input: CREDENTIALS }); - const real = owner.cookie()!; - - const attacker = createBrowser(); - for (const forged of [`${real.slice(0, -1)}${real.endsWith('A') ? 'B' : 'A'}`, 'not-a-token', '']) { - attacker.setCookie(forged); - expect((await attacker.request(ME)).data).toEqual({ me: null }); - } + expect(codeOf(result)).toBe('USERNAME_TAKEN'); + }); + + it('login with a wrong password gives INVALID_CREDENTIALS and no cookie', async () => { + const { createBrowser } = setup(); + await createBrowser().request(REGISTER, { input: CREDENTIALS }); + const browser = createBrowser(); + const result = await browser.request(LOGIN, { + input: { ...CREDENTIALS, password: 'feil-passord' }, }); + expect(codeOf(result)).toBe('INVALID_CREDENTIALS'); + expect(browser.cookie()).toBeUndefined(); + }); + + it('a forged or changed cookie is treated as logged out', async () => { + const { createBrowser } = setup(); + const owner = createBrowser(); + await owner.request(REGISTER, { input: CREDENTIALS }); + const real = owner.cookie()!; + + const attacker = createBrowser(); + for (const forged of [ + `${real.slice(0, -1)}${real.endsWith('A') ? 'B' : 'A'}`, + 'not-a-token', + '', + ]) { + attacker.setCookie(forged); + expect((await attacker.request(ME)).data).toEqual({ me: null }); + } + }); }); describe('requireUser', () => { - it('throws UNAUTHENTICATED without a session, for features that need a logged-in user', async () => { - const { store } = createMemoryUserStore(); - const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); - const auth = createAuthContext(service, undefined, { setSession() {}, clearSession() {} }); - await expect(auth.requireUser()).rejects.toMatchObject({ extensions: { code: 'UNAUTHENTICATED' } }); + it('throws UNAUTHENTICATED without a session, for features that need a logged-in user', async () => { + const { store } = createMemoryUserStore(); + const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); + const auth = createAuthContext(service, undefined, { setSession() {}, clearSession() {} }); + await expect(auth.requireUser()).rejects.toMatchObject({ + extensions: { code: 'UNAUTHENTICATED' }, }); + }); }); diff --git a/backend/src/auth/auth-context.ts b/backend/src/auth/auth-context.ts index 6315fbe..54a7585 100644 --- a/backend/src/auth/auth-context.ts +++ b/backend/src/auth/auth-context.ts @@ -6,45 +6,49 @@ import type { CredentialsInput } from './credentials'; import { AuthErrorCode, authError } from './errors'; export interface AuthContext { - /** The logged-in user, or null. Looked up at most once per request, and only if a resolver asks. */ - currentUser(): Promise; - /** The logged-in user, or an UNAUTHENTICATED error. Use this in resolvers for favourites, reviews and so on. */ - requireUser(): Promise; - register(input: CredentialsInput): Promise; - login(input: CredentialsInput): Promise; - logout(): Promise; + /** The logged-in user, or null. Looked up at most once per request, and only if a resolver asks. */ + currentUser(): Promise; + /** The logged-in user, or an UNAUTHENTICATED error. Use this in resolvers for favourites, reviews and so on. */ + requireUser(): Promise; + register(input: CredentialsInput): Promise; + login(input: CredentialsInput): Promise; + logout(): Promise; } -export function createAuthContext(service: AuthService, token: string | undefined, cookies: CookieJar): AuthContext { - let current: Promise | undefined; - - const currentUser = () => (current ??= service.userForToken(token)); - - async function signIn(start: () => Promise): Promise { - const { user, session } = await start(); - // A new login replaces the old session in this browser, so an old token stops working. - await service.logout(token); - cookies.setSession(session.token, session.expiresAt); - current = Promise.resolve(user); - return user; - } - - return { - currentUser, - - async requireUser() { - const user = await currentUser(); - if (!user) throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); - return user; - }, - - register: (input) => signIn(() => service.register(input)), - login: (input) => signIn(() => service.login(input)), - - async logout() { - await service.logout(token); - cookies.clearSession(); - current = Promise.resolve(null); - }, - }; +export function createAuthContext( + service: AuthService, + token: string | undefined, + cookies: CookieJar, +): AuthContext { + let current: Promise | undefined; + + const currentUser = () => (current ??= service.userForToken(token)); + + async function signIn(start: () => Promise): Promise { + const { user, session } = await start(); + // A new login replaces the old session in this browser, so an old token stops working. + await service.logout(token); + cookies.setSession(session.token, session.expiresAt); + current = Promise.resolve(user); + return user; + } + + return { + currentUser, + + async requireUser() { + const user = await currentUser(); + if (!user) throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + return user; + }, + + register: (input) => signIn(() => service.register(input)), + login: (input) => signIn(() => service.login(input)), + + async logout() { + await service.logout(token); + cookies.clearSession(); + current = Promise.resolve(null); + }, + }; } diff --git a/backend/src/auth/auth-service.test.ts b/backend/src/auth/auth-service.test.ts index ab28675..426e311 100644 --- a/backend/src/auth/auth-service.test.ts +++ b/backend/src/auth/auth-service.test.ts @@ -8,131 +8,145 @@ const FAST = { N: 1024, r: 8, p: 1 }; const CREDENTIALS = { username: 'Kari', password: 'langt-nok-passord' }; function setup(options: AuthServiceOptions = {}) { - let time = new Date('2026-11-12T12:00:00Z'); - const now = () => time; - const memory = createMemoryUserStore(now); - const service = createAuthService(memory.store, { scryptParams: FAST, now, ...options }); - return { ...memory, service, advanceDays: (days: number) => (time = new Date(time.getTime() + days * 86_400_000)) }; + let time = new Date('2026-11-12T12:00:00Z'); + const now = () => time; + const memory = createMemoryUserStore(now); + const service = createAuthService(memory.store, { scryptParams: FAST, now, ...options }); + return { + ...memory, + service, + advanceDays: (days: number) => (time = new Date(time.getTime() + days * 86_400_000)), + }; } /** The error code, so tests do not depend on the developer message. */ async function codeOf(promise: Promise) { - try { - await promise; - } catch (error) { - return (error as { extensions?: { code?: string } }).extensions?.code; - } - return undefined; + try { + await promise; + } catch (error) { + return (error as { extensions?: { code?: string } }).extensions?.code; + } + return undefined; } describe('register', () => { - it('creates a user with a generated id and a lowercase username', async () => { - const { service } = setup(); - const { user } = await service.register(CREDENTIALS); - expect(user).toMatchObject({ id: expect.any(Number), username: 'kari' }); - }); - - it('stores a hash, never the password', async () => { - const { service, users } = setup(); - await service.register(CREDENTIALS); - expect(users[0].passwordHash).toMatch(/^scrypt\$/); - expect(users[0].passwordHash).not.toContain(CREDENTIALS.password); - }); - - it('does not return the password hash', async () => { - const { service } = setup(); - const { user } = await service.register(CREDENTIALS); - expect(Object.keys(user).sort()).toEqual(['createdAt', 'id', 'username']); - }); - - it('logs the user in, and only the token hash is stored', async () => { - const { service, sessions } = setup(); - const { user, session } = await service.register(CREDENTIALS); - expect(await service.userForToken(session.token)).toEqual(user); - expect([...sessions.keys()]).toEqual([hashSessionToken(session.token).toString('hex')]); - }); - - it('rejects a taken username, also with other casing', async () => { - const { service } = setup(); - await service.register(CREDENTIALS); - expect(await codeOf(service.register({ ...CREDENTIALS, username: 'KARI' }))).toBe('USERNAME_TAKEN'); - }); - - it('validates the input before anything is stored', async () => { - const { service, users } = setup(); - expect(await codeOf(service.register({ username: 'k', password: 'kort' }))).toBe('BAD_USER_INPUT'); - expect(users).toHaveLength(0); - }); + it('creates a user with a generated id and a lowercase username', async () => { + const { service } = setup(); + const { user } = await service.register(CREDENTIALS); + expect(user).toMatchObject({ id: expect.any(Number), username: 'kari' }); + }); + + it('stores a hash, never the password', async () => { + const { service, users } = setup(); + await service.register(CREDENTIALS); + expect(users[0].passwordHash).toMatch(/^scrypt\$/); + expect(users[0].passwordHash).not.toContain(CREDENTIALS.password); + }); + + it('does not return the password hash', async () => { + const { service } = setup(); + const { user } = await service.register(CREDENTIALS); + expect(Object.keys(user).sort()).toEqual(['createdAt', 'id', 'username']); + }); + + it('logs the user in, and only the token hash is stored', async () => { + const { service, sessions } = setup(); + const { user, session } = await service.register(CREDENTIALS); + expect(await service.userForToken(session.token)).toEqual(user); + expect([...sessions.keys()]).toEqual([hashSessionToken(session.token).toString('hex')]); + }); + + it('rejects a taken username, also with other casing', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.register({ ...CREDENTIALS, username: 'KARI' }))).toBe( + 'USERNAME_TAKEN', + ); + }); + + it('validates the input before anything is stored', async () => { + const { service, users } = setup(); + expect(await codeOf(service.register({ username: 'k', password: 'kort' }))).toBe( + 'BAD_USER_INPUT', + ); + expect(users).toHaveLength(0); + }); }); describe('login', () => { - it('logs in with the right password, ignoring the casing of the username', async () => { - const { service } = setup(); - const registered = await service.register(CREDENTIALS); - const { user } = await service.login({ ...CREDENTIALS, username: ' KARI ' }); - expect(user).toEqual(registered.user); - }); - - it('gives the same error for a wrong password and an unknown username', async () => { - const { service } = setup(); - await service.register(CREDENTIALS); - expect(await codeOf(service.login({ ...CREDENTIALS, password: 'feil-passord' }))).toBe('INVALID_CREDENTIALS'); - expect(await codeOf(service.login({ ...CREDENTIALS, username: 'finnes_ikke' }))).toBe('INVALID_CREDENTIALS'); - }); - - it('rejects a password that is too long without hashing it', async () => { - const { service } = setup(); - await service.register(CREDENTIALS); - expect(await codeOf(service.login({ ...CREDENTIALS, password: 'a'.repeat(10_000) }))).toBe('INVALID_CREDENTIALS'); - }); - - it('gives each login its own session', async () => { - const { service } = setup(); - await service.register(CREDENTIALS); - const first = await service.login(CREDENTIALS); - const second = await service.login(CREDENTIALS); - expect(first.session.token).not.toBe(second.session.token); - }); - - it('pauses a username after too many failures, and the right password is also refused', async () => { - const loginLimiter = createAttemptLimiter({ maxAttempts: 2, windowMs: 60_000 }); - const { service } = setup({ loginLimiter }); - await service.register(CREDENTIALS); - await codeOf(service.login({ ...CREDENTIALS, password: 'feil-1-passord' })); - await codeOf(service.login({ ...CREDENTIALS, password: 'feil-2-passord' })); - expect(await codeOf(service.login(CREDENTIALS))).toBe('TOO_MANY_ATTEMPTS'); - }); - - it('removes expired sessions', async () => { - const { service, sessions, advanceDays } = setup({ sessionDays: 1 }); - await service.register(CREDENTIALS); - advanceDays(2); - await service.login(CREDENTIALS); - expect(sessions.size).toBe(1); - }); + it('logs in with the right password, ignoring the casing of the username', async () => { + const { service } = setup(); + const registered = await service.register(CREDENTIALS); + const { user } = await service.login({ ...CREDENTIALS, username: ' KARI ' }); + expect(user).toEqual(registered.user); + }); + + it('gives the same error for a wrong password and an unknown username', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.login({ ...CREDENTIALS, password: 'feil-passord' }))).toBe( + 'INVALID_CREDENTIALS', + ); + expect(await codeOf(service.login({ ...CREDENTIALS, username: 'finnes_ikke' }))).toBe( + 'INVALID_CREDENTIALS', + ); + }); + + it('rejects a password that is too long without hashing it', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.login({ ...CREDENTIALS, password: 'a'.repeat(10_000) }))).toBe( + 'INVALID_CREDENTIALS', + ); + }); + + it('gives each login its own session', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + const first = await service.login(CREDENTIALS); + const second = await service.login(CREDENTIALS); + expect(first.session.token).not.toBe(second.session.token); + }); + + it('pauses a username after too many failures, and the right password is also refused', async () => { + const loginLimiter = createAttemptLimiter({ maxAttempts: 2, windowMs: 60_000 }); + const { service } = setup({ loginLimiter }); + await service.register(CREDENTIALS); + await codeOf(service.login({ ...CREDENTIALS, password: 'feil-1-passord' })); + await codeOf(service.login({ ...CREDENTIALS, password: 'feil-2-passord' })); + expect(await codeOf(service.login(CREDENTIALS))).toBe('TOO_MANY_ATTEMPTS'); + }); + + it('removes expired sessions', async () => { + const { service, sessions, advanceDays } = setup({ sessionDays: 1 }); + await service.register(CREDENTIALS); + advanceDays(2); + await service.login(CREDENTIALS); + expect(sessions.size).toBe(1); + }); }); describe('sessions', () => { - it('stop working after logout', async () => { - const { service } = setup(); - const { session } = await service.register(CREDENTIALS); - await service.logout(session.token); - expect(await service.userForToken(session.token)).toBeNull(); - }); - - it('expire after the configured number of days', async () => { - const { service, advanceDays } = setup({ sessionDays: 30 }); - const { session } = await service.register(CREDENTIALS); - advanceDays(29); - expect(await service.userForToken(session.token)).not.toBeNull(); - advanceDays(2); - expect(await service.userForToken(session.token)).toBeNull(); - }); - - it('ignore missing and malformed tokens', async () => { - const { service } = setup(); - expect(await service.userForToken(undefined)).toBeNull(); - expect(await service.userForToken('not-a-token')).toBeNull(); - await expect(service.logout('not-a-token')).resolves.toBeUndefined(); - }); + it('stop working after logout', async () => { + const { service } = setup(); + const { session } = await service.register(CREDENTIALS); + await service.logout(session.token); + expect(await service.userForToken(session.token)).toBeNull(); + }); + + it('expire after the configured number of days', async () => { + const { service, advanceDays } = setup({ sessionDays: 30 }); + const { session } = await service.register(CREDENTIALS); + advanceDays(29); + expect(await service.userForToken(session.token)).not.toBeNull(); + advanceDays(2); + expect(await service.userForToken(session.token)).toBeNull(); + }); + + it('ignore missing and malformed tokens', async () => { + const { service } = setup(); + expect(await service.userForToken(undefined)).toBeNull(); + expect(await service.userForToken('not-a-token')).toBeNull(); + await expect(service.logout('not-a-token')).resolves.toBeUndefined(); + }); }); diff --git a/backend/src/auth/auth-service.ts b/backend/src/auth/auth-service.ts index 740d032..910329e 100644 --- a/backend/src/auth/auth-service.ts +++ b/backend/src/auth/auth-service.ts @@ -1,7 +1,12 @@ // Registration, login, logout and "who is this?". Knows nothing about HTTP or GraphQL fields: // it gets a UserStore and returns users and session tokens. import { LOGIN_ATTEMPT_WINDOW_MS, MAX_LOGIN_ATTEMPTS, SESSION_DAYS } from './config'; -import { normalizeUsername, PASSWORD_MAX_LENGTH, validateCredentials, type CredentialsInput } from './credentials'; +import { + normalizeUsername, + PASSWORD_MAX_LENGTH, + validateCredentials, + type CredentialsInput, +} from './credentials'; import { AuthErrorCode, authError } from './errors'; import { DEFAULT_SCRYPT_PARAMS, hashPassword, verifyPassword, type ScryptParams } from './password'; import { createAttemptLimiter, type AttemptLimiter } from './rate-limit'; @@ -10,93 +15,108 @@ import type { UserRecord, UserStore } from './user-store'; /** A user without the password hash. This is all that leaves the auth module. */ export interface PublicUser { - id: number; - username: string; - createdAt: Date; + id: number; + username: string; + createdAt: Date; } export interface Session { - token: string; - expiresAt: Date; + token: string; + expiresAt: Date; } export interface AuthResult { - user: PublicUser; - session: Session; + user: PublicUser; + session: Session; } export interface AuthServiceOptions { - sessionDays?: number; - now?: () => Date; - /** Tests use cheaper parameters so they run fast. */ - scryptParams?: ScryptParams; - loginLimiter?: AttemptLimiter; + sessionDays?: number; + now?: () => Date; + /** Tests use cheaper parameters so they run fast. */ + scryptParams?: ScryptParams; + loginLimiter?: AttemptLimiter; } export type AuthService = ReturnType; const DAY_MS = 24 * 60 * 60 * 1000; -const toPublicUser = ({ id, username, createdAt }: UserRecord): PublicUser => ({ id, username, createdAt }); +const toPublicUser = ({ id, username, createdAt }: UserRecord): PublicUser => ({ + id, + username, + createdAt, +}); export function createAuthService(store: UserStore, options: AuthServiceOptions = {}) { - const { - sessionDays = SESSION_DAYS, - now = () => new Date(), - scryptParams = DEFAULT_SCRYPT_PARAMS, - loginLimiter = createAttemptLimiter({ maxAttempts: MAX_LOGIN_ATTEMPTS, windowMs: LOGIN_ATTEMPT_WINDOW_MS }), - } = options; - - // Compared against when the username does not exist, so a wrong username takes as long - // as a wrong password and the response time does not reveal which usernames exist. - let dummyHash: Promise | undefined; - const getDummyHash = () => (dummyHash ??= hashPassword('not-a-real-password', scryptParams)); - - async function startSession(userId: number): Promise { - const token = createSessionToken(); - const expiresAt = new Date(now().getTime() + sessionDays * DAY_MS); - await store.createSession(hashSessionToken(token), userId, expiresAt); - return { token, expiresAt }; - } - - return { - async register(input: CredentialsInput): Promise { - const { username, password } = validateCredentials(input); - const user = await store.createUser(username, await hashPassword(password, scryptParams)); - if (!user) throw authError(AuthErrorCode.USERNAME_TAKEN, 'The username is taken.', { field: 'username' }); - return { user: toPublicUser(user), session: await startSession(user.id) }; - }, - - async login(input: CredentialsInput): Promise { - const username = normalizeUsername(input.username); - if (loginLimiter.isBlocked(username)) { - throw authError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed logins. Try again later.'); - } - - // A password longer than any we accept can never match, so it is not hashed at all. - const tooLong = input.password.length > PASSWORD_MAX_LENGTH; - const user = tooLong ? null : await store.findUserByUsername(username); - const matches = !tooLong && (await verifyPassword(input.password, user?.passwordHash ?? (await getDummyHash()))); - - if (!user || !matches) { - loginLimiter.recordFailure(username); - // The same error for wrong username and wrong password. - throw authError(AuthErrorCode.INVALID_CREDENTIALS, 'Wrong username or password.'); - } - - loginLimiter.reset(username); - await store.deleteExpiredSessions(); // Cheap with the index, and keeps the table small. - return { user: toPublicUser(user), session: await startSession(user.id) }; - }, - - async logout(token: string | undefined): Promise { - if (isSessionToken(token)) await store.deleteSession(hashSessionToken(token)); - }, - - async userForToken(token: string | undefined): Promise { - if (!isSessionToken(token)) return null; - const user = await store.findUserBySession(hashSessionToken(token)); - return user ? toPublicUser(user) : null; - }, - }; + const { + sessionDays = SESSION_DAYS, + now = () => new Date(), + scryptParams = DEFAULT_SCRYPT_PARAMS, + loginLimiter = createAttemptLimiter({ + maxAttempts: MAX_LOGIN_ATTEMPTS, + windowMs: LOGIN_ATTEMPT_WINDOW_MS, + }), + } = options; + + // Compared against when the username does not exist, so a wrong username takes as long + // as a wrong password and the response time does not reveal which usernames exist. + let dummyHash: Promise | undefined; + const getDummyHash = () => (dummyHash ??= hashPassword('not-a-real-password', scryptParams)); + + async function startSession(userId: number): Promise { + const token = createSessionToken(); + const expiresAt = new Date(now().getTime() + sessionDays * DAY_MS); + await store.createSession(hashSessionToken(token), userId, expiresAt); + return { token, expiresAt }; + } + + return { + async register(input: CredentialsInput): Promise { + const { username, password } = validateCredentials(input); + const user = await store.createUser(username, await hashPassword(password, scryptParams)); + if (!user) + throw authError(AuthErrorCode.USERNAME_TAKEN, 'The username is taken.', { + field: 'username', + }); + return { user: toPublicUser(user), session: await startSession(user.id) }; + }, + + async login(input: CredentialsInput): Promise { + const username = normalizeUsername(input.username); + if (loginLimiter.isBlocked(username)) { + throw authError( + AuthErrorCode.TOO_MANY_ATTEMPTS, + 'Too many failed logins. Try again later.', + ); + } + + // A password longer than any we accept can never match, so it is not hashed at all. + const tooLong = input.password.length > PASSWORD_MAX_LENGTH; + const user = tooLong ? null : await store.findUserByUsername(username); + const matches = + !tooLong && + (await verifyPassword(input.password, user?.passwordHash ?? (await getDummyHash()))); + + if (!user || !matches) { + loginLimiter.recordFailure(username); + // The same error for wrong username and wrong password. + throw authError(AuthErrorCode.INVALID_CREDENTIALS, 'Wrong username or password.'); + } + + loginLimiter.reset(username); + await store.deleteExpiredSessions(); // Cheap with the index, and keeps the table small. + return { user: toPublicUser(user), session: await startSession(user.id) }; + }, + + async logout(token: string | undefined): Promise { + if (isSessionToken(token)) await store.deleteSession(hashSessionToken(token)); + }, + + async userForToken(token: string | undefined): Promise { + if (!isSessionToken(token)) return null; + const user = await store.findUserBySession(hashSessionToken(token)); + return user ? toPublicUser(user) : null; + }, + }; } diff --git a/backend/src/auth/cookies.test.ts b/backend/src/auth/cookies.test.ts index 527115d..4eb9f52 100644 --- a/backend/src/auth/cookies.test.ts +++ b/backend/src/auth/cookies.test.ts @@ -2,36 +2,41 @@ import { describe, expect, it } from 'vitest'; import { parseCookies, sessionCookieOptions } from './cookies'; describe('parseCookies', () => { - it('reads several cookies', () => { - const cookies = parseCookies('kk_session=abc; theme=dark'); - expect(cookies.get('kk_session')).toBe('abc'); - expect(cookies.get('theme')).toBe('dark'); - }); + it('reads several cookies', () => { + const cookies = parseCookies('kk_session=abc; theme=dark'); + expect(cookies.get('kk_session')).toBe('abc'); + expect(cookies.get('theme')).toBe('dark'); + }); - it('returns an empty map without a header', () => { - expect(parseCookies(undefined).size).toBe(0); - expect(parseCookies('').size).toBe(0); - }); + it('returns an empty map without a header', () => { + expect(parseCookies(undefined).size).toBe(0); + expect(parseCookies('').size).toBe(0); + }); - it('decodes values and keeps "=" inside a value', () => { - expect(parseCookies('a=b%20c; d=e=f').get('a')).toBe('b c'); - expect(parseCookies('d=e=f').get('d')).toBe('e=f'); - }); + it('decodes values and keeps "=" inside a value', () => { + expect(parseCookies('a=b%20c; d=e=f').get('a')).toBe('b c'); + expect(parseCookies('d=e=f').get('d')).toBe('e=f'); + }); - it('keeps the first value of a repeated name', () => { - expect(parseCookies('a=1; a=2').get('a')).toBe('1'); - }); + it('keeps the first value of a repeated name', () => { + expect(parseCookies('a=1; a=2').get('a')).toBe('1'); + }); - it('skips broken parts instead of throwing', () => { - const cookies = parseCookies('bad; =x; broken=%E0%A4%A; ok=1'); - expect(cookies.get('ok')).toBe('1'); - expect(cookies.has('broken')).toBe(false); - }); + it('skips broken parts instead of throwing', () => { + const cookies = parseCookies('bad; =x; broken=%E0%A4%A; ok=1'); + expect(cookies.get('ok')).toBe('1'); + expect(cookies.has('broken')).toBe(false); + }); }); describe('sessionCookieOptions', () => { - it('keeps the cookie away from JavaScript and other sites', () => { - expect(sessionCookieOptions(false)).toMatchObject({ httpOnly: true, sameSite: 'lax', secure: false, path: '/' }); - expect(sessionCookieOptions(true).secure).toBe(true); + it('keeps the cookie away from JavaScript and other sites', () => { + expect(sessionCookieOptions(false)).toMatchObject({ + httpOnly: true, + sameSite: 'lax', + secure: false, + path: '/', }); + expect(sessionCookieOptions(true).secure).toBe(true); + }); }); diff --git a/backend/src/auth/cookies.ts b/backend/src/auth/cookies.ts index 04ab45b..7d58296 100644 --- a/backend/src/auth/cookies.ts +++ b/backend/src/auth/cookies.ts @@ -4,39 +4,40 @@ import { SESSION_COOKIE } from './config'; /** Parses a Cookie header. Values that cannot be decoded are skipped. */ export function parseCookies(header: string | undefined): Map { - const cookies = new Map(); - if (!header) return cookies; + const cookies = new Map(); + if (!header) return cookies; - for (const part of header.split(';')) { - const separator = part.indexOf('='); - if (separator === -1) continue; - const name = part.slice(0, separator).trim(); - const value = part.slice(separator + 1).trim(); - if (!name || cookies.has(name)) continue; // The first value wins, as in browsers. - try { - cookies.set(name, decodeURIComponent(value)); - } catch { - // Malformed percent-encoding: ignore this cookie. - } + for (const part of header.split(';')) { + const separator = part.indexOf('='); + if (separator === -1) continue; + const name = part.slice(0, separator).trim(); + const value = part.slice(separator + 1).trim(); + if (!name || cookies.has(name)) continue; // The first value wins, as in browsers. + try { + cookies.set(name, decodeURIComponent(value)); + } catch { + // Malformed percent-encoding: ignore this cookie. } - return cookies; + } + return cookies; } /** The options for the session cookie. httpOnly keeps it away from JavaScript, so XSS cannot steal it. */ export function sessionCookieOptions(secure: boolean): CookieOptions { - return { httpOnly: true, sameSite: 'lax', secure, path: '/' }; + return { httpOnly: true, sameSite: 'lax', secure, path: '/' }; } /** What the auth code needs from the response. Lets tests use a fake instead of Express. */ export interface CookieJar { - setSession(token: string, expiresAt: Date): void; - clearSession(): void; + setSession(token: string, expiresAt: Date): void; + clearSession(): void; } export function createCookieJar(res: Response, secure: boolean): CookieJar { - const options = sessionCookieOptions(secure); - return { - setSession: (token, expiresAt) => res.cookie(SESSION_COOKIE, token, { ...options, expires: expiresAt }), - clearSession: () => res.clearCookie(SESSION_COOKIE, options), - }; + const options = sessionCookieOptions(secure); + return { + setSession: (token, expiresAt) => + res.cookie(SESSION_COOKIE, token, { ...options, expires: expiresAt }), + clearSession: () => res.clearCookie(SESSION_COOKIE, options), + }; } diff --git a/backend/src/auth/credentials.test.ts b/backend/src/auth/credentials.test.ts index 5ec750f..4f5b701 100644 --- a/backend/src/auth/credentials.test.ts +++ b/backend/src/auth/credentials.test.ts @@ -1,63 +1,67 @@ import { describe, expect, it } from 'vitest'; import { - normalizeUsername, - PASSWORD_MAX_LENGTH, - PASSWORD_MIN_LENGTH, - USERNAME_MAX_LENGTH, - validateCredentials, + normalizeUsername, + PASSWORD_MAX_LENGTH, + PASSWORD_MIN_LENGTH, + USERNAME_MAX_LENGTH, + validateCredentials, } from './credentials'; const PASSWORD = 'langt-nok-passord'; /** The `reason` from the BAD_USER_INPUT error, so tests do not depend on the message. */ function reasonFor(username: string, password = PASSWORD): unknown { - try { - validateCredentials({ username, password }); - } catch (error) { - return (error as { extensions: { reason: string } }).extensions.reason; - } - return undefined; + try { + validateCredentials({ username, password }); + } catch (error) { + return (error as { extensions: { reason: string } }).extensions.reason; + } + return undefined; } describe('normalizeUsername', () => { - it('trims and lowercases', () => { - expect(normalizeUsername(' Ola_N ')).toBe('ola_n'); - }); + it('trims and lowercases', () => { + expect(normalizeUsername(' Ola_N ')).toBe('ola_n'); + }); }); describe('validateCredentials', () => { - it('accepts valid input and normalizes the username', () => { - expect(validateCredentials({ username: 'Kari_99', password: PASSWORD })).toEqual({ - username: 'kari_99', - password: PASSWORD, - }); + it('accepts valid input and normalizes the username', () => { + expect(validateCredentials({ username: 'Kari_99', password: PASSWORD })).toEqual({ + username: 'kari_99', + password: PASSWORD, }); + }); - it('does not trim the password', () => { - expect(validateCredentials({ username: 'kari', password: ' mellomrom ' }).password).toBe(' mellomrom '); - }); + it('does not trim the password', () => { + expect(validateCredentials({ username: 'kari', password: ' mellomrom ' }).password).toBe( + ' mellomrom ', + ); + }); - it('rejects usernames that are too short or too long', () => { - expect(reasonFor('ab')).toBe('USERNAME_TOO_SHORT'); - expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH + 1))).toBe('USERNAME_TOO_LONG'); - expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH))).toBeUndefined(); - }); + it('rejects usernames that are too short or too long', () => { + expect(reasonFor('ab')).toBe('USERNAME_TOO_SHORT'); + expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH + 1))).toBe('USERNAME_TOO_LONG'); + expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH))).toBeUndefined(); + }); - it('rejects characters outside a-z, 0-9 and _', () => { - for (const username of ['ola nordmann', 'blåbær', 'ola-n', 'ola.n', 'ola@ntnu']) { - expect(reasonFor(username)).toBe('USERNAME_INVALID_CHARACTERS'); - } - }); + it('rejects characters outside a-z, 0-9 and _', () => { + for (const username of ['ola nordmann', 'blåbær', 'ola-n', 'ola.n', 'ola@ntnu']) { + expect(reasonFor(username)).toBe('USERNAME_INVALID_CHARACTERS'); + } + }); - it('checks the password length at both ends', () => { - expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH - 1))).toBe('PASSWORD_TOO_SHORT'); - expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH))).toBeUndefined(); - expect(reasonFor('kari', 'a'.repeat(PASSWORD_MAX_LENGTH + 1))).toBe('PASSWORD_TOO_LONG'); - }); + it('checks the password length at both ends', () => { + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH - 1))).toBe('PASSWORD_TOO_SHORT'); + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH))).toBeUndefined(); + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MAX_LENGTH + 1))).toBe('PASSWORD_TOO_LONG'); + }); - it('says which field is wrong, with the BAD_USER_INPUT code', () => { - expect(() => validateCredentials({ username: 'x', password: PASSWORD })).toThrow( - expect.objectContaining({ extensions: expect.objectContaining({ code: 'BAD_USER_INPUT', field: 'username' }) }), - ); - }); + it('says which field is wrong, with the BAD_USER_INPUT code', () => { + expect(() => validateCredentials({ username: 'x', password: PASSWORD })).toThrow( + expect.objectContaining({ + extensions: expect.objectContaining({ code: 'BAD_USER_INPUT', field: 'username' }), + }), + ); + }); }); diff --git a/backend/src/auth/credentials.ts b/backend/src/auth/credentials.ts index ec5b713..ade6b77 100644 --- a/backend/src/auth/credentials.ts +++ b/backend/src/auth/credentials.ts @@ -13,35 +13,55 @@ export const PASSWORD_MIN_LENGTH = 8; export const PASSWORD_MAX_LENGTH = 128; export interface CredentialsInput { - username: string; - password: string; + username: string; + password: string; } /** " Ola_N " → "ola_n". Usernames are unique regardless of case. */ export function normalizeUsername(username: string): string { - return username.trim().toLowerCase(); + return username.trim().toLowerCase(); } /** For registration. Returns the cleaned input, or throws BAD_USER_INPUT with `field` and `reason`. */ export function validateCredentials(input: CredentialsInput): CredentialsInput { - const username = normalizeUsername(input.username); - const { password } = input; // Never trimmed: spaces are allowed in passwords. + const username = normalizeUsername(input.username); + const { password } = input; // Never trimmed: spaces are allowed in passwords. - if (username.length < USERNAME_MIN_LENGTH) { - throw invalidCredentialsInput('username', 'USERNAME_TOO_SHORT', `The username needs at least ${USERNAME_MIN_LENGTH} characters.`); - } - if (username.length > USERNAME_MAX_LENGTH) { - throw invalidCredentialsInput('username', 'USERNAME_TOO_LONG', `The username can have at most ${USERNAME_MAX_LENGTH} characters.`); - } - if (!USERNAME_PATTERN.test(username)) { - throw invalidCredentialsInput('username', 'USERNAME_INVALID_CHARACTERS', 'The username can only contain a-z, 0-9 and _.'); - } - if (password.length < PASSWORD_MIN_LENGTH) { - throw invalidCredentialsInput('password', 'PASSWORD_TOO_SHORT', `The password needs at least ${PASSWORD_MIN_LENGTH} characters.`); - } - if (password.length > PASSWORD_MAX_LENGTH) { - throw invalidCredentialsInput('password', 'PASSWORD_TOO_LONG', `The password can have at most ${PASSWORD_MAX_LENGTH} characters.`); - } + if (username.length < USERNAME_MIN_LENGTH) { + throw invalidCredentialsInput( + 'username', + 'USERNAME_TOO_SHORT', + `The username needs at least ${USERNAME_MIN_LENGTH} characters.`, + ); + } + if (username.length > USERNAME_MAX_LENGTH) { + throw invalidCredentialsInput( + 'username', + 'USERNAME_TOO_LONG', + `The username can have at most ${USERNAME_MAX_LENGTH} characters.`, + ); + } + if (!USERNAME_PATTERN.test(username)) { + throw invalidCredentialsInput( + 'username', + 'USERNAME_INVALID_CHARACTERS', + 'The username can only contain a-z, 0-9 and _.', + ); + } + if (password.length < PASSWORD_MIN_LENGTH) { + throw invalidCredentialsInput( + 'password', + 'PASSWORD_TOO_SHORT', + `The password needs at least ${PASSWORD_MIN_LENGTH} characters.`, + ); + } + if (password.length > PASSWORD_MAX_LENGTH) { + throw invalidCredentialsInput( + 'password', + 'PASSWORD_TOO_LONG', + `The password can have at most ${PASSWORD_MAX_LENGTH} characters.`, + ); + } - return { username, password }; + return { username, password }; } diff --git a/backend/src/auth/errors.ts b/backend/src/auth/errors.ts index d9fccc5..0813341 100644 --- a/backend/src/auth/errors.ts +++ b/backend/src/auth/errors.ts @@ -3,27 +3,35 @@ import { GraphQLError } from 'graphql'; export const AuthErrorCode = { - BAD_USER_INPUT: 'BAD_USER_INPUT', - USERNAME_TAKEN: 'USERNAME_TAKEN', - INVALID_CREDENTIALS: 'INVALID_CREDENTIALS', - TOO_MANY_ATTEMPTS: 'TOO_MANY_ATTEMPTS', - UNAUTHENTICATED: 'UNAUTHENTICATED', + BAD_USER_INPUT: 'BAD_USER_INPUT', + USERNAME_TAKEN: 'USERNAME_TAKEN', + INVALID_CREDENTIALS: 'INVALID_CREDENTIALS', + TOO_MANY_ATTEMPTS: 'TOO_MANY_ATTEMPTS', + UNAUTHENTICATED: 'UNAUTHENTICATED', } as const; export type AuthErrorCode = (typeof AuthErrorCode)[keyof typeof AuthErrorCode]; /** Why a username or password was rejected at registration. */ export type CredentialsReason = - | 'USERNAME_TOO_SHORT' - | 'USERNAME_TOO_LONG' - | 'USERNAME_INVALID_CHARACTERS' - | 'PASSWORD_TOO_SHORT' - | 'PASSWORD_TOO_LONG'; + | 'USERNAME_TOO_SHORT' + | 'USERNAME_TOO_LONG' + | 'USERNAME_INVALID_CHARACTERS' + | 'PASSWORD_TOO_SHORT' + | 'PASSWORD_TOO_LONG'; -export function authError(code: AuthErrorCode, message: string, extensions: Record = {}) { - return new GraphQLError(message, { extensions: { code, ...extensions } }); +export function authError( + code: AuthErrorCode, + message: string, + extensions: Record = {}, +) { + return new GraphQLError(message, { extensions: { code, ...extensions } }); } -export function invalidCredentialsInput(field: 'username' | 'password', reason: CredentialsReason, message: string) { - return authError(AuthErrorCode.BAD_USER_INPUT, message, { field, reason }); +export function invalidCredentialsInput( + field: 'username' | 'password', + reason: CredentialsReason, + message: string, +) { + return authError(AuthErrorCode.BAD_USER_INPUT, message, { field, reason }); } diff --git a/backend/src/auth/password.test.ts b/backend/src/auth/password.test.ts index 3efe9b2..7b3a4ad 100644 --- a/backend/src/auth/password.test.ts +++ b/backend/src/auth/password.test.ts @@ -5,39 +5,47 @@ import { DEFAULT_SCRYPT_PARAMS, hashPassword, verifyPassword } from './password' const FAST = { N: 1024, r: 8, p: 1 }; describe('hashPassword', () => { - it('stores the parameters, salt and hash, never the password', async () => { - const stored = await hashPassword('hemmelig-passord', FAST); - expect(stored).toMatch(/^scrypt\$1024\$8\$1\$[A-Za-z0-9+/=]+\$[A-Za-z0-9+/=]+$/); - expect(stored).not.toContain('hemmelig-passord'); - }); + it('stores the parameters, salt and hash, never the password', async () => { + const stored = await hashPassword('hemmelig-passord', FAST); + expect(stored).toMatch(/^scrypt\$1024\$8\$1\$[A-Za-z0-9+/=]+\$[A-Za-z0-9+/=]+$/); + expect(stored).not.toContain('hemmelig-passord'); + }); - it('gives a different hash for the same password, because the salt is random', async () => { - expect(await hashPassword('samme-passord', FAST)).not.toBe(await hashPassword('samme-passord', FAST)); - }); + it('gives a different hash for the same password, because the salt is random', async () => { + expect(await hashPassword('samme-passord', FAST)).not.toBe( + await hashPassword('samme-passord', FAST), + ); + }); - it('works with the default parameters', async () => { - const stored = await hashPassword('standard-passord'); - expect(stored.startsWith(`scrypt$${DEFAULT_SCRYPT_PARAMS.N}$`)).toBe(true); - expect(await verifyPassword('standard-passord', stored)).toBe(true); - }); + it('works with the default parameters', async () => { + const stored = await hashPassword('standard-passord'); + expect(stored.startsWith(`scrypt$${DEFAULT_SCRYPT_PARAMS.N}$`)).toBe(true); + expect(await verifyPassword('standard-passord', stored)).toBe(true); + }); }); describe('verifyPassword', () => { - it('accepts the right password and rejects a wrong one', async () => { - const stored = await hashPassword('riktig passord', FAST); - expect(await verifyPassword('riktig passord', stored)).toBe(true); - expect(await verifyPassword('feil passord', stored)).toBe(false); - expect(await verifyPassword('riktig passord ', stored)).toBe(false); - }); + it('accepts the right password and rejects a wrong one', async () => { + const stored = await hashPassword('riktig passord', FAST); + expect(await verifyPassword('riktig passord', stored)).toBe(true); + expect(await verifyPassword('feil passord', stored)).toBe(false); + expect(await verifyPassword('riktig passord ', stored)).toBe(false); + }); - it('handles passwords with æ, ø, å and emoji', async () => { - const stored = await hashPassword('blåbærsyltetøy 🍷', FAST); - expect(await verifyPassword('blåbærsyltetøy 🍷', stored)).toBe(true); - }); + it('handles passwords with æ, ø, å and emoji', async () => { + const stored = await hashPassword('blåbærsyltetøy 🍷', FAST); + expect(await verifyPassword('blåbærsyltetøy 🍷', stored)).toBe(true); + }); - it('returns false for malformed hashes instead of throwing', async () => { - for (const stored of ['', 'plaintext', 'bcrypt$1$2$3$a$b', 'scrypt$x$8$1$c2FsdA==$aGFzaA==', 'scrypt$1000$8$1$c2FsdA==$aGFzaA==']) { - expect(await verifyPassword('passord', stored)).toBe(false); - } - }); + it('returns false for malformed hashes instead of throwing', async () => { + for (const stored of [ + '', + 'plaintext', + 'bcrypt$1$2$3$a$b', + 'scrypt$x$8$1$c2FsdA==$aGFzaA==', + 'scrypt$1000$8$1$c2FsdA==$aGFzaA==', + ]) { + expect(await verifyPassword('passord', stored)).toBe(false); + } + }); }); diff --git a/backend/src/auth/password.ts b/backend/src/auth/password.ts index cf7e7ae..416e4b2 100644 --- a/backend/src/auth/password.ts +++ b/backend/src/auth/password.ts @@ -4,12 +4,12 @@ import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'; export interface ScryptParams { - /** CPU and memory cost. Must be a power of two. */ - N: number; - /** Block size. */ - r: number; - /** Parallelisation. */ - p: number; + /** CPU and memory cost. Must be a power of two. */ + N: number; + /** Block size. */ + r: number; + /** Parallelisation. */ + p: number; } /** One of the scrypt settings recommended by the OWASP Password Storage Cheat Sheet (about 32 MiB). */ @@ -19,39 +19,54 @@ const SALT_BYTES = 16; const KEY_BYTES = 32; const PREFIX = 'scrypt'; -function derive(password: string, salt: Buffer, keyLength: number, params: ScryptParams): Promise { - return new Promise((resolve, reject) => { - // maxmem must be above 128 * N * r, or Node refuses the parameters. - const maxmem = 256 * params.N * params.r; - scrypt(password, salt, keyLength, { ...params, maxmem }, (error, key) => - error ? reject(error) : resolve(key), - ); - }); +function derive( + password: string, + salt: Buffer, + keyLength: number, + params: ScryptParams, +): Promise { + return new Promise((resolve, reject) => { + // maxmem must be above 128 * N * r, or Node refuses the parameters. + const maxmem = 256 * params.N * params.r; + scrypt(password, salt, keyLength, { ...params, maxmem }, (error, key) => + error ? reject(error) : resolve(key), + ); + }); } /** Returns "scrypt$N$r$p$salt$hash", with salt and hash in base64. */ -export async function hashPassword(password: string, params = DEFAULT_SCRYPT_PARAMS): Promise { - const salt = randomBytes(SALT_BYTES); - const key = await derive(password, salt, KEY_BYTES, params); - return [PREFIX, params.N, params.r, params.p, salt.toString('base64'), key.toString('base64')].join('$'); +export async function hashPassword( + password: string, + params = DEFAULT_SCRYPT_PARAMS, +): Promise { + const salt = randomBytes(SALT_BYTES); + const key = await derive(password, salt, KEY_BYTES, params); + return [ + PREFIX, + params.N, + params.r, + params.p, + salt.toString('base64'), + key.toString('base64'), + ].join('$'); } /** Compares in constant time. A malformed stored hash gives false instead of an error. */ export async function verifyPassword(password: string, stored: string): Promise { - const parts = stored.split('$'); - if (parts.length !== 6 || parts[0] !== PREFIX) return false; - - const [N, r, p] = parts.slice(1, 4).map(Number); - if (![N, r, p].every((value) => Number.isInteger(value) && value > 0)) return false; - - const salt = Buffer.from(parts[4], 'base64'); - const expected = Buffer.from(parts[5], 'base64'); - if (salt.length === 0 || expected.length === 0) return false; - - try { - const actual = await derive(password, salt, expected.length, { N, r, p }); - return timingSafeEqual(actual, expected); - } catch { - return false; // For example N that is not a power of two. - } + const parts = stored.split('$'); + if (parts.length !== 6 || parts[0] !== PREFIX) return false; + + const [N, r, p] = parts.slice(1, 4).map(Number); + if (![N, r, p].every((value) => Number.isInteger(value) && value > 0)) return false; + + const salt = Buffer.from(parts[4], 'base64'); + const expected = Buffer.from(parts[5], 'base64'); + if (salt.length === 0 || expected.length === 0) return false; + + try { + const actual = await derive(password, salt, expected.length, { N, r, p }); + return timingSafeEqual(actual, expected); + } catch { + return false; // For example N that is not a power of two. + } } diff --git a/backend/src/auth/rate-limit.test.ts b/backend/src/auth/rate-limit.test.ts index 7c4d8b5..68fd08d 100644 --- a/backend/src/auth/rate-limit.test.ts +++ b/backend/src/auth/rate-limit.test.ts @@ -2,38 +2,38 @@ import { describe, expect, it } from 'vitest'; import { createAttemptLimiter } from './rate-limit'; function setup() { - let time = 0; - const limiter = createAttemptLimiter({ maxAttempts: 3, windowMs: 1000, now: () => time }); - return { limiter, advance: (ms: number) => (time += ms) }; + let time = 0; + const limiter = createAttemptLimiter({ maxAttempts: 3, windowMs: 1000, now: () => time }); + return { limiter, advance: (ms: number) => (time += ms) }; } describe('createAttemptLimiter', () => { - it('blocks a key after too many failures', () => { - const { limiter } = setup(); - limiter.recordFailure('ola'); - limiter.recordFailure('ola'); - expect(limiter.isBlocked('ola')).toBe(false); - limiter.recordFailure('ola'); - expect(limiter.isBlocked('ola')).toBe(true); - }); + it('blocks a key after too many failures', () => { + const { limiter } = setup(); + limiter.recordFailure('ola'); + limiter.recordFailure('ola'); + expect(limiter.isBlocked('ola')).toBe(false); + limiter.recordFailure('ola'); + expect(limiter.isBlocked('ola')).toBe(true); + }); - it('counts each key on its own', () => { - const { limiter } = setup(); - for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); - expect(limiter.isBlocked('kari')).toBe(false); - }); + it('counts each key on its own', () => { + const { limiter } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + expect(limiter.isBlocked('kari')).toBe(false); + }); - it('lets the key in again when the window has passed', () => { - const { limiter, advance } = setup(); - for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); - advance(1000); - expect(limiter.isBlocked('ola')).toBe(false); - }); + it('lets the key in again when the window has passed', () => { + const { limiter, advance } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + advance(1000); + expect(limiter.isBlocked('ola')).toBe(false); + }); - it('starts over after reset', () => { - const { limiter } = setup(); - for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); - limiter.reset('ola'); - expect(limiter.isBlocked('ola')).toBe(false); - }); + it('starts over after reset', () => { + const { limiter } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + limiter.reset('ola'); + expect(limiter.isBlocked('ola')).toBe(false); + }); }); diff --git a/backend/src/auth/rate-limit.ts b/backend/src/auth/rate-limit.ts index db68224..3ae6466 100644 --- a/backend/src/auth/rate-limit.ts +++ b/backend/src/auth/rate-limit.ts @@ -3,51 +3,55 @@ // if the backend ever runs as several processes. export interface AttemptLimiterOptions { - maxAttempts: number; - windowMs: number; - /** Can be replaced in tests. */ - now?: () => number; + maxAttempts: number; + windowMs: number; + /** Can be replaced in tests. */ + now?: () => number; } export interface AttemptLimiter { - isBlocked(key: string): boolean; - recordFailure(key: string): void; - reset(key: string): void; + isBlocked(key: string): boolean; + recordFailure(key: string): void; + reset(key: string): void; } /** Stops the map from growing without limit if someone tries many different usernames. */ const PRUNE_AT_SIZE = 10_000; -export function createAttemptLimiter({ maxAttempts, windowMs, now = Date.now }: AttemptLimiterOptions): AttemptLimiter { - const attempts = new Map(); - - function current(key: string) { - const entry = attempts.get(key); - if (entry && now() >= entry.resetAt) { - attempts.delete(key); - return undefined; - } - return entry; - } - - function prune() { - const time = now(); - for (const [key, entry] of attempts) if (time >= entry.resetAt) attempts.delete(key); +export function createAttemptLimiter({ + maxAttempts, + windowMs, + now = Date.now, +}: AttemptLimiterOptions): AttemptLimiter { + const attempts = new Map(); + + function current(key: string) { + const entry = attempts.get(key); + if (entry && now() >= entry.resetAt) { + attempts.delete(key); + return undefined; } - - return { - isBlocked: (key) => (current(key)?.count ?? 0) >= maxAttempts, - - recordFailure(key) { - const entry = current(key); - if (entry) { - entry.count += 1; - return; - } - if (attempts.size >= PRUNE_AT_SIZE) prune(); - attempts.set(key, { count: 1, resetAt: now() + windowMs }); - }, - - reset: (key) => void attempts.delete(key), - }; + return entry; + } + + function prune() { + const time = now(); + for (const [key, entry] of attempts) if (time >= entry.resetAt) attempts.delete(key); + } + + return { + isBlocked: (key) => (current(key)?.count ?? 0) >= maxAttempts, + + recordFailure(key) { + const entry = current(key); + if (entry) { + entry.count += 1; + return; + } + if (attempts.size >= PRUNE_AT_SIZE) prune(); + attempts.set(key, { count: 1, resetAt: now() + windowMs }); + }, + + reset: (key) => void attempts.delete(key), + }; } diff --git a/backend/src/auth/resolvers.ts b/backend/src/auth/resolvers.ts index c6d154c..0624997 100644 --- a/backend/src/auth/resolvers.ts +++ b/backend/src/auth/resolvers.ts @@ -7,29 +7,37 @@ import type { CredentialsInput } from './credentials'; type AuthResolverContext = { auth: AuthContext }; export function toGraphQLUser(user: PublicUser) { - return { id: String(user.id), username: user.username, createdAt: user.createdAt.toISOString() }; + return { id: String(user.id), username: user.username, createdAt: user.createdAt.toISOString() }; } export const authResolvers = { - Query: { - async me(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { - const user = await auth.currentUser(); - return user ? toGraphQLUser(user) : null; - }, + Query: { + async me(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { + const user = await auth.currentUser(); + return user ? toGraphQLUser(user) : null; }, + }, - Mutation: { - async register(_parent: unknown, { input }: { input: CredentialsInput }, { auth }: AuthResolverContext) { - return toGraphQLUser(await auth.register(input)); - }, + Mutation: { + async register( + _parent: unknown, + { input }: { input: CredentialsInput }, + { auth }: AuthResolverContext, + ) { + return toGraphQLUser(await auth.register(input)); + }, - async login(_parent: unknown, { input }: { input: CredentialsInput }, { auth }: AuthResolverContext) { - return toGraphQLUser(await auth.login(input)); - }, + async login( + _parent: unknown, + { input }: { input: CredentialsInput }, + { auth }: AuthResolverContext, + ) { + return toGraphQLUser(await auth.login(input)); + }, - async logout(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { - await auth.logout(); - return true; - }, + async logout(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { + await auth.logout(); + return true; }, + }, }; diff --git a/backend/src/auth/session-token.test.ts b/backend/src/auth/session-token.test.ts index 8ee5831..1b463ed 100644 --- a/backend/src/auth/session-token.test.ts +++ b/backend/src/auth/session-token.test.ts @@ -2,27 +2,27 @@ import { describe, expect, it } from 'vitest'; import { createSessionToken, hashSessionToken, isSessionToken } from './session-token'; describe('session tokens', () => { - it('creates tokens that pass the format check', () => { - const token = createSessionToken(); - expect(token).toHaveLength(43); - expect(isSessionToken(token)).toBe(true); - }); + it('creates tokens that pass the format check', () => { + const token = createSessionToken(); + expect(token).toHaveLength(43); + expect(isSessionToken(token)).toBe(true); + }); - it('never creates the same token twice', () => { - const tokens = new Set(Array.from({ length: 1000 }, createSessionToken)); - expect(tokens.size).toBe(1000); - }); + it('never creates the same token twice', () => { + const tokens = new Set(Array.from({ length: 1000 }, createSessionToken)); + expect(tokens.size).toBe(1000); + }); - it('rejects values that cannot be tokens', () => { - for (const value of [undefined, null, '', 'abc', 'a'.repeat(44), `${'a'.repeat(42)}=`, 123]) { - expect(isSessionToken(value)).toBe(false); - } - }); + it('rejects values that cannot be tokens', () => { + for (const value of [undefined, null, '', 'abc', 'a'.repeat(44), `${'a'.repeat(42)}=`, 123]) { + expect(isSessionToken(value)).toBe(false); + } + }); - it('hashes to 32 bytes, the same way every time', () => { - const token = createSessionToken(); - expect(hashSessionToken(token)).toHaveLength(32); - expect(hashSessionToken(token).equals(hashSessionToken(token))).toBe(true); - expect(hashSessionToken(token).equals(hashSessionToken(createSessionToken()))).toBe(false); - }); + it('hashes to 32 bytes, the same way every time', () => { + const token = createSessionToken(); + expect(hashSessionToken(token)).toHaveLength(32); + expect(hashSessionToken(token).equals(hashSessionToken(token))).toBe(true); + expect(hashSessionToken(token).equals(hashSessionToken(createSessionToken()))).toBe(false); + }); }); diff --git a/backend/src/auth/session-token.ts b/backend/src/auth/session-token.ts index e4b552c..656eea9 100644 --- a/backend/src/auth/session-token.ts +++ b/backend/src/auth/session-token.ts @@ -8,15 +8,15 @@ const TOKEN_FORMAT = /^[A-Za-z0-9_-]{43}$/; /** 256 random bits. Cannot be guessed, so it is safe to use as the only proof of a login. */ export function createSessionToken(): string { - return randomBytes(TOKEN_BYTES).toString('base64url'); + return randomBytes(TOKEN_BYTES).toString('base64url'); } /** Rejects cookies that cannot be a token, before the database is asked. */ export function isSessionToken(value: unknown): value is string { - return typeof value === 'string' && TOKEN_FORMAT.test(value); + return typeof value === 'string' && TOKEN_FORMAT.test(value); } /** SHA-256 is enough here: the token is random and long, so it needs no salt or slow hash. */ export function hashSessionToken(token: string): Buffer { - return createHash('sha256').update(token).digest(); + return createHash('sha256').update(token).digest(); } diff --git a/backend/src/auth/user-store.db.test.ts b/backend/src/auth/user-store.db.test.ts index b973a9a..b75be55 100644 --- a/backend/src/auth/user-store.db.test.ts +++ b/backend/src/auth/user-store.db.test.ts @@ -9,69 +9,69 @@ import { createPgUserStore, type UserStore } from './user-store'; const url = process.env.TEST_DATABASE_URL; describe.skipIf(!url)('createPgUserStore (PostgreSQL)', () => { - let pool: Pool; - let store: UserStore; - const created: number[] = []; + let pool: Pool; + let store: UserStore; + const created: number[] = []; - /** A unique, valid username, so the tests never clash with other data in the database. */ - const uniqueName = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + /** A unique, valid username, so the tests never clash with other data in the database. */ + const uniqueName = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; - async function createUser() { - const user = await store.createUser(uniqueName(), 'scrypt$1024$8$1$c2FsdA==$aGFzaA=='); - if (!user) throw new Error('Could not create test user'); - created.push(user.id); - return user; - } + async function createUser() { + const user = await store.createUser(uniqueName(), 'scrypt$1024$8$1$c2FsdA==$aGFzaA=='); + if (!user) throw new Error('Could not create test user'); + created.push(user.id); + return user; + } - beforeAll(() => { - pool = new Pool({ connectionString: url }); - store = createPgUserStore(pool); - }); + beforeAll(() => { + pool = new Pool({ connectionString: url }); + store = createPgUserStore(pool); + }); - // Removes only what these tests made. Sessions go with the user (ON DELETE CASCADE). - afterEach(async () => { - await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [created.splice(0)]); - }); + // Removes only what these tests made. Sessions go with the user (ON DELETE CASCADE). + afterEach(async () => { + await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [created.splice(0)]); + }); - afterAll(() => pool.end()); + afterAll(() => pool.end()); - it('generates increasing ids and sets created_at', async () => { - const first = await createUser(); - const second = await createUser(); - expect(second.id).toBeGreaterThan(first.id); - expect(first.createdAt).toBeInstanceOf(Date); - }); + it('generates increasing ids and sets created_at', async () => { + const first = await createUser(); + const second = await createUser(); + expect(second.id).toBeGreaterThan(first.id); + expect(first.createdAt).toBeInstanceOf(Date); + }); - it('returns null instead of throwing when the username is taken', async () => { - const user = await createUser(); - expect(await store.createUser(user.username, 'hash')).toBeNull(); - }); + it('returns null instead of throwing when the username is taken', async () => { + const user = await createUser(); + expect(await store.createUser(user.username, 'hash')).toBeNull(); + }); - it('the database itself rejects usernames that break the rules', async () => { - await expect(store.createUser('Ola Nordmann', 'hash')).rejects.toMatchObject({ code: '23514' }); - }); + it('the database itself rejects usernames that break the rules', async () => { + await expect(store.createUser('Ola Nordmann', 'hash')).rejects.toMatchObject({ code: '23514' }); + }); - it('finds a user by username', async () => { - const user = await createUser(); - expect(await store.findUserByUsername(user.username)).toEqual(user); - expect(await store.findUserByUsername(uniqueName())).toBeNull(); - }); + it('finds a user by username', async () => { + const user = await createUser(); + expect(await store.findUserByUsername(user.username)).toEqual(user); + expect(await store.findUserByUsername(uniqueName())).toBeNull(); + }); - it('finds the user from a session, and not after it is deleted', async () => { - const user = await createUser(); - const tokenHash = hashSessionToken(createSessionToken()); - await store.createSession(tokenHash, user.id, new Date(Date.now() + 60_000)); - expect(await store.findUserBySession(tokenHash)).toEqual(user); + it('finds the user from a session, and not after it is deleted', async () => { + const user = await createUser(); + const tokenHash = hashSessionToken(createSessionToken()); + await store.createSession(tokenHash, user.id, new Date(Date.now() + 60_000)); + expect(await store.findUserBySession(tokenHash)).toEqual(user); - await store.deleteSession(tokenHash); - expect(await store.findUserBySession(tokenHash)).toBeNull(); - }); + await store.deleteSession(tokenHash); + expect(await store.findUserBySession(tokenHash)).toBeNull(); + }); - it('ignores and removes expired sessions', async () => { - const user = await createUser(); - const tokenHash = hashSessionToken(createSessionToken()); - await store.createSession(tokenHash, user.id, new Date(Date.now() - 1000)); - expect(await store.findUserBySession(tokenHash)).toBeNull(); - expect(await store.deleteExpiredSessions()).toBeGreaterThanOrEqual(1); - }); + it('ignores and removes expired sessions', async () => { + const user = await createUser(); + const tokenHash = hashSessionToken(createSessionToken()); + await store.createSession(tokenHash, user.id, new Date(Date.now() - 1000)); + expect(await store.findUserBySession(tokenHash)).toBeNull(); + expect(await store.deleteExpiredSessions()).toBeGreaterThanOrEqual(1); + }); }); diff --git a/backend/src/auth/user-store.ts b/backend/src/auth/user-store.ts index 2b2f00b..4e94b21 100644 --- a/backend/src/auth/user-store.ts +++ b/backend/src/auth/user-store.ts @@ -3,78 +3,86 @@ import type { Pool } from 'pg'; export interface UserRecord { - id: number; - username: string; - passwordHash: string; - createdAt: Date; + id: number; + username: string; + passwordHash: string; + createdAt: Date; } export interface UserStore { - /** Returns null if the username is taken. */ - createUser(username: string, passwordHash: string): Promise; - findUserByUsername(username: string): Promise; - createSession(tokenHash: Buffer, userId: number, expiresAt: Date): Promise; - /** Only sessions that have not expired. */ - findUserBySession(tokenHash: Buffer): Promise; - deleteSession(tokenHash: Buffer): Promise; - /** Returns the number of sessions removed. */ - deleteExpiredSessions(): Promise; + /** Returns null if the username is taken. */ + createUser(username: string, passwordHash: string): Promise; + findUserByUsername(username: string): Promise; + createSession(tokenHash: Buffer, userId: number, expiresAt: Date): Promise; + /** Only sessions that have not expired. */ + findUserBySession(tokenHash: Buffer): Promise; + deleteSession(tokenHash: Buffer): Promise; + /** Returns the number of sessions removed. */ + deleteExpiredSessions(): Promise; } interface UserRow { - id: number; - username: string; - password_hash: string; - created_at: Date; + id: number; + username: string; + password_hash: string; + created_at: Date; } const toUser = (row: UserRow | undefined): UserRecord | null => - row ? { id: row.id, username: row.username, passwordHash: row.password_hash, createdAt: row.created_at } : null; + row + ? { + id: row.id, + username: row.username, + passwordHash: row.password_hash, + createdAt: row.created_at, + } + : null; export function createPgUserStore(pool: Pool): UserStore { - return { - async createUser(username, passwordHash) { - // ON CONFLICT avoids a race where two people register the same name at the same time. - const result = await pool.query( - `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) + return { + async createUser(username, passwordHash) { + // ON CONFLICT avoids a race where two people register the same name at the same time. + const result = await pool.query( + `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) ON CONFLICT (username) DO NOTHING RETURNING *`, - [username, passwordHash], - ); - return toUser(result.rows[0]); - }, + [username, passwordHash], + ); + return toUser(result.rows[0]); + }, - async findUserByUsername(username) { - const result = await pool.query('SELECT * FROM app_user WHERE username = $1', [username]); - return toUser(result.rows[0]); - }, + async findUserByUsername(username) { + const result = await pool.query('SELECT * FROM app_user WHERE username = $1', [ + username, + ]); + return toUser(result.rows[0]); + }, - async createSession(tokenHash, userId, expiresAt) { - await pool.query('INSERT INTO user_session (token_hash, user_id, expires_at) VALUES ($1, $2, $3)', [ - tokenHash, - userId, - expiresAt, - ]); - }, + async createSession(tokenHash, userId, expiresAt) { + await pool.query( + 'INSERT INTO user_session (token_hash, user_id, expires_at) VALUES ($1, $2, $3)', + [tokenHash, userId, expiresAt], + ); + }, - async findUserBySession(tokenHash) { - const result = await pool.query( - `SELECT app_user.* + async findUserBySession(tokenHash) { + const result = await pool.query( + `SELECT app_user.* FROM user_session JOIN app_user ON app_user.id = user_session.user_id WHERE user_session.token_hash = $1 AND user_session.expires_at > now()`, - [tokenHash], - ); - return toUser(result.rows[0]); - }, + [tokenHash], + ); + return toUser(result.rows[0]); + }, - async deleteSession(tokenHash) { - await pool.query('DELETE FROM user_session WHERE token_hash = $1', [tokenHash]); - }, + async deleteSession(tokenHash) { + await pool.query('DELETE FROM user_session WHERE token_hash = $1', [tokenHash]); + }, - async deleteExpiredSessions() { - const result = await pool.query('DELETE FROM user_session WHERE expires_at <= now()'); - return result.rowCount ?? 0; - }, - }; + async deleteExpiredSessions() { + const result = await pool.query('DELETE FROM user_session WHERE expires_at <= now()'); + return result.rowCount ?? 0; + }, + }; } diff --git a/backend/src/connection.test.ts b/backend/src/connection.test.ts index e754692..eaade18 100644 --- a/backend/src/connection.test.ts +++ b/backend/src/connection.test.ts @@ -2,45 +2,45 @@ import { describe, expect, it } from 'vitest'; import { decodeIdCursor, encodeIdCursor, toConnection } from './connection'; describe('toConnection', () => { - const page = (rows: number[], first: number) => - toConnection({ - rows, - first, - totalCount: 10, - toNode: (row) => ({ id: row }), - cursorFor: (row) => encodeIdCursor(row), - }); - - it('uses the extra row only to tell that there is a next page', () => { - const result = page([9, 8, 7], 2); - expect(result.edges.map((edge) => edge.node.id)).toEqual([9, 8]); - expect(result.pageInfo).toEqual({ hasNextPage: true, endCursor: encodeIdCursor(8) }); - expect(result.totalCount).toBe(10); + const page = (rows: number[], first: number) => + toConnection({ + rows, + first, + totalCount: 10, + toNode: (row) => ({ id: row }), + cursorFor: (row) => encodeIdCursor(row), }); - it('has no next page and no end cursor when the page is empty', () => { - expect(page([], 2).pageInfo).toEqual({ hasNextPage: false, endCursor: null }); - }); + it('uses the extra row only to tell that there is a next page', () => { + const result = page([9, 8, 7], 2); + expect(result.edges.map((edge) => edge.node.id)).toEqual([9, 8]); + expect(result.pageInfo).toEqual({ hasNextPage: true, endCursor: encodeIdCursor(8) }); + expect(result.totalCount).toBe(10); + }); + + it('has no next page and no end cursor when the page is empty', () => { + expect(page([], 2).pageInfo).toEqual({ hasNextPage: false, endCursor: null }); + }); }); describe('id cursors', () => { - it('round-trips an id', () => { - expect(decodeIdCursor(encodeIdCursor(4821))).toBe(4821); - expect(decodeIdCursor(encodeIdCursor(2_147_483_647))).toBe(2_147_483_647); - expect(decodeIdCursor(null)).toBeNull(); - expect(decodeIdCursor(undefined)).toBeNull(); - }); + it('round-trips an id', () => { + expect(decodeIdCursor(encodeIdCursor(4821))).toBe(4821); + expect(decodeIdCursor(encodeIdCursor(2_147_483_647))).toBe(2_147_483_647); + expect(decodeIdCursor(null)).toBeNull(); + expect(decodeIdCursor(undefined)).toBeNull(); + }); - it.each([ - ['not base64 at all', 'not-a-cursor'], - ['an offset cursor', Buffer.from('offset:10').toString('base64')], - ['a negative id', Buffer.from('id:-1').toString('base64')], - ['id 0', Buffer.from('id:0').toString('base64')], - ['an id above the largest database integer', Buffer.from('id:2147483648').toString('base64')], - ['a very long number', Buffer.from(`id:${'9'.repeat(25)}`).toString('base64')], - ])('rejects %s with BAD_USER_INPUT', (_name, cursor) => { - expect(() => decodeIdCursor(cursor)).toThrow( - expect.objectContaining({ extensions: { code: 'BAD_USER_INPUT' } }), - ); - }); + it.each([ + ['not base64 at all', 'not-a-cursor'], + ['an offset cursor', Buffer.from('offset:10').toString('base64')], + ['a negative id', Buffer.from('id:-1').toString('base64')], + ['id 0', Buffer.from('id:0').toString('base64')], + ['an id above the largest database integer', Buffer.from('id:2147483648').toString('base64')], + ['a very long number', Buffer.from(`id:${'9'.repeat(25)}`).toString('base64')], + ])('rejects %s with BAD_USER_INPUT', (_name, cursor) => { + expect(() => decodeIdCursor(cursor)).toThrow( + expect.objectContaining({ extensions: { code: 'BAD_USER_INPUT' } }), + ); + }); }); diff --git a/backend/src/connection.ts b/backend/src/connection.ts index ac97bac..c812556 100644 --- a/backend/src/connection.ts +++ b/backend/src/connection.ts @@ -7,28 +7,28 @@ import { GraphQLError } from 'graphql'; * That extra row is only used to set hasNextPage. */ export function toConnection({ - rows, - first, - totalCount, - toNode, - cursorFor, + rows, + first, + totalCount, + toNode, + cursorFor, }: { - rows: Row[]; - first: number; - totalCount: number; - toNode: (row: Row) => Node; - /** The cursor that points just after this row. `index` is its place on the page. */ - cursorFor: (row: Row, index: number) => string; + rows: Row[]; + first: number; + totalCount: number; + toNode: (row: Row) => Node; + /** The cursor that points just after this row. `index` is its place on the page. */ + cursorFor: (row: Row, index: number) => string; }) { - const edges = rows.slice(0, first).map((row, index) => ({ - cursor: cursorFor(row, index), - node: toNode(row), - })); - return { - totalCount, - edges, - pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null }, - }; + const edges = rows.slice(0, first).map((row, index) => ({ + cursor: cursorFor(row, index), + node: toNode(row), + })); + return { + totalCount, + edges, + pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null }, + }; } /* @@ -42,16 +42,16 @@ export function toConnection({ const MAX_INTEGER = 2_147_483_647; export function encodeIdCursor(id: number): string { - return Buffer.from(`id:${id}`).toString('base64'); + return Buffer.from(`id:${id}`).toString('base64'); } /** The id in the cursor, or null without one. A cursor the API did not make gives BAD_USER_INPUT. */ export function decodeIdCursor(cursor: string | null | undefined): number | null { - if (!cursor) return null; - const match = /^id:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); - const id = match ? Number(match[1]) : NaN; - if (!Number.isInteger(id) || id <= 0 || id > MAX_INTEGER) { - throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); - } - return id; + if (!cursor) return null; + const match = /^id:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); + const id = match ? Number(match[1]) : NaN; + if (!Number.isInteger(id) || id <= 0 || id > MAX_INTEGER) { + throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + return id; } diff --git a/backend/src/context.ts b/backend/src/context.ts index 28eab9b..af70206 100644 --- a/backend/src/context.ts +++ b/backend/src/context.ts @@ -7,18 +7,18 @@ import { createCookieJar, parseCookies } from './auth/cookies'; import { createLoaders, type Loaders } from './loaders'; export interface Context { - loaders: Loaders; - auth: AuthContext; + loaders: Loaders; + auth: AuthContext; } export function createContextFactory(authService: AuthService) { - return async ({ req, res }: { req: Request; res: Response }): Promise => ({ - // Fresh loaders for every request, so batched data is never shared between requests or users. - loaders: createLoaders(), - auth: createAuthContext( - authService, - parseCookies(req.headers.cookie).get(SESSION_COOKIE), - createCookieJar(res, COOKIE_SECURE), - ), - }); + return async ({ req, res }: { req: Request; res: Response }): Promise => ({ + // Fresh loaders for every request, so batched data is never shared between requests or users. + loaders: createLoaders(), + auth: createAuthContext( + authService, + parseCookies(req.headers.cookie).get(SESSION_COOKIE), + createCookieJar(res, COOKIE_SECURE), + ), + }); } diff --git a/backend/src/csv.test.ts b/backend/src/csv.test.ts index c6f3b81..6ffe699 100644 --- a/backend/src/csv.test.ts +++ b/backend/src/csv.test.ts @@ -2,19 +2,19 @@ import { describe, expect, it } from 'vitest'; import { splitCsvLine } from './csv'; describe('splitCsvLine', () => { - it('splits plain cells', () => { - expect(splitCsvLine('1,2,N.V.,4.5')).toEqual(['1', '2', 'N.V.', '4.5']); - }); + it('splits plain cells', () => { + expect(splitCsvLine('1,2,N.V.,4.5')).toEqual(['1', '2', 'N.V.', '4.5']); + }); - it('keeps commas inside quotes', () => { - expect(splitCsvLine('1,"Merlot, Syrah",3')).toEqual(['1', 'Merlot, Syrah', '3']); - }); + it('keeps commas inside quotes', () => { + expect(splitCsvLine('1,"Merlot, Syrah",3')).toEqual(['1', 'Merlot, Syrah', '3']); + }); - it('reads "" as one quote', () => { - expect(splitCsvLine('1,"say ""hi""",3')).toEqual(['1', 'say "hi"', '3']); - }); + it('reads "" as one quote', () => { + expect(splitCsvLine('1,"say ""hi""",3')).toEqual(['1', 'say "hi"', '3']); + }); - it('keeps empty cells', () => { - expect(splitCsvLine('1,,3')).toEqual(['1', '', '3']); - }); -}); \ No newline at end of file + it('keeps empty cells', () => { + expect(splitCsvLine('1,,3')).toEqual(['1', '', '3']); + }); +}); diff --git a/backend/src/csv.ts b/backend/src/csv.ts index 43de6d6..d025ff8 100644 --- a/backend/src/csv.ts +++ b/backend/src/csv.ts @@ -1,51 +1,51 @@ // Minimal CSV reader for the X-Wines files: comma separated, "quoted" fields, "" as an escaped quote. export function parseCsv(text: string): Record[] { - const rows = parseRows(text.replace(/^\uFEFF/, '')); - const [header, ...data] = rows; - if (!header) return []; - return data + const rows = parseRows(text.replace(/^\uFEFF/, '')); + const [header, ...data] = rows; + if (!header) return []; + return data .filter((row) => row.some((cell) => cell !== '')) .map((row) => Object.fromEntries(header.map((name, i) => [name, row[i] ?? '']))); } function parseRows(text: string): string[][] { - const rows: string[][] = []; - let row: string[] = []; - let cell = ''; - let quoted = false; + const rows: string[][] = []; + let row: string[] = []; + let cell = ''; + let quoted = false; - for (let i = 0; i < text.length; i += 1) { + for (let i = 0; i < text.length; i += 1) { const char = text[i]; if (quoted) { - if (char === '"' && text[i + 1] === '"') { + if (char === '"' && text[i + 1] === '"') { cell += '"'; i += 1; - } else if (char === '"') { + } else if (char === '"') { quoted = false; - } else { + } else { cell += char; - } + } } else if (char === '"') { - quoted = true; + quoted = true; } else if (char === ',') { - row.push(cell); - cell = ''; + row.push(cell); + cell = ''; } else if (char === '\n' || char === '\r') { - if (char === '\r' && text[i + 1] === '\n') i += 1; - row.push(cell); - rows.push(row); - row = []; - cell = ''; + if (char === '\r' && text[i + 1] === '\n') i += 1; + row.push(cell); + rows.push(row); + row = []; + cell = ''; } else { - cell += char; - } - } - if (cell !== '' || row.length > 0) { - row.push(cell); - rows.push(row); + cell += char; } - return rows; + } + if (cell !== '' || row.length > 0) { + row.push(cell); + rows.push(row); + } + return rows; } /** @@ -54,31 +54,31 @@ function parseRows(text: string): string[][] { * Only safe when no field contains a newline, which is true for the ratings file. */ export function splitCsvLine(line: string): string[] { - const cells: string[] = []; - let cell = ''; - let quoted = false; + const cells: string[] = []; + let cell = ''; + let quoted = false; - for (let i = 0; i < line.length; i += 1) { + for (let i = 0; i < line.length; i += 1) { const char = line[i]; if (quoted) { - if (char === '"' && line[i + 1] === '"') { + if (char === '"' && line[i + 1] === '"') { cell += '"'; i += 1; - } else if (char === '"') { + } else if (char === '"') { quoted = false; - } else { + } else { cell += char; - } + } } else if (char === '"') { - quoted = true; + quoted = true; } else if (char === ',') { - cells.push(cell); - cell = ''; + cells.push(cell); + cell = ''; } else { - cell += char; - } + cell += char; } + } - cells.push(cell); - return cells; -} \ No newline at end of file + cells.push(cell); + return cells; +} diff --git a/backend/src/db-errors.test.ts b/backend/src/db-errors.test.ts index 73bcc31..fdd0a89 100644 --- a/backend/src/db-errors.test.ts +++ b/backend/src/db-errors.test.ts @@ -2,15 +2,20 @@ import { describe, expect, it } from 'vitest'; import { isForeignKeyViolation } from './db-errors'; describe('isForeignKeyViolation', () => { - it('matches the code and the constraint name', () => { - const error = { code: '23503', constraint: 'review_wine_id_fkey' }; - expect(isForeignKeyViolation(error, 'review_wine_id_fkey')).toBe(true); - expect(isForeignKeyViolation(error, 'review_user_id_fkey')).toBe(false); - }); + it('matches the code and the constraint name', () => { + const error = { code: '23503', constraint: 'review_wine_id_fkey' }; + expect(isForeignKeyViolation(error, 'review_wine_id_fkey')).toBe(true); + expect(isForeignKeyViolation(error, 'review_user_id_fkey')).toBe(false); + }); - it('ignores other errors', () => { - expect(isForeignKeyViolation({ code: '23505', constraint: 'review_wine_id_fkey' }, 'review_wine_id_fkey')).toBe(false); - expect(isForeignKeyViolation(new Error('Connection lost'), 'review_wine_id_fkey')).toBe(false); - expect(isForeignKeyViolation(null, 'review_wine_id_fkey')).toBe(false); - }); + it('ignores other errors', () => { + expect( + isForeignKeyViolation( + { code: '23505', constraint: 'review_wine_id_fkey' }, + 'review_wine_id_fkey', + ), + ).toBe(false); + expect(isForeignKeyViolation(new Error('Connection lost'), 'review_wine_id_fkey')).toBe(false); + expect(isForeignKeyViolation(null, 'review_wine_id_fkey')).toBe(false); + }); }); diff --git a/backend/src/db-errors.ts b/backend/src/db-errors.ts index 9c130bd..6d394fd 100644 --- a/backend/src/db-errors.ts +++ b/backend/src/db-errors.ts @@ -4,8 +4,8 @@ const FOREIGN_KEY_VIOLATION = '23503'; interface PgError { - code?: unknown; - constraint?: unknown; + code?: unknown; + constraint?: unknown; } /** @@ -14,6 +14,6 @@ interface PgError { * since one table can have several. */ export function isForeignKeyViolation(error: unknown, constraint: string): boolean { - const pgError = error as PgError | null; - return pgError?.code === FOREIGN_KEY_VIOLATION && pgError.constraint === constraint; + const pgError = error as PgError | null; + return pgError?.code === FOREIGN_KEY_VIOLATION && pgError.constraint === constraint; } diff --git a/backend/src/db.ts b/backend/src/db.ts index 49b3f68..ac3ecba 100644 --- a/backend/src/db.ts +++ b/backend/src/db.ts @@ -7,7 +7,7 @@ const envFile = path.join(__dirname, '..', '.env'); if (existsSync(envFile)) process.loadEnvFile(envFile); if (!process.env.DATABASE_URL) { - throw new Error('DATABASE_URL is required. See docs/setup.md.'); + throw new Error('DATABASE_URL is required. See docs/setup.md.'); } export const pool = new Pool({ connectionString: process.env.DATABASE_URL }); @@ -17,16 +17,16 @@ export const pool = new Pool({ connectionString: process.env.DATABASE_URL }); * nothing is. Use the `client` it gets, not `pool`, for every query that belongs to it. */ export async function withTransaction(work: (client: PoolClient) => Promise): Promise { - const client = await pool.connect(); - try { - await client.query('BEGIN'); - const result = await work(client); - await client.query('COMMIT'); - return result; - } catch (error) { - await client.query('ROLLBACK'); - throw error; - } finally { - client.release(); - } -} \ No newline at end of file + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const result = await work(client); + await client.query('COMMIT'); + return result; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} diff --git a/backend/src/demo/demo-user.db.test.ts b/backend/src/demo/demo-user.db.test.ts index 5e0b820..fc805e0 100644 --- a/backend/src/demo/demo-user.db.test.ts +++ b/backend/src/demo/demo-user.db.test.ts @@ -10,97 +10,100 @@ const url = process.env.TEST_DATABASE_URL; const FAST_SCRYPT = { N: 1024, r: 8, p: 1 }; describe.skipIf(!url)('demo user (PostgreSQL)', () => { - const api = createTestApi({ firstId: 700_000_000 }); - afterAll(async () => { - await pool.query('DELETE FROM app_user WHERE username = $1', [DEMO_USERNAME]); - await api.close(); - }); + const api = createTestApi({ firstId: 700_000_000 }); + afterAll(async () => { + await pool.query('DELETE FROM app_user WHERE username = $1', [DEMO_USERNAME]); + await api.close(); + }); - /** What the demo user has, read straight from the database. */ - async function stateOf(userId: number) { - const lists = await pool.query<{ list: string; wine_id: number; top_position: number | null }>( - 'SELECT list, wine_id, top_position FROM user_wine WHERE user_id = $1', - [userId], - ); - const reviews = await pool.query<{ wine_id: number }>('SELECT wine_id FROM review WHERE user_id = $1', [ - userId, - ]); - const on = (list: string) => lists.rows.filter((row) => row.list === list).map((row) => row.wine_id); - const top = lists.rows - .filter((row) => row.top_position !== null) - .sort((a, b) => (a.top_position ?? 0) - (b.top_position ?? 0)) - .map((row) => row.wine_id); - return { - favourites: on('FAVOURITE').sort((a, b) => a - b), - wantToTry: on('WANT_TO_TRY').sort((a, b) => a - b), - tried: on('TRIED').sort((a, b) => a - b), - top, - reviewed: reviews.rows.map((row) => row.wine_id).sort((a, b) => a - b), - }; - } + /** What the demo user has, read straight from the database. */ + async function stateOf(userId: number) { + const lists = await pool.query<{ list: string; wine_id: number; top_position: number | null }>( + 'SELECT list, wine_id, top_position FROM user_wine WHERE user_id = $1', + [userId], + ); + const reviews = await pool.query<{ wine_id: number }>( + 'SELECT wine_id FROM review WHERE user_id = $1', + [userId], + ); + const on = (list: string) => + lists.rows.filter((row) => row.list === list).map((row) => row.wine_id); + const top = lists.rows + .filter((row) => row.top_position !== null) + .sort((a, b) => (a.top_position ?? 0) - (b.top_position ?? 0)) + .map((row) => row.wine_id); + return { + favourites: on('FAVOURITE').sort((a, b) => a - b), + wantToTry: on('WANT_TO_TRY').sort((a, b) => a - b), + tried: on('TRIED').sort((a, b) => a - b), + top, + reviewed: reviews.rows.map((row) => row.wine_id).sort((a, b) => a - b), + }; + } - it('creates a user with the documented password, lists that follow the rules, and reviews', async () => { - const wineIds = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + it('creates a user with the documented password, lists that follow the rules, and reviews', async () => { + const wineIds = (await api.createWines(DEMO_WINE_COUNT)).map(Number); - const { userId } = await withTransaction((client) => - seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT }), - ); + const { userId } = await withTransaction((client) => + seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT }), + ); - const user = await pool.query<{ password_hash: string }>('SELECT password_hash FROM app_user WHERE id = $1', [ - userId, - ]); - expect(await verifyPassword(DEMO_PASSWORD, user.rows[0].password_hash)).toBe(true); + const user = await pool.query<{ password_hash: string }>( + 'SELECT password_hash FROM app_user WHERE id = $1', + [userId], + ); + expect(await verifyPassword(DEMO_PASSWORD, user.rows[0].password_hash)).toBe(true); - const state = await stateOf(userId); - expect(state.favourites).toHaveLength(6); - expect(state.wantToTry).toHaveLength(5); - expect(state.top).toHaveLength(4); - expect(state.reviewed).toHaveLength(5); - // The rules: the top 4 are favourites, reviewed wines are tried, and tried wines are not on «Vil prøve». - expect(state.favourites).toEqual(expect.arrayContaining(state.top)); - expect(state.tried).toEqual(expect.arrayContaining(state.reviewed)); - expect(state.wantToTry.filter((wine) => state.tried.includes(wine))).toEqual([]); + const state = await stateOf(userId); + expect(state.favourites).toHaveLength(6); + expect(state.wantToTry).toHaveLength(5); + expect(state.top).toHaveLength(4); + expect(state.reviewed).toHaveLength(5); + // The rules: the top 4 are favourites, reviewed wines are tried, and tried wines are not on «Vil prøve». + expect(state.favourites).toEqual(expect.arrayContaining(state.top)); + expect(state.tried).toEqual(expect.arrayContaining(state.reviewed)); + expect(state.wantToTry.filter((wine) => state.tried.includes(wine))).toEqual([]); - // The reviews count in the wines' averages. - const stats = await pool.query<{ community_count: number }>( - 'SELECT community_count FROM wine WHERE id = ANY($1)', - [state.reviewed], - ); - expect(stats.rows.map((row) => row.community_count)).toEqual([1, 1, 1, 1, 1]); - }); + // The reviews count in the wines' averages. + const stats = await pool.query<{ community_count: number }>( + 'SELECT community_count FROM wine WHERE id = ANY($1)', + [state.reviewed], + ); + expect(stats.rows.map((row) => row.community_count)).toEqual([1, 1, 1, 1, 1]); + }); - it('resets the same user to the same state when it is run again, also with other wines', async () => { - const firstWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); - const secondWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); - const seed = (wineIds: number[]) => - withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })); + it('resets the same user to the same state when it is run again, also with other wines', async () => { + const firstWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + const secondWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + const seed = (wineIds: number[]) => + withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })); - const first = await seed(firstWines); - const before = await stateOf(first.userId); - expect((await seed(firstWines)).userId).toBe(first.userId); - expect(await stateOf(first.userId)).toEqual(before); + const first = await seed(firstWines); + const before = await stateOf(first.userId); + expect((await seed(firstWines)).userId).toBe(first.userId); + expect(await stateOf(first.userId)).toEqual(before); - // With other wines (a new import), nothing is left of the old ones, and their averages are updated. - await seed(secondWines); - const after = await stateOf(first.userId); - const listed = [...after.favourites, ...after.wantToTry, ...after.tried]; - expect(listed.filter((wine) => !secondWines.includes(wine))).toEqual([]); - const old = await pool.query<{ community_count: number }>( - 'SELECT community_count FROM wine WHERE id = ANY($1)', - [before.reviewed], - ); - expect(old.rows.map((row) => row.community_count)).toEqual([0, 0, 0, 0, 0]); - }); + // With other wines (a new import), nothing is left of the old ones, and their averages are updated. + await seed(secondWines); + const after = await stateOf(first.userId); + const listed = [...after.favourites, ...after.wantToTry, ...after.tried]; + expect(listed.filter((wine) => !secondWines.includes(wine))).toEqual([]); + const old = await pool.query<{ community_count: number }>( + 'SELECT community_count FROM wine WHERE id = ANY($1)', + [before.reviewed], + ); + expect(old.rows.map((row) => row.community_count)).toEqual([0, 0, 0, 0, 0]); + }); - it('refuses too few wines or the same wine twice, and changes nothing', async () => { - const wineIds = (await api.createWines(DEMO_WINE_COUNT - 1)).map(Number); - await expect( - withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })), - ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); - await expect( - withTransaction((client) => - seedDemoUser(client, { wineIds: [...wineIds, wineIds[0]], scryptParams: FAST_SCRYPT }), - ), - ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); - }); + it('refuses too few wines or the same wine twice, and changes nothing', async () => { + const wineIds = (await api.createWines(DEMO_WINE_COUNT - 1)).map(Number); + await expect( + withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })), + ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); + await expect( + withTransaction((client) => + seedDemoUser(client, { wineIds: [...wineIds, wineIds[0]], scryptParams: FAST_SCRYPT }), + ), + ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); + }); }); diff --git a/backend/src/demo/demo-user.ts b/backend/src/demo/demo-user.ts index 0fe3e48..4d0472b 100644 --- a/backend/src/demo/demo-user.ts +++ b/backend/src/demo/demo-user.ts @@ -13,18 +13,18 @@ export const DEMO_PASSWORD = 'kork-og-krone'; /** The reviews of the demo user, by the index of the wine in the list given to seedDemoUser. */ const REVIEWS: { wine: number; rating: number; comment: string }[] = [ - { wine: 0, rating: 5, comment: 'Favoritten. Fyldig og rund, perfekt til lam.' }, - { wine: 1, rating: 4.5, comment: 'Mye smak for pengene. Kjøper igjen.' }, - { wine: 2, rating: 4, comment: 'Frisk og lett, god til fisk.' }, - { wine: 10, rating: 3, comment: 'Grei nok, men litt tynn.' }, - { wine: 11, rating: 2.5, comment: 'For søt for min smak.' }, + { wine: 0, rating: 5, comment: 'Favoritten. Fyldig og rund, perfekt til lam.' }, + { wine: 1, rating: 4.5, comment: 'Mye smak for pengene. Kjøper igjen.' }, + { wine: 2, rating: 4, comment: 'Frisk og lett, god til fisk.' }, + { wine: 10, rating: 3, comment: 'Grei nok, men litt tynn.' }, + { wine: 11, rating: 2.5, comment: 'For søt for min smak.' }, ]; /** The lists, by wine index. The reviewed wines are put on «Har prøvd» by the reviews. */ const LISTS: { list: WineList; wines: number[] }[] = [ - { list: 'FAVOURITE', wines: [0, 1, 2, 3, 4, 5] }, - { list: 'TRIED', wines: [3, 12] }, - { list: 'WANT_TO_TRY', wines: [6, 7, 8, 9, 13] }, + { list: 'FAVOURITE', wines: [0, 1, 2, 3, 4, 5] }, + { list: 'TRIED', wines: [3, 12] }, + { list: 'WANT_TO_TRY', wines: [6, 7, 8, 9, 13] }, ]; /** The top 4, by wine index: chosen among the favourites, not just the first four. */ @@ -38,51 +38,57 @@ export const DEMO_WINE_COUNT = 14; * Uses the same functions as the API, so the demo data follows the same rules. */ export async function seedDemoUser( - client: PoolClient, - { wineIds, scryptParams = DEFAULT_SCRYPT_PARAMS }: { wineIds: number[]; scryptParams?: ScryptParams }, + client: PoolClient, + { + wineIds, + scryptParams = DEFAULT_SCRYPT_PARAMS, + }: { wineIds: number[]; scryptParams?: ScryptParams }, ): Promise<{ userId: number }> { - if (new Set(wineIds).size !== DEMO_WINE_COUNT || wineIds.length !== DEMO_WINE_COUNT) { - throw new Error(`The demo user needs ${DEMO_WINE_COUNT} different wines, got ${wineIds.length}.`); - } + if (new Set(wineIds).size !== DEMO_WINE_COUNT || wineIds.length !== DEMO_WINE_COUNT) { + throw new Error( + `The demo user needs ${DEMO_WINE_COUNT} different wines, got ${wineIds.length}.`, + ); + } - // Also resets the password, in case it was changed. - const passwordHash = await hashPassword(DEMO_PASSWORD, scryptParams); - const user = await client.query<{ id: number }>( - `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) + // Also resets the password, in case it was changed. + const passwordHash = await hashPassword(DEMO_PASSWORD, scryptParams); + const user = await client.query<{ id: number }>( + `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) ON CONFLICT (username) DO UPDATE SET password_hash = EXCLUDED.password_hash RETURNING id`, - [DEMO_USERNAME, passwordHash], - ); - const userId = user.rows[0].id; + [DEMO_USERNAME, passwordHash], + ); + const userId = user.rows[0].id; - // Start from nothing. The wines that lose a review need their average recalculated too. - const oldReviews = await client.query<{ wine_id: number }>( - 'DELETE FROM review WHERE user_id = $1 RETURNING wine_id', - [userId], - ); - await client.query('DELETE FROM user_wine WHERE user_id = $1', [userId]); + // Start from nothing. The wines that lose a review need their average recalculated too. + const oldReviews = await client.query<{ wine_id: number }>( + 'DELETE FROM review WHERE user_id = $1 RETURNING wine_id', + [userId], + ); + await client.query('DELETE FROM user_wine WHERE user_id = $1', [userId]); - for (const { list, wines } of LISTS) { - for (const index of wines) { - await setWineInList(client, { userId, wineId: wineIds[index], list, inList: true }); - } - } - for (const { wine, rating, comment } of REVIEWS) { - const wineId = wineIds[wine]; - await client.query('INSERT INTO review (wine_id, user_id, rating, comment) VALUES ($1, $2, $3, $4)', [ - wineId, - userId, - rating, - comment, - ]); - // The same rule as saveReview: a reviewed wine has been tried. - await setWineInList(client, { userId, wineId, list: 'TRIED', inList: true }); + for (const { list, wines } of LISTS) { + for (const index of wines) { + await setWineInList(client, { userId, wineId: wineIds[index], list, inList: true }); } - await setTopFavourites(client, { userId, wineIds: TOP_FAVOURITES.map((index) => wineIds[index]) }); + } + for (const { wine, rating, comment } of REVIEWS) { + const wineId = wineIds[wine]; + await client.query( + 'INSERT INTO review (wine_id, user_id, rating, comment) VALUES ($1, $2, $3, $4)', + [wineId, userId, rating, comment], + ); + // The same rule as saveReview: a reviewed wine has been tried. + await setWineInList(client, { userId, wineId, list: 'TRIED', inList: true }); + } + await setTopFavourites(client, { + userId, + wineIds: TOP_FAVOURITES.map((index) => wineIds[index]), + }); - const reviewed = REVIEWS.map(({ wine }) => wineIds[wine]); - const changed = new Set([...oldReviews.rows.map((row) => row.wine_id), ...reviewed]); - for (const wineId of changed) await client.query(UPDATE_WINE_RATING_STATS, [wineId]); + const reviewed = REVIEWS.map(({ wine }) => wineIds[wine]); + const changed = new Set([...oldReviews.rows.map((row) => row.wine_id), ...reviewed]); + for (const wineId of changed) await client.query(UPDATE_WINE_RATING_STATS, [wineId]); - return { userId }; + return { userId }; } diff --git a/backend/src/lists/lists-api.db.test.ts b/backend/src/lists/lists-api.db.test.ts index 7024192..aaa0b72 100644 --- a/backend/src/lists/lists-api.db.test.ts +++ b/backend/src/lists/lists-api.db.test.ts @@ -26,288 +26,308 @@ const DELETE_REVIEW = `mutation Delete($wineId: ID!) { deleteReview(wineId: $win const SET_TOP = `mutation SetTop($wineIds: [ID!]!) { setTopFavourites(wineIds: $wineIds) { id topFavourites { id } } }`; const TOP = `query Top { me { topFavourites { id } } }`; -type Page = { totalCount: number; edges: { node: { id: string } }[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }; +type Page = { + totalCount: number; + edges: { node: { id: string } }[]; + pageInfo: { hasNextPage: boolean; endCursor: string | null }; +}; -const listsOf = (result: GraphQLResult) => (result.data?.setWineInList ?? result.data?.wine) as { myLists: string[] }; +const listsOf = (result: GraphQLResult) => + (result.data?.setWineInList ?? result.data?.wine) as { myLists: string[] }; const pageOf = (result: GraphQLResult) => (result.data?.me as { wines: Page }).wines; const idsOf = (page: Page) => page.edges.map((edge) => edge.node.id); const topOf = (result: GraphQLResult) => { - const user = (result.data?.setTopFavourites ?? result.data?.me) as { topFavourites: { id: string }[] }; - return user.topFavourites.map((wine) => wine.id); + const user = (result.data?.setTopFavourites ?? result.data?.me) as { + topFavourites: { id: string }[]; + }; + return user.topFavourites.map((wine) => wine.id); }; describe.skipIf(!url)('wine lists API (PostgreSQL)', () => { - const api = createTestApi({ firstId: 800_000_000 }); - afterAll(() => api.close()); - - const set = (wineId: string, list: string, inList = true) => ({ wineId, list, inList }); - - describe('without login', () => { - it('cannot change a list, and has no lists of its own', async () => { - const [wine] = await api.createWines(1); - const visitor = await api.createBrowser(); - expect(codeOf(await visitor.request(SET, set(wine, 'FAVOURITE')))).toBe('UNAUTHENTICATED'); - expect(listsOf(await visitor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); - }); + const api = createTestApi({ firstId: 800_000_000 }); + afterAll(() => api.close()); + + const set = (wineId: string, list: string, inList = true) => ({ wineId, list, inList }); + + describe('without login', () => { + it('cannot change a list, and has no lists of its own', async () => { + const [wine] = await api.createWines(1); + const visitor = await api.createBrowser(); + expect(codeOf(await visitor.request(SET, set(wine, 'FAVOURITE')))).toBe('UNAUTHENTICATED'); + expect(listsOf(await visitor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); + }); + }); + + describe('setWineInList', () => { + it('puts a wine on a list and takes it off again, and doing it twice changes nothing', async () => { + const [wine] = await api.createWines(1); + const kari = await api.createBrowser('kari'); + + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual([ + 'FAVOURITE', + ]); + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual([ + 'FAVOURITE', + ]); + expect(pageOf(await kari.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(1); + + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); + }); + + it('lets a wine be on several lists, in a fixed order', async () => { + const [wine] = await api.createWines(1); + const ola = await api.createBrowser('ola'); + await ola.request(SET, set(wine, 'TRIED')); + const result = await ola.request(SET, set(wine, 'FAVOURITE')); + expect(listsOf(result).myLists).toEqual(['FAVOURITE', 'TRIED']); }); - describe('setWineInList', () => { - it('puts a wine on a list and takes it off again, and doing it twice changes nothing', async () => { - const [wine] = await api.createWines(1); - const kari = await api.createBrowser('kari'); - - expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual(['FAVOURITE']); - expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual(['FAVOURITE']); - expect(pageOf(await kari.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(1); - - expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); - expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); - }); - - it('lets a wine be on several lists, in a fixed order', async () => { - const [wine] = await api.createWines(1); - const ola = await api.createBrowser('ola'); - await ola.request(SET, set(wine, 'TRIED')); - const result = await ola.request(SET, set(wine, 'FAVOURITE')); - expect(listsOf(result).myLists).toEqual(['FAVOURITE', 'TRIED']); - }); - - it('takes a wine off «Vil prøve» when it goes on «Har prøvd»', async () => { - const [wine] = await api.createWines(1); - const per = await api.createBrowser('per'); - await per.request(SET, set(wine, 'WANT_TO_TRY')); - - const result = await per.request(SET, set(wine, 'TRIED')); - - expect(listsOf(result).myLists).toEqual(['TRIED']); - expect(pageOf(await per.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); - }); - - it('lets a tried wine go back on «Vil prøve», so it is on both lists', async () => { - // A choice, not an accident: the user may want to taste it again. Only «Har prøvd» - // moves a wine between the two lists, not «Vil prøve». - const [wine] = await api.createWines(1); - const eli = await api.createBrowser('eli'); - await eli.request(SET, set(wine, 'TRIED')); - - const result = await eli.request(SET, set(wine, 'WANT_TO_TRY')); - - expect(listsOf(result).myLists).toEqual(['WANT_TO_TRY', 'TRIED']); - }); - - it('keeps the lists of each user apart', async () => { - const [wine] = await api.createWines(1); - const anne = await api.createBrowser('anne'); - const tor = await api.createBrowser('tor'); - await anne.request(SET, set(wine, 'FAVOURITE')); - - expect(listsOf(await tor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); - expect(pageOf(await tor.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(0); - }); - - it('rejects a wine that does not exist, and an unknown list', async () => { - const kim = await api.createBrowser('kim'); - expect(codeOf(await kim.request(SET, set('1999999999', 'FAVOURITE')))).toBe('BAD_USER_INPUT'); - expect(codeOf(await kim.request(SET, set('1', 'WISHLIST')))).toBe('BAD_USER_INPUT'); - }); + it('takes a wine off «Vil prøve» when it goes on «Har prøvd»', async () => { + const [wine] = await api.createWines(1); + const per = await api.createBrowser('per'); + await per.request(SET, set(wine, 'WANT_TO_TRY')); + + const result = await per.request(SET, set(wine, 'TRIED')); + + expect(listsOf(result).myLists).toEqual(['TRIED']); + expect(pageOf(await per.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); }); - describe('User.wines', () => { - it('lists the newest first, one page at a time, without skipping when the list changes', async () => { - const [a, b, c] = await api.createWines(3); - const siv = await api.createBrowser('siv'); - for (const wine of [a, b, c]) await siv.request(SET, set(wine, 'WANT_TO_TRY')); - - const first = pageOf(await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2 })); - expect(first.totalCount).toBe(3); - expect(idsOf(first)).toEqual([c, b]); - expect(first.pageInfo.hasNextPage).toBe(true); - - // A wine shown on the first page is taken off before the next page. With an offset, - // the next page would start one wine too late and skip «a». - await siv.request(SET, set(c, 'WANT_TO_TRY', false)); - - const second = pageOf( - await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2, after: first.pageInfo.endCursor }), - ); - expect(idsOf(second)).toEqual([a]); - expect(second.pageInfo.hasNextPage).toBe(false); - }); - - it('rejects a cursor that was not made by the API', async () => { - const lise = await api.createBrowser('lise'); - expect(codeOf(await lise.request(LIST, { list: 'TRIED', after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT'); - }); + it('lets a tried wine go back on «Vil prøve», so it is on both lists', async () => { + // A choice, not an accident: the user may want to taste it again. Only «Har prøvd» + // moves a wine between the two lists, not «Vil prøve». + const [wine] = await api.createWines(1); + const eli = await api.createBrowser('eli'); + await eli.request(SET, set(wine, 'TRIED')); + + const result = await eli.request(SET, set(wine, 'WANT_TO_TRY')); + + expect(listsOf(result).myLists).toEqual(['WANT_TO_TRY', 'TRIED']); }); - describe('Wine.myLists', () => { - it('asks the database once for a whole page of wines', async () => { - const wines = await api.createWines(3); - const nina = await api.createBrowser('nina'); - for (const wine of wines) await nina.request(SET, set(wine, 'FAVOURITE')); - - // A real page, like the profile shows: all wines on it come from one query, so their - // myLists are asked for at the same time, and DataLoader sends them as one query. - const PAGE = `query { me { wines(list: FAVOURITE, first: 24) { edges { node { id myLists } } } } }`; - const spy = vi.spyOn(pool, 'query'); - try { - const page = pageOf(await nina.request(PAGE)); - expect(page.edges.map((edge) => edge.node)).toEqual( - [...wines].reverse().map((id) => ({ id, myLists: ['FAVOURITE'] })), - ); - // Only the loader's query: the page itself also reads user_wine, for the page and the count. - const myListsQueries = spy.mock.calls.filter(([sql]) => - String(sql).includes('SELECT wine_id, list FROM user_wine'), - ); - expect(myListsQueries).toHaveLength(1); - } finally { - spy.mockRestore(); - } - }); + it('keeps the lists of each user apart', async () => { + const [wine] = await api.createWines(1); + const anne = await api.createBrowser('anne'); + const tor = await api.createBrowser('tor'); + await anne.request(SET, set(wine, 'FAVOURITE')); + + expect(listsOf(await tor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); + expect(pageOf(await tor.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(0); }); - describe('top favourites', () => { - /** A logged-in user with `count` new wines, all on the favourites. */ - async function userWithFavourites(name: string, count: number) { - const wines = await api.createWines(count); - const browser = await api.createBrowser(name); - for (const wine of wines) await browser.request(SET, set(wine, 'FAVOURITE')); - return { browser, wines }; - } - - it('cannot be changed without login', async () => { - const visitor = await api.createBrowser(); - expect(codeOf(await visitor.request(SET_TOP, { wineIds: [] }))).toBe('UNAUTHENTICATED'); - }); - - it('keeps the order the user chose, and can be replaced and cleared', async () => { - const { browser: eva, wines } = await userWithFavourites('eva', 5); - const [a, b, c, d, e] = wines; - - expect(topOf(await eva.request(SET_TOP, { wineIds: [c, a, d, b] }))).toEqual([c, a, d, b]); - expect(topOf(await eva.request(TOP))).toEqual([c, a, d, b]); - - expect(topOf(await eva.request(SET_TOP, { wineIds: [e, c] }))).toEqual([e, c]); - expect(topOf(await eva.request(SET_TOP, { wineIds: [] }))).toEqual([]); - }); - - it('refuses more than four, a wine twice and wines that are not favourites, and keeps the old list', async () => { - const { browser: jon, wines } = await userWithFavourites('jon', 5); - const [a, b, c, d, e] = wines; - const [tried] = await api.createWines(1); - await jon.request(SET, set(tried, 'TRIED')); - await jon.request(SET_TOP, { wineIds: [a, b] }); - - for (const wineIds of [[a, b, c, d, e], [a, a], [a, tried], ['1999999999'], ['not-an-id']]) { - expect(codeOf(await jon.request(SET_TOP, { wineIds }))).toBe('BAD_USER_INPUT'); - } - expect(topOf(await jon.request(TOP))).toEqual([a, b]); - }); - - it('loses a wine that is taken off the favourites, and keeps the order of the rest', async () => { - const { browser: mia, wines } = await userWithFavourites('mia', 3); - const [a, b, c] = wines; - await mia.request(SET_TOP, { wineIds: [a, b, c] }); - - await mia.request(SET, set(b, 'FAVOURITE', false)); - - expect(topOf(await mia.request(TOP))).toEqual([a, c]); - // The free place can be used again. - await mia.request(SET, set(b, 'FAVOURITE')); - expect(topOf(await mia.request(SET_TOP, { wineIds: [b, a, c] }))).toEqual([b, a, c]); - }); - - it('keeps the lists of each user apart', async () => { - const { browser: ida, wines } = await userWithFavourites('ida', 1); - const { browser: leo } = await userWithFavourites('leo', 0); - await ida.request(SET_TOP, { wineIds: wines }); - - // Leo cannot use Ida's favourite, and does not see her top list as his own. - expect(codeOf(await leo.request(SET_TOP, { wineIds: wines }))).toBe('BAD_USER_INPUT'); - expect(topOf(await leo.request(TOP))).toEqual([]); - expect(topOf(await ida.request(TOP))).toEqual(wines); - }); - - it('handles two changes at the same time without an error, and ends with one of them', async () => { - const { browser: ask, wines } = await userWithFavourites('ask', 4); - const [a, b, c, d] = wines; - - const results = await Promise.all([ - ask.request(SET_TOP, { wineIds: [a, b, c, d] }), - ask.request(SET_TOP, { wineIds: [d, c, b, a] }), - ]); - - expect(results.map((result) => result.errors)).toEqual([undefined, undefined]); - expect([ - [a, b, c, d], - [d, c, b, a], - ]).toContainEqual(topOf(await ask.request(TOP))); - }); - - it('is checked by the database as well: at most one wine per place, and only favourites', async () => { - const { browser: ulf, wines } = await userWithFavourites('ulf', 2); - const [a, b] = wines; - await ulf.request(SET_TOP, { wineIds: [a] }); - const userId = ( - await pool.query<{ user_id: number }>( - "SELECT user_id FROM user_wine WHERE wine_id = $1 AND list = 'FAVOURITE'", - [Number(a)], - ) - ).rows[0].user_id; - - const setTop = (list: string, wine: string, position: number) => - pool.query( - `INSERT INTO user_wine (user_id, wine_id, list, top_position) VALUES ($1, $2, $3, $4) + it('rejects a wine that does not exist, and an unknown list', async () => { + const kim = await api.createBrowser('kim'); + expect(codeOf(await kim.request(SET, set('1999999999', 'FAVOURITE')))).toBe('BAD_USER_INPUT'); + expect(codeOf(await kim.request(SET, set('1', 'WISHLIST')))).toBe('BAD_USER_INPUT'); + }); + }); + + describe('User.wines', () => { + it('lists the newest first, one page at a time, without skipping when the list changes', async () => { + const [a, b, c] = await api.createWines(3); + const siv = await api.createBrowser('siv'); + for (const wine of [a, b, c]) await siv.request(SET, set(wine, 'WANT_TO_TRY')); + + const first = pageOf(await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2 })); + expect(first.totalCount).toBe(3); + expect(idsOf(first)).toEqual([c, b]); + expect(first.pageInfo.hasNextPage).toBe(true); + + // A wine shown on the first page is taken off before the next page. With an offset, + // the next page would start one wine too late and skip «a». + await siv.request(SET, set(c, 'WANT_TO_TRY', false)); + + const second = pageOf( + await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2, after: first.pageInfo.endCursor }), + ); + expect(idsOf(second)).toEqual([a]); + expect(second.pageInfo.hasNextPage).toBe(false); + }); + + it('rejects a cursor that was not made by the API', async () => { + const lise = await api.createBrowser('lise'); + expect(codeOf(await lise.request(LIST, { list: 'TRIED', after: 'not-a-cursor' }))).toBe( + 'BAD_USER_INPUT', + ); + }); + }); + + describe('Wine.myLists', () => { + it('asks the database once for a whole page of wines', async () => { + const wines = await api.createWines(3); + const nina = await api.createBrowser('nina'); + for (const wine of wines) await nina.request(SET, set(wine, 'FAVOURITE')); + + // A real page, like the profile shows: all wines on it come from one query, so their + // myLists are asked for at the same time, and DataLoader sends them as one query. + const PAGE = `query { me { wines(list: FAVOURITE, first: 24) { edges { node { id myLists } } } } }`; + const spy = vi.spyOn(pool, 'query'); + try { + const page = pageOf(await nina.request(PAGE)); + expect(page.edges.map((edge) => edge.node)).toEqual( + [...wines].reverse().map((id) => ({ id, myLists: ['FAVOURITE'] })), + ); + // Only the loader's query: the page itself also reads user_wine, for the page and the count. + const myListsQueries = spy.mock.calls.filter(([sql]) => + String(sql).includes('SELECT wine_id, list FROM user_wine'), + ); + expect(myListsQueries).toHaveLength(1); + } finally { + spy.mockRestore(); + } + }); + }); + + describe('top favourites', () => { + /** A logged-in user with `count` new wines, all on the favourites. */ + async function userWithFavourites(name: string, count: number) { + const wines = await api.createWines(count); + const browser = await api.createBrowser(name); + for (const wine of wines) await browser.request(SET, set(wine, 'FAVOURITE')); + return { browser, wines }; + } + + it('cannot be changed without login', async () => { + const visitor = await api.createBrowser(); + expect(codeOf(await visitor.request(SET_TOP, { wineIds: [] }))).toBe('UNAUTHENTICATED'); + }); + + it('keeps the order the user chose, and can be replaced and cleared', async () => { + const { browser: eva, wines } = await userWithFavourites('eva', 5); + const [a, b, c, d, e] = wines; + + expect(topOf(await eva.request(SET_TOP, { wineIds: [c, a, d, b] }))).toEqual([c, a, d, b]); + expect(topOf(await eva.request(TOP))).toEqual([c, a, d, b]); + + expect(topOf(await eva.request(SET_TOP, { wineIds: [e, c] }))).toEqual([e, c]); + expect(topOf(await eva.request(SET_TOP, { wineIds: [] }))).toEqual([]); + }); + + it('refuses more than four, a wine twice and wines that are not favourites, and keeps the old list', async () => { + const { browser: jon, wines } = await userWithFavourites('jon', 5); + const [a, b, c, d, e] = wines; + const [tried] = await api.createWines(1); + await jon.request(SET, set(tried, 'TRIED')); + await jon.request(SET_TOP, { wineIds: [a, b] }); + + for (const wineIds of [[a, b, c, d, e], [a, a], [a, tried], ['1999999999'], ['not-an-id']]) { + expect(codeOf(await jon.request(SET_TOP, { wineIds }))).toBe('BAD_USER_INPUT'); + } + expect(topOf(await jon.request(TOP))).toEqual([a, b]); + }); + + it('loses a wine that is taken off the favourites, and keeps the order of the rest', async () => { + const { browser: mia, wines } = await userWithFavourites('mia', 3); + const [a, b, c] = wines; + await mia.request(SET_TOP, { wineIds: [a, b, c] }); + + await mia.request(SET, set(b, 'FAVOURITE', false)); + + expect(topOf(await mia.request(TOP))).toEqual([a, c]); + // The free place can be used again. + await mia.request(SET, set(b, 'FAVOURITE')); + expect(topOf(await mia.request(SET_TOP, { wineIds: [b, a, c] }))).toEqual([b, a, c]); + }); + + it('keeps the lists of each user apart', async () => { + const { browser: ida, wines } = await userWithFavourites('ida', 1); + const { browser: leo } = await userWithFavourites('leo', 0); + await ida.request(SET_TOP, { wineIds: wines }); + + // Leo cannot use Ida's favourite, and does not see her top list as his own. + expect(codeOf(await leo.request(SET_TOP, { wineIds: wines }))).toBe('BAD_USER_INPUT'); + expect(topOf(await leo.request(TOP))).toEqual([]); + expect(topOf(await ida.request(TOP))).toEqual(wines); + }); + + it('handles two changes at the same time without an error, and ends with one of them', async () => { + const { browser: ask, wines } = await userWithFavourites('ask', 4); + const [a, b, c, d] = wines; + + const results = await Promise.all([ + ask.request(SET_TOP, { wineIds: [a, b, c, d] }), + ask.request(SET_TOP, { wineIds: [d, c, b, a] }), + ]); + + expect(results.map((result) => result.errors)).toEqual([undefined, undefined]); + expect([ + [a, b, c, d], + [d, c, b, a], + ]).toContainEqual(topOf(await ask.request(TOP))); + }); + + it('is checked by the database as well: at most one wine per place, and only favourites', async () => { + const { browser: ulf, wines } = await userWithFavourites('ulf', 2); + const [a, b] = wines; + await ulf.request(SET_TOP, { wineIds: [a] }); + const userId = ( + await pool.query<{ user_id: number }>( + "SELECT user_id FROM user_wine WHERE wine_id = $1 AND list = 'FAVOURITE'", + [Number(a)], + ) + ).rows[0].user_id; + + const setTop = (list: string, wine: string, position: number) => + pool.query( + `INSERT INTO user_wine (user_id, wine_id, list, top_position) VALUES ($1, $2, $3, $4) ON CONFLICT ON CONSTRAINT user_wine_once DO UPDATE SET top_position = EXCLUDED.top_position`, - [userId, Number(wine), list, position], - ); - - await expect(setTop('FAVOURITE', b, 1)).rejects.toMatchObject({ code: '23505', constraint: 'user_wine_top' }); - await expect(setTop('TRIED', b, 2)).rejects.toMatchObject({ - code: '23514', - constraint: 'user_wine_top_only_favourites', - }); - }); + [userId, Number(wine), list, position], + ); + + await expect(setTop('FAVOURITE', b, 1)).rejects.toMatchObject({ + code: '23505', + constraint: 'user_wine_top', + }); + await expect(setTop('TRIED', b, 2)).rejects.toMatchObject({ + code: '23514', + constraint: 'user_wine_top_only_favourites', + }); + }); + }); + + describe('a saved review', () => { + const review = (wineId: string, rating = 4) => ({ + input: { wineId, rating, comment: 'Smakte godt' }, }); - describe('a saved review', () => { - const review = (wineId: string, rating = 4) => ({ input: { wineId, rating, comment: 'Smakte godt' } }); - - it('puts the wine on «Har prøvd» and takes it off «Vil prøve»', async () => { - const [wine] = await api.createWines(1); - const rut = await api.createBrowser('rut'); - await rut.request(SET, set(wine, 'WANT_TO_TRY')); - await rut.request(SET, set(wine, 'FAVOURITE')); - - const result = await rut.request(SAVE_REVIEW, review(wine)); - - expect(result.errors).toBeUndefined(); - const saved = result.data?.saveReview as { wine: { myLists: string[] } }; - expect(saved.wine.myLists).toEqual(['FAVOURITE', 'TRIED']); - expect(pageOf(await rut.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); - }); - - it('keeps the wine once on «Har prøvd» when the review is edited, and there when it is deleted', async () => { - const [wine] = await api.createWines(1); - const bo = await api.createBrowser('bo'); - await bo.request(SAVE_REVIEW, review(wine, 3)); - await bo.request(SAVE_REVIEW, review(wine, 4.5)); - expect(pageOf(await bo.request(LIST, { list: 'TRIED' })).totalCount).toBe(1); - - expect((await bo.request(DELETE_REVIEW, { wineId: wine })).data).toEqual({ deleteReview: true }); - expect(listsOf(await bo.request(MY_LISTS, { id: wine })).myLists).toEqual(['TRIED']); - }); - - it('changes no list when the review is refused', async () => { - const [wine] = await api.createWines(1); - const vera = await api.createBrowser('vera'); - await vera.request(SET, set(wine, 'WANT_TO_TRY')); - - expect(codeOf(await vera.request(SAVE_REVIEW, review(wine, 7)))).toBe('BAD_USER_INPUT'); - expect(codeOf(await vera.request(SAVE_REVIEW, review('1999999999')))).toBe('BAD_USER_INPUT'); - - expect(listsOf(await vera.request(MY_LISTS, { id: wine })).myLists).toEqual(['WANT_TO_TRY']); - expect(pageOf(await vera.request(LIST, { list: 'TRIED' })).totalCount).toBe(0); - }); + it('puts the wine on «Har prøvd» and takes it off «Vil prøve»', async () => { + const [wine] = await api.createWines(1); + const rut = await api.createBrowser('rut'); + await rut.request(SET, set(wine, 'WANT_TO_TRY')); + await rut.request(SET, set(wine, 'FAVOURITE')); + + const result = await rut.request(SAVE_REVIEW, review(wine)); + + expect(result.errors).toBeUndefined(); + const saved = result.data?.saveReview as { wine: { myLists: string[] } }; + expect(saved.wine.myLists).toEqual(['FAVOURITE', 'TRIED']); + expect(pageOf(await rut.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); + }); + + it('keeps the wine once on «Har prøvd» when the review is edited, and there when it is deleted', async () => { + const [wine] = await api.createWines(1); + const bo = await api.createBrowser('bo'); + await bo.request(SAVE_REVIEW, review(wine, 3)); + await bo.request(SAVE_REVIEW, review(wine, 4.5)); + expect(pageOf(await bo.request(LIST, { list: 'TRIED' })).totalCount).toBe(1); + + expect((await bo.request(DELETE_REVIEW, { wineId: wine })).data).toEqual({ + deleteReview: true, + }); + expect(listsOf(await bo.request(MY_LISTS, { id: wine })).myLists).toEqual(['TRIED']); + }); + + it('changes no list when the review is refused', async () => { + const [wine] = await api.createWines(1); + const vera = await api.createBrowser('vera'); + await vera.request(SET, set(wine, 'WANT_TO_TRY')); + + expect(codeOf(await vera.request(SAVE_REVIEW, review(wine, 7)))).toBe('BAD_USER_INPUT'); + expect(codeOf(await vera.request(SAVE_REVIEW, review('1999999999')))).toBe('BAD_USER_INPUT'); + + expect(listsOf(await vera.request(MY_LISTS, { id: wine })).myLists).toEqual(['WANT_TO_TRY']); + expect(pageOf(await vera.request(LIST, { list: 'TRIED' })).totalCount).toBe(0); }); + }); }); diff --git a/backend/src/lists/resolvers.ts b/backend/src/lists/resolvers.ts index e70e097..3e4ff40 100644 --- a/backend/src/lists/resolvers.ts +++ b/backend/src/lists/resolvers.ts @@ -9,93 +9,94 @@ import { withTransaction } from '../db'; import { toWine } from '../resolvers'; import { validateWineId } from '../review-input'; import { - findListPage, - findTopFavourites, - setTopFavourites, - setWineInList, - TopFavouritesError, - type WineList, + findListPage, + findTopFavourites, + setTopFavourites, + setWineInList, + TopFavouritesError, + type WineList, } from './wine-lists'; /** The most wines one page of a list can have. */ const MAX_PAGE_SIZE = 50; -const badInput = (message: string) => new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); +const badInput = (message: string) => + new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); const wineNotFound = () => badInput('Wine not found.'); export const listResolvers = { - Mutation: { - async setWineInList( - _parent: unknown, - args: { wineId: string; list: WineList; inList: boolean }, - { auth, loaders }: Context, - ) { - const user = await auth.requireUser(); - const wineId = validateWineId(args.wineId); - try { - await withTransaction((client) => - setWineInList(client, { userId: user.id, wineId, list: args.list, inList: args.inList }), - ); - } catch (error) { - if (isForeignKeyViolation(error, 'user_wine_wine_id_fkey')) throw wineNotFound(); - // The account was deleted after the session was checked, in the same moment. - if (isForeignKeyViolation(error, 'user_wine_user_id_fkey')) { - throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); - } - throw error; - } + Mutation: { + async setWineInList( + _parent: unknown, + args: { wineId: string; list: WineList; inList: boolean }, + { auth, loaders }: Context, + ) { + const user = await auth.requireUser(); + const wineId = validateWineId(args.wineId); + try { + await withTransaction((client) => + setWineInList(client, { userId: user.id, wineId, list: args.list, inList: args.inList }), + ); + } catch (error) { + if (isForeignKeyViolation(error, 'user_wine_wine_id_fkey')) throw wineNotFound(); + // The account was deleted after the session was checked, in the same moment. + if (isForeignKeyViolation(error, 'user_wine_user_id_fkey')) { + throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + } + throw error; + } - // The answer must show the lists after the change. - loaders.myLists(user.id).clear(wineId); - const row = await loaders.wines.load(wineId); - if (!row) throw wineNotFound(); - return toWine(row); - }, + // The answer must show the lists after the change. + loaders.myLists(user.id).clear(wineId); + const row = await loaders.wines.load(wineId); + if (!row) throw wineNotFound(); + return toWine(row); + }, - async setTopFavourites(_parent: unknown, args: { wineIds: string[] }, { auth }: Context) { - const user = await auth.requireUser(); - const wineIds = args.wineIds.map(validateWineId); - try { - await withTransaction((client) => setTopFavourites(client, { userId: user.id, wineIds })); - } catch (error) { - if (error instanceof TopFavouritesError) throw badInput(error.message); - throw error; - } - return toGraphQLUser(user); - }, + async setTopFavourites(_parent: unknown, args: { wineIds: string[] }, { auth }: Context) { + const user = await auth.requireUser(); + const wineIds = args.wineIds.map(validateWineId); + try { + await withTransaction((client) => setTopFavourites(client, { userId: user.id, wineIds })); + } catch (error) { + if (error instanceof TopFavouritesError) throw badInput(error.message); + throw error; + } + return toGraphQLUser(user); }, + }, - // Lists are public, so this works for any user, also on other users' profiles later. - User: { - async wines( - user: { id: string }, - args: { list: WineList; first?: number | null; after?: string | null }, - ) { - const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); - const { rows, totalCount } = await findListPage({ - userId: Number(user.id), - list: args.list, - first, - after: args.after, - }); - return toConnection({ - rows, - first, - totalCount, - toNode: toWine, - cursorFor: (row) => encodeIdCursor(row.entry_id), - }); - }, + // Lists are public, so this works for any user, also on other users' profiles later. + User: { + async wines( + user: { id: string }, + args: { list: WineList; first?: number | null; after?: string | null }, + ) { + const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); + const { rows, totalCount } = await findListPage({ + userId: Number(user.id), + list: args.list, + first, + after: args.after, + }); + return toConnection({ + rows, + first, + totalCount, + toNode: toWine, + cursorFor: (row) => encodeIdCursor(row.entry_id), + }); + }, - async topFavourites(user: { id: string }) { - return (await findTopFavourites(Number(user.id))).map(toWine); - }, + async topFavourites(user: { id: string }) { + return (await findTopFavourites(Number(user.id))).map(toWine); }, + }, - Wine: { - async myLists(wine: { id: string }, _args: unknown, { auth, loaders }: Context) { - const user = await auth.currentUser(); - return user ? loaders.myLists(user.id).load(Number(wine.id)) : []; - }, + Wine: { + async myLists(wine: { id: string }, _args: unknown, { auth, loaders }: Context) { + const user = await auth.currentUser(); + return user ? loaders.myLists(user.id).load(Number(wine.id)) : []; }, + }, }; diff --git a/backend/src/lists/wine-lists.ts b/backend/src/lists/wine-lists.ts index 99a7776..630364d 100644 --- a/backend/src/lists/wine-lists.ts +++ b/backend/src/lists/wine-lists.ts @@ -13,7 +13,7 @@ export type WineList = (typeof WINE_LISTS)[number]; /** The lists in a fixed order, so the API always answers the same way. */ export function sortLists(lists: WineList[]): WineList[] { - return WINE_LISTS.filter((list) => lists.includes(list)); + return WINE_LISTS.filter((list) => lists.includes(list)); } /** @@ -21,29 +21,34 @@ export function sortLists(lists: WineList[]): WineList[] { * Rule: a wine on «Har prøvd» is taken off «Vil prøve». */ export async function setWineInList( - client: PoolClient, - { userId, wineId, list, inList }: { userId: number; wineId: number; list: WineList; inList: boolean }, + client: PoolClient, + { + userId, + wineId, + list, + inList, + }: { userId: number; wineId: number; list: WineList; inList: boolean }, ): Promise { - if (!inList) { - await client.query('DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = $3', [ - userId, - wineId, - list, - ]); - return; - } + if (!inList) { + await client.query('DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = $3', [ + userId, + wineId, + list, + ]); + return; + } - await client.query( - `INSERT INTO user_wine (user_id, wine_id, list) VALUES ($1, $2, $3) + await client.query( + `INSERT INTO user_wine (user_id, wine_id, list) VALUES ($1, $2, $3) ON CONFLICT ON CONSTRAINT user_wine_once DO NOTHING`, - [userId, wineId, list], + [userId, wineId, list], + ); + if (list === 'TRIED') { + await client.query( + "DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = 'WANT_TO_TRY'", + [userId, wineId], ); - if (list === 'TRIED') { - await client.query( - "DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = 'WANT_TO_TRY'", - [userId, wineId], - ); - } + } } /** How many wines the top list among the favourites can hold. Same limit as the CHECK on top_position. */ @@ -58,78 +63,86 @@ export class TopFavouritesError extends Error {} * Taking a wine off the favourites deletes its row, and with it its place in the top list. */ export async function setTopFavourites( - client: PoolClient, - { userId, wineIds }: { userId: number; wineIds: number[] }, + client: PoolClient, + { userId, wineIds }: { userId: number; wineIds: number[] }, ): Promise { - if (wineIds.length > MAX_TOP_FAVOURITES) { - throw new TopFavouritesError(`The top list can hold at most ${MAX_TOP_FAVOURITES} wines.`); - } - if (new Set(wineIds).size !== wineIds.length) { - throw new TopFavouritesError('A wine can only be in the top list once.'); - } + if (wineIds.length > MAX_TOP_FAVOURITES) { + throw new TopFavouritesError(`The top list can hold at most ${MAX_TOP_FAVOURITES} wines.`); + } + if (new Set(wineIds).size !== wineIds.length) { + throw new TopFavouritesError('A wine can only be in the top list once.'); + } - // One change of the top list at a time per user. Without the lock, two changes at the same - // time could both pass the first UPDATE and then collide on the index user_wine_top. - // NO KEY UPDATE does not block the foreign key checks when the user adds wines or reviews. - await client.query('SELECT 1 FROM app_user WHERE id = $1 FOR NO KEY UPDATE', [userId]); + // One change of the top list at a time per user. Without the lock, two changes at the same + // time could both pass the first UPDATE and then collide on the index user_wine_top. + // NO KEY UPDATE does not block the foreign key checks when the user adds wines or reviews. + await client.query('SELECT 1 FROM app_user WHERE id = $1 FOR NO KEY UPDATE', [userId]); - // Clear first, so the new positions never collide with the old ones on the unique index. - await client.query( - 'UPDATE user_wine SET top_position = NULL WHERE user_id = $1 AND top_position IS NOT NULL', - [userId], - ); - const placed = await client.query( - `UPDATE user_wine SET top_position = top.position + // Clear first, so the new positions never collide with the old ones on the unique index. + await client.query( + 'UPDATE user_wine SET top_position = NULL WHERE user_id = $1 AND top_position IS NOT NULL', + [userId], + ); + const placed = await client.query( + `UPDATE user_wine SET top_position = top.position FROM unnest($2::integer[]) WITH ORDINALITY AS top(wine_id, position) WHERE user_wine.user_id = $1 AND user_wine.list = 'FAVOURITE' AND user_wine.wine_id = top.wine_id`, - [userId, wineIds], - ); - // A wine that is not a favourite (or does not exist) matched no row. Throwing rolls back the - // transaction, so the old top list is kept. - if (placed.rowCount !== wineIds.length) { - throw new TopFavouritesError('Only favourites can be in the top list.'); - } + [userId, wineIds], + ); + // A wine that is not a favourite (or does not exist) matched no row. Throwing rolls back the + // transaction, so the old top list is kept. + if (placed.rowCount !== wineIds.length) { + throw new TopFavouritesError('Only favourites can be in the top list.'); + } } /** The user's top list, position 1 first. Positions can have gaps after a favourite is removed. */ export async function findTopFavourites(userId: number) { - const { rows } = await pool.query( - `SELECT wine.* + const { rows } = await pool.query( + `SELECT wine.* FROM user_wine JOIN wine ON wine.id = user_wine.wine_id WHERE user_wine.user_id = $1 AND user_wine.top_position IS NOT NULL ORDER BY user_wine.top_position`, - [userId], - ); - return rows; + [userId], + ); + return rows; } /** A row of the wine table, plus the id of its row in the list (for the cursor). */ export interface ListedWineRow extends WineRow { - entry_id: number; + entry_id: number; } /** One page of a list, newest first, and how many wines the list has in all. */ -export async function findListPage( - { userId, list, first, after }: { userId: number; list: WineList; first: number; after?: string | null }, -) { - const before = decodeIdCursor(after); - // The index user_wine_list_newest covers both queries. - const [page, count] = await Promise.all([ - pool.query( - `SELECT wine.*, user_wine.id AS entry_id +export async function findListPage({ + userId, + list, + first, + after, +}: { + userId: number; + list: WineList; + first: number; + after?: string | null; +}) { + const before = decodeIdCursor(after); + // The index user_wine_list_newest covers both queries. + const [page, count] = await Promise.all([ + pool.query( + `SELECT wine.*, user_wine.id AS entry_id FROM user_wine JOIN wine ON wine.id = user_wine.wine_id WHERE user_wine.user_id = $1 AND user_wine.list = $2 AND ($3::integer IS NULL OR user_wine.id < $3) ORDER BY user_wine.id DESC LIMIT $4`, - [userId, list, before, first + 1], - ), - pool.query<{ total: number }>( - 'SELECT count(*)::int AS total FROM user_wine WHERE user_id = $1 AND list = $2', - [userId, list], - ), - ]); - return { rows: page.rows, totalCount: count.rows[0].total }; + [userId, list, before, first + 1], + ), + pool.query<{ total: number }>( + 'SELECT count(*)::int AS total FROM user_wine WHERE user_id = $1 AND list = $2', + [userId, list], + ), + ]); + return { rows: page.rows, totalCount: count.rows[0].total }; } diff --git a/backend/src/loaders.ts b/backend/src/loaders.ts index e4530dc..b363669 100644 --- a/backend/src/loaders.ts +++ b/backend/src/loaders.ts @@ -6,74 +6,74 @@ import { sortLists, type WineList } from './lists/wine-lists'; // A row from the wine table, as returned by pg. export interface WineRow { - id: number; - name: string; - type: string; - elaborate: string | null; - grapes: string[]; - harmonize: string[]; - abv: string | null; // pg returns numeric columns as strings - body: string | null; - acidity: string | null; - country_code: string | null; - country: string | null; - region_name: string | null; - winery_name: string | null; - website: string | null; - vintages: number[]; - community_avg: string | null; - community_count: number; + id: number; + name: string; + type: string; + elaborate: string | null; + grapes: string[]; + harmonize: string[]; + abv: string | null; // pg returns numeric columns as strings + body: string | null; + acidity: string | null; + country_code: string | null; + country: string | null; + region_name: string | null; + winery_name: string | null; + website: string | null; + vintages: number[]; + community_avg: string | null; + community_count: number; } // A row from the review table. Exactly one of user_id and student_id is set: // user_id for reviews written with an account, student_id for old anonymous reviews. export interface ReviewRow { - id: number; - wine_id: number; - user_id: number | null; - student_id: number | null; - rating: string; // pg returns numeric columns as strings - comment: string | null; - created_at: Date; - updated_at: Date; + id: number; + wine_id: number; + user_id: number | null; + student_id: number | null; + rating: string; // pg returns numeric columns as strings + comment: string | null; + created_at: Date; + updated_at: Date; } export interface StudentRating { - average: number | null; - count: number; + average: number | null; + count: number; } export interface RatingCount { - rating: number; - count: number; + rating: number; + count: number; } /** New loaders for every request, so data is never cached between users or requests. */ export function createLoaders() { - const wines = new DataLoader(async (ids) => { - const result = await pool.query('SELECT * FROM wine WHERE id = ANY($1)', [[...ids]]); - const byId = new Map(result.rows.map((row) => [row.id, row])); - return ids.map((id) => byId.get(id) ?? null); - }); + const wines = new DataLoader(async (ids) => { + const result = await pool.query('SELECT * FROM wine WHERE id = ANY($1)', [[...ids]]); + const byId = new Map(result.rows.map((row) => [row.id, row])); + return ids.map((id) => byId.get(id) ?? null); + }); - const studentRatings = new DataLoader(async (wineIds) => { - const result = await pool.query<{ wine_id: number; average: number; count: number }>( - `SELECT wine_id, AVG(rating)::float AS average, COUNT(*)::int AS count + const studentRatings = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; average: number; count: number }>( + `SELECT wine_id, AVG(rating)::float AS average, COUNT(*)::int AS count FROM review WHERE wine_id = ANY($1) GROUP BY wine_id`, - [[...wineIds]], - ); - const byWine = new Map(result.rows.map((row) => [row.wine_id, row])); - return wineIds.map((id) => { - const row = byWine.get(id); - return row ? { average: row.average, count: row.count } : { average: null, count: 0 }; - }); + [[...wineIds]], + ); + const byWine = new Map(result.rows.map((row) => [row.wine_id, row])); + return wineIds.map((id) => { + const row = byWine.get(id); + return row ? { average: row.average, count: row.count } : { average: null, count: 0 }; }); + }); - const ratingDistributions = new DataLoader(async (wineIds) => { - const result = await pool.query<{ wine_id: number; rating: number; count: number }>( - `SELECT wine_id, rating::float AS rating, count(*)::int AS count + const ratingDistributions = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; rating: number; count: number }>( + `SELECT wine_id, rating::float AS rating, count(*)::int AS count FROM ( SELECT wine_id, rating FROM community_rating WHERE wine_id = ANY($1) UNION ALL @@ -81,25 +81,25 @@ export function createLoaders() { ) AS all_ratings GROUP BY wine_id, rating ORDER BY rating DESC`, - [[...wineIds]], - ); - return wineIds.map((id) => - result.rows - .filter((row) => row.wine_id === id) - .map(({ rating, count }) => ({ rating, count })), - ); - }); + [[...wineIds]], + ); + return wineIds.map((id) => + result.rows + .filter((row) => row.wine_id === id) + .map(({ rating, count }) => ({ rating, count })), + ); + }); - // One loader per page size, because "first" is part of the query. - const reviewLoaders = new Map>(); + // One loader per page size, because "first" is part of the query. + const reviewLoaders = new Map>(); - function reviews(first: number) { - let loader = reviewLoaders.get(first); - if (!loader) { - loader = new DataLoader(async (wineIds) => { - // row_number() numbers each wine's reviews, newest first, so we keep the first N per wine. - const result = await pool.query( - `SELECT id, wine_id, user_id, student_id, rating, comment, created_at, updated_at + function reviews(first: number) { + let loader = reviewLoaders.get(first); + if (!loader) { + loader = new DataLoader(async (wineIds) => { + // row_number() numbers each wine's reviews, newest first, so we keep the first N per wine. + const result = await pool.query( + `SELECT id, wine_id, user_id, student_id, rating, comment, created_at, updated_at FROM ( SELECT *, row_number() OVER (PARTITION BY wine_id ORDER BY updated_at DESC, id DESC) AS position FROM review @@ -107,47 +107,47 @@ export function createLoaders() { ) numbered WHERE position <= $2 ORDER BY updated_at DESC, id DESC`, - [[...wineIds], first], - ); - return wineIds.map((id) => result.rows.filter((row) => row.wine_id === id)); - }); - reviewLoaders.set(first, loader); - } - return loader; + [[...wineIds], first], + ); + return wineIds.map((id) => result.rows.filter((row) => row.wine_id === id)); + }); + reviewLoaders.set(first, loader); } + return loader; + } - // Only the username is read, never the password hash. - const usernames = new DataLoader(async (userIds) => { - const result = await pool.query<{ id: number; username: string }>( - 'SELECT id, username FROM app_user WHERE id = ANY($1)', - [[...userIds]], - ); - const byId = new Map(result.rows.map((row) => [row.id, row.username])); - return userIds.map((id) => byId.get(id) ?? null); - }); + // Only the username is read, never the password hash. + const usernames = new DataLoader(async (userIds) => { + const result = await pool.query<{ id: number; username: string }>( + 'SELECT id, username FROM app_user WHERE id = ANY($1)', + [[...userIds]], + ); + const byId = new Map(result.rows.map((row) => [row.id, row.username])); + return userIds.map((id) => byId.get(id) ?? null); + }); - // One loader per user, because the user is part of the query. In practice there is only one: - // the logged-in user. A page of wines then asks for their lists in one query. - const listLoaders = new Map>(); + // One loader per user, because the user is part of the query. In practice there is only one: + // the logged-in user. A page of wines then asks for their lists in one query. + const listLoaders = new Map>(); - function myLists(userId: number) { - let loader = listLoaders.get(userId); - if (!loader) { - loader = new DataLoader(async (wineIds) => { - const result = await pool.query<{ wine_id: number; list: WineList }>( - 'SELECT wine_id, list FROM user_wine WHERE user_id = $1 AND wine_id = ANY($2)', - [userId, [...wineIds]], - ); - return wineIds.map((id) => - sortLists(result.rows.filter((row) => row.wine_id === id).map((row) => row.list)), - ); - }); - listLoaders.set(userId, loader); - } - return loader; + function myLists(userId: number) { + let loader = listLoaders.get(userId); + if (!loader) { + loader = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; list: WineList }>( + 'SELECT wine_id, list FROM user_wine WHERE user_id = $1 AND wine_id = ANY($2)', + [userId, [...wineIds]], + ); + return wineIds.map((id) => + sortLists(result.rows.filter((row) => row.wine_id === id).map((row) => row.list)), + ); + }); + listLoaders.set(userId, loader); } + return loader; + } - return { wines, studentRatings, ratingDistributions, reviews, usernames, myLists }; + return { wines, studentRatings, ratingDistributions, reviews, usernames, myLists }; } -export type Loaders = ReturnType; \ No newline at end of file +export type Loaders = ReturnType; diff --git a/backend/src/rating-stats.ts b/backend/src/rating-stats.ts index 455236f..fb1bb58 100644 --- a/backend/src/rating-stats.ts +++ b/backend/src/rating-stats.ts @@ -35,4 +35,4 @@ export const UPDATE_WINE_RATING_STATS = ` WHERE wine_id = $1 ) AS stats WHERE wine.id = $1 -`; \ No newline at end of file +`; diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index a3abfb3..72e08a6 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -9,11 +9,11 @@ import { setWineInList } from './lists/wine-lists'; import { type ReviewRow, type WineRow } from './loaders'; import { validateReviewInput, validateWineId, type ReviewInput } from './review-input'; import { - buildFilterOptionsQueries, - buildWinesQuery, - encodeCursor, - type FilterArgs, - type WinesArgs, + buildFilterOptionsQueries, + buildWinesQuery, + encodeCursor, + type FilterArgs, + type WinesArgs, } from './wine-query'; import { UPDATE_WINE_RATING_STATS } from './rating-stats'; @@ -22,239 +22,240 @@ const MAX_REVIEWS = 50; // Converts database names (snake_case) to GraphQL names (camelCase). Also used by the lists. export function toWine(row: WineRow) { - return { - id: String(row.id), - name: row.name, - type: row.type, - elaborate: row.elaborate, - grapes: row.grapes, - harmonize: row.harmonize, - abv: row.abv === null ? null : Number(row.abv), - body: row.body, - acidity: row.acidity, - countryCode: row.country_code, - country: row.country, - regionName: row.region_name, - wineryName: row.winery_name, - website: row.website, - vintages: row.vintages, - communityRating: row.community_avg === null ? null : Number(row.community_avg), - communityRatingCount: row.community_count, - }; + return { + id: String(row.id), + name: row.name, + type: row.type, + elaborate: row.elaborate, + grapes: row.grapes, + harmonize: row.harmonize, + abv: row.abv === null ? null : Number(row.abv), + body: row.body, + acidity: row.acidity, + countryCode: row.country_code, + country: row.country, + regionName: row.region_name, + wineryName: row.winery_name, + website: row.website, + vintages: row.vintages, + communityRating: row.community_avg === null ? null : Number(row.community_avg), + communityRatingCount: row.community_count, + }; } // The author is resolved in Review.author, so a page of reviews looks up the usernames in one query. function toReview(row: ReviewRow) { - return { - id: String(row.id), - wineId: row.wine_id, - userId: row.user_id, - rating: Number(row.rating), - comment: row.comment, - createdAt: row.created_at.toISOString(), - updatedAt: row.updated_at.toISOString(), - }; + return { + id: String(row.id), + wineId: row.wine_id, + userId: row.user_id, + rating: Number(row.rating), + comment: row.comment, + createdAt: row.created_at.toISOString(), + updatedAt: row.updated_at.toISOString(), + }; } /** Keeps "first" between 1 and MAX_REVIEWS, whatever the frontend sends. */ function limitReviews(first: number | null | undefined, fallback: number): number { - return Math.min(Math.max(first ?? fallback, 1), MAX_REVIEWS); + return Math.min(Math.max(first ?? fallback, 1), MAX_REVIEWS); } async function filterOptions( - args: FilterArgs, - group: keyof ReturnType, + args: FilterArgs, + group: keyof ReturnType, ) { - const { sql, params } = buildFilterOptionsQueries(args)[group]; - return (await pool.query(sql, params)).rows; + const { sql, params } = buildFilterOptionsQueries(args)[group]; + return (await pool.query(sql, params)).rows; } export const resolvers = { - Query: { - async wines(_parent: unknown, args: WinesArgs) { - const query = buildWinesQuery(args); - const [list, count] = await Promise.all([ - pool.query(query.listSql, query.listParams), - pool.query<{ total: number }>(query.countSql, query.countParams), - ]); + Query: { + async wines(_parent: unknown, args: WinesArgs) { + const query = buildWinesQuery(args); + const [list, count] = await Promise.all([ + pool.query(query.listSql, query.listParams), + pool.query<{ total: number }>(query.countSql, query.countParams), + ]); - return toConnection({ - rows: list.rows, - first: query.first, - totalCount: count.rows[0].total, - toNode: toWine, - cursorFor: (_row, index) => encodeCursor(query.offset + index + 1), - }); - }, + return toConnection({ + rows: list.rows, + first: query.first, + totalCount: count.rows[0].total, + toNode: toWine, + cursorFor: (_row, index) => encodeCursor(query.offset + index + 1), + }); + }, - async wine(_parent: unknown, args: { id: string }) { - const id = Number(args.id); - if (!Number.isInteger(id)) return null; - const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); - return result.rows[0] ? toWine(result.rows[0]) : null; - }, + async wine(_parent: unknown, args: { id: string }) { + const id = Number(args.id); + if (!Number.isInteger(id)) return null; + const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); + return result.rows[0] ? toWine(result.rows[0]) : null; + }, - // The counts are in the fields below, so a query only pays for the groups it asks for. - filterOptions(_parent: unknown, args: FilterArgs) { - return args; - }, + // The counts are in the fields below, so a query only pays for the groups it asks for. + filterOptions(_parent: unknown, args: FilterArgs) { + return args; + }, - async recentReviews(_parent: unknown, args: { first?: number | null }) { - const result = await pool.query( - 'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1', - [limitReviews(args.first, 5)], - ); - return result.rows.map(toReview); - }, + async recentReviews(_parent: unknown, args: { first?: number | null }) { + const result = await pool.query( + 'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1', + [limitReviews(args.first, 5)], + ); + return result.rows.map(toReview); + }, - // Null when logged out, so the wine page can ask for it whether the user is logged in or not. - async myReview(_parent: unknown, args: { wineId: string }, { auth }: Context) { - const wineId = validateWineId(args.wineId); - const user = await auth.currentUser(); - if (!user) return null; + // Null when logged out, so the wine page can ask for it whether the user is logged in or not. + async myReview(_parent: unknown, args: { wineId: string }, { auth }: Context) { + const wineId = validateWineId(args.wineId); + const user = await auth.currentUser(); + if (!user) return null; - const result = await pool.query( - 'SELECT * FROM review WHERE wine_id = $1 AND user_id = $2', - [wineId, user.id], - ); - return result.rows[0] ? toReview(result.rows[0]) : null; - }, + const result = await pool.query( + 'SELECT * FROM review WHERE wine_id = $1 AND user_id = $2', + [wineId, user.id], + ); + return result.rows[0] ? toReview(result.rows[0]) : null; }, + }, - // The author is always the logged-in user from the session, never an argument. - Mutation: { - async saveReview(_parent: unknown, args: { input: ReviewInput }, { auth, loaders }: Context) { - const user = await auth.requireUser(); - const review = validateReviewInput(args.input); - try { - // All or nothing: the review, the wine on «Har prøvd», and the wine's average. - const row = await withTransaction(async (client) => { - // Adds the review, or updates the user's earlier review of the same wine. - const result = await client.query( - `INSERT INTO review (wine_id, user_id, rating, comment) + // The author is always the logged-in user from the session, never an argument. + Mutation: { + async saveReview(_parent: unknown, args: { input: ReviewInput }, { auth, loaders }: Context) { + const user = await auth.requireUser(); + const review = validateReviewInput(args.input); + try { + // All or nothing: the review, the wine on «Har prøvd», and the wine's average. + const row = await withTransaction(async (client) => { + // Adds the review, or updates the user's earlier review of the same wine. + const result = await client.query( + `INSERT INTO review (wine_id, user_id, rating, comment) VALUES ($1, $2, $3, $4) ON CONFLICT (wine_id, user_id) DO UPDATE SET rating = EXCLUDED.rating, comment = EXCLUDED.comment, updated_at = now() RETURNING *`, - [review.wineId, user.id, review.rating, review.comment], - ); - // Rule: a reviewed wine has been tried. This also takes it off «Vil prøve». - await setWineInList(client, { - userId: user.id, - wineId: review.wineId, - list: 'TRIED', - inList: true, - }); - // The new review counts in the wine's average right away. - await client.query(UPDATE_WINE_RATING_STATS, [review.wineId]); - return result.rows[0]; - }); - loaders.myLists(user.id).clear(review.wineId); - return toReview(row); - } catch (error) { - if (isForeignKeyViolation(error, 'review_wine_id_fkey')) { - throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); - } - // The account was deleted after the session was checked, in the same moment. - if ( - isForeignKeyViolation(error, 'review_user_id_fkey') || - isForeignKeyViolation(error, 'user_wine_user_id_fkey') - ) { - throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); - } - throw error; - } - }, - - // The wine stays on «Har prøvd»: the user has still tried it. - async deleteReview(_parent: unknown, args: { wineId: string }, { auth }: Context) { - const user = await auth.requireUser(); - const wineId = validateWineId(args.wineId); - const result = await pool.query('DELETE FROM review WHERE wine_id = $1 AND user_id = $2', [ - wineId, - user.id, - ]); - const deleted = (result.rowCount ?? 0) > 0; - if (deleted) await pool.query(UPDATE_WINE_RATING_STATS, [wineId]); - return deleted; - }, + [review.wineId, user.id, review.rating, review.comment], + ); + // Rule: a reviewed wine has been tried. This also takes it off «Vil prøve». + await setWineInList(client, { + userId: user.id, + wineId: review.wineId, + list: 'TRIED', + inList: true, + }); + // The new review counts in the wine's average right away. + await client.query(UPDATE_WINE_RATING_STATS, [review.wineId]); + return result.rows[0]; + }); + loaders.myLists(user.id).clear(review.wineId); + return toReview(row); + } catch (error) { + if (isForeignKeyViolation(error, 'review_wine_id_fkey')) { + throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + // The account was deleted after the session was checked, in the same moment. + if ( + isForeignKeyViolation(error, 'review_user_id_fkey') || + isForeignKeyViolation(error, 'user_wine_user_id_fkey') + ) { + throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + } + throw error; + } }, - FilterOptions: { - types: (args: FilterArgs) => filterOptions(args, 'types'), - countries: (args: FilterArgs) => filterOptions(args, 'countries'), - grapes: (args: FilterArgs) => filterOptions(args, 'grapes'), - harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'), + // The wine stays on «Har prøvd»: the user has still tried it. + async deleteReview(_parent: unknown, args: { wineId: string }, { auth }: Context) { + const user = await auth.requireUser(); + const wineId = validateWineId(args.wineId); + const result = await pool.query('DELETE FROM review WHERE wine_id = $1 AND user_id = $2', [ + wineId, + user.id, + ]); + const deleted = (result.rowCount ?? 0) > 0; + if (deleted) await pool.query(UPDATE_WINE_RATING_STATS, [wineId]); + return deleted; }, + }, - // Fields on Wine that are not columns in the wine table. The loaders batch them, - // so a page of 50 wines runs one query per field instead of 50. - Wine: { - studentRating(wine: { id: string }, _args: unknown, { loaders }: Context) { - return loaders.studentRatings.load(Number(wine.id)); - }, + FilterOptions: { + types: (args: FilterArgs) => filterOptions(args, 'types'), + countries: (args: FilterArgs) => filterOptions(args, 'countries'), + grapes: (args: FilterArgs) => filterOptions(args, 'grapes'), + harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'), + }, - ratingDistribution(wine: { id: string }, _args: unknown, { loaders }: Context) { - return loaders.ratingDistributions.load(Number(wine.id)); - }, + // Fields on Wine that are not columns in the wine table. The loaders batch them, + // so a page of 50 wines runs one query per field instead of 50. + Wine: { + studentRating(wine: { id: string }, _args: unknown, { loaders }: Context) { + return loaders.studentRatings.load(Number(wine.id)); + }, - async reviews(wine: { id: string }, args: { first?: number | null }, { loaders }: Context) { - const rows = await loaders.reviews(limitReviews(args.first, 10)).load(Number(wine.id)); - return rows.map(toReview); - }, + ratingDistribution(wine: { id: string }, _args: unknown, { loaders }: Context) { + return loaders.ratingDistributions.load(Number(wine.id)); }, - // User comes from auth/resolvers.ts. Fields that belong to other features are added here. - User: { - // By when the review was given, newest or oldest first. The order is by id, which an edit - // does not change, so editing a review while someone pages through the list neither skips - // nor repeats one. The cursor is the id of the last review on the page, in both orders. - async reviews( - user: { id: string }, - args: { first?: number | null; after?: string | null; order?: 'NEWEST' | 'OLDEST' | null }, - ) { - const userId = Number(user.id); - const first = limitReviews(args.first, 10); - const afterId = decodeIdCursor(args.after); - // Fixed SQL for each order, never text from the request. The index review_user_id - // (user_id, id DESC) covers both, read forwards or backwards. - const page = - args.order === 'OLDEST' - ? `SELECT * FROM review + async reviews(wine: { id: string }, args: { first?: number | null }, { loaders }: Context) { + const rows = await loaders.reviews(limitReviews(args.first, 10)).load(Number(wine.id)); + return rows.map(toReview); + }, + }, + + // User comes from auth/resolvers.ts. Fields that belong to other features are added here. + User: { + // By when the review was given, newest or oldest first. The order is by id, which an edit + // does not change, so editing a review while someone pages through the list neither skips + // nor repeats one. The cursor is the id of the last review on the page, in both orders. + async reviews( + user: { id: string }, + args: { first?: number | null; after?: string | null; order?: 'NEWEST' | 'OLDEST' | null }, + ) { + const userId = Number(user.id); + const first = limitReviews(args.first, 10); + const afterId = decodeIdCursor(args.after); + // Fixed SQL for each order, never text from the request. The index review_user_id + // (user_id, id DESC) covers both, read forwards or backwards. + const page = + args.order === 'OLDEST' + ? `SELECT * FROM review WHERE user_id = $1 AND ($2::integer IS NULL OR id > $2) ORDER BY id ASC LIMIT $3` - : `SELECT * FROM review + : `SELECT * FROM review WHERE user_id = $1 AND ($2::integer IS NULL OR id < $2) ORDER BY id DESC LIMIT $3`; - const [list, count] = await Promise.all([ - pool.query(page, [userId, afterId, first + 1]), - pool.query<{ total: number }>('SELECT count(*)::int AS total FROM review WHERE user_id = $1', [ - userId, - ]), - ]); - return toConnection({ - rows: list.rows, - first, - totalCount: count.rows[0].total, - toNode: toReview, - cursorFor: (row) => encodeIdCursor(row.id), - }); - }, + const [list, count] = await Promise.all([ + pool.query(page, [userId, afterId, first + 1]), + pool.query<{ total: number }>( + 'SELECT count(*)::int AS total FROM review WHERE user_id = $1', + [userId], + ), + ]); + return toConnection({ + rows: list.rows, + first, + totalCount: count.rows[0].total, + toNode: toReview, + cursorFor: (row) => encodeIdCursor(row.id), + }); }, + }, - Review: { - // Null for old anonymous reviews. The frontend chooses the text to show for them. - author(review: { userId: number | null }, _args: unknown, { loaders }: Context) { - return review.userId === null ? null : loaders.usernames.load(review.userId); - }, + Review: { + // Null for old anonymous reviews. The frontend chooses the text to show for them. + author(review: { userId: number | null }, _args: unknown, { loaders }: Context) { + return review.userId === null ? null : loaders.usernames.load(review.userId); + }, - async wine(review: { wineId: number }, _args: unknown, { loaders }: Context) { - const row = await loaders.wines.load(review.wineId); - // The foreign key should make this impossible, but a clear error is better than a crash. - if (!row) throw new GraphQLError('Wine not found.', { extensions: { code: 'NOT_FOUND' } }); - return toWine(row); - }, + async wine(review: { wineId: number }, _args: unknown, { loaders }: Context) { + const row = await loaders.wines.load(review.wineId); + // The foreign key should make this impossible, but a clear error is better than a crash. + if (!row) throw new GraphQLError('Wine not found.', { extensions: { code: 'NOT_FOUND' } }); + return toWine(row); }, -}; \ No newline at end of file + }, +}; diff --git a/backend/src/review-api.db.test.ts b/backend/src/review-api.db.test.ts index 54b9e58..8cd870a 100644 --- a/backend/src/review-api.db.test.ts +++ b/backend/src/review-api.db.test.ts @@ -33,227 +33,251 @@ const WINE = `query Wine($id: ID!) { }`; describe.skipIf(!url)('reviews API (PostgreSQL)', () => { - const service: AuthService = createAuthService(createPgUserStore(pool), { - scryptParams: { N: 1024, r: 8, p: 1 }, - }); - const server = new ApolloServer({ - typeDefs: [typeDefs, authTypeDefs], - resolvers: [resolvers, authResolvers], - }); - - // A wine of our own with an id far above the X-Wines ids, so the tests never touch real data. - const wineId = String(900_000_000 + Math.floor(Math.random() * 1_000_000)); - const otherWineId = String(Number(wineId) + 1); - const userIds: number[] = []; - const studentIds: number[] = []; - - beforeAll(async () => { - await pool.query( - `INSERT INTO wine (id, name, type, search_text) + const service: AuthService = createAuthService(createPgUserStore(pool), { + scryptParams: { N: 1024, r: 8, p: 1 }, + }); + const server = new ApolloServer({ + typeDefs: [typeDefs, authTypeDefs], + resolvers: [resolvers, authResolvers], + }); + + // A wine of our own with an id far above the X-Wines ids, so the tests never touch real data. + const wineId = String(900_000_000 + Math.floor(Math.random() * 1_000_000)); + const otherWineId = String(Number(wineId) + 1); + const userIds: number[] = []; + const studentIds: number[] = []; + + beforeAll(async () => { + await pool.query( + `INSERT INTO wine (id, name, type, search_text) VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2')`, - [wineId, otherWineId], - ); - }); - - // Reviews go with the wine and the users (ON DELETE CASCADE). - afterAll(async () => { - await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId]]); - await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]); - await pool.query('DELETE FROM student WHERE id = ANY($1)', [studentIds]); - await pool.end(); - }); - - /** A browser that keeps the session cookie, like a real one. Without `as`, nobody is logged in. */ - async function createBrowser(as?: string) { - let cookie: string | undefined; - const jar: CookieJar = { - setSession: (token) => (cookie = token), - clearSession: () => (cookie = undefined), - }; - - if (as) { - const username = `t_${as}_${Math.random().toString(36).slice(2, 10)}`; - const { user, session } = await service.register({ username, password: 'langt-nok-passord' }); - userIds.push(user.id); - cookie = session.token; - } - - async function request(query: string, variables?: Record) { - const response = await server.executeOperation( - { query, variables }, - { contextValue: { loaders: createLoaders(), auth: createAuthContext(service, cookie, jar) } }, - ); - if (response.body.kind !== 'single') throw new Error('Expected a single result'); - return response.body.singleResult; - } - - return { request }; + [wineId, otherWineId], + ); + }); + + // Reviews go with the wine and the users (ON DELETE CASCADE). + afterAll(async () => { + await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId]]); + await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]); + await pool.query('DELETE FROM student WHERE id = ANY($1)', [studentIds]); + await pool.end(); + }); + + /** A browser that keeps the session cookie, like a real one. Without `as`, nobody is logged in. */ + async function createBrowser(as?: string) { + let cookie: string | undefined; + const jar: CookieJar = { + setSession: (token) => (cookie = token), + clearSession: () => (cookie = undefined), + }; + + if (as) { + const username = `t_${as}_${Math.random().toString(36).slice(2, 10)}`; + const { user, session } = await service.register({ username, password: 'langt-nok-passord' }); + userIds.push(user.id); + cookie = session.token; } - const codeOf = (result: { errors?: readonly { extensions?: Record }[] }) => - result.errors?.[0]?.extensions?.code; - - const save = (rating: number, comment?: string) => ({ input: { wineId, rating, comment } }); + async function request(query: string, variables?: Record) { + const response = await server.executeOperation( + { query, variables }, + { + contextValue: { loaders: createLoaders(), auth: createAuthContext(service, cookie, jar) }, + }, + ); + if (response.body.kind !== 'single') throw new Error('Expected a single result'); + return response.body.singleResult; + } - it('a visitor cannot save or delete a review, and has no review of their own', async () => { - const visitor = await createBrowser(); - expect(codeOf(await visitor.request(SAVE, save(4)))).toBe('UNAUTHENTICATED'); - expect(codeOf(await visitor.request(DELETE, { wineId }))).toBe('UNAUTHENTICATED'); - expect((await visitor.request(MINE, { wineId })).data).toEqual({ myReview: null }); + return { request }; + } + + const codeOf = (result: { errors?: readonly { extensions?: Record }[] }) => + result.errors?.[0]?.extensions?.code; + + const save = (rating: number, comment?: string) => ({ input: { wineId, rating, comment } }); + + it('a visitor cannot save or delete a review, and has no review of their own', async () => { + const visitor = await createBrowser(); + expect(codeOf(await visitor.request(SAVE, save(4)))).toBe('UNAUTHENTICATED'); + expect(codeOf(await visitor.request(DELETE, { wineId }))).toBe('UNAUTHENTICATED'); + expect((await visitor.request(MINE, { wineId })).data).toEqual({ myReview: null }); + }); + + it('saves a review with the username as the author, and updates it on the next save', async () => { + const kari = await createBrowser('kari'); + const first = await kari.request(SAVE, save(4, 'Fin')); + const { author } = first.data?.saveReview as { author: string }; + expect(author).toMatch(/^t_kari_/); + + const second = await kari.request(SAVE, save(2.5, 'Endret mening')); + expect(second.data?.saveReview).toMatchObject({ rating: 2.5, comment: 'Endret mening' }); + expect((second.data?.saveReview as { id: string }).id).toBe( + (first.data?.saveReview as { id: string }).id, + ); + + const mine = await kari.request(MINE, { wineId }); + expect(mine.data?.myReview).toMatchObject({ rating: 2.5, author }); + }); + + it('keeps users apart: nobody sees or deletes the review of another user', async () => { + const ola = await createBrowser('ola'); + const per = await createBrowser('per'); + await ola.request(SAVE, save(5)); + + expect((await per.request(MINE, { wineId })).data).toEqual({ myReview: null }); + expect((await per.request(DELETE, { wineId })).data).toEqual({ deleteReview: false }); + expect((await ola.request(MINE, { wineId })).data?.myReview).toMatchObject({ rating: 5 }); + }); + + it('counts the review in the wine average at once, and removes it again on delete', async () => { + const anne = await createBrowser('anne'); + const before = await anne.request(WINE, { id: wineId }); + const countBefore = (before.data?.wine as { studentRating: { count: number } }).studentRating + .count; + + await anne.request(SAVE, save(3)); + const after = await anne.request(WINE, { id: wineId }); + expect((after.data?.wine as { studentRating: { count: number } }).studentRating.count).toBe( + countBefore + 1, + ); + + expect((await anne.request(DELETE, { wineId })).data).toEqual({ deleteReview: true }); + const deleted = await anne.request(WINE, { id: wineId }); + expect((deleted.data?.wine as { studentRating: { count: number } }).studentRating.count).toBe( + countBefore, + ); + }); + + it('shows old anonymous reviews without an author', async () => { + const student = await pool.query<{ id: number }>( + 'INSERT INTO student (user_id) VALUES (gen_random_uuid()) RETURNING id', + ); + studentIds.push(student.rows[0].id); + await pool.query('INSERT INTO review (wine_id, student_id, rating) VALUES ($1, $2, 1.5)', [ + wineId, + student.rows[0].id, + ]); + + const visitor = await createBrowser(); + const result = await visitor.request(WINE, { id: wineId }); + const reviews = (result.data?.wine as { reviews: { rating: number; author: string | null }[] }) + .reviews; + expect(reviews).toContainEqual({ rating: 1.5, author: null }); + }); + + it('rejects a wine that does not exist and an invalid rating', async () => { + const kim = await createBrowser('kim'); + expect(codeOf(await kim.request(SAVE, { input: { wineId: '1999999999', rating: 4 } }))).toBe( + 'BAD_USER_INPUT', + ); + expect(codeOf(await kim.request(SAVE, save(4.25)))).toBe('BAD_USER_INPUT'); + }); + + describe('User.reviews', () => { + type Page = { + totalCount: number; + edges: { node: { rating: number; wine: { id: string } } }[]; + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + }; + const pageOf = (result: { data?: Record | null }) => + (result.data?.me as { reviews: Page }).reviews; + + it('is empty for a user without reviews', async () => { + const lise = await createBrowser('lise'); + expect(pageOf(await lise.request(MY_REVIEWS))).toEqual({ + totalCount: 0, + edges: [], + pageInfo: { hasNextPage: false, endCursor: null }, + }); }); - it('saves a review with the username as the author, and updates it on the next save', async () => { - const kari = await createBrowser('kari'); - const first = await kari.request(SAVE, save(4, 'Fin')); - const { author } = first.data?.saveReview as { author: string }; - expect(author).toMatch(/^t_kari_/); - - const second = await kari.request(SAVE, save(2.5, 'Endret mening')); - expect(second.data?.saveReview).toMatchObject({ rating: 2.5, comment: 'Endret mening' }); - expect((second.data?.saveReview as { id: string }).id).toBe((first.data?.saveReview as { id: string }).id); - - const mine = await kari.request(MINE, { wineId }); - expect(mine.data?.myReview).toMatchObject({ rating: 2.5, author }); + it('lists only the reviews of this user, newest first, one page at a time', async () => { + const tor = await createBrowser('tor'); + const other = await createBrowser('other'); + await tor.request(SAVE, save(4)); + await tor.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + await other.request(SAVE, save(1)); + + const first = pageOf(await tor.request(MY_REVIEWS, { first: 1 })); + expect(first.totalCount).toBe(2); + expect(first.edges.map((edge) => edge.node)).toEqual([ + { rating: 2, wine: { id: otherWineId } }, + ]); + expect(first.pageInfo.hasNextPage).toBe(true); + + const second = pageOf( + await tor.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor }), + ); + expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]); + expect(second.pageInfo.hasNextPage).toBe(false); }); - it('keeps users apart: nobody sees or deletes the review of another user', async () => { - const ola = await createBrowser('ola'); - const per = await createBrowser('per'); - await ola.request(SAVE, save(5)); + it('neither skips nor repeats a review that is edited while paging', async () => { + const siv = await createBrowser('siv'); + await siv.request(SAVE, save(4)); + await siv.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); - expect((await per.request(MINE, { wineId })).data).toEqual({ myReview: null }); - expect((await per.request(DELETE, { wineId })).data).toEqual({ deleteReview: false }); - expect((await ola.request(MINE, { wineId })).data?.myReview).toMatchObject({ rating: 5 }); - }); + const first = pageOf(await siv.request(MY_REVIEWS, { first: 1 })); + expect(first.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId]); - it('counts the review in the wine average at once, and removes it again on delete', async () => { - const anne = await createBrowser('anne'); - const before = await anne.request(WINE, { id: wineId }); - const countBefore = (before.data?.wine as { studentRating: { count: number } }).studentRating.count; + // The older review is edited before the next page. Sorted by updated_at, it would jump + // to the top and never show up on the next page. + await siv.request(SAVE, save(5)); - await anne.request(SAVE, save(3)); - const after = await anne.request(WINE, { id: wineId }); - expect((after.data?.wine as { studentRating: { count: number } }).studentRating.count).toBe(countBefore + 1); + const second = pageOf( + await siv.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor }), + ); + expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 5, wine: { id: wineId } }]); + }); - expect((await anne.request(DELETE, { wineId })).data).toEqual({ deleteReview: true }); - const deleted = await anne.request(WINE, { id: wineId }); - expect((deleted.data?.wine as { studentRating: { count: number } }).studentRating.count).toBe(countBefore); + it('lists the oldest first with order: OLDEST, one page at a time, without skipping', async () => { + const eva = await createBrowser('eva'); + await eva.request(SAVE, save(4)); + await eva.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + + const first = pageOf(await eva.request(MY_REVIEWS, { first: 1, order: 'OLDEST' })); + expect(first.totalCount).toBe(2); + expect(first.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]); + expect(first.pageInfo.hasNextPage).toBe(true); + + // Editing the review already shown neither moves it nor repeats it on the next page. + await eva.request(SAVE, save(5)); + + const second = pageOf( + await eva.request(MY_REVIEWS, { + first: 1, + after: first.pageInfo.endCursor, + order: 'OLDEST', + }), + ); + expect(second.edges.map((edge) => edge.node)).toEqual([ + { rating: 2, wine: { id: otherWineId } }, + ]); + expect(second.pageInfo.hasNextPage).toBe(false); }); - it('shows old anonymous reviews without an author', async () => { - const student = await pool.query<{ id: number }>( - 'INSERT INTO student (user_id) VALUES (gen_random_uuid()) RETURNING id', - ); - studentIds.push(student.rows[0].id); - await pool.query('INSERT INTO review (wine_id, student_id, rating) VALUES ($1, $2, 1.5)', [ - wineId, - student.rows[0].id, - ]); - - const visitor = await createBrowser(); - const result = await visitor.request(WINE, { id: wineId }); - const reviews = (result.data?.wine as { reviews: { rating: number; author: string | null }[] }).reviews; - expect(reviews).toContainEqual({ rating: 1.5, author: null }); + it('lists the newest first when the order is NEWEST or left out', async () => { + const ole = await createBrowser('ole'); + await ole.request(SAVE, save(4)); + await ole.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + + for (const order of [undefined, 'NEWEST']) { + const page = pageOf(await ole.request(MY_REVIEWS, { order })); + expect(page.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId, wineId]); + } }); - it('rejects a wine that does not exist and an invalid rating', async () => { - const kim = await createBrowser('kim'); - expect(codeOf(await kim.request(SAVE, { input: { wineId: '1999999999', rating: 4 } }))).toBe( - 'BAD_USER_INPUT', - ); - expect(codeOf(await kim.request(SAVE, save(4.25)))).toBe('BAD_USER_INPUT'); + it('rejects an order that does not exist', async () => { + const per = await createBrowser('per'); + expect(codeOf(await per.request(MY_REVIEWS, { order: 'BEST' }))).toBe('BAD_USER_INPUT'); }); - describe('User.reviews', () => { - type Page = { - totalCount: number; - edges: { node: { rating: number; wine: { id: string } } }[]; - pageInfo: { hasNextPage: boolean; endCursor: string | null }; - }; - const pageOf = (result: { data?: Record | null }) => - (result.data?.me as { reviews: Page }).reviews; - - it('is empty for a user without reviews', async () => { - const lise = await createBrowser('lise'); - expect(pageOf(await lise.request(MY_REVIEWS))).toEqual({ - totalCount: 0, - edges: [], - pageInfo: { hasNextPage: false, endCursor: null }, - }); - }); - - it('lists only the reviews of this user, newest first, one page at a time', async () => { - const tor = await createBrowser('tor'); - const other = await createBrowser('other'); - await tor.request(SAVE, save(4)); - await tor.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); - await other.request(SAVE, save(1)); - - const first = pageOf(await tor.request(MY_REVIEWS, { first: 1 })); - expect(first.totalCount).toBe(2); - expect(first.edges.map((edge) => edge.node)).toEqual([{ rating: 2, wine: { id: otherWineId } }]); - expect(first.pageInfo.hasNextPage).toBe(true); - - const second = pageOf(await tor.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor })); - expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]); - expect(second.pageInfo.hasNextPage).toBe(false); - }); - - it('neither skips nor repeats a review that is edited while paging', async () => { - const siv = await createBrowser('siv'); - await siv.request(SAVE, save(4)); - await siv.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); - - const first = pageOf(await siv.request(MY_REVIEWS, { first: 1 })); - expect(first.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId]); - - // The older review is edited before the next page. Sorted by updated_at, it would jump - // to the top and never show up on the next page. - await siv.request(SAVE, save(5)); - - const second = pageOf(await siv.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor })); - expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 5, wine: { id: wineId } }]); - }); - - it('lists the oldest first with order: OLDEST, one page at a time, without skipping', async () => { - const eva = await createBrowser('eva'); - await eva.request(SAVE, save(4)); - await eva.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); - - const first = pageOf(await eva.request(MY_REVIEWS, { first: 1, order: 'OLDEST' })); - expect(first.totalCount).toBe(2); - expect(first.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]); - expect(first.pageInfo.hasNextPage).toBe(true); - - // Editing the review already shown neither moves it nor repeats it on the next page. - await eva.request(SAVE, save(5)); - - const second = pageOf( - await eva.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor, order: 'OLDEST' }), - ); - expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 2, wine: { id: otherWineId } }]); - expect(second.pageInfo.hasNextPage).toBe(false); - }); - - it('lists the newest first when the order is NEWEST or left out', async () => { - const ole = await createBrowser('ole'); - await ole.request(SAVE, save(4)); - await ole.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); - - for (const order of [undefined, 'NEWEST']) { - const page = pageOf(await ole.request(MY_REVIEWS, { order })); - expect(page.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId, wineId]); - } - }); - - it('rejects an order that does not exist', async () => { - const per = await createBrowser('per'); - expect(codeOf(await per.request(MY_REVIEWS, { order: 'BEST' }))).toBe('BAD_USER_INPUT'); - }); - - it('rejects a cursor that was not made by the API', async () => { - const ina = await createBrowser('ina'); - expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT'); - }); + it('rejects a cursor that was not made by the API', async () => { + const ina = await createBrowser('ina'); + expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe( + 'BAD_USER_INPUT', + ); }); + }); }); diff --git a/backend/src/review-input.test.ts b/backend/src/review-input.test.ts index 77f135a..1a822e5 100644 --- a/backend/src/review-input.test.ts +++ b/backend/src/review-input.test.ts @@ -2,49 +2,49 @@ import { describe, expect, it } from 'vitest'; import { MAX_COMMENT_LENGTH, validateReviewInput } from './review-input'; describe('validateReviewInput', () => { - it('accepts a valid review and converts the wine ID to a number', () => { - const review = validateReviewInput({ wineId: '100062', rating: 5, comment: 'Godt!' }); - expect(review).toEqual({ wineId: 100062, rating: 5, comment: 'Godt!' }); - }); - - it('accepts whole and half stars from 0.5 to 5', () => { - for (const rating of [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]) { - expect(validateReviewInput({ wineId: '1', rating }).rating).toBe(rating); - } - }); - - it('rejects ratings outside the range and values that are not half stars', () => { - for (const rating of [0, 5.5, 6, -1, 1.25, 3.3]) { - expect(() => validateReviewInput({ wineId: '1', rating })).toThrow('rating'); - } - }); - - it('stores a blank comment as no comment', () => { - expect(validateReviewInput({ wineId: '1', rating: 4, comment: ' ' }).comment).toBeNull(); - expect(validateReviewInput({ wineId: '1', rating: 4 }).comment).toBeNull(); - }); - - it('trims the comment', () => { - expect(validateReviewInput({ wineId: '1', rating: 4, comment: ' Fin ' }).comment).toBe('Fin'); - }); - - it('rejects a comment that is too long', () => { - const comment = 'a'.repeat(MAX_COMMENT_LENGTH + 1); - expect(() => validateReviewInput({ wineId: '1', rating: 4, comment })).toThrow('comment'); - }); - - it('rejects invalid wine IDs', () => { - for (const wineId of ['abc', '-1', '0', '1.5']) { - expect(() => validateReviewInput({ wineId, rating: 4 })).toThrow('wine ID'); - } - }); - - it('gives a BAD_USER_INPUT error so the frontend can show the message', () => { - try { - validateReviewInput({ wineId: '1', rating: 9 }); - } catch (error) { - expect((error as { extensions: { code: string } }).extensions.code).toBe('BAD_USER_INPUT'); - } - expect.assertions(1); - }); + it('accepts a valid review and converts the wine ID to a number', () => { + const review = validateReviewInput({ wineId: '100062', rating: 5, comment: 'Godt!' }); + expect(review).toEqual({ wineId: 100062, rating: 5, comment: 'Godt!' }); + }); + + it('accepts whole and half stars from 0.5 to 5', () => { + for (const rating of [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]) { + expect(validateReviewInput({ wineId: '1', rating }).rating).toBe(rating); + } + }); + + it('rejects ratings outside the range and values that are not half stars', () => { + for (const rating of [0, 5.5, 6, -1, 1.25, 3.3]) { + expect(() => validateReviewInput({ wineId: '1', rating })).toThrow('rating'); + } + }); + + it('stores a blank comment as no comment', () => { + expect(validateReviewInput({ wineId: '1', rating: 4, comment: ' ' }).comment).toBeNull(); + expect(validateReviewInput({ wineId: '1', rating: 4 }).comment).toBeNull(); + }); + + it('trims the comment', () => { + expect(validateReviewInput({ wineId: '1', rating: 4, comment: ' Fin ' }).comment).toBe('Fin'); + }); + + it('rejects a comment that is too long', () => { + const comment = 'a'.repeat(MAX_COMMENT_LENGTH + 1); + expect(() => validateReviewInput({ wineId: '1', rating: 4, comment })).toThrow('comment'); + }); + + it('rejects invalid wine IDs', () => { + for (const wineId of ['abc', '-1', '0', '1.5']) { + expect(() => validateReviewInput({ wineId, rating: 4 })).toThrow('wine ID'); + } + }); + + it('gives a BAD_USER_INPUT error so the frontend can show the message', () => { + try { + validateReviewInput({ wineId: '1', rating: 9 }); + } catch (error) { + expect((error as { extensions: { code: string } }).extensions.code).toBe('BAD_USER_INPUT'); + } + expect.assertions(1); + }); }); diff --git a/backend/src/review-input.ts b/backend/src/review-input.ts index d0e19d0..f00caa8 100644 --- a/backend/src/review-input.ts +++ b/backend/src/review-input.ts @@ -8,43 +8,43 @@ export const MAX_COMMENT_LENGTH = 500; /** The author is never part of the input: it is always the logged-in user. */ export interface ReviewInput { - wineId: string; - rating: number; - comment?: string | null; + wineId: string; + rating: number; + comment?: string | null; } export interface ValidReview { - wineId: number; - rating: number; - comment: string | null; + wineId: number; + rating: number; + comment: string | null; } function badInput(message: string): GraphQLError { - return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); + return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); } export function validateWineId(value: string): number { - const id = Number(value); - if (!Number.isInteger(id) || id <= 0) throw badInput('Invalid wine ID.'); - return id; + const id = Number(value); + if (!Number.isInteger(id) || id <= 0) throw badInput('Invalid wine ID.'); + return id; } export function validateReviewInput(input: ReviewInput): ValidReview { - const { rating } = input; - // Whole or half stars: the rating times two must be a whole number. - if (!Number.isInteger(rating * 2) || rating < MIN_RATING || rating > MAX_RATING) { - throw badInput(`The rating must be from ${MIN_RATING} to ${MAX_RATING} in half stars.`); - } - - // An empty or blank comment is stored as no comment. - const comment = input.comment?.trim() || null; - if (comment && comment.length > MAX_COMMENT_LENGTH) { - throw badInput(`The comment can be at most ${MAX_COMMENT_LENGTH} characters.`); - } - - return { - wineId: validateWineId(input.wineId), - rating, - comment, - }; + const { rating } = input; + // Whole or half stars: the rating times two must be a whole number. + if (!Number.isInteger(rating * 2) || rating < MIN_RATING || rating > MAX_RATING) { + throw badInput(`The rating must be from ${MIN_RATING} to ${MAX_RATING} in half stars.`); + } + + // An empty or blank comment is stored as no comment. + const comment = input.comment?.trim() || null; + if (comment && comment.length > MAX_COMMENT_LENGTH) { + throw badInput(`The comment can be at most ${MAX_COMMENT_LENGTH} characters.`); + } + + return { + wineId: validateWineId(input.wineId), + rating, + comment, + }; } diff --git a/backend/src/scripts/seed-demo-user.ts b/backend/src/scripts/seed-demo-user.ts index 2161ad1..c58d4bf 100644 --- a/backend/src/scripts/seed-demo-user.ts +++ b/backend/src/scripts/seed-demo-user.ts @@ -4,25 +4,25 @@ import { pool, withTransaction } from '../db'; import { DEMO_PASSWORD, DEMO_USERNAME, DEMO_WINE_COUNT, seedDemoUser } from '../demo/demo-user'; async function main() { - // Well-known wines make a better demo: the ones with the most ratings. Ties by id, so the - // choice is the same each time on the same data. - const { rows } = await pool.query<{ id: number }>( - 'SELECT id FROM wine WHERE community_count > 0 ORDER BY community_count DESC, id LIMIT $1', - [DEMO_WINE_COUNT], + // Well-known wines make a better demo: the ones with the most ratings. Ties by id, so the + // choice is the same each time on the same data. + const { rows } = await pool.query<{ id: number }>( + 'SELECT id FROM wine WHERE community_count > 0 ORDER BY community_count DESC, id LIMIT $1', + [DEMO_WINE_COUNT], + ); + if (rows.length < DEMO_WINE_COUNT) { + throw new Error( + `Found ${rows.length} rated wines, need ${DEMO_WINE_COUNT}. Import wines first (docs/setup.md).`, ); - if (rows.length < DEMO_WINE_COUNT) { - throw new Error( - `Found ${rows.length} rated wines, need ${DEMO_WINE_COUNT}. Import wines first (docs/setup.md).`, - ); - } + } - await withTransaction((client) => seedDemoUser(client, { wineIds: rows.map((row) => row.id) })); - console.log(`Demo user ready. Username: ${DEMO_USERNAME} Password: ${DEMO_PASSWORD}`); + await withTransaction((client) => seedDemoUser(client, { wineIds: rows.map((row) => row.id) })); + console.log(`Demo user ready. Username: ${DEMO_USERNAME} Password: ${DEMO_PASSWORD}`); } main() - .catch((error: unknown) => { - console.error(error instanceof Error ? error.message : error); - process.exitCode = 1; - }) - .finally(() => pool.end()); + .catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }) + .finally(() => pool.end()); diff --git a/backend/src/scripts/seed-xwines.ts b/backend/src/scripts/seed-xwines.ts index bf56feb..bce2c6a 100644 --- a/backend/src/scripts/seed-xwines.ts +++ b/backend/src/scripts/seed-xwines.ts @@ -49,8 +49,8 @@ const INSERT_RATINGS = ` `; function toWineRow(row: Record) { - const grapes = parseTextList(row.Grapes); - return { + const grapes = parseTextList(row.Grapes); + return { id: Number(row.WineID), name: row.WineName, type: row.Type, @@ -69,96 +69,96 @@ function toWineRow(row: Record) { website: row.Website || null, vintages: parseYearList(row.Vintages), search_text: toSearchText(row.WineName, row.WineryName, row.RegionName, ...grapes), - }; + }; } function toRatingRow(row: Record) { - return { + return { id: Number(row.RatingID), wine_id: Number(row.WineID), user_id: Number(row.UserID), vintage: parseNumber(row.Vintage), // "N.V." becomes null rating: Number(row.Rating), rated_at: row.Date, - }; + }; } async function insertInBatches(sql: string, rows: object[], size: number) { - for (let start = 0; start < rows.length; start += size) { + for (let start = 0; start < rows.length; start += size) { await pool.query(sql, [JSON.stringify(rows.slice(start, start + size))]); - } + } } /** Reads the ratings file line by line, so only one batch is in memory at a time. */ async function importRatings(file: string): Promise { - const lines = createInterface({ + const lines = createInterface({ input: createReadStream(file, 'utf8'), crlfDelay: Infinity, - }); + }); - let header: string[] | null = null; - let batch: object[] = []; - let total = 0; - let reported = 0; + let header: string[] | null = null; + let batch: object[] = []; + let total = 0; + let reported = 0; - for await (const line of lines) { + for await (const line of lines) { if (line.trim() === '') continue; const cells = splitCsvLine(line); if (!header) { - header = cells.map((name) => name.replace(/^\uFEFF/, '')); - continue; + header = cells.map((name) => name.replace(/^\uFEFF/, '')); + continue; } batch.push(toRatingRow(Object.fromEntries(header.map((name, i) => [name, cells[i] ?? ''])))); if (batch.length >= RATING_BATCH_SIZE) { - await pool.query(INSERT_RATINGS, [JSON.stringify(batch)]); - total += batch.length; - batch = []; - if (total - reported >= PROGRESS_EVERY) { + await pool.query(INSERT_RATINGS, [JSON.stringify(batch)]); + total += batch.length; + batch = []; + if (total - reported >= PROGRESS_EVERY) { reported = total; console.log(` ${total.toLocaleString('en')} ratings …`); - } - } + } } + } - if (batch.length > 0) { + if (batch.length > 0) { await pool.query(INSERT_RATINGS, [JSON.stringify(batch)]); total += batch.length; - } + } - return total; + return total; } /** Seconds since `start`, with one decimal. */ function secondsSince(start: number): string { - return `${((Date.now() - start) / 1000).toFixed(1)} s`; + return `${((Date.now() - start) / 1000).toFixed(1)} s`; } async function main() { - const [winesFile, ratingsFile] = process.argv.slice(2); - if (!winesFile || !ratingsFile) { + const [winesFile, ratingsFile] = process.argv.slice(2); + if (!winesFile || !ratingsFile) { throw new Error('Usage: seed-xwines '); - } + } - const wineStart = Date.now(); - const wines = parseCsv(readFileSync(winesFile, 'utf8')).map(toWineRow); - await insertInBatches(UPSERT_WINES, wines, WINE_BATCH_SIZE); - console.log(`Saved ${wines.length} wines in ${secondsSince(wineStart)}.`); + const wineStart = Date.now(); + const wines = parseCsv(readFileSync(winesFile, 'utf8')).map(toWineRow); + await insertInBatches(UPSERT_WINES, wines, WINE_BATCH_SIZE); + console.log(`Saved ${wines.length} wines in ${secondsSince(wineStart)}.`); - const ratingStart = Date.now(); - const ratings = await importRatings(ratingsFile); - console.log(`Saved ${ratings} ratings in ${secondsSince(ratingStart)}.`); + const ratingStart = Date.now(); + const ratings = await importRatings(ratingsFile); + console.log(`Saved ${ratings} ratings in ${secondsSince(ratingStart)}.`); - const statsStart = Date.now(); - await pool.query(UPDATE_ALL_RATING_STATS); - console.log(`Updated average ratings in ${secondsSince(statsStart)}.`); + const statsStart = Date.now(); + await pool.query(UPDATE_ALL_RATING_STATS); + console.log(`Updated average ratings in ${secondsSince(statsStart)}.`); } main() - .catch((error: unknown) => { + .catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; - }) - .finally(() => pool.end()); \ No newline at end of file + }) + .finally(() => pool.end()); diff --git a/backend/src/server.ts b/backend/src/server.ts index 47b423e..3f707f2 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -10,40 +10,42 @@ import { allResolvers, allTypeDefs } from './graphql'; const PORT = Number(process.env.PORT ?? 3001); async function main() { - const app = express(); - // Each feature adds its own types and resolvers. See graphql.ts. - const apollo = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); - const createContext = createContextFactory(createAuthService(createPgUserStore(pool))); - await apollo.start(); + const app = express(); + // Each feature adds its own types and resolvers. See graphql.ts. + const apollo = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); + const createContext = createContextFactory(createAuthService(createPgUserStore(pool))); + await apollo.start(); - // Database check, same as before: shows that the backend can reach PostgreSQL. - app.get('/', async (_req, res) => { - try { - const { rows } = await pool.query( - 'SELECT current_database() AS database, current_user AS username, now() AS time', - ); - const info = rows[0]; - res.type('text').send( - `Hello from PostgreSQL!\nDatabase: ${info.database}\nUser: ${info.username}\nServer time: ${info.time.toISOString()}\n`, - ); - } catch (error) { - console.error('Database query failed:', error instanceof Error ? error.message : error); - res.status(503).type('text').send('Database unavailable\n'); - } - }); + // Database check, same as before: shows that the backend can reach PostgreSQL. + app.get('/', async (_req, res) => { + try { + const { rows } = await pool.query( + 'SELECT current_database() AS database, current_user AS username, now() AS time', + ); + const info = rows[0]; + res + .type('text') + .send( + `Hello from PostgreSQL!\nDatabase: ${info.database}\nUser: ${info.username}\nServer time: ${info.time.toISOString()}\n`, + ); + } catch (error) { + console.error('Database query failed:', error instanceof Error ? error.message : error); + res.status(503).type('text').send('Database unavailable\n'); + } + }); - // The context reads the session cookie and gets fresh loaders for every request (see context.ts). - // Apollo's CSRF protection is on by default: it rejects simple cross-site requests, and the - // SameSite=Lax cookie is not sent with cross-site POSTs. Together they protect the login cookie. - app.use('/graphql', express.json(), expressMiddleware(apollo, { context: createContext })); + // The context reads the session cookie and gets fresh loaders for every request (see context.ts). + // Apollo's CSRF protection is on by default: it rejects simple cross-site requests, and the + // SameSite=Lax cookie is not sent with cross-site POSTs. Together they protect the login cookie. + app.use('/graphql', express.json(), expressMiddleware(apollo, { context: createContext })); - app.listen(PORT, () => { - console.log(`Backend listening on http://localhost:${PORT}`); - console.log(`GraphQL: http://localhost:${PORT}/graphql`); - }); + app.listen(PORT, () => { + console.log(`Backend listening on http://localhost:${PORT}`); + console.log(`GraphQL: http://localhost:${PORT}/graphql`); + }); } main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); \ No newline at end of file + console.error(error); + process.exit(1); +}); diff --git a/backend/src/test/graphql-test-api.ts b/backend/src/test/graphql-test-api.ts index b89164b..d2724a4 100644 --- a/backend/src/test/graphql-test-api.ts +++ b/backend/src/test/graphql-test-api.ts @@ -15,8 +15,8 @@ import { createLoaders } from '../loaders'; const FAST_SCRYPT = { N: 1024, r: 8, p: 1 }; export interface GraphQLResult { - data?: Record | null; - errors?: readonly { message: string; extensions?: Record }[]; + data?: Record | null; + errors?: readonly { message: string; extensions?: Record }[]; } /** The error code of the first error, for example 'UNAUTHENTICATED'. */ @@ -24,58 +24,63 @@ export const codeOf = (result: GraphQLResult) => result.errors?.[0]?.extensions? /** `firstId` keeps the wines of different test files apart when they run at the same time. */ export function createTestApi({ firstId }: { firstId: number }) { - const service = createAuthService(createPgUserStore(pool), { scryptParams: FAST_SCRYPT }); - const server = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); - const userIds: number[] = []; - const wineIds: number[] = []; - let nextWineId = firstId + Math.floor(Math.random() * 1_000_000); + const service = createAuthService(createPgUserStore(pool), { scryptParams: FAST_SCRYPT }); + const server = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); + const userIds: number[] = []; + const wineIds: number[] = []; + let nextWineId = firstId + Math.floor(Math.random() * 1_000_000); - /** Wines of the test's own. Returns their ids as the API writes them. */ - async function createWines(count: number): Promise { - const ids = Array.from({ length: count }, () => nextWineId++); - await pool.query( - `INSERT INTO wine (id, name, type, search_text) + /** Wines of the test's own. Returns their ids as the API writes them. */ + async function createWines(count: number): Promise { + const ids = Array.from({ length: count }, () => nextWineId++); + await pool.query( + `INSERT INTO wine (id, name, type, search_text) SELECT id, 'Testvin ' || id, 'Red', 'testvin ' || id FROM unnest($1::integer[]) AS id`, - [ids], - ); - wineIds.push(...ids); - return ids.map(String); - } - - /** A browser that keeps the session cookie. With `as`, a new user is registered and logged in. */ - async function createBrowser(as?: string) { - let cookie: string | undefined; - let username: string | undefined; - const jar: CookieJar = { - setSession: (token) => (cookie = token), - clearSession: () => (cookie = undefined), - }; - - if (as) { - username = `t_${as}_${Math.random().toString(36).slice(2, 10)}`.slice(0, 30); - const { user, session } = await service.register({ username, password: 'langt-nok-passord' }); - userIds.push(user.id); - cookie = session.token; - } + [ids], + ); + wineIds.push(...ids); + return ids.map(String); + } - async function request(query: string, variables?: Record): Promise { - const response = await server.executeOperation( - { query, variables }, - { contextValue: { loaders: createLoaders(), auth: createAuthContext(service, cookie, jar) } }, - ); - if (response.body.kind !== 'single') throw new Error('Expected a single result'); - return response.body.singleResult; - } + /** A browser that keeps the session cookie. With `as`, a new user is registered and logged in. */ + async function createBrowser(as?: string) { + let cookie: string | undefined; + let username: string | undefined; + const jar: CookieJar = { + setSession: (token) => (cookie = token), + clearSession: () => (cookie = undefined), + }; - return { request, username }; + if (as) { + username = `t_${as}_${Math.random().toString(36).slice(2, 10)}`.slice(0, 30); + const { user, session } = await service.register({ username, password: 'langt-nok-passord' }); + userIds.push(user.id); + cookie = session.token; } - /** Removes what the tests made, and closes the pool. Call it in afterAll. */ - async function close() { - await pool.query('DELETE FROM wine WHERE id = ANY($1)', [wineIds]); - await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]); - await pool.end(); + async function request( + query: string, + variables?: Record, + ): Promise { + const response = await server.executeOperation( + { query, variables }, + { + contextValue: { loaders: createLoaders(), auth: createAuthContext(service, cookie, jar) }, + }, + ); + if (response.body.kind !== 'single') throw new Error('Expected a single result'); + return response.body.singleResult; } - return { createBrowser, createWines, close }; + return { request, username }; + } + + /** Removes what the tests made, and closes the pool. Call it in afterAll. */ + async function close() { + await pool.query('DELETE FROM wine WHERE id = ANY($1)', [wineIds]); + await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]); + await pool.end(); + } + + return { createBrowser, createWines, close }; } diff --git a/backend/src/test/memory-user-store.ts b/backend/src/test/memory-user-store.ts index bcef196..120a5cf 100644 --- a/backend/src/test/memory-user-store.ts +++ b/backend/src/test/memory-user-store.ts @@ -3,50 +3,50 @@ import type { UserRecord, UserStore } from '../auth/user-store'; export function createMemoryUserStore(now: () => Date = () => new Date()) { - const users: UserRecord[] = []; - const sessions = new Map(); - let nextId = 1; - - const key = (tokenHash: Buffer) => tokenHash.toString('hex'); - - const store: UserStore = { - async createUser(username, passwordHash) { - if (users.some((user) => user.username === username)) return null; - const user = { id: nextId++, username, passwordHash, createdAt: now() }; - users.push(user); - return user; - }, - - async findUserByUsername(username) { - return users.find((user) => user.username === username) ?? null; - }, - - async createSession(tokenHash, userId, expiresAt) { - sessions.set(key(tokenHash), { userId, expiresAt }); - }, - - async findUserBySession(tokenHash) { - const session = sessions.get(key(tokenHash)); - if (!session || session.expiresAt <= now()) return null; - return users.find((user) => user.id === session.userId) ?? null; - }, - - async deleteSession(tokenHash) { - sessions.delete(key(tokenHash)); - }, - - async deleteExpiredSessions() { - let removed = 0; - for (const [id, session] of sessions) { - if (session.expiresAt <= now()) { - sessions.delete(id); - removed += 1; - } - } - return removed; - }, - }; - - // users and sessions are exposed so tests can check what was stored. - return { store, users, sessions }; + const users: UserRecord[] = []; + const sessions = new Map(); + let nextId = 1; + + const key = (tokenHash: Buffer) => tokenHash.toString('hex'); + + const store: UserStore = { + async createUser(username, passwordHash) { + if (users.some((user) => user.username === username)) return null; + const user = { id: nextId++, username, passwordHash, createdAt: now() }; + users.push(user); + return user; + }, + + async findUserByUsername(username) { + return users.find((user) => user.username === username) ?? null; + }, + + async createSession(tokenHash, userId, expiresAt) { + sessions.set(key(tokenHash), { userId, expiresAt }); + }, + + async findUserBySession(tokenHash) { + const session = sessions.get(key(tokenHash)); + if (!session || session.expiresAt <= now()) return null; + return users.find((user) => user.id === session.userId) ?? null; + }, + + async deleteSession(tokenHash) { + sessions.delete(key(tokenHash)); + }, + + async deleteExpiredSessions() { + let removed = 0; + for (const [id, session] of sessions) { + if (session.expiresAt <= now()) { + sessions.delete(id); + removed += 1; + } + } + return removed; + }, + }; + + // users and sessions are exposed so tests can check what was stored. + return { store, users, sessions }; } diff --git a/backend/src/wine-query.test.ts b/backend/src/wine-query.test.ts index 0c31803..cde7e6f 100644 --- a/backend/src/wine-query.test.ts +++ b/backend/src/wine-query.test.ts @@ -1,131 +1,133 @@ import { describe, expect, it } from 'vitest'; import { - buildFilterOptionsQueries, - buildWinesQuery, - decodeCursor, - encodeCursor, - MAX_FACET_VALUES, - MAX_PAGE_SIZE, + buildFilterOptionsQueries, + buildWinesQuery, + decodeCursor, + encodeCursor, + MAX_FACET_VALUES, + MAX_PAGE_SIZE, } from './wine-query'; describe('buildWinesQuery', () => { - it('returns all wines sorted by top rating when there are no arguments', () => { + it('returns all wines sorted by top rating when there are no arguments', () => { const query = buildWinesQuery({}); expect(query.listSql).not.toContain('WHERE'); expect(query.listSql).toContain('ORDER BY community_avg DESC NULLS LAST'); expect(query.first).toBe(24); expect(query.offset).toBe(0); - }); + }); - it('never puts the search text in the SQL itself', () => { + it('never puts the search text in the SQL itself', () => { const query = buildWinesQuery({ search: "'; DROP TABLE wine; --" }); expect(query.listSql).not.toContain('DROP TABLE'); expect(query.listParams[0]).toBe("%'; drop table wine; --%"); - }); + }); - it('makes the search case and accent insensitive', () => { + it('makes the search case and accent insensitive', () => { expect(buildWinesQuery({ search: ' ROSÉ ' }).listParams[0]).toBe('%rose%'); - }); + }); - it('escapes % and _ in the search text', () => { + it('escapes % and _ in the search text', () => { expect(buildWinesQuery({ search: '100%_' }).listParams[0]).toBe('%100\\%\\_%'); - }); + }); - it('combines search and filters with AND', () => { + it('combines search and filters with AND', () => { const query = buildWinesQuery({ - search: 'pinot', - filter: { types: ['Red'], countryCodes: ['FR'], grapes: ['Pinot Noir'], minRating: 4 }, + search: 'pinot', + filter: { types: ['Red'], countryCodes: ['FR'], grapes: ['Pinot Noir'], minRating: 4 }, }); expect(query.countSql).toContain( - 'WHERE search_text ILIKE $1 AND type = ANY($2) AND country_code = ANY($3) AND grapes && $4::text[] AND community_avg >= $5', + 'WHERE search_text ILIKE $1 AND type = ANY($2) AND country_code = ANY($3) AND grapes && $4::text[] AND community_avg >= $5', ); expect(query.countParams).toEqual(['%pinot%', ['Red'], ['FR'], ['Pinot Noir'], 4]); - }); + }); - it('ignores empty filter lists', () => { + it('ignores empty filter lists', () => { expect(buildWinesQuery({ filter: { types: [], grapes: null } }).listSql).not.toContain('WHERE'); - }); + }); - it('limits the page size', () => { + it('limits the page size', () => { expect(buildWinesQuery({ first: 1000 }).first).toBe(MAX_PAGE_SIZE); expect(buildWinesQuery({ first: 0 }).first).toBe(1); - }); + }); - it('fetches one extra row to know if there is a next page', () => { + it('fetches one extra row to know if there is a next page', () => { const query = buildWinesQuery({ first: 10, after: encodeCursor(20) }); expect(query.listParams.slice(-2)).toEqual([11, 20]); - }); + }); }); describe('buildFilterOptionsQueries', () => { - const args = { + const args = { search: 'pinot', filter: { - types: ['Red'], - countryCodes: ['FR'], - grapes: ['Merlot'], - harmonize: ['Beef'], - minRating: 4, + types: ['Red'], + countryCodes: ['FR'], + grapes: ['Merlot'], + harmonize: ['Beef'], + minRating: 4, }, - }; + }; - it('counts all wines when there is no search or filter', () => { + it('counts all wines when there is no search or filter', () => { const { types } = buildFilterOptionsQueries({}); expect(types.sql).not.toContain('WHERE'); expect(types.params).toEqual([]); - }); + }); - it('leaves out its own filter, so the other values in the group still have a count', () => { + it('leaves out its own filter, so the other values in the group still have a count', () => { const { types, countries, grapes, harmonize } = buildFilterOptionsQueries(args); expect(types.params).toEqual(['%pinot%', ['FR'], ['Merlot'], ['Beef'], 4]); expect(countries.params).toEqual(['%pinot%', ['Red'], ['Merlot'], ['Beef'], 4]); expect(grapes.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Beef'], 4]); expect(harmonize.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Merlot'], 4]); - }); + }); - it('keeps the search and the other filters', () => { + it('keeps the search and the other filters', () => { const { types } = buildFilterOptionsQueries(args); expect(types.sql).toContain('search_text ILIKE $1'); expect(types.sql).toContain('country_code = ANY($2)'); expect(types.sql).not.toContain('type = ANY'); - }); + }); - it('leaves out wines without a country', () => { + it('leaves out wines without a country', () => { expect(buildFilterOptionsQueries({}).countries.sql).toContain('WHERE country_code IS NOT NULL'); expect(buildFilterOptionsQueries(args).countries.sql).toContain('AND country_code IS NOT NULL'); - }); + }); - it('splits the lists of grapes and food into one row per value', () => { + it('splits the lists of grapes and food into one row per value', () => { const { grapes, harmonize } = buildFilterOptionsQueries({}); expect(grapes.sql).toContain('unnest(grapes)'); expect(harmonize.sql).toContain('unnest(harmonize)'); - }); + }); - it('limits the number of grapes and food values, since there can be thousands', () => { + it('limits the number of grapes and food values, since there can be thousands', () => { const { grapes, harmonize } = buildFilterOptionsQueries({}); expect(grapes.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`); expect(harmonize.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`); - }); + }); - it('never puts the search text in the SQL itself', () => { + it('never puts the search text in the SQL itself', () => { const { grapes } = buildFilterOptionsQueries({ search: "'; DROP TABLE wine; --" }); expect(grapes.sql).not.toContain('DROP TABLE'); - }); + }); }); describe('cursor', () => { - it('round-trips an offset', () => { + it('round-trips an offset', () => { expect(decodeCursor(encodeCursor(48))).toBe(48); expect(decodeCursor(null)).toBe(0); - }); + }); - it('rejects an invalid cursor', () => { + it('rejects an invalid cursor', () => { expect(() => decodeCursor('not-a-cursor')).toThrow('Invalid cursor.'); - }); + }); - it('rejects an offset too large for the database, instead of a server error', () => { + it('rejects an offset too large for the database, instead of a server error', () => { const huge = Buffer.from(`offset:${'9'.repeat(25)}`).toString('base64'); expect(() => decodeCursor(huge)).toThrow('Invalid cursor.'); - expect(() => decodeCursor(Buffer.from('offset:1000000001').toString('base64'))).toThrow('Invalid cursor.'); - }); -}); \ No newline at end of file + expect(() => decodeCursor(Buffer.from('offset:1000000001').toString('base64'))).toThrow( + 'Invalid cursor.', + ); + }); +}); diff --git a/backend/src/wine-query.ts b/backend/src/wine-query.ts index daac614..89e3adf 100644 --- a/backend/src/wine-query.ts +++ b/backend/src/wine-query.ts @@ -2,27 +2,28 @@ import { GraphQLError } from 'graphql'; import { toSearchText } from './xwines-parse'; -export type WineSort = 'TOP_RATED' | 'MOST_RATED' | 'NAME_ASC' | 'NAME_DESC' | 'ABV_ASC' | 'ABV_DESC'; +export type WineSort = + 'TOP_RATED' | 'MOST_RATED' | 'NAME_ASC' | 'NAME_DESC' | 'ABV_ASC' | 'ABV_DESC'; export interface WineFilter { - types?: string[] | null; - countryCodes?: string[] | null; - grapes?: string[] | null; - harmonize?: string[] | null; - minRating?: number | null; - minAbv?: number | null; - maxAbv?: number | null; + types?: string[] | null; + countryCodes?: string[] | null; + grapes?: string[] | null; + harmonize?: string[] | null; + minRating?: number | null; + minAbv?: number | null; + maxAbv?: number | null; } export interface FilterArgs { - search?: string | null; - filter?: WineFilter | null; + search?: string | null; + filter?: WineFilter | null; } export interface WinesArgs extends FilterArgs { - sort?: WineSort | null; - first?: number | null; - after?: string | null; + sort?: WineSort | null; + first?: number | null; + after?: string | null; } export const MAX_PAGE_SIZE = 50; @@ -32,61 +33,61 @@ export const MAX_FACET_VALUES = 40; // Only these ORDER BY clauses can ever reach the database. "id" last makes the order stable. const ORDER_BY: Record = { - TOP_RATED: 'community_avg DESC NULLS LAST, community_count DESC, id', - MOST_RATED: 'community_count DESC, community_avg DESC NULLS LAST, id', - NAME_ASC: 'name ASC, id', - NAME_DESC: 'name DESC, id', - ABV_ASC: 'abv ASC NULLS LAST, id', - ABV_DESC: 'abv DESC NULLS LAST, id', + TOP_RATED: 'community_avg DESC NULLS LAST, community_count DESC, id', + MOST_RATED: 'community_count DESC, community_avg DESC NULLS LAST, id', + NAME_ASC: 'name ASC, id', + NAME_DESC: 'name DESC, id', + ABV_ASC: 'abv ASC NULLS LAST, id', + ABV_DESC: 'abv DESC NULLS LAST, id', }; // The cursor is the position in the list, base64-encoded so the frontend treats it as a "black box". export function encodeCursor(offset: number): string { - return Buffer.from(`offset:${offset}`).toString('base64'); + return Buffer.from(`offset:${offset}`).toString('base64'); } /** No catalogue is this large. Larger offsets would only make the database fail. */ const MAX_OFFSET = 1_000_000_000; export function decodeCursor(cursor: string | null | undefined): number { - if (!cursor) return 0; - const match = /^offset:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); - const offset = match ? Number(match[1]) : NaN; - if (!Number.isInteger(offset) || offset > MAX_OFFSET) { - throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); - } - return offset; + if (!cursor) return 0; + const match = /^offset:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); + const offset = match ? Number(match[1]) : NaN; + if (!Number.isInteger(offset) || offset > MAX_OFFSET) { + throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + return offset; } /** Escapes % and _ so the user's text is matched literally by ILIKE. */ function escapeLike(text: string): string { - return text.replace(/[\\%_]/g, (char) => `\\${char}`); + return text.replace(/[\\%_]/g, (char) => `\\${char}`); } /** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */ function addParam(params: unknown[], value: unknown): string { - params.push(value); - return `$${params.length}`; + params.push(value); + return `$${params.length}`; } /** The search and the filters as WHERE conditions. `omit` leaves out one filter, for the counts. */ function buildWhere(args: FilterArgs, params: unknown[], omit?: keyof WineFilter): string[] { - const where: string[] = []; - const param = (value: unknown) => addParam(params, value); + const where: string[] = []; + const param = (value: unknown) => addParam(params, value); - const search = toSearchText(args.search ?? ''); - if (search) where.push(`search_text ILIKE ${param(`%${escapeLike(search)}%`)}`); + const search = toSearchText(args.search ?? ''); + if (search) where.push(`search_text ILIKE ${param(`%${escapeLike(search)}%`)}`); - const filter: WineFilter = { ...args.filter, ...(omit && { [omit]: null }) }; - if (filter.types?.length) where.push(`type = ANY(${param(filter.types)})`); - if (filter.countryCodes?.length) where.push(`country_code = ANY(${param(filter.countryCodes)})`); + const filter: WineFilter = { ...args.filter, ...(omit && { [omit]: null }) }; + if (filter.types?.length) where.push(`type = ANY(${param(filter.types)})`); + if (filter.countryCodes?.length) where.push(`country_code = ANY(${param(filter.countryCodes)})`); // && means "the lists have at least one value in common". - if (filter.grapes?.length) where.push(`grapes && ${param(filter.grapes)}::text[]`); - if (filter.harmonize?.length) where.push(`harmonize && ${param(filter.harmonize)}::text[]`); - if (filter.minRating != null) where.push(`community_avg >= ${param(filter.minRating)}`); - if (filter.minAbv != null) where.push(`abv >= ${param(filter.minAbv)}`); - if (filter.maxAbv != null) where.push(`abv <= ${param(filter.maxAbv)}`); - return where; + if (filter.grapes?.length) where.push(`grapes && ${param(filter.grapes)}::text[]`); + if (filter.harmonize?.length) where.push(`harmonize && ${param(filter.harmonize)}::text[]`); + if (filter.minRating != null) where.push(`community_avg >= ${param(filter.minRating)}`); + if (filter.minAbv != null) where.push(`abv >= ${param(filter.minAbv)}`); + if (filter.maxAbv != null) where.push(`abv <= ${param(filter.maxAbv)}`); + return where; } const toWhereSql = (where: string[]) => (where.length ? `WHERE ${where.join(' AND ')}` : ''); @@ -96,47 +97,47 @@ const toWhereSql = (where: string[]) => (where.length ? `WHERE ${where.join(' AN * out the group's own filter: with "Red" selected, "White" still shows what it would add. */ export function buildFilterOptionsQueries(args: FilterArgs) { - const query = (omit: keyof WineFilter, build: (where: string[]) => string) => { + const query = (omit: keyof WineFilter, build: (where: string[]) => string) => { const params: unknown[] = []; return { sql: build(buildWhere(args, params, omit)), params }; - }; + }; // Grapes and food are lists on each wine, so each value in a list becomes its own row. - const listValues = (column: 'grapes' | 'harmonize') => (where: string[]) => + const listValues = (column: 'grapes' | 'harmonize') => (where: string[]) => `SELECT value, value AS label, count(*)::int AS count FROM wine CROSS JOIN LATERAL unnest(${column}) AS value ${toWhereSql(where)} GROUP BY value ORDER BY count DESC, value LIMIT ${MAX_FACET_VALUES}`; - return { + return { types: query( - 'types', - (where) => `SELECT type AS value, type AS label, count(*)::int AS count + 'types', + (where) => `SELECT type AS value, type AS label, count(*)::int AS count FROM wine ${toWhereSql(where)} GROUP BY type ORDER BY count DESC, type`, ), countries: query( - 'countryCodes', - (where) => `SELECT country_code AS value, max(country) AS label, count(*)::int AS count + 'countryCodes', + (where) => `SELECT country_code AS value, max(country) AS label, count(*)::int AS count FROM wine ${toWhereSql([...where, 'country_code IS NOT NULL'])} GROUP BY country_code ORDER BY count DESC, label`, ), grapes: query('grapes', listValues('grapes')), harmonize: query('harmonize', listValues('harmonize')), - }; + }; } export function buildWinesQuery(args: WinesArgs) { - const params: unknown[] = []; - const whereSql = toWhereSql(buildWhere(args, params)); - const orderBy = ORDER_BY[args.sort ?? 'TOP_RATED']; - if (!orderBy) throw new Error('Invalid sort.'); + const params: unknown[] = []; + const whereSql = toWhereSql(buildWhere(args, params)); + const orderBy = ORDER_BY[args.sort ?? 'TOP_RATED']; + if (!orderBy) throw new Error('Invalid sort.'); - const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); - const offset = decodeCursor(args.after); - const countParams = [...params]; + const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); + const offset = decodeCursor(args.after); + const countParams = [...params]; // Fetch one extra row to know if there is a next page. const listSql = `SELECT * FROM wine ${whereSql} ORDER BY ${orderBy} LIMIT ${addParam(params, first + 1)} OFFSET ${addParam(params, offset)}`; - const countSql = `SELECT count(*)::int AS total FROM wine ${whereSql}`; + const countSql = `SELECT count(*)::int AS total FROM wine ${whereSql}`; - return { listSql, listParams: params, countSql, countParams, first, offset }; -} \ No newline at end of file + return { listSql, listParams: params, countSql, countParams, first, offset }; +} diff --git a/backend/src/xwines-parse.test.ts b/backend/src/xwines-parse.test.ts index 693bf46..9b6768b 100644 --- a/backend/src/xwines-parse.test.ts +++ b/backend/src/xwines-parse.test.ts @@ -3,43 +3,43 @@ import { parseCsv } from './csv'; import { parseNumber, parseTextList, parseYearList, toSearchText } from './xwines-parse'; describe('parseTextList', () => { - it('reads a Python list of strings', () => { + it('reads a Python list of strings', () => { expect(parseTextList("['Merlot', 'Syrah']")).toEqual(['Merlot', 'Syrah']); - }); + }); - it('reads double-quoted items that contain an apostrophe', () => { + it('reads double-quoted items that contain an apostrophe', () => { expect(parseTextList(`["Nero d'Avola", 'Syrah']`)).toEqual(["Nero d'Avola", 'Syrah']); - }); + }); - it('returns an empty list for empty input', () => { + it('returns an empty list for empty input', () => { expect(parseTextList('')).toEqual([]); expect(parseTextList('[]')).toEqual([]); - }); + }); }); describe('parseYearList', () => { - it('keeps years and skips non-vintage', () => { + it('keeps years and skips non-vintage', () => { expect(parseYearList("[2020, 2019, 'N.V.']")).toEqual([2020, 2019]); - }); + }); }); describe('parseNumber', () => { - it('returns null for empty or invalid values', () => { + it('returns null for empty or invalid values', () => { expect(parseNumber('13.5')).toBe(13.5); expect(parseNumber('')).toBeNull(); expect(parseNumber('N.V.')).toBeNull(); - }); + }); }); describe('toSearchText', () => { - it('lowercases, removes accents and joins the parts', () => { + it('lowercases, removes accents and joins the parts', () => { expect(toSearchText('Rosé', ' Domaine Drouhin ', null)).toBe('rose domaine drouhin'); - }); + }); }); describe('parseCsv', () => { - it('handles quoted fields with commas and escaped quotes', () => { + it('handles quoted fields with commas and escaped quotes', () => { const csv = 'id,grapes,note\n1,"[\'Merlot\', \'Syrah\']","say ""hi"""\n'; expect(parseCsv(csv)).toEqual([{ id: '1', grapes: "['Merlot', 'Syrah']", note: 'say "hi"' }]); - }); -}); \ No newline at end of file + }); +}); diff --git a/backend/src/xwines-parse.ts b/backend/src/xwines-parse.ts index 43ee0e4..42d2b5d 100644 --- a/backend/src/xwines-parse.ts +++ b/backend/src/xwines-parse.ts @@ -3,32 +3,32 @@ /** Parses Python list text into strings. Handles both 'single' and "double" quoted items. */ export function parseTextList(value: string | undefined): string[] { - if (!value) return []; - const items: string[] = []; - const pattern = /'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g; - for (const match of value.matchAll(pattern)) { + if (!value) return []; + const items: string[] = []; + const pattern = /'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g; + for (const match of value.matchAll(pattern)) { const item = (match[1] ?? match[2]).replace(/\\(.)/g, '$1').trim(); if (item) items.push(item); - } - return items; + } + return items; } /** Parses "[2020, 2019, 'N.V.']" into [2020, 2019]. Non-vintage ("N.V.") is skipped. */ export function parseYearList(value: string | undefined): number[] { - if (!value) return []; - return (value.match(/\d{4}/g) ?? []).map(Number); + if (!value) return []; + return (value.match(/\d{4}/g) ?? []).map(Number); } /** Returns a number, or null for empty or invalid values. */ export function parseNumber(value: string | undefined): number | null { - if (value === undefined || value.trim() === '') return null; - const number = Number(value); - return Number.isFinite(number) ? number : null; + if (value === undefined || value.trim() === '') return null; + const number = Number(value); + return Number.isFinite(number) ? number : null; } /** Lowercase text without accents, used for searching ("Rosé" -> "rose"). */ export function toSearchText(...parts: (string | null | undefined)[]): string { - return parts + return parts .filter((part): part is string => Boolean(part)) .join(' ') .normalize('NFD') @@ -36,4 +36,4 @@ export function toSearchText(...parts: (string | null | undefined)[]): string { .toLowerCase() .replace(/\s+/g, ' ') .trim(); -} \ No newline at end of file +} diff --git a/backend/tsconfig.json b/backend/tsconfig.json index b24e437..b94af3f 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -11,4 +11,4 @@ "types": ["node"] }, "include": ["src"] -} \ No newline at end of file +} diff --git a/backend/vitest.config.mts b/backend/vitest.config.mts index eff2e16..4cf1456 100644 --- a/backend/vitest.config.mts +++ b/backend/vitest.config.mts @@ -1,12 +1,12 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ - test: { - env: { - // Tests never use the database in backend/.env. db.ts reads DATABASE_URL when it is - // imported, and a variable that is already set wins over the .env file. The *.db.test.ts - // files use TEST_DATABASE_URL, and are skipped without it (see docs/api.md). - DATABASE_URL: process.env.TEST_DATABASE_URL ?? 'postgresql://localhost/not-used-in-tests', - }, + test: { + env: { + // Tests never use the database in backend/.env. db.ts reads DATABASE_URL when it is + // imported, and a variable that is already set wins over the .env file. The *.db.test.ts + // files use TEST_DATABASE_URL, and are skipped without it (see docs/api.md). + DATABASE_URL: process.env.TEST_DATABASE_URL ?? 'postgresql://localhost/not-used-in-tests', }, + }, }); From 32e6ebe0254e59f70473d7751c6471bd041eb91e Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 24 Nov 2026 13:28:53 +0100 Subject: [PATCH 3/5] style(frontend): format App.test.tsx with Prettier (#112) --- frontend/src/app/App.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx index bd6ef64..5f20e05 100644 --- a/frontend/src/app/App.test.tsx +++ b/frontend/src/app/App.test.tsx @@ -67,4 +67,4 @@ describe('AppRoutes', () => { renderRoute('/sok'); expect(await findHeading('Utforsk viner')).toBeInTheDocument(); }); -}); \ No newline at end of file +}); From 67fc2241b614ef7fb62bd08ce785a44fdae1399d Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 24 Nov 2026 13:30:58 +0100 Subject: [PATCH 4/5] docs: ESLint, Prettier and TypeScript 6 in the backend (#112) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ff5a395..374d683 100644 --- a/README.md +++ b/README.md @@ -379,8 +379,8 @@ npm test ### Tools -- ESLint with TypeScript and React Hooks rules, and Prettier for formatting. -- Strict TypeScript in both frontend and backend. +- ESLint and Prettier in both frontend and backend, with the same settings. The frontend also has the React Hooks rules. +- Strict TypeScript in both frontend and backend. Both use TypeScript 6, because typescript-eslint does not support TypeScript 7 yet.