Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

test: cover the untested authorization, billing and SQL-generation paths, and run the suites in CI (#1125)

Goldflag9ec40e2c26bf
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 000000000..be92bb4a6
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,82 @@
+name: Tests
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ branches:
+ - master
+ paths-ignore:
+ - "docs/**"
+ - "**.md"
+
+# A newer push to the same branch makes an in-flight run obsolete.
+concurrency:
+ group: tests-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+# Pinned so a run never depends on the runner's default zone. The suites are
+# timezone-independent (verified across UTC, US, EU, IN and NZ zones); this keeps
+# an accidental system-zone dependency from passing here and failing elsewhere.
+env:
+ TZ: UTC
+
+jobs:
+ server:
+ name: Server
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: npm
+ cache-dependency-path: |
+ shared/package-lock.json
+ server/package-lock.json
+
+ # server depends on @rybbit/shared via `file:../shared`, which resolves to
+ # the package's built `dist/` β€” so shared must be built before install.
+ - name: Install and build shared
+ working-directory: shared
+ run: |
+ npm ci
+ npm run build
+
+ - name: Install server dependencies
+ working-directory: server
+ run: npm ci --legacy-peer-deps
+
+ - name: Run server tests
+ working-directory: server
+ run: npm run test:run
+
+ client:
+ name: Client
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: npm
+ cache-dependency-path: |
+ shared/package-lock.json
+ client/package-lock.json
+
+ - name: Install and build shared
+ working-directory: shared
+ run: |
+ npm ci
+ npm run build
+
+ - name: Install client dependencies
+ working-directory: client
+ run: npm ci --legacy-peer-deps
+
+ - name: Run client tests
+ working-directory: client
+ run: npm test
diff --git a/client/package-lock.json b/client/package-lock.json
index de935d596..b3cca026f 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -93,6 +93,8 @@
"zustand": "5.0.4"
},
"devDependencies": {
+ "@testing-library/dom": "^10.4.1",
+ "@testing-library/react": "^16.3.2",
"@types/d3": "7.4.3",
"@types/geojson": "7946.0.16",
"@types/lodash": "4.17.16",
@@ -105,6 +107,7 @@
"@types/react-syntax-highlighter": "^15.5.13",
"eslint": "^9.39.1",
"eslint-config-next": "^16.0.7",
+ "jsdom": "^29.1.1",
"knip": "^5.60.2",
"prettier": "^3.8.1",
"tailwindcss": "^4.1.17",
@@ -134,6 +137,57 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "5.1.11",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@csstools/css-calc": "^3.2.0",
+ "@csstools/css-color-parser": "^4.1.0",
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/dom-selector": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",
+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@asamuzakjp/nwsapi": "^2.3.9",
+ "bidi-js": "^1.0.3",
+ "css-tree": "^3.2.1",
+ "is-potential-custom-element-name": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/generational-cache": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",
+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/nwsapi": {
+ "version": "2.3.9",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",
+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@babel/code-frame": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
@@ -547,6 +601,19 @@
"integrity": "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g==",
"license": "MIT"
},
+ "node_modules/@bramus/specificity": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "css-tree": "^3.0.0"
+ },
+ "bin": {
+ "specificity": "bin/cli.js"
+ }
+ },
"node_modules/@calcom/embed-core": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@calcom/embed-core/-/embed-core-1.5.3.tgz",
@@ -576,6 +643,146 @@
"@calcom/embed-core": "1.5.3"
}
},
+ "node_modules/@csstools/color-helpers": {
+ "version": "6.1.1",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",
+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",
+ "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.0.tgz",
+ "integrity": "sha512-5+5LEmFuY1AjXdYhmgjTJogtQnP1evJ1zrBZGUNZ0thkpwnnmKxcHdAMn/OtFjAb25zA+jKDVYVRl+5G7rjv1A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^6.1.1",
+ "@csstools/css-calc": "^3.3.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",
+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-syntax-patches-for-csstree": {
+ "version": "1.1.8",
+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.8.tgz",
+ "integrity": "sha512-CpMLjAvwQg3BL5S0IeqsZNMH7EQrEWi0kLKOC13ZBF0ZwERiLWlibNPJr8G1kdU3Ms/r2KiNrF81pUh2HwAHdg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "peerDependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "peerDependenciesMeta": {
+ "css-tree": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",
+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
"node_modules/@date-fns/tz": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.4.1.tgz",
@@ -757,6 +964,24 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
+ "node_modules/@exodus/bytes": {
+ "version": "1.15.1",
+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
+ "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "@noble/hashes": "^1.8.0 || ^2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@noble/hashes": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@floating-ui/core": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",
@@ -5958,6 +6183,64 @@
"url": "https://github.com/sponsors/tannerlinsley"
}
},
+ "node_modules/@testing-library/dom": {
+ "version": "10.4.1",
+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",
+ "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.10.4",
+ "@babel/runtime": "^7.12.5",
+ "@types/aria-query": "^5.0.1",
+ "aria-query": "5.3.0",
+ "dom-accessibility-api": "^0.5.9",
+ "lz-string": "^1.5.0",
+ "picocolors": "1.1.1",
+ "pretty-format": "^27.0.2"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/aria-query": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
+ "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "dequal": "^2.0.3"
+ }
+ },
+ "node_modules/@testing-library/react": {
+ "version": "16.3.2",
+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz",
+ "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.12.5"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@testing-library/dom": "^10.0.0",
+ "@types/react": "^18.0.0 || ^19.0.0",
+ "@types/react-dom": "^18.0.0 || ^19.0.0",
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@tsconfig/svelte": {
"version": "1.0.13",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-1.0.13.tgz",
@@ -5974,6 +6257,13 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/aria-query": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
+ "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -7186,6 +7476,16 @@
"url": "https://github.com/sponsors/epoberezkin"
}
},
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
@@ -7632,6 +7932,16 @@
}
}
},
+ "node_modules/bidi-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "require-from-string": "^2.0.2"
+ }
+ },
"node_modules/boring-avatars": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/boring-avatars/-/boring-avatars-2.0.4.tgz",
@@ -7976,6 +8286,20 @@
"node": ">= 8"
}
},
+ "node_modules/css-tree": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mdn-data": "2.27.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
+ }
+ },
"node_modules/csscolorparser": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/csscolorparser/-/csscolorparser-1.0.3.tgz",
@@ -8429,6 +8753,20 @@
"dev": true,
"license": "BSD-2-Clause"
},
+ "node_modules/data-urls": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
"node_modules/data-view-buffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -8509,6 +8847,13 @@
}
}
},
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/decode-named-character-reference": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
@@ -8589,6 +8934,16 @@
"node": ">=0.4.0"
}
},
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -8623,6 +8978,13 @@
"node": ">=0.10.0"
}
},
+ "node_modules/dom-accessibility-api": {
+ "version": "0.5.16",
+ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
+ "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -8697,6 +9059,19 @@
"node": ">=10.13.0"
}
},
+ "node_modules/entities": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/es-abstract": {
"version": "1.24.0",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.0.tgz",
@@ -10081,6 +10456,19 @@
"integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==",
"license": "CC0-1.0"
},
+ "node_modules/html-encoding-sniffer": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.6.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
@@ -10525,6 +10913,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/is-regex": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
@@ -10767,6 +11162,57 @@
"js-yaml": "bin/js-yaml.js"
}
},
+ "node_modules/jsdom": {
+ "version": "29.1.1",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",
+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^5.1.11",
+ "@asamuzakjp/dom-selector": "^7.1.1",
+ "@bramus/specificity": "^2.4.2",
+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",
+ "@exodus/bytes": "^1.15.0",
+ "css-tree": "^3.2.1",
+ "data-urls": "^7.0.0",
+ "decimal.js": "^10.6.0",
+ "html-encoding-sniffer": "^6.0.0",
+ "is-potential-custom-element-name": "^1.0.1",
+ "lru-cache": "^11.3.5",
+ "parse5": "^8.0.1",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^6.0.1",
+ "undici": "^7.25.0",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^8.0.1",
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.1",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/jsdom/node_modules/lru-cache": {
+ "version": "11.5.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",
+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
"node_modules/jsesc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
@@ -11349,6 +11795,16 @@
"node": ">=12"
}
},
+ "node_modules/lz-string": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
+ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "lz-string": "bin/bin.js"
+ }
+ },
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -11430,6 +11886,13 @@
"node": ">= 0.4"
}
},
+ "node_modules/mdn-data": {
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@@ -12176,6 +12639,19 @@
"integrity": "sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==",
"license": "MIT"
},
+ "node_modules/parse5": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -12316,6 +12792,41 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/pretty-format": {
+ "version": "27.5.1",
+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1",
+ "ansi-styles": "^5.0.0",
+ "react-is": "^17.0.1"
+ },
+ "engines": {
+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
+ }
+ },
+ "node_modules/pretty-format/node_modules/ansi-styles": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/pretty-format/node_modules/react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
@@ -12738,6 +13249,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/resize-observer-polyfill": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz",
@@ -13016,6 +13537,19 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
@@ -13552,6 +14086,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tailwind-merge": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz",
@@ -13640,6 +14181,26 @@
"node": ">=14.0.0"
}
},
+ "node_modules/tldts": {
+ "version": "7.4.10",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.10.tgz",
+ "integrity": "sha512-GgouD1B+sWwvkaEq8vXC15DjQitxbvs12oIXELpconwm+Tg3zfcEv4jgzq3vtKverDXsg3VI8aRgNL2Nra0Iog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^7.4.10"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "7.4.10",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.10.tgz",
+ "integrity": "sha512-KnQjp53ZekKgm/r3l+u8kJGGzYgrWdP8+Mql7a4vijh2WE0IrZWspQj/TpTxDho/YxO+AnOZnIjQcCD+q6iJsw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -13653,6 +14214,32 @@
"node": ">=8.0"
}
},
+ "node_modules/tough-cookie": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^7.0.5"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/ts-api-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
@@ -13856,6 +14443,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/undici": {
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
@@ -14458,6 +15055,19 @@
}
}
},
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/walk-up-path": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz",
@@ -14474,6 +15084,41 @@
"integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",
"license": "Apache-2.0"
},
+ "node_modules/webidl-conversions": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.11.0",
+ "tr46": "^6.0.0",
+ "webidl-conversions": "^8.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -14613,12 +15258,29 @@
"node": ">=0.10.0"
}
},
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/xml-utils": {
"version": "1.10.2",
"resolved": "https://registry.npmjs.org/xml-utils/-/xml-utils-1.10.2.tgz",
"integrity": "sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==",
"license": "CC0-1.0"
},
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
diff --git a/client/package.json b/client/package.json
index f81adde2f..d80e3ff4a 100644
--- a/client/package.json
+++ b/client/package.json
@@ -100,6 +100,8 @@
"zustand": "5.0.4"
},
"devDependencies": {
+ "@testing-library/dom": "^10.4.1",
+ "@testing-library/react": "^16.3.2",
"@types/d3": "7.4.3",
"@types/geojson": "7946.0.16",
"@types/lodash": "4.17.16",
@@ -112,6 +114,7 @@
"@types/react-syntax-highlighter": "^15.5.13",
"eslint": "^9.39.1",
"eslint-config-next": "^16.0.7",
+ "jsdom": "^29.1.1",
"knip": "^5.60.2",
"prettier": "^3.8.1",
"tailwindcss": "^4.1.17",
diff --git a/client/src/components/ToggleChip.test.tsx b/client/src/components/ToggleChip.test.tsx
new file mode 100644
index 000000000..c91c1f059
--- /dev/null
+++ b/client/src/components/ToggleChip.test.tsx
@@ -0,0 +1,79 @@
+import { render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ToggleChip } from "./ToggleChip";
+
+// Proof of life for the jsdom project in vitest.config.ts: a purely
+// presentational component, rendered and driven through the real DOM.
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("ToggleChip", () => {
+ it("renders its label inside a non-submitting button", () => {
+ render(<ToggleChip isSelected={false} onClick={() => {}} label="Chrome" />);
+
+ const button = screen.getByRole("button", { name: "Chrome" });
+ expect(button).toBeTruthy();
+ expect(button.getAttribute("type")).toBe("button");
+ });
+
+ it("calls onClick when clicked", () => {
+ const onClick = vi.fn();
+ render(<ToggleChip isSelected={false} onClick={onClick} label="Chrome" />);
+
+ screen.getByRole("button").click();
+
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+
+ it("renders no indicator unless one is asked for", () => {
+ const { container } = render(<ToggleChip isSelected={false} onClick={() => {}} label="Chrome" />);
+
+ expect(container.querySelectorAll("div")).toHaveLength(0);
+ });
+
+ it("renders a colour swatch when given one, and dims it while unselected", () => {
+ const { container, rerender } = render(
+ <ToggleChip isSelected={false} onClick={() => {}} label="Chrome" swatchColor="rgb(255, 0, 0)" />
+ );
+
+ const swatch = container.querySelector("[style]") as HTMLElement;
+ expect(swatch.style.backgroundColor).toBe("rgb(255, 0, 0)");
+ expect(swatch.parentElement!.className).toContain("opacity-30");
+
+ rerender(<ToggleChip isSelected onClick={() => {}} label="Chrome" swatchColor="rgb(255, 0, 0)" />);
+ expect((container.querySelector("[style]") as HTMLElement).parentElement!.className).toContain("opacity-100");
+ });
+
+ it("lets an explicit indicator win over the swatch colour", () => {
+ render(
+ <ToggleChip
+ isSelected
+ onClick={() => {}}
+ label="Chrome"
+ swatchColor="red"
+ indicator={<span data-testid="icon" />}
+ />
+ );
+
+ expect(screen.getByTestId("icon")).toBeTruthy();
+ expect(document.querySelector("[style]")).toBeNull();
+ });
+
+ it("appends a right adornment and merges extra class names", () => {
+ render(
+ <ToggleChip
+ isSelected={false}
+ onClick={() => {}}
+ label="Chrome"
+ rightAdornment={<span>42</span>}
+ className="custom-chip"
+ />
+ );
+
+ const button = screen.getByRole("button");
+ expect(button.textContent).toBe("Chrome42");
+ expect(button.className).toContain("custom-chip");
+ });
+});
diff --git a/client/src/lib/dateTimeUtils.test.ts b/client/src/lib/dateTimeUtils.test.ts
new file mode 100644
index 000000000..d9d2583c6
--- /dev/null
+++ b/client/src/lib/dateTimeUtils.test.ts
@@ -0,0 +1,217 @@
+import { DateTime, Settings } from "luxon";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// dateTimeUtils reads navigator.language and the store's timezone at module
+// scope, so both are pinned before it is loaded. Everything else here either
+// carries an explicit zone or round-trips through the machine's own zone, so
+// no TZ pinning is needed.
+const getTimezone = vi.hoisted(() => vi.fn<() => string>(() => "UTC"));
+vi.mock("./store", () => ({ getTimezone }));
+
+vi.stubGlobal("navigator", { language: "en-US" });
+
+const {
+ formatChartDateTime,
+ formatDuration,
+ formatLocalTime,
+ formatShortDuration,
+ getTimezoneLabel,
+ hour12,
+ hourLabels,
+ hourMinuteLabels,
+ longDayNames,
+ parseUtcTimestamp,
+ shortDayNames,
+ timeZone,
+ timezones,
+ userLocale,
+} = await import("./dateTimeUtils");
+
+beforeEach(() => {
+ getTimezone.mockReturnValue("UTC");
+ Settings.defaultLocale = "en-US";
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("locale detection", () => {
+ it("takes the locale from navigator and resolves a 12-hour preference for en-US", () => {
+ expect(userLocale).toBe("en-US");
+ expect(hour12).toBe(true);
+ });
+
+ it("resolves the runtime timezone to a zone Luxon can use", () => {
+ expect(timeZone).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);
+ expect(DateTime.now().setZone(timeZone).isValid).toBe(true);
+ });
+});
+
+describe("formatDuration", () => {
+ it("shows seconds alone below a minute", () => {
+ expect(formatDuration(0)).toBe("0 sec");
+ expect(formatDuration(45)).toBe("45 sec");
+ expect(formatDuration(59)).toBe("59 sec");
+ });
+
+ it("shows minutes and seconds from a minute up", () => {
+ expect(formatDuration(60)).toBe("1 min, 0 sec");
+ expect(formatDuration(90)).toBe("1 min, 30 sec");
+ expect(formatDuration(605)).toBe("10 min, 5 sec");
+ });
+
+ it("rounds fractional seconds and carries the rounding into minutes", () => {
+ expect(formatDuration(44.4)).toBe("44 sec");
+ expect(formatDuration(59.6)).toBe("1 min, 0 sec");
+ });
+
+ it("never rolls up past minutes", () => {
+ expect(formatDuration(3600)).toBe("60 min, 0 sec");
+ expect(formatDuration(7325)).toBe("122 min, 5 sec");
+ });
+});
+
+describe("formatShortDuration", () => {
+ it("shows seconds alone below a minute", () => {
+ expect(formatShortDuration(0)).toBe("0s");
+ expect(formatShortDuration(45)).toBe("45s");
+ expect(formatShortDuration(59)).toBe("59s");
+ });
+
+ it("drops a zero seconds part", () => {
+ expect(formatShortDuration(60)).toBe("1m");
+ expect(formatShortDuration(120)).toBe("2m");
+ });
+
+ it("shows both parts when there is a remainder", () => {
+ expect(formatShortDuration(90)).toBe("1m 30s");
+ expect(formatShortDuration(3661)).toBe("61m 1s");
+ });
+
+ it("rounds the seconds part", () => {
+ expect(formatShortDuration(59.4)).toBe("59s");
+ // Quirk: the parts are computed independently, so a seconds value that
+ // rounds up to 60 is rendered as-is instead of carrying into the minutes.
+ expect(formatShortDuration(119.6)).toBe("1m 60s");
+ });
+});
+
+describe("formatLocalTime", () => {
+ it("pads the minutes to two digits", () => {
+ expect(formatLocalTime(9, 5)).toMatch(/9.05/);
+ });
+
+ it("distinguishes morning from afternoon under a 12-hour preference", () => {
+ expect(formatLocalTime(21, 5)).toMatch(/9.05/);
+ expect(formatLocalTime(9, 5)).not.toBe(formatLocalTime(21, 5));
+ });
+});
+
+describe("formatChartDateTime", () => {
+ const dt = DateTime.fromISO("2024-03-15T12:30:00Z", { zone: "utc" });
+
+ it("shows a weekday and date, with no time, for the day bucket", () => {
+ expect(formatChartDateTime(dt, "day", "en-US")).toBe("Fri, Mar 15");
+ });
+
+ it("shows the hour for coarser-than-day buckets", () => {
+ expect(formatChartDateTime(dt, "hour", "en-US")).toBe("Mar 15, 12 PM");
+ expect(formatChartDateTime(dt, "week", "en-US")).toBe("Mar 15, 12 PM");
+ expect(formatChartDateTime(dt, "month", "en-US")).toBe("Mar 15, 12 PM");
+ });
+
+ it.each(["minute", "five_minutes", "ten_minutes", "fifteen_minutes"] as const)(
+ "shows minutes for the %s bucket",
+ bucket => {
+ expect(formatChartDateTime(dt, bucket, "en-US")).toBe("Mar 15, 12:30 PM");
+ }
+ );
+
+ it("renders in the timezone the store reports, not the datetime's own zone", () => {
+ getTimezone.mockReturnValue("America/New_York");
+
+ expect(formatChartDateTime(dt, "hour", "en-US")).toBe("Mar 15, 8 AM");
+ expect(formatChartDateTime(dt, "day", "en-US")).toBe("Fri, Mar 15");
+ });
+
+ it("crosses the date line when the timezone pushes it there", () => {
+ getTimezone.mockReturnValue("Asia/Tokyo");
+
+ expect(formatChartDateTime(dt, "day", "en-US")).toBe("Fri, Mar 15");
+ expect(formatChartDateTime(DateTime.fromISO("2024-03-15T20:00:00Z", { zone: "utc" }), "day", "en-US")).toBe(
+ "Sat, Mar 16"
+ );
+ });
+
+ it("honours the locale it is handed", () => {
+ expect(formatChartDateTime(dt, "day", "de-DE")).toBe("Fr., 15. MΓ€rz");
+ });
+});
+
+describe("parseUtcTimestamp", () => {
+ it("reads a SQL timestamp as UTC and moves it into the selected timezone", () => {
+ getTimezone.mockReturnValue("America/New_York");
+
+ const parsed = parseUtcTimestamp("2024-03-15 12:00:00");
+
+ expect(parsed.isValid).toBe(true);
+ expect(parsed.zoneName).toBe("America/New_York");
+ expect(parsed.toISO()).toBe("2024-03-15T08:00:00.000-04:00");
+ });
+
+ it("accepts a Date and treats its wall-clock fields as UTC", () => {
+ getTimezone.mockReturnValue("Asia/Tokyo");
+
+ const parsed = parseUtcTimestamp(new Date(Date.UTC(2024, 2, 15, 12, 0, 0)));
+
+ expect(parsed.toISO()).toBe("2024-03-15T21:00:00.000+09:00");
+ });
+
+ it("keeps the timestamp unchanged when the selected timezone is UTC", () => {
+ expect(parseUtcTimestamp("2024-03-15 12:00:00").toISO()).toBe("2024-03-15T12:00:00.000Z");
+ });
+
+ it("returns an invalid DateTime for an unparseable timestamp rather than throwing", () => {
+ expect(parseUtcTimestamp("not a timestamp").isValid).toBe(false);
+ });
+});
+
+describe("timezone list", () => {
+ it("leads with the system sentinel and labels it System", () => {
+ expect(timezones[0]).toEqual({ value: "system", label: "System" });
+ expect(getTimezoneLabel("system")).toBe("System");
+ });
+
+ it("returns the IANA name unchanged for every real zone", () => {
+ expect(getTimezoneLabel("Asia/Tokyo")).toBe("Asia/Tokyo");
+ expect(getTimezoneLabel("UTC")).toBe("UTC");
+ });
+
+ it("offers only zones Luxon can resolve, with no duplicates", () => {
+ const real = timezones.filter(tz => tz.value !== "system");
+
+ expect(real.length).toBeGreaterThan(0);
+ for (const tz of real) {
+ expect(DateTime.now().setZone(tz.value).isValid, tz.value).toBe(true);
+ }
+ expect(new Set(timezones.map(tz => tz.value)).size).toBe(timezones.length);
+ });
+});
+
+describe("precomputed labels", () => {
+ it("lists weekdays Monday-first", () => {
+ expect(longDayNames).toEqual(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);
+ expect(shortDayNames).toEqual(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]);
+ });
+
+ it("lists all 24 hours in the detected 12-hour format", () => {
+ expect(hourLabels).toHaveLength(24);
+ expect(hourLabels[0]).toBe("12 AM");
+ expect(hourLabels[13]).toBe("1 PM");
+
+ expect(hourMinuteLabels).toHaveLength(24);
+ expect(hourMinuteLabels[0]).toBe("12:00 AM");
+ expect(hourMinuteLabels[13]).toBe("1:00 PM");
+ });
+});
diff --git a/client/src/lib/filterGroups.test.ts b/client/src/lib/filterGroups.test.ts
new file mode 100644
index 000000000..c2195ee5b
--- /dev/null
+++ b/client/src/lib/filterGroups.test.ts
@@ -0,0 +1,91 @@
+import { FilterParameter } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import {
+ EVENT_FILTERS,
+ FUNNEL_PAGE_FILTERS,
+ GOALS_PAGE_FILTERS,
+ JOURNEY_PAGE_FILTERS,
+ SESSION_PAGE_FILTERS,
+ SESSION_REPLAY_PAGE_FILTERS,
+ USER_DETAIL_PAGE_FILTERS,
+ USER_PAGE_FILTERS,
+} from "./filterGroups";
+import { parseAsFilters } from "./parsers";
+
+const GROUPS: Record<string, FilterParameter[]> = {
+ SESSION_PAGE_FILTERS,
+ USER_DETAIL_PAGE_FILTERS,
+ EVENT_FILTERS,
+ GOALS_PAGE_FILTERS,
+ FUNNEL_PAGE_FILTERS,
+ USER_PAGE_FILTERS,
+ JOURNEY_PAGE_FILTERS,
+ SESSION_REPLAY_PAGE_FILTERS,
+};
+
+describe.each(Object.entries(GROUPS))("%s", (_name, group) => {
+ it("is non-empty", () => {
+ expect(group.length).toBeGreaterThan(0);
+ });
+
+ it("only offers parameters that survive a url round-trip", () => {
+ // A parameter the URL parser rejects would be silently dropped on reload,
+ // so anything the picker offers has to be in parseAsFilters' allow-list.
+ const filters = group.map(parameter => ({ parameter, type: "equals" as const, value: ["x"] }));
+
+ expect(parseAsFilters.parse(JSON.stringify(filters))).toHaveLength(group.length);
+ });
+});
+
+describe("uniqueness", () => {
+ it.each(Object.entries(GROUPS).filter(([name]) => name !== "EVENT_FILTERS"))(
+ "%s lists each parameter once",
+ (_name, group) => {
+ expect(new Set(group).size).toBe(group.length);
+ }
+ );
+
+ it("EVENT_FILTERS is the exception β€” it re-adds page_title, which BASE_FILTERS already has", () => {
+ // Current behaviour, and a bug: the filter picker gets page_title twice.
+ expect(EVENT_FILTERS.filter(parameter => parameter === "page_title")).toHaveLength(2);
+ expect(new Set(EVENT_FILTERS).size).toBe(EVENT_FILTERS.length - 1);
+ });
+});
+
+describe("group relationships", () => {
+ it("scopes the user detail page to everything but user_id", () => {
+ expect(SESSION_PAGE_FILTERS).toContain("user_id");
+ expect(USER_DETAIL_PAGE_FILTERS).not.toContain("user_id");
+ expect(USER_DETAIL_PAGE_FILTERS).toEqual(SESSION_PAGE_FILTERS.filter(f => f !== "user_id"));
+ });
+
+ it("gives goals and funnels the same base set, without page-level parameters", () => {
+ expect(GOALS_PAGE_FILTERS).toEqual(FUNNEL_PAGE_FILTERS);
+ for (const pageLevel of ["pathname", "entry_page", "exit_page", "event_name"] as FilterParameter[]) {
+ expect(GOALS_PAGE_FILTERS).not.toContain(pageLevel);
+ }
+ });
+
+ it("offers event_name only where events are listed", () => {
+ expect(EVENT_FILTERS).toContain("event_name");
+ expect(SESSION_PAGE_FILTERS).toContain("event_name");
+ expect(USER_PAGE_FILTERS).not.toContain("event_name");
+ expect(JOURNEY_PAGE_FILTERS).not.toContain("event_name");
+ expect(SESSION_REPLAY_PAGE_FILTERS).not.toContain("event_name");
+ });
+
+ it("keeps every group's parameters within the session page's superset, minus journey-only geo", () => {
+ for (const [name, group] of Object.entries(GROUPS)) {
+ for (const parameter of group) {
+ expect(SESSION_PAGE_FILTERS, `${name}.${parameter}`).toContain(parameter);
+ }
+ }
+ });
+
+ it("restricts session replay to session-level dimensions only", () => {
+ for (const pageLevel of ["pathname", "entry_page", "exit_page", "querystring"] as FilterParameter[]) {
+ expect(SESSION_REPLAY_PAGE_FILTERS).not.toContain(pageLevel);
+ }
+ expect(SESSION_REPLAY_PAGE_FILTERS).toContain("user_id");
+ });
+});
diff --git a/client/src/lib/import/csvParser.test.ts b/client/src/lib/import/csvParser.test.ts
new file mode 100644
index 000000000..756f56ca0
--- /dev/null
+++ b/client/src/lib/import/csvParser.test.ts
@@ -0,0 +1,300 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ImportPlatform } from "@/types/import";
+
+const authedFetch = vi.hoisted(() => vi.fn());
+vi.mock("@/api/utils", () => ({ authedFetch }));
+
+import { CsvParser } from "./csvParser";
+
+// ---------------------------------------------------------------------------
+// Harness
+//
+// startImport hands the input straight to Papa. Papa's worker path is inert
+// outside a browser, and it streams a string through the same chunk/complete
+// callbacks a File would take, so a plain string stands in for the upload.
+// ---------------------------------------------------------------------------
+
+const SITE_ID = 42;
+const IMPORT_ID = "import-9";
+
+interface Upload {
+ events: Record<string, string>[];
+ isLastBatch: boolean;
+}
+
+function uploads(): Upload[] {
+ return authedFetch.mock.calls.map(call => (call[2] as { data: Upload }).data);
+}
+
+const events = () => uploads().flatMap(u => u.events);
+
+async function runImport(
+ csv: string,
+ opts: { platform?: ImportPlatform; earliest?: string; latest?: string } = {}
+): Promise<Upload[]> {
+ authedFetch.mockClear();
+ const parser = new CsvParser(
+ SITE_ID,
+ IMPORT_ID,
+ opts.platform ?? "umami",
+ opts.earliest ?? "2024-01-01",
+ opts.latest ?? "2024-12-31"
+ );
+ parser.startImport(csv as unknown as File);
+ // The chunk/complete callbacks are async and Papa does not await them.
+ await new Promise(resolve => setTimeout(resolve, 0));
+ return uploads();
+}
+
+const UMAMI_HEADER =
+ "session_id,hostname,browser,os,device,screen,language,country,region,city," +
+ "url_path,url_query,referrer_path,referrer_domain,page_title,event_type,event_name,distinct_id,created_at\n";
+
+const UMAMI_ROW =
+ "sess-1,example.com,chrome,Mac OS,desktop,1920x1080,en-US,US,US-CA,San Francisco," +
+ "/pricing,?ref=hn,/post,news.ycombinator.com,Pricing,1,,user-7,2024-03-15 10:00:00\n";
+
+const SA_HEADER =
+ "added_iso,country_code,datapoint,document_referrer,hostname,lang_language,lang_region," +
+ "path,query,screen_height,screen_width,session_id,user_agent,uuid\n";
+
+const SA_ROW =
+ "2024-03-15T10:00:00.000Z,US,pageview,https://news.ycombinator.com/,example.com,en,US," +
+ "/pricing,?ref=hn,1080,1920,sess-1,Mozilla/5.0,uuid-1\n";
+
+beforeEach(() => {
+ authedFetch.mockReset();
+ authedFetch.mockResolvedValue(undefined);
+});
+
+describe("upload envelope", () => {
+ it("posts rows to the import's events endpoint and closes with an empty final batch", async () => {
+ await runImport(UMAMI_HEADER + UMAMI_ROW);
+
+ expect(authedFetch).toHaveBeenCalledTimes(2);
+ expect(authedFetch.mock.calls[0][0]).toBe(`/sites/${SITE_ID}/imports/${IMPORT_ID}/events`);
+ expect(authedFetch.mock.calls[0][2]).toMatchObject({ method: "POST" });
+ expect(uploads().map(u => ({ n: u.events.length, last: u.isLastBatch }))).toEqual([
+ { n: 1, last: false },
+ { n: 0, last: true },
+ ]);
+ });
+
+ it("sends only the final batch when nothing survives, never an empty data chunk", async () => {
+ const sent = await runImport(UMAMI_HEADER);
+
+ expect(sent).toEqual([{ events: [], isLastBatch: true }]);
+ });
+});
+
+describe("umami rows", () => {
+ it("maps every recognised column onto the wire shape", async () => {
+ await runImport(UMAMI_HEADER + UMAMI_ROW);
+
+ expect(events()[0]).toEqual({
+ session_id: "sess-1",
+ hostname: "example.com",
+ browser: "chrome",
+ os: "Mac OS",
+ device: "desktop",
+ screen: "1920x1080",
+ language: "en-US",
+ country: "US",
+ region: "US-CA",
+ city: "San Francisco",
+ url_path: "/pricing",
+ url_query: "?ref=hn",
+ referrer_path: "/post",
+ referrer_domain: "news.ycombinator.com",
+ page_title: "Pricing",
+ event_type: "1",
+ event_name: "",
+ distinct_id: "user-7",
+ created_at: "2024-03-15 10:00:00",
+ });
+ });
+
+ it("ignores columns it does not know about", async () => {
+ await runImport("created_at,session_id,internal_id,tenant\n2024-03-15 10:00:00,sess-1,99,acme\n");
+
+ expect(events()[0]).not.toHaveProperty("internal_id");
+ expect(events()[0]).not.toHaveProperty("tenant");
+ expect(events()[0]).toMatchObject({ session_id: "sess-1", created_at: "2024-03-15 10:00:00" });
+ });
+
+ it("drops rows with no created_at", async () => {
+ const sent = await runImport("session_id,created_at\nsess-1,\nsess-2,2024-03-15 10:00:00\nsess-3,\n");
+
+ expect(sent[0].events.map(e => e.session_id)).toEqual(["sess-2"]);
+ });
+
+ it("drops every row when the headers do not match the platform at all", async () => {
+ const sent = await runImport("timestamp,page,visitor\n2024-03-15 10:00:00,/,v1\n");
+
+ expect(sent).toEqual([{ events: [], isLastBatch: true }]);
+ });
+});
+
+describe("simple analytics rows", () => {
+ it("maps every recognised column onto the wire shape", async () => {
+ await runImport(SA_HEADER + SA_ROW, { platform: "simple_analytics" });
+
+ expect(events()[0]).toEqual({
+ added_iso: "2024-03-15T10:00:00.000Z",
+ country_code: "US",
+ datapoint: "pageview",
+ document_referrer: "https://news.ycombinator.com/",
+ hostname: "example.com",
+ lang_language: "en",
+ lang_region: "US",
+ path: "/pricing",
+ query: "?ref=hn",
+ screen_height: "1080",
+ screen_width: "1920",
+ session_id: "sess-1",
+ user_agent: "Mozilla/5.0",
+ uuid: "uuid-1",
+ });
+ });
+
+ it("drops rows with no added_iso", async () => {
+ const sent = await runImport("added_iso,uuid\n,uuid-1\n2024-03-15T10:00:00Z,uuid-2\n", {
+ platform: "simple_analytics",
+ });
+
+ expect(sent[0].events.map(e => e.uuid)).toEqual(["uuid-2"]);
+ });
+
+ it("accepts ISO timestamps with an offset as well as Z", async () => {
+ const sent = await runImport("added_iso,uuid\n2024-03-15T10:00:00+02:00,offset\n2024-03-15T10:00:00Z,zulu\n", {
+ platform: "simple_analytics",
+ });
+
+ expect(sent[0].events.map(e => e.uuid)).toEqual(["offset", "zulu"]);
+ });
+
+ it("treats any platform other than umami as simple analytics", async () => {
+ await runImport(SA_HEADER + SA_ROW, { platform: "plausible" });
+
+ expect(events()[0]).toMatchObject({ added_iso: "2024-03-15T10:00:00.000Z", uuid: "uuid-1" });
+ });
+});
+
+describe("date range", () => {
+ it("keeps rows on the boundary days and drops rows outside them", async () => {
+ const sent = await runImport(
+ "session_id,created_at\n" +
+ "before,2024-02-29 23:59:59\n" +
+ "first,2024-03-01 00:00:00\n" +
+ "last,2024-03-31 23:59:59\n" +
+ "after,2024-04-01 00:00:00\n",
+ { earliest: "2024-03-01", latest: "2024-03-31" }
+ );
+
+ expect(sent[0].events.map(e => e.session_id)).toEqual(["first", "last"]);
+ });
+
+ it("drops rows whose timestamp matches neither the umami nor the ISO shape", async () => {
+ const sent = await runImport(
+ "session_id,created_at\n" +
+ "slash,15/03/2024 10:00:00\n" +
+ "spaced-iso,2024-03-15 10:00:00.123\n" +
+ "ok,2024-03-15 10:00:00\n"
+ );
+
+ // Note: a fractional-second Umami timestamp matches neither
+ // "yyyy-MM-dd HH:mm:ss" nor Luxon's ISO parser (which needs the T), so it
+ // is silently discarded.
+ expect(sent[0].events.map(e => e.session_id)).toEqual(["ok"]);
+ });
+
+ it("uploads nothing at all when the constructor gets an unparseable range", async () => {
+ const parser = new CsvParser(SITE_ID, IMPORT_ID, "umami", "01-01-2024", "2024-12-31");
+ parser.startImport((UMAMI_HEADER + UMAMI_ROW) as unknown as File);
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(authedFetch).not.toHaveBeenCalled();
+ });
+
+ it("uploads nothing after cancel()", async () => {
+ const parser = new CsvParser(SITE_ID, IMPORT_ID, "umami", "2024-01-01", "2024-12-31");
+ parser.cancel();
+ parser.startImport((UMAMI_HEADER + UMAMI_ROW) as unknown as File);
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(authedFetch).not.toHaveBeenCalled();
+ });
+});
+
+describe("malformed and awkward csv", () => {
+ it("keeps commas, escaped quotes and newlines inside quoted fields", async () => {
+ await runImport(
+ "session_id,page_title,created_at\n" +
+ 'sess-1,"Pricing, Plans and ""Add-ons""\nsecond line",2024-03-15 10:00:00\n'
+ );
+
+ expect(events()[0].page_title).toBe('Pricing, Plans and "Add-ons"\nsecond line');
+ });
+
+ it("strips a UTF-8 byte order mark from the first header", async () => {
+ await runImport("ο»Ώsession_id,created_at\nsess-1,2024-03-15 10:00:00\n");
+
+ expect(events()).toHaveLength(1);
+ expect(events()[0].session_id).toBe("sess-1");
+ });
+
+ it("handles CRLF line endings", async () => {
+ await runImport("session_id,created_at\r\nsess-1,2024-03-15 10:00:00\r\n");
+
+ expect(events()[0]).toMatchObject({ session_id: "sess-1", created_at: "2024-03-15 10:00:00" });
+ });
+
+ it("skips blank and whitespace-only lines", async () => {
+ const sent = await runImport(
+ "session_id,created_at\n\nsess-1,2024-03-15 10:00:00\n \n\nsess-2,2024-03-16 10:00:00\n"
+ );
+
+ expect(sent[0].events.map(e => e.session_id)).toEqual(["sess-1", "sess-2"]);
+ });
+
+ it("tolerates rows with fewer columns than the header", async () => {
+ const sent = await runImport(
+ "session_id,hostname,created_at\nsess-1,example.com\nsess-2,example.com,2024-03-15 10:00:00\n"
+ );
+
+ // The short row has no created_at, so it is dropped rather than uploaded
+ // with a missing timestamp.
+ expect(sent[0].events.map(e => e.session_id)).toEqual(["sess-2"]);
+ });
+
+ it("tolerates rows with more columns than the header", async () => {
+ await runImport("session_id,created_at\nsess-1,2024-03-15 10:00:00,extra,more\n");
+
+ expect(events()[0]).toMatchObject({ session_id: "sess-1", created_at: "2024-03-15 10:00:00" });
+ });
+
+ it("uploads nothing for a completely empty input", async () => {
+ const sent = await runImport("");
+
+ expect(sent).toEqual([{ events: [], isLastBatch: true }]);
+ });
+});
+
+describe("upload failures", () => {
+ it("finalises the import even though the data chunk failed to upload", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ authedFetch.mockRejectedValue(new Error("network down"));
+
+ const sent = await runImport(UMAMI_HEADER + UMAMI_ROW);
+
+ // Current behaviour, and a bug: Papa does not await the async chunk
+ // callback, so `complete` runs β€” and marks the import finished β€” before the
+ // rejected upload has had a chance to set `cancelled`.
+ expect(sent.map(u => ({ n: u.events.length, last: u.isLastBatch }))).toEqual([
+ { n: 1, last: false },
+ { n: 0, last: true },
+ ]);
+
+ vi.restoreAllMocks();
+ });
+});
diff --git a/client/src/lib/import/plausibleParser.test.ts b/client/src/lib/import/plausibleParser.test.ts
new file mode 100644
index 000000000..0c4764f4b
--- /dev/null
+++ b/client/src/lib/import/plausibleParser.test.ts
@@ -0,0 +1,517 @@
+import JSZip from "jszip";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const authedFetch = vi.hoisted(() => vi.fn());
+vi.mock("@/api/utils", () => ({ authedFetch }));
+
+import { PlausibleCsvParser } from "./plausibleParser";
+
+// ---------------------------------------------------------------------------
+// Harness
+//
+// Only the class is exported, so every helper (file identification, dimension
+// normalisation, session synthesis, chunking) is exercised through a real ZIP
+// fed to startImport, with the upload seam mocked. JSZip accepts a Uint8Array,
+// so no browser File is needed.
+// ---------------------------------------------------------------------------
+
+const SITE_ID = 7;
+const IMPORT_ID = "import-1";
+
+type Csvs = Record<string, string>;
+
+interface Upload {
+ events: SyntheticEvent[];
+ isLastBatch: boolean;
+}
+
+interface SyntheticEvent {
+ timestamp: string;
+ session_id: string;
+ user_id: string;
+ hostname: string;
+ pathname: string;
+ querystring: string;
+ referrer: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ device_type: string;
+ country: string;
+ region: string;
+ city: string;
+ type: string;
+ event_name: string;
+ props: string;
+}
+
+async function zipOf(files: Csvs): Promise<File> {
+ const zip = new JSZip();
+ for (const [name, content] of Object.entries(files)) zip.file(name, content);
+ const bytes = await zip.generateAsync({ type: "uint8array" });
+ return bytes as unknown as File;
+}
+
+async function runImport(
+ files: Csvs,
+ range: { earliest?: string; latest?: string } = {}
+): Promise<{ uploads: Upload[]; events: SyntheticEvent[] }> {
+ // Recorded calls, but not the mock implementation β€” a test may have armed a
+ // rejection before calling in.
+ authedFetch.mockClear();
+ const parser = new PlausibleCsvParser(
+ SITE_ID,
+ IMPORT_ID,
+ range.earliest ?? "2024-01-01",
+ range.latest ?? "2024-12-31"
+ );
+ await parser.startImport(await zipOf(files));
+ return { uploads: uploads(), events: uploads().flatMap(u => u.events) };
+}
+
+function uploads(): Upload[] {
+ return authedFetch.mock.calls.map(call => (call[2] as { data: Upload }).data);
+}
+
+// A two-page day with no visitors.csv. The pages totals alone (4 pageviews
+// across 3 visits) size the session pool, which makes every downstream number
+// in these tests hand-checkable.
+const BASIC_PAGES =
+ "date,page,hostname,visitors,pageviews,visits\n" +
+ "2024-03-01,/,example.com,3,3,2\n" +
+ "2024-03-01,/about,example.com,1,1,1\n";
+
+beforeEach(() => {
+ authedFetch.mockReset();
+ authedFetch.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("upload envelope", () => {
+ it("posts each chunk to the import's events endpoint and closes with an empty final batch", async () => {
+ await runImport({ "pages.csv": BASIC_PAGES });
+
+ expect(authedFetch).toHaveBeenCalledTimes(2);
+ expect(authedFetch.mock.calls[0][0]).toBe(`/sites/${SITE_ID}/imports/${IMPORT_ID}/events`);
+ expect(authedFetch.mock.calls[0][2]).toMatchObject({ method: "POST" });
+ expect(uploads().map(u => ({ n: u.events.length, last: u.isLastBatch }))).toEqual([
+ { n: 4, last: false },
+ { n: 0, last: true },
+ ]);
+ });
+});
+
+describe("file identification", () => {
+ it("finalises without events when the zip has no pages.csv", async () => {
+ const { uploads } = await runImport({
+ "browsers.csv": "date,browser,browser_version,visitors,pageviews\n2024-03-01,Chrome,120,5,5\n",
+ });
+
+ expect(uploads).toEqual([{ events: [], isLastBatch: true }]);
+ });
+
+ it("finalises without events when pages.csv has a header but no rows", async () => {
+ const { uploads } = await runImport({ "pages.csv": "date,page,hostname,visitors,pageviews,visits\n" });
+
+ expect(uploads).toEqual([{ events: [], isLastBatch: true }]);
+ });
+
+ it("ignores non-csv entries and csvs with unrecognised headers", async () => {
+ const { events } = await runImport({
+ "README.txt": "not a csv at all",
+ "mystery.csv": "alpha,beta\n1,2\n",
+ "nested/pages.csv": BASIC_PAGES,
+ });
+
+ expect(events).toHaveLength(4);
+ });
+});
+
+describe("pageview synthesis", () => {
+ it("spreads pageviews over a session pool sized by the pages totals", async () => {
+ const { events } = await runImport({ "pages.csv": BASIC_PAGES });
+
+ // 3 visits => 3 sessions, starting at even thirds of the day. 4 pageviews
+ // are dealt round-robin, so the fourth lands back on the first session,
+ // one page-gap (30s) after its first pageview.
+ expect(events.map(e => ({ timestamp: e.timestamp, pathname: e.pathname }))).toEqual([
+ { timestamp: "2024-03-01 00:00:00", pathname: "/" },
+ { timestamp: "2024-03-01 08:00:00", pathname: "/" },
+ { timestamp: "2024-03-01 16:00:00", pathname: "/" },
+ { timestamp: "2024-03-01 00:00:30", pathname: "/about" },
+ ]);
+ expect(new Set(events.map(e => e.session_id)).size).toBe(3);
+ expect(events[0].session_id).toBe(events[3].session_id);
+ expect(events[0].user_id).toBe(events[3].user_id);
+ });
+
+ it("stamps every pageview with type pageview, no event name and empty props", async () => {
+ const { events } = await runImport({ "pages.csv": BASIC_PAGES });
+
+ expect(events.every(e => e.type === "pageview" && e.event_name === "" && e.props === "{}")).toBe(true);
+ });
+
+ it("takes hostname and pathname from the page row, defaulting a blank page to /", async () => {
+ const { events } = await runImport({
+ "pages.csv": "date,page,hostname,visitors,pageviews,visits\n2024-03-01,,blog.example.com,1,1,1\n",
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ hostname: "blog.example.com", pathname: "/" });
+ });
+
+ it("skips rows with no date, no pageviews or a non-numeric pageview count", async () => {
+ const { events } = await runImport({
+ "pages.csv":
+ "date,page,hostname,visitors,pageviews,visits\n" +
+ ",/orphan,example.com,1,5,1\n" +
+ "2024-03-01,/zero,example.com,0,0,1\n" +
+ "2024-03-01,/junk,example.com,1,abc,1\n" +
+ "2024-03-01,/real,example.com,1,1,1\n",
+ });
+
+ expect(events.map(e => e.pathname)).toEqual(["/real"]);
+ });
+
+ it("gives bounced sessions exactly one pageview when visitors.csv reports bounces", async () => {
+ const { events } = await runImport({
+ "pages.csv":
+ "date,page,hostname,visitors,pageviews,visits\n" +
+ "2024-03-01,/,example.com,2,3,2\n" +
+ "2024-03-01,/about,example.com,1,1,1\n",
+ "visitors.csv": "date,visitors,pageviews,bounces,visits,visit_duration\n2024-03-01,2,4,1,2,120\n",
+ });
+
+ // visitors.csv wins over the pages totals: 2 visits => 2 sessions, 1 of
+ // which bounced and therefore gets a single pageview.
+ const perSession = new Map<string, number>();
+ for (const e of events) perSession.set(e.session_id, (perSession.get(e.session_id) ?? 0) + 1);
+ expect([...perSession.values()].sort()).toEqual([1, 3]);
+ expect(events).toHaveLength(4);
+ });
+
+ it("is deterministic β€” the same zip twice yields byte-identical events", async () => {
+ const files = {
+ "pages.csv": BASIC_PAGES,
+ "browsers.csv":
+ "date,browser,browser_version,visitors,pageviews\n2024-03-01,Chrome,120,2,2\n2024-03-01,Firefox,124,1,1\n",
+ "locations.csv":
+ "date,country,region,city,visitors,pageviews\n2024-03-01,US,US-CA,5391959,2,2\n2024-03-01,DE,DE-BE,2950159,1,1\n",
+ };
+
+ const first = await runImport(files);
+ const second = await runImport(files);
+
+ expect(second.events).toEqual(first.events);
+ });
+
+ it("assigns pages by entry weight when entry_pages.csv is present", async () => {
+ const withoutEntryPages = await runImport({ "pages.csv": BASIC_PAGES });
+ const withEntryPages = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "entry_pages.csv": "date,entry_page,visitors,entrances\n2024-03-01,/about,50,50\n2024-03-01,/,1,1\n",
+ });
+
+ // Same events, but /about is dealt first so it starts a session instead of
+ // continuing one.
+ expect(withEntryPages.events).toHaveLength(4);
+ expect(withEntryPages.events.map(e => e.pathname)).toEqual(["/about", "/", "/", "/"]);
+ expect(withoutEntryPages.events.map(e => e.pathname)).toEqual(["/", "/", "/", "/about"]);
+ expect(withEntryPages.events[0].timestamp).toBe("2024-03-01 00:00:00");
+ });
+});
+
+describe("date range", () => {
+ it("drops dates outside the allowed window, inclusive of both ends", async () => {
+ const { events } = await runImport(
+ {
+ "pages.csv":
+ "date,page,hostname,visitors,pageviews,visits\n" +
+ "2024-02-28,/early,example.com,1,1,1\n" +
+ "2024-03-01,/first,example.com,1,1,1\n" +
+ "2024-03-02,/last,example.com,1,1,1\n" +
+ "2024-03-03,/late,example.com,1,1,1\n",
+ },
+ { earliest: "2024-03-01", latest: "2024-03-02" }
+ );
+
+ expect(events.map(e => e.pathname)).toEqual(["/first", "/last"]);
+ });
+
+ it("drops rows whose date is not yyyy-MM-dd", async () => {
+ const { events } = await runImport({
+ "pages.csv":
+ "date,page,hostname,visitors,pageviews,visits\n" +
+ "03/01/2024,/us-format,example.com,1,1,1\n" +
+ "2024-03-01,/iso,example.com,1,1,1\n",
+ });
+
+ expect(events.map(e => e.pathname)).toEqual(["/iso"]);
+ });
+
+ it("uploads nothing at all when the constructor gets an unparseable range", async () => {
+ const parser = new PlausibleCsvParser(SITE_ID, IMPORT_ID, "not-a-date", "2024-12-31");
+ await parser.startImport(await zipOf({ "pages.csv": BASIC_PAGES }));
+
+ expect(authedFetch).not.toHaveBeenCalled();
+ });
+
+ it("uploads nothing after cancel()", async () => {
+ const parser = new PlausibleCsvParser(SITE_ID, IMPORT_ID, "2024-01-01", "2024-12-31");
+ parser.cancel();
+ await parser.startImport(await zipOf({ "pages.csv": BASIC_PAGES }));
+
+ expect(authedFetch).not.toHaveBeenCalled();
+ });
+});
+
+describe("dimension normalisation", () => {
+ const single = (extra: Csvs) => ({
+ "pages.csv": "date,page,hostname,visitors,pageviews,visits\n2024-03-01,/,example.com,1,1,1\n",
+ ...extra,
+ });
+
+ it("maps Plausible's browser, os and device names onto Rybbit's", async () => {
+ const { events } = await runImport(
+ single({
+ "browsers.csv": "date,browser,browser_version,visitors,pageviews\n2024-03-01,Microsoft Edge,120.0,1,1\n",
+ "operating_systems.csv":
+ "date,operating_system,operating_system_version,visitors,pageviews\n2024-03-01,GNU/Linux,6.5,1,1\n",
+ "devices.csv": "date,device,visitors,pageviews\n2024-03-01,laptop,1,1\n",
+ })
+ );
+
+ expect(events[0]).toMatchObject({
+ browser: "Edge",
+ browser_version: "120.0",
+ operating_system: "Linux",
+ operating_system_version: "6.5",
+ device_type: "Desktop",
+ });
+ });
+
+ it.each([
+ ["Microsoft Edge", "Edge"],
+ ["Samsung Browser", "Samsung Internet"],
+ ["Yandex Browser", "Yandex"],
+ ["MICROSOFT EDGE", "Edge"],
+ ["Firefox", "Firefox"],
+ ["", ""],
+ ])("normalises browser %s to %s", async (input, expected) => {
+ const { events } = await runImport(
+ single({ "browsers.csv": `date,browser,browser_version,visitors,pageviews\n2024-03-01,${input},1.0,1,1\n` })
+ );
+ expect(events[0].browser).toBe(expected);
+ });
+
+ it.each([
+ ["GNU/Linux", "Linux"],
+ ["Ubuntu", "Linux"],
+ ["Mac", "macOS"],
+ ["Mac OS X", "macOS"],
+ ["iOS", "iOS"],
+ ["iPadOS", "iOS"],
+ ["Android", "Android"],
+ ["Windows", "Windows"],
+ ["ChromeOS", "Chrome OS"],
+ ["Chrome OS", "Chrome OS"],
+ ["FreeBSD", "FreeBSD"],
+ ])("normalises operating system %s to %s", async (input, expected) => {
+ const { events } = await runImport(
+ single({
+ "operating_systems.csv": `date,operating_system,operating_system_version,visitors,pageviews\n2024-03-01,${input},1,1,1\n`,
+ })
+ );
+ expect(events[0].operating_system).toBe(expected);
+ });
+
+ it.each([
+ ["desktop", "Desktop"],
+ ["laptop", "Desktop"],
+ ["Desktop", "Desktop"],
+ ["mobile", "Mobile"],
+ ["tablet", "Mobile"],
+ ["wearable", "wearable"],
+ ])("normalises device %s to %s", async (input, expected) => {
+ const { events } = await runImport(
+ single({ "devices.csv": `date,device,visitors,pageviews\n2024-03-01,${input},1,1\n` })
+ );
+ expect(events[0].device_type).toBe(expected);
+ });
+
+ it("keeps country and region but drops Plausible's numeric city id", async () => {
+ const { events } = await runImport(
+ single({ "locations.csv": "date,country,region,city,visitors,pageviews\n2024-03-01,US,US-CA,5391959,1,1\n" })
+ );
+
+ expect(events[0]).toMatchObject({ country: "US", region: "US-CA", city: "" });
+ });
+
+ it("leaves every dimension blank when the zip carries only pages.csv", async () => {
+ const { events } = await runImport(single({}));
+
+ expect(events[0]).toMatchObject({
+ browser: "",
+ browser_version: "",
+ operating_system: "",
+ operating_system_version: "",
+ device_type: "",
+ country: "",
+ region: "",
+ city: "",
+ referrer: "",
+ querystring: "",
+ });
+ });
+});
+
+describe("referrers and utm parameters", () => {
+ const withSource = async (row: string) => {
+ const { events } = await runImport({
+ "pages.csv": "date,page,hostname,visitors,pageviews,visits\n2024-03-01,/,example.com,1,1,1\n",
+ "sources.csv":
+ "date,source,referrer,utm_source,utm_medium,utm_campaign,utm_content,utm_term,visitors,pageviews\n" + row,
+ });
+ return events[0];
+ };
+
+ it("promotes a bare referrer host to https", async () => {
+ const event = await withSource("2024-03-01,Google,google.com/search,,,,,,1,1\n");
+ expect(event.referrer).toBe("https://google.com/search");
+ });
+
+ it("falls back to the source when there is no referrer", async () => {
+ expect((await withSource("2024-03-01,t.co,,,,,,,1,1\n")).referrer).toBe("https://t.co");
+ });
+
+ it("drops friendly source names that cannot become urls", async () => {
+ expect((await withSource("2024-03-01,Brave,,,,,,,1,1\n")).referrer).toBe("");
+ expect((await withSource("2024-03-01,Direct / None,,,,,,,1,1\n")).referrer).toBe("https://Direct / None");
+ });
+
+ it("keeps a value that already has a scheme", async () => {
+ expect((await withSource("2024-03-01,android-app://com.linkedin.android,,,,,,,1,1\n")).referrer).toBe(
+ "android-app://com.linkedin.android"
+ );
+ });
+
+ it("rebuilds a querystring from the utm columns in a fixed order", async () => {
+ const event = await withSource("2024-03-01,newsletter,,spring,email,launch,banner,shoes,1,1\n");
+
+ expect(event.querystring).toBe(
+ "?utm_source=spring&utm_medium=email&utm_campaign=launch&utm_content=banner&utm_term=shoes"
+ );
+ });
+
+ it("omits empty utm columns and url-encodes the rest", async () => {
+ const event = await withSource("2024-03-01,newsletter,,spring sale,,,,,1,1\n");
+
+ expect(event.querystring).toBe("?utm_source=spring+sale");
+ });
+
+ it("leaves the querystring empty when no utm columns are set", async () => {
+ expect((await withSource("2024-03-01,Google,google.com,,,,,,1,1\n")).querystring).toBe("");
+ });
+});
+
+describe("custom events", () => {
+ it("attaches custom events to the day's sessions, spread across the day", async () => {
+ const { events } = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "custom_events.csv": "date,name,visitors,events,path,link_url\n2024-03-01,Signup,2,2,/signup,\n",
+ });
+
+ const custom = events.filter(e => e.type === "custom_event");
+ expect(custom).toHaveLength(2);
+ expect(
+ custom.map(e => ({ timestamp: e.timestamp, event_name: e.event_name, pathname: e.pathname, props: e.props }))
+ ).toEqual([
+ { timestamp: "2024-03-01 00:00:00", event_name: "Signup", pathname: "/signup", props: "{}" },
+ { timestamp: "2024-03-01 12:00:00", event_name: "Signup", pathname: "/signup", props: "{}" },
+ ]);
+
+ // They reuse pageview sessions, so the day's user ids do not multiply.
+ const pageviewSessions = new Set(events.filter(e => e.type === "pageview").map(e => e.session_id));
+ expect(custom.every(e => pageviewSessions.has(e.session_id))).toBe(true);
+ });
+
+ it("carries link_url through as a url prop", async () => {
+ const { events } = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "custom_events.csv":
+ "date,name,visitors,events,path,link_url\n2024-03-01,Outbound Link: Click,1,1,/,https://x.com/rybbit\n",
+ });
+
+ expect(events.filter(e => e.type === "custom_event")[0].props).toBe('{"url":"https://x.com/rybbit"}');
+ });
+
+ it("uses the session hostname rather than a per-row one", async () => {
+ const { events } = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "custom_events.csv": "date,name,visitors,events,path,link_url\n2024-03-01,Signup,1,1,/signup,\n",
+ });
+
+ expect(events.filter(e => e.type === "custom_event")[0].hostname).toBe("example.com");
+ });
+
+ it("defaults a blank path to /", async () => {
+ const { events } = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "custom_events.csv": "date,name,visitors,events,path,link_url\n2024-03-01,Signup,1,1,,\n",
+ });
+
+ expect(events.filter(e => e.type === "custom_event")[0].pathname).toBe("/");
+ });
+
+ it("skips rows with no name, no events or a date that has no pageviews", async () => {
+ const { events } = await runImport({
+ "pages.csv": BASIC_PAGES,
+ "custom_events.csv":
+ "date,name,visitors,events,path,link_url\n" +
+ "2024-03-01,,1,5,/anon,\n" +
+ "2024-03-01,ZeroEvents,1,0,/zero,\n" +
+ "2024-03-09,OtherDay,1,3,/other,\n" +
+ "2024-03-01,Kept,1,1,/kept,\n",
+ });
+
+ expect(events.filter(e => e.type === "custom_event").map(e => e.pathname)).toEqual(["/kept"]);
+ });
+});
+
+describe("chunking and timestamp clamping", () => {
+ it("uploads in 5000-event chunks and clamps timestamps to the end of the day", async () => {
+ const { uploads, events } = await runImport({
+ "pages.csv": "date,page,hostname,visitors,pageviews,visits\n2024-03-01,/,example.com,1,12000,1\n",
+ });
+
+ expect(uploads.map(u => ({ n: u.events.length, last: u.isLastBatch }))).toEqual([
+ { n: 5000, last: false },
+ { n: 5000, last: false },
+ { n: 2000, last: false },
+ { n: 0, last: true },
+ ]);
+
+ // One session, 30s between pages: everything past 23:59:59 is pinned there
+ // rather than spilling into the next day.
+ expect(events[0].timestamp).toBe("2024-03-01 00:00:00");
+ expect(events[2879].timestamp).toBe("2024-03-01 23:59:30");
+ expect(events[2880].timestamp).toBe("2024-03-01 23:59:59");
+ expect(events.at(-1)!.timestamp).toBe("2024-03-01 23:59:59");
+ });
+});
+
+describe("upload failures", () => {
+ it("swallows the error and still attempts to finalise the import", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ authedFetch.mockRejectedValue(new Error("network down"));
+
+ await expect(runImport({ "pages.csv": BASIC_PAGES })).resolves.toBeDefined();
+
+ expect(authedFetch).toHaveBeenCalledTimes(2);
+ expect(uploads()[1]).toEqual({ events: [], isLastBatch: true });
+ });
+});
diff --git a/client/src/lib/ipValidation.test.ts b/client/src/lib/ipValidation.test.ts
new file mode 100644
index 000000000..33690eadc
--- /dev/null
+++ b/client/src/lib/ipValidation.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "vitest";
+import { validateIPPattern } from "./ipValidation";
+
+const valid = (pattern: string) => expect(validateIPPattern(pattern)).toEqual({ valid: true });
+const invalid = (pattern: string, error: string) => expect(validateIPPattern(pattern)).toEqual({ valid: false, error });
+
+describe("empty input", () => {
+ it("treats blank patterns as valid so they can be filtered out later", () => {
+ valid("");
+ valid(" ");
+ valid("\t\n");
+ });
+});
+
+describe("single addresses", () => {
+ it.each(["192.168.1.1", "0.0.0.0", "255.255.255.255", "8.8.8.8"])("accepts the IPv4 address %s", valid);
+
+ it.each(["::1", "::", "2001:db8::1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", "fe80::1", "::ffff:192.168.1.1"])(
+ "accepts the IPv6 address %s",
+ valid
+ );
+
+ it("rejects out-of-range octets", () => {
+ invalid("999.1.1.1", "Invalid IP address format");
+ invalid("256.0.0.1", "Invalid IP address format");
+ });
+
+ it("rejects incomplete IPv4 addresses", () => {
+ invalid("192.168.1", "Invalid IP address format");
+ invalid("192.168.1.1.1", "Invalid IP address format");
+ });
+
+ it("rejects text that is not an address", () => {
+ invalid("abc", "Invalid IP address format");
+ invalid("localhost", "Invalid IP address format");
+ invalid("example.com", "Invalid IP address format");
+ });
+
+ it("trims surrounding whitespace before validating", () => {
+ valid(" 192.168.1.1 ");
+ valid("\t2001:db8::1\n");
+ });
+});
+
+describe("CIDR notation", () => {
+ it.each(["192.168.1.0/24", "10.0.0.0/8", "0.0.0.0/0", "192.168.1.1/32"])("accepts the IPv4 CIDR %s", valid);
+
+ it.each(["2001:db8::/32", "::/0", "fe80::/10", "2001:db8::1/128"])("accepts the IPv6 CIDR %s", valid);
+
+ it("rejects a prefix length outside the address family's range", () => {
+ invalid("1.2.3.4/33", "Invalid CIDR notation");
+ invalid("2001:db8::/129", "Invalid CIDR notation");
+ });
+
+ it("rejects malformed CIDR strings", () => {
+ invalid("192.168.1.1/24/8", "Invalid CIDR notation");
+ invalid("192.168.1.1/", "Invalid CIDR notation");
+ invalid("/24", "Invalid CIDR notation");
+ invalid("192.168.1.1/abc", "Invalid CIDR notation");
+ });
+
+ it("checks the slash before the dash, so a slash always means CIDR", () => {
+ invalid("192.168.1.1-192.168.1.10/24", "Invalid CIDR notation");
+ });
+});
+
+describe("range notation", () => {
+ it("accepts an IPv4 range", () => {
+ valid("192.168.1.1-192.168.1.10");
+ valid("10.0.0.1 - 10.0.0.5");
+ });
+
+ it("points IPv6 ranges at CIDR instead", () => {
+ invalid(
+ "2001:db8::1-2001:db8::2",
+ "IPv6 range notation not supported. Use CIDR notation instead (e.g., 2001:db8::/32)"
+ );
+ });
+
+ it("rejects a range with a missing endpoint", () => {
+ invalid("192.168.1.1-", "Invalid range format");
+ invalid("-192.168.1.10", "Invalid range format");
+ });
+
+ it("rejects a range with more than two endpoints", () => {
+ invalid("192.168.1.1-192.168.1.5-192.168.1.10", "Invalid range format");
+ });
+
+ it("rejects a range whose endpoints are not addresses", () => {
+ invalid("hello-world", "Invalid IP addresses in range");
+ invalid("192.168.1.1-notanip", "Invalid IP addresses in range");
+ });
+
+ it("routes any dash-containing text through the range branch", () => {
+ // "not-an-ip" splits into three parts, so it fails on arity rather than on
+ // address parsing.
+ invalid("not-an-ip", "Invalid range format");
+ });
+
+ it("does not check that the range is ordered", () => {
+ valid("192.168.1.10-192.168.1.1");
+ });
+});
diff --git a/client/src/lib/parsers.test.ts b/client/src/lib/parsers.test.ts
new file mode 100644
index 000000000..1162672f0
--- /dev/null
+++ b/client/src/lib/parsers.test.ts
@@ -0,0 +1,187 @@
+import { Filter } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { Time } from "@/components/DateSelector/types";
+import {
+ analyticsParsers,
+ appSumoCallbackParsers,
+ invitationParsers,
+ parseAsFilters,
+ parseAsStatType,
+ parseAsStringArray,
+ parseAsTimeBucket,
+ parseAsTimeMode,
+ parseAsWellKnown,
+} from "./parsers";
+import { timeToUrlParams } from "./time";
+
+describe("parseAsFilters", () => {
+ const chrome: Filter = { parameter: "browser", type: "equals", value: ["Chrome"] };
+
+ it("round-trips a filter through the query string", () => {
+ const serialized = parseAsFilters.serialize([chrome]);
+
+ expect(parseAsFilters.parse(serialized)).toEqual([chrome]);
+ });
+
+ it("accepts every filter type and parameter it declares", () => {
+ const filters: Filter[] = [
+ { parameter: "pathname", type: "contains", value: ["/blog"] },
+ { parameter: "country", type: "not_equals", value: ["US", "CA"] },
+ { parameter: "referrer", type: "is_null", value: [] },
+ { parameter: "lat", type: "greater_than_or_equal", value: [37.7] },
+ { parameter: "utm_source", type: "not_regex", value: ["^spam"] },
+ { parameter: "timezone", type: "ends_with", value: ["Tokyo"] },
+ ];
+
+ expect(parseAsFilters.parse(parseAsFilters.serialize(filters))).toEqual(filters);
+ });
+
+ it("keeps numeric filter values alongside strings", () => {
+ const mixed = [{ parameter: "lon", type: "less_than", value: ["-122", -122.4] }] as unknown as Filter[];
+
+ expect(parseAsFilters.parse(JSON.stringify(mixed))).toEqual(mixed);
+ });
+
+ it("drops entries with an unknown parameter or type instead of failing the whole list", () => {
+ const parsed = parseAsFilters.parse(
+ JSON.stringify([
+ { parameter: "not_a_column", type: "equals", value: ["x"] },
+ { parameter: "browser", type: "sounds_like", value: ["x"] },
+ chrome,
+ ])
+ );
+
+ expect(parsed).toEqual([chrome]);
+ });
+
+ it("drops entries whose value is missing, not an array, or holds non-primitives", () => {
+ const parsed = parseAsFilters.parse(
+ JSON.stringify([
+ { parameter: "browser", type: "equals" },
+ { parameter: "browser", type: "equals", value: "Chrome" },
+ { parameter: "browser", type: "equals", value: [{ nested: true }] },
+ { parameter: "browser", type: "equals", value: [null] },
+ chrome,
+ ])
+ );
+
+ expect(parsed).toEqual([chrome]);
+ });
+
+ it("drops non-object entries", () => {
+ expect(parseAsFilters.parse(JSON.stringify([null, "browser", 7, [], chrome]))).toEqual([chrome]);
+ });
+
+ it("yields an empty list when the payload is valid json but not an array", () => {
+ expect(parseAsFilters.parse('{"parameter":"browser"}')).toEqual([]);
+ expect(parseAsFilters.parse('"browser"')).toEqual([]);
+ expect(parseAsFilters.parse("[]")).toEqual([]);
+ });
+
+ it("yields null when the payload is not json at all", () => {
+ expect(parseAsFilters.parse("browser=Chrome")).toBeNull();
+ expect(parseAsFilters.parse("")).toBeNull();
+ });
+});
+
+describe("parseAsStringArray", () => {
+ it("round-trips a string array", () => {
+ expect(parseAsStringArray.parse(parseAsStringArray.serialize(["a", "b"]))).toEqual(["a", "b"]);
+ });
+
+ it("does not validate its contents β€” anything json-shaped comes back as-is", () => {
+ expect(parseAsStringArray.parse("[1,2]")).toEqual([1, 2]);
+ expect(parseAsStringArray.parse('{"a":1}')).toEqual({ a: 1 });
+ });
+});
+
+describe("enum parsers", () => {
+ it.each(["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour", "day", "week", "month", "year"])(
+ "accepts the %s bucket",
+ value => {
+ expect(parseAsTimeBucket.parse(value)).toBe(value);
+ }
+ );
+
+ it("rejects buckets outside the allowed set, including by case", () => {
+ expect(parseAsTimeBucket.parse("fortnight")).toBeNull();
+ expect(parseAsTimeBucket.parse("Hour")).toBeNull();
+ expect(parseAsTimeBucket.parse("")).toBeNull();
+ });
+
+ it.each(["pageviews", "sessions", "users", "pages_per_session", "bounce_rate", "session_duration"])(
+ "accepts the %s stat",
+ value => {
+ expect(parseAsStatType.parse(value)).toBe(value);
+ }
+ );
+
+ it("rejects unknown stats", () => {
+ expect(parseAsStatType.parse("revenue")).toBeNull();
+ });
+
+ it.each(["day", "range", "week", "month", "year", "all-time", "past-minutes"])("accepts the %s time mode", value => {
+ expect(parseAsTimeMode.parse(value)).toBe(value);
+ });
+
+ it("rejects unknown time modes", () => {
+ expect(parseAsTimeMode.parse("quarter")).toBeNull();
+ });
+
+ it("accepts the dashboard presets and rejects anything else", () => {
+ expect(parseAsWellKnown.parse("last-7-days")).toBe("last-7-days");
+ expect(parseAsWellKnown.parse("today")).toBe("today");
+ expect(parseAsWellKnown.parse("last-3-fortnights")).toBeNull();
+ });
+});
+
+describe("analyticsParsers", () => {
+ it("has a parser for every param timeToUrlParams can write", () => {
+ const times: Time[] = [
+ { mode: "day", day: "2024-03-15" },
+ { mode: "day", day: "2024-03-15", wellKnown: "today" },
+ { mode: "range", startDate: "2024-03-01", endDate: "2024-03-14" },
+ { mode: "range", startDate: "2024-03-01", endDate: "2024-03-14", startTime: "08:00:00", endTime: "17:00:00" },
+ { mode: "week", week: "2024-03-11" },
+ { mode: "month", month: "2024-03-01" },
+ { mode: "year", year: "2024-01-01" },
+ { mode: "past-minutes", pastMinutesStart: 30, pastMinutesEnd: 0 },
+ { mode: "all-time" },
+ ];
+
+ const written = new Set(times.flatMap(time => Object.keys(timeToUrlParams(time))));
+
+ expect(written.size).toBeGreaterThan(0);
+ for (const key of written) {
+ expect(analyticsParsers, key).toHaveProperty(key);
+ }
+ });
+
+ it("parses the display and feature-flag params", () => {
+ expect(analyticsParsers.bucket.parse("day")).toBe("day");
+ expect(analyticsParsers.stat.parse("sessions")).toBe("sessions");
+ expect(analyticsParsers.embed.parse("true")).toBe(true);
+ expect(analyticsParsers.hideSidebar.parse("false")).toBe(false);
+ expect(analyticsParsers.past_minutes_start.parse("30")).toBe(30);
+ expect(analyticsParsers.past_minutes_end.parse("abc")).toBeNull();
+ });
+
+ it("leaves date params as opaque strings", () => {
+ expect(analyticsParsers.day.parse("2024-03-15")).toBe("2024-03-15");
+ expect(analyticsParsers.startDate.parse("whenever")).toBe("whenever");
+ });
+});
+
+describe("callback parsers", () => {
+ it("reads invitation params as strings", () => {
+ expect(invitationParsers.organization.parse("acme")).toBe("acme");
+ expect(invitationParsers.inviterEmail.parse("[email protected]")).toBe("[email protected]");
+ expect(invitationParsers.invitationId.parse("inv_1")).toBe("inv_1");
+ });
+
+ it("reads the AppSumo step as an integer", () => {
+ expect(appSumoCallbackParsers.code.parse("abc123")).toBe("abc123");
+ expect(appSumoCallbackParsers.step.parse("2")).toBe(2);
+ expect(appSumoCallbackParsers.step.parse("two")).toBeNull();
+ });
+});
diff --git a/client/src/lib/subscription/planUtils.test.tsx b/client/src/lib/subscription/planUtils.test.tsx
new file mode 100644
index 000000000..1db27f9a2
--- /dev/null
+++ b/client/src/lib/subscription/planUtils.test.tsx
@@ -0,0 +1,161 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { getStripePrices, STRIPE_TIERS } from "../stripe";
+import { EVENT_TIERS, findPriceForTier, formatDate, formatEventTier, planIncludesReplay } from "./planUtils";
+
+// formatDate parses a bare "yyyy-MM-dd" as UTC midnight and then renders it in
+// the machine's timezone, so the zone has to be pinned for these assertions to
+// mean the same thing everywhere. formatDate builds its formatter per call, so
+// stubbing after import is enough.
+vi.stubEnv("TZ", "UTC");
+
+afterAll(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("formatDate", () => {
+ it("renders a date string in long US format", () => {
+ expect(formatDate("2024-01-15")).toBe("January 15, 2024");
+ expect(formatDate("2024-12-31T23:59:59Z")).toBe("December 31, 2024");
+ });
+
+ it("renders a Date the same way", () => {
+ expect(formatDate(new Date(Date.UTC(2024, 6, 4)))).toBe("July 4, 2024");
+ });
+
+ it("falls back to N/A for missing values", () => {
+ expect(formatDate(null)).toBe("N/A");
+ expect(formatDate(undefined)).toBe("N/A");
+ expect(formatDate("")).toBe("N/A");
+ });
+
+ it("stays in en-US regardless of the viewer's locale", () => {
+ expect(formatDate("2024-03-01")).toBe("March 1, 2024");
+ });
+});
+
+describe("formatEventTier", () => {
+ it("abbreviates millions and thousands", () => {
+ expect(formatEventTier(1_000_000)).toBe("1M");
+ expect(formatEventTier(2_500_000)).toBe("2.5M");
+ expect(formatEventTier(20_000_000)).toBe("20M");
+ expect(formatEventTier(100_000)).toBe("100k");
+ expect(formatEventTier(500_000)).toBe("500k");
+ });
+
+ it("passes string tiers through untouched", () => {
+ expect(formatEventTier("Custom")).toBe("Custom");
+ });
+
+ it("uses the k suffix below a million, even for tiny numbers", () => {
+ expect(formatEventTier(0)).toBe("0k");
+ expect(formatEventTier(1_000)).toBe("1k");
+ });
+});
+
+describe("EVENT_TIERS", () => {
+ it("lists the standard monthly tiers, ending with Custom", () => {
+ expect(EVENT_TIERS.at(-1)).toBe("Custom");
+ expect(EVENT_TIERS.slice(0, -1)).toEqual(STRIPE_TIERS.map(tier => tier.events));
+ expect(EVENT_TIERS).toContain(100_000);
+ });
+
+ it("is ordered smallest to largest", () => {
+ const numeric = EVENT_TIERS.filter((tier): tier is number => typeof tier === "number");
+
+ expect(numeric).toEqual([...numeric].sort((a, b) => a - b));
+ });
+});
+
+describe("findPriceForTier", () => {
+ it("returns null for the custom tier", () => {
+ expect(findPriceForTier("Custom", "month")).toBeNull();
+ expect(findPriceForTier("Custom", "year", "pro")).toBeNull();
+ });
+
+ it("picks the smallest plan that covers the requested event limit", () => {
+ const plan = findPriceForTier(100_000, "month");
+
+ expect(plan).toMatchObject({ name: "standard100k", interval: "month", events: 100_000 });
+ });
+
+ it("rounds up to the next tier when the limit falls between two", () => {
+ expect(findPriceForTier(150_000, "month")).toMatchObject({ name: "standard250k", events: 250_000 });
+ });
+
+ it("selects annual plans for the year interval", () => {
+ const plan = findPriceForTier(100_000, "year");
+
+ expect(plan).toMatchObject({ name: "standard100k-annual", interval: "year" });
+ });
+
+ it("honours the plan type", () => {
+ expect(findPriceForTier(250_000, "month", "basic")).toMatchObject({ name: "basic250k" });
+ expect(findPriceForTier(250_000, "month", "pro")).toMatchObject({ name: "pro250k" });
+ expect(findPriceForTier(250_000, "year", "pro")).toMatchObject({ name: "pro250k-annual" });
+ });
+
+ it("defaults to the standard plan type", () => {
+ expect(findPriceForTier(100_000, "month")).toEqual(findPriceForTier(100_000, "month", "standard"));
+ });
+
+ it("falls back to the largest plan when the limit exceeds every tier", () => {
+ const largest = getStripePrices()
+ .filter(plan => plan.name.startsWith("standard") && !plan.name.includes("-annual"))
+ .at(-1);
+
+ expect(findPriceForTier(999_000_000, "month")).toEqual(largest);
+ });
+
+ it("accepts the limit as a numeric string", () => {
+ expect(findPriceForTier("100000", "month")).toEqual(findPriceForTier(100_000, "month"));
+ });
+
+ it("never returns an annual plan for a monthly interval, or the reverse", () => {
+ for (const tier of [100_000, 1_000_000, 10_000_000]) {
+ expect(findPriceForTier(tier, "month")!.name).not.toContain("-annual");
+ expect(findPriceForTier(tier, "year")!.name).toContain("-annual");
+ }
+ });
+});
+
+describe("planIncludesReplay", () => {
+ it("says no when there is no subscription", () => {
+ expect(planIncludesReplay(null)).toBe(false);
+ expect(planIncludesReplay(undefined)).toBe(false);
+ });
+
+ it("includes every pro plan", () => {
+ expect(planIncludesReplay({ planName: "pro100k" })).toBe(true);
+ expect(planIncludesReplay({ planName: "pro10m-annual" })).toBe(true);
+ });
+
+ it("excludes basic and standard plans", () => {
+ expect(planIncludesReplay({ planName: "basic100k" })).toBe(false);
+ expect(planIncludesReplay({ planName: "standard1m" })).toBe(false);
+ expect(planIncludesReplay({ planName: "free" })).toBe(false);
+ });
+
+ it("includes custom (enterprise) plans", () => {
+ expect(planIncludesReplay({ planName: "custom" })).toBe(true);
+ });
+
+ it("includes AppSumo tiers 4 through 7 only", () => {
+ for (const tier of [4, 5, 6, 7]) {
+ expect(planIncludesReplay({ planName: `appsumo-${tier}` }), `appsumo-${tier}`).toBe(true);
+ }
+ for (const tier of [1, 2, 3, 8]) {
+ expect(planIncludesReplay({ planName: `appsumo-${tier}` }), `appsumo-${tier}`).toBe(false);
+ }
+ });
+
+ it("excludes large pro trials but keeps small ones", () => {
+ expect(planIncludesReplay({ planName: "pro500k", isTrial: true, eventLimit: 500_000 })).toBe(false);
+ expect(planIncludesReplay({ planName: "pro1m", isTrial: true, eventLimit: 1_000_000 })).toBe(false);
+ expect(planIncludesReplay({ planName: "pro100k", isTrial: true, eventLimit: 100_000 })).toBe(true);
+ expect(planIncludesReplay({ planName: "pro500k", isTrial: false, eventLimit: 500_000 })).toBe(true);
+ });
+
+ it("treats a trial with no event limit as small", () => {
+ expect(planIncludesReplay({ planName: "pro100k", isTrial: true })).toBe(true);
+ });
+});
diff --git a/client/src/lib/time.ts b/client/src/lib/time.ts
index 3ab8ace0e..00b53b663 100644
--- a/client/src/lib/time.ts
+++ b/client/src/lib/time.ts
@@ -199,8 +199,10 @@ export const shiftTimeForward = (time: Time, zone: string, now: DateTime = DateT
return toRangeWithTimes(proposedStart, proposedEnd > zonedNow ? zonedNow : proposedEnd);
}
- const startDate = DateTime.fromISO(time.startDate);
- const endDate = DateTime.fromISO(time.endDate);
+ // Parsed in `zone` for the same reason as canGoForward: both are compared against `now`
+ // below, so a system-zone parse shifts the future-edge check by the offset.
+ const startDate = DateTime.fromISO(time.startDate, { zone });
+ const endDate = DateTime.fromISO(time.endDate, { zone });
const daysBetweenStartAndEnd = endDate.diff(startDate, "days").days;
if (daysBetweenStartAndEnd === 0) {
@@ -250,10 +252,14 @@ export const shiftTimeForward = (time: Time, zone: string, now: DateTime = DateT
};
export const canGoForward = (time: Time, zone: string, now: DateTime = DateTime.now()): boolean => {
- const currentDay = now.startOf("day");
+ // Both sides of every comparison below must be resolved in `zone`: the stored dates are
+ // bare `yyyy-MM-dd` strings with no offset, and callers pass the *site's* timezone while
+ // `now` defaults to the browser's. Parsing either side in the system zone silently offsets
+ // the comparison and enables the forward arrow on today for anyone east of the site.
+ const currentDay = now.setZone(zone).startOf("day");
if (time.mode === "day") {
- return !(DateTime.fromISO(time.day).startOf("day") >= currentDay);
+ return !(DateTime.fromISO(time.day, { zone }).startOf("day") >= currentDay);
}
if (time.mode === "range") {
@@ -261,19 +267,19 @@ export const canGoForward = (time: Time, zone: string, now: DateTime = DateTime.
return !(getRangeDateTimeBounds(time, zone).end >= now.setZone(zone));
}
- return !(DateTime.fromISO(time.endDate).startOf("day") >= currentDay);
+ return !(DateTime.fromISO(time.endDate, { zone }).startOf("day") >= currentDay);
}
if (time.mode === "week") {
- return !(DateTime.fromISO(time.week).startOf("week") >= currentDay);
+ return !(DateTime.fromISO(time.week, { zone }).startOf("week") >= currentDay);
}
if (time.mode === "month") {
- return !(DateTime.fromISO(time.month).startOf("month") >= currentDay);
+ return !(DateTime.fromISO(time.month, { zone }).startOf("month") >= currentDay);
}
if (time.mode === "year") {
- return !(DateTime.fromISO(time.year).startOf("year") >= currentDay);
+ return !(DateTime.fromISO(time.year, { zone }).startOf("year") >= currentDay);
}
return false;
diff --git a/client/vitest.config.ts b/client/vitest.config.ts
index fb91caaf8..450a07390 100644
--- a/client/vitest.config.ts
+++ b/client/vitest.config.ts
@@ -1,14 +1,38 @@
import { defineConfig } from "vitest/config";
import path from "path";
-export default defineConfig({
+// Two projects instead of one `environment` because component tests need a DOM
+// while the pure-logic tests do not. `.tsx` tests run in jsdom, `.ts` tests in
+// node. (The server uses `environmentMatchGlobs` for the same split, but that
+// option was removed in Vitest 4 β€” `projects` is its replacement.)
+const shared = {
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
+};
+
+export default defineConfig({
+ ...shared,
test: {
- include: ["src/**/*.test.{ts,tsx}"],
- environment: "node",
+ projects: [
+ {
+ ...shared,
+ test: {
+ name: "node",
+ include: ["src/**/*.test.ts"],
+ environment: "node",
+ },
+ },
+ {
+ ...shared,
+ test: {
+ name: "dom",
+ include: ["src/**/*.test.tsx"],
+ environment: "jsdom",
+ },
+ },
+ ],
},
});
diff --git a/server/src/api/analytics/funnels/funnelSteps.test.ts b/server/src/api/analytics/funnels/funnelSteps.test.ts
new file mode 100644
index 000000000..20d1cb608
--- /dev/null
+++ b/server/src/api/analytics/funnels/funnelSteps.test.ts
@@ -0,0 +1,234 @@
+import { describe, it, expect } from "vitest";
+import { buildFunnelStepCondition, FunnelStep } from "./funnelSteps.js";
+
+describe("buildFunnelStepCondition β€” page steps", () => {
+ it("builds a pageview condition from a literal path", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/pricing" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$')"
+ );
+ });
+
+ it("expands a single wildcard to one path segment", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/blog/*" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/blog/[^/]+$')"
+ );
+ });
+
+ it("expands a double wildcard across path segments", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/docs/**" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/docs/.*$')"
+ );
+ });
+
+ it("matches property filters against url_parameters", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "page",
+ value: "/pricing",
+ propertyFilters: [{ key: "utm_source", value: "google" }],
+ })
+ ).toBe("type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google'");
+ });
+
+ it("anchors an empty value to the empty path", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "" })).toBe("type = 'pageview' AND match(pathname, '^$')");
+ });
+});
+
+describe("buildFunnelStepCondition β€” event steps", () => {
+ it("builds a custom_event condition from the value", () => {
+ expect(buildFunnelStepCondition({ type: "event", value: "signup" })).toBe(
+ "type = 'custom_event' AND event_name = 'signup'"
+ );
+ });
+
+ it("matches property filters against props", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "event",
+ value: "purchase",
+ propertyFilters: [{ key: "plan", value: "pro" }],
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro'");
+ });
+
+ it("compares numeric property filters as floats", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "event",
+ value: "purchase",
+ propertyFilters: [{ key: "amount", value: 10 }],
+ })
+ ).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 10"
+ );
+ });
+
+ it("honours the deprecated single-property fields", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "event",
+ value: "purchase",
+ eventPropertyKey: "plan",
+ eventPropertyValue: "pro",
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro'");
+ });
+
+ it("prefers propertyFilters over the deprecated fields", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "event",
+ value: "purchase",
+ propertyFilters: [{ key: "new", value: "yes" }],
+ eventPropertyKey: "legacy",
+ eventPropertyValue: "no",
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'new') = 'yes'");
+ });
+
+ it("falls back to a custom event match for unknown legacy step types", () => {
+ // Anything that is neither "page" nor an autocapture type is treated as a
+ // custom event name.
+ expect(buildFunnelStepCondition({ type: "legacy_thing" as FunnelStep["type"], value: "signup" })).toBe(
+ "type = 'custom_event' AND event_name = 'signup'"
+ );
+ expect(buildFunnelStepCondition({ type: "" as FunnelStep["type"], value: "signup" })).toBe(
+ "type = 'custom_event' AND event_name = 'signup'"
+ );
+ });
+
+ it("treats 'path' as an event step, since page steps use the 'page' spelling", () => {
+ expect(buildFunnelStepCondition({ type: "path" as FunnelStep["type"], value: "/pricing" })).toBe(
+ "type = 'custom_event' AND event_name = '/pricing'"
+ );
+ });
+
+ it("escapes quotes in the event name", () => {
+ expect(buildFunnelStepCondition({ type: "event", value: "evt'; DROP TABLE events;--" })).toBe(
+ "type = 'custom_event' AND event_name = 'evt\\'; DROP TABLE events;--'"
+ );
+ });
+});
+
+describe("buildFunnelStepCondition β€” autocapture steps", () => {
+ it("uses the step value as the autocapture value pattern", () => {
+ expect(buildFunnelStepCondition({ type: "outbound", value: "https://partner.com/*" })).toBe(
+ "type = 'outbound' AND (match(JSONExtractString(toString(props), 'url'), '^https://partner\\\\.com/.+$'))"
+ );
+ });
+
+ it("matches a button_click step against the text prop", () => {
+ expect(buildFunnelStepCondition({ type: "button_click", value: "Buy now" })).toBe(
+ "type = 'button_click' AND (match(JSONExtractString(toString(props), 'text'), '^Buy now$'))"
+ );
+ });
+
+ it("ORs a form_submit step across all three form props", () => {
+ expect(buildFunnelStepCondition({ type: "form_submit", value: "signup" })).toBe(
+ "type = 'form_submit' AND (match(JSONExtractString(toString(props), 'formName'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formId'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formAction'), '^signup$'))"
+ );
+ });
+
+ it("matches a copy step against the text prop", () => {
+ expect(buildFunnelStepCondition({ type: "copy", value: "coupon-*" })).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^coupon-.+$'))"
+ );
+ });
+
+ it("matches the bare type when the value is empty or whitespace", () => {
+ expect(buildFunnelStepCondition({ type: "outbound", value: "" })).toBe("type = 'outbound'");
+ expect(buildFunnelStepCondition({ type: "copy", value: " " })).toBe("type = 'copy'");
+ });
+
+ it("applies property filters after the value pattern", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "outbound",
+ value: "https://x.com",
+ propertyFilters: [{ key: "target", value: "_blank" }],
+ })
+ ).toBe(
+ "type = 'outbound' AND (match(JSONExtractString(toString(props), 'url'), '^https://x\\\\.com$'))" +
+ " AND JSONExtractString(toString(props), 'target') = '_blank'"
+ );
+ });
+});
+
+describe("buildFunnelStepCondition β€” hostname", () => {
+ it("appends a hostname clause last for page steps", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/pricing", hostname: "app.example.com" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND hostname = 'app.example.com'"
+ );
+ });
+
+ it("appends a hostname clause for event steps", () => {
+ expect(buildFunnelStepCondition({ type: "event", value: "signup", hostname: "app.example.com" })).toBe(
+ "type = 'custom_event' AND event_name = 'signup' AND hostname = 'app.example.com'"
+ );
+ });
+
+ it("appends a hostname clause after autocapture filters", () => {
+ expect(
+ buildFunnelStepCondition({
+ type: "copy",
+ value: "coupon",
+ propertyFilters: [{ key: "page", value: "/x" }],
+ hostname: "app.example.com",
+ })
+ ).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^coupon$'))" +
+ " AND JSONExtractString(toString(props), 'page') = '/x'" +
+ " AND hostname = 'app.example.com'"
+ );
+ });
+
+ it("omits the hostname clause when it is empty", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/pricing", hostname: "" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$')"
+ );
+ });
+
+ it("escapes quotes in the hostname", () => {
+ expect(buildFunnelStepCondition({ type: "page", value: "/x", hostname: "a'; DROP TABLE events;--" })).toBe(
+ "type = 'pageview' AND match(pathname, '^/x$') AND hostname = 'a\\'; DROP TABLE events;--'"
+ );
+ });
+});
+
+describe("buildFunnelStepCondition β€” multi-step sequences", () => {
+ it("builds an independent condition per step, in order", () => {
+ const steps: FunnelStep[] = [
+ { type: "page", value: "/", name: "Landing" },
+ { type: "page", value: "/pricing", name: "Pricing" },
+ { type: "button_click", value: "Start trial", name: "CTA" },
+ { type: "event", value: "signup", name: "Signup", propertyFilters: [{ key: "plan", value: "pro" }] },
+ ];
+
+ expect(steps.map(buildFunnelStepCondition)).toEqual([
+ "type = 'pageview' AND match(pathname, '^/$')",
+ "type = 'pageview' AND match(pathname, '^/pricing$')",
+ "type = 'button_click' AND (match(JSONExtractString(toString(props), 'text'), '^Start trial$'))",
+ "type = 'custom_event' AND event_name = 'signup' AND JSONExtractString(toString(props), 'plan') = 'pro'",
+ ]);
+ });
+
+ it("keeps per-step hostnames independent", () => {
+ const steps: FunnelStep[] = [
+ { type: "page", value: "/a", hostname: "marketing.example.com" },
+ { type: "page", value: "/b" },
+ ];
+
+ expect(steps.map(buildFunnelStepCondition)).toEqual([
+ "type = 'pageview' AND match(pathname, '^/a$') AND hostname = 'marketing.example.com'",
+ "type = 'pageview' AND match(pathname, '^/b$')",
+ ]);
+ });
+
+ it("produces nothing for an empty step list", () => {
+ const steps: FunnelStep[] = [];
+ expect(steps.map(buildFunnelStepCondition)).toEqual([]);
+ });
+});
diff --git a/server/src/api/analytics/goals/goalConditions.test.ts b/server/src/api/analytics/goals/goalConditions.test.ts
new file mode 100644
index 000000000..887792cbf
--- /dev/null
+++ b/server/src/api/analytics/goals/goalConditions.test.ts
@@ -0,0 +1,204 @@
+import { describe, it, expect } from "vitest";
+import { buildGoalCondition } from "./goalConditions.js";
+
+describe("buildGoalCondition β€” path goals", () => {
+ it("builds a pageview condition from a literal path pattern", () => {
+ expect(buildGoalCondition({ goalType: "path", config: { pathPattern: "/checkout/success" } })).toBe(
+ "type = 'pageview' AND match(pathname, '^/checkout/success$')"
+ );
+ });
+
+ it("expands wildcards in the path pattern", () => {
+ expect(buildGoalCondition({ goalType: "path", config: { pathPattern: "/blog/*" } })).toBe(
+ "type = 'pageview' AND match(pathname, '^/blog/[^/]+$')"
+ );
+ expect(buildGoalCondition({ goalType: "path", config: { pathPattern: "/docs/**" } })).toBe(
+ "type = 'pageview' AND match(pathname, '^/docs/.*$')"
+ );
+ });
+
+ it("applies property filters as url_parameters comparisons", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "path",
+ config: { pathPattern: "/pricing", propertyFilters: [{ key: "utm_source", value: "google" }] },
+ })
+ ).toBe("type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google'");
+ });
+
+ it("AND-joins multiple property filters", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "path",
+ config: {
+ pathPattern: "/pricing",
+ propertyFilters: [
+ { key: "utm_source", value: "google" },
+ { key: "utm_medium", value: "cpc" },
+ ],
+ },
+ })
+ ).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google' AND url_parameters['utm_medium'] = 'cpc'"
+ );
+ });
+
+ it("honours the legacy single-property fields", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "path",
+ config: { pathPattern: "/pricing", eventPropertyKey: "utm_source", eventPropertyValue: "google" },
+ })
+ ).toBe("type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google'");
+ });
+
+ it("returns null when the path pattern is missing or empty", () => {
+ expect(buildGoalCondition({ goalType: "path", config: {} })).toBeNull();
+ expect(buildGoalCondition({ goalType: "path", config: { pathPattern: "" } })).toBeNull();
+ });
+
+ it("ignores eventName on a path goal", () => {
+ expect(buildGoalCondition({ goalType: "path", config: { eventName: "signup" } })).toBeNull();
+ });
+
+ it("escapes quotes in the path pattern", () => {
+ expect(buildGoalCondition({ goalType: "path", config: { pathPattern: "/a'b" } })).toBe(
+ "type = 'pageview' AND match(pathname, '^/a\\'b$')"
+ );
+ });
+});
+
+describe("buildGoalCondition β€” event goals", () => {
+ it("builds a custom_event condition from the event name", () => {
+ expect(buildGoalCondition({ goalType: "event", config: { eventName: "signup" } })).toBe(
+ "type = 'custom_event' AND event_name = 'signup'"
+ );
+ });
+
+ it("applies property filters against props", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "event",
+ config: { eventName: "purchase", propertyFilters: [{ key: "plan", value: "pro" }] },
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro'");
+ });
+
+ it("compares numeric property filters as floats", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "event",
+ config: { eventName: "purchase", propertyFilters: [{ key: "amount", value: 99.5 }] },
+ })
+ ).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 99.5"
+ );
+ });
+
+ it("honours the legacy single-property fields", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "event",
+ config: { eventName: "purchase", eventPropertyKey: "plan", eventPropertyValue: "pro" },
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro'");
+ });
+
+ it("prefers propertyFilters over the legacy fields when both are present", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "event",
+ config: {
+ eventName: "purchase",
+ propertyFilters: [{ key: "new", value: "yes" }],
+ eventPropertyKey: "legacy",
+ eventPropertyValue: "no",
+ },
+ })
+ ).toBe("type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'new') = 'yes'");
+ });
+
+ it("returns null when the event name is missing or empty", () => {
+ expect(buildGoalCondition({ goalType: "event", config: {} })).toBeNull();
+ expect(buildGoalCondition({ goalType: "event", config: { eventName: "" } })).toBeNull();
+ });
+
+ it("escapes quotes in the event name", () => {
+ expect(buildGoalCondition({ goalType: "event", config: { eventName: "evt'; DROP TABLE events;--" } })).toBe(
+ "type = 'custom_event' AND event_name = 'evt\\'; DROP TABLE events;--'"
+ );
+ });
+});
+
+describe("buildGoalCondition β€” autocapture goals", () => {
+ it("matches a bare autocapture type when no value pattern is set", () => {
+ expect(buildGoalCondition({ goalType: "outbound", config: {} })).toBe("type = 'outbound'");
+ expect(buildGoalCondition({ goalType: "button_click", config: {} })).toBe("type = 'button_click'");
+ expect(buildGoalCondition({ goalType: "form_submit", config: {} })).toBe("type = 'form_submit'");
+ expect(buildGoalCondition({ goalType: "copy", config: {} })).toBe("type = 'copy'");
+ });
+
+ it("narrows an outbound goal by its url pattern", () => {
+ expect(buildGoalCondition({ goalType: "outbound", config: { valuePattern: "https://partner.com/**" } })).toBe(
+ "type = 'outbound' AND (match(JSONExtractString(toString(props), 'url'), '^https://partner\\\\.com/.*$'))"
+ );
+ });
+
+ it("narrows a button_click goal by its text pattern", () => {
+ expect(buildGoalCondition({ goalType: "button_click", config: { valuePattern: "Buy now" } })).toBe(
+ "type = 'button_click' AND (match(JSONExtractString(toString(props), 'text'), '^Buy now$'))"
+ );
+ });
+
+ it("ORs a form_submit value pattern over all three form props", () => {
+ expect(buildGoalCondition({ goalType: "form_submit", config: { valuePattern: "signup" } })).toBe(
+ "type = 'form_submit' AND (match(JSONExtractString(toString(props), 'formName'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formId'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formAction'), '^signup$'))"
+ );
+ });
+
+ it("applies property filters alongside the value pattern", () => {
+ expect(
+ buildGoalCondition({
+ goalType: "copy",
+ config: { valuePattern: "coupon-*", propertyFilters: [{ key: "page", value: "/pricing" }] },
+ })
+ ).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^coupon-.+$'))" +
+ " AND JSONExtractString(toString(props), 'page') = '/pricing'"
+ );
+ });
+
+ it("ignores pathPattern and eventName on an autocapture goal", () => {
+ expect(buildGoalCondition({ goalType: "outbound", config: { pathPattern: "/x", eventName: "y" } })).toBe(
+ "type = 'outbound'"
+ );
+ });
+});
+
+describe("buildGoalCondition β€” malformed input", () => {
+ it("returns null for an unknown goal type", () => {
+ expect(buildGoalCondition({ goalType: "unknown", config: { pathPattern: "/x" } })).toBeNull();
+ expect(buildGoalCondition({ goalType: "pageview", config: { pathPattern: "/x" } })).toBeNull();
+ });
+
+ it("returns null for an empty goal type", () => {
+ expect(buildGoalCondition({ goalType: "", config: {} })).toBeNull();
+ });
+
+ it("returns null for an entirely empty goal", () => {
+ expect(buildGoalCondition({ goalType: "path", config: {} })).toBeNull();
+ expect(buildGoalCondition({ goalType: "event", config: {} })).toBeNull();
+ });
+
+ it("is case sensitive on the goal type", () => {
+ expect(buildGoalCondition({ goalType: "Path", config: { pathPattern: "/x" } })).toBeNull();
+ expect(buildGoalCondition({ goalType: "EVENT", config: { eventName: "signup" } })).toBeNull();
+ expect(buildGoalCondition({ goalType: "Outbound", config: {} })).toBeNull();
+ });
+
+ it("does not treat 'page' as a path goal (that spelling belongs to funnel steps)", () => {
+ expect(buildGoalCondition({ goalType: "page", config: { pathPattern: "/x" } })).toBeNull();
+ });
+});
diff --git a/server/src/api/analytics/utils/effectiveUserId.test.ts b/server/src/api/analytics/utils/effectiveUserId.test.ts
new file mode 100644
index 000000000..3ef224f0d
--- /dev/null
+++ b/server/src/api/analytics/utils/effectiveUserId.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect } from "vitest";
+import { doesNotMatchUser, EFFECTIVE_SESSION_USER_ID, effectiveUserId, matchesUser } from "./effectiveUserId.js";
+
+describe("effectiveUserId", () => {
+ it("falls back from the identity to the fingerprint with no alias", () => {
+ expect(effectiveUserId()).toBe("COALESCE(NULLIF(identified_user_id, ''), user_id)");
+ });
+
+ it("treats an empty alias as no alias", () => {
+ expect(effectiveUserId("")).toBe("COALESCE(NULLIF(identified_user_id, ''), user_id)");
+ });
+
+ it("prefixes both columns with the table alias", () => {
+ expect(effectiveUserId("e")).toBe("COALESCE(NULLIF(e.identified_user_id, ''), e.user_id)");
+ });
+
+ it("prefixes a multi-character alias", () => {
+ expect(effectiveUserId("events")).toBe("COALESCE(NULLIF(events.identified_user_id, ''), events.user_id)");
+ });
+
+ it("appends exactly one dot, so a caller-supplied dotted alias would double up", () => {
+ // Pinned behavior: the alias is interpolated verbatim before the dot.
+ expect(effectiveUserId("db.events")).toBe("COALESCE(NULLIF(db.events.identified_user_id, ''), db.events.user_id)");
+ });
+
+ it("guards the fallback on empty string, not NULL", () => {
+ // NULLIF(..., '') is what makes a site that never calls identify() collapse
+ // to plain user_id, so the '' literal is load-bearing.
+ expect(effectiveUserId()).toContain("NULLIF(identified_user_id, '')");
+ });
+});
+
+describe("EFFECTIVE_SESSION_USER_ID", () => {
+ it("is the session-grain aggregate form of the same fallback", () => {
+ expect(EFFECTIVE_SESSION_USER_ID).toBe(
+ "COALESCE(NULLIF(anyIf(identified_user_id, identified_user_id != ''), ''), anyLast(user_id))"
+ );
+ });
+
+ it("takes any non-empty identity in the session before falling back", () => {
+ expect(EFFECTIVE_SESSION_USER_ID).toContain("anyIf(identified_user_id, identified_user_id != '')");
+ expect(EFFECTIVE_SESSION_USER_ID).toContain("anyLast(user_id)");
+ });
+
+ it("is a constant, not an alias-aware builder", () => {
+ // It is designed to be used inside a GROUP BY session_id aggregation on a
+ // single unaliased events scan.
+ expect(typeof EFFECTIVE_SESSION_USER_ID).toBe("string");
+ expect(EFFECTIVE_SESSION_USER_ID).not.toContain(".");
+ });
+
+ it("uses the same COALESCE/NULLIF shape as the event-level key", () => {
+ expect(EFFECTIVE_SESSION_USER_ID.startsWith("COALESCE(NULLIF(")).toBe(true);
+ expect(effectiveUserId().startsWith("COALESCE(NULLIF(")).toBe(true);
+ });
+});
+
+describe("matchesUser", () => {
+ it("matches an identified user, or a device only while it is still anonymous", () => {
+ expect(matchesUser("{userId:String}")).toBe(
+ "(identified_user_id = {userId:String} OR (user_id = {userId:String} AND identified_user_id = ''))"
+ );
+ });
+
+ it("treats an empty alias as no alias", () => {
+ expect(matchesUser("{userId:String}", "")).toBe(matchesUser("{userId:String}"));
+ });
+
+ it("prefixes every column reference with the table alias", () => {
+ expect(matchesUser("{userId:String}", "e")).toBe(
+ "(e.identified_user_id = {userId:String} OR (e.user_id = {userId:String} AND e.identified_user_id = ''))"
+ );
+ });
+
+ it("interpolates an escaped literal verbatim", () => {
+ expect(matchesUser("'user123'")).toBe(
+ "(identified_user_id = 'user123' OR (user_id = 'user123' AND identified_user_id = ''))"
+ );
+ });
+
+ it("guards the fingerprint branch so a shared device does not sweep in identified users", () => {
+ // The regression this exists for: several people behind one corporate proxy
+ // share a fingerprint, so an unguarded user_id match would return all of them.
+ const sql = matchesUser("'fp1'");
+ expect(sql).toContain("user_id = 'fp1' AND identified_user_id = ''");
+ expect(sql).not.toMatch(/user_id = 'fp1'\)\s*$/);
+ });
+
+ it("keeps the alias out of the value expression", () => {
+ const sql = matchesUser("{userId:String}", "e");
+ expect(sql).not.toContain("e.{userId:String}");
+ expect(sql.match(/\{userId:String\}/g)?.length).toBe(2);
+ expect(sql.match(/e\./g)?.length).toBe(3);
+ });
+});
+
+describe("doesNotMatchUser", () => {
+ it("is the exact negation of matchesUser", () => {
+ expect(doesNotMatchUser("{userId:String}")).toBe(`NOT ${matchesUser("{userId:String}")}`);
+ });
+
+ it("renders the full predicate with no alias", () => {
+ expect(doesNotMatchUser("{userId:String}")).toBe(
+ "NOT (identified_user_id = {userId:String} OR (user_id = {userId:String} AND identified_user_id = ''))"
+ );
+ });
+
+ it("passes the alias through to matchesUser", () => {
+ expect(doesNotMatchUser("{userId:String}", "e")).toBe(`NOT ${matchesUser("{userId:String}", "e")}`);
+ expect(doesNotMatchUser("{userId:String}", "e")).toBe(
+ "NOT (e.identified_user_id = {userId:String} OR (e.user_id = {userId:String} AND e.identified_user_id = ''))"
+ );
+ });
+
+ it("wraps the whole predicate in parentheses so NOT binds to all of it", () => {
+ const sql = doesNotMatchUser("'user123'");
+ expect(sql.startsWith("NOT (")).toBe(true);
+ expect(sql.endsWith(")")).toBe(true);
+ });
+
+ it("partitions the rows together with matchesUser", () => {
+ // equals/not_equals filters must be exact complements.
+ for (const alias of ["", "e", "events"]) {
+ expect(doesNotMatchUser("{userId:String}", alias)).toBe(`NOT ${matchesUser("{userId:String}", alias)}`);
+ }
+ });
+});
diff --git a/server/src/api/analytics/utils/eventConditions.test.ts b/server/src/api/analytics/utils/eventConditions.test.ts
new file mode 100644
index 000000000..f0228000b
--- /dev/null
+++ b/server/src/api/analytics/utils/eventConditions.test.ts
@@ -0,0 +1,325 @@
+import { describe, it, expect } from "vitest";
+import {
+ AUTOCAPTURE_PATTERN_PROPS,
+ AUTOCAPTURE_TARGET_TYPES,
+ buildAutocaptureCondition,
+ buildEventCondition,
+ buildPageCondition,
+ isAutocaptureTargetType,
+ resolvePropertyFilters,
+} from "./eventConditions.js";
+
+describe("isAutocaptureTargetType", () => {
+ it("accepts every declared autocapture target type", () => {
+ expect(AUTOCAPTURE_TARGET_TYPES).toEqual(["outbound", "button_click", "form_submit", "copy"]);
+ for (const type of AUTOCAPTURE_TARGET_TYPES) {
+ expect(isAutocaptureTargetType(type)).toBe(true);
+ }
+ });
+
+ it("rejects the non-autocapture target types", () => {
+ expect(isAutocaptureTargetType("page")).toBe(false);
+ expect(isAutocaptureTargetType("path")).toBe(false);
+ expect(isAutocaptureTargetType("event")).toBe(false);
+ expect(isAutocaptureTargetType("pageview")).toBe(false);
+ expect(isAutocaptureTargetType("")).toBe(false);
+ });
+
+ it("is case sensitive and does not accept near-misses", () => {
+ expect(isAutocaptureTargetType("Outbound")).toBe(false);
+ expect(isAutocaptureTargetType("outbound ")).toBe(false);
+ expect(isAutocaptureTargetType("buttonclick")).toBe(false);
+ });
+
+ it("declares pattern props for every target type", () => {
+ expect(AUTOCAPTURE_PATTERN_PROPS).toEqual({
+ outbound: ["url"],
+ button_click: ["text"],
+ form_submit: ["formName", "formId", "formAction"],
+ copy: ["text"],
+ });
+ for (const type of AUTOCAPTURE_TARGET_TYPES) {
+ expect(AUTOCAPTURE_PATTERN_PROPS[type].length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe("resolvePropertyFilters", () => {
+ it("returns an empty list when nothing is configured", () => {
+ expect(resolvePropertyFilters({})).toEqual([]);
+ });
+
+ it("prefers the propertyFilters array when present", () => {
+ const filters = [{ key: "plan", value: "pro" }];
+ expect(resolvePropertyFilters({ propertyFilters: filters })).toBe(filters);
+ });
+
+ it("returns an empty propertyFilters array as-is, ignoring the legacy fields", () => {
+ // An empty array is truthy, so it short-circuits the legacy fallback.
+ const filters: { key: string; value: string }[] = [];
+ expect(
+ resolvePropertyFilters({ propertyFilters: filters, eventPropertyKey: "plan", eventPropertyValue: "pro" })
+ ).toBe(filters);
+ });
+
+ it("lifts the legacy single-property fields into a one-element array", () => {
+ expect(resolvePropertyFilters({ eventPropertyKey: "plan", eventPropertyValue: "pro" })).toEqual([
+ { key: "plan", value: "pro" },
+ ]);
+ });
+
+ it("keeps falsy-but-defined legacy values", () => {
+ expect(resolvePropertyFilters({ eventPropertyKey: "count", eventPropertyValue: 0 })).toEqual([
+ { key: "count", value: 0 },
+ ]);
+ expect(resolvePropertyFilters({ eventPropertyKey: "optedIn", eventPropertyValue: false })).toEqual([
+ { key: "optedIn", value: false },
+ ]);
+ expect(resolvePropertyFilters({ eventPropertyKey: "note", eventPropertyValue: "" })).toEqual([
+ { key: "note", value: "" },
+ ]);
+ });
+
+ it("drops a legacy key with no value, and a legacy value with no key", () => {
+ expect(resolvePropertyFilters({ eventPropertyKey: "plan" })).toEqual([]);
+ expect(resolvePropertyFilters({ eventPropertyValue: "pro" })).toEqual([]);
+ expect(resolvePropertyFilters({ eventPropertyKey: "", eventPropertyValue: "pro" })).toEqual([]);
+ });
+});
+
+describe("buildPageCondition", () => {
+ it("matches a literal path with no filters", () => {
+ expect(buildPageCondition("/pricing", [])).toBe("type = 'pageview' AND match(pathname, '^/pricing$')");
+ });
+
+ it("expands a single wildcard to one path segment", () => {
+ expect(buildPageCondition("/blog/*", [])).toBe("type = 'pageview' AND match(pathname, '^/blog/[^/]+$')");
+ });
+
+ it("expands a double wildcard across path segments", () => {
+ expect(buildPageCondition("/docs/**", [])).toBe("type = 'pageview' AND match(pathname, '^/docs/.*$')");
+ });
+
+ it("escapes regex metacharacters in the path pattern", () => {
+ expect(buildPageCondition("/a.b+c", [])).toBe("type = 'pageview' AND match(pathname, '^/a\\\\.b\\\\+c$')");
+ });
+
+ it("matches property filters against url_parameters, not props", () => {
+ expect(buildPageCondition("/pricing", [{ key: "utm_source", value: "google" }])).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google'"
+ );
+ });
+
+ it("AND-joins multiple url parameter filters in order", () => {
+ expect(
+ buildPageCondition("/pricing", [
+ { key: "utm_source", value: "google" },
+ { key: "utm_medium", value: "cpc" },
+ ])
+ ).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['utm_source'] = 'google' AND url_parameters['utm_medium'] = 'cpc'"
+ );
+ });
+
+ it("stringifies non-string url parameter values", () => {
+ // Page targets compare url_parameters (always strings) so numbers and
+ // booleans are String()-ed into quoted literals rather than emitted bare.
+ expect(buildPageCondition("/pricing", [{ key: "n", value: 42 }])).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['n'] = '42'"
+ );
+ expect(buildPageCondition("/pricing", [{ key: "b", value: true }])).toBe(
+ "type = 'pageview' AND match(pathname, '^/pricing$') AND url_parameters['b'] = 'true'"
+ );
+ });
+
+ it("escapes quotes in the path pattern so a pattern cannot break out of the literal", () => {
+ expect(buildPageCondition("/a') OR 1=1--", [])).toBe(
+ "type = 'pageview' AND match(pathname, '^/a\\'\\\\) OR 1=1--$')"
+ );
+ });
+
+ it("escapes quotes in url parameter filter keys and values", () => {
+ expect(buildPageCondition("/x", [{ key: "k'ey", value: "v') OR 1=1--" }])).toBe(
+ "type = 'pageview' AND match(pathname, '^/x$') AND url_parameters['k\\'ey'] = 'v\\') OR 1=1--'"
+ );
+ });
+
+ it("escapes backslashes in filter values", () => {
+ expect(buildPageCondition("/x", [{ key: "p", value: "a\\b" }])).toBe(
+ "type = 'pageview' AND match(pathname, '^/x$') AND url_parameters['p'] = 'a\\\\b'"
+ );
+ });
+
+ it("does not let a user-supplied double-star marker survive into the regex", () => {
+ // The {{DOUBLE_STAR}} sentinel is escaped before substitution, so a literal
+ // one in the pattern stays literal.
+ expect(buildPageCondition("/{{DOUBLE_STAR}}", [])).toBe(
+ "type = 'pageview' AND match(pathname, '^/\\\\{\\\\{DOUBLE_STAR\\\\}\\\\}$')"
+ );
+ });
+});
+
+describe("buildEventCondition", () => {
+ it("matches a custom event by name with no filters", () => {
+ expect(buildEventCondition("signup", [])).toBe("type = 'custom_event' AND event_name = 'signup'");
+ });
+
+ it("matches a string property filter against props", () => {
+ expect(buildEventCondition("purchase", [{ key: "plan", value: "pro" }])).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro'"
+ );
+ });
+
+ it("compares numeric property filters as floats with an unquoted literal", () => {
+ expect(buildEventCondition("purchase", [{ key: "amount", value: 42 }])).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 42"
+ );
+ expect(buildEventCondition("purchase", [{ key: "amount", value: 9.5 }])).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 9.5"
+ );
+ });
+
+ it("compares boolean property filters against the strings 'true' and 'false'", () => {
+ expect(buildEventCondition("purchase", [{ key: "gift", value: true }])).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'gift') = 'true'"
+ );
+ expect(buildEventCondition("purchase", [{ key: "gift", value: false }])).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'gift') = 'false'"
+ );
+ });
+
+ it("AND-joins multiple property filters in order", () => {
+ expect(
+ buildEventCondition("purchase", [
+ { key: "plan", value: "pro" },
+ { key: "seats", value: 3 },
+ ])
+ ).toBe(
+ "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro' AND toFloat64(JSONExtractString(toString(props), 'seats')) = 3"
+ );
+ });
+
+ it("escapes quotes in the event name", () => {
+ expect(buildEventCondition("evt'; DROP TABLE events;--", [])).toBe(
+ "type = 'custom_event' AND event_name = 'evt\\'; DROP TABLE events;--'"
+ );
+ });
+
+ it("escapes quotes in property filter keys and values", () => {
+ expect(buildEventCondition("evt", [{ key: "k'ey", value: "v'al" }])).toBe(
+ "type = 'custom_event' AND event_name = 'evt' AND JSONExtractString(toString(props), 'k\\'ey') = 'v\\'al'"
+ );
+ });
+
+ it("escapes backslashes in event names and property values", () => {
+ expect(buildEventCondition("a\\b", [{ key: "p", value: "c\\d" }])).toBe(
+ "type = 'custom_event' AND event_name = 'a\\\\b' AND JSONExtractString(toString(props), 'p') = 'c\\\\d'"
+ );
+ });
+
+ it("emits an empty quoted literal for an empty event name", () => {
+ expect(buildEventCondition("", [])).toBe("type = 'custom_event' AND event_name = ''");
+ });
+});
+
+describe("buildAutocaptureCondition", () => {
+ it("matches the bare event type when no pattern is given", () => {
+ expect(buildAutocaptureCondition("outbound", undefined, [])).toBe("type = 'outbound'");
+ expect(buildAutocaptureCondition("button_click", undefined, [])).toBe("type = 'button_click'");
+ expect(buildAutocaptureCondition("form_submit", undefined, [])).toBe("type = 'form_submit'");
+ expect(buildAutocaptureCondition("copy", undefined, [])).toBe("type = 'copy'");
+ });
+
+ it("treats an empty or whitespace-only pattern as no pattern", () => {
+ expect(buildAutocaptureCondition("outbound", "", [])).toBe("type = 'outbound'");
+ expect(buildAutocaptureCondition("outbound", " ", [])).toBe("type = 'outbound'");
+ });
+
+ it("trims the pattern before compiling it", () => {
+ expect(buildAutocaptureCondition("copy", " hello ", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^hello$'))"
+ );
+ });
+
+ it("matches an outbound pattern against the url prop", () => {
+ expect(buildAutocaptureCondition("outbound", "https://example.com/*", [])).toBe(
+ "type = 'outbound' AND (match(JSONExtractString(toString(props), 'url'), '^https://example\\\\.com/.+$'))"
+ );
+ });
+
+ it("matches a button_click pattern against the text prop", () => {
+ expect(buildAutocaptureCondition("button_click", "Buy now", [])).toBe(
+ "type = 'button_click' AND (match(JSONExtractString(toString(props), 'text'), '^Buy now$'))"
+ );
+ });
+
+ it("ORs a form_submit pattern across all three form props", () => {
+ expect(buildAutocaptureCondition("form_submit", "signup", [])).toBe(
+ "type = 'form_submit' AND (match(JSONExtractString(toString(props), 'formName'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formId'), '^signup$') OR " +
+ "match(JSONExtractString(toString(props), 'formAction'), '^signup$'))"
+ );
+ });
+
+ it("matches a copy pattern against the text prop", () => {
+ expect(buildAutocaptureCondition("copy", "coupon-*", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^coupon-.+$'))"
+ );
+ });
+
+ it("lets a single star cross a slash, unlike path patterns", () => {
+ // Autocapture values have no path-segment boundary, so '*' compiles to '.+'
+ // rather than '[^/]+'.
+ expect(buildAutocaptureCondition("outbound", "https://example.com/*", [])).toContain("/.+$");
+ expect(buildPageCondition("/a/*", [])).toContain("[^/]+");
+ });
+
+ it("compiles a double star to .*", () => {
+ expect(buildAutocaptureCondition("copy", "a**b", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^a.*b$'))"
+ );
+ });
+
+ it("escapes regex metacharacters in the pattern", () => {
+ expect(buildAutocaptureCondition("copy", "a.b(c)", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^a\\\\.b\\\\(c\\\\)$'))"
+ );
+ });
+
+ it("appends property filters after the pattern clause", () => {
+ expect(buildAutocaptureCondition("outbound", "https://x.com", [{ key: "target", value: "_blank" }])).toBe(
+ "type = 'outbound' AND (match(JSONExtractString(toString(props), 'url'), '^https://x\\\\.com$'))" +
+ " AND JSONExtractString(toString(props), 'target') = '_blank'"
+ );
+ });
+
+ it("applies property filters with no pattern", () => {
+ expect(
+ buildAutocaptureCondition("button_click", undefined, [
+ { key: "id", value: "cta" },
+ { key: "count", value: 2 },
+ ])
+ ).toBe(
+ "type = 'button_click' AND JSONExtractString(toString(props), 'id') = 'cta'" +
+ " AND toFloat64(JSONExtractString(toString(props), 'count')) = 2"
+ );
+ });
+
+ it("escapes quotes in the pattern so it cannot break out of the literal", () => {
+ expect(buildAutocaptureCondition("copy", "a') OR 1=1--", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^a\\'\\\\) OR 1=1--$'))"
+ );
+ });
+
+ it("escapes backslashes in the pattern", () => {
+ expect(buildAutocaptureCondition("copy", "a\\b", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^a\\\\\\\\b$'))"
+ );
+ });
+
+ it("does not let a user-supplied double-star marker survive into the regex", () => {
+ expect(buildAutocaptureCondition("copy", "{{DOUBLE_STAR}}", [])).toBe(
+ "type = 'copy' AND (match(JSONExtractString(toString(props), 'text'), '^\\\\{\\\\{DOUBLE_STAR\\\\}\\\\}$'))"
+ );
+ });
+});
diff --git a/server/src/api/gsc/utils.test.ts b/server/src/api/gsc/utils.test.ts
new file mode 100644
index 000000000..38379f988
--- /dev/null
+++ b/server/src/api/gsc/utils.test.ts
@@ -0,0 +1,383 @@
+import crypto from "crypto";
+import type { FastifyBaseLogger } from "fastify";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const TEST_SECRET = "test-better-auth-secret-0123456789";
+
+const state = vi.hoisted(() => ({
+ secret: undefined as string | undefined,
+ connections: [] as Record<string, unknown>[],
+ updates: [] as Record<string, unknown>[],
+}));
+
+vi.mock("../../lib/const.js", async importOriginal => {
+ const actual = await importOriginal<typeof import("../../lib/const.js")>();
+ return {
+ ...actual,
+ get SECRET() {
+ return state.secret;
+ },
+ };
+});
+
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {
+ select: () => ({
+ from: () => ({
+ where: async () => state.connections,
+ }),
+ }),
+ update: () => ({
+ set: (data: Record<string, unknown>) => ({
+ where: async () => {
+ state.updates.push(data);
+ },
+ }),
+ }),
+ },
+}));
+
+import { getGSCProperties, refreshGSCToken, signGSCState, verifyGSCState } from "./utils.js";
+
+const TTL_MS = 15 * 60 * 1000;
+
+function hmac(body: string, secret: string): string {
+ return crypto.createHmac("sha256", secret).update(body).digest("base64url");
+}
+
+function encodeBody(payload: unknown): string {
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
+}
+
+/** Mint a state for an arbitrary (possibly hostile) payload, correctly signed. */
+function signedState(payload: unknown, secret = TEST_SECRET): string {
+ const body = encodeBody(payload);
+ return `${body}.${hmac(body, secret)}`;
+}
+
+function loggerStub() {
+ return { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as unknown as FastifyBaseLogger & {
+ error: ReturnType<typeof vi.fn>;
+ };
+}
+
+beforeEach(() => {
+ state.secret = TEST_SECRET;
+ state.connections = [];
+ state.updates = [];
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("signGSCState / verifyGSCState", () => {
+ it("round-trips the site and user the flow was minted for", () => {
+ const verified = verifyGSCState(signGSCState(42, "user_abc"));
+
+ expect(verified).not.toBeNull();
+ expect(verified!.siteId).toBe(42);
+ expect(verified!.userId).toBe("user_abc");
+ expect(typeof verified!.ts).toBe("number");
+ });
+
+ it("emits a two-part base64url `body.signature` value", () => {
+ const value = signGSCState(1, "user_abc");
+ const parts = value.split(".");
+
+ expect(parts).toHaveLength(2);
+ for (const part of parts) {
+ expect(part).toMatch(/^[A-Za-z0-9_-]+$/);
+ }
+ // The body is not encryption: it is readable, only tamper-evident.
+ expect(JSON.parse(Buffer.from(parts[0], "base64url").toString())).toMatchObject({
+ siteId: 1,
+ userId: "user_abc",
+ });
+ });
+
+ it("rejects a body swapped to another site while keeping the original signature (IDOR)", () => {
+ const original = signGSCState(1, "user_abc");
+ const [, signature] = original.split(".");
+ const attackerBody = encodeBody({ siteId: 999, userId: "user_abc", ts: Date.now() });
+
+ expect(verifyGSCState(`${attackerBody}.${signature}`)).toBeNull();
+ });
+
+ it("rejects a body swapped to another user while keeping the original signature", () => {
+ const original = signGSCState(1, "victim_user");
+ const [, signature] = original.split(".");
+ const attackerBody = encodeBody({ siteId: 1, userId: "attacker_user", ts: Date.now() });
+
+ expect(verifyGSCState(`${attackerBody}.${signature}`)).toBeNull();
+ });
+
+ it("rejects a forged signature of the correct length", () => {
+ const [body, signature] = signGSCState(1, "user_abc").split(".");
+ // Same length, one character flipped: exercises timingSafeEqual's compare path.
+ const flipped = (signature[0] === "A" ? "B" : "A") + signature.slice(1);
+
+ expect(flipped).toHaveLength(signature.length);
+ expect(verifyGSCState(`${body}.${flipped}`)).toBeNull();
+ });
+
+ it("rejects a signature of the wrong length without throwing", () => {
+ // crypto.timingSafeEqual throws on length mismatch; the length guard must
+ // short-circuit before it is reached.
+ const [body, signature] = signGSCState(1, "user_abc").split(".");
+
+ expect(() => verifyGSCState(`${body}.${signature.slice(0, 5)}`)).not.toThrow();
+ expect(verifyGSCState(`${body}.${signature.slice(0, 5)}`)).toBeNull();
+ expect(verifyGSCState(`${body}.${signature}extra`)).toBeNull();
+ expect(verifyGSCState(`${body}.`)).toBeNull();
+ expect(verifyGSCState(`${body}.x`)).toBeNull();
+ });
+
+ it("rejects structurally malformed state values", () => {
+ expect(verifyGSCState("")).toBeNull();
+ expect(verifyGSCState("no-separator-here")).toBeNull();
+ expect(verifyGSCState(".")).toBeNull();
+ expect(verifyGSCState("a.b.c")).toBeNull();
+ expect(verifyGSCState(`${signGSCState(1, "user_abc")}.extra`)).toBeNull();
+ });
+
+ it("rejects state signed with a different secret", () => {
+ const foreign = signedState({ siteId: 1, userId: "user_abc", ts: Date.now() }, "some-other-deployment-secret");
+
+ expect(verifyGSCState(foreign)).toBeNull();
+ });
+
+ it("rejects a correctly signed body that is not valid JSON", () => {
+ // The attacker controls the body only if they hold the secret; this guards
+ // the decode path against a corrupted (not forged) value.
+ expect(
+ verifyGSCState(
+ `${Buffer.from("not json").toString("base64url")}.${hmac(Buffer.from("not json").toString("base64url"), TEST_SECRET)}`
+ )
+ ).toBeNull();
+
+ const garbageBody = "!!!!not-base64url!!!!";
+ expect(verifyGSCState(`${garbageBody}.${hmac(garbageBody, TEST_SECRET)}`)).toBeNull();
+ });
+
+ it("rejects correctly signed payloads that are not objects", () => {
+ expect(verifyGSCState(signedState(null))).toBeNull();
+ expect(verifyGSCState(signedState("user_abc"))).toBeNull();
+ expect(verifyGSCState(signedState(123))).toBeNull();
+ expect(verifyGSCState(signedState([1, "user_abc", Date.now()]))).toBeNull();
+ });
+
+ it("rejects payloads with missing or wrongly typed fields", () => {
+ const now = Date.now();
+
+ expect(verifyGSCState(signedState({ siteId: "1", userId: "user_abc", ts: now }))).toBeNull();
+ expect(verifyGSCState(signedState({ siteId: 1, ts: now }))).toBeNull();
+ expect(verifyGSCState(signedState({ siteId: 1, userId: 7, ts: now }))).toBeNull();
+ expect(verifyGSCState(signedState({ siteId: 1, userId: "user_abc" }))).toBeNull();
+ expect(verifyGSCState(signedState({ siteId: 1, userId: "user_abc", ts: String(now) }))).toBeNull();
+ expect(verifyGSCState(signedState({ siteId: null, userId: "user_abc", ts: now }))).toBeNull();
+ expect(verifyGSCState(signedState({}))).toBeNull();
+ });
+
+ it("keeps extra payload fields intact when the signature covers them", () => {
+ const verified = verifyGSCState(signedState({ siteId: 5, userId: "user_abc", ts: Date.now(), extra: "kept" }));
+
+ expect(verified).toMatchObject({ siteId: 5, userId: "user_abc", extra: "kept" });
+ });
+
+ it("accepts a state up to the TTL and rejects it one millisecond later", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
+
+ const value = signGSCState(1, "user_abc");
+
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z").getTime() + TTL_MS);
+ expect(verifyGSCState(value)).not.toBeNull();
+
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z").getTime() + TTL_MS + 1);
+ expect(verifyGSCState(value)).toBeNull();
+ });
+
+ it("rejects a long-expired state", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
+ const value = signGSCState(1, "user_abc");
+
+ vi.setSystemTime(new Date("2026-01-02T00:00:00.000Z"));
+ expect(verifyGSCState(value)).toBeNull();
+ });
+
+ it("accepts future-dated timestamps (no clock-skew ceiling)", () => {
+ // Current behavior: only `now - ts > TTL` is checked, so a forward-dated ts
+ // never expires. Only a holder of the signing secret can mint one.
+ const future = signedState({ siteId: 1, userId: "user_abc", ts: Date.now() + 10 * 365 * 24 * 60 * 60 * 1000 });
+
+ expect(verifyGSCState(future)).toMatchObject({ siteId: 1, userId: "user_abc" });
+ });
+
+ it("refuses to sign or verify when BETTER_AUTH_SECRET is unset", () => {
+ const value = signGSCState(1, "user_abc");
+ state.secret = undefined;
+
+ expect(() => signGSCState(1, "user_abc")).toThrow(/BETTER_AUTH_SECRET is not set/);
+ expect(() => verifyGSCState(value)).toThrow(/BETTER_AUTH_SECRET is not set/);
+ // The malformed-shape guard runs first, so those still return null.
+ expect(verifyGSCState("no-separator-here")).toBeNull();
+ });
+});
+
+describe("refreshGSCToken", () => {
+ const futureIso = () => new Date(Date.now() + 60 * 60 * 1000).toISOString();
+ const staleIso = () => new Date(Date.now() - 60 * 60 * 1000).toISOString();
+
+ it("returns null when the site has no GSC connection", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ expect(await refreshGSCToken(1, loggerStub())).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("returns the stored token without a network call while it is still fresh", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ state.connections = [{ siteId: 1, accessToken: "stored-token", refreshToken: "r1", expiresAt: futureIso() }];
+
+ expect(await refreshGSCToken(1, loggerStub())).toBe("stored-token");
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("refreshes an expired token and persists the new access token and expiry", async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ access_token: "fresh-token", expires_in: 3600 }),
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ state.connections = [{ siteId: 1, accessToken: "old-token", refreshToken: "r1", expiresAt: staleIso() }];
+
+ expect(await refreshGSCToken(1, loggerStub())).toBe("fresh-token");
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://oauth2.googleapis.com/token",
+ expect.objectContaining({ method: "POST" })
+ );
+ expect(state.updates).toHaveLength(1);
+ expect(state.updates[0].accessToken).toBe("fresh-token");
+ // No new refresh_token in the response => the stored one is left alone.
+ expect(state.updates[0]).not.toHaveProperty("refreshToken");
+ expect(new Date(state.updates[0].expiresAt as string).getTime()).toBeGreaterThan(Date.now());
+ });
+
+ it("stores a rotated refresh token when Google returns one", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ access_token: "fresh-token", refresh_token: "r2", expires_in: 3600 }),
+ }))
+ );
+ state.connections = [{ siteId: 1, accessToken: "old-token", refreshToken: "r1", expiresAt: staleIso() }];
+
+ await refreshGSCToken(1, loggerStub());
+
+ expect(state.updates[0].refreshToken).toBe("r2");
+ });
+
+ it("refreshes inside the five minute expiry buffer", async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ access_token: "fresh-token", expires_in: 3600 }),
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ state.connections = [
+ {
+ siteId: 1,
+ accessToken: "old-token",
+ refreshToken: "r1",
+ expiresAt: new Date(Date.now() + 60 * 1000).toISOString(),
+ },
+ ];
+
+ expect(await refreshGSCToken(1, loggerStub())).toBe("fresh-token");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns null and logs when Google rejects the refresh", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: false, status: 400, text: async () => "invalid_grant" }))
+ );
+ state.connections = [{ siteId: 1, accessToken: "old-token", refreshToken: "r1", expiresAt: staleIso() }];
+ const logger = loggerStub();
+
+ expect(await refreshGSCToken(1, logger)).toBeNull();
+ expect(logger.error).toHaveBeenCalled();
+ expect(state.updates).toHaveLength(0);
+ });
+
+ it("returns null when the request throws", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new Error("network down");
+ })
+ );
+ state.connections = [{ siteId: 1, accessToken: "old-token", refreshToken: "r1", expiresAt: staleIso() }];
+ const logger = loggerStub();
+
+ expect(await refreshGSCToken(1, logger)).toBeNull();
+ expect(logger.error).toHaveBeenCalled();
+ });
+});
+
+describe("getGSCProperties", () => {
+ it("returns the site URLs from a successful response and sends the bearer token", async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ siteEntry: [{ siteUrl: "https://a.example/" }, { siteUrl: "sc-domain:b.example" }] }),
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ expect(await getGSCProperties("token-123", loggerStub())).toEqual(["https://a.example/", "sc-domain:b.example"]);
+ expect(fetchMock).toHaveBeenCalledWith("https://www.googleapis.com/webmasters/v3/sites", {
+ headers: { Authorization: "Bearer token-123" },
+ });
+ });
+
+ it("returns an empty list when the response has no siteEntry", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}) }))
+ );
+
+ expect(await getGSCProperties("token-123", loggerStub())).toEqual([]);
+ });
+
+ it("returns an empty list and logs on a non-OK response", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: false, status: 403, text: async () => "forbidden" }))
+ );
+ const logger = loggerStub();
+
+ expect(await getGSCProperties("token-123", logger)).toEqual([]);
+ expect(logger.error).toHaveBeenCalled();
+ });
+
+ it("returns an empty list when the request throws", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new Error("network down");
+ })
+ );
+ const logger = loggerStub();
+
+ expect(await getGSCProperties("token-123", logger)).toEqual([]);
+ expect(logger.error).toHaveBeenCalled();
+ });
+});
diff --git a/server/src/lib/access.test.ts b/server/src/lib/access.test.ts
new file mode 100644
index 000000000..e40b202aa
--- /dev/null
+++ b/server/src/lib/access.test.ts
@@ -0,0 +1,349 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * Rows the mocked Drizzle builder hands back, keyed by the table each query reads.
+ * `team_site_access` is read twice with different meanings β€” once joined to `team`
+ * (every site gated by any team in the scoped orgs) and once unjoined (the sites of
+ * the teams this user belongs to) β€” so the mock tracks innerJoin as well as the table.
+ */
+const state = vi.hoisted(() => ({
+ member: [] as unknown[],
+ sites: [] as unknown[],
+ member_site_access: [] as unknown[],
+ team_site_access_joined: [] as unknown[],
+ team_site_access: [] as unknown[],
+ teamMember: [] as unknown[],
+ /** Every table a query touched, in call order β€” lets tests assert queries are skipped. */
+ queriedTables: [] as string[],
+}));
+
+vi.mock("../db/postgres/postgres.js", async () => {
+ const { getTableName } = await import("drizzle-orm");
+
+ // Drizzle query builders are thenable: access.ts awaits `.limit(1)` in one place and
+ // `.where(...)` in the others, so every link in the chain resolves to the same rows.
+ function chain() {
+ let table = "";
+ let joined = false;
+ const builder: any = {
+ from: (t: any) => {
+ table = getTableName(t);
+ return builder;
+ },
+ innerJoin: () => {
+ joined = true;
+ return builder;
+ },
+ where: () => builder,
+ limit: () => builder,
+ then: (resolve: any, reject: any) => {
+ const key = table === "team_site_access" && joined ? "team_site_access_joined" : table;
+ state.queriedTables.push(key);
+ return Promise.resolve((state as any)[key] ?? []).then(resolve, reject);
+ },
+ };
+ return builder;
+ }
+
+ return { db: { select: () => chain() } };
+});
+
+import {
+ filterSitesByMemberAccess,
+ getOrgMembership,
+ isOrgAdmin,
+ isOrgOwner,
+ memberCanAccessSite,
+ MemberSiteGrants,
+ resolveMemberSiteGrants,
+ restrictedMemberSiteIds,
+ siteIdsInOrganization,
+} from "./access.js";
+
+function grants(overrides: Partial<Record<keyof MemberSiteGrants, number[]>> = {}): MemberSiteGrants {
+ return {
+ explicitSiteIds: new Set(overrides.explicitSiteIds ?? []),
+ teamGatedSiteIds: new Set(overrides.teamGatedSiteIds ?? []),
+ userTeamSiteIds: new Set(overrides.userTeamSiteIds ?? []),
+ };
+}
+
+/** All subsets of `universe`, as arrays β€” used to enumerate every possible grant shape. */
+function subsets(universe: number[]): number[][] {
+ return Array.from({ length: 1 << universe.length }, (_, mask) => universe.filter((_, i) => mask & (1 << i)));
+}
+
+beforeEach(() => {
+ state.member = [];
+ state.sites = [];
+ state.member_site_access = [];
+ state.team_site_access_joined = [];
+ state.team_site_access = [];
+ state.teamMember = [];
+ state.queriedTables.length = 0;
+});
+
+describe("memberCanAccessSite", () => {
+ it("honours an explicit grant even for a site gated behind a team the member is not on", () => {
+ const g = grants({ explicitSiteIds: [1], teamGatedSiteIds: [1] });
+
+ expect(memberCanAccessSite(g, 1, true)).toBe(true);
+ expect(memberCanAccessSite(g, 1, false)).toBe(true);
+ });
+
+ it("grants sites reached through the member's own teams regardless of the restriction flag", () => {
+ const g = grants({ userTeamSiteIds: [2], teamGatedSiteIds: [2] });
+
+ expect(memberCanAccessSite(g, 2, true)).toBe(true);
+ expect(memberCanAccessSite(g, 2, false)).toBe(true);
+ });
+
+ it("denies a restricted member every site they hold no grant for", () => {
+ const g = grants({ explicitSiteIds: [1], userTeamSiteIds: [2], teamGatedSiteIds: [3] });
+
+ expect(memberCanAccessSite(g, 3, true)).toBe(false);
+ // Ungated too: restricted access is grant-driven, not gating-driven.
+ expect(memberCanAccessSite(g, 99, true)).toBe(false);
+ });
+
+ it("gives an unrestricted member every site no team gates, and withholds the gated ones", () => {
+ const g = grants({ teamGatedSiteIds: [3] });
+
+ expect(memberCanAccessSite(g, 99, false)).toBe(true);
+ expect(memberCanAccessSite(g, 3, false)).toBe(false);
+ });
+});
+
+describe("restrictedMemberSiteIds cross-checks memberCanAccessSite", () => {
+ // The contract access.ts documents: the enumeration must return exactly the sites the
+ // restricted branch of the predicate admits. Checked over every grant shape drawable
+ // from a four-site universe (4096 combinations) so a change to either side that the
+ // other does not mirror fails here.
+ const universe = [1, 2, 3, 4];
+ const shapes = subsets(universe);
+
+ it("enumerates exactly the sites the restricted predicate admits, for every grant shape", () => {
+ let checked = 0;
+
+ for (const explicitSiteIds of shapes) {
+ for (const teamGatedSiteIds of shapes) {
+ for (const userTeamSiteIds of shapes) {
+ const g = grants({ explicitSiteIds, teamGatedSiteIds, userTeamSiteIds });
+
+ const enumerated = [...restrictedMemberSiteIds(g)].sort((a, b) => a - b);
+ const predicated = universe.filter(siteId => memberCanAccessSite(g, siteId, true));
+
+ expect(enumerated).toEqual(predicated);
+ checked++;
+ }
+ }
+ }
+
+ expect(checked).toBe(shapes.length ** 3);
+ });
+
+ it("never repeats a site id, even when the explicit and team grants overlap", () => {
+ const ids = restrictedMemberSiteIds(grants({ explicitSiteIds: [1, 2], userTeamSiteIds: [2, 3] }));
+
+ expect([...ids].sort((a, b) => a - b)).toEqual([1, 2, 3]);
+ expect(ids).toHaveLength(new Set(ids).size);
+ });
+
+ it("ignores teamGatedSiteIds, which only matter to the unrestricted branch", () => {
+ expect(restrictedMemberSiteIds(grants({ teamGatedSiteIds: [1, 2, 3] }))).toEqual([]);
+ });
+});
+
+describe("getOrgMembership", () => {
+ it("returns the membership row when the user belongs to the organization", async () => {
+ state.member = [
+ { id: "m_1", userId: "u_1", organizationId: "org_1", role: "member", hasRestrictedSiteAccess: true },
+ ];
+
+ await expect(getOrgMembership("u_1", "org_1")).resolves.toMatchObject({ id: "m_1", role: "member" });
+ });
+
+ it("returns null when the organization has no row for the user", async () => {
+ await expect(getOrgMembership("u_1", "org_1")).resolves.toBeNull();
+ });
+
+ it("short-circuits without querying when either identifier is missing", async () => {
+ state.member = [
+ { id: "m_1", userId: "u_1", organizationId: "org_1", role: "owner", hasRestrictedSiteAccess: false },
+ ];
+
+ await expect(getOrgMembership(undefined, "org_1")).resolves.toBeNull();
+ await expect(getOrgMembership("u_1", null)).resolves.toBeNull();
+ await expect(getOrgMembership("", "")).resolves.toBeNull();
+ expect(state.queriedTables).toEqual([]);
+ });
+});
+
+describe("isOrgAdmin / isOrgOwner", () => {
+ const membership = (role: string) => ({
+ id: "m_1",
+ userId: "u_1",
+ organizationId: "org_1",
+ role,
+ hasRestrictedSiteAccess: false,
+ });
+
+ it("treats admin and owner as admin, and nothing else", () => {
+ expect(isOrgAdmin(membership("admin"))).toBe(true);
+ expect(isOrgAdmin(membership("owner"))).toBe(true);
+ expect(isOrgAdmin(membership("member"))).toBe(false);
+ expect(isOrgAdmin(membership("Owner"))).toBe(false);
+ });
+
+ it("treats only owner as owner", () => {
+ expect(isOrgOwner(membership("owner"))).toBe(true);
+ expect(isOrgOwner(membership("admin"))).toBe(false);
+ });
+
+ it("treats a missing membership as neither", () => {
+ for (const missing of [null, undefined]) {
+ expect(isOrgAdmin(missing)).toBe(false);
+ expect(isOrgOwner(missing)).toBe(false);
+ }
+ });
+});
+
+describe("siteIdsInOrganization", () => {
+ it("returns only the ids the organization still owns", async () => {
+ state.sites = [{ siteId: 1 }, { siteId: 3 }];
+
+ await expect(siteIdsInOrganization([1, 2, 3], "org_1")).resolves.toEqual([1, 3]);
+ });
+
+ it("skips the query entirely for an empty id list", async () => {
+ await expect(siteIdsInOrganization([], "org_1")).resolves.toEqual([]);
+ expect(state.queriedTables).toEqual([]);
+ });
+});
+
+describe("resolveMemberSiteGrants", () => {
+ it("collects explicit grants, team-gated sites and the user's own team sites", async () => {
+ state.member_site_access = [{ siteId: 1 }, { siteId: 1 }, { siteId: 2 }];
+ state.team_site_access_joined = [{ siteId: 2 }, { siteId: 3 }];
+ state.teamMember = [{ teamId: "t_1" }];
+ state.team_site_access = [{ siteId: 3 }];
+
+ const resolved = await resolveMemberSiteGrants({
+ userId: "u_1",
+ organizationIds: ["org_1"],
+ grantedMemberIds: ["m_1"],
+ });
+
+ expect(resolved.explicitSiteIds).toEqual(new Set([1, 2]));
+ expect(resolved.teamGatedSiteIds).toEqual(new Set([2, 3]));
+ expect(resolved.userTeamSiteIds).toEqual(new Set([3]));
+ });
+
+ it("skips the explicit-grant query when no member ids are supplied", async () => {
+ state.member_site_access = [{ siteId: 42 }];
+
+ const resolved = await resolveMemberSiteGrants({
+ userId: "u_1",
+ organizationIds: ["org_1"],
+ grantedMemberIds: [],
+ });
+
+ expect(resolved.explicitSiteIds).toEqual(new Set());
+ expect(state.queriedTables).not.toContain("member_site_access");
+ });
+
+ it("skips the team-site query when the user is on no team", async () => {
+ state.teamMember = [];
+ state.team_site_access = [{ siteId: 7 }];
+
+ const resolved = await resolveMemberSiteGrants({
+ userId: "u_1",
+ organizationIds: ["org_1"],
+ grantedMemberIds: [],
+ });
+
+ expect(resolved.userTeamSiteIds).toEqual(new Set());
+ expect(state.queriedTables).not.toContain("team_site_access");
+ });
+
+ it("returns empty grants without querying when there is nothing to scope by", async () => {
+ const resolved = await resolveMemberSiteGrants({ userId: "u_1", organizationIds: [], grantedMemberIds: [] });
+
+ expect(resolved.explicitSiteIds).toEqual(new Set());
+ expect(resolved.teamGatedSiteIds).toEqual(new Set());
+ expect(resolved.userTeamSiteIds).toEqual(new Set());
+ expect(state.queriedTables).toEqual([]);
+ });
+
+ it("still loads explicit grants when only member ids are scoped, leaving the org-scoped sets empty", async () => {
+ state.member_site_access = [{ siteId: 5 }];
+ state.team_site_access_joined = [{ siteId: 6 }];
+
+ const resolved = await resolveMemberSiteGrants({
+ userId: "u_1",
+ organizationIds: [],
+ grantedMemberIds: ["m_1"],
+ });
+
+ expect(resolved.explicitSiteIds).toEqual(new Set([5]));
+ expect(resolved.teamGatedSiteIds).toEqual(new Set());
+ expect(state.queriedTables).toEqual(["member_site_access"]);
+ });
+});
+
+describe("filterSitesByMemberAccess", () => {
+ it("keeps only granted sites for a restricted member and asks for their explicit grants", async () => {
+ state.member_site_access = [{ siteId: 1 }];
+ state.team_site_access_joined = [{ siteId: 2 }];
+ state.teamMember = [{ teamId: "t_1" }];
+ state.team_site_access = [{ siteId: 2 }];
+
+ const kept = await filterSitesByMemberAccess(
+ [{ siteId: 1 }, { siteId: 2 }, { siteId: 3 }],
+ "org_1",
+ "u_1",
+ "m_1",
+ true
+ );
+
+ expect(kept).toEqual([{ siteId: 1 }, { siteId: 2 }]);
+ expect(state.queriedTables).toContain("member_site_access");
+ });
+
+ it("keeps ungated sites for an unrestricted member and does not load explicit grants", async () => {
+ state.member_site_access = [{ siteId: 99 }];
+ state.team_site_access_joined = [{ siteId: 2 }];
+
+ const kept = await filterSitesByMemberAccess(
+ [{ siteId: 1 }, { siteId: 2 }, { siteId: 3 }],
+ "org_1",
+ "u_1",
+ "m_1",
+ false
+ );
+
+ expect(kept).toEqual([{ siteId: 1 }, { siteId: 3 }]);
+ expect(state.queriedTables).not.toContain("member_site_access");
+ });
+
+ it("preserves the caller's own row shape and ordering", async () => {
+ state.team_site_access_joined = [{ siteId: 2 }];
+
+ const kept = await filterSitesByMemberAccess(
+ [
+ { siteId: 3, domain: "c.example" },
+ { siteId: 1, domain: "a.example" },
+ { siteId: 2, domain: "b.example" },
+ ],
+ "org_1",
+ "u_1",
+ "m_1",
+ false
+ );
+
+ expect(kept).toEqual([
+ { siteId: 3, domain: "c.example" },
+ { siteId: 1, domain: "a.example" },
+ ]);
+ });
+});
diff --git a/server/src/lib/ipUtils.test.ts b/server/src/lib/ipUtils.test.ts
new file mode 100644
index 000000000..6a08bbc91
--- /dev/null
+++ b/server/src/lib/ipUtils.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("./logger/logger.js", () => ({
+ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() },
+}));
+
+import { matchesCIDR, matchesRange, validateIPPattern } from "./ipUtils.js";
+
+describe("validateIPPattern", () => {
+ it("treats empty and whitespace-only patterns as valid (matches the client)", () => {
+ expect(validateIPPattern("")).toEqual({ valid: true });
+ expect(validateIPPattern(" ")).toEqual({ valid: true });
+ expect(validateIPPattern("\t\n")).toEqual({ valid: true });
+ });
+
+ it("accepts single IPv4 and IPv6 addresses, trimming surrounding whitespace", () => {
+ expect(validateIPPattern("192.168.1.1")).toEqual({ valid: true });
+ expect(validateIPPattern(" 10.0.0.1 ")).toEqual({ valid: true });
+ expect(validateIPPattern("0.0.0.0")).toEqual({ valid: true });
+ expect(validateIPPattern("255.255.255.255")).toEqual({ valid: true });
+ expect(validateIPPattern("2001:db8::1")).toEqual({ valid: true });
+ expect(validateIPPattern("::1")).toEqual({ valid: true });
+ expect(validateIPPattern("::ffff:192.168.1.1")).toEqual({ valid: true });
+ });
+
+ it("rejects malformed single addresses", () => {
+ for (const pattern of ["256.1.1.1", "1.2.3", "1.2.3.4.5", "abc", "1.2.3.4x", "0x1.2.3.4", "2130706433", "..."]) {
+ expect(validateIPPattern(pattern)).toEqual({ valid: false, error: "Invalid IP address format" });
+ }
+ });
+
+ it("accepts zero-padded IPv4 octets (ip-address normalizes them)", () => {
+ // Documenting current behavior: "01.2.3.4" parses as 1.2.3.4 rather than
+ // being rejected as ambiguous octal-looking input.
+ expect(validateIPPattern("01.2.3.4")).toEqual({ valid: true });
+ expect(validateIPPattern("192.168.001.1")).toEqual({ valid: true });
+ });
+
+ it("accepts CIDR notation for IPv4 and IPv6", () => {
+ expect(validateIPPattern("192.168.1.0/24")).toEqual({ valid: true });
+ expect(validateIPPattern("10.0.0.1/32")).toEqual({ valid: true });
+ expect(validateIPPattern("0.0.0.0/0")).toEqual({ valid: true });
+ expect(validateIPPattern("2001:db8::/32")).toEqual({ valid: true });
+ expect(validateIPPattern("::/0")).toEqual({ valid: true });
+ });
+
+ it("rejects malformed CIDR notation", () => {
+ for (const pattern of ["192.168.1.1/33", "192.168.1.1/-1", "192.168.1.1/", "192.168.1.1/abc", "/24", "1.2.3/24"]) {
+ expect(validateIPPattern(pattern)).toEqual({ valid: false, error: "Invalid CIDR notation" });
+ }
+ });
+
+ it("classifies a pattern containing a slash as CIDR even when it also has a dash", () => {
+ expect(validateIPPattern("192.168.1.0/24-192.168.2.0/24")).toEqual({
+ valid: false,
+ error: "Invalid CIDR notation",
+ });
+ });
+
+ it("accepts IPv4 range notation, including inner whitespace around the dash", () => {
+ expect(validateIPPattern("192.168.1.1-192.168.1.10")).toEqual({ valid: true });
+ expect(validateIPPattern(" 192.168.1.1 - 192.168.1.10 ")).toEqual({ valid: true });
+ expect(validateIPPattern("10.0.0.5-10.0.0.5")).toEqual({ valid: true });
+ });
+
+ it("does not enforce range ordering", () => {
+ // A reversed range validates but can never match; see matchesRange.
+ expect(validateIPPattern("192.168.1.10-192.168.1.1")).toEqual({ valid: true });
+ });
+
+ it("rejects incomplete range notation", () => {
+ for (const pattern of ["192.168.1.1-", "-192.168.1.1", "-", " - "]) {
+ expect(validateIPPattern(pattern)).toEqual({ valid: false, error: "Invalid range format" });
+ }
+ });
+
+ it("rejects ranges whose endpoints are not valid IPv4 addresses", () => {
+ expect(validateIPPattern("192.168.1.1-999.1.1.1")).toEqual({
+ valid: false,
+ error: "Invalid IP addresses in range",
+ });
+ expect(validateIPPattern("abc-def")).toEqual({ valid: false, error: "Invalid IP addresses in range" });
+ expect(validateIPPattern("192.168.1.1-2001:db8::1")).toEqual({
+ valid: false,
+ error: "Invalid IP addresses in range",
+ });
+ // Three endpoints: the third is ignored, but the second must still parse.
+ expect(validateIPPattern("10.0.0.1-10.0.0.5-10.0.0.9")).toEqual({ valid: true });
+ });
+
+ it("points IPv6 ranges at CIDR notation instead", () => {
+ expect(validateIPPattern("2001:db8::1-2001:db8::5")).toEqual({
+ valid: false,
+ error: "IPv6 range notation not supported. Use CIDR notation instead (e.g., 2001:db8::/32)",
+ });
+ });
+});
+
+describe("matchesCIDR", () => {
+ it("matches an IPv4 address inside the subnet", () => {
+ expect(matchesCIDR("192.168.1.42", "192.168.1.0/24")).toBe(true);
+ });
+
+ it("includes both boundary addresses of a /24 and excludes the neighbours", () => {
+ expect(matchesCIDR("192.168.1.0", "192.168.1.0/24")).toBe(true);
+ expect(matchesCIDR("192.168.1.255", "192.168.1.0/24")).toBe(true);
+ expect(matchesCIDR("192.168.0.255", "192.168.1.0/24")).toBe(false);
+ expect(matchesCIDR("192.168.2.0", "192.168.1.0/24")).toBe(false);
+ });
+
+ it("treats /32 as a single host", () => {
+ expect(matchesCIDR("10.0.0.1", "10.0.0.1/32")).toBe(true);
+ expect(matchesCIDR("10.0.0.2", "10.0.0.1/32")).toBe(false);
+ });
+
+ it("treats a bare IP pattern as an exact match", () => {
+ expect(matchesCIDR("10.0.0.1", "10.0.0.1")).toBe(true);
+ expect(matchesCIDR("10.0.0.2", "10.0.0.1")).toBe(false);
+ });
+
+ it("matches everything under /0", () => {
+ expect(matchesCIDR("8.8.8.8", "0.0.0.0/0")).toBe(true);
+ expect(matchesCIDR("255.255.255.255", "0.0.0.0/0")).toBe(true);
+ expect(matchesCIDR("2001:db8::1", "::/0")).toBe(true);
+ });
+
+ it("handles a /31 pair", () => {
+ expect(matchesCIDR("10.0.0.0", "10.0.0.0/31")).toBe(true);
+ expect(matchesCIDR("10.0.0.1", "10.0.0.0/31")).toBe(true);
+ expect(matchesCIDR("10.0.0.2", "10.0.0.0/31")).toBe(false);
+ });
+
+ it("ignores host bits set in the pattern", () => {
+ // 192.168.1.5/24 behaves as 192.168.1.0/24.
+ expect(matchesCIDR("192.168.1.9", "192.168.1.5/24")).toBe(true);
+ });
+
+ it("matches IPv6 subnets", () => {
+ expect(matchesCIDR("2001:db8::5", "2001:db8::/32")).toBe(true);
+ expect(matchesCIDR("2001:db9::5", "2001:db8::/32")).toBe(false);
+ expect(matchesCIDR("::1", "::1/128")).toBe(true);
+ expect(matchesCIDR("::2", "::1/128")).toBe(false);
+ });
+
+ it("returns false without throwing when the family of the address and pattern differ", () => {
+ expect(matchesCIDR("192.168.1.1", "2001:db8::/32")).toBe(false);
+ expect(matchesCIDR("2001:db8::1", "192.168.1.0/24")).toBe(false);
+ // An IPv4-mapped IPv6 literal is parsed as IPv6, so an IPv4 CIDR misses it.
+ expect(matchesCIDR("::ffff:192.168.1.5", "192.168.1.0/24")).toBe(false);
+ expect(matchesCIDR("::ffff:192.168.1.5", "::ffff:192.168.1.0/120")).toBe(true);
+ });
+
+ it("returns false for unparseable input on either side", () => {
+ expect(matchesCIDR("", "192.168.1.0/24")).toBe(false);
+ expect(matchesCIDR("192.168.1.1", "")).toBe(false);
+ expect(matchesCIDR("not-an-ip", "192.168.1.0/24")).toBe(false);
+ expect(matchesCIDR("192.168.1.1", "not-a-cidr")).toBe(false);
+ expect(matchesCIDR("999.1.1.1", "192.168.1.0/24")).toBe(false);
+ expect(matchesCIDR("192.168.1.1", "192.168.1.0/33")).toBe(false);
+ expect(matchesCIDR("192.168.1.1", "192.168.1.0/-1")).toBe(false);
+ expect(matchesCIDR(" 192.168.1.1", "192.168.1.0/24")).toBe(false);
+ });
+});
+
+describe("matchesRange", () => {
+ it("matches an address inside the range", () => {
+ expect(matchesRange("192.168.1.5", "192.168.1.1-192.168.1.10")).toBe(true);
+ });
+
+ it("is inclusive of both endpoints and excludes the addresses just outside", () => {
+ expect(matchesRange("192.168.1.1", "192.168.1.1-192.168.1.10")).toBe(true);
+ expect(matchesRange("192.168.1.10", "192.168.1.1-192.168.1.10")).toBe(true);
+ expect(matchesRange("192.168.1.0", "192.168.1.1-192.168.1.10")).toBe(false);
+ expect(matchesRange("192.168.1.11", "192.168.1.1-192.168.1.10")).toBe(false);
+ });
+
+ it("supports a single-address range", () => {
+ expect(matchesRange("10.0.0.5", "10.0.0.5-10.0.0.5")).toBe(true);
+ expect(matchesRange("10.0.0.6", "10.0.0.5-10.0.0.5")).toBe(false);
+ });
+
+ it("never matches a reversed range", () => {
+ expect(matchesRange("192.168.1.5", "192.168.1.10-192.168.1.1")).toBe(false);
+ expect(matchesRange("192.168.1.10", "192.168.1.10-192.168.1.1")).toBe(false);
+ });
+
+ it("compares addresses as unsigned 32-bit integers across the high half of the space", () => {
+ expect(matchesRange("200.0.0.1", "0.0.0.0-255.255.255.255")).toBe(true);
+ expect(matchesRange("128.0.0.1", "127.0.0.0-255.255.255.255")).toBe(true);
+ expect(matchesRange("126.255.255.255", "127.0.0.0-255.255.255.255")).toBe(false);
+ expect(matchesRange("255.255.255.255", "255.255.255.254-255.255.255.255")).toBe(true);
+ // A range that straddles the sign bit must not fold around.
+ expect(matchesRange("10.0.0.1", "127.0.0.0-129.0.0.0")).toBe(false);
+ });
+
+ it("tolerates whitespace around the endpoints", () => {
+ expect(matchesRange("192.168.1.5", " 192.168.1.1 - 192.168.1.10 ")).toBe(true);
+ });
+
+ it("uses only the first two endpoints when extra dashes are present", () => {
+ expect(matchesRange("10.0.0.3", "10.0.0.1-10.0.0.5-10.0.0.9")).toBe(true);
+ expect(matchesRange("10.0.0.7", "10.0.0.1-10.0.0.5-10.0.0.9")).toBe(false);
+ });
+
+ it("returns false for a pattern without a dash", () => {
+ expect(matchesRange("10.0.0.5", "10.0.0.5")).toBe(false);
+ expect(matchesRange("10.0.0.5", "")).toBe(false);
+ });
+
+ it("does not support IPv6 ranges", () => {
+ expect(matchesRange("2001:db8::5", "2001:db8::1-2001:db8::10")).toBe(false);
+ expect(matchesRange("::1", "::0-::ffff")).toBe(false);
+ });
+
+ it("returns false without throwing on mixed families and garbage", () => {
+ expect(matchesRange("2001:db8::5", "192.168.1.1-192.168.1.10")).toBe(false);
+ expect(matchesRange("192.168.1.5", "2001:db8::1-2001:db8::10")).toBe(false);
+ expect(matchesRange("not-an-ip", "192.168.1.1-192.168.1.10")).toBe(false);
+ expect(matchesRange("192.168.1.5", "garbage-garbage")).toBe(false);
+ expect(matchesRange("192.168.1.5", "192.168.1.1-")).toBe(false);
+ expect(matchesRange("192.168.1.5", "-192.168.1.10")).toBe(false);
+ expect(matchesRange(" 192.168.1.5", "192.168.1.1-192.168.1.10")).toBe(false);
+ });
+});
diff --git a/server/src/lib/subscriptionUtils.test.ts b/server/src/lib/subscriptionUtils.test.ts
new file mode 100644
index 000000000..2bb4f7386
--- /dev/null
+++ b/server/src/lib/subscriptionUtils.test.ts
@@ -0,0 +1,869 @@
+import { DateTime } from "luxon";
+import type Stripe from "stripe";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * subscriptionUtils talks to exactly two outside systems: Postgres (plan override,
+ * custom plan, AppSumo licenses) and Stripe. Both are mocked here; everything else β€”
+ * plan resolution, ranking, caching β€” is the module's own logic under test.
+ */
+const state = vi.hoisted(() => ({
+ planOverride: null as string | null,
+ customPlan: null as { events: number; members?: number | null; websites?: number | null } | null,
+ appsumoLicenses: [] as Array<{ tier: string; status: string }>,
+ orgSelectError: null as Error | null,
+ appsumoError: null as Error | null,
+}));
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(),
+ stripeEnabled: true,
+}));
+
+vi.mock("../db/postgres/postgres.js", () => {
+ // Drizzle builders are thenable; both org lookups await `.limit(1)`.
+ function chain(rows: () => unknown[]) {
+ const builder: any = {
+ from: () => builder,
+ where: () => builder,
+ limit: () => builder,
+ then: (resolve: any, reject: any) => {
+ if (state.orgSelectError) {
+ return Promise.reject(state.orgSelectError).then(resolve, reject);
+ }
+ return Promise.resolve(rows()).then(resolve, reject);
+ },
+ };
+ return builder;
+ }
+
+ return {
+ db: {
+ // The two org reads are told apart by the column each one selects.
+ select: (fields: Record<string, unknown>) =>
+ chain(() =>
+ "customPlan" in fields ? [{ customPlan: state.customPlan }] : [{ planOverride: state.planOverride }]
+ ),
+ execute: async () => {
+ if (state.appsumoError) {
+ throw state.appsumoError;
+ }
+ return state.appsumoLicenses;
+ },
+ },
+ };
+});
+
+vi.mock("./stripe.js", () => ({
+ get stripe() {
+ return mocks.stripeEnabled ? { subscriptions: { list: mocks.list } } : null;
+ },
+}));
+
+import { APPSUMO_REPLAY_LIMITS, APPSUMO_TIER_LIMITS, DEFAULT_EVENT_LIMIT, getStripePrices } from "./const.js";
+import {
+ AppSumoSubscriptionInfo,
+ CustomPlanSubscriptionInfo,
+ FreeSubscriptionInfo,
+ getAllStripeSubscriptionsByCustomer,
+ getAppSumoSubscription,
+ getBestSubscription,
+ getBestSubscriptionFromStripeSub,
+ getCustomPlanSubscription,
+ getOverrideSubscription,
+ getReplayLimit,
+ getStripeSubscription,
+ invalidateAllStripeSubscriptionsCache,
+ invalidateStripeSubscriptionCache,
+ OverrideSubscriptionInfo,
+ StripeSubscriptionInfo,
+ stripeSubscriptionInfoFromSnapshot,
+ subscriptionIncludesReplay,
+} from "./subscriptionUtils.js";
+
+function planByName(name: string) {
+ const plan = getStripePrices().find(p => p.name === name);
+ if (!plan) {
+ throw new Error(`No Stripe plan named ${name}`);
+ }
+ return plan;
+}
+
+/** Unique customer id per test so the per-customer cache never leaks between them. */
+let customerCounter = 0;
+function nextCustomer(): string {
+ customerCounter += 1;
+ return `cus_${customerCounter}`;
+}
+
+const HOUR = 3_600;
+
+function stripeSub(
+ overrides: {
+ id?: string;
+ customer?: string;
+ status?: string;
+ created?: number;
+ priceId?: string | undefined;
+ interval?: string | null;
+ cancelAtPeriodEnd?: boolean;
+ trialEnd?: number | null;
+ periodStart?: number;
+ periodEnd?: number;
+ noItems?: boolean;
+ } = {}
+): Stripe.Subscription {
+ const nowSeconds = Math.floor(Date.now() / 1000);
+ const {
+ id = "sub_1",
+ customer = "cus_1",
+ status = "active",
+ created = nowSeconds - 30 * 24 * HOUR,
+ priceId = planByName("pro500k").priceId,
+ interval = "month",
+ cancelAtPeriodEnd = false,
+ trialEnd = null,
+ periodStart = nowSeconds - 5 * 24 * HOUR,
+ periodEnd = nowSeconds + 25 * 24 * HOUR,
+ noItems = false,
+ } = overrides;
+
+ return {
+ id,
+ customer,
+ status,
+ created,
+ cancel_at_period_end: cancelAtPeriodEnd,
+ trial_end: trialEnd,
+ items: {
+ data: noItems
+ ? []
+ : [
+ {
+ current_period_start: periodStart,
+ current_period_end: periodEnd,
+ price: { id: priceId, recurring: interval === null ? null : { interval } },
+ },
+ ],
+ },
+ } as unknown as Stripe.Subscription;
+}
+
+/** Stripe's list() is awaited for per-customer reads and async-iterated for the bulk snapshot. */
+function listReturns(subs: Stripe.Subscription[]) {
+ mocks.list.mockImplementation(() => {
+ const result: any = {
+ data: subs,
+ [Symbol.asyncIterator]: async function* () {
+ for (const sub of subs) {
+ yield sub;
+ }
+ },
+ };
+ return result;
+ });
+}
+
+/** Per-customer reads await list(); this is how a Stripe outage reaches them. */
+function listRejects(message: string) {
+ mocks.list.mockImplementation(() => Promise.reject(new Error(message)));
+}
+
+/** The bulk snapshot iterates list(); a failure surfaces while paginating. */
+function listRejectsWhileIterating(message: string) {
+ mocks.list.mockImplementation(() => ({
+ async *[Symbol.asyncIterator]() {
+ throw new Error(message);
+ },
+ }));
+}
+
+function appsumo(overrides: Partial<AppSumoSubscriptionInfo> = {}): AppSumoSubscriptionInfo {
+ return {
+ source: "appsumo",
+ tier: "4",
+ eventLimit: 500_000,
+ replayLimit: 500,
+ periodStart: "2026-08-01",
+ planName: "appsumo-4",
+ status: "active",
+ interval: "lifetime",
+ cancelAtPeriodEnd: false,
+ ...overrides,
+ };
+}
+
+function override(overrides: Partial<OverrideSubscriptionInfo> = {}): OverrideSubscriptionInfo {
+ return {
+ source: "override",
+ planName: "pro500k",
+ eventLimit: 500_000,
+ replayLimit: 50_000,
+ periodStart: "2026-08-01",
+ status: "active",
+ interval: "month",
+ cancelAtPeriodEnd: false,
+ ...overrides,
+ };
+}
+
+function stripeInfo(overrides: Partial<StripeSubscriptionInfo> = {}): StripeSubscriptionInfo {
+ return {
+ source: "stripe",
+ subscriptionId: "sub_1",
+ priceId: "price_1",
+ planName: "pro500k",
+ eventLimit: 500_000,
+ replayLimit: 50_000,
+ periodStart: "2026-08-01",
+ currentPeriodEnd: new Date("2026-09-01T00:00:00Z"),
+ status: "active",
+ interval: "month",
+ cancelAtPeriodEnd: false,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ ...overrides,
+ };
+}
+
+function custom(overrides: Partial<CustomPlanSubscriptionInfo> = {}): CustomPlanSubscriptionInfo {
+ return {
+ source: "custom",
+ planName: "custom",
+ eventLimit: 10_000_000,
+ memberLimit: null,
+ siteLimit: null,
+ periodStart: "2026-08-01",
+ status: "active",
+ interval: "lifetime",
+ cancelAtPeriodEnd: false,
+ ...overrides,
+ };
+}
+
+function free(): FreeSubscriptionInfo {
+ return {
+ source: "free",
+ eventLimit: DEFAULT_EVENT_LIMIT,
+ periodStart: "2026-08-01",
+ planName: "free",
+ status: "free",
+ };
+}
+
+beforeEach(() => {
+ state.planOverride = null;
+ state.customPlan = null;
+ state.appsumoLicenses = [];
+ state.orgSelectError = null;
+ state.appsumoError = null;
+ mocks.stripeEnabled = true;
+ mocks.list.mockReset();
+ listReturns([]);
+ invalidateAllStripeSubscriptionsCache();
+ // These modules log expected failures through console.error; keep test output readable.
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe("subscriptionIncludesReplay", () => {
+ it("includes replay on every custom (enterprise) plan", () => {
+ expect(subscriptionIncludesReplay(custom())).toBe(true);
+ });
+
+ it("gates Stripe plans on the plan name containing 'pro'", () => {
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "pro100k" }))).toBe(true);
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "pro1m-annual" }))).toBe(true);
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "standard500k" }))).toBe(false);
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "basic100k" }))).toBe(false);
+ // Replay quota carried by a non-pro plan is a volume number, not an entitlement.
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "standard500k", replayLimit: 50_000 }))).toBe(false);
+ });
+
+ it("excludes trials at or above the 500k event tier, and only those", () => {
+ const trial = (eventLimit: number) => stripeInfo({ planName: "pro500k", status: "trialing", eventLimit });
+
+ expect(subscriptionIncludesReplay(trial(500_000))).toBe(false);
+ expect(subscriptionIncludesReplay(trial(500_001))).toBe(false);
+ expect(subscriptionIncludesReplay(trial(499_999))).toBe(true);
+ // The exclusion is trial-only: the same plan, paid, keeps replay.
+ expect(subscriptionIncludesReplay(stripeInfo({ planName: "pro500k", status: "active", eventLimit: 500_000 }))).toBe(
+ true
+ );
+ });
+
+ it("gives AppSumo tiers replay exactly when their tier carries a quota", () => {
+ for (const [tier, replayLimit] of Object.entries(APPSUMO_REPLAY_LIMITS)) {
+ expect(subscriptionIncludesReplay(appsumo({ tier, planName: `appsumo-${tier}`, replayLimit }))).toBe(
+ replayLimit > 0
+ );
+ }
+ });
+
+ it("routes AppSumo overrides by quota and Stripe-plan overrides by name", () => {
+ expect(subscriptionIncludesReplay(override({ planName: "appsumo-4", replayLimit: 500 }))).toBe(true);
+ expect(subscriptionIncludesReplay(override({ planName: "appsumo-1", replayLimit: 0 }))).toBe(false);
+ expect(subscriptionIncludesReplay(override({ planName: "pro500k" }))).toBe(true);
+ // A Stripe-plan override ignores its replay quota, exactly like a real Stripe plan.
+ expect(subscriptionIncludesReplay(override({ planName: "standard500k", replayLimit: 50_000 }))).toBe(false);
+ });
+
+ it("never includes replay on the free tier", () => {
+ expect(subscriptionIncludesReplay(free())).toBe(false);
+ });
+});
+
+describe("getReplayLimit", () => {
+ it("treats custom plans as uncapped", () => {
+ expect(getReplayLimit(custom())).toBe(Infinity);
+ });
+
+ it("reports the plan's own quota for stripe, override and appsumo plans", () => {
+ expect(getReplayLimit(stripeInfo({ replayLimit: 50_000 }))).toBe(50_000);
+ expect(getReplayLimit(override({ replayLimit: 500 }))).toBe(500);
+ expect(getReplayLimit(appsumo({ replayLimit: 1_000 }))).toBe(1_000);
+ });
+
+ it("reports zero for the free tier", () => {
+ expect(getReplayLimit(free())).toBe(0);
+ });
+
+ it("reports zero for plans that carry replay quota but no entitlement", () => {
+ // getReplayLimit is only meaningful alongside subscriptionIncludesReplay; an
+ // AppSumo tier without replay reports 0 on both.
+ const tier1 = appsumo({ tier: "1", planName: "appsumo-1", replayLimit: 0 });
+ expect(subscriptionIncludesReplay(tier1)).toBe(false);
+ expect(getReplayLimit(tier1)).toBe(0);
+ });
+});
+
+describe("getStripeSubscription", () => {
+ it("returns null without touching Stripe when the org has no customer id", async () => {
+ await expect(getStripeSubscription(null)).resolves.toBeNull();
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+ it("builds subscription info from the plan matching the price id", async () => {
+ const plan = planByName("pro500k");
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, priceId: plan.priceId })]);
+
+ const info = await getStripeSubscription(customer);
+
+ expect(info).toMatchObject({
+ source: "stripe",
+ planName: plan.name,
+ eventLimit: plan.limits.events,
+ replayLimit: plan.limits.replays,
+ status: "active",
+ interval: "month",
+ cancelAtPeriodEnd: false,
+ });
+ });
+
+ it("ignores canceled and past_due subscriptions and picks the newest active/trialing one", async () => {
+ const customer = nextCustomer();
+ const now = Math.floor(Date.now() / 1000);
+ listReturns([
+ stripeSub({ id: "sub_canceled", customer, status: "canceled", created: now }),
+ stripeSub({ id: "sub_past_due", customer, status: "past_due", created: now }),
+ stripeSub({ id: "sub_old", customer, status: "active", created: now - 1000 }),
+ stripeSub({ id: "sub_new", customer, status: "trialing", created: now - 10, trialEnd: now + 1000 }),
+ ]);
+
+ const info = await getStripeSubscription(customer);
+
+ expect(info?.subscriptionId).toBe("sub_new");
+ expect(info?.trialEnd).toEqual(new Date((now + 1000) * 1000));
+ });
+
+ it("returns null when the customer has no active or trialing subscription", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, status: "canceled" })]);
+
+ await expect(getStripeSubscription(customer)).resolves.toBeNull();
+ });
+
+ it("falls back to placeholder plan details for an unmapped price id", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, priceId: "price_not_in_our_catalog" })]);
+
+ const info = await getStripeSubscription(customer);
+
+ expect(info).toMatchObject({ planName: "Unknown Plan", eventLimit: 0, replayLimit: 0 });
+ });
+
+ it("returns null when the subscription carries no price", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, noItems: true })]);
+
+ await expect(getStripeSubscription(customer)).resolves.toBeNull();
+ });
+
+ it("reports 'unknown' interval for a price with no recurring block", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, interval: null })]);
+
+ await expect(getStripeSubscription(customer)).resolves.toMatchObject({ interval: "unknown" });
+ });
+
+ it("uses the subscription's own start date as periodStart when the period began this month", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 7, 20, 12));
+ const startedThisMonth = DateTime.local(2026, 8, 5, 9);
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, periodStart: Math.floor(startedThisMonth.toMillis() / 1000) })]);
+
+ const info = await getStripeSubscription(customer);
+
+ expect(info?.periodStart).toBe(startedThisMonth.toISODate());
+ });
+
+ it("falls back to the start of the month when the period began earlier", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 7, 20, 12));
+ const startedLastMonth = DateTime.local(2026, 7, 5, 9);
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, periodStart: Math.floor(startedLastMonth.toMillis() / 1000) })]);
+
+ const info = await getStripeSubscription(customer);
+
+ expect(info?.periodStart).toBe(DateTime.local(2026, 8, 1).toISODate());
+ });
+});
+
+describe("getStripeSubscription caching", () => {
+ it("serves repeat reads for the same customer from cache", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer })]);
+
+ await getStripeSubscription(customer);
+ await getStripeSubscription(customer);
+
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ });
+
+ it("caches a negative result too, so free orgs do not re-query Stripe", async () => {
+ const customer = nextCustomer();
+ listReturns([]);
+
+ await expect(getStripeSubscription(customer)).resolves.toBeNull();
+ await expect(getStripeSubscription(customer)).resolves.toBeNull();
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ });
+
+ it("refetches after invalidation, so a plan change is visible immediately", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, priceId: planByName("standard100k").priceId })]);
+ await getStripeSubscription(customer);
+
+ invalidateStripeSubscriptionCache(customer);
+ listReturns([stripeSub({ customer, priceId: planByName("pro1m").priceId })]);
+
+ await expect(getStripeSubscription(customer)).resolves.toMatchObject({ planName: "pro1m" });
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+ });
+
+ it("leaves other customers' cache entries alone when one is invalidated", async () => {
+ const kept = nextCustomer();
+ const dropped = nextCustomer();
+ listReturns([stripeSub({ customer: kept }), stripeSub({ customer: dropped })]);
+ await getStripeSubscription(kept);
+ await getStripeSubscription(dropped);
+
+ invalidateStripeSubscriptionCache(dropped);
+
+ await getStripeSubscription(kept);
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+
+ await getStripeSubscription(dropped);
+ expect(mocks.list).toHaveBeenCalledTimes(3);
+ });
+
+ it("tolerates a null customer id being invalidated", async () => {
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer })]);
+ await getStripeSubscription(customer);
+
+ invalidateStripeSubscriptionCache(null);
+
+ await getStripeSubscription(customer);
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ });
+
+ it("refetches once the 60s TTL has elapsed", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 7, 20, 12, 0, 0));
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer })]);
+ await getStripeSubscription(customer);
+
+ vi.setSystemTime(new Date(2026, 7, 20, 12, 0, 59));
+ await getStripeSubscription(customer);
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+
+ vi.setSystemTime(new Date(2026, 7, 20, 12, 1, 1));
+ await getStripeSubscription(customer);
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+ });
+
+ it("prefers a stale cached value over downgrading a paying customer on a Stripe failure", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 7, 20, 12, 0, 0));
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer, priceId: planByName("pro1m").priceId })]);
+ await getStripeSubscription(customer);
+
+ vi.setSystemTime(new Date(2026, 7, 20, 12, 5, 0));
+ listRejects("stripe is down");
+
+ // Even with throwOnError, a cached value wins over the error.
+ await expect(getStripeSubscription(customer, { throwOnError: true })).resolves.toMatchObject({
+ planName: "pro1m",
+ });
+ });
+
+ it("returns null on a Stripe failure with nothing cached, or throws when the caller opts in", async () => {
+ const customer = nextCustomer();
+ listRejects("stripe is down");
+
+ await expect(getStripeSubscription(customer, { throwOnError: true })).rejects.toThrow("stripe is down");
+ await expect(getStripeSubscription(nextCustomer())).resolves.toBeNull();
+ });
+});
+
+describe("getAllStripeSubscriptionsByCustomer", () => {
+ it("returns an empty map when Stripe is not configured", async () => {
+ mocks.stripeEnabled = false;
+
+ await expect(getAllStripeSubscriptionsByCustomer()).resolves.toEqual(new Map());
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+ it("prefers an active subscription over a canceled one created later", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ listReturns([
+ stripeSub({ id: "sub_active_old", customer: "cus_rank", status: "active", created: now - 100_000 }),
+ stripeSub({ id: "sub_canceled_new", customer: "cus_rank", status: "canceled", created: now }),
+ ]);
+
+ const snapshot = await getAllStripeSubscriptionsByCustomer();
+
+ expect(snapshot.get("cus_rank")?.id).toBe("sub_active_old");
+ });
+
+ it("prefers trialing over canceled, and the newest among equally active ones", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ listReturns([
+ stripeSub({ id: "sub_canceled", customer: "cus_a", status: "canceled", created: now }),
+ stripeSub({ id: "sub_trialing", customer: "cus_a", status: "trialing", created: now - 50_000 }),
+ stripeSub({ id: "sub_b_old", customer: "cus_b", status: "active", created: now - 10 }),
+ stripeSub({ id: "sub_b_new", customer: "cus_b", status: "active", created: now }),
+ ]);
+
+ const snapshot = await getAllStripeSubscriptionsByCustomer();
+
+ expect(snapshot.get("cus_a")?.id).toBe("sub_trialing");
+ expect(snapshot.get("cus_b")?.id).toBe("sub_b_new");
+ });
+
+ it("keeps the newest of several non-active subscriptions when no active one exists", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ listReturns([
+ stripeSub({ id: "sub_older", customer: "cus_c", status: "canceled", created: now - 5_000 }),
+ stripeSub({ id: "sub_newer", customer: "cus_c", status: "past_due", created: now }),
+ ]);
+
+ const snapshot = await getAllStripeSubscriptionsByCustomer();
+
+ expect(snapshot.get("cus_c")?.id).toBe("sub_newer");
+ });
+
+ it("resolves a customer object rather than a bare id", async () => {
+ const sub = stripeSub({ id: "sub_obj" });
+ (sub as any).customer = { id: "cus_object", object: "customer" };
+ listReturns([sub]);
+
+ const snapshot = await getAllStripeSubscriptionsByCustomer();
+
+ expect(snapshot.get("cus_object")?.id).toBe("sub_obj");
+ });
+
+ it("caches the account-wide snapshot until it is invalidated", async () => {
+ listReturns([stripeSub({ customer: "cus_snap" })]);
+
+ await getAllStripeSubscriptionsByCustomer();
+ await getAllStripeSubscriptionsByCustomer();
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+
+ invalidateAllStripeSubscriptionsCache();
+ await getAllStripeSubscriptionsByCustomer();
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+ });
+
+ it("is also dropped by a per-customer invalidation, so admin reads see the change", async () => {
+ listReturns([stripeSub({ customer: "cus_snap2" })]);
+ await getAllStripeSubscriptionsByCustomer();
+
+ invalidateStripeSubscriptionCache("cus_snap2");
+ await getAllStripeSubscriptionsByCustomer();
+
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+ });
+
+ it("collapses concurrent refreshes into a single pagination", async () => {
+ listReturns([stripeSub({ customer: "cus_concurrent" })]);
+
+ const [a, b, c] = await Promise.all([
+ getAllStripeSubscriptionsByCustomer(),
+ getAllStripeSubscriptionsByCustomer(),
+ getAllStripeSubscriptionsByCustomer(),
+ ]);
+
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ expect(a).toBe(b);
+ expect(b).toBe(c);
+ });
+
+ it("clears the in-flight guard when pagination fails, so the next call retries", async () => {
+ listRejectsWhileIterating("stripe is down");
+ await expect(getAllStripeSubscriptionsByCustomer()).rejects.toThrow("stripe is down");
+
+ listReturns([stripeSub({ customer: "cus_retry" })]);
+ const snapshot = await getAllStripeSubscriptionsByCustomer();
+
+ expect(snapshot.get("cus_retry")).toBeDefined();
+ });
+});
+
+describe("stripeSubscriptionInfoFromSnapshot", () => {
+ it("resolves an active subscription to the same shape as a direct lookup", () => {
+ const plan = planByName("pro500k");
+ const snapshot = new Map([["cus_x", stripeSub({ customer: "cus_x", priceId: plan.priceId })]]);
+
+ expect(stripeSubscriptionInfoFromSnapshot(snapshot, "cus_x")).toMatchObject({
+ source: "stripe",
+ planName: plan.name,
+ eventLimit: plan.limits.events,
+ });
+ });
+
+ it("treats canceled and past_due subscriptions as no subscription at all", () => {
+ for (const status of ["canceled", "past_due", "incomplete", "unpaid"]) {
+ const snapshot = new Map([["cus_x", stripeSub({ customer: "cus_x", status })]]);
+ expect(stripeSubscriptionInfoFromSnapshot(snapshot, "cus_x")).toBeNull();
+ }
+ });
+
+ it("returns null for a missing customer id or a customer absent from the snapshot", () => {
+ const snapshot = new Map([["cus_x", stripeSub({ customer: "cus_x" })]]);
+
+ expect(stripeSubscriptionInfoFromSnapshot(snapshot, null)).toBeNull();
+ expect(stripeSubscriptionInfoFromSnapshot(snapshot, "cus_absent")).toBeNull();
+ });
+});
+
+describe("getOverrideSubscription", () => {
+ it("returns null when the organization has no override", async () => {
+ await expect(getOverrideSubscription("org_1")).resolves.toBeNull();
+ });
+
+ it("maps an appsumo tier override to that tier's event and replay limits", async () => {
+ state.planOverride = "appsumo-5";
+
+ await expect(getOverrideSubscription("org_1")).resolves.toMatchObject({
+ source: "override",
+ planName: "appsumo-5",
+ eventLimit: APPSUMO_TIER_LIMITS["5"],
+ replayLimit: APPSUMO_REPLAY_LIMITS["5"],
+ interval: "lifetime",
+ status: "active",
+ });
+ });
+
+ it("maps a Stripe plan override to that plan's limits and interval", async () => {
+ const plan = planByName("standard250k");
+ state.planOverride = plan.name;
+
+ await expect(getOverrideSubscription("org_1")).resolves.toMatchObject({
+ planName: plan.name,
+ eventLimit: plan.limits.events,
+ replayLimit: plan.limits.replays,
+ interval: plan.interval,
+ });
+ });
+
+ it("rejects an override naming no known plan, including out-of-range appsumo tiers", async () => {
+ for (const planOverride of ["not-a-plan", "appsumo-0", "appsumo-8", "appsumo-12"]) {
+ state.planOverride = planOverride;
+ await expect(getOverrideSubscription("org_1")).resolves.toBeNull();
+ }
+ });
+
+ it("returns null instead of throwing when the lookup fails", async () => {
+ state.orgSelectError = new Error("pg down");
+
+ await expect(getOverrideSubscription("org_1")).resolves.toBeNull();
+ });
+});
+
+describe("getCustomPlanSubscription", () => {
+ it("returns null when the organization has no custom plan", async () => {
+ await expect(getCustomPlanSubscription("org_1")).resolves.toBeNull();
+ });
+
+ it("maps the stored plan, treating missing member/site caps as unlimited", async () => {
+ state.customPlan = { events: 25_000_000 };
+
+ await expect(getCustomPlanSubscription("org_1")).resolves.toEqual({
+ source: "custom",
+ planName: "custom",
+ eventLimit: 25_000_000,
+ memberLimit: null,
+ siteLimit: null,
+ periodStart: DateTime.now().startOf("month").toISODate(),
+ status: "active",
+ interval: "lifetime",
+ cancelAtPeriodEnd: false,
+ });
+ });
+
+ it("carries explicit member and site caps through", async () => {
+ state.customPlan = { events: 1_000_000, members: 7, websites: 12 };
+
+ await expect(getCustomPlanSubscription("org_1")).resolves.toMatchObject({ memberLimit: 7, siteLimit: 12 });
+ });
+
+ it("returns null instead of throwing when the lookup fails", async () => {
+ state.orgSelectError = new Error("pg down");
+
+ await expect(getCustomPlanSubscription("org_1")).resolves.toBeNull();
+ });
+});
+
+describe("getAppSumoSubscription", () => {
+ it("maps an active license to its tier limits", async () => {
+ state.appsumoLicenses = [{ tier: "6", status: "active" }];
+
+ await expect(getAppSumoSubscription("org_1")).resolves.toMatchObject({
+ source: "appsumo",
+ tier: "6",
+ planName: "appsumo-6",
+ eventLimit: APPSUMO_TIER_LIMITS["6"],
+ replayLimit: APPSUMO_REPLAY_LIMITS["6"],
+ });
+ });
+
+ it("falls back to tier 1 limits (and no replay) for an unrecognized tier", async () => {
+ state.appsumoLicenses = [{ tier: "99", status: "active" }];
+
+ await expect(getAppSumoSubscription("org_1")).resolves.toMatchObject({
+ planName: "appsumo-99",
+ eventLimit: APPSUMO_TIER_LIMITS["1"],
+ replayLimit: 0,
+ });
+ });
+
+ it("returns null when there is no license", async () => {
+ await expect(getAppSumoSubscription("org_1")).resolves.toBeNull();
+ });
+
+ it("returns null instead of throwing when the lookup fails", async () => {
+ state.appsumoError = new Error("appsumo schema missing");
+
+ await expect(getAppSumoSubscription("org_1")).resolves.toBeNull();
+ });
+});
+
+describe("getBestSubscription priority", () => {
+ it("puts a custom plan above every other source", async () => {
+ state.customPlan = { events: 9_000_000 };
+ state.planOverride = "appsumo-7";
+ state.appsumoLicenses = [{ tier: "7", status: "active" }];
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer })]);
+
+ await expect(getBestSubscription("org_1", customer)).resolves.toMatchObject({ source: "custom" });
+ });
+
+ it("puts an override above Stripe and AppSumo", async () => {
+ state.planOverride = "standard1m";
+ state.appsumoLicenses = [{ tier: "7", status: "active" }];
+ const customer = nextCustomer();
+ listReturns([stripeSub({ customer })]);
+
+ await expect(getBestSubscription("org_1", customer)).resolves.toMatchObject({
+ source: "override",
+ planName: "standard1m",
+ });
+ });
+
+ it("prefers Stripe over AppSumo even when the AppSumo tier allows more events", async () => {
+ // Pinned current behavior: despite the "highest limit" wording in the doc comment,
+ // any active Stripe subscription wins outright over an AppSumo license.
+ state.appsumoLicenses = [{ tier: "7", status: "active" }];
+ const customer = nextCustomer();
+ const smallPlan = planByName("standard100k");
+ listReturns([stripeSub({ customer, priceId: smallPlan.priceId })]);
+
+ const best = await getBestSubscription("org_1", customer);
+
+ expect(best).toMatchObject({ source: "stripe", eventLimit: smallPlan.limits.events });
+ expect(best.eventLimit).toBeLessThan(APPSUMO_TIER_LIMITS["7"]);
+ });
+
+ it("falls back to AppSumo when there is no Stripe subscription", async () => {
+ state.appsumoLicenses = [{ tier: "2", status: "active" }];
+
+ await expect(getBestSubscription("org_1", nextCustomer())).resolves.toMatchObject({
+ source: "appsumo",
+ eventLimit: APPSUMO_TIER_LIMITS["2"],
+ });
+ });
+
+ it("falls back to the free tier when nothing else applies", async () => {
+ await expect(getBestSubscription("org_1", null)).resolves.toEqual({
+ source: "free",
+ planName: "free",
+ status: "free",
+ eventLimit: DEFAULT_EVENT_LIMIT,
+ periodStart: DateTime.now().startOf("month").toISODate(),
+ });
+ });
+
+ it("propagates a Stripe failure when the caller opts in rather than downgrading to free", async () => {
+ listRejects("stripe is down");
+
+ await expect(getBestSubscription("org_1", nextCustomer(), { throwOnStripeError: true })).rejects.toThrow(
+ "stripe is down"
+ );
+ await expect(getBestSubscription("org_1", nextCustomer())).resolves.toMatchObject({ source: "free" });
+ });
+});
+
+describe("getBestSubscriptionFromStripeSub", () => {
+ it("applies the same custom > override > stripe > appsumo > free order without calling Stripe", async () => {
+ const resolved = stripeInfo();
+
+ state.customPlan = { events: 5_000_000 };
+ await expect(getBestSubscriptionFromStripeSub("org_1", resolved)).resolves.toMatchObject({ source: "custom" });
+
+ state.customPlan = null;
+ state.planOverride = "pro1m";
+ await expect(getBestSubscriptionFromStripeSub("org_1", resolved)).resolves.toMatchObject({ source: "override" });
+
+ state.planOverride = null;
+ state.appsumoLicenses = [{ tier: "7", status: "active" }];
+ await expect(getBestSubscriptionFromStripeSub("org_1", resolved)).resolves.toMatchObject({ source: "stripe" });
+
+ await expect(getBestSubscriptionFromStripeSub("org_1", null)).resolves.toMatchObject({ source: "appsumo" });
+
+ state.appsumoLicenses = [];
+ await expect(getBestSubscriptionFromStripeSub("org_1", null)).resolves.toMatchObject({ source: "free" });
+
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/services/admin/subscriptionService.test.ts b/server/src/services/admin/subscriptionService.test.ts
new file mode 100644
index 000000000..b20d6c41b
--- /dev/null
+++ b/server/src/services/admin/subscriptionService.test.ts
@@ -0,0 +1,364 @@
+import { DateTime } from "luxon";
+import type Stripe from "stripe";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * The admin org list resolves every organization's plan from one cached account-wide
+ * Stripe snapshot plus the AppSumo license table. What matters here is which source wins
+ * per org, and that a failure on either side degrades to "free" instead of failing the page.
+ */
+const state = vi.hoisted(() => ({
+ /** Rows returned by the AppSumo license query, one batch at a time. */
+ licenses: [] as Array<{ organization_id: string; tier: string }>,
+ licenseQueryError: null as Error | null,
+ /** Number of licence queries issued β€” the loop batches at 1000 org ids. */
+ licenseQueries: 0,
+ stripeEnabled: true,
+}));
+
+const mocks = vi.hoisted(() => ({
+ getAllStripeSubscriptionsByCustomer: vi.fn(),
+}));
+
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {
+ execute: async () => {
+ state.licenseQueries += 1;
+ if (state.licenseQueryError) {
+ throw state.licenseQueryError;
+ }
+ return state.licenses;
+ },
+ },
+}));
+
+vi.mock("../../lib/stripe.js", () => ({
+ get stripe() {
+ return state.stripeEnabled ? {} : null;
+ },
+}));
+
+vi.mock("../../lib/subscriptionUtils.js", () => ({
+ getAllStripeSubscriptionsByCustomer: mocks.getAllStripeSubscriptionsByCustomer,
+}));
+
+import { APPSUMO_TIER_LIMITS, DEFAULT_EVENT_LIMIT, getStripePrices } from "../../lib/const.js";
+import { getOrganizationSubscriptions } from "./subscriptionService.js";
+
+function planByName(name: string) {
+ const plan = getStripePrices().find(p => p.name === name);
+ if (!plan) {
+ throw new Error(`No Stripe plan named ${name}`);
+ }
+ return plan;
+}
+
+const HOUR = 3_600;
+
+function stripeSub(
+ overrides: {
+ id?: string;
+ status?: string;
+ priceId?: string;
+ interval?: string | null;
+ cancelAtPeriodEnd?: boolean;
+ periodStart?: number;
+ periodEnd?: number;
+ noItems?: boolean;
+ } = {}
+): Stripe.Subscription {
+ const nowSeconds = Math.floor(Date.now() / 1000);
+ const {
+ id = "sub_1",
+ status = "active",
+ priceId = planByName("pro500k").priceId,
+ interval = "month",
+ cancelAtPeriodEnd = false,
+ periodStart = nowSeconds - 5 * 24 * HOUR,
+ periodEnd = nowSeconds + 25 * 24 * HOUR,
+ noItems = false,
+ } = overrides;
+
+ return {
+ id,
+ status,
+ cancel_at_period_end: cancelAtPeriodEnd,
+ items: {
+ data: noItems
+ ? []
+ : [
+ {
+ current_period_start: periodStart,
+ current_period_end: periodEnd,
+ price: { id: priceId, recurring: interval === null ? null : { interval } },
+ },
+ ],
+ },
+ } as unknown as Stripe.Subscription;
+}
+
+function snapshot(entries: Record<string, Stripe.Subscription>) {
+ mocks.getAllStripeSubscriptionsByCustomer.mockResolvedValue(new Map(Object.entries(entries)));
+}
+
+const nextMonthStart = () => DateTime.now().startOf("month").plus({ months: 1 }).toJSDate();
+
+beforeEach(() => {
+ state.licenses = [];
+ state.licenseQueryError = null;
+ state.licenseQueries = 0;
+ state.stripeEnabled = true;
+ mocks.getAllStripeSubscriptionsByCustomer.mockReset();
+ mocks.getAllStripeSubscriptionsByCustomer.mockResolvedValue(new Map());
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+describe("getOrganizationSubscriptions β€” free fallback", () => {
+ it("returns the free plan for an org with neither Stripe nor AppSumo", async () => {
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: null }]);
+
+ expect(result.get("org_1")).toEqual({
+ id: "",
+ planName: "free",
+ status: "free",
+ eventLimit: DEFAULT_EVENT_LIMIT,
+ currentPeriodEnd: nextMonthStart(),
+ });
+ });
+
+ it("returns a row for every organization, including ones absent from Stripe", async () => {
+ snapshot({ cus_1: stripeSub() });
+
+ const result = await getOrganizationSubscriptions(
+ [{ id: "org_1", stripeCustomerId: "cus_1" }, { id: "org_2", stripeCustomerId: "cus_missing" }, { id: "org_3" }],
+ true
+ );
+
+ expect(result.size).toBe(3);
+ expect(result.get("org_2")?.planName).toBe("free");
+ expect(result.get("org_3")?.planName).toBe("free");
+ });
+
+ it("does not query Stripe at all when it is not configured", async () => {
+ state.stripeEnabled = false;
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }]);
+
+ expect(mocks.getAllStripeSubscriptionsByCustomer).not.toHaveBeenCalled();
+ expect(result.get("org_1")?.planName).toBe("free");
+ });
+
+ it("degrades every org to free when the bulk Stripe fetch fails, instead of failing the page", async () => {
+ mocks.getAllStripeSubscriptionsByCustomer.mockRejectedValue(new Error("stripe rate limit"));
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({ planName: "free", status: "free" });
+ });
+});
+
+describe("getOrganizationSubscriptions β€” Stripe plans", () => {
+ it("keeps non-active subscriptions so the admin view can show them", async () => {
+ snapshot({ cus_1: stripeSub({ status: "past_due" }) });
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({ planName: "pro500k", status: "past_due" });
+ });
+
+ it("adds periods, interval and event limit only when full details are requested", async () => {
+ const plan = planByName("standard250k");
+ const periodEnd = Math.floor(Date.now() / 1000) + 10 * 24 * HOUR;
+ snapshot({ cus_1: stripeSub({ priceId: plan.priceId, periodEnd, cancelAtPeriodEnd: true }) });
+
+ const withDetails = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+ expect(withDetails.get("org_1")).toMatchObject({
+ planName: plan.name,
+ eventLimit: plan.limits.events,
+ interval: "month",
+ cancelAtPeriodEnd: true,
+ currentPeriodEnd: new Date(periodEnd * 1000),
+ });
+
+ const summary = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], false);
+ const row = summary.get("org_1")!;
+ expect(row.planName).toBe(plan.name);
+ expect(row.interval).toBeUndefined();
+ expect(row.cancelAtPeriodEnd).toBeUndefined();
+ // Pinned current behavior: without full details the caller still gets the required
+ // eventLimit/currentPeriodEnd fields, filled with placeholders rather than real values.
+ expect(row.eventLimit).toBe(0);
+ expect(row.currentPeriodEnd).toBeInstanceOf(Date);
+ });
+
+ it("labels an unmapped price id as an unknown plan with a zero limit", async () => {
+ snapshot({ cus_1: stripeSub({ priceId: "price_not_in_our_catalog" }) });
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({ planName: "Unknown Plan", eventLimit: 0 });
+ });
+
+ it("falls back to free when the subscription carries no price", async () => {
+ snapshot({ cus_1: stripeSub({ noItems: true }) });
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({ planName: "free", eventLimit: DEFAULT_EVENT_LIMIT });
+ });
+
+ it("reports 'unknown' interval for a price with no recurring block", async () => {
+ snapshot({ cus_1: stripeSub({ interval: null }) });
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")?.interval).toBe("unknown");
+ });
+});
+
+describe("getOrganizationSubscriptions β€” AppSumo licenses", () => {
+ it("maps an active license to its tier limits and a lifetime period", async () => {
+ state.licenses = [{ organization_id: "org_1", tier: "3" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: null }], true);
+
+ expect(result.get("org_1")).toEqual({
+ id: "",
+ planName: "appsumo-3",
+ status: "active",
+ eventLimit: APPSUMO_TIER_LIMITS["3"],
+ currentPeriodEnd: nextMonthStart(),
+ currentPeriodStart: DateTime.now().startOf("month").toJSDate(),
+ cancelAtPeriodEnd: false,
+ interval: "lifetime",
+ });
+ });
+
+ it("omits the lifetime detail fields in summary mode", async () => {
+ state.licenses = [{ organization_id: "org_1", tier: "3" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: null }]);
+
+ expect(result.get("org_1")).toEqual({
+ id: "",
+ planName: "appsumo-3",
+ status: "active",
+ eventLimit: APPSUMO_TIER_LIMITS["3"],
+ currentPeriodEnd: nextMonthStart(),
+ });
+ });
+
+ it("falls back to tier 1 limits for an unrecognized tier", async () => {
+ state.licenses = [{ organization_id: "org_1", tier: "99" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: null }]);
+
+ expect(result.get("org_1")).toMatchObject({
+ planName: "appsumo-99",
+ eventLimit: APPSUMO_TIER_LIMITS["1"],
+ });
+ });
+
+ it("degrades to free when the license query fails", async () => {
+ state.licenseQueryError = new Error("appsumo schema missing");
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: null }]);
+
+ expect(result.get("org_1")?.planName).toBe("free");
+ });
+
+ it("batches the license lookup at 1000 organization ids", async () => {
+ const organizations = Array.from({ length: 2_001 }, (_, i) => ({ id: `org_${i}`, stripeCustomerId: null }));
+
+ await getOrganizationSubscriptions(organizations);
+
+ expect(state.licenseQueries).toBe(3);
+ });
+
+ it("skips the license lookup entirely when there are no organizations", async () => {
+ const result = await getOrganizationSubscriptions([]);
+
+ expect(result.size).toBe(0);
+ expect(state.licenseQueries).toBe(0);
+ });
+});
+
+describe("getOrganizationSubscriptions β€” Stripe versus AppSumo", () => {
+ it("prefers the Stripe plan when it allows at least as many events", async () => {
+ const plan = planByName("pro1m");
+ snapshot({ cus_1: stripeSub({ priceId: plan.priceId }) });
+ state.licenses = [{ organization_id: "org_1", tier: "1" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({ planName: plan.name, eventLimit: plan.limits.events });
+ });
+
+ it("prefers the AppSumo license when it allows more events", async () => {
+ const plan = planByName("standard100k");
+ snapshot({ cus_1: stripeSub({ priceId: plan.priceId }) });
+ state.licenses = [{ organization_id: "org_1", tier: "7" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")).toMatchObject({
+ planName: "appsumo-7",
+ eventLimit: APPSUMO_TIER_LIMITS["7"],
+ });
+ });
+
+ it("keeps the Stripe plan on an exact tie", async () => {
+ // standard500k and AppSumo tier 4 both allow 500k events.
+ const plan = planByName("standard500k");
+ expect(plan.limits.events).toBe(APPSUMO_TIER_LIMITS["4"]);
+ snapshot({ cus_1: stripeSub({ priceId: plan.priceId }) });
+ state.licenses = [{ organization_id: "org_1", tier: "4" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], true);
+
+ expect(result.get("org_1")?.planName).toBe(plan.name);
+ });
+
+ it("lets any AppSumo license win in summary mode, where Stripe limits are not resolved", async () => {
+ // Pinned current behavior: without full details the Stripe row has no eventLimit, so it
+ // compares as 0 and even the smallest AppSumo tier outranks a large Stripe plan.
+ snapshot({ cus_1: stripeSub({ priceId: planByName("pro10m").priceId }) });
+ state.licenses = [{ organization_id: "org_1", tier: "1" }];
+
+ const result = await getOrganizationSubscriptions([{ id: "org_1", stripeCustomerId: "cus_1" }], false);
+
+ expect(result.get("org_1")).toMatchObject({ planName: "appsumo-1" });
+ });
+
+ it("resolves each organization independently", async () => {
+ snapshot({ cus_1: stripeSub({ priceId: planByName("pro1m").priceId }) });
+ state.licenses = [{ organization_id: "org_2", tier: "5" }];
+
+ const result = await getOrganizationSubscriptions(
+ [
+ { id: "org_1", stripeCustomerId: "cus_1" },
+ { id: "org_2", stripeCustomerId: null },
+ { id: "org_3", stripeCustomerId: null },
+ ],
+ true
+ );
+
+ expect(result.get("org_1")?.planName).toBe("pro1m");
+ expect(result.get("org_2")?.planName).toBe("appsumo-5");
+ expect(result.get("org_3")?.planName).toBe("free");
+ });
+
+ it("shares one Stripe snapshot across every organization on the page", async () => {
+ snapshot({ cus_1: stripeSub(), cus_2: stripeSub({ id: "sub_2" }) });
+
+ await getOrganizationSubscriptions(
+ [
+ { id: "org_1", stripeCustomerId: "cus_1" },
+ { id: "org_2", stripeCustomerId: "cus_2" },
+ ],
+ true
+ );
+
+ expect(mocks.getAllStripeSubscriptionsByCustomer).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/services/featureFlags/regex.test.ts b/server/src/services/featureFlags/regex.test.ts
new file mode 100644
index 000000000..50a964600
--- /dev/null
+++ b/server/src/services/featureFlags/regex.test.ts
@@ -0,0 +1,251 @@
+import { describe, it, expect } from "vitest";
+import type { FeatureFlagConditionSet, FeatureFlagRule } from "../../db/postgres/schema.js";
+import {
+ getCompiledFeatureFlagRegex,
+ precompileFeatureFlagConditionSetRegexes,
+ precompileFeatureFlagRegexPattern,
+ precompileFeatureFlagRuleRegexes,
+ validateFeatureFlagRegexPattern,
+} from "./regex.js";
+
+// The compile caches live at module scope, so every test uses a pattern unique
+// to itself and cache-visibility assertions never collide across tests.
+let uniqueCounter = 0;
+const uniquePattern = (body = "ok") => `^${body}-unique-${process.pid}-${uniqueCounter++}$`;
+
+describe("validateFeatureFlagRegexPattern", () => {
+ it("accepts a plain valid pattern", () => {
+ expect(validateFeatureFlagRegexPattern("^/pricing")).toBeNull();
+ expect(validateFeatureFlagRegexPattern("foo|bar")).toBeNull();
+ expect(validateFeatureFlagRegexPattern("[a-z]+\\d{2}")).toBeNull();
+ });
+
+ it("rejects an empty pattern", () => {
+ expect(validateFeatureFlagRegexPattern("")).toBe("Regex pattern cannot be empty");
+ });
+
+ it("accepts a whitespace-only pattern (it is truthy and parses)", () => {
+ expect(validateFeatureFlagRegexPattern(" ")).toBeNull();
+ });
+
+ it("rejects a pattern over the 256 character limit", () => {
+ expect(validateFeatureFlagRegexPattern("a".repeat(256))).toBeNull();
+ expect(validateFeatureFlagRegexPattern("a".repeat(257))).toBe("Regex pattern cannot exceed 256 characters");
+ });
+
+ it("checks length before parseability", () => {
+ // An over-long AND unparseable pattern reports the length error.
+ expect(validateFeatureFlagRegexPattern("[" + "a".repeat(300))).toBe("Regex pattern cannot exceed 256 characters");
+ });
+
+ it("rejects an unparseable pattern and includes the engine message", () => {
+ const error = validateFeatureFlagRegexPattern("[invalid");
+ expect(error).toMatch(/^Invalid regex pattern: /);
+ expect(error).toContain("Unterminated character class");
+ });
+
+ it("rejects other malformed patterns", () => {
+ expect(validateFeatureFlagRegexPattern("(unclosed")).toMatch(/^Invalid regex pattern: /);
+ expect(validateFeatureFlagRegexPattern("a{2,1}")).toMatch(/^Invalid regex pattern: /);
+ expect(validateFeatureFlagRegexPattern("*")).toMatch(/^Invalid regex pattern: /);
+ });
+
+ it("rejects catastrophic-backtracking patterns as too complex", () => {
+ expect(validateFeatureFlagRegexPattern("(a+)+$")).toBe("Regex pattern is too complex");
+ expect(validateFeatureFlagRegexPattern("^(x+x+)+y$")).toBe("Regex pattern is too complex");
+ expect(validateFeatureFlagRegexPattern("(a{2,3}){2,3}")).toBe("Regex pattern is too complex");
+ });
+
+ it("allows up to 25 repetition operators and rejects 26", () => {
+ expect(validateFeatureFlagRegexPattern("a*".repeat(25))).toBeNull();
+ expect(validateFeatureFlagRegexPattern("a*".repeat(26))).toBe("Regex pattern is too complex");
+ });
+
+ it("does not reject a nested-quantifier-free alternation", () => {
+ expect(validateFeatureFlagRegexPattern("(a|a)*$")).toBeNull();
+ });
+});
+
+describe("precompileFeatureFlagRegexPattern", () => {
+ it("returns a RegExp for a valid pattern", () => {
+ const pattern = uniquePattern();
+ const compiled = precompileFeatureFlagRegexPattern(pattern);
+ expect(compiled).toBeInstanceOf(RegExp);
+ expect(compiled!.source).toBe(pattern);
+ expect(compiled!.flags).toBe("");
+ });
+
+ it("compiles a pattern that actually matches", () => {
+ const compiled = precompileFeatureFlagRegexPattern("^/pricing");
+ expect(compiled!.test("/pricing/pro")).toBe(true);
+ expect(compiled!.test("/docs")).toBe(false);
+ });
+
+ it("returns undefined for an empty pattern", () => {
+ expect(precompileFeatureFlagRegexPattern("")).toBeUndefined();
+ });
+
+ it("returns undefined for an invalid pattern", () => {
+ expect(precompileFeatureFlagRegexPattern("[invalid-" + uniqueCounter++)).toBeUndefined();
+ });
+
+ it("returns undefined for a too-complex pattern", () => {
+ expect(precompileFeatureFlagRegexPattern("(a+)+" + uniqueCounter++)).toBeUndefined();
+ });
+
+ it("returns undefined for an over-long pattern", () => {
+ expect(precompileFeatureFlagRegexPattern("a".repeat(300))).toBeUndefined();
+ });
+
+ it("returns the identical cached instance on repeat calls", () => {
+ const pattern = uniquePattern("cached");
+ const first = precompileFeatureFlagRegexPattern(pattern);
+ const second = precompileFeatureFlagRegexPattern(pattern);
+ expect(first).toBe(second);
+ });
+
+ it("keeps distinct patterns as distinct instances", () => {
+ const a = precompileFeatureFlagRegexPattern(uniquePattern("a"));
+ const b = precompileFeatureFlagRegexPattern(uniquePattern("b"));
+ expect(a).not.toBe(b);
+ });
+
+ it("keeps returning undefined for a pattern it has already rejected", () => {
+ const bad = "(bad+)+" + uniqueCounter++;
+ expect(precompileFeatureFlagRegexPattern(bad)).toBeUndefined();
+ expect(precompileFeatureFlagRegexPattern(bad)).toBeUndefined();
+ expect(getCompiledFeatureFlagRegex(bad)).toBeUndefined();
+ });
+});
+
+describe("getCompiledFeatureFlagRegex", () => {
+ it("returns undefined before the pattern has been precompiled", () => {
+ const pattern = uniquePattern("notyet");
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeUndefined();
+ });
+
+ it("returns the cached instance after precompiling", () => {
+ const pattern = uniquePattern("lookup");
+ const compiled = precompileFeatureFlagRegexPattern(pattern);
+ expect(getCompiledFeatureFlagRegex(pattern)).toBe(compiled);
+ });
+
+ it("never compiles on demand β€” it is a pure cache read", () => {
+ const pattern = uniquePattern("lazy");
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeUndefined();
+ // A second read still misses; only precompile populates the cache.
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeUndefined();
+ });
+
+ it("returns undefined for an invalid pattern even after a precompile attempt", () => {
+ const bad = "[nope-" + uniqueCounter++;
+ precompileFeatureFlagRegexPattern(bad);
+ expect(getCompiledFeatureFlagRegex(bad)).toBeUndefined();
+ });
+});
+
+describe("precompileFeatureFlagRuleRegexes", () => {
+ it("does nothing for undefined rules", () => {
+ expect(() => precompileFeatureFlagRuleRegexes(undefined)).not.toThrow();
+ });
+
+ it("does nothing for an empty rule list", () => {
+ expect(() => precompileFeatureFlagRuleRegexes([])).not.toThrow();
+ });
+
+ it("tolerates a non-array value", () => {
+ expect(() => precompileFeatureFlagRuleRegexes({} as unknown as FeatureFlagRule[])).not.toThrow();
+ expect(() => precompileFeatureFlagRuleRegexes(null as unknown as FeatureFlagRule[])).not.toThrow();
+ });
+
+ it("precompiles a single-value regex rule", () => {
+ const pattern = uniquePattern("rule");
+ precompileFeatureFlagRuleRegexes([{ field: "pathname", operator: "regex", value: pattern }]);
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeInstanceOf(RegExp);
+ });
+
+ it("precompiles every value of an array-valued regex rule", () => {
+ const a = uniquePattern("arr-a");
+ const b = uniquePattern("arr-b");
+ precompileFeatureFlagRuleRegexes([{ field: "pathname", operator: "regex", value: [a, b] }]);
+ expect(getCompiledFeatureFlagRegex(a)).toBeInstanceOf(RegExp);
+ expect(getCompiledFeatureFlagRegex(b)).toBeInstanceOf(RegExp);
+ });
+
+ it("skips rules whose operator is not regex", () => {
+ const pattern = uniquePattern("notregex");
+ precompileFeatureFlagRuleRegexes([{ field: "pathname", operator: "equals", value: pattern }]);
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeUndefined();
+ });
+
+ it("skips non-string values inside a regex rule", () => {
+ expect(() =>
+ precompileFeatureFlagRuleRegexes([{ field: "pathname", operator: "regex", value: [1, true] }])
+ ).not.toThrow();
+ expect(getCompiledFeatureFlagRegex("1")).toBeUndefined();
+ expect(getCompiledFeatureFlagRegex("true")).toBeUndefined();
+ });
+
+ it("precompiles across several rules and ignores invalid patterns", () => {
+ const good = uniquePattern("multi");
+ const bad = "(bad+)+" + uniqueCounter++;
+ precompileFeatureFlagRuleRegexes([
+ { field: "pathname", operator: "regex", value: good },
+ { field: "country", operator: "equals", value: "US" },
+ { field: "referrer", operator: "regex", value: bad },
+ ]);
+ expect(getCompiledFeatureFlagRegex(good)).toBeInstanceOf(RegExp);
+ expect(getCompiledFeatureFlagRegex(bad)).toBeUndefined();
+ });
+
+ it("shares one cache entry when two rules use the same pattern", () => {
+ const pattern = uniquePattern("shared");
+ precompileFeatureFlagRuleRegexes([
+ { field: "pathname", operator: "regex", value: pattern },
+ { field: "referrer", operator: "regex", value: pattern },
+ ]);
+ expect(getCompiledFeatureFlagRegex(pattern)).toBe(precompileFeatureFlagRegexPattern(pattern));
+ });
+});
+
+describe("precompileFeatureFlagConditionSetRegexes", () => {
+ it("does nothing for undefined condition sets", () => {
+ expect(() => precompileFeatureFlagConditionSetRegexes(undefined)).not.toThrow();
+ });
+
+ it("does nothing for an empty condition set list", () => {
+ expect(() => precompileFeatureFlagConditionSetRegexes([])).not.toThrow();
+ });
+
+ it("tolerates a non-array value", () => {
+ expect(() => precompileFeatureFlagConditionSetRegexes({} as unknown as FeatureFlagConditionSet[])).not.toThrow();
+ });
+
+ it("precompiles the regex rules of every condition set", () => {
+ const a = uniquePattern("cs-a");
+ const b = uniquePattern("cs-b");
+ const sets = [
+ { rules: [{ field: "pathname", operator: "regex", value: a }] },
+ { rules: [{ field: "referrer", operator: "regex", value: b }] },
+ ] as FeatureFlagConditionSet[];
+
+ precompileFeatureFlagConditionSetRegexes(sets);
+ expect(getCompiledFeatureFlagRegex(a)).toBeInstanceOf(RegExp);
+ expect(getCompiledFeatureFlagRegex(b)).toBeInstanceOf(RegExp);
+ });
+
+ it("tolerates a condition set with no rules", () => {
+ expect(() =>
+ precompileFeatureFlagConditionSetRegexes([{ rules: [] } as unknown as FeatureFlagConditionSet])
+ ).not.toThrow();
+ expect(() => precompileFeatureFlagConditionSetRegexes([{} as unknown as FeatureFlagConditionSet])).not.toThrow();
+ });
+
+ it("skips non-regex operators inside condition sets", () => {
+ const pattern = uniquePattern("cs-equals");
+ precompileFeatureFlagConditionSetRegexes([
+ { rules: [{ field: "pathname", operator: "equals", value: pattern }] },
+ ] as FeatureFlagConditionSet[]);
+ expect(getCompiledFeatureFlagRegex(pattern)).toBeUndefined();
+ });
+});
diff --git a/server/src/services/usageService.test.ts b/server/src/services/usageService.test.ts
new file mode 100644
index 000000000..afcdeccb7
--- /dev/null
+++ b/server/src/services/usageService.test.ts
@@ -0,0 +1,566 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SubscriptionInfo } from "../lib/subscriptionUtils.js";
+
+/**
+ * The usage cron is the quota gate: it decides which sites stop ingesting (over the
+ * monthly event limit) and which stop recording replays (plan or quota exhausted), and
+ * which owners get warned. Everything it reads β€” ClickHouse counts, Postgres orgs/sites,
+ * Stripe subscriptions β€” is mocked; the thresholds and the set bookkeeping are the
+ * subject under test.
+ */
+const state = vi.hoisted(() => ({
+ sites: [] as Array<{ siteId: number; organizationId: string | null }>,
+ organizations: [] as Array<{
+ id: string;
+ name: string;
+ stripeCustomerId: string | null;
+ createdAt: string;
+ overMonthlyLimit: boolean | null;
+ approachingLimitNotifiedPeriodStart: string | null;
+ }>,
+ owners: [] as Array<{ email: string }>,
+ eventCounts: [] as Array<{ site_id: number; count: string }>,
+ replayCounts: [] as Array<{ site_id: number; count: string }>,
+ /** organizationId -> subscription the resolver should return (or an Error to throw). */
+ subscriptions: new Map<string, SubscriptionInfo | Error>(),
+ /** Every organization update the run performed, in order. */
+ updates: [] as Array<Record<string, unknown>>,
+ clickhouseError: null as Error | null,
+}));
+
+const mocks = vi.hoisted(() => ({
+ getAllStripeSubscriptionsByCustomer: vi.fn(),
+ sendLimitExceededEmail: vi.fn(),
+ sendApproachingLimitEmail: vi.fn(),
+}));
+
+vi.mock("../db/postgres/postgres.js", () => {
+ function chain(rows: () => unknown[]) {
+ const builder: any = {
+ from: () => builder,
+ innerJoin: () => builder,
+ where: () => builder,
+ then: (resolve: any, reject: any) => Promise.resolve(rows()).then(resolve, reject),
+ };
+ return builder;
+ }
+
+ return {
+ db: {
+ // The three reads are told apart by the columns each one selects.
+ select: (fields: Record<string, unknown>) =>
+ chain(() => {
+ if ("email" in fields) return state.owners;
+ if ("siteId" in fields) return state.sites;
+ return state.organizations;
+ }),
+ update: () => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ state.updates.push(values);
+ },
+ }),
+ }),
+ },
+ };
+});
+
+vi.mock("../db/clickhouse/clickhouse.js", () => ({
+ clickhouse: {
+ query: async ({ query }: { query: string }) => {
+ if (state.clickhouseError) {
+ throw state.clickhouseError;
+ }
+ return { kind: query.includes("session_replay_metadata") ? "replays" : "events" };
+ },
+ },
+}));
+
+vi.mock("../api/analytics/utils/utils.js", () => ({
+ processResults: async (result: { kind: string }) =>
+ result.kind === "replays" ? state.replayCounts : state.eventCounts,
+}));
+
+vi.mock("../lib/email/email.js", () => ({
+ sendLimitExceededEmail: mocks.sendLimitExceededEmail,
+ sendApproachingLimitEmail: mocks.sendApproachingLimitEmail,
+}));
+
+vi.mock("../lib/logger/logger.js", () => ({
+ createServiceLogger: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+// Only the Stripe-touching resolvers are stubbed; subscriptionIncludesReplay and
+// getReplayLimit stay real so the replay gate is exercised, not re-specified.
+vi.mock("../lib/subscriptionUtils.js", async importOriginal => {
+ const actual = await importOriginal<typeof import("../lib/subscriptionUtils.js")>();
+ return {
+ ...actual,
+ getAllStripeSubscriptionsByCustomer: mocks.getAllStripeSubscriptionsByCustomer,
+ stripeSubscriptionInfoFromSnapshot: () => null,
+ getBestSubscriptionFromStripeSub: async (organizationId: string) => {
+ const subscription = state.subscriptions.get(organizationId);
+ if (subscription instanceof Error) {
+ throw subscription;
+ }
+ return subscription ?? freeSub();
+ },
+ };
+});
+
+vi.mock("../lib/stripe.js", () => ({ stripe: null }));
+
+import { usageService } from "./usageService.js";
+
+function freeSub(): SubscriptionInfo {
+ return {
+ source: "free",
+ eventLimit: 3_000,
+ periodStart: "2026-08-01",
+ planName: "free",
+ status: "free",
+ };
+}
+
+function stripeSub(overrides: Partial<Extract<SubscriptionInfo, { source: "stripe" }>> = {}): SubscriptionInfo {
+ return {
+ source: "stripe",
+ subscriptionId: "sub_1",
+ priceId: "price_1",
+ planName: "pro500k",
+ eventLimit: 100_000,
+ replayLimit: 1_000,
+ periodStart: "2026-08-01",
+ currentPeriodEnd: new Date("2026-09-01T00:00:00Z"),
+ status: "active",
+ interval: "month",
+ cancelAtPeriodEnd: false,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ ...overrides,
+ };
+}
+
+function org(
+ id: string,
+ overrides: Partial<{
+ name: string;
+ stripeCustomerId: string | null;
+ overMonthlyLimit: boolean | null;
+ approachingLimitNotifiedPeriodStart: string | null;
+ }> = {}
+) {
+ return {
+ id,
+ name: `Org ${id}`,
+ stripeCustomerId: "cus_1",
+ createdAt: "2026-01-01",
+ overMonthlyLimit: false,
+ approachingLimitNotifiedPeriodStart: null,
+ ...overrides,
+ };
+}
+
+/** One org, one site, with the given subscription and monthly event count. */
+function singleOrg(options: {
+ subscription?: SubscriptionInfo;
+ eventCount?: number;
+ replayCount?: number;
+ orgOverrides?: Parameters<typeof org>[1];
+}) {
+ state.organizations = [org("org_1", options.orgOverrides)];
+ state.sites = [{ siteId: 1, organizationId: "org_1" }];
+ state.subscriptions.set("org_1", options.subscription ?? stripeSub());
+ state.eventCounts = [{ site_id: 1, count: String(options.eventCount ?? 0) }];
+ state.replayCounts = [{ site_id: 1, count: String(options.replayCount ?? 0) }];
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date(2026, 7, 3, 12, 0, 0));
+
+ state.sites = [];
+ state.organizations = [];
+ state.owners = [{ email: "[email protected]" }];
+ state.eventCounts = [];
+ state.replayCounts = [];
+ state.subscriptions.clear();
+ state.updates.length = 0;
+ state.clickhouseError = null;
+
+ mocks.getAllStripeSubscriptionsByCustomer.mockReset();
+ mocks.getAllStripeSubscriptionsByCustomer.mockResolvedValue(new Map());
+ mocks.sendLimitExceededEmail.mockReset();
+ mocks.sendLimitExceededEmail.mockResolvedValue(undefined);
+ mocks.sendApproachingLimitEmail.mockReset();
+ mocks.sendApproachingLimitEmail.mockResolvedValue(undefined);
+
+ // The service is a singleton; clear the blocked sets between tests.
+ usageService.setSitesOverLimit(new Set());
+ usageService.setSitesWithoutReplay(new Set());
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("updateOrganizationsMonthlyUsage β€” Stripe outage", () => {
+ it("skips the whole run rather than treating every paying org as free", async () => {
+ singleOrg({ eventCount: 10_000_000 });
+ mocks.getAllStripeSubscriptionsByCustomer.mockRejectedValue(new Error("stripe is down"));
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates).toEqual([]);
+ expect(usageService.getSitesOverLimit().size).toBe(0);
+ expect(mocks.sendLimitExceededEmail).not.toHaveBeenCalled();
+ });
+
+ it("leaves already-blocked sites blocked when the run is skipped", async () => {
+ usageService.setSitesOverLimit(new Set([1]));
+ singleOrg({ eventCount: 0 });
+ mocks.getAllStripeSubscriptionsByCustomer.mockRejectedValue(new Error("stripe is down"));
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteOverLimit(1)).toBe(true);
+ });
+});
+
+describe("updateOrganizationsMonthlyUsage β€” event limit boundary", () => {
+ it("does not block an org sitting exactly on its limit", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 100_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ monthlyEventCount: 100_000, overMonthlyLimit: false });
+ expect(usageService.isSiteOverLimit(1)).toBe(false);
+ });
+
+ it("blocks an org one event past its limit", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 100_001 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ overMonthlyLimit: true });
+ expect(usageService.isSiteOverLimit(1)).toBe(true);
+ });
+
+ it("blocks every site of an over-limit org, counting their events together", async () => {
+ state.organizations = [org("org_1")];
+ state.sites = [
+ { siteId: 1, organizationId: "org_1" },
+ { siteId: 2, organizationId: "org_1" },
+ ];
+ state.subscriptions.set("org_1", stripeSub({ eventLimit: 100_000 }));
+ state.eventCounts = [
+ { site_id: 1, count: "60000" },
+ { site_id: 2, count: "60000" },
+ ];
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ monthlyEventCount: 120_000, overMonthlyLimit: true });
+ expect([...usageService.getSitesOverLimit()].sort()).toEqual([1, 2]);
+ });
+
+ it("unblocks an org's sites once it drops back under the limit", async () => {
+ usageService.setSitesOverLimit(new Set([1, 99]));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 10 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteOverLimit(1)).toBe(false);
+ // Sites belonging to no processed org are left untouched.
+ expect(usageService.isSiteOverLimit(99)).toBe(true);
+ });
+
+ it("ignores sites with no organization", async () => {
+ state.organizations = [org("org_1")];
+ state.sites = [
+ { siteId: 1, organizationId: null },
+ { siteId: 2, organizationId: "org_1" },
+ ];
+ state.subscriptions.set("org_1", stripeSub({ eventLimit: 1_000 }));
+ state.eventCounts = [
+ { site_id: 1, count: "999999" },
+ { site_id: 2, count: "500" },
+ ];
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ monthlyEventCount: 500, overMonthlyLimit: false });
+ expect(usageService.getSitesOverLimit().size).toBe(0);
+ });
+
+ it("fails open when ClickHouse cannot be queried", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 1_000 }), eventCount: 10_000_000 });
+ state.clickhouseError = new Error("clickhouse is down");
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ monthlyEventCount: 0, overMonthlyLimit: false });
+ expect(usageService.getSitesOverLimit().size).toBe(0);
+ });
+});
+
+describe("updateOrganizationsMonthlyUsage β€” limit exceeded email", () => {
+ it("emails every owner on the transition from under to over limit", async () => {
+ state.owners = [{ email: "[email protected]" }, { email: "[email protected]" }];
+ singleOrg({ subscription: stripeSub({ eventLimit: 100 }), eventCount: 101 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendLimitExceededEmail).toHaveBeenCalledTimes(2);
+ expect(mocks.sendLimitExceededEmail).toHaveBeenCalledWith("[email protected]", "Org org_1", 101, 100);
+ });
+
+ it("does not re-email an org that was already over its limit", async () => {
+ singleOrg({
+ subscription: stripeSub({ eventLimit: 100 }),
+ eventCount: 5_000,
+ orgOverrides: { overMonthlyLimit: true },
+ });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendLimitExceededEmail).not.toHaveBeenCalled();
+ expect(state.updates[0]).toMatchObject({ overMonthlyLimit: true });
+ });
+
+ it("still blocks the sites when the org has no owner to email", async () => {
+ state.owners = [];
+ singleOrg({ subscription: stripeSub({ eventLimit: 100 }), eventCount: 101 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendLimitExceededEmail).not.toHaveBeenCalled();
+ expect(usageService.isSiteOverLimit(1)).toBe(true);
+ });
+
+ it("keeps blocking sites when the email itself fails", async () => {
+ mocks.sendLimitExceededEmail.mockRejectedValue(new Error("smtp down"));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100 }), eventCount: 101 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteOverLimit(1)).toBe(true);
+ });
+});
+
+describe("updateOrganizationsMonthlyUsage β€” approaching limit email", () => {
+ it("warns at 90% of the limit and records the period it warned for", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 90_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).toHaveBeenCalledWith("[email protected]", "Org org_1", 90_000, 100_000);
+ expect(state.updates[0]).toMatchObject({ approachingLimitNotifiedPeriodStart: "2026-08-01" });
+ });
+
+ it("stays quiet just below 90% early in the month", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 89_999 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).not.toHaveBeenCalled();
+ expect(state.updates[0]).not.toHaveProperty("approachingLimitNotifiedPeriodStart");
+ });
+
+ it("warns on the run-rate projection once a week of the month has elapsed", async () => {
+ // Day 15 of a 31-day month: 50k events project to ~107k, over the 100k limit,
+ // while still being well under the 90% threshold.
+ vi.setSystemTime(new Date(2026, 7, 15, 12, 0, 0));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 50_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not project in the first week of the month", async () => {
+ // Same run rate on day 3: the projection would fire, but it is not consulted yet.
+ vi.setSystemTime(new Date(2026, 7, 3, 12, 0, 0));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 10_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).not.toHaveBeenCalled();
+ });
+
+ it("stays quiet in the last two days of the month, when a warning could not be acted on", async () => {
+ vi.setSystemTime(new Date(2026, 7, 30, 12, 0, 0));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 95_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).not.toHaveBeenCalled();
+ });
+
+ it("does not warn twice in the same billing period", async () => {
+ singleOrg({
+ subscription: stripeSub({ eventLimit: 100_000 }),
+ eventCount: 95_000,
+ orgOverrides: { approachingLimitNotifiedPeriodStart: "2026-08-01" },
+ });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).not.toHaveBeenCalled();
+ });
+
+ it("warns again in a new period after last month's warning", async () => {
+ singleOrg({
+ subscription: stripeSub({ eventLimit: 100_000 }),
+ eventCount: 95_000,
+ orgOverrides: { approachingLimitNotifiedPeriodStart: "2026-07-01" },
+ });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).toHaveBeenCalledTimes(1);
+ });
+
+ it("sends only the exceeded email once the limit is actually passed", async () => {
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 100_001 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(mocks.sendApproachingLimitEmail).not.toHaveBeenCalled();
+ expect(mocks.sendLimitExceededEmail).toHaveBeenCalledTimes(1);
+ });
+
+ it("records the warning even when the email fails, so it is not retried every 30 minutes", async () => {
+ mocks.sendApproachingLimitEmail.mockRejectedValue(new Error("smtp down"));
+ singleOrg({ subscription: stripeSub({ eventLimit: 100_000 }), eventCount: 95_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates[0]).toMatchObject({ approachingLimitNotifiedPeriodStart: "2026-08-01" });
+ });
+});
+
+describe("updateOrganizationsMonthlyUsage β€” session replay gating", () => {
+ it("blocks replays for a plan that does not include them", async () => {
+ singleOrg({ subscription: stripeSub({ planName: "standard100k", replayLimit: 50_000 }), replayCount: 0 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(true);
+ });
+
+ it("allows replays below the plan's quota", async () => {
+ singleOrg({ subscription: stripeSub({ planName: "pro500k", replayLimit: 1_000 }), replayCount: 999 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(false);
+ expect(usageService.getSitesWithoutReplay().size).toBe(0);
+ });
+
+ it("blocks replays once the quota is exactly reached", async () => {
+ singleOrg({ subscription: stripeSub({ planName: "pro500k", replayLimit: 1_000 }), replayCount: 1_000 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(true);
+ });
+
+ it("unblocks replays after a downgrade is reversed", async () => {
+ usageService.setSitesWithoutReplay(new Set([1]));
+ singleOrg({ subscription: stripeSub({ planName: "pro500k", replayLimit: 1_000 }), replayCount: 0 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(false);
+ });
+
+ it("counts replays across all of an org's sites against one quota", async () => {
+ state.organizations = [org("org_1")];
+ state.sites = [
+ { siteId: 1, organizationId: "org_1" },
+ { siteId: 2, organizationId: "org_1" },
+ ];
+ state.subscriptions.set("org_1", stripeSub({ planName: "pro500k", replayLimit: 1_000 }));
+ state.replayCounts = [
+ { site_id: 1, count: "600" },
+ { site_id: 2, count: "400" },
+ ];
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect([...usageService.getSitesWithoutReplay()].sort()).toEqual([1, 2]);
+ });
+
+ it("blocks replays for free-tier orgs", async () => {
+ singleOrg({ subscription: freeSub(), replayCount: 0 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(true);
+ });
+
+ it("never blocks replays for a custom (uncapped) plan", async () => {
+ singleOrg({
+ subscription: {
+ source: "custom",
+ planName: "custom",
+ eventLimit: 50_000_000,
+ memberLimit: null,
+ siteLimit: null,
+ periodStart: "2026-08-01",
+ status: "active",
+ interval: "lifetime",
+ cancelAtPeriodEnd: false,
+ },
+ replayCount: 10_000_000,
+ });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(usageService.isSiteWithoutReplay(1)).toBe(false);
+ });
+});
+
+describe("updateOrganizationsMonthlyUsage β€” resilience and notification", () => {
+ it("keeps processing later organizations when one fails", async () => {
+ state.organizations = [org("org_bad"), org("org_good")];
+ state.sites = [
+ { siteId: 1, organizationId: "org_bad" },
+ { siteId: 2, organizationId: "org_good" },
+ ];
+ state.subscriptions.set("org_bad", new Error("subscription lookup failed"));
+ state.subscriptions.set("org_good", stripeSub({ eventLimit: 100 }));
+ state.eventCounts = [{ site_id: 2, count: "500" }];
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(state.updates).toHaveLength(1);
+ expect(state.updates[0]).toMatchObject({ monthlyEventCount: 500, overMonthlyLimit: true });
+ expect(usageService.isSiteOverLimit(2)).toBe(true);
+ expect(usageService.isSiteOverLimit(1)).toBe(false);
+ });
+
+ it("notifies registered listeners once the run completes", async () => {
+ const callback = vi.fn();
+ usageService.onUsageUpdated(callback);
+ singleOrg({ eventCount: 0 });
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not notify listeners when the run is skipped", async () => {
+ const callback = vi.fn();
+ usageService.onUsageUpdated(callback);
+ mocks.getAllStripeSubscriptionsByCustomer.mockRejectedValue(new Error("stripe is down"));
+
+ await usageService.updateOrganizationsMonthlyUsage();
+
+ expect(callback).not.toHaveBeenCalled();
+ });
+});