From 57a0c0e8f95ca32faf884c5d815e5fa15a4fb2bf Mon Sep 17 00:00:00 2001 From: operatoruplift Date: Sat, 3 Oct 2026 02:04:36 +0700 Subject: [PATCH 01/25] fix: upgrade Next.js to 16.3.8 for GHSA-vcvr-r3jv-pc5j The advisory (critical, published 2026-09-30) is remote code execution in the Node.js `ImageResponse` from `next/og` when attacker-controlled values reach SVG content, attributes or styles. This app does not import `next/og` or `ImageResponse`, so it was not exploitable, but `npm audit --omit=dev` reported it as critical. 16.3.8 is the newest 16.3 patch release; eslint-config-next moves with it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHDgeGLvKoi7gnFqUbJ1sw --- package-lock.json | 183 +++++++++++++++------------------------------- package.json | 4 +- 2 files changed, 62 insertions(+), 125 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1cf354b..9ddceae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@wallet-standard/app": "^1.1.1", "@wallet-standard/base": "^1.1.0", "decimal.js": "10.6.0", - "next": "16.3.4", + "next": "16.3.8", "react": "19.3.0", "react-dom": "19.3.0", "server-only": "0.0.1", @@ -29,7 +29,7 @@ "@types/react": "19.2.7", "@types/react-dom": "19.2.3", "eslint": "9.39.1", - "eslint-config-next": "16.3.4", + "eslint-config-next": "16.3.8", "typescript": "5.9.3", "vitest": "5.0.0" }, @@ -1695,15 +1695,15 @@ } }, "node_modules/@next/env": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.3.4.tgz", - "integrity": "sha512-cjWZnUUa6jZq2kFaNe/ZyJdZonOZ/QoN0Zka2nz/FLOrfx14pQuM9c5RaSVkWMqgdt4ksgPAMWPyHSs/CyV48Q==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.3.8.tgz", + "integrity": "sha512-Al9zqHVV7TJv0eFuOU4U7Lvv74PTih4Ch63sk2xCIpSTkE3udFnaOcnzP2lQVymiL7yS9Cj2iClUXlR3EQ5sEw==", "license": "MIT" }, "node_modules/@next/eslint-plugin-next": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.3.4.tgz", - "integrity": "sha512-szW9y2Aumu4z88YXfTzcFsgUAg2k64uzbtcO5L9f1AKS4w/GUKJcbFllRflROVyNPgJtGOnvNxiyp3v6b+prIA==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.3.8.tgz", + "integrity": "sha512-eCR9RcLTZrVS+K3+VOhi0xMdUUGNuriCHHhU1ZoABC/QQ/Gp0OWbLKQxV2/9DkmihYdYRcQWFmZXW8M1AMUXYw==", "dev": true, "license": "MIT", "dependencies": { @@ -1744,9 +1744,9 @@ } }, "node_modules/@next/swc-darwin-arm64": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.3.4.tgz", - "integrity": "sha512-iBr3I5LZNk5/bgl5//iTgD2tcym14MX0Xo7fD//u9dYAEgGzza1y9oywluPtf74YnOswVdH1908aK9xVz7zQTw==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.3.8.tgz", + "integrity": "sha512-2JPRMh2nmQG5CiL7cXGL9AGwnPWJQ//cTtAUCT+w511QHk79SYz3LGv/pc5X643B/WEO0rvu3Yww0hqwt3kgeA==", "cpu": [ "arm64" ], @@ -1760,9 +1760,9 @@ } }, "node_modules/@next/swc-darwin-x64": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.3.4.tgz", - "integrity": "sha512-2dpiSyl2Jw/NrBPaU2MAKGSa+2MR82pJIn4Sm5Rjr+gxAeuh0z158Su3Z2O8zn7UNNq+ej4bToed6RcRN/Lydg==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.3.8.tgz", + "integrity": "sha512-GZtCCOBKJ4leVIT/Th0llWKhD1ca92lzbQiS5R5ON9QkoiFnilFsebDae1JU2a3HWoKMEmEZWGs1AGLavVM72Q==", "cpu": [ "x64" ], @@ -1776,12 +1776,15 @@ } }, "node_modules/@next/swc-linux-arm64-gnu": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.3.4.tgz", - "integrity": "sha512-+t+U8HZT+fApePCS5h89CSH3datz29MkzyfCn+6fpsZBG/oiEOhINcb9rtkv6sdpToLGFn2e6146NzaKCXkqrA==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.3.8.tgz", + "integrity": "sha512-O659ygeQYqneJ1fBKMpFxIFqYkYswu8IAS1OCKK/4f3ZgJJm1dRz4fVJZRi/kLLWjnBKnebOePA4WNv+sV1pVA==", "cpu": [ "arm64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1792,12 +1795,15 @@ } }, "node_modules/@next/swc-linux-arm64-musl": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.3.4.tgz", - "integrity": "sha512-mx03GNs1ocQA5JQ4FxDMmIsNkdrZh8cuezKCrId28e5/gIPU/l7Kcy2+vmCCzdjnnmXJy+iOAu+7K0QppO6Urg==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.3.8.tgz", + "integrity": "sha512-dSjKSyWpzxoO1d3DIZZcP4XJcNaKeLmxQMFOiYl5vuBRMmweIqnAhty8tAmRsvTss779cK1FtYnDMj40e4TQlg==", "cpu": [ "arm64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1808,12 +1814,15 @@ } }, "node_modules/@next/swc-linux-x64-gnu": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.3.4.tgz", - "integrity": "sha512-YIhGY6fSMfha52bnVxnzc9zaVBzJg+cqQTOD8tXIBSx4fuv0pVMxQTE0PaS59YhnMOiYiG09IMwxJAf/CFm/Dw==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.3.8.tgz", + "integrity": "sha512-lbqOuz3RPRcv+o9msNsJw5x4+Y1ZwPTs6vmL6DCf7i0fZfvng/F59wyeDwqHIvV0mK//RBy/jJkZ+nCKsSMXjQ==", "cpu": [ "x64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1824,12 +1833,15 @@ } }, "node_modules/@next/swc-linux-x64-musl": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.3.4.tgz", - "integrity": "sha512-+eaaX6axpDb0yF1GCpiERe6njplvdC+nks/fKfcHu3XPGRrald8P3/X7yv7QLdjA51knnxwl9pxdIJsg+w1L+Q==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.3.8.tgz", + "integrity": "sha512-+316WswI8ScVgZeUd+1KGaXkHhaYQzCjvH/05TZSpJ8zBizb1a4G7DtO7F12jcBIqMOtsz9ji1t48fmKtzqsGA==", "cpu": [ "x64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1840,9 +1852,9 @@ } }, "node_modules/@next/swc-win32-arm64-msvc": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.3.4.tgz", - "integrity": "sha512-0jcXW7Xs/uzICrmgV3MhDYDeRy++1CqnpDIerlPIqYO4bhzB4WNbX/aRnQclustsAyTkFKB0z6rbcjmNg5tR8A==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.3.8.tgz", + "integrity": "sha512-ji0gd4kMYUxO+1fJBIbiBVRCjzG/lloiyCccnlebvb1ZJ5qXCPZqYg4Jl1DrrixnWNMKylzgpmMWx0yNDYXlzw==", "cpu": [ "arm64" ], @@ -1856,9 +1868,9 @@ } }, "node_modules/@next/swc-win32-x64-msvc": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.3.4.tgz", - "integrity": "sha512-vvBzwu1pYQCp92maZCFCIw/XgOTMR5tur9GjakwIo2cmwRTMKajRZZDS9+e4KsUZWKu1E007WUeAFXRRjZeuzw==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.3.8.tgz", + "integrity": "sha512-WcTlaKt/TWkh5kUjdJcUmB1XgZ+1c6fz4Y9fDHL73YNSdGaUWjceeWrrlwF0nv19iABYWC4iAq1oX1w4Bn0vfg==", "cpu": [ "x64" ], @@ -2343,21 +2355,6 @@ "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" } }, - "node_modules/@react-native/dev-middleware/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/@react-native/dev-middleware/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", @@ -13634,13 +13631,13 @@ } }, "node_modules/eslint-config-next": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.3.4.tgz", - "integrity": "sha512-35/8RM10huEL9vlr8hUZMERMENHBrnyHN3ZZkF9efSgzGaqK34jIqry44A956//zriUhUAUW0XSkcolhrryqAA==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.3.8.tgz", + "integrity": "sha512-81vovwMe6NGnoFsl0KUJWzlS+y239i3fdsxs49gSEX3pDQW2cuKy+fxUPXNkQqqx6OCPheYPtBlSufc9aZ0k+w==", "dev": true, "license": "MIT", "dependencies": { - "@next/eslint-plugin-next": "16.3.4", + "@next/eslint-plugin-next": "16.3.8", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", @@ -15729,21 +15726,6 @@ "ws": "*" } }, - "node_modules/jayson/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/jayson/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", @@ -16828,21 +16810,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/metro/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/metro/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", @@ -17013,12 +16980,12 @@ } }, "node_modules/next": { - "version": "16.3.4", - "resolved": "https://registry.npmjs.org/next/-/next-16.3.4.tgz", - "integrity": "sha512-/Ztf6CeRH+ejEXUrYtqI4gkS66eFIHuSwqi60RgcpWKodxFZx2/dqVCMKBwILfAHXQ+F1b1vAudgj3mnxqtoIA==", + "version": "16.3.8", + "resolved": "https://registry.npmjs.org/next/-/next-16.3.8.tgz", + "integrity": "sha512-U7QEZaTini6wKrb8A8hqLLqYQyCetegKjCpJOyxk642vWoMoU1x5PyZCJFvgYgiptA8xc5j/9xYlZFO7w9Sjmw==", "license": "MIT", "dependencies": { - "@next/env": "16.3.4", + "@next/env": "16.3.8", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -17032,14 +16999,14 @@ "node": ">=20.9.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "16.3.4", - "@next/swc-darwin-x64": "16.3.4", - "@next/swc-linux-arm64-gnu": "16.3.4", - "@next/swc-linux-arm64-musl": "16.3.4", - "@next/swc-linux-x64-gnu": "16.3.4", - "@next/swc-linux-x64-musl": "16.3.4", - "@next/swc-win32-arm64-msvc": "16.3.4", - "@next/swc-win32-x64-msvc": "16.3.4", + "@next/swc-darwin-arm64": "16.3.8", + "@next/swc-darwin-x64": "16.3.8", + "@next/swc-linux-arm64-gnu": "16.3.8", + "@next/swc-linux-arm64-musl": "16.3.8", + "@next/swc-linux-x64-gnu": "16.3.8", + "@next/swc-linux-x64-musl": "16.3.8", + "@next/swc-win32-arm64-msvc": "16.3.8", + "@next/swc-win32-x64-msvc": "16.3.8", "sharp": "^0.35.4" }, "peerDependencies": { @@ -17919,21 +17886,6 @@ "ws": "^7" } }, - "node_modules/react-devtools-core/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/react-devtools-core/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", @@ -18036,21 +17988,6 @@ "license": "MIT", "peer": true }, - "node_modules/react-native/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/react-native/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", diff --git a/package.json b/package.json index 553e2f5..dcd0e31 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "@wallet-standard/app": "^1.1.1", "@wallet-standard/base": "^1.1.0", "decimal.js": "10.6.0", - "next": "16.3.4", + "next": "16.3.8", "react": "19.3.0", "react-dom": "19.3.0", "server-only": "0.0.1", @@ -37,7 +37,7 @@ "@types/react": "19.2.7", "@types/react-dom": "19.2.3", "eslint": "9.39.1", - "eslint-config-next": "16.3.4", + "eslint-config-next": "16.3.8", "typescript": "5.9.3", "vitest": "5.0.0" }, From e7eb9318d3a137eaf2f51c988a2177f8a47db835 Mon Sep 17 00:00:00 2001 From: operatoruplift Date: Thu, 8 Oct 2026 01:49:03 +0700 Subject: [PATCH 02/25] feat: let signed-in people delete their account and its data The Solana dApp Store Publisher Policy requires in-app account deletion. Vercel holds no service-role key, so a new security definer function, public.delete_own_account(), deletes auth.users where id = auth.uid() and every owner-keyed row cascades with it. It takes no argument, pins an empty search_path and is executable by authenticated only. My reports gains a Delete account section with an in-page confirmation. The client calls the RPC with the confirmed session only, then clears the account's device alert settings and signs out. Failures say whether anything was deleted, and a retry is safe. Tests: PGlite checks the cascade across all six owner-keyed tables, owner isolation and that anon, service_role and a forged anon subject cannot call it; unit tests cover the client flow; Playwright covers the dialog with mocked Auth and PostgREST. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHDgeGLvKoi7gnFqUbJ1sw --- .github/workflows/ci.yml | 3 +- e2e/account-deletion.spec.ts | 108 ++++++++++++ scripts/verify-account-deletion.mjs | 154 ++++++++++++++++++ src/components/AccountDeletion.module.css | 11 ++ src/components/AccountDeletion.tsx | 68 ++++++++ src/components/AccountPanel.tsx | 56 ++++++- src/components/AlertsPanel.tsx | 4 +- src/lib/account-deletion.ts | 149 +++++++++++++++++ src/lib/alerts.ts | 3 + .../20261007120000_delete_own_account.sql | 26 +++ tests/account-deletion.test.ts | 145 +++++++++++++++++ 11 files changed, 718 insertions(+), 9 deletions(-) create mode 100644 e2e/account-deletion.spec.ts create mode 100644 scripts/verify-account-deletion.mjs create mode 100644 src/components/AccountDeletion.module.css create mode 100644 src/components/AccountDeletion.tsx create mode 100644 src/lib/account-deletion.ts create mode 100644 supabase/migrations/20261007120000_delete_own_account.sql create mode 100644 tests/account-deletion.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f22217..0705d49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,13 +37,14 @@ jobs: - run: npm run lint - run: npm run typecheck - run: npm test - - name: Verify alert migrations and owner isolation + - name: Verify migrations, owner isolation and account deletion run: | npm install --prefix "$RUNNER_TEMP/buffer-pglite" --no-package-lock --no-audit --no-fund @electric-sql/pglite@0.5.8 export BUFFER_PGLITE_MODULE="$RUNNER_TEMP/buffer-pglite/node_modules/@electric-sql/pglite/dist/index.js" node scripts/verify-alert-schema.mjs node scripts/verify-hosted-monitoring.mjs node scripts/verify-monitoring-scheduler.mjs + node scripts/verify-account-deletion.mjs - run: npm run build # Deterministic browser regressions block the release. External credentials diff --git a/e2e/account-deletion.spec.ts b/e2e/account-deletion.spec.ts new file mode 100644 index 0000000..843934b --- /dev/null +++ b/e2e/account-deletion.spec.ts @@ -0,0 +1,108 @@ +import { expect, test, type Page, type Request } from '@playwright/test'; +import { AUTH_MOCK_CONFIGURED, AUTH_STORAGE_KEY, SUPABASE_ORIGIN, authMockSession, authMockUser, installAuthMock } from './auth-mock'; + +const person = authMockUser('00000000-0000-4000-8000-00000000000a', 'leaving@example.test'); +const reports = `${SUPABASE_ORIGIN}/rest/v1/saved_reports**`; +const deletion = `${SUPABASE_ORIGIN}/rest/v1/rpc/delete_own_account`; +const rehearsalKey = `buffer.alerts.rehearsal.v2:${person.id}`; + +test.skip(!AUTH_MOCK_CONFIGURED, 'Requires configured public Supabase URL; every auth and database request stays intercepted locally.'); + +async function openAccount(page: Page) { + await page.addInitScript(key => { + if (sessionStorage.getItem('buffer.deletion-fixture')) return; + sessionStorage.setItem('buffer.deletion-fixture', 'seeded'); + localStorage.setItem(key, JSON.stringify({ version: 2, rules: [], events: [], deliveries: [], monitors: [] })); + localStorage.setItem('buffer.device-reports.v1', JSON.stringify({ version: 1, reports: [] })); + }, rehearsalKey); + await page.route(reports, route => route.fulfill({ json: [] })); + await page.goto('/app'); + await page.locator('button[data-report-storage="cloud"]').click(); + const dialog = page.getByRole('dialog', { name: 'Saved perspectives.' }); + await expect(dialog.getByText('No reports saved yet.')).toBeVisible(); + return dialog; +} + +test('a signed-in person deletes their account after an in-page confirmation', async ({ page }) => { + const session = authMockSession(person); + await installAuthMock(page, { session }); + const calls: Request[] = []; + await page.route(deletion, route => { calls.push(route.request()); return route.fulfill({ json: person.id }); }); + let signedOut = 0; + await page.route(`${SUPABASE_ORIGIN}/auth/v1/logout**`, route => { signedOut++; return route.fulfill({ status: 403, json: { code: 'user_not_found', msg: 'User from sub claim in JWT does not exist' } }); }); + const dialog = await openAccount(page); + + const section = dialog.getByRole('region', { name: 'Delete account' }); + await section.getByRole('button', { name: 'Delete account…' }).click(); + await expect(section.getByRole('heading', { name: `Delete ${person.email} permanently?` })).toBeFocused(); + for (const item of ['Saved reports', 'Monitored wallet addresses and alert rules', 'Alert destinations, events and delivery records']) await expect(section).toContainText(item); + await expect(section.getByRole('link', { name: 'How deletion works' })).toHaveAttribute('href', '/privacy#delete-account'); + await section.getByRole('button', { name: 'Keep my account' }).click(); + await expect(section.getByRole('button', { name: 'Delete account…' })).toBeFocused(); + expect(calls).toHaveLength(0); + + await section.getByRole('button', { name: 'Delete account…' }).click(); + await section.getByRole('button', { name: 'Delete account permanently' }).click(); + + const notice = page.getByRole('status').filter({ hasText: 'Account deleted.' }); + await expect(notice).toBeVisible(); + await expect(notice).toContainText('You are signed out on this device.'); + await expect(page.locator('a.cloud-sign-in')).toBeVisible(); + await expect(dialog).toBeHidden(); + expect(calls).toHaveLength(1); + expect(calls[0].method()).toBe('POST'); + expect(calls[0].postData()).toBe('{}'); + // The caller's own session authorizes the call; the body names no account. + expect(calls[0].headers().authorization).toBe(`Bearer ${session.access_token}`); + expect(signedOut).toBe(1); + expect(await page.evaluate(([session, alerts]) => [localStorage.getItem(session), localStorage.getItem(alerts), localStorage.getItem('buffer.device-reports.v1') !== null], [AUTH_STORAGE_KEY, rehearsalKey])).toEqual([null, null, true]); + await notice.getByRole('button', { name: 'Dismiss' }).click(); + await expect(notice).toHaveCount(0); +}); + +test('an unconfirmed deletion keeps the session, says so, and can be retried', async ({ page }) => { + await installAuthMock(page, { session: authMockSession(person) }); + let reply: 'unavailable' | 'expired' | 'deleted' = 'unavailable'; + let calls = 0; + await page.route(deletion, route => { + calls++; + if (reply === 'unavailable') return route.fulfill({ status: 503, json: { message: 'Mock unavailable' } }); + if (reply === 'expired') return route.fulfill({ status: 401, json: { code: 'PGRST301', message: 'JWT expired' } }); + return route.fulfill({ json: person.id }); + }); + const dialog = await openAccount(page); + const section = dialog.getByRole('region', { name: 'Delete account' }); + await section.getByRole('button', { name: 'Delete account…' }).click(); + await section.getByRole('button', { name: 'Delete account permanently' }).click(); + await expect(section.getByRole('status')).toHaveText('Account deletion could not be confirmed. Try again; repeating it is safe.'); + expect(await page.evaluate(key => JSON.parse(localStorage.getItem(key) || 'null')?.user?.id, AUTH_STORAGE_KEY)).toBe(person.id); + expect(await page.evaluate(key => localStorage.getItem(key) !== null, rehearsalKey)).toBe(true); + + reply = 'expired'; + await section.getByRole('button', { name: 'Delete account permanently' }).click(); + await expect(section.getByRole('status')).toHaveText('Your session has expired. Nothing was deleted. Sign in again, then retry.'); + await expect(dialog.getByText(person.email!, { exact: true })).toBeVisible(); + + reply = 'deleted'; + await section.getByRole('button', { name: 'Delete account permanently' }).click(); + await expect(page.getByRole('status').filter({ hasText: 'Account deleted.' })).toBeVisible(); + expect(calls).toBe(3); +}); + +test('closing the dialog while a deletion is in flight neither cancels it nor hides its result', async ({ page }) => { + await installAuthMock(page, { session: authMockSession(person) }); + let release: (() => Promise) | undefined; + await page.route(deletion, route => { release = () => route.fulfill({ json: person.id }).catch(() => {}); }); + const dialog = await openAccount(page); + const section = dialog.getByRole('region', { name: 'Delete account' }); + await section.getByRole('button', { name: 'Delete account…' }).click(); + await section.getByRole('button', { name: 'Delete account permanently' }).click(); + await expect(section.getByRole('button', { name: 'Deleting your account…' })).toBeDisabled(); + await expect(dialog.getByRole('button', { name: 'Close saved reports' })).toBeDisabled(); + await page.keyboard.press('Escape'); + await expect(dialog).toBeVisible(); + await expect.poll(() => Boolean(release)).toBe(true); + await release!(); + await expect(page.getByRole('status').filter({ hasText: 'Account deleted.' })).toBeVisible(); + await expect(page.locator('a.cloud-sign-in')).toBeVisible(); +}); diff --git a/scripts/verify-account-deletion.mjs b/scripts/verify-account-deletion.mjs new file mode 100644 index 0000000..e70df2f --- /dev/null +++ b/scripts/verify-account-deletion.mjs @@ -0,0 +1,154 @@ +/** + * Local PostgreSQL/WASM checks for self-service account deletion. No hosted + * connection. Hosted Supabase owns auth.users as supabase_auth_admin and runs + * migrations as a non-superuser postgres role, so this fixture creates the + * deletion function as a non-superuser that holds only the auth.users + * privileges that role has. + */ +import { readdir, readFile } from 'node:fs/promises'; +import assert from 'node:assert/strict'; +const { PGlite } = await import(process.env.BUFFER_PGLITE_MODULE || '@electric-sql/pglite'); + +const DELETION_MIGRATION = '20261007120000_delete_own_account.sql'; +const migrations = new URL('../supabase/migrations/', import.meta.url); +const db = new PGlite(); +let checks = 0; +const ownerA = '00000000-0000-4000-8000-00000000000a'; +const ownerB = '00000000-0000-4000-8000-00000000000b'; +const sql = (query, params = []) => db.query(query, params); +const rows = async (query, params = []) => (await sql(query, params)).rows; +async function check(query, expected, params = []) { assert.deepEqual(await rows(query, params), expected); checks++; } +async function rejects(query, code) { await assert.rejects(sql(query), error => error.code === code); checks++; } +async function as(role, owner = '') { + await db.exec(`reset role; set role ${role}; select set_config('request.jwt.claim.sub','${owner}',false);`); +} +async function asAdmin() { await db.exec("reset role; select set_config('request.jwt.claim.sub','',false);"); } + +await db.exec(` + create role anon; create role authenticated; create role service_role bypassrls; + create role supabase_auth_admin; create role buffer_migrator; create role no_grants; + create schema auth authorization supabase_auth_admin; + create table auth.users(id uuid primary key, email text not null); + create table auth.sessions(id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.users(id) on delete cascade); + create table auth.identities(id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.users(id) on delete cascade); + alter table auth.users owner to supabase_auth_admin; + alter table auth.sessions owner to supabase_auth_admin; + alter table auth.identities owner to supabase_auth_admin; + create function auth.uid() returns uuid language sql stable as $$ select nullif(current_setting('request.jwt.claim.sub',true),'')::uuid $$; + grant usage on schema auth, public to anon, authenticated, service_role, buffer_migrator, no_grants; + grant execute on function auth.uid() to anon, authenticated, service_role, buffer_migrator; + -- The privileges hosted postgres holds on Auth's table; nothing on its other tables. + grant select, delete on auth.users to buffer_migrator; + -- Supabase grants browser roles EXECUTE on new public functions directly. + -- Revoking PUBLIC alone would leave those grants in place. + alter default privileges in schema public grant execute on functions to anon, authenticated, service_role; + alter default privileges for role buffer_migrator in schema public grant execute on functions to anon, authenticated, service_role; + create schema private; +`); +const files = (await readdir(migrations)).filter(name => name.endsWith('.sql')).sort(); +assert.ok(files.includes(DELETION_MIGRATION), `Missing ${DELETION_MIGRATION}`); +assert.equal(files.at(-1), DELETION_MIGRATION, 'The deletion migration must be timestamped after every earlier migration.'); +checks++; +for (const name of files) { + const body = await readFile(new URL(name, migrations), 'utf8'); + if (name !== DELETION_MIGRATION) { await db.exec(body); continue; } + await db.exec('grant create on schema public to buffer_migrator; set role buffer_migrator;'); + await db.exec(body); + await db.exec('reset role; revoke create on schema public from buffer_migrator;'); +} + +// Every owner-keyed table must disappear with its account. A new table that +// references auth.users fails here until it cascades and the privacy page lists it. +await check(`select conrelid::regclass::text as owned, confdeltype as on_delete from pg_constraint + where contype='f' and confrelid='auth.users'::regclass and connamespace <> 'auth'::regnamespace order by 1`, [ + { owned: 'alert_destinations', on_delete: 'c' }, { owned: 'alert_events', on_delete: 'c' }, + { owned: 'alert_outbox', on_delete: 'c' }, { owned: 'alert_rules', on_delete: 'c' }, + { owned: 'private.buffer_monitor_runs', on_delete: 'c' }, { owned: 'saved_reports', on_delete: 'c' }, +]); +await check(`select p.prosecdef as definer, p.pronargs as arguments, p.prorettype::regtype::text as returns, + coalesce(p.proconfig @> array['search_path=""'], false) as pinned_search_path, pg_get_userbyid(p.proowner) as owner + from pg_proc p where p.oid='public.delete_own_account()'::regprocedure`, + [{ definer: true, arguments: 0, returns: 'uuid', pinned_search_path: true, owner: 'buffer_migrator' }]); +for (const [role, permitted] of [['anon', false], ['service_role', false], ['no_grants', false], ['authenticated', true]]) { + await check(`select has_function_privilege('${role}','public.delete_own_account()','EXECUTE') as permitted`, [{ permitted }]); +} + +const report = JSON.stringify({ report: 'Buffer perpetual price scenario', version: 1, sourceMode: 'live', scenario: {} }); +const fingerprint = letter => letter.repeat(64); +await db.exec(` + insert into auth.users values ('${ownerA}','a@example.test'),('${ownerB}','b@example.test'); + insert into auth.sessions(user_id) values ('${ownerA}'),('${ownerA}'),('${ownerB}'); + insert into auth.identities(user_id) values ('${ownerA}'),('${ownerB}'); + insert into public.saved_reports(user_id,title,report) values + ('${ownerA}','A first',$json$${report}$json$),('${ownerA}','A second',$json$${report}$json$),('${ownerB}','B only',$json$${report}$json$); + insert into public.alert_destinations(id,owner_id,provider,config_ref,fingerprint,label,masked_destination) values + ('00000000-0000-4000-8000-0000000000a1','${ownerA}','discord','00000000-0000-4000-8000-0000000000f1','${fingerprint('a')}','A channel','Discord …00a1'), + ('00000000-0000-4000-8000-0000000000a2','${ownerA}','webhook','00000000-0000-4000-8000-0000000000f2','${fingerprint('b')}','A hook','Webhook hooks.example.com'), + ('00000000-0000-4000-8000-0000000000b1','${ownerB}','discord','00000000-0000-4000-8000-0000000000f1','${fingerprint('c')}','B channel','Discord …00b1'); + insert into public.alert_rules(id,owner_id,authority,subaccount_id,metric,unit,market,direction,threshold,cadence_minutes,timezone,destination_id,destination) values + ('00000000-0000-4000-8000-0000000000a3','${ownerA}','DxoRJ4f5XRMvXU9SGuM4ZziBFUxbhB3ubur5sVZEvue2',0,'maintenance_headroom','USD',null,'below',300,15,'UTC','00000000-0000-4000-8000-0000000000a1','discord'), + ('00000000-0000-4000-8000-0000000000a4','${ownerA}','DxoRJ4f5XRMvXU9SGuM4ZziBFUxbhB3ubur5sVZEvue2',0,'liquidation_distance','%','SOL-PERP','below',5,15,'UTC','00000000-0000-4000-8000-0000000000a2','webhook'), + ('00000000-0000-4000-8000-0000000000b3','${ownerB}','DxoRJ4f5XRMvXU9SGuM4ZziBFUxbhB3ubur5sVZEvue2',0,'maintenance_headroom','USD',null,'below',300,15,'UTC','00000000-0000-4000-8000-0000000000b1','discord'); + insert into public.alert_events(id,rule_id,rule_version,owner_id,event_key,state,observed_at,value,threshold,reason,destination_id,destination_fingerprint) values + ('00000000-0000-4000-8000-0000000000a5','00000000-0000-4000-8000-0000000000a3',1,'${ownerA}','a-queued','queued',now(),250,300,'Queued fixture','00000000-0000-4000-8000-0000000000a1','${fingerprint('a')}'), + ('00000000-0000-4000-8000-0000000000a6','00000000-0000-4000-8000-0000000000a4',1,'${ownerA}','a-delivered','delivered',now(),4,5,'Delivered fixture','00000000-0000-4000-8000-0000000000a2','${fingerprint('b')}'), + ('00000000-0000-4000-8000-0000000000a7',null,1,'${ownerA}','a-history','suppressed',now()-interval '2 days',250,300,'Event kept after its rule was deleted',null,null), + ('00000000-0000-4000-8000-0000000000b5','00000000-0000-4000-8000-0000000000b3',1,'${ownerB}','b-queued','queued',now(),250,300,'Queued fixture','00000000-0000-4000-8000-0000000000b1','${fingerprint('c')}'); + insert into public.alert_outbox(event_id,owner_id,state) values + ('00000000-0000-4000-8000-0000000000a5','${ownerA}','pending'),('00000000-0000-4000-8000-0000000000a6','${ownerA}','delivered'), + ('00000000-0000-4000-8000-0000000000b5','${ownerB}','pending'); + update public.alert_rules set unresolved_event_id='00000000-0000-4000-8000-0000000000a5' where id='00000000-0000-4000-8000-0000000000a3'; + update public.alert_rules set unresolved_event_id='00000000-0000-4000-8000-0000000000b5' where id='00000000-0000-4000-8000-0000000000b3'; + insert into private.buffer_monitor_runs(run_key,mode,owner_id) values + ('manual:00000000-0000-4000-8000-0000000000a8','dry_run','${ownerA}'),('manual:00000000-0000-4000-8000-0000000000b8','dry_run','${ownerB}'),('cron:1','dry_run',null); +`); + +const OWNED = [ + ['auth.users', 'id'], ['auth.sessions', 'user_id'], ['auth.identities', 'user_id'], ['public.saved_reports', 'user_id'], + ['public.alert_rules', 'owner_id'], ['public.alert_destinations', 'owner_id'], ['public.alert_events', 'owner_id'], + ['public.alert_outbox', 'owner_id'], ['private.buffer_monitor_runs', 'owner_id'], +]; +async function holdings(owner) { + await asAdmin(); + const counts = {}; + for (const [table, column] of OWNED) counts[table] = (await rows(`select count(*)::int as n from ${table} where ${column}=$1`, [owner]))[0].n; + return counts; +} +const before = { a: await holdings(ownerA), b: await holdings(ownerB) }; +assert.deepEqual(before.a, { 'auth.users': 1, 'auth.sessions': 2, 'auth.identities': 1, 'public.saved_reports': 2, 'public.alert_rules': 2, + 'public.alert_destinations': 2, 'public.alert_events': 3, 'public.alert_outbox': 2, 'private.buffer_monitor_runs': 1 }); checks++; +const bWork = `select e.state as event, o.state as outbox from public.alert_events e join public.alert_outbox o on o.event_id=e.id where e.owner_id='${ownerB}'`; + +// Browser roles without a signed-in subject cannot reach the function at all, +// even when a subject claim is forged onto an anonymous request. +await as('anon'); await rejects('select public.delete_own_account()', '42501'); +await as('anon', ownerA); await rejects('select public.delete_own_account()', '42501'); +await as('service_role', ownerA); await rejects('select public.delete_own_account()', '42501'); +await as('authenticated'); await rejects('select public.delete_own_account()', '42501'); +assert.deepEqual(await holdings(ownerA), before.a); checks++; + +// The caller deletes their own account and nothing else. +await as('authenticated', ownerA); +await check('select public.delete_own_account() as removed', [{ removed: ownerA }]); +assert.deepEqual(await holdings(ownerA), Object.fromEntries(OWNED.map(([table]) => [table, 0]))); checks++; +assert.deepEqual(await holdings(ownerB), before.b); checks++; +await check(bWork, [{ event: 'queued', outbox: 'pending' }]); +await check("select count(*)::int as n from private.buffer_monitor_runs where owner_id is null", [{ n: 1 }]); + +// A token that outlives its account deletes nothing more. +await as('authenticated', ownerA); +await check('select public.delete_own_account() as removed', [{ removed: null }]); +assert.deepEqual(await holdings(ownerB), before.b); checks++; + +// The other owner still reads their own rows through RLS, then can leave too. +await as('authenticated', ownerB); +await check('select title from public.saved_reports', [{ title: 'B only' }]); +await check('select jsonb_array_length(public.buffer_monitor_status()->\'rules\') as rules', [{ rules: 1 }]); +await check('select public.delete_own_account() as removed', [{ removed: ownerB }]); +assert.deepEqual(await holdings(ownerB), Object.fromEntries(OWNED.map(([table]) => [table, 0]))); checks++; +await asAdmin(); +await check('select count(*)::int as n from auth.users', [{ n: 0 }]); +await check("select run_key from private.buffer_monitor_runs", [{ run_key: 'cron:1' }]); + +await db.close(); +console.log(JSON.stringify({ result: 'PASS', assertions: checks, database: 'local PostgreSQL (PGlite)', externalWrites: false }, null, 2)); diff --git a/src/components/AccountDeletion.module.css b/src/components/AccountDeletion.module.css new file mode 100644 index 0000000..976f9aa --- /dev/null +++ b/src/components/AccountDeletion.module.css @@ -0,0 +1,11 @@ +.section{margin-top:28px;padding-top:22px;border-top:1px solid #e7eaf0}.section h3{font-size:14px;margin-bottom:6px}.section p{font-size:13px!important;margin-bottom:12px!important;color:#4d586b} +.start{color:var(--red);padding-left:0}.start:hover:not(:disabled){background:transparent;text-decoration:underline;text-underline-offset:4px} +.confirm{margin-top:14px;border:1px solid #efd4d5;border-radius:14px;padding:18px 20px;background:#fdf7f7}.confirm h4{margin:0 0 8px;font-size:15px;font-weight:600;letter-spacing:-.2px;color:#182236;overflow-wrap:anywhere}.confirm h4:focus-visible{outline:2px solid #315fe8;outline-offset:4px;border-radius:4px}.confirm ul{margin:0 0 14px;padding-left:18px;font-size:13px;line-height:1.85;color:#182236} +.kept a{color:#315fe8;text-decoration:underline;text-underline-offset:3px} +.actions{display:flex;flex-wrap:wrap;gap:10px}.destroy{background:var(--red);border-color:var(--red);color:#fff}.destroy:hover:not(:disabled){background:#9c3a3e;border-color:#9c3a3e}.destroy:focus-visible{outline:3px solid #e2a3a5} +.done{display:flex;align-items:center;gap:8px;color:#182236!important}.done svg{color:var(--teal);flex-shrink:0} +.status:empty{display:none} +.notice{position:fixed;left:50%;bottom:max(20px,env(safe-area-inset-bottom));transform:translateX(-50%);z-index:46;width:min(460px,calc(100% - 32px));display:grid;grid-template-columns:auto 1fr auto;gap:12px;align-items:start;padding:16px 14px 16px 16px;border:1px solid #d6e3df;border-radius:16px;background:#fff;color:#182236;box-shadow:0 18px 50px #1724402e}.notice:focus-visible{outline:3px solid #7b9af4;outline-offset:3px}.notice strong{font-size:14px}.notice p{margin:4px 0 0;font-size:13px;line-height:1.6;color:#4d586b}.notice button{min-height:36px;padding:6px 8px} +.noticeIcon{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;background:#e3f2ef;color:var(--teal)} +@media(max-width:1179px){.notice{bottom:calc(88px + env(safe-area-inset-bottom))}} +@media(max-width:600px){.confirm{padding:16px}.actions button{width:100%;min-height:44px}.notice{grid-template-columns:auto 1fr}.notice button{grid-column:1 / -1;justify-self:end}} diff --git a/src/components/AccountDeletion.tsx b/src/components/AccountDeletion.tsx new file mode 100644 index 0000000..4dbbd39 --- /dev/null +++ b/src/components/AccountDeletion.tsx @@ -0,0 +1,68 @@ +'use client'; + +import { useEffect, useRef } from 'react'; +import { Icon } from './Icons'; +import styles from './AccountDeletion.module.css'; + +export type DeletionStage = 'idle' | 'confirming' | 'deleting' | 'deleted'; + +type SectionProps = { + email: string | undefined; + stage: DeletionStage; + message: string; + disabled: boolean; + onStart: () => void; + onCancel: () => void; + onConfirm: () => void; +}; + +/** In-page confirmation. Nothing is sent until the person confirms a second time. */ +export function DeleteAccountSection({ email, stage, message, disabled, onStart, onCancel, onConfirm }: SectionProps) { + const start = useRef(null); + const prompt = useRef(null); + const previous = useRef(stage); + useEffect(() => { + if (previous.current === 'idle' && stage === 'confirming') prompt.current?.focus(); + if (previous.current === 'confirming' && stage === 'idle') start.current?.focus(); + previous.current = stage; + }, [stage]); + const working = stage === 'deleting'; + return
+

Delete account

+ {stage === 'idle' && <> +

Remove this account and everything stored with it. This cannot be undone.

+ + } + {(stage === 'confirming' || working) &&
+

Delete {email || 'this account'} permanently?

+

This removes, for good:

+
    +
  • Your sign-in and email address
  • +
  • Saved reports
  • +
  • Monitored wallet addresses and alert rules
  • +
  • Alert destinations, events and delivery records
  • +
+

Reports saved on this device stay until you delete them. Alerts already sent to Discord or a webhook stay with their recipients. How deletion works

+
+ + +
+
} + {stage === 'deleted' &&

Your account and its data are deleted. Sign out to finish on this device.

} +

{message}

+
; +} + +/** Shown after sign-out, when the account panel no longer has a signed-in user. */ +export function AccountDeletedNotice({ onDismiss }: { onDismiss: () => void }) { + const notice = useRef(null); + useEffect(() => { notice.current?.focus(); }, []); + return
+ +
+ Account deleted. +

Your sign-in, saved reports, alert rules and alert history are gone. You are signed out on this device.

+
+ +
; +} diff --git a/src/components/AccountPanel.tsx b/src/components/AccountPanel.tsx index d23567e..0c07a3f 100644 --- a/src/components/AccountPanel.tsx +++ b/src/components/AccountPanel.tsx @@ -4,12 +4,14 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import type { Session, User } from '@supabase/supabase-js'; import { getSupabase } from '@/lib/supabase'; import { runAuthOperation } from '@/lib/auth-flow'; +import { AccountDeletionError, accountDeletionMessage, clearAccountDeviceData, deleteOwnAccount, runAccountDeletion } from '@/lib/account-deletion'; import { persistedAuthSession, sessionIdentity, sameAuthSession, withIdentityBoundSignOut, type AuthSessionIdentity } from '@/lib/auth-storage'; import { decodeCloudReports, isCloudReportPayload, type SavedReport } from '@/lib/cloud-reports'; import { formatUtc } from '@/lib/format'; import type { createReport } from '@/lib/report'; import styles from './AccountPanel.module.css'; import DeviceReportsPanel from './DeviceReportsPanel'; +import { AccountDeletedNotice, DeleteAccountSection, type DeletionStage } from './AccountDeletion'; type Report = ReturnType; type Operation = { identity: string; controller: AbortController }; @@ -40,6 +42,10 @@ export default function AccountPanel({ report }: { report: Report | null }) { const [loadState, setLoadState] = useState<'idle' | 'loaded' | 'error'>('idle'); const [writeUncertain, setWriteUncertain] = useState(false); const [message, setMessage] = useState(''); + const [deletion, setDeletion] = useState('idle'); + const [deletionMessage, setDeletionMessage] = useState(''); + const [accountDeleted, setAccountDeleted] = useState(false); + const deleting = useRef(false); const dialog = useRef(null); const trigger = useRef(null); const identity = useRef(null); @@ -59,6 +65,9 @@ export default function AccountPanel({ report }: { report: Report | null }) { setBusy(false); setLoadState('idle'); setWriteUncertain(false); + setDeletion('idle'); + setDeletionMessage(''); + if (nextIdentity) setAccountDeleted(false); if (!nextIdentity) dialog.current?.close(); } acceptedSession.current = nextSession; @@ -218,6 +227,33 @@ export default function AccountPanel({ report }: { report: Report | null }) { if (current(ticket)) setMessage('Could not sign out. Please retry.'); } finally { finish(ticket); } } + /** The database confirms the deletion before this device clears its data or session. */ + async function deleteAccount() { + const db = getSupabase(); + if (!db || busy || deleting.current) return; + const expected = acceptedSession.current; + if (!expected || expected.userId !== user?.id) { setDeletionMessage(accountDeletionMessage(new AccountDeletionError('session'))); return; } + const ticket = begin(); + if (!ticket) return; + deleting.current = true; + setDeletion('deleting'); + setDeletionMessage(''); + try { + await runAccountDeletion({ + remove: () => deleteOwnAccount(expected, ticket.controller.signal), + afterDelete: () => { clearAccountDeviceData(expected.userId); setAccountDeleted(true); }, + // The deleted account's session is already revoked; this clears it from this browser. + signOut: () => runAuthOperation('signout', signal => withIdentityBoundSignOut(AUTH_URL, expected, + () => db.auth.signOut({ scope: 'local' }), signal), undefined, REQUEST_TIMEOUT_MS, expected), + }); + if (current(ticket) && sameAuthSession(persistedAuthSession(AUTH_URL), expected)) setDeletion('deleted'); + } catch (error) { + if (current(ticket)) { setDeletion('confirming'); setDeletionMessage(accountDeletionMessage(error)); } + } finally { + deleting.current = false; + finish(ticket); + } + } function download(item: SavedReport) { const url = URL.createObjectURL(new Blob([JSON.stringify(item.report, null, 2)], { type: 'application/json' })); const link = document.createElement('a'); @@ -225,16 +261,20 @@ export default function AccountPanel({ report }: { report: Report | null }) { setTimeout(() => URL.revokeObjectURL(url), 1000); } function close() { - operation.current?.controller.abort(); - operation.current = null; - setBusy(false); + // Closing never abandons a deletion in flight; its result still signs this device out. + if (!deleting.current) { + operation.current?.controller.abort(); + operation.current = null; + setBusy(false); + if (deletion === 'confirming') { setDeletion('idle'); setDeletionMessage(''); } + } trigger.current?.focus(); } - if (!user) return <>{authReady ? Sign in : authError ? : Checking account…}; + if (!user) return <>{authReady ? Sign in : authError ? : Checking account…}{accountDeleted && setAccountDeleted(false)} />}; return <> - -

YOUR WORKSPACE

Saved perspectives.

+ { if (deleting.current) event.preventDefault(); }}> +

YOUR WORKSPACE

Saved perspectives.

{user.email}

Keep a dated copy of a scenario. Saved reports are historical records; they do not refresh with the market.

@@ -244,6 +284,10 @@ export default function AccountPanel({ report }: { report: Report | null }) {
    {reports.map(item =>
  • {item.title}{formatUtc(item.created_at)}
  • )}

Your most recent 50 reports. Only your signed-in account can access them.

+ { setDeletion('confirming'); setDeletionMessage(''); }} + onCancel={() => { setDeletion('idle'); setDeletionMessage(''); }} + onConfirm={() => void deleteAccount()} />
; } diff --git a/src/components/AlertsPanel.tsx b/src/components/AlertsPanel.tsx index 7700f21..c29b55c 100644 --- a/src/components/AlertsPanel.tsx +++ b/src/components/AlertsPanel.tsx @@ -7,7 +7,7 @@ import { getSupabase } from '@/lib/supabase'; import { persistedAuthSession } from '@/lib/auth-storage'; import { formatUtc } from '@/lib/format'; import { - alertStorageKey, createAlertRule, parseAlertStore, deleteAlertRule, + alertRehearsalKey, alertStorageKey, createAlertRule, parseAlertStore, deleteAlertRule, emptyAlertStore, encodeAlertStore, evaluateFixtureAlerts, pauseAlertRule, runAlertWorker, updateAlertRule, type AlertStore, } from '@/lib/alerts'; @@ -76,7 +76,7 @@ function RehearsalAlerts({ ownerId, sessionId }: Props & { ownerId: string; sess const [busy, setBusy] = useState(false); const active = useRef(true); const inFlight = useRef(false); - const key = `buffer.alerts.rehearsal.v2:${ownerId}`; + const key = alertRehearsalKey(ownerId); const [legacyAvailable, setLegacyAvailable] = useState(false); useEffect(() => { diff --git a/src/lib/account-deletion.ts b/src/lib/account-deletion.ts new file mode 100644 index 0000000..6494217 --- /dev/null +++ b/src/lib/account-deletion.ts @@ -0,0 +1,149 @@ +import type { SupabaseClient } from '@supabase/supabase-js'; +import { alertRehearsalKey, alertStorageKey } from './alerts'; +import { persistedAuthSession, sameAuthSession, sessionIdentity, type AuthSessionIdentity } from './auth-storage'; +import { getSupabase } from './supabase'; + +/** + * Self-service account deletion. The browser calls public.delete_own_account() + * with the session the person confirmed in. The database deletes that auth user + * and, by cascade, every row keyed to it. No service-role key is involved, and + * the request carries no account identifier: the function acts on auth.uid(). + */ +export const ACCOUNT_DELETION_RPC_PATH = '/rest/v1/rpc/delete_own_account'; +export const ACCOUNT_DELETION_TIMEOUT_MS = 20_000; +const RESPONSE_BYTES = 4096; + +export type AccountDeletionOutcome = 'deleted' | 'already-deleted'; +export type AccountDeletionFailure = 'session' | 'cancelled' | 'unauthorized' | 'unconfirmed'; + +const MESSAGES: Record = { + session: 'This sign-in could not be confirmed. Nothing was deleted. Reload the page and try again.', + cancelled: 'Account deletion stopped before it started. Nothing was deleted.', + unauthorized: 'Your session has expired. Nothing was deleted. Sign in again, then retry.', + unconfirmed: 'Account deletion could not be confirmed. Try again; repeating it is safe.', +}; + +export class AccountDeletionError extends Error { + constructor(public readonly code: AccountDeletionFailure) { + super(MESSAGES[code]); + this.name = 'AccountDeletionError'; + } +} + +export function accountDeletionMessage(error: unknown): string { + return error instanceof AccountDeletionError ? error.message : MESSAGES.unconfirmed; +} + +export interface AccountDeletionOptions { + projectUrl?: string; + publishableKey?: string; + client?: Pick | null; + fetcher?: typeof fetch; + persisted?: () => AuthSessionIdentity | null; + timeoutMs?: number; +} + +async function readResult(response: Response): Promise { + if (!response.body) throw new AccountDeletionError('unconfirmed'); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + for (;;) { + const next = await reader.read(); + if (next.done) break; + size += next.value.byteLength; + if (size > RESPONSE_BYTES) { await reader.cancel().catch(() => undefined); throw new AccountDeletionError('unconfirmed'); } + chunks.push(next.value); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + try { return JSON.parse(new TextDecoder().decode(bytes)); } + catch { throw new AccountDeletionError('unconfirmed'); } +} + +/** Deletes the confirmed account. A replaced or missing session sends nothing. */ +export async function deleteOwnAccount(expected: AuthSessionIdentity, signal: AbortSignal, options: AccountDeletionOptions = {}): Promise { + const projectUrl = (options.projectUrl ?? process.env.NEXT_PUBLIC_SUPABASE_URL ?? '').replace(/\/+$/, ''); + const publishableKey = options.publishableKey ?? process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? ''; + const client = options.client === undefined ? getSupabase() : options.client; + const persisted = options.persisted ?? (() => persistedAuthSession(projectUrl)); + const fetcher = options.fetcher ?? ((input, init) => fetch(input, init)); + if (signal.aborted) throw new AccountDeletionError('cancelled'); + if (!projectUrl || !publishableKey || !client || !sameAuthSession(persisted(), expected)) throw new AccountDeletionError('session'); + + const controller = new AbortController(); + const abort = () => controller.abort(); + signal.addEventListener('abort', abort, { once: true }); + const timer = setTimeout(abort, options.timeoutMs ?? ACCOUNT_DELETION_TIMEOUT_MS); + let sent = false; + try { + const stopped = new Promise((_resolve, reject) => { + controller.signal.addEventListener('abort', () => reject(new Error('stopped')), { once: true }); + }); + const { data, error } = await Promise.race([client.auth.getSession(), stopped]); + const session = data.session; + if (error || !session || !sameAuthSession(sessionIdentity(session), expected) || !sameAuthSession(persisted(), expected)) { + throw new AccountDeletionError('session'); + } + controller.signal.throwIfAborted(); + sent = true; + const response = await fetcher(`${projectUrl}${ACCOUNT_DELETION_RPC_PATH}`, { + method: 'POST', cache: 'no-store', redirect: 'error', signal: controller.signal, + headers: { apikey: publishableKey, Authorization: `Bearer ${session.access_token}`, 'Content-Type': 'application/json', Accept: 'application/json' }, + body: '{}', + }); + // PostgREST rejects an expired token or a missing grant before the function runs. + if (response.status === 401 || response.status === 403) { + await response.body?.cancel().catch(() => undefined); + throw new AccountDeletionError('unauthorized'); + } + if (!response.ok) { + await response.body?.cancel().catch(() => undefined); + throw new AccountDeletionError('unconfirmed'); + } + const removed = await readResult(response); + if (removed === expected.userId) return 'deleted'; + // The function returns null when this account no longer exists. + if (removed === null) return 'already-deleted'; + throw new AccountDeletionError('unconfirmed'); + } catch (error) { + if (error instanceof AccountDeletionError) throw error; + if (!sent) throw new AccountDeletionError(signal.aborted ? 'cancelled' : 'session'); + throw new AccountDeletionError('unconfirmed'); + } finally { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + } +} + +/** Device-local example alert settings stored under the deleted account's ID. */ +export function accountDeviceKeys(ownerId: string): string[] { + return [alertRehearsalKey(ownerId), alertStorageKey(ownerId)]; +} + +/** Device reports are not account data and stay until the person deletes them. */ +export function clearAccountDeviceData(ownerId: string, storage?: Pick): void { + for (const key of accountDeviceKeys(ownerId)) { + try { (storage ?? window.localStorage).removeItem(key); } + catch { /* Unavailable storage holds nothing to clear. */ } + } +} + +export interface AccountDeletionSteps { + remove: () => Promise; + /** Runs once the database confirms the deletion: clear device data and record the result. */ + afterDelete: () => void; + signOut: () => Promise<{ error: unknown }>; +} + +/** Device data and the local session go only after the database confirms the account is gone. */ +export async function runAccountDeletion(steps: AccountDeletionSteps): Promise<{ outcome: AccountDeletionOutcome; signedOut: boolean }> { + const outcome = await steps.remove(); + try { steps.afterDelete(); } + catch { /* Best effort: the account itself is already deleted. */ } + let signedOut = false; + try { signedOut = !(await steps.signOut()).error; } + catch { signedOut = false; } + return { outcome, signedOut }; +} diff --git a/src/lib/alerts.ts b/src/lib/alerts.ts index 759ecd6..d6c9f88 100644 --- a/src/lib/alerts.ts +++ b/src/lib/alerts.ts @@ -9,6 +9,7 @@ const Exact = Decimal.clone({ precision: 260 }); export const ALERT_STORAGE_VERSION = 1; export const ALERT_STORAGE_PREFIX = 'buffer.alerts.v1:'; +export const ALERT_REHEARSAL_PREFIX = 'buffer.alerts.rehearsal.v2:'; export const ALERT_LEASE_MS = 30_000; export const ALERT_MAX_INPUT_AGE_MS = 120_000; export const ALERT_MAX_ATTEMPTS = 3; @@ -330,3 +331,5 @@ export function updateAlertRule(input: AlertStore, ruleId: string, ownerId: stri } export function pauseAlertRule(input: AlertStore, ruleId: string, ownerId: string, now = new Date()): AlertStore { return updateAlertRule(input, ruleId, ownerId, { enabled: false }, now); } export function alertStorageKey(ownerId: string) { return `${ALERT_STORAGE_PREFIX}${ownerId}`; } +/** The device-local example alert store for one signed-in owner, or the guest device owner. */ +export function alertRehearsalKey(ownerId: string) { return `${ALERT_REHEARSAL_PREFIX}${ownerId}`; } diff --git a/supabase/migrations/20261007120000_delete_own_account.sql b/supabase/migrations/20261007120000_delete_own_account.sql new file mode 100644 index 0000000..8c21461 --- /dev/null +++ b/supabase/migrations/20261007120000_delete_own_account.sql @@ -0,0 +1,26 @@ +-- Self-service account deletion, required by the Solana dApp Store Publisher +-- Policy. The hosted app holds no service-role key, so a signed-in person calls +-- this owner-scoped RPC with their own session. Deleting the auth.users row +-- cascades to every owner-keyed table: saved_reports, alert_rules, +-- alert_destinations, alert_events, alert_outbox and +-- private.buffer_monitor_runs, plus Supabase Auth's sessions and identities. +-- Additive: no existing row, table or policy changes when this is applied. +-- Reverse with: drop function public.delete_own_account(); +create function public.delete_own_account() returns uuid +language plpgsql security definer set search_path = '' as $$ +declare + caller uuid := auth.uid(); + removed uuid; +begin + if caller is null then + raise exception 'Authentication required' using errcode = '42501'; + end if; + delete from auth.users where id = caller returning id into removed; + -- Null when this account was already deleted, for example by a retried call. + return removed; +end $$; +-- Supabase grants browser roles EXECUTE on new public functions directly, so +-- revoking PUBLIC alone is not enough. Only a signed-in session may call this. +revoke all on function public.delete_own_account() from public, anon, authenticated, service_role; +grant execute on function public.delete_own_account() to authenticated; +comment on function public.delete_own_account() is 'Deletes the calling account and, by cascade, all of its Buffer data. Takes no argument, so it can only ever act on auth.uid().'; diff --git a/tests/account-deletion.test.ts b/tests/account-deletion.test.ts new file mode 100644 index 0000000..1ac1e0f --- /dev/null +++ b/tests/account-deletion.test.ts @@ -0,0 +1,145 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { SupabaseClient } from '@supabase/supabase-js'; +import { + ACCOUNT_DELETION_RPC_PATH, AccountDeletionError, accountDeletionMessage, accountDeviceKeys, + clearAccountDeviceData, deleteOwnAccount, runAccountDeletion, +} from '../src/lib/account-deletion'; +import { alertRehearsalKey, alertStorageKey } from '../src/lib/alerts'; +import type { AuthSessionIdentity } from '../src/lib/auth-storage'; + +const origin = 'https://local-test.supabase.co'; +const alice: AuthSessionIdentity = { userId: '00000000-0000-4000-8000-00000000000a', sessionId: 'session-a' }; +const bob: AuthSessionIdentity = { userId: '00000000-0000-4000-8000-00000000000b', sessionId: 'session-b' }; + +function token(identity: AuthSessionIdentity) { + return `mock.${Buffer.from(JSON.stringify({ sub: identity.userId, session_id: identity.sessionId, exp: 4_000_000_000 })).toString('base64url')}.signature`; +} +function client(identity: AuthSessionIdentity | null) { + const getSession = vi.fn().mockResolvedValue({ data: { session: identity ? { access_token: token(identity), user: { id: identity.userId } } : null }, error: null }); + return { client: { auth: { getSession } } as unknown as SupabaseClient, getSession }; +} +function deps(overrides: Partial[2]> = {}) { + const { client: db, getSession } = client(alice); + const fetcher = vi.fn().mockResolvedValue(Response.json(alice.userId)); + return { getSession, fetcher, options: { projectUrl: origin, publishableKey: 'sb_publishable_test', client: db, fetcher, persisted: () => alice, ...overrides } }; +} +afterEach(() => { vi.useRealTimers(); }); + +describe('deleting the signed-in account', () => { + it('calls the owner-scoped RPC with the confirmed session and sends no account identifier', async () => { + const { fetcher, options } = deps(); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).resolves.toBe('deleted'); + expect(fetcher).toHaveBeenCalledTimes(1); + const [url, init] = fetcher.mock.calls[0]; + expect(String(url)).toBe(`${origin}${ACCOUNT_DELETION_RPC_PATH}`); + expect(init).toMatchObject({ method: 'POST', cache: 'no-store', redirect: 'error', body: '{}' }); + expect(new Headers(init?.headers).get('authorization')).toBe(`Bearer ${token(alice)}`); + expect(new Headers(init?.headers).get('apikey')).toBe('sb_publishable_test'); + expect(String(init?.body)).not.toContain(alice.userId); + }); + + it('treats a null result as an account that was already deleted', async () => { + const { options } = deps({ fetcher: vi.fn().mockResolvedValue(Response.json(null)) }); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).resolves.toBe('already-deleted'); + }); + + it('refuses before reading credentials when another session replaced the confirmed one', async () => { + const { fetcher, getSession, options } = deps({ persisted: () => bob }); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).rejects.toMatchObject({ code: 'session' }); + expect(getSession).not.toHaveBeenCalled(); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it.each([ + ['a different account', bob], + ['a fresh session of the same account', { ...alice, sessionId: 'replacement' }], + ['no session', null], + ])('never sends the request with %s', async (_name, identity) => { + const { client: db } = client(identity); + const { fetcher, options } = deps({ client: db }); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).rejects.toMatchObject({ code: 'session' }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it('does nothing once the person cancelled', async () => { + const { fetcher, options } = deps(); + const controller = new AbortController(); controller.abort(); + await expect(deleteOwnAccount(alice, controller.signal, options)).rejects.toMatchObject({ code: 'cancelled' }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it.each([401, 403])('maps HTTP %i to a rejected session, which deletes nothing', async status => { + const { options } = deps({ fetcher: vi.fn().mockResolvedValue(Response.json({ code: '42501' }, { status })) }); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).rejects.toMatchObject({ code: 'unauthorized' }); + }); + + it.each([ + ['a server error', () => Response.json({ message: 'unavailable' }, { status: 503 })], + ['another account id', () => Response.json(bob.userId)], + ['a malformed body', () => new Response('not json', { status: 200 })], + ['an oversized body', () => new Response(JSON.stringify('x'.repeat(5000)), { status: 200 })], + ['a transport failure', () => { throw new TypeError('Failed to fetch'); }], + ])('reports %s as unconfirmed so a retry can finish safely', async (_name, reply) => { + const { options } = deps({ fetcher: vi.fn().mockImplementation(async () => reply()) }); + await expect(deleteOwnAccount(alice, new AbortController().signal, options)).rejects.toMatchObject({ code: 'unconfirmed' }); + }); + + it('ends a hung request at its deadline as unconfirmed', async () => { + vi.useFakeTimers(); + const fetcher = vi.fn().mockImplementation((_input, init) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true }); + })); + const { options } = deps({ fetcher, timeoutMs: 1000 }); + const pending = expect(deleteOwnAccount(alice, new AbortController().signal, options)).rejects.toMatchObject({ code: 'unconfirmed' }); + await vi.advanceTimersByTimeAsync(1001); + await pending; + }); + + it('gives every failure a plain message that says whether anything was deleted', () => { + expect(accountDeletionMessage(new AccountDeletionError('session'))).toMatch(/Nothing was deleted/); + expect(accountDeletionMessage(new AccountDeletionError('cancelled'))).toMatch(/Nothing was deleted/); + expect(accountDeletionMessage(new AccountDeletionError('unauthorized'))).toMatch(/Nothing was deleted/); + expect(accountDeletionMessage(new AccountDeletionError('unconfirmed'))).toMatch(/could not be confirmed/); + expect(accountDeletionMessage(new Error('anything else'))).toMatch(/could not be confirmed/); + }); +}); + +describe('finishing a deletion on this device', () => { + it('signs out and clears device data only after the account is gone', async () => { + const order: string[] = []; + const result = await runAccountDeletion({ + remove: async () => { order.push('remove'); return 'deleted'; }, + afterDelete: () => { order.push('clear'); }, + signOut: async () => { order.push('signout'); return { error: null }; }, + }); + expect(order).toEqual(['remove', 'clear', 'signout']); + expect(result).toEqual({ outcome: 'deleted', signedOut: true }); + }); + + it('keeps the session and device data when the deletion fails', async () => { + const afterDelete = vi.fn(); const signOut = vi.fn(); + await expect(runAccountDeletion({ remove: async () => { throw new AccountDeletionError('unconfirmed'); }, afterDelete, signOut })) + .rejects.toMatchObject({ code: 'unconfirmed' }); + expect(afterDelete).not.toHaveBeenCalled(); + expect(signOut).not.toHaveBeenCalled(); + }); + + it('still reports a completed deletion when signing out of this device fails', async () => { + for (const signOut of [async () => ({ error: new Error('offline') }), async () => { throw new Error('offline'); }]) { + await expect(runAccountDeletion({ remove: async () => 'already-deleted', afterDelete: () => {}, signOut })) + .resolves.toEqual({ outcome: 'already-deleted', signedOut: false }); + } + }); + + it('clears only the deleted account’s keys and tolerates unavailable storage', () => { + const values = new Map([ + [alertRehearsalKey(alice.userId), '{}'], [alertStorageKey(alice.userId), '{}'], + [alertRehearsalKey(bob.userId), '{}'], ['buffer.device-reports.v1', '{}'], + ]); + const storage = { removeItem: (key: string) => { values.delete(key); } }; + expect(accountDeviceKeys(alice.userId)).toEqual([alertRehearsalKey(alice.userId), alertStorageKey(alice.userId)]); + clearAccountDeviceData(alice.userId, storage); + expect([...values.keys()]).toEqual([alertRehearsalKey(bob.userId), 'buffer.device-reports.v1']); + expect(() => clearAccountDeviceData(alice.userId, { removeItem: () => { throw new Error('blocked'); } })).not.toThrow(); + }); +}); From feb9287e973954434319f6e55bfe675170900e43 Mon Sep 17 00:00:00 2001 From: operatoruplift Date: Thu, 8 Oct 2026 01:49:50 +0700 Subject: [PATCH 03/25] feat: publish privacy and terms pages and describe the wallet connection accurately Adds public /privacy and /terms pages for Operator Uplift, built from what the code does: Supabase accounts, saved reports, alert rules, destinations, events and deliveries, hashed-IP rate limiting, the read-only wallet connection, processors, retention, account deletion, security and the 18+ requirement. The terms carry the Solana dApp Store Developer Agreement 10.6 clause, the not-advice and estimate limits, the alert caveat, no warranty and limitation of liability. Both pages are linked from the landing footer, the workspace navigation and footer, the sign-in page and the sitemap. Contact uses NEXT_PUBLIC_SUPPORT_EMAIL when set and the GitHub issue tracker otherwise. The landing hero, FAQ and privacy section, docs/PROVIDER.md and docs/DESCRIPTION.md now describe the optional read-only wallet connection and the Android app instead of claiming there is no wallet connection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHDgeGLvKoi7gnFqUbJ1sw --- .env.example | 3 + docs/DESCRIPTION.md | 6 +- docs/PROVIDER.md | 2 +- e2e/brand-motion.spec.ts | 2 +- e2e/legal.spec.ts | 72 ++++++++++ src/app/landing.css | 5 +- src/app/privacy/page.tsx | 127 ++++++++++++++++++ src/app/sitemap.ts | 2 + src/app/terms/page.tsx | 73 ++++++++++ src/components/AppNavigation.module.css | 2 + src/components/AppNavigation.tsx | 1 + src/components/AppWorkspace.css | 5 +- src/components/AuthForm.module.css | 2 + src/components/AuthForm.tsx | 4 +- src/components/Dashboard.tsx | 1 + src/components/Landing.tsx | 8 +- src/components/legal/LegalDocument.module.css | 100 ++++++++++++++ src/components/legal/LegalDocument.tsx | 89 ++++++++++++ src/lib/legal.ts | 16 +++ tests/legal.test.ts | 32 +++++ 20 files changed, 539 insertions(+), 13 deletions(-) create mode 100644 e2e/legal.spec.ts create mode 100644 src/app/privacy/page.tsx create mode 100644 src/app/terms/page.tsx create mode 100644 src/components/legal/LegalDocument.module.css create mode 100644 src/components/legal/LegalDocument.tsx create mode 100644 src/lib/legal.ts create mode 100644 tests/legal.test.ts diff --git a/.env.example b/.env.example index eea642b..9a12738 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,9 @@ NEXT_PUBLIC_SUPABASE_URL= NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= # Set true only after SMTP, allowed redirects, and email confirmation/recovery are verified. NEXT_PUBLIC_AUTH_EMAIL_READY=false +# Optional public support address shown on /privacy and /terms. When unset, both pages +# point to https://github.com/operatoruplift/buffer/issues instead. +# NEXT_PUBLIC_SUPPORT_EMAIL= # Optional path for the durable local SQLite mock worker. Defaults to .local/alerts.sqlite. # BUFFER_ALERT_STORE= # Optional server-only distributed read-limit secret. Requires the protected consume_rate_limit RPC. diff --git a/docs/DESCRIPTION.md b/docs/DESCRIPTION.md index d386918..959c021 100644 --- a/docs/DESCRIPTION.md +++ b/docs/DESCRIPTION.md @@ -24,7 +24,7 @@ The result comes with its explanation: what was included, what was excluded, whi - **Current risk and optional monitoring.** Open a public Velocity account directly and inspect current maintenance headroom beside the independent price scenario. Owner-authenticated cloud rules use fresh provider observations, durable event/outbox state and protected scheduled work. One Discord adapter separates acceptance from a matching channel receipt; destination setup and authorized live delivery remain explicit gates. Local examples use a separate rehearsal with no outbound path. - **Portable reports.** Download a JSON report containing the snapshot, exact scenario values, coverage, assumptions, and the identity the snapshot came from: the fixed protocol or API identity for a live read, and the reference perpetual catalog for an editable preset portfolio. - **Useful without an account.** Explore deterministic samples, read public accounts, and save historical reports on this device without signing in or connecting a wallet. Optional cloud accounts keep a separate private library. -- **A workspace that travels.** Use the responsive web app on mobile, tablet, and desktop, with installation through supported PWA browsers. +- **A workspace that travels.** Use the responsive web app on mobile, tablet, and desktop, install it through supported PWA browsers, or install the Android app built from `android/` for Seeker and the Solana dApp Store. ### Simple math, carefully scoped @@ -40,7 +40,7 @@ Sample values are fixtures, not live market observations. The calculation is a p ### Read-only by design -Buffer does not require a seed phrase, private key, wallet connection, or trading approval. Live lookups read Pacifica's public API or use a configured server-side Solana RPC for Velocity and Jupiter inventory. Velocity uses its pinned official SDK; Jupiter uses a separate canonical account decoder. Pacifica requires no API key. Optional sign-in and scenario storage do not grant authority over a wallet. +Buffer does not require a seed phrase, private key, wallet connection, or trading approval. The optional **Use my wallet** button is a read-only wallet connection: it asks the wallet for its public address and never requests a signature. Live lookups read Pacifica's public API or use a configured server-side Solana RPC for Velocity and Jupiter inventory. Velocity uses its pinned official SDK; Jupiter uses a separate canonical account decoder. Pacifica requires no API key. Optional sign-in and scenario storage do not grant authority over a wallet. Live availability depends on the deployment's provider configuration and RPC service. Modeled live calculations expire after at most two minutes, or earlier when their source price expires, and require a refresh. Live balances and oracle prices can change between reads. Jupiter has no current-price scenario until its oracle and collateral-dependent capped payoff are verified together. Legacy Drift is labeled paused and its balances are not treated as migrated Velocity state. Internet access is needed for live reads and account synchronization. @@ -54,4 +54,4 @@ Buffer pairs a responsive video-led website with a precise decimal calculation e --- -Buffer provides scenario exploration, not trading recommendations; its liquidation estimate is a narrow, versioned model, not the protocol’s liquidation engine. Browser installation is a PWA feature, not a claim of a separately published native iOS, Android, Windows, or macOS binary. +Buffer provides scenario exploration, not trading recommendations; its liquidation estimate is a narrow, versioned model, not the protocol’s liquidation engine. Browser installation is a PWA feature. The Android app is a Solana Mobile Web Shell, a signed APK built from `android/` that opens the same web app; there is no native iOS, Windows, or macOS binary. diff --git a/docs/PROVIDER.md b/docs/PROVIDER.md index 186b312..643746f 100644 --- a/docs/PROVIDER.md +++ b/docs/PROVIDER.md @@ -89,7 +89,7 @@ The earlier production Drift check is retained as historical evidence: authority Only server-side `SOLANA_RPC_URL` configures the RPC. The browser cannot supply an endpoint or program override. The endpoint must support `getGenesisHash`, filtered `getProgramAccounts`, `getAccountInfo`, `getMultipleAccounts`, and `getSlot`. Requests abort after 18 seconds; Vercel routes allow 30 seconds of function execution. Each process permits 60 reads per minute and four concurrent reads. Provider URLs and raw exceptions are not returned to the browser, and errors never fall back to samples. -The initial production RPC is Solana's shared mainnet endpoint and has no application-specific capacity guarantee. Use a dedicated endpoint for sustained traffic, and add a shared ingress limit when deploying more than one instance. All wallet-signing methods throw; there is no transaction, custody, trading, or wallet-connection path. +The initial production RPC is Solana's shared mainnet endpoint and has no application-specific capacity guarantee. Use a dedicated endpoint for sustained traffic, and add a shared ingress limit when deploying more than one instance. All wallet-signing methods throw; there is no transaction, custody, or trading path. The optional read-only wallet connection (**Use my wallet**) asks a Wallet Standard wallet, or Mobile Wallet Adapter on Android and Seeker, for its public address only. It never requests a signature, and the address follows the same read path as a pasted one. ## Tests and references diff --git a/e2e/brand-motion.spec.ts b/e2e/brand-motion.spec.ts index 9109a3f..e500c91 100644 --- a/e2e/brand-motion.spec.ts +++ b/e2e/brand-motion.spec.ts @@ -2,7 +2,7 @@ import { expect, test } from '@playwright/test'; test('wordmarks share the landing header typography and blue across pages and footer', async ({ page }) => { const identities = []; - for (const path of ['/', '/app', '/demo', '/auth']) { + for (const path of ['/', '/app', '/demo', '/auth', '/privacy', '/terms']) { await page.goto(path); for (const brand of await page.locator('[data-brand="buffer"]').all()) { identities.push(await brand.evaluate(element => { diff --git a/e2e/legal.spec.ts b/e2e/legal.spec.ts new file mode 100644 index 0000000..f4c3580 --- /dev/null +++ b/e2e/legal.spec.ts @@ -0,0 +1,72 @@ +import { expect, test, type Page } from '@playwright/test'; + +async function noOverflow(page: Page) { + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); +} + +test('the privacy policy is public, specific to Buffer and states what deletion removes', async ({ page }) => { + const response = await page.goto('/privacy'); + expect(response?.status()).toBe(200); + await expect(page).toHaveTitle('Privacy policy — Buffer'); + await expect(page.getByRole('heading', { level: 1, name: 'Privacy policy' })).toBeVisible(); + const main = page.getByRole('main'); + await expect(main).toContainText('Last updated: 7 October 2026'); + await expect(main).toContainText('Operator Uplift'); + await expect(main).toContainText('IPs are hashed for rate limiting and no address is stored.'); + for (const processor of ['Vercel', 'Supabase', 'Solana RPC provider', 'Velocity', 'Pacifica', 'Drift', 'Jupiter', 'Discord']) await expect(main).toContainText(processor); + for (const record of ['Saved reports', 'Monitored wallet addresses and alert rules', 'Alert destinations', 'Alert events and delivery records']) await expect(page.locator('#delete-account')).toContainText(record); + await expect(page.locator('#delete-account')).toContainText('BUFFER_WEBHOOK_DESTINATIONS_JSON'); + await expect(main).toContainText('18'); + await expect(main.getByRole('link', { name: 'github.com/operatoruplift/buffer/issues' }).first()).toHaveAttribute('href', 'https://github.com/operatoruplift/buffer/issues'); + await expect(main.getByRole('link', { name: 'Terms of use' }).first()).toHaveAttribute('href', '/terms'); + await expect(page.locator('meta[name="robots"]')).toHaveCount(0); + await noOverflow(page); +}); + +test('the terms carry the Solana dApp Store clause and the read-only limits', async ({ page }) => { + const response = await page.goto('/terms'); + expect(response?.status()).toBe(200); + await expect(page).toHaveTitle('Terms of use — Buffer'); + await expect(page.getByRole('heading', { level: 1, name: 'Terms of use' })).toBeVisible(); + const main = page.getByRole('main'); + await expect(main).toContainText('Last updated: 7 October 2026'); + await expect(main).toContainText('not trading advice'); + await expect(main).toContainText('cross-margin-hold-others-v1'); + await expect(main).toContainText('never asks for your seed phrase or private key'); + await expect(main).toContainText('Alerts can be delayed or fail'); + await expect(page.locator('#dapp-store')).toContainText('If you obtained Buffer through the Solana dApp Store, these terms are between you and Operator Uplift only.'); + await expect(page.locator('#dapp-store')).toContainText('Solana Mobile is not a party to these terms and has no responsibility or liability for Buffer, its content, or its support or maintenance.'); + for (const heading of ['No warranty', 'Limitation of liability', 'Governing law', 'Changes to these terms', 'Contact']) { + await expect(main.getByRole('heading', { name: heading })).toBeVisible(); + } + await expect(main.getByRole('link', { name: 'Privacy policy' }).first()).toHaveAttribute('href', '/privacy'); + await noOverflow(page); +}); + +test('the landing footer, the workspace and the sitemap all reach the legal pages', async ({ page, request }) => { + await page.goto('/'); + const legal = page.getByRole('navigation', { name: 'Footer legal navigation', exact: true }); + await expect(legal.getByRole('link', { name: 'Terms of use', exact: true })).toHaveAttribute('href', '/terms'); + await legal.getByRole('link', { name: 'Privacy policy', exact: true }).click(); + await expect(page).toHaveURL(/\/privacy$/); + await expect(page.getByRole('heading', { level: 1, name: 'Privacy policy' })).toBeVisible(); + + await page.goto('/app'); + const workspaceLegal = page.getByRole('navigation', { name: 'Legal', exact: true }); + await expect(workspaceLegal.getByRole('link', { name: 'Privacy', exact: true })).toBeVisible(); + await workspaceLegal.getByRole('link', { name: 'Terms', exact: true }).click(); + await expect(page).toHaveURL(/\/terms$/); + await expect(page.getByRole('heading', { level: 1, name: 'Terms of use' })).toBeVisible(); + + const sitemap = await (await request.get('/sitemap.xml')).text(); + expect(sitemap).toContain('https://bufferonsolana.vercel.app/privacy'); + expect(sitemap).toContain('https://bufferonsolana.vercel.app/terms'); +}); + +test('the landing hero describes the read-only wallet connection accurately', async ({ page }) => { + await page.goto('/'); + const note = page.locator('.buffer-hero-note'); + await expect(note).toHaveText('Read-only wallet connection. No signatures or trading permissions.'); + await expect(page.getByText('No wallet connection.', { exact: false })).toHaveCount(0); + await expect(page.locator('#privacy').getByRole('link', { name: 'Read the privacy policy' })).toHaveAttribute('href', '/privacy'); +}); diff --git a/src/app/landing.css b/src/app/landing.css index 2d16a75..e08e148 100644 --- a/src/app/landing.css +++ b/src/app/landing.css @@ -163,6 +163,7 @@ .buffer-privacy h2 { font-size: 34px; letter-spacing: -1.4px; margin-top: 6px; } .buffer-privacy p { font-size: 12px; line-height: 1.85; color: var(--quiet); max-width: 392px; } .buffer-privacy .buffer-text-link { margin-top: 19px; } +.buffer-privacy-links { display: flex; flex-wrap: wrap; gap: 0 28px; } .buffer-faq { display: grid; grid-template-columns: 1fr 1.25fr; gap: 70px; } .buffer-faq h2 { margin: 25px 0; } .buffer-faq-list { border-top: 1px solid var(--line); } @@ -178,7 +179,7 @@ .buffer-last-call .buffer-cta { background: #fff; color: var(--cobalt) !important; } .buffer-last-call .buffer-cta > span { background: #e9edff; } .buffer-footer { margin: 0; padding: 56px max(48px, calc((100vw - 1296px) / 2)) 25px; border: 0; display: block; color: var(--ink); background: #f0f1e9; } -.buffer-footer-top { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 35px; } +.buffer-footer-top { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 35px; } .buffer-footer-top > p { font-size: 22px; line-height: 1.3; letter-spacing: -.6px; } .buffer-footer nav { display: flex; flex-direction: column; align-items: flex-start; gap: 12px; font-size: 11px; } .buffer-footer nav a:hover { color: var(--cobalt); } @@ -587,3 +588,5 @@ html[data-buffer-scroll="smooth"] { scroll-behavior: smooth; } html[data-buffer-scroll="smooth"] { scroll-behavior: auto; } .buffer-site [data-scroll-depth] { transform: none !important; } } +/* The footer gained a legal column; give it a row of its own before phones stack it. */ +@media (min-width: 521px) and (max-width: 800px) { .buffer-footer-top { grid-template-columns: repeat(3, minmax(0, 1fr)); } .buffer-footer-top > p { grid-column: 1 / -1; } } diff --git a/src/app/privacy/page.tsx b/src/app/privacy/page.tsx new file mode 100644 index 0000000..665a5b9 --- /dev/null +++ b/src/app/privacy/page.tsx @@ -0,0 +1,127 @@ +import type { Metadata } from 'next'; +import Link from 'next/link'; +import LegalDocument, { LegalList, SupportLink, type LegalSection } from '@/components/legal/LegalDocument'; +import { LEGAL_OPERATOR } from '@/lib/legal'; + +export const metadata: Metadata = { + title: 'Privacy policy — Buffer', + description: 'What Buffer stores, why, for how long, and how to delete your account and its data.', + alternates: { canonical: '/privacy' }, +}; + +const summary = [ + 'Presets, live account reads and reports saved on your device work without an account.', + 'Buffer never asks for your seed phrase or private key, never requests a signature and never moves funds.', + 'With an account, we store your email address, saved reports and the alert rules you create.', + 'You can delete your account and its data from inside the app at any time.', + 'We do not sell your information, and Buffer has no advertising or analytics trackers.', +]; + +const sections: LegalSection[] = [ + { id: 'who-we-are', title: 'Who we are', body: <> +

Buffer is operated by {LEGAL_OPERATOR} (“we”, “us”). This policy covers the Buffer website and web app at bufferonsolana.vercel.app, the installed web app, and the Buffer Android app, which opens the same web app.

+

Our Terms of use set out the rules for using Buffer. Questions about this policy go to .

+ }, + { id: 'without-an-account', title: 'Using Buffer without an account', body: <> + Presets and the portfolio builder run in your browser with fixed reference prices. Nothing about them is sent to us., + <>Live reads. When you read an account, your browser sends the public wallet address, protocol, network and subaccount to Buffer’s server. The server reads that account’s public data from the provider and returns it. Buffer does not store the addresses you look up., + <>Reports on this device stay in your browser’s storage. We never receive them and they are never uploaded. Clearing your browser data removes them., + <>Settings on this device. Your browser also keeps your animation preference, example alert settings and, when you sign in, your session. They stay on the device., + ]} /> +

Buffer sets no tracking cookies and includes no advertising or analytics scripts.

+ }, + { id: 'wallet', title: 'Wallet connection', body: <> +

“Use my wallet” asks a wallet in your browser, or on Android and Seeker a wallet through Mobile Wallet Adapter, to share its public address. Buffer uses that address only to read the public account, exactly as if you had pasted it.

+

Buffer never requests a signature or a transaction, and it cannot move funds. On Android, Mobile Wallet Adapter keeps its connection approval in this app’s storage on your device so your wallet can reconnect. You can revoke it in your wallet.

+ }, + { id: 'accounts', title: 'Accounts and saved reports', body: <> +

Accounts are optional. If you create one, Supabase, our database and sign-in provider, stores:

+ +

Database rules let only your signed-in account read or change these records. Supabase Auth sends confirmation and password recovery emails to your address.

+ }, + { id: 'alerts', title: 'Alerts and monitored wallets', body: <> +

Alerts are optional and need an account. When you set an alert rule, we store:

+ Alert rules: the monitored public wallet address and subaccount, the metric (maintenance headroom or liquidation distance), the market, your threshold, check interval, timezone, cooldown and recovery distance., + <>Monitoring state: when each rule was last checked, its latest observation and any error., + <>Alert events: each threshold crossing, with the observed value, the observation it came from and a preview of the message., + <>Delivery records: attempts, outcomes and the receipt returned by Discord or the webhook., + <>Alert destinations: the label and masked name of each destination set up for your account., + <>Manual checks: a record of each check you start, kept for 7 days., + ]} /> +

Destinations are Discord channels or signed webhooks that the operator configures on the server for specific accounts. You cannot add one yourself, and their URLs and secrets are never stored in the database. When an alert fires, Buffer sends the alert message, which includes the monitored wallet address, subaccount, metric and values, to that destination.

+ }, + { id: 'rate-limiting', title: 'Rate limiting and service logs', body: <> +

To keep live reads available, Buffer limits how often one connection can read. IPs are hashed for rate limiting and no address is stored. The counter keeps a one-way SHA-256 hash of your IP address, never the address itself, with a request count for the current minute. It holds no account or wallet data.

+

Our hosting provider, Vercel, processes every request to serve Buffer and keeps standard request logs under its own policies. These can include your IP address, browser details and the address of the page or API called. For a live read, that includes the public wallet address you looked up.

+ }, + { id: 'processors', title: 'Service providers', body: <> +

We use these providers to run Buffer. Each receives only what it needs for its part:

+ Vercel hosts the website, the app and its server functions., + <>Supabase stores accounts, saved reports, alerts and rate-limit counters, handles sign-in and sends account emails. Your account data is stored in the United States., + <>A Solana RPC provider chosen by the operator receives the public addresses Buffer reads on Velocity, Jupiter and legacy Drift, and returns on-chain data. Velocity devnet reads use Solana’s public devnet RPC., + <>Velocity, Jupiter and Drift data is read from their public on-chain accounts through that RPC provider., + <>Pacifica data is read from Pacifica’s public API, which receives the public address you look up., + <>Discord or webhook recipients receive alert messages for the accounts the operator set them up for., + <>Your wallet shares your public address when you choose “Use my wallet”. Its own privacy policy applies., + <>GitHub hosts our public issue tracker. Its privacy policy applies to anything you post there., + ]} /> +

Vercel and Supabase can process information in the United States and other countries.

+ }, + { id: 'retention', title: 'How long we keep information', body: }, + { id: 'delete-account', title: 'Deleting your account', body: <> +

Signed in, open My reports in the app and choose Delete account. After you confirm, Buffer deletes your account in the database and signs you out on that device. This permanently removes:

+ +

It does not remove:

+ +

Alert destinations themselves are operator configuration, not your data. The operator lists which accounts may use each destination in the server settings BUFFER_DISCORD_DESTINATIONS_JSON and BUFFER_WEBHOOK_DESTINATIONS_JSON (their ownerIds). Deleting your account removes the destination records linked to it, so nothing more is sent. Your former account ID can stay in that configuration until we next update it. It no longer matches any account, and we remove it at that update.

+

If you can no longer sign in, contact us at and we will delete the account for you.

+ }, + { id: 'security', title: 'Security', body: }, + { id: 'children', title: 'Age requirement', body:

Buffer is for people aged 18 or older. We do not knowingly collect information from anyone under 18. If you believe a person under 18 created an account, contact us and we will delete it.

}, + { id: 'rights', title: 'Your choices and rights', body: <> +

You can use Buffer without an account, download any saved report as JSON, delete reports and delete your account in the app.

+

Depending on where you live, you may have rights to access, correct, export or delete your information, or to object to how we use it. Contact us to make a request and we will respond within the time the law requires. We do not sell your information or share it for advertising.

+ }, + { id: 'changes', title: 'Changes to this policy', body:

We post changes on this page and update the date at the top. If you keep using Buffer after a change, the updated policy applies.

}, + { id: 'contact', title: 'Contact', body: <> +

{LEGAL_OPERATOR}: .

+

GitHub issues are public. Do not post your email address, wallet address or other personal details there. Describe your request and we will arrange a private way to complete it.

+ }, +]; + +export default function PrivacyPage() { + return ; +} diff --git a/src/app/sitemap.ts b/src/app/sitemap.ts index 90a05e9..7007be3 100644 --- a/src/app/sitemap.ts +++ b/src/app/sitemap.ts @@ -8,5 +8,7 @@ export default function sitemap(): MetadataRoute.Sitemap { { url: `${SITE_URL}/app`, changeFrequency: 'weekly', priority: 0.9 }, { url: `${SITE_URL}/demo`, changeFrequency: 'monthly', priority: 0.7 }, { url: `${SITE_URL}/brand-kit`, changeFrequency: 'monthly', priority: 0.6 }, + { url: `${SITE_URL}/privacy`, changeFrequency: 'yearly', priority: 0.3 }, + { url: `${SITE_URL}/terms`, changeFrequency: 'yearly', priority: 0.3 }, ]; } diff --git a/src/app/terms/page.tsx b/src/app/terms/page.tsx new file mode 100644 index 0000000..5827e66 --- /dev/null +++ b/src/app/terms/page.tsx @@ -0,0 +1,73 @@ +import type { Metadata } from 'next'; +import Link from 'next/link'; +import LegalDocument, { LegalClause, LegalList, SupportLink, type LegalSection } from '@/components/legal/LegalDocument'; +import { LEGAL_OPERATOR } from '@/lib/legal'; +import { LIQUIDATION_MODEL_VERSION } from '@/lib/risk/liquidation'; + +export const metadata: Metadata = { + title: 'Terms of use — Buffer', + description: 'The terms for using Buffer, a read-only tool for exploring Solana perpetual positions.', + alternates: { canonical: '/terms' }, +}; + +const summary = [ + 'Buffer is a read-only tool. It is not trading advice.', + 'Price scenarios and liquidation estimates are versioned estimates, not guarantees.', + 'Buffer never asks for your keys and never signs.', + 'Alerts can be delayed or fail. Do not rely on them alone.', + 'Buffer is provided as is, without warranties.', +]; + +const sections: LegalSection[] = [ + { id: 'agreement', title: 'These terms', body: <> +

These terms are an agreement between you and {LEGAL_OPERATOR}, which operates Buffer (“we”, “us”). They cover the Buffer website and web app, the installed web app and the Buffer Android app. By using Buffer you agree to them. If you do not agree, do not use Buffer.

+

Our Privacy policy explains what Buffer stores and how to delete it.

+ }, + { id: 'eligibility', title: 'Who can use Buffer', body:

You must be at least 18 years old and able to enter a binding agreement. Do not use Buffer where doing so breaks the law, or if you are the target of sanctions or are in a sanctioned country or region.

}, + { id: 'service', title: 'What Buffer does', body: <> +

Buffer reads public data about Solana perpetual positions on Velocity, Pacifica, Jupiter Perps and legacy Drift. It shows a price scenario, the provider’s risk context and related details. Buffer is read-only. It does not hold funds, place trades, custody assets or give access to any exchange.

+

Protocols, RPC providers and APIs are run by third parties. Their data can be late, incomplete or wrong, and their own terms apply to them.

+ }, + { id: 'not-advice', title: 'Not trading advice', body:

Buffer is not trading advice, and it is not investment, financial, legal or tax advice. Nothing in Buffer recommends buying, selling or holding anything. You are responsible for your own decisions and trades.

}, + { id: 'estimates', title: 'Estimates are not guarantees', body: <> +

A price scenario applies one percentage move to eligible positions, with sizes and baseline prices held fixed. It leaves out funding, fees, collateral changes, future fills and liquidation effects.

+

The liquidation estimate is a versioned estimate, currently model {LIQUIDATION_MODEL_VERSION}. It solves for the price at which one position alone would reach the maintenance boundary while everything else stays fixed. It is not the protocol’s liquidation engine and it is not a guarantee: a position can be liquidated at a different price or time. Live calculations expire after at most two minutes.

+ }, + { id: 'keys', title: 'Your keys and wallet', body: <> +

Buffer never asks for your seed phrase or private key, never requests a signature and never sends a transaction. “Use my wallet” asks your wallet for its public address and nothing else.

+

If anyone claiming to be Buffer asks for your keys or a signature, do not provide them. You are responsible for your wallets, devices and trades.

+ }, + { id: 'alerts', title: 'Alerts', body: <> +

Alerts are optional and need an account. Delivery depends on the protocols, RPC providers and scheduler Buffer uses, on Discord or your webhook receiver, and on the destinations the operator configures.

+

Alerts can be delayed or fail. They can also arrive twice or not at all, and checks pause when data is unavailable. Do not rely on alerts alone. Watch your positions directly and use your protocol’s own tools.

+ }, + { id: 'accounts', title: 'Your account', body:

Keep your sign-in details secure, and tell us if you think someone else used your account. You can delete your account and its data at any time from My reports in the app. We may suspend or close an account that breaks these terms or puts the service at risk.

}, + { id: 'acceptable-use', title: 'Acceptable use', body: <> +

Do not misuse Buffer. In particular, do not:

+ +

Buffer’s source code is available under the MIT License at github.com/operatoruplift/buffer. That license covers the code. These terms cover your use of the hosted service and apps.

+ }, + { id: 'availability', title: 'Changes to Buffer', body:

Buffer is free to use. We can change, pause or stop any part of it at any time, including supported protocols, live reads and alerts. Buffer depends on third-party services, and we are not responsible for their outages.

}, + { id: 'no-warranty', title: 'No warranty', body:

Buffer is provided “as is” and “as available”. To the fullest extent the law allows, we disclaim all warranties, express or implied, including accuracy, merchantability, fitness for a particular purpose, non-infringement and uninterrupted or error-free operation.

}, + { id: 'liability', title: 'Limitation of liability', body: <> +

To the fullest extent the law allows, {LEGAL_OPERATOR} is not liable for any indirect, incidental, special, consequential or punitive damages, or for any loss of funds, trading losses, liquidations, lost profits or lost data, arising from your use of Buffer or your reliance on its information or alerts.

+

Our total liability for any claim relating to Buffer is limited to 100 US dollars. Some places do not allow these limits, so they may not apply to you.

+ }, + { id: 'dapp-store', title: 'Solana dApp Store', body: +

If you obtained Buffer through the Solana dApp Store, these terms are between you and {LEGAL_OPERATOR} only. Solana Mobile is not a party to these terms and has no responsibility or liability for Buffer, its content, or its support or maintenance.

+
}, + { id: 'law', title: 'Governing law', body:

These terms are governed by the laws of the place where {LEGAL_OPERATOR} is established, without regard to conflict-of-law rules. The mandatory consumer protections of the place where you live still apply.

}, + { id: 'changes', title: 'Changes to these terms', body:

We may update these terms. We post the new version on this page and update the date at the top. If you keep using Buffer after a change, the updated terms apply.

}, + { id: 'contact', title: 'Contact', body:

Questions about these terms go to {LEGAL_OPERATOR} at .

}, +]; + +export default function TermsPage() { + return ; +} diff --git a/src/components/AppNavigation.module.css b/src/components/AppNavigation.module.css index e85617f..5adc0c0 100644 --- a/src/components/AppNavigation.module.css +++ b/src/components/AppNavigation.module.css @@ -51,6 +51,8 @@ .utilities a { display: flex; align-items: center; gap: 8px; min-height: 38px; padding: 7px 6px; color: #65715f; font-size: 11px; border-radius: 8px; } .utilities a:hover { color: #315fe8; background: #eef2e9; text-decoration: none; } .utilities a > span { width: 17px; text-align: center; font-size: 16px; } +.utilities .legal { display: flex; align-items: center; gap: 4px; margin: 6px 0 0; padding: 0 6px; color: #a0a89a; font-size: 11px; } +.utilities .legal a { min-height: 32px; padding: 6px 4px; } @media (max-width: 1179px) { .shell { --app-nav-fill: #fafbf8; diff --git a/src/components/AppNavigation.tsx b/src/components/AppNavigation.tsx index fc40068..2551a27 100644 --- a/src/components/AppNavigation.tsx +++ b/src/components/AppNavigation.tsx @@ -127,6 +127,7 @@ export default function AppNavigation({ positionsAvailable, scenarioAvailable, a
Watch walkthrough Back to website +

PrivacyTerms

; } diff --git a/src/components/AppWorkspace.css b/src/components/AppWorkspace.css index 07df2c6..fa32ce5 100644 --- a/src/components/AppWorkspace.css +++ b/src/components/AppWorkspace.css @@ -97,7 +97,10 @@ .buffer-app .network-picker button[aria-pressed="true"] { background: #243b31; border-color: #243b31; } .buffer-app .address-bottom p { font-size: 12px; line-height: 1.6; } .buffer-app .model-tag { font-size: 9px; } -.buffer-app footer { margin-top: 32px; padding-bottom: 0; font-size: 11px; } +.buffer-app footer { margin-top: 32px; padding-bottom: 0; font-size: 11px; gap: 16px; } +.buffer-app .footer-legal { display: flex; gap: 18px; } +.buffer-app .footer-legal a { display: inline-flex; align-items: center; min-height: 32px; color: var(--muted); } +.buffer-app .footer-legal a:hover { color: var(--blue); } .buffer-app .toast { z-index: 45; } body:has(.buffer-app) { background: #f3f5f1; } body:has(.buffer-app) #app-installation { max-width: none; padding-top: 0; background: #f3f5f1; } diff --git a/src/components/AuthForm.module.css b/src/components/AuthForm.module.css index 11b956c..0ed96ed 100644 --- a/src/components/AuthForm.module.css +++ b/src/components/AuthForm.module.css @@ -50,6 +50,8 @@ .unavailable p + p { margin-top: 16px; } .footer { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 14px; width: 100%; max-width: 1280px; margin: 0 auto; font-size: 10px; color: #f7f9ff; text-shadow: 0 1px 5px rgb(15 31 59 / 90%); } .footer a { color: inherit; } +.legal { display: flex; gap: 18px; } +.fine a { color: #203c70; text-decoration: underline; text-underline-offset: 2px; } .content > .intro, .form > .field, .form > .recovery, .form > .submit, .form > .switch, .content > .guest, .content > .unavailable { animation: auth-enter 700ms cubic-bezier(.22, 1, .36, 1) both; } .form > :nth-child(1) { animation-delay: 100ms; } .form > :nth-child(2) { animation-delay: 200ms; } diff --git a/src/components/AuthForm.tsx b/src/components/AuthForm.tsx index 80872f5..14999e4 100644 --- a/src/components/AuthForm.tsx +++ b/src/components/AuthForm.tsx @@ -252,11 +252,11 @@ export default function AuthForm({ initialMode = 'signin' }: { initialMode?: 'si }
{ if (event.target === event.currentTarget) setEntered(true); }}> Continue without an account -

The public explorer and device reports are ready to use. Signing in never connects a wallet or grants permission to trade.

+

The public explorer and device reports are ready to use. Signing in never connects a wallet or grants permission to trade. By creating an account you agree to the Terms of use; the Privacy policy explains what is stored and how to delete it.

-
A little more room to think.Privacy by design
+
A little more room to think.
; } diff --git a/src/components/Dashboard.tsx b/src/components/Dashboard.tsx index 6d58e59..67ceb3c 100644 --- a/src/components/Dashboard.tsx +++ b/src/components/Dashboard.tsx @@ -1289,6 +1289,7 @@ export default function Dashboard({ Solana · {mode === "sample" ? "Examples" : protocol.label} /{" "} {mode === "sample" ? "Reference data" : snapshot?.network === "devnet" ? `${NETWORK_LABELS.devnet} public account data` : "Mainnet public account data"} +
diff --git a/src/components/Landing.tsx b/src/components/Landing.tsx index 5cf4700..27b523a 100644 --- a/src/components/Landing.tsx +++ b/src/components/Landing.tsx @@ -87,7 +87,7 @@ function ScenarioContextCard({ shock }: { shock: number }) { const questions = [ ["What does Buffer calculate?", "Buffer models the incremental price P&L of eligible linear perpetual positions. It multiplies each signed position size by its frozen baseline oracle price and your chosen percentage move, then totals contributions with the same quote currency."], - ["Do I need a wallet or an account?", "You can explore preset accounts immediately without signing in or connecting a wallet. For a live lookup, enter a public Solana authority address. Save scenarios on your device without an account. Optional cloud sign-in never grants Buffer trading permissions."], + ["Do I need a wallet or an account?", "You can explore preset accounts immediately without signing in or connecting a wallet. For a live lookup, paste a public Solana address or tap Use my wallet, which shares only your public address and never asks for a signature. Save scenarios on your device without an account. Optional cloud sign-in never grants Buffer trading permissions, and you can delete the account in the app."], ["Is this a liquidation or account-equity forecast?", "The price scenario is not. It covers the modeled perpetual price effect and does not recalculate account equity or margin health. A separate, versioned estimate on live Velocity reads solves the oracle price at which one position alone would reach the maintenance boundary, holding everything else; it is a narrow model, not the protocol’s liquidation engine."], ["Which positions are supported?", "Explore 76 configured perpetual markets on Pacifica, spanning crypto, equities, commodities, and FX, plus SOL, BTC, ETH, and HYPE on Velocity. Browse the market list in the app. Each live position must pass market and price checks. Jupiter Perps shows verified inventory without a price-effect estimate; legacy Drift reads are paused. Unsupported exposure is excluded with an explanation."], ["Are the example numbers live market prices?", "No. Examples are deterministic fixtures, clearly labeled in the app. Live lookups use Pacifica’s public API or a Solana RPC provider and show source and freshness information. Live calculations expire after at most two minutes and require a refresh."], @@ -194,7 +194,7 @@ export default function Landing() {

Explore the price effect on your Solana perpetual positions, with the source, assumptions and coverage in view.

Open Buffer
Explore live risk Public Velocity account -
No wallet connection. No trading permissions.
+
Read-only wallet connection. No signatures or trading permissions.
@@ -240,14 +240,14 @@ export default function Landing() {