Compose Billing scoped-read repair with current main

Retain both the protected Assistant stream contract and the Billing cancellation contract. The four browser-verified runtime files and final prepared dependency manifests are unchanged from the imported candidate.

Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-01 06:28:52 +00:00
16 changed files with 1244 additions and 595 deletions
@@ -56,6 +56,21 @@ real persisted DELETE for all three routes. Shared writer tests pin deadline
forwarding, final closure and the lack of a bypass. These are synthetic source
proofs, not installed/private-extension recovery, exposure or publication.
### Billing Admin cancellation and non-replayed writes
`frontend-modern/src/api/billingAdmin.ts` accepts an optional cancellation signal
for the global hosted organization inventory, per-organization billing read and
subscription PUT. Existing session preference, encoded organization path and
`skipOrgContext` are unchanged: the platform-admin endpoints still use default
request context, not the UI's selected tenant. Idempotent reads retain the
existing client fallback policy. Subscription writes set `retry: false`, so an
unconfirmed response does not replay after CSRF refresh, rate limiting or token
fallback; the client rechecks cancellation after CSRF preparation before dispatch.
A pending abort does not claim a server-side rollback. Existing server-side
administration, organization and capability checks remain authoritative.
API unit and real-client transport tests cover option propagation, headers,
encoded targets, non-retry responses and cancellation during CSRF preparation.
### Selected organization detail and billing request lifetimes
The existing organization `update` client optionally accepts the same
@@ -15,6 +15,39 @@
## Purpose
### Billing Admin reads and changes use an accepted global snapshot
Hosted Billing Admin remains a platform-administration surface, not an
organization-selected read. Its existing hosted/multitenant/demo and server
permission boundaries stay in place. A refresh, capability/presentation
withdrawal, read-only transition or disposal invalidates the inventory and row
requests, aborts pending transport and removes retained billing details. Late
successes, failures and spinner completions cannot change a newer snapshot.
The six-worker billing prefetch runs once per accepted inventory; failures are
not rescheduled by sibling completions. Opaque organization IDs are own keys,
not object-prototype entries.
Only a successful, well-formed inventory can assert emptiness. Failed inventory
reads show a fixed inline error, not old rows or an empty-list claim. Failed or
malformed billing rows show unavailable data and deliberate read-only recovery,
not a trial/customer default or a permanent JSON loading placeholder. Subscription
controls require the current accepted row and a non-read-only session; they
never fetch missing billing data as an implicit prelude to writing.
A subscription change preserves the saved plan and other billing fields, admits
one in-flight write per row and is never automatically repeated. Refresh,
withdrawal and disposal abort its transport, including after CSRF preparation.
Cancellation is not server rollback. A failed, malformed or mismatched response
withdraws the row snapshot and says the change is unconfirmed until an explicit
reload. Obsolete completions produce no success or failure toast in a later view.
On phones, one set of subscription actions stays in the subscription cell, beside
its accepted state and recovery control, rather than extending a separate column
off-screen. Error text and expanded JSON override inherited table no-wrap rules
so the warning, recovery and billing details remain readable. Normal-suite
BillingAdminPanel/ReadLifetimes and billingAdmin transport tests pin these boundaries. Desktop and phone browser evidence uses the actual panel,
grid, client and capability stores with synthetic HTTP responses; no installed
billing, provider mutation or original administrator recovery is claimed.
### Organization billing reads are a selected snapshot, not fallback plan data
The existing Billing & Usage panel displays plan and member figures only after
@@ -0,0 +1,60 @@
{
"version": 1,
"base_sha": "057b6bab50df9824ff8a7f8475b7e8c1880b44b0",
"verified_at": "2026-11-01T04:02:01.787308Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/api/billingAdmin.ts",
"frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx",
"frontend-modern/src/components/Settings/BillingAdminPanel.tsx",
"frontend-modern/src/components/Settings/useBillingAdminPanelState.ts"
],
"content_sha256": {
"frontend-modern/src/api/billingAdmin.ts": "002a8d6098da60a54343d63713f472d3fc6da087db5bfa7feb798d307618ae3d",
"frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx": "e4ddd3767d966ca1821f4d22755c4c0d76ea0c4a2b73b3202898d5f016e07ab8",
"frontend-modern/src/components/Settings/BillingAdminPanel.tsx": "ee9b471b5478a20eec2656e02367ee8e9520066765729b1a382129a1d45e0e60",
"frontend-modern/src/components/Settings/useBillingAdminPanelState.ts": "f1d0f8405fec7463dcbc7e157d2ad045382696f7c152acc47eace5e94e7f91ac"
},
"routes": [
"/"
],
"viewports": [
{
"width": 1360,
"height": 920
},
{
"width": 320,
"height": 844
}
],
"states": [
"Safe compiled adapter renders the actual existing Billing Admin panel, grid, global API client and runtime/presentation stores with production CSS. The route is the synthetic adapter root, not a full Settings-router or installed authorization journey. All backend responses and billing fields are synthetic.",
"Exact source 057b6bab50df9824ff8a7f8475b7e8c1880b44b0; source-1xw2f265 passes types, 8 affected consumer tests, changed-file lint/format and full production/embed plus preview builds. The 44 compiled source inputs match this tree.",
"Playwright 1.56.1 matches the integration lock; desktop/light Chromium141.0.7390.37 and narrow/dark touch WebKit26.0. Native view_image inspection of all 12 final captures confirms readable state, warnings, controls and wrapped JSON, without overlap or inner-table/page-wide clipping."
],
"interactions": [
"Read-pending and unavailable rows disable both mutation actions; explicit keyboard Reload billing is a read, not a PUT. Accepted empty inventory differs from failed inventory, and refreshing removes old rows.",
"One subscription PUT preserves the accepted plan/limits/capabilities/meters/trial/customer fields; duplicate activation is blocked. A failed response clears old billing and shows unconfirmed, followed by deliberate saved-state read and a separately confirmed change.",
"Withdraw pending inventory and re-enter with fresh reads. Withdraw while the real client awaits CSRF preparation: no subscription PUT in the bounded 100ms post-response observation. Read-only state blocks programmatic clicks but keeps billing readable.",
"All admin reads/writes use the existing default global request context and omit the synthetic stored API token on the session-preferred request. This is transport evidence, not real server-side authority or customer billing recovery."
],
"evidence": {
"source_proof": "source-1xw2f265",
"source_sha": "057b6bab50df9824ff8a7f8475b7e8c1880b44b0",
"preview_sha256": "210afbaff54ac827b8009537d87cf3af04749ce8ddf47fb26de0a9302345aba8",
"scripted_checks": 15,
"captures_natively_inspected": 12,
"page_errors": 0,
"pending_handlers": 0,
"browser_server_closed": true,
"lane_records": [
"RECEIPTS.md",
"SOURCE-FINAL.json",
"FINAL-PREVIEW-BINDING.json",
"BROWSER-COMPLETE-SUMMARY.json",
"PIXEL-REVIEW.json",
"BROWSER-EVIDENCE.tar.xz"
]
}
}
+84 -331
View File
@@ -17,7 +17,7 @@
"solid-js": "^1.9.17"
},
"devDependencies": {
"@eslint/js": "^9.39.2",
"@eslint/js": "10.0.0",
"@solidjs/testing-library": "^0.8.5",
"@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.3.3",
@@ -27,10 +27,11 @@
"@typescript-eslint/eslint-plugin": "^8.72.0",
"@typescript-eslint/parser": "^8.72.0",
"@vitest/coverage-v8": "^4.1.12",
"eslint": "^9.20.0",
"eslint": "10.0.0",
"eslint-config-prettier": "^10.0.0",
"eslint-plugin-solid": "^0.18.1",
"globals": "^17.13.0",
"js-yaml": "^4.3.2",
"jscpd": "^5.4.2",
"jsdom": "^24.1.0",
"prettier": "3.9.10",
@@ -967,190 +968,72 @@
}
},
"node_modules/@eslint/config-array": {
"version": "0.21.2",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz",
"integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==",
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.0.tgz",
"integrity": "sha512-T5Swqd+PZxBekRuMsIFCySM3NUE8GjuqyksIIsXgkF2GCuiDaqpxKyPkv9VMEKpq5D7r5DLss1tM8tCsvRSjeg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/object-schema": "^2.1.7",
"@eslint/object-schema": "^3.0.0",
"debug": "^4.3.1",
"minimatch": "^3.1.5"
"minimatch": "^10.1.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@eslint/config-array/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/@eslint/config-array/node_modules/brace-expansion": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/@eslint/config-array/node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@eslint/config-helpers": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",
"integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.5.2.tgz",
"integrity": "sha512-a5MxrdDXEvqnIq+LisyCX6tQMPF/dSJpCfBgBauY+pNZ28yCtSsTvyTYrMhaI+LK26bVyCJfJkT0u8KIj2i1dQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/core": "^0.17.0"
"@eslint/core": "^1.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@eslint/core": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",
"integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.1.0.tgz",
"integrity": "sha512-/nr9K9wkr3P1EzFTdFdMoLuo1PmIxjmwvPozwoSodjNBdefGujXQUF93u1DDZpEaTuDvMsIQddsd35BwtrW9Xw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@types/json-schema": "^7.0.15"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@eslint/eslintrc": {
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz",
"integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==",
"dev": true,
"license": "MIT",
"dependencies": {
"ajv": "^6.14.0",
"debug": "^4.3.2",
"espree": "^10.0.1",
"globals": "^14.0.0",
"ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.1",
"minimatch": "^3.1.5",
"strip-json-comments": "^3.1.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
}
},
"node_modules/@eslint/eslintrc/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/@eslint/eslintrc/node_modules/brace-expansion": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/@eslint/eslintrc/node_modules/globals": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
"integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@eslint/eslintrc/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@eslint/js": {
"version": "9.39.4",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz",
"integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==",
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.0.tgz",
"integrity": "sha512-J2VKrn6YUBegZFzRQVOVA8jk7VViV/MXhQUvXuCUK1I2RGGT2E+bmNGOsgtdO9Wo25Kd3hfZFuCm8LcfsUFV7g==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://eslint.org/donate"
}
},
"node_modules/@eslint/object-schema": {
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",
"integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.0.tgz",
"integrity": "sha512-nWl20RtHQP2A2yvKU6Fee62Xo1AoNRqBLixtyg45zJhU8ljPFCyBK90d8e8XTnPns1RggSf4HH3bM8AhevkPVg==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@eslint/plugin-kit": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",
"integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.6.0.tgz",
"integrity": "sha512-bIZEUzOI1jkhviX2cp5vNyXQc6olzb2ohewQubuYlMXZ2Q/XjBO0x0XhGPvc9fjSIiUN0vw+0hq53BJ4eQSJKQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/core": "^0.17.0",
"@eslint/core": "^1.1.0",
"levn": "^0.4.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@humanfs/core": {
@@ -1219,6 +1102,12 @@
"url": "https://github.com/sponsors/nzakas"
}
},
"node_modules/@isaacs/nonrecursive-glob-match": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.1.tgz",
"integrity": "sha512-rNKPuTXBacPpn5+CP+S3/UI6uq/0jHZjPpaBLaRE3blpgX+E+ZUIrGfViPvUjUnQG6W1+3OTFUiVRCjTffs2+Q==",
"dev": true
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -2110,6 +1999,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
"integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",
"dev": true
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -2788,16 +2683,6 @@
"node": ">= 0.4"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
"integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
@@ -2838,23 +2723,6 @@
"node": ">=18"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -2911,13 +2779,6 @@
"node": ">= 0.8"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true,
"license": "MIT"
},
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -3271,33 +3132,29 @@
}
},
"node_modules/eslint": {
"version": "9.39.4",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz",
"integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.0.0.tgz",
"integrity": "sha512-O0piBKY36YSJhlFSG8p9VUdPV/SxxS4FYDWVpr/9GJuMaepzwlf4J8I4ov1b+ySQfDTPhc3DtLaxcT1fN0yqCg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
"@eslint/config-array": "^0.21.2",
"@eslint/config-helpers": "^0.4.2",
"@eslint/core": "^0.17.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "9.39.4",
"@eslint/plugin-kit": "^0.4.1",
"@eslint-community/regexpp": "^4.12.2",
"@eslint/config-array": "^0.23.0",
"@eslint/config-helpers": "^0.5.2",
"@eslint/core": "^1.1.0",
"@eslint/plugin-kit": "^0.6.0",
"@humanfs/node": "^0.16.6",
"@humanwhocodes/module-importer": "^1.0.1",
"@humanwhocodes/retry": "^0.4.2",
"@types/estree": "^1.0.6",
"ajv": "^6.14.0",
"chalk": "^4.0.0",
"ajv": "^6.12.4",
"cross-spawn": "^7.0.6",
"debug": "^4.3.2",
"escape-string-regexp": "^4.0.0",
"eslint-scope": "^8.4.0",
"eslint-visitor-keys": "^4.2.1",
"espree": "^10.4.0",
"esquery": "^1.5.0",
"eslint-scope": "^9.1.0",
"eslint-visitor-keys": "^5.0.0",
"espree": "^11.1.0",
"esquery": "^1.7.0",
"esutils": "^2.0.2",
"fast-deep-equal": "^3.1.3",
"file-entry-cache": "^8.0.0",
@@ -3307,19 +3164,12 @@
"imurmurhash": "^0.1.4",
"is-glob": "^4.0.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
"lodash.merge": "^4.6.2",
"minimatch": "^3.1.5",
"minimatch": "^10.1.1",
"natural-compare": "^1.4.0",
"optionator": "^0.9.3"
},
"bin": {
"eslint": "bin/eslint.js"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://eslint.org/donate"
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"peerDependencies": {
"jiti": "*"
@@ -3328,6 +3178,9 @@
"jiti": {
"optional": true
}
},
"bin": {
"eslint": "bin/eslint.js"
}
},
"node_modules/eslint-config-prettier": {
@@ -3369,20 +3222,18 @@
}
},
"node_modules/eslint-scope": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",
"integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.0.tgz",
"integrity": "sha512-CkWE42hOJsNj9FJRaoMX9waUFYhqY4jmyLFdAdzZr6VaCg3ynLYx4WnOdkaIifGfH4gsUcBTn4OZbHXkpLD0FQ==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"@types/esrecurse": "^4.3.1",
"@types/estree": "^1.0.8",
"esrecurse": "^4.3.0",
"estraverse": "^5.2.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/eslint-visitor-keys": {
@@ -3398,32 +3249,14 @@
"url": "https://opencollective.com/eslint"
}
},
"node_modules/eslint/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/eslint/node_modules/brace-expansion": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/eslint/node_modules/eslint-visitor-keys": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
"integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"funding": {
"url": "https://opencollective.com/eslint"
@@ -3439,45 +3272,28 @@
"node": ">= 4"
}
},
"node_modules/eslint/node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/espree": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
"integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/espree/-/espree-11.1.0.tgz",
"integrity": "sha512-WFWYhO1fV4iYkqOOvq8FbqIhr2pYfoDY0kCotMkDeNtGpiGGkZ1iov2u8ydjtgM8yF8rzK7oaTbw2NAzbAbehw==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"acorn": "^8.15.0",
"acorn-jsx": "^5.3.2",
"eslint-visitor-keys": "^4.2.1"
"eslint-visitor-keys": "^5.0.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/espree/node_modules/eslint-visitor-keys": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
"integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"funding": {
"url": "https://opencollective.com/eslint"
@@ -3910,23 +3726,6 @@
"node": ">= 4"
}
},
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
"integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"parent-module": "^1.0.0",
"resolve-from": "^4.0.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/imurmurhash": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
@@ -4670,13 +4469,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
@@ -4813,19 +4605,16 @@
}
},
"node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.1.tgz",
"integrity": "sha512-t+Vn6DX4wPCxS23y03C0uhF7S1jpi1GfqPrnlEipCJaA2ykiNbMkVlDutZtmvLfRcUN6R8AYVlzTsQrT4RZoLQ==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"brace-expansion": "^5.0.5"
"@isaacs/nonrecursive-glob-match": "^1.0.1",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/ms": {
@@ -4951,19 +4740,6 @@
"node": ">=6"
}
},
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
"integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
"dev": true,
"license": "MIT",
"dependencies": {
"callsites": "^3.0.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/parse5": {
"version": "7.3.0",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
@@ -5219,16 +4995,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
"integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/rollup": {
"version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -5458,19 +5224,6 @@
"node": ">=8"
}
},
"node_modules/strip-json-comments": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
"integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/style-to-object": {
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",
+5 -3
View File
@@ -67,10 +67,11 @@
"@babel/core": "^7.29.6",
"js-yaml": "^4.3.2",
"postcss-selector-parser": "^7.1.6",
"source-map-js": "^1.2.2"
"source-map-js": "^1.2.2",
"minimatch@^10.0.0": "11.0.1"
},
"devDependencies": {
"@eslint/js": "^9.39.2",
"@eslint/js": "10.0.0",
"@solidjs/testing-library": "^0.8.5",
"@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.3.3",
@@ -80,10 +81,11 @@
"@typescript-eslint/eslint-plugin": "^8.72.0",
"@typescript-eslint/parser": "^8.72.0",
"@vitest/coverage-v8": "^4.1.12",
"eslint": "^9.20.0",
"eslint": "10.0.0",
"eslint-config-prettier": "^10.0.0",
"eslint-plugin-solid": "^0.18.1",
"globals": "^17.13.0",
"js-yaml": "^4.3.2",
"jscpd": "^5.4.2",
"jsdom": "^24.1.0",
"prettier": "3.9.10",
@@ -92,4 +92,31 @@ describe('BillingAdminAPI', () => {
expect(result).toEqual(mockState);
});
});
it('forwards cancellation for all operations and makes writes non-retrying', async () => {
const signal = new AbortController().signal;
await BillingAdminAPI.listOrganizations({ signal });
await BillingAdminAPI.getBillingState('org/one', { signal });
const state: BillingState = { subscription_state: 'active', capabilities: [], limits: {} };
await BillingAdminAPI.putBillingState('org/one', state, { signal });
expect(apiFetchJSON).toHaveBeenNthCalledWith(
1,
'/api/hosted/organizations',
expect.objectContaining({ signal, preferSessionAuth: true, skipOrgContext: true }),
);
expect(apiFetchJSON).toHaveBeenNthCalledWith(
2,
'/api/admin/orgs/org%2Fone/billing-state',
expect.objectContaining({ signal, preferSessionAuth: true, skipOrgContext: true }),
);
expect(apiFetchJSON).toHaveBeenNthCalledWith(
3,
'/api/admin/orgs/org%2Fone/billing-state',
expect.objectContaining({
signal,
retry: false,
preferSessionAuth: true,
skipOrgContext: true,
}),
);
});
});
@@ -0,0 +1,87 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BillingState } from '../billingAdmin';
const fetchMock = vi.fn();
let api: typeof import('../billingAdmin');
let client: typeof import('@/utils/apiClient');
const state: BillingState = {
subscription_state: 'suspended',
capabilities: ['multi_tenant'],
limits: { max_nodes: 30 },
};
beforeEach(async () => {
vi.resetModules();
fetchMock.mockReset();
vi.stubGlobal('fetch', fetchMock);
document.cookie = 'pulse_csrf=; Max-Age=0; Path=/';
sessionStorage.clear();
client = await import('@/utils/apiClient');
api = await import('../billingAdmin');
client.setApiToken('synthetic-stored-token');
client.setOrgID('selected-tenant');
});
afterEach(() => {
client.clearAuth();
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
describe('Billing Admin real transport', () => {
it('keeps global reads session-preferred and cancellable, without using the selected tenant', async () => {
const signal = new AbortController().signal;
fetchMock.mockResolvedValueOnce(new Response('[]', { status: 200 }));
await api.BillingAdminAPI.listOrganizations({ signal });
expect(fetchMock.mock.calls[0][1]).toMatchObject({
signal,
credentials: 'include',
headers: { 'X-Pulse-Org-ID': 'default' },
});
expect(fetchMock.mock.calls[0][1].headers['X-API-Token']).toBeUndefined();
expect(client.getOrgID()).toBe('selected-tenant');
});
it.each([403, 429, 503])(
'does not automatically repeat a subscription PUT after HTTP %i',
async (status) => {
fetchMock.mockResolvedValueOnce(
new Response('{}', {
status,
headers: { 'X-CSRF-Token': 'synthetic-new-csrf', 'Retry-After': '0' },
}),
);
await expect(api.BillingAdminAPI.putBillingState('org/one', state)).rejects.toMatchObject({
status,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBe('/api/admin/orgs/org%2Fone/billing-state');
expect(fetchMock.mock.calls[0][1]).toMatchObject({
method: 'PUT',
body: JSON.stringify(state),
headers: { 'X-Pulse-Org-ID': 'default' },
});
expect(fetchMock.mock.calls[0][1].headers['X-API-Token']).toBeUndefined();
},
);
it('does not dispatch a withdrawn subscription change after CSRF preparation completes', async () => {
vi.stubEnv('MODE', 'production');
let resolve!: (value: Response) => void;
fetchMock.mockImplementationOnce(
() =>
new Promise<Response>((yes) => {
resolve = yes;
}),
);
const controller = new AbortController();
const writing = api.BillingAdminAPI.putBillingState('org-a', state, {
signal: controller.signal,
});
const result = expect(writing).rejects.toMatchObject({ name: 'AbortError' });
expect(fetchMock.mock.calls[0][0]).toBe('/api/health');
controller.abort();
resolve(new Response('{}', { status: 200 }));
await result;
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
+13 -3
View File
@@ -22,24 +22,34 @@ export interface BillingState {
stripe_price_id?: string;
}
interface BillingAdminRequestOptions {
signal?: AbortSignal;
}
export const BillingAdminAPI = {
listOrganizations: () =>
listOrganizations: (options?: BillingAdminRequestOptions) =>
apiFetchJSON<HostedOrganizationSummary[]>('/api/hosted/organizations', {
preferSessionAuth: true,
skipOrgContext: true,
...options,
}),
getBillingState: (orgID: string) =>
getBillingState: (orgID: string, options?: BillingAdminRequestOptions) =>
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
preferSessionAuth: true,
skipOrgContext: true,
...options,
}),
putBillingState: (orgID: string, payload: BillingState) =>
putBillingState: (orgID: string, payload: BillingState, options?: BillingAdminRequestOptions) =>
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
method: 'PUT',
body: JSON.stringify(payload),
preferSessionAuth: true,
skipOrgContext: true,
...options,
// A failed response does not establish whether a subscription changed.
// Also recheck cancellation after the client's CSRF preparation wait.
retry: false,
}),
};
@@ -1,6 +1,7 @@
import type { Component } from 'solid-js';
import { Show, type Component } from 'solid-js';
import { Button } from '@/components/shared/Button';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import {
BILLING_ADMIN_EMPTY_STATE,
getBillingAdminOrganizationBadges,
@@ -13,6 +14,8 @@ import type { BillingStateCache } from './useBillingAdminPanelState';
interface BillingAdminOrganizationsTableProps {
billingByOrgID: BillingStateCache;
billingLoadingByOrgID: Record<string, boolean>;
billingErrorByOrgID: Record<string, string>;
canManageBilling: boolean;
expandedOrgID: string | null;
isLoading: boolean;
orgs: HostedOrganizationSummary[];
@@ -31,152 +34,187 @@ const stripeCustomerCell = (state?: BillingState) => {
export const BillingAdminOrganizationsTable: Component<BillingAdminOrganizationsTableProps> = (
props,
) => (
<PulseDataGrid
data={props.orgs}
isLoading={props.isLoading}
emptyState={BILLING_ADMIN_EMPTY_STATE}
desktopMinWidth="920px"
columns={[
{
key: 'organization',
label: 'Organization',
render: (org) => {
const orgID = (org.org_id || '').trim();
return (
<button
type="button"
class="text-left w-full"
onClick={() => {
props.onToggleOrganization(orgID);
}}
>
<div class="font-medium text-base-content">{org.display_name || org.org_id}</div>
<div class="text-xs text-muted">
<span class="font-mono">{org.org_id}</span>
{getBillingAdminOrganizationBadges(org).map((badge) => (
<span class={`ml-2 rounded-sm px-1.5 py-0.5 ${badge.badgeClass}`}>
{badge.label}
</span>
))}
) => {
const { isMobile } = useBreakpoint();
const unreadLabel = (orgID: string) =>
props.billingLoadingByOrgID[orgID] ? 'Loading' : 'Unavailable';
const actionsDisabled = (orgID: string) =>
!props.canManageBilling ||
!props.billingByOrgID[orgID] ||
!!props.billingErrorByOrgID[orgID] ||
props.savingByOrgID[orgID] ||
props.billingLoadingByOrgID[orgID];
const subscriptionActions = (orgID: string) => {
const currentSubState = () =>
(props.billingByOrgID[orgID]?.subscription_state || '').toLowerCase();
return (
<div class="flex flex-col sm:inline-flex sm:flex-row sm:items-center gap-2">
<Button
variant="secondary"
size="sm"
onClick={() => props.onSuspendOrganization(orgID)}
disabled={actionsDisabled(orgID) || currentSubState() === 'suspended'}
>
Suspend Org
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => props.onActivateOrganization(orgID)}
disabled={actionsDisabled(orgID) || currentSubState() === 'active'}
>
Activate Org
</Button>
</div>
);
};
return (
<PulseDataGrid
data={props.orgs}
isLoading={props.isLoading}
emptyState={BILLING_ADMIN_EMPTY_STATE}
desktopMinWidth="920px"
columns={[
{
key: 'organization',
label: 'Organization',
render: (org) => {
const orgID = (org.org_id || '').trim();
return (
<button
type="button"
class="text-left w-full whitespace-normal [overflow-wrap:anywhere]"
onClick={() => {
props.onToggleOrganization(orgID);
}}
>
<div class="font-medium text-base-content">{org.display_name || org.org_id}</div>
<div class="text-xs text-muted">
<span class="font-mono">{org.org_id}</span>
{getBillingAdminOrganizationBadges(org).map((badge) => (
<span class={`ml-2 rounded-sm px-1.5 py-0.5 ${badge.badgeClass}`}>
{badge.label}
</span>
))}
</div>
</button>
);
},
},
{
key: 'owner',
label: 'Owner',
hiddenOnMobile: true,
render: (org) => (
<span class="font-mono text-xs text-base-content">{org.owner_user_id || 'N/A'}</span>
),
},
{
key: 'subscription',
label: 'Subscription',
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
const orgID = (org.org_id || '').trim();
return (
<div class="space-y-2">
<span class="font-mono text-xs text-base-content">
{billing
? getLicenseSubscriptionStatusPresentation(billing.subscription_state).label
: unreadLabel(orgID)}
</span>
<Show when={props.billingErrorByOrgID[orgID]}>
<p
role="alert"
class="max-w-xs whitespace-normal [overflow-wrap:anywhere] text-xs text-red-700 dark:text-red-300"
>
{props.billingErrorByOrgID[orgID]}
</p>
<Button
variant="secondary"
size="xs"
aria-label={`Reload billing for ${org.display_name || orgID}`}
onClick={() => props.onReloadOrganization(orgID)}
disabled={props.billingLoadingByOrgID[orgID] || props.savingByOrgID[orgID]}
>
Reload billing
</Button>
</Show>
<Show when={isMobile()}>{subscriptionActions(orgID)}</Show>
</div>
</button>
);
);
},
},
},
{
key: 'owner',
label: 'Owner',
hiddenOnMobile: true,
render: (org) => (
<span class="font-mono text-xs text-base-content">{org.owner_user_id || 'N/A'}</span>
),
},
{
key: 'subscription',
label: 'Subscription',
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
return (
<span class="font-mono text-xs text-base-content">
{getLicenseSubscriptionStatusPresentation(billing?.subscription_state).label}
</span>
);
{
key: 'trial',
label: 'Trial',
hiddenOnMobile: true,
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
return (
<span class="text-xs text-base-content">
{billing ? getBillingAdminTrialStatus(billing) : unreadLabel(org.org_id)}
</span>
);
},
},
},
{
key: 'trial',
label: 'Trial',
hiddenOnMobile: true,
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
return (
<span class="text-xs text-base-content">{getBillingAdminTrialStatus(billing)}</span>
);
{
key: 'stripeCustomer',
label: 'Stripe Customer',
hiddenOnMobile: true,
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
const cellValue = billing ? stripeCustomerCell(billing) : unreadLabel(org.org_id);
return (
<span class="font-mono text-xs text-base-content" title={cellValue}>
{cellValue}
</span>
);
},
},
},
{
key: 'stripeCustomer',
label: 'Stripe Customer',
hiddenOnMobile: true,
render: (org) => {
const billing = props.billingByOrgID[(org.org_id || '').trim()];
const cellValue = stripeCustomerCell(billing);
return (
<span class="font-mono text-xs text-base-content" title={cellValue}>
{cellValue}
</span>
);
{
key: 'actions',
label: 'Actions',
hiddenOnMobile: true,
align: 'right',
render: (org) => <Show when={!isMobile()}>{subscriptionActions(org.org_id)}</Show>,
},
},
{
key: 'actions',
label: 'Actions',
align: 'right',
render: (org) => {
const orgID = (org.org_id || '').trim();
const billing = props.billingByOrgID[orgID];
const currentSubState = (billing?.subscription_state || '').toLowerCase() || 'unknown';
return (
<div class="inline-flex flex-col sm:flex-row sm:items-center gap-2">
<Button
variant="secondary"
size="sm"
onClick={() => {
props.onSuspendOrganization(orgID);
}}
disabled={
props.savingByOrgID[orgID] ||
props.billingLoadingByOrgID[orgID] ||
currentSubState === 'suspended'
]}
keyExtractor={(org) => org.org_id}
isRowExpanded={(org) => props.expandedOrgID === (org.org_id || '').trim()}
expandedRender={(org) => {
const orgID = (org.org_id || '').trim();
return (
<div class="px-3 pb-3 bg-surface-alt whitespace-normal">
<div class="rounded-md border border-border bg-surface-alt p-3">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-2">
<div class="text-xs font-semibold text-muted">Billing state JSON</div>
<Button
variant="secondary"
size="xs"
disabled={props.billingLoadingByOrgID[orgID] || props.savingByOrgID[orgID]}
onClick={() => {
props.onReloadOrganization(orgID);
}}
>
Reload
</Button>
</div>
<Show
when={props.billingByOrgID[orgID]}
fallback={
<p role="status" class="text-sm text-muted">
{props.billingErrorByOrgID[orgID] || 'Loading billing state...'}
</p>
}
>
Suspend Org
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => {
props.onActivateOrganization(orgID);
}}
disabled={
props.savingByOrgID[orgID] ||
props.billingLoadingByOrgID[orgID] ||
currentSubState === 'active'
}
>
Activate Org
</Button>
<pre class="text-xs overflow-x-auto whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-base-content">
{JSON.stringify(props.billingByOrgID[orgID], null, 2)}
</pre>
</Show>
</div>
);
},
},
]}
keyExtractor={(org) => org.org_id}
isRowExpanded={(org) => props.expandedOrgID === (org.org_id || '').trim()}
expandedRender={(org) => {
const orgID = (org.org_id || '').trim();
return (
<div class="px-3 pb-3 bg-surface-alt">
<div class="rounded-md border border-border bg-surface-alt p-3">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-2">
<div class="text-xs font-semibold text-muted">Billing state JSON</div>
<Button
variant="secondary"
size="xs"
onClick={() => {
props.onReloadOrganization(orgID);
}}
>
Reload
</Button>
</div>
<pre class="text-xs overflow-x-auto whitespace-pre-wrap font-mono text-base-content">
{JSON.stringify(props.billingByOrgID[orgID] ?? { loading: true }, null, 2)}
</pre>
</div>
</div>
);
}}
/>
);
);
}}
/>
);
};
@@ -38,33 +38,40 @@ export const BillingAdminPanel: Component = () => {
bodyClass="space-y-4"
>
<Show when={state.orgsError()}>
<div class="rounded-md border border-red-200 dark:border-red-900/25 bg-red-50 dark:bg-red-900/25 p-3 text-sm text-red-800 dark:text-red-200">
<div
role="alert"
class="rounded-md border border-red-200 dark:border-red-900/25 bg-red-50 dark:bg-red-900/25 p-3 text-sm text-red-800 dark:text-red-200"
>
{state.orgsError()}
</div>
</Show>
<div class="mt-4">
<BillingAdminOrganizationsTable
orgs={state.orgs()}
isLoading={state.loadingOrgs()}
billingByOrgID={state.billingByOrgID()}
billingLoadingByOrgID={state.billingLoadingByOrgID()}
savingByOrgID={state.savingByOrgID()}
expandedOrgID={state.expandedOrgID()}
onToggleOrganization={(orgID) => {
void state.toggleExpandedOrganization(orgID);
}}
onSuspendOrganization={(orgID) => {
void state.updateSubscriptionState(orgID, 'suspended');
}}
onActivateOrganization={(orgID) => {
void state.updateSubscriptionState(orgID, 'active');
}}
onReloadOrganization={(orgID) => {
void state.reloadOrganization(orgID);
}}
/>
</div>
<Show when={!state.orgsError()}>
<div class="mt-4" aria-busy={state.loadingOrgs()}>
<BillingAdminOrganizationsTable
orgs={state.orgs()}
isLoading={state.loadingOrgs()}
billingByOrgID={state.billingByOrgID()}
billingLoadingByOrgID={state.billingLoadingByOrgID()}
billingErrorByOrgID={state.billingErrorByOrgID()}
canManageBilling={state.canManageBilling()}
savingByOrgID={state.savingByOrgID()}
expandedOrgID={state.expandedOrgID()}
onToggleOrganization={(orgID) => {
void state.toggleExpandedOrganization(orgID);
}}
onSuspendOrganization={(orgID) => {
void state.updateSubscriptionState(orgID, 'suspended');
}}
onActivateOrganization={(orgID) => {
void state.updateSubscriptionState(orgID, 'active');
}}
onReloadOrganization={(orgID) => {
void state.reloadOrganization(orgID);
}}
/>
</div>
</Show>
</SettingsPanel>
</Show>
);
@@ -6,6 +6,7 @@ import billingAdminOrganizationsTableSource from '../BillingAdminOrganizationsTa
import billingAdminPanelSource from '../BillingAdminPanel.tsx?raw';
import billingAdminPanelStateSource from '../useBillingAdminPanelState.ts?raw';
const isMobileMock = vi.fn();
const listOrganizationsMock = vi.fn();
const getBillingStateMock = vi.fn();
const putBillingStateMock = vi.fn();
@@ -13,6 +14,10 @@ const successMock = vi.fn();
const errorMock = vi.fn();
const presentationPolicyHidesOrganizationSurfacesMock = vi.fn();
vi.mock('@/hooks/useBreakpoint', () => ({
useBreakpoint: () => ({ isMobile: () => isMobileMock() }),
}));
vi.mock('@/api/billingAdmin', () => ({
BillingAdminAPI: {
listOrganizations: (...args: unknown[]) => listOrganizationsMock(...args),
@@ -34,6 +39,7 @@ vi.mock('@/stores/notifications', () => ({
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
presentationPolicyIsReadOnly: () => false,
presentationPolicyHidesOrganizationSurfaces: (...args: unknown[]) =>
presentationPolicyHidesOrganizationSurfacesMock(...args),
}));
@@ -46,6 +52,7 @@ vi.mock('@/utils/logger', () => ({
describe('BillingAdminPanel', () => {
beforeEach(() => {
isMobileMock.mockReset().mockReturnValue(false);
listOrganizationsMock.mockReset();
getBillingStateMock.mockReset();
putBillingStateMock.mockReset();
@@ -178,4 +185,25 @@ describe('BillingAdminPanel', () => {
expect(listOrganizationsMock).not.toHaveBeenCalled();
expect(getBillingStateMock).not.toHaveBeenCalled();
});
it('keeps one set of mobile subscription actions beside their confirmed billing state', async () => {
isMobileMock.mockReturnValue(true);
getBillingStateMock.mockResolvedValue({
capabilities: [],
limits: {},
meters_enabled: [],
subscription_state: 'active',
});
putBillingStateMock.mockImplementation(async (_orgID, payload) => payload);
render(() => <BillingAdminPanel />);
await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled());
expect(screen.getAllByRole('button', { name: 'Suspend Org' })).toHaveLength(1);
expect(screen.getAllByRole('button', { name: 'Activate Org' })).toHaveLength(1);
expect(screen.getByRole('button', { name: 'Suspend Org' }).closest('td')).toHaveTextContent(
'Active',
);
await fireEvent.click(screen.getByRole('button', { name: 'Suspend Org' }));
await waitFor(() => expect(putBillingStateMock).toHaveBeenCalledTimes(1));
expect(putBillingStateMock.mock.calls[0][0]).toBe('org-1');
expect(putBillingStateMock.mock.calls[0][1].subscription_state).toBe('suspended');
});
});
@@ -0,0 +1,439 @@
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { BillingAdminPanel } from '../BillingAdminPanel';
import {
BILLING_ADMIN_READ_ERROR,
BILLING_ADMIN_UNCONFIRMED_CHANGE,
useBillingAdminPanelState,
} from '../useBillingAdminPanelState';
import type { BillingState } from '@/api/billingAdmin';
const mocks = vi.hoisted(() => ({
list: vi.fn(),
get: vi.fn(),
put: vi.fn(),
success: vi.fn(),
error: vi.fn(),
log: vi.fn(),
hosted: vi.fn(),
multi: vi.fn(),
hidden: vi.fn(),
readOnly: vi.fn(),
}));
vi.mock('@/api/billingAdmin', () => ({
BillingAdminAPI: {
listOrganizations: mocks.list,
getBillingState: mocks.get,
putBillingState: mocks.put,
},
}));
vi.mock('@/stores/license', () => ({
isHostedModeEnabled: mocks.hosted,
isMultiTenantEnabled: mocks.multi,
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
presentationPolicyHidesOrganizationSurfaces: mocks.hidden,
presentationPolicyIsReadOnly: mocks.readOnly,
}));
vi.mock('@/stores/notifications', () => ({
notificationStore: { success: mocks.success, error: mocks.error },
}));
vi.mock('@/utils/logger', () => ({ logger: { error: mocks.log } }));
const deferred = <T,>() => {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
};
const org = (id = 'org-a') => ({
org_id: id,
display_name: `Organization ${id}`,
owner_user_id: 'owner',
created_at: '2026-01-01',
suspended: false,
soft_deleted: false,
});
const billing = (name = 'active'): BillingState => ({
subscription_state: name,
capabilities: ['multi_tenant'],
limits: { max_nodes: 20 },
meters_enabled: [],
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
const signalAt = (mock: typeof mocks.list, call = 0, position = 0) =>
(mock.mock.calls[call][position] as { signal: AbortSignal }).signal;
const mountState = () => {
let state!: ReturnType<typeof useBillingAdminPanelState>;
const view = render(() => {
state = useBillingAdminPanelState();
return null;
});
return { state, unmount: view.unmount };
};
let setHosted!: (v: boolean) => void;
let setMulti!: (v: boolean) => void;
let setHidden!: (v: boolean) => void;
let setReadOnly!: (v: boolean) => void;
beforeEach(() => {
Object.values(mocks).forEach((mock) => mock.mockReset());
const [hosted, hostedSetter] = createSignal(true);
setHosted = hostedSetter;
const [multi, multiSetter] = createSignal(true);
setMulti = multiSetter;
const [hidden, hiddenSetter] = createSignal(false);
setHidden = hiddenSetter;
const [readOnly, readOnlySetter] = createSignal(false);
setReadOnly = readOnlySetter;
mocks.hosted.mockImplementation(hosted);
mocks.multi.mockImplementation(multi);
mocks.hidden.mockImplementation(hidden);
mocks.readOnly.mockImplementation(readOnly);
mocks.list.mockResolvedValue([org()]);
mocks.get.mockResolvedValue(billing());
mocks.put.mockImplementation(async (_id, payload) => payload);
});
afterEach(cleanup);
describe('Billing Admin accepted inventory and billing reads', () => {
it('disables both actions until the actual row read succeeds', async () => {
const pending = deferred<BillingState>();
mocks.get.mockReturnValueOnce(pending.promise);
render(() => <BillingAdminPanel />);
await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Activate Org' })).toBeDisabled();
expect(screen.queryByText('N/A')).not.toBeInTheDocument();
pending.resolve(billing());
await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled());
});
it('removes the former inventory on refresh and distinguishes failure from an empty inventory', async () => {
render(() => <BillingAdminPanel />);
await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled());
const pending = deferred<unknown>();
mocks.list.mockReturnValueOnce(pending.promise);
await fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
expect(screen.queryByText('Organization org-a')).not.toBeInTheDocument();
pending.reject(new Error('SYNTHETIC PRIVATE BACKEND DETAIL'));
await waitFor(() =>
expect(screen.getByRole('alert')).toHaveTextContent('Unable to load the organization list.'),
);
expect(screen.queryByText(/No organizations/)).not.toBeInTheDocument();
expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument();
expect(mocks.error).not.toHaveBeenCalled();
mocks.list.mockResolvedValueOnce([]);
await fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
await waitFor(() => expect(screen.getByText(/No organizations/)).toBeInTheDocument());
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(mocks.get).toHaveBeenCalledTimes(1);
});
it.each([
null,
{},
[org(), org()],
[{ ...org(), org_id: ' ' }],
[{ ...org(), org_id: ' org-a' }],
])('does not turn malformed inventory %j into usable rows', async (data) => {
mocks.list.mockResolvedValueOnce(data);
const { state } = mountState();
await settle();
expect(state.orgsError()).toBeTruthy();
expect(state.orgs()).toEqual([]);
expect(mocks.get).not.toHaveBeenCalled();
});
it('keeps a failed row unavailable without automatic retries as other rows finish, and offers a read-only reload', async () => {
const other = deferred<BillingState>();
mocks.list.mockResolvedValue([org(), org('org-b')]);
mocks.get
.mockRejectedValueOnce(new Error('SYNTHETIC PRIVATE BILLING DETAIL'))
.mockReturnValueOnce(other.promise)
.mockResolvedValue(billing());
render(() => <BillingAdminPanel />);
await waitFor(() =>
expect(screen.getByRole('alert')).toHaveTextContent(BILLING_ADMIN_READ_ERROR),
);
other.resolve(billing());
await settle();
await settle();
expect(mocks.get).toHaveBeenCalledTimes(2);
expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument();
await fireEvent.click(screen.getByRole('button', { name: 'Organization org-a org-a' }));
expect(screen.getByRole('status')).toHaveTextContent(BILLING_ADMIN_READ_ERROR);
expect(screen.queryByText(/"loading": true/)).not.toBeInTheDocument();
const before = mocks.put.mock.calls.length;
await fireEvent.click(
screen.getByRole('button', { name: 'Reload billing for Organization org-a' }),
);
await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
expect(mocks.get).toHaveBeenCalledTimes(3);
expect(mocks.put).toHaveBeenCalledTimes(before);
});
it.each([
null,
{},
{ ...billing(), capabilities: null },
{ ...billing(), limits: [] },
{ ...billing(), limits: { users: NaN } },
{ ...billing(), meters_enabled: 'all' },
{ ...billing(), subscription_state: '' },
])('rejects malformed billing %j rather than enabling a write', async (data) => {
mocks.get.mockResolvedValueOnce(data);
const { state } = mountState();
await settle();
expect(state.billingErrorByOrgID()['org-a']).toBe(BILLING_ADMIN_READ_ERROR);
expect(state.billingByOrgID()['org-a']).toBeUndefined();
await state.updateSubscriptionState('org-a', 'suspended');
expect(mocks.put).not.toHaveBeenCalled();
expect(mocks.get).toHaveBeenCalledTimes(1);
});
it.each(['success', 'failure'])(
'ignores an obsolete row reload %s without ending its replacement spinner',
async (outcome) => {
const old = deferred<BillingState>();
const current = deferred<BillingState>();
mocks.get.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise);
const { state } = mountState();
await settle();
const reload = state.reloadOrganization('org-a');
expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
if (outcome === 'success') old.resolve(billing('obsolete'));
else old.reject(new Error('obsolete'));
await settle();
expect(state.billingLoadingByOrgID()['org-a']).toBe(true);
expect(state.billingByOrgID()['org-a']).toBeUndefined();
expect(state.billingErrorByOrgID()['org-a']).toBeUndefined();
expect(mocks.log).not.toHaveBeenCalled();
current.resolve(billing('trialing'));
await reload;
expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('trialing');
},
);
it('ignores obsolete list success and failure across repeated refreshes', async () => {
const first = deferred<ReturnType<typeof org>[]>();
const second = deferred<ReturnType<typeof org>[]>();
mocks.list
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise)
.mockResolvedValueOnce([org('current')]);
const { state } = mountState();
const middle = state.refreshOrganizations();
await state.refreshOrganizations();
expect(signalAt(mocks.list, 0).aborted).toBe(true);
expect(signalAt(mocks.list, 1).aborted).toBe(true);
first.resolve([org('obsolete')]);
second.reject(new Error('obsolete'));
await middle;
await settle();
expect(state.orgs().map((o) => o.org_id)).toEqual(['current']);
expect(state.orgsError()).toBeNull();
expect(mocks.log).not.toHaveBeenCalled();
expect(mocks.get.mock.calls.map((c) => c[0])).toEqual(['current']);
});
it('does not let a previous inventory billing completion overwrite a new row with the same ID', async () => {
const old = deferred<BillingState>();
const current = deferred<BillingState>();
mocks.get.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise);
const { state } = mountState();
await settle();
const refreshing = state.refreshOrganizations();
await settle();
current.resolve(billing('trialing'));
await refreshing;
old.resolve(billing('obsolete'));
await settle();
expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('trialing');
expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
});
it.each(['hosted', 'multi', 'hidden'])(
'clears and invalidates %s withdrawal, then reads afresh on re-entry',
async (kind) => {
const old = deferred<ReturnType<typeof org>[]>();
mocks.list.mockReturnValueOnce(old.promise);
const { state } = mountState();
const withdraw = () =>
kind === 'hosted' ? setHosted(false) : kind === 'multi' ? setMulti(false) : setHidden(true);
const restore = () =>
kind === 'hosted' ? setHosted(true) : kind === 'multi' ? setMulti(true) : setHidden(false);
withdraw();
await settle();
expect(state.orgs()).toEqual([]);
expect(state.hostedEnabled()).toBe(false);
expect(signalAt(mocks.list).aborted).toBe(true);
restore();
await settle();
old.resolve([org('obsolete')]);
await settle();
expect(state.orgs().map((o) => o.org_id)).toEqual(['org-a']);
expect(mocks.get.mock.calls.map((c) => c[0])).toEqual(['org-a']);
},
);
it('bounds prefetch to six concurrent reads and stops the old pool from admitting queued rows', async () => {
mocks.list.mockResolvedValue(Array.from({ length: 10 }, (_, i) => org(`org-${i}`)));
const pending = Array.from({ length: 6 }, () => deferred<BillingState>());
let n = 0;
mocks.get.mockImplementation(() => pending[n++].promise);
const { state } = mountState();
await settle();
expect(mocks.get).toHaveBeenCalledTimes(6);
setHosted(false);
await settle();
pending.forEach((p) => p.resolve(billing()));
await settle();
await settle();
expect(mocks.get).toHaveBeenCalledTimes(6);
expect(state.orgs()).toEqual([]);
mocks.get.mock.calls.forEach((_c, i) => expect(signalAt(mocks.get, i, 1).aborted).toBe(true));
});
it('disposal aborts reads, clears retained snapshots, and ignores later errors without notifications', async () => {
const pending = deferred<BillingState>();
mocks.get.mockReturnValueOnce(pending.promise);
const { state, unmount } = mountState();
await settle();
unmount();
expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
pending.reject(new Error('late'));
await settle();
expect(state.orgs()).toEqual([]);
expect(state.billingByOrgID()).toEqual({});
expect(mocks.log).not.toHaveBeenCalled();
expect(mocks.error).not.toHaveBeenCalled();
await state.refreshOrganizations();
expect(mocks.list).toHaveBeenCalledTimes(1);
});
it('disposal while listing cannot launch a billing read', async () => {
const pending = deferred<ReturnType<typeof org>[]>();
mocks.list.mockReturnValueOnce(pending.promise);
const { unmount } = mountState();
unmount();
pending.resolve([org()]);
await settle();
expect(mocks.get).not.toHaveBeenCalled();
expect(signalAt(mocks.list).aborted).toBe(true);
});
it('keeps opaque organization IDs separate from object prototypes', async () => {
mocks.list.mockResolvedValue(['__proto__', 'constructor', 'toString'].map(org));
const { state } = mountState();
await settle();
expect(mocks.get).toHaveBeenCalledTimes(3);
for (const id of ['__proto__', 'constructor', 'toString'])
expect(state.billingByOrgID()[id]?.subscription_state).toBe('active');
await state.updateSubscriptionState('__proto__', 'suspended');
expect(mocks.put.mock.calls[0][0]).toBe('__proto__');
expect(Object.prototype).not.toHaveProperty('subscription_state');
});
});
describe('Billing Admin writes require the current accepted snapshot', () => {
it('does not fetch or write implicitly for an unread or unknown organization', async () => {
const pending = deferred<BillingState>();
mocks.get.mockReturnValueOnce(pending.promise);
const { state } = mountState();
await settle();
await state.updateSubscriptionState('org-a', 'suspended');
await state.updateSubscriptionState('foreign', 'active');
expect(mocks.get).toHaveBeenCalledTimes(1);
expect(mocks.put).not.toHaveBeenCalled();
pending.resolve(billing());
});
it('deduplicates writes, preserves all saved billing fields and refuses a row reload while saving', async () => {
const current = {
...billing(),
plan_version: 'cloud_power',
trial_started_at: 10,
trial_ends_at: 20,
stripe_customer_id: 'cus_fixture',
stripe_subscription_id: 'sub_fixture',
stripe_price_id: 'price_fixture',
};
mocks.get.mockResolvedValueOnce(current);
const pending = deferred<BillingState>();
mocks.put.mockReturnValueOnce(pending.promise);
const { state } = mountState();
await settle();
const writing = state.updateSubscriptionState('org-a', 'suspended');
await state.updateSubscriptionState('org-a', 'suspended');
await state.reloadOrganization('org-a');
expect(mocks.put).toHaveBeenCalledTimes(1);
expect(mocks.get).toHaveBeenCalledTimes(1);
expect(mocks.put.mock.calls[0][1]).toEqual({ ...current, subscription_state: 'suspended' });
pending.resolve({ ...current, subscription_state: 'suspended' });
await writing;
expect(state.savingByOrgID()['org-a']).toBe(false);
expect(mocks.success).toHaveBeenCalledTimes(1);
await state.updateSubscriptionState('org-a', 'suspended');
expect(mocks.put).toHaveBeenCalledTimes(1);
});
it.each(['rejected', 'malformed', 'mismatched'])(
'withdraws the snapshot after an unconfirmed %s update without retrying or claiming rollback',
async (kind) => {
if (kind === 'rejected')
mocks.put.mockRejectedValueOnce(new Error('SYNTHETIC PRIVATE UPDATE DETAIL'));
else mocks.put.mockResolvedValueOnce(kind === 'mismatched' ? billing('active') : {});
const { state } = mountState();
await settle();
await state.updateSubscriptionState('org-a', 'suspended');
expect(state.billingByOrgID()['org-a']).toBeUndefined();
expect(state.billingErrorByOrgID()['org-a']).toBe(BILLING_ADMIN_UNCONFIRMED_CHANGE);
expect(mocks.success).not.toHaveBeenCalled();
expect(mocks.error).not.toHaveBeenCalled();
await state.updateSubscriptionState('org-a', 'active');
expect(mocks.put).toHaveBeenCalledTimes(1);
expect(mocks.get).toHaveBeenCalledTimes(1);
mocks.get.mockResolvedValueOnce(billing('suspended'));
await state.reloadOrganization('org-a');
expect(state.billingErrorByOrgID()['org-a']).toBeUndefined();
expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('suspended');
},
);
it.each(['refresh', 'read-only', 'dispose'])(
'invalidates a pending write on %s without applying its completion to the new snapshot',
async (kind) => {
const pending = deferred<BillingState>();
mocks.put.mockReturnValueOnce(pending.promise);
const { state, unmount } = mountState();
await settle();
const writing = state.updateSubscriptionState('org-a', 'suspended');
if (kind === 'refresh') {
mocks.list.mockResolvedValueOnce([org('org-b')]);
await state.refreshOrganizations();
} else if (kind === 'read-only') {
setReadOnly(true);
await settle();
} else unmount();
expect(signalAt(mocks.put, 0, 2).aborted).toBe(true);
pending.resolve(billing('suspended'));
await writing;
expect(mocks.success).not.toHaveBeenCalled();
expect(mocks.error).not.toHaveBeenCalled();
if (kind === 'dispose') expect(state.billingByOrgID()['org-a']).toBeUndefined();
else if (kind === 'refresh') {
expect(state.billingByOrgID()['org-a']).toBeUndefined();
await state.updateSubscriptionState('org-a', 'suspended');
} else {
expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('active');
await state.updateSubscriptionState('org-a', 'suspended');
}
expect(mocks.put).toHaveBeenCalledTimes(1);
},
);
});
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal } from 'solid-js';
import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';
import {
BillingAdminAPI,
type BillingState,
@@ -6,12 +6,49 @@ import {
} from '@/api/billingAdmin';
import { isHostedModeEnabled, isMultiTenantEnabled } from '@/stores/license';
import { notificationStore } from '@/stores/notifications';
import { presentationPolicyHidesOrganizationSurfaces } from '@/stores/sessionPresentationPolicy';
import {
presentationPolicyHidesOrganizationSurfaces,
presentationPolicyIsReadOnly,
} from '@/stores/sessionPresentationPolicy';
import { logger } from '@/utils/logger';
import { getBillingAdminStateUpdateSuccessMessage } from '@/utils/licensePresentation';
import { getOrganizationSettingsLoadErrorMessage as getOrganizationSettingsPanelLoadErrorMessage } from '@/utils/organizationSettingsPresentation';
import { getOrganizationSettingsLoadErrorMessage } from '@/utils/organizationSettingsPresentation';
export type BillingStateCache = Record<string, BillingState | undefined>;
const emptyRecord = <T>(): Record<string, T> => Object.create(null);
const withEntry = <T>(entries: Record<string, T>, key: string, value: T): Record<string, T> =>
Object.assign(emptyRecord<T>(), entries, { [key]: value });
export const BILLING_ADMIN_READ_ERROR =
'Billing state is unavailable. Reload it before making changes.';
export const BILLING_ADMIN_UNCONFIRMED_CHANGE =
'The subscription change could not be confirmed. Reload billing state before making another change.';
const isBillingState = (value: unknown): value is BillingState => {
if (!value || typeof value !== 'object') return false;
const state = value as BillingState;
const isStringArray = (items: unknown) =>
Array.isArray(items) && items.every((item) => typeof item === 'string');
return (
typeof state.subscription_state === 'string' &&
state.subscription_state.trim().length > 0 &&
isStringArray(state.capabilities) &&
!!state.limits &&
typeof state.limits === 'object' &&
!Array.isArray(state.limits) &&
Object.values(state.limits).every(
(limit) => typeof limit === 'number' && Number.isFinite(limit),
) &&
(state.meters_enabled === undefined || isStringArray(state.meters_enabled)) &&
['plan_version', 'stripe_customer_id', 'stripe_subscription_id', 'stripe_price_id'].every(
(key) =>
state[key as keyof BillingState] === undefined ||
typeof state[key as keyof BillingState] === 'string',
) &&
[state.trial_started_at, state.trial_ends_at].every(
(time) => time == null || (typeof time === 'number' && Number.isFinite(time)),
)
);
};
async function promisePool<T>(items: T[], concurrency: number, fn: (item: T) => Promise<void>) {
if (items.length === 0) return;
@@ -32,12 +69,18 @@ export function useBillingAdminPanelState() {
const [orgs, setOrgs] = createSignal<HostedOrganizationSummary[]>([]);
const [loadingOrgs, setLoadingOrgs] = createSignal(false);
const [orgsError, setOrgsError] = createSignal<string | null>(null);
const [billingByOrgID, setBillingByOrgID] = createSignal<BillingStateCache>({});
const [billingLoadingByOrgID, setBillingLoadingByOrgID] = createSignal<Record<string, boolean>>(
{},
);
const [savingByOrgID, setSavingByOrgID] = createSignal<Record<string, boolean>>({});
const [billingByOrgID, setBillingByOrgID] = createSignal<BillingStateCache>(emptyRecord());
const [billingLoadingByOrgID, setBillingLoadingByOrgID] =
createSignal<Record<string, boolean>>(emptyRecord());
const [billingErrorByOrgID, setBillingErrorByOrgID] =
createSignal<Record<string, string>>(emptyRecord());
const [savingByOrgID, setSavingByOrgID] = createSignal<Record<string, boolean>>(emptyRecord());
const [expandedOrgID, setExpandedOrgID] = createSignal<string | null>(null);
let generation = 0;
let disposed = false;
let listController: AbortController | undefined;
const billingReads = new Map<string, AbortController>();
const billingWrites = new Map<string, AbortController>();
const hostedEnabled = createMemo(
() =>
@@ -45,118 +88,206 @@ export function useBillingAdminPanelState() {
isHostedModeEnabled() &&
!presentationPolicyHidesOrganizationSurfaces(),
);
const canManageBilling = () => hostedEnabled() && !presentationPolicyIsReadOnly();
const isCurrent = (request: number) => !disposed && request === generation && hostedEnabled();
const hasCurrentOrganization = (orgID: string) =>
!loadingOrgs() && !orgsError() && orgs().some((org) => org.org_id === orgID);
const setBillingLoading = (orgID: string, value: boolean) => {
setBillingLoadingByOrgID((prev) => ({ ...prev, [orgID]: value }));
const invalidateRequests = () => {
generation += 1;
listController?.abort();
listController = undefined;
for (const controller of billingReads.values()) controller.abort();
for (const controller of billingWrites.values()) controller.abort();
billingReads.clear();
billingWrites.clear();
};
const setSaving = (orgID: string, value: boolean) => {
setSavingByOrgID((prev) => ({ ...prev, [orgID]: value }));
};
const loadOrganizations = async () => {
setLoadingOrgs(true);
const clearSnapshot = () => {
setOrgs([]);
setOrgsError(null);
try {
const next = await BillingAdminAPI.listOrganizations();
setOrgs(next ?? []);
} catch (err) {
logger.error('Failed to list hosted organizations', err);
const msg = err instanceof Error ? err.message : '';
const errorMessage = getOrganizationSettingsPanelLoadErrorMessage(msg, 'billing-admin');
setOrgsError(errorMessage);
notificationStore.error(errorMessage);
} finally {
setLoadingOrgs(false);
}
setBillingByOrgID(emptyRecord<BillingState | undefined>());
setBillingLoadingByOrgID(emptyRecord<boolean>());
setBillingErrorByOrgID(emptyRecord<string>());
setSavingByOrgID(emptyRecord<boolean>());
setExpandedOrgID(null);
};
const ensureBillingState = async (orgID: string): Promise<BillingState | null> => {
const cached = billingByOrgID()[orgID];
if (cached) return cached;
const ensureBillingState = async (orgID: string, request = generation) => {
if (
!isCurrent(request) ||
!hasCurrentOrganization(orgID) ||
billingByOrgID()[orgID] ||
billingReads.has(orgID) ||
billingWrites.has(orgID) ||
billingErrorByOrgID()[orgID]
)
return;
if (billingLoadingByOrgID()[orgID]) {
return null;
}
setBillingLoading(orgID, true);
const controller = new AbortController();
billingReads.set(orgID, controller);
const readIsCurrent = () =>
isCurrent(request) && hasCurrentOrganization(orgID) && billingReads.get(orgID) === controller;
setBillingLoadingByOrgID((prev) => withEntry(prev, orgID, true));
try {
const state = await BillingAdminAPI.getBillingState(orgID);
setBillingByOrgID((prev) => ({ ...prev, [orgID]: state }));
return state;
const state = await BillingAdminAPI.getBillingState(orgID, { signal: controller.signal });
if (!readIsCurrent()) return;
if (!isBillingState(state)) throw new Error('Billing state returned invalid data');
setBillingByOrgID((prev) => withEntry<BillingState | undefined>(prev, orgID, state));
} catch (err) {
if (!readIsCurrent()) return;
logger.error('Failed to fetch billing state', { orgID, err });
return null;
setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_READ_ERROR));
} finally {
setBillingLoading(orgID, false);
}
};
const updateSubscriptionState = async (orgID: string, nextState: 'suspended' | 'active') => {
setSaving(orgID, true);
try {
const current =
(await ensureBillingState(orgID)) ?? (await BillingAdminAPI.getBillingState(orgID));
const planVersion = current.plan_version?.trim() || undefined;
const payload: BillingState = {
...current,
subscription_state: nextState,
capabilities: Array.isArray(current.capabilities) ? current.capabilities : [],
limits: current.limits ?? {},
meters_enabled: Array.isArray(current.meters_enabled) ? current.meters_enabled : [],
...(planVersion ? { plan_version: planVersion } : {}),
};
const saved = await BillingAdminAPI.putBillingState(orgID, payload);
setBillingByOrgID((prev) => ({ ...prev, [orgID]: saved }));
notificationStore.success(getBillingAdminStateUpdateSuccessMessage(nextState), 2500);
} catch (err) {
logger.error('Failed to update billing state', { orgID, err });
const msg = err instanceof Error ? err.message : 'Failed to update billing state';
notificationStore.error(msg);
} finally {
setSaving(orgID, false);
if (readIsCurrent()) {
billingReads.delete(orgID);
setBillingLoadingByOrgID((prev) => withEntry(prev, orgID, false));
}
}
};
const refreshOrganizations = async () => {
setBillingByOrgID({});
setExpandedOrgID(null);
await loadOrganizations();
if (disposed) return;
invalidateRequests();
const request = generation;
batch(() => {
clearSnapshot();
setLoadingOrgs(hostedEnabled());
});
if (!hostedEnabled()) return;
const controller = new AbortController();
listController = controller;
let next: HostedOrganizationSummary[];
try {
next = await BillingAdminAPI.listOrganizations({ signal: controller.signal });
if (!isCurrent(request)) return;
if (
!Array.isArray(next) ||
next.some(
(org) =>
!org ||
typeof org.org_id !== 'string' ||
!org.org_id.trim() ||
org.org_id !== org.org_id.trim(),
) ||
new Set(next.map((org) => org.org_id)).size !== next.length
)
throw new Error('Hosted organizations returned invalid data');
setOrgs(next);
} catch (err) {
if (!isCurrent(request)) return;
logger.error('Failed to list hosted organizations', err);
setOrgsError(getOrganizationSettingsLoadErrorMessage('', 'billing-admin'));
return;
} finally {
if (isCurrent(request)) {
listController = undefined;
setLoadingOrgs(false);
}
}
// One bounded prefetch per accepted inventory, not a reactive retry loop.
// Invalidation also prevents the old pool from admitting its queued rows.
await promisePool(next, 6, async (org) => {
await ensureBillingState(org.org_id, request);
});
};
const updateSubscriptionState = async (orgID: string, nextState: 'suspended' | 'active') => {
const request = generation;
const current = billingByOrgID()[orgID];
if (
!isCurrent(request) ||
!canManageBilling() ||
!hasCurrentOrganization(orgID) ||
!current ||
billingReads.has(orgID) ||
billingWrites.has(orgID) ||
billingErrorByOrgID()[orgID] ||
current.subscription_state.toLowerCase() === nextState
)
return;
const controller = new AbortController();
billingWrites.set(orgID, controller);
const writeIsCurrent = () =>
isCurrent(request) &&
canManageBilling() &&
hasCurrentOrganization(orgID) &&
billingWrites.get(orgID) === controller;
setSavingByOrgID((prev) => withEntry(prev, orgID, true));
try {
const planVersion = current.plan_version?.trim() || undefined;
const payload: BillingState = {
...current,
subscription_state: nextState,
...(planVersion ? { plan_version: planVersion } : {}),
};
const saved = await BillingAdminAPI.putBillingState(orgID, payload, {
signal: controller.signal,
});
if (!writeIsCurrent()) return;
if (!isBillingState(saved) || saved.subscription_state.toLowerCase() !== nextState) {
throw new Error('Billing update did not confirm the requested subscription state');
}
setBillingByOrgID((prev) => withEntry<BillingState | undefined>(prev, orgID, saved));
notificationStore.success(getBillingAdminStateUpdateSuccessMessage(nextState), 2500);
} catch (err) {
if (!writeIsCurrent()) return;
logger.error('Failed to update billing state', { orgID, err });
batch(() => {
setBillingByOrgID((prev) => withEntry<BillingState | undefined>(prev, orgID, undefined));
setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_UNCONFIRMED_CHANGE));
});
} finally {
if (writeIsCurrent()) {
billingWrites.delete(orgID);
setSavingByOrgID((prev) => withEntry(prev, orgID, false));
}
}
};
const toggleExpandedOrganization = async (orgID: string) => {
if (!orgID) return;
setExpandedOrgID((prev) => (prev === orgID ? null : orgID));
await ensureBillingState(orgID);
if (!isCurrent(generation) || !hasCurrentOrganization(orgID)) return;
const opening = expandedOrgID() !== orgID;
setExpandedOrgID(opening ? orgID : null);
if (opening) await ensureBillingState(orgID);
};
const reloadOrganization = async (orgID: string) => {
if (!orgID) return;
setBillingByOrgID((prev) => ({ ...prev, [orgID]: undefined }));
if (!isCurrent(generation) || !hasCurrentOrganization(orgID) || billingWrites.has(orgID))
return;
billingReads.get(orgID)?.abort();
billingReads.delete(orgID);
batch(() => {
setBillingByOrgID((prev) => withEntry<BillingState | undefined>(prev, orgID, undefined));
setBillingErrorByOrgID((prev) => {
const next = Object.assign(emptyRecord<string>(), prev);
delete next[orgID];
return next;
});
});
await ensureBillingState(orgID);
};
createEffect(() => {
if (!hostedEnabled()) return;
void loadOrganizations();
});
createEffect(() => {
const list = orgs();
if (!hostedEnabled() || loadingOrgs() || list.length === 0) return;
const missing = list.map((o) => o.org_id).filter((id) => id && !billingByOrgID()[id]);
if (missing.length === 0) return;
void promisePool(missing, 6, async (orgID) => {
await ensureBillingState(orgID);
createEffect(
on([hostedEnabled, presentationPolicyIsReadOnly], () => void refreshOrganizations()),
);
onCleanup(() => {
disposed = true;
invalidateRequests();
batch(() => {
clearSnapshot();
setLoadingOrgs(false);
});
});
return {
billingByOrgID,
billingErrorByOrgID,
billingLoadingByOrgID,
canManageBilling,
expandedOrgID,
hostedEnabled,
loadingOrgs,
@@ -9,8 +9,8 @@ const frontendRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)),
const repoRoot = path.resolve(frontendRoot, '..');
const readDoc = (name: string) => readFileSync(path.join(repoRoot, 'docs', `${name}.md`), 'utf8');
const guide = readDoc('KUBERNETES');
// js-yaml is already in the committed lint/build graph. Parse the copied YAML,
// rather than accepting a permissions sentence elsewhere in the guide.
// js-yaml is an explicit test dependency, not an incidental ESLint dependency.
// Parse the copied YAML rather than accepting a permissions sentence elsewhere.
const yaml = createRequire(import.meta.url)('js-yaml') as {
loadAll: (text: string) => unknown[];
};
@@ -150,15 +150,32 @@ describe('frontend dependency security floors', () => {
it('keeps every js-yaml copy above the empty-merge CPU exhaustion floor', () => {
// GHSA-2883-xcg3-v3hh: our override keeps every transitive copy on patched 4.x.
// The Kubernetes docs tests parse the actual copied RBAC YAML. Declare that
// consumer directly instead of relying on legacy ESLint's transitive copy.
expect(manifest.devDependencies['js-yaml']).toBe('^4.3.2');
expect(manifest.overrides['js-yaml']).toBe('^4.3.2');
const versions = lockedVersions('js-yaml');
expect(versions).not.toHaveLength(0);
expect(versions, 'the Kubernetes docs parser must be installed').not.toHaveLength(0);
for (const version of versions) {
expect(version).not.toContain('-');
expect(atLeast(version, [4, 3, 2]), `js-yaml ${version} is vulnerable`).toBe(true);
}
});
it('keeps modern glob consumers above the minimatch amplification floor', () => {
// GHSA-g3hv-75wg-m249 affects every minimatch release before 11.0.1.
// Scope the override to modern v10 edges, not callable/default v3 consumers.
expect(manifest.overrides['minimatch@^10.0.0']).toBe('11.0.1');
expect(manifest.overrides.minimatch).toBeUndefined();
expect(lockedVersions('@eslint/eslintrc')).toEqual([]);
const versions = lockedVersions('minimatch');
expect(versions).not.toHaveLength(0);
for (const version of versions) {
expect(version).not.toContain('-');
expect(atLeast(version, [11, 0, 1]), `minimatch ${version} is vulnerable`).toBe(true);
}
});
it.each(['^3.4.13', '^3.4.14', '^3.5.0'])('accepts patched DOMPurify range %s', (range) => {
expect(dompurifyRangeIsPatched(range)).toBe(true);
});
@@ -1177,7 +1177,9 @@ describe('frontend resource type boundaries', () => {
expect(billingAdminPanelSource).not.toContain('soft-deleted');
expect(billingAdminPanelSource).not.toContain('Organization billing suspended');
expect(billingAdminPanelStateSource).toContain('getBillingAdminStateUpdateSuccessMessage');
expect(billingAdminPanelStateSource).toContain('getOrganizationSettingsPanelLoadErrorMessage');
expect(billingAdminPanelStateSource).toContain(
"getOrganizationSettingsLoadErrorMessage('', 'billing-admin')",
);
expect(billingAdminOrganizationsTableSource).toContain('getBillingAdminTrialStatus');
expect(organizationSettingsPresentationSource).toContain(
'export function getOrganizationSettingsLoadErrorMessage',