diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3b80d9a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 + +[*.{cs,csproj}] +indent_size = 4 + +[*.md] +trim_trailing_whitespace = false diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8571c8b --- /dev/null +++ b/.env.example @@ -0,0 +1,13 @@ +# Sessionist environment template. Copy to `.env` and fill in. +# Never commit real values. See PRD §13.8 (Payments & licensing). + +# Public Ed25519 key (base64) baked into the extension build to verify license +# keys offline. The matching private key lives only in the Cloudflare Worker. +WXT_LICENSE_PUBLIC_KEY= + +# Base URL of the Cloudflare Worker that creates Stripe Checkout sessions and +# mints signed license keys. +WXT_CHECKOUT_WORKER_URL=https://checkout.sessionist.example + +# Optional telemetry collector endpoint (telemetry is opt-in, PRD §15). +WXT_TELEMETRY_ENDPOINT= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c93dc4b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,64 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + extension: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm run compile + - run: npm run lint + - run: npm run format + - run: npm run build + + # Spec-by-test suite. Currently RED BY DESIGN: tests encode the contract each + # feature must satisfy and go green as features are implemented. `continue-on- + # error` keeps it informational on the skeleton — remove it (make it a hard + # gate) once the suite is green. + tests: + runs-on: ubuntu-latest + continue-on-error: true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm test + + worker: + runs-on: ubuntu-latest + defaults: + run: + working-directory: worker + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: worker/package-lock.json + - run: npm ci + - run: npm run compile + + backend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - run: dotnet build backend/Sessionist.Api/Sessionist.Api.csproj + # Backend contract tests — red by design until the Team backend is built. + - run: dotnet test backend/Sessionist.Api.Tests/Sessionist.Api.Tests.csproj + continue-on-error: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b5d3162 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Dependencies +node_modules/ + +# WXT build output +.wxt/ +.output/ +stats.html + +# Playwright +playwright-report/ +test-results/ +.playwright/ + +# Env / secrets +.env +.env.* +!.env.example + +# Agent worktrees / local tooling +.claude/ + +# Editor / OS +.vscode/ +.idea/ +.DS_Store +Thumbs.db + +# .NET backend +backend/**/bin/ +backend/**/obj/ + +# Cloudflare worker +worker/node_modules/ +worker/.wrangler/ diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..1636e8e --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +node_modules/ +.wxt/ +.output/ +worker/node_modules/ +backend/**/bin/ +backend/**/obj/ +*.md diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..e5ce635 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "singleQuote": true, + "trailingComma": "all", + "printWidth": 100, + "semi": true +} diff --git a/LICENSE b/LICENSE index 261eeb9..ce78f1c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,115 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +# Functional Source License, Version 1.1, Apache 2.0 Future License + +## Abbreviation + +FSL-1.1-Apache-2.0 + +## Notice + +Copyright 2026 Murray le Roux (Sessionist) + +## Terms and Conditions + +### Licensor ("We") + +The party offering the Software under these Terms and Conditions. + +### The Software + +The "Software" is each version of the software that we make available under +these Terms and Conditions, as indicated by our inclusion of these Terms and +Conditions with the Software. + +### License Grant + +Subject to your compliance with this License Grant and the Patents, +Redistribution and Trademark clauses below, we hereby grant you the right to use, +copy, modify, create derivative works, publicly perform, publicly display and +redistribute the Software for any Permitted Purpose identified below. + +### Permitted Purpose + +A Permitted Purpose is any purpose other than a Competing Use. A Competing Use +means making the Software available to others in a commercial product or service +that: + +1. substitutes for the Software; + +2. substitutes for any other product or service we offer using the Software that + exists as of the date we make the Software available; or + +3. offers the same or substantially similar functionality as the Software. + +Permitted Purposes specifically include using the Software: + +1. for your internal use and access; + +2. for non-commercial education; + +3. for non-commercial research; and + +4. in connection with professional services that you provide to a licensee using + the Software in accordance with these Terms and Conditions. + +### Patents + +To the extent your use for a Permitted Purpose would necessarily infringe our +patents, the license grant above includes a license under our patents. If you +make a claim against any party that the Software infringes or contributes to the +infringement of any patent, then your patent license to the Software ends +immediately. + +### Redistribution + +The Terms and Conditions apply to all copies, modifications and derivatives of +the Software. + +If you redistribute any copies, modifications or derivatives of the Software, you +must include a copy of or a link to these Terms and Conditions and not remove any +copyright notices provided in or with the Software. + +### Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, INCLUDING +BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE, TITLE OR NON-INFRINGEMENT. + +IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE +SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN +IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. + +### Trademarks + +Except for displaying the License Details and identifying us as the origin of the +Software, you have no right under these Terms and Conditions to use our +trademarks, trade names, service marks or product names. + +## Grant of Future License + +We hereby irrevocably grant you an additional license to use the Software under +the Apache License, Version 2.0 that is effective on the second anniversary of +the date we make the Software available. On or after that date, you may use the +Software under the Apache License, Version 2.0, in which case the following will +apply: + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and limitations +under the License. + +--- + +NOTE (Sessionist): The specific source-available license is still an open +decision (PRD §18 — BSL vs FSL vs PolyForm). FSL-1.1-Apache-2.0 is used here as a +sensible default that satisfies the locked decision #2 (source-available, NOT +OSI-permissive). Only the cookie editor and local session capture/switch client +are covered; Pro entitlement logic and the Team sync server remain closed-source. diff --git a/README.md b/README.md index c964cc1..b8133fa 100644 --- a/README.md +++ b/README.md @@ -1 +1,103 @@ -# Sessionist \ No newline at end of file +# Sessionist + +> Save, switch, and export browser session identities — the missing power-tool for testing as different users. + +A Manifest V3 browser extension for developers and QA engineers. Cookie editor, +session profiles, and Playwright `storageState` export. See +[`sessionist-prd-v1_5.md`](sessionist-prd-v1_5.md) for the full product spec. + +> **Status: skeleton.** Every feature has a wired entry point and the project +> builds, but service logic is stubbed (`NotImplementedError`). No behaviour yet. + +## Stack + +- **Extension:** [WXT](https://wxt.dev) (Vite), TypeScript strict, React + Tailwind, Zustand. MV3, Side Panel first. +- **Checkout/licensing:** Cloudflare Worker (`worker/`) — Stripe Checkout + Ed25519 license minting, verified offline. +- **Team backend (P2):** ASP.NET Core / .NET 10 Minimal API (`backend/`) — zero-knowledge sync, stubbed until validated. + +## Getting started + +```bash +npm install # installs deps + runs `wxt prepare` +npm run dev # Chrome dev build with HMR +npm run dev:firefox +npm run build # production build -> .output/ +npm run compile # typecheck only (tsc --noEmit) +npm run lint # eslint +npm run format # prettier --check (use format:write to fix) +npm test # vitest unit + integration suite +npm run test:coverage +npm run test:e2e # Playwright E2E (needs `npm run build` first + a browser) +``` + +### Tests + +The repo ships a **spec-by-test** suite (~1100 vitest + 40 .NET + 43 Playwright +specs) that encodes the PRD contract for every feature. It is **red by design** +on the skeleton — each test goes green only when its feature is implemented +correctly, and fails again if an implementation is wrong or an edge case is +unhandled. When the whole suite is green, the app meets the PRD. See +[`tests/README.md`](tests/README.md) for layout, the fake-`chrome` harness, and +per-PRD-section coverage; [`tests/CONTRACTS.md`](tests/CONTRACTS.md) is the +behavioural source of truth. + +CI (`.github/workflows/ci.yml`) runs compile + lint + format + build for the +extension, typecheck for the worker, and `dotnet build` for the backend. Use +`npm ci` (not `npm install`) for reproducible installs. + +Load the unpacked extension from `.output/chrome-mv3/` (or use `npm run dev`, +which launches a browser with it installed). + +Copy `.env.example` to `.env` and fill in the license public key / worker URL. + +## Layout + +``` +src/ + entrypoints/ WXT entry points + background.ts MV3 service worker — message router + sidepanel/ primary UI (React); opens on toolbar click + popup/ compact UI (P1) + types/ models (PRD §13.11) + message protocol + envelope + lib/ messaging, error markers, redacting logger + background/router.ts single dispatch point for all UI requests + services/ one folder per capability (see map below) + capture/pageScript.ts page-context web-storage fns injected via + chrome.scripting.executeScript (no content script) + state/store.ts Zustand UI store + ui/ App shell, hooks, views, components +worker/ Cloudflare Worker (checkout + license minting) +backend/ .NET 10 Team backend (P2) +``` + +Web storage (localStorage/sessionStorage) is read/written by injecting a +function into the active, granted tab — there is **no persistent content script** +and **no install-time host permission** (host access is requested per-origin at +runtime). Verify: the built `manifest.json` has no `host_permissions`. + +## PRD feature → entry point map + +| PRD section | Feature | Entry point | +|---|---|---| +| §9.1 | Cookie editor (free) | [`services/cookies/`](src/services/cookies), [`CookieEditorView`](src/ui/views/CookieEditorView.tsx) | +| §9.2 | Session profiles / switch | [`services/profiles/`](src/services/profiles), [`ProfilesView`](src/ui/views/ProfilesView.tsx) | +| §9.3 | Playwright export (P0) | [`playwrightExport`](src/services/export/playwrightExport.ts), [`ExportView`](src/ui/views/ExportView.tsx) | +| §9.4 | Puppeteer/Selenium/cURL (P1) | [`services/export/`](src/services/export) | +| §9.5 | Search-intent onboarding | [`OnboardingView`](src/ui/views/OnboardingView.tsx) | +| §9.6 | Permission UX | [`permissionService`](src/services/permissions/permissionService.ts), [`SiteAccessView`](src/ui/views/SiteAccessView.tsx) | +| §9.7 | Team sync & vaults (P2) | [`services/team/`](src/services/team), [`TeamView`](src/ui/views/TeamView.tsx), [`backend/`](backend) | +| §9.8 | Encryption / telemetry / theme | [`services/crypto/`](src/services/crypto), [`services/telemetry/`](src/services/telemetry), [`SettingsView`](src/ui/views/SettingsView.tsx) | +| §11 | Tiers / paywall / Pro unlock | [`UpgradeView`](src/ui/views/UpgradeView.tsx), [`entitlementService`](src/services/licensing/entitlementService.ts) | +| §13.4 | Storage architecture | [`services/storage/`](src/services/storage) | +| §13.8 | Payments & licensing | [`services/licensing/`](src/services/licensing), [`worker/`](worker) | +| §13.11 | Data model | [`types/models.ts`](src/types/models.ts) | + +## Conventions + +- Service functions are stubs that throw `NotImplementedError` — replace as features land. Types are real. +- Never log or transmit cookie/storage/profile values (PRD §14.3 / §15). +- Minimum install-time permissions; host access requested at runtime (PRD §9.6). +- Core is **source-available, not OSI-permissive** (PRD §12.4): `LICENSE` is + FSL-1.1-Apache-2.0. The exact choice (BSL/FSL/PolyForm) is still open (§18). +- `settingsRepository` is implemented (not a stub) because onboarding routing, + theming, and the telemetry opt-in depend on it to make the skeleton runnable. diff --git a/backend/Sessionist.Api.Tests/ApiFactory.cs b/backend/Sessionist.Api.Tests/ApiFactory.cs new file mode 100644 index 0000000..e7f9a55 --- /dev/null +++ b/backend/Sessionist.Api.Tests/ApiFactory.cs @@ -0,0 +1,17 @@ +// Shared WebApplicationFactory for all integration tests. +// Uses the Program from Sessionist.Api (top-level statements + "public partial class Program {}" seam). + +using Microsoft.AspNetCore.Mvc.Testing; + +namespace Sessionist.Api.Tests; + +/// +/// Spins up the real ASP.NET Core pipeline in-memory. +/// Tests that exercise auth use per-test clients with real JWT headers via JwtHelper. +/// +public sealed class ApiFactory : WebApplicationFactory +{ + // The JWT signing constants are in sync with JwtHelper.cs and Program.cs. + // No WebApplicationFactory overrides needed: the API is configured at startup + // using the same constants that JwtHelper uses to produce tokens. +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/AuditTests.cs b/backend/Sessionist.Api.Tests/ContractTests/AuditTests.cs new file mode 100644 index 0000000..e376e7f --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/AuditTests.cs @@ -0,0 +1,304 @@ +// PRD §9.7 / §13.10 – Audit log contract tests. +// +// GET /vaults/{id}/audit must return entries that contain: +// - eventType (string, non-empty) +// - objectId (or vaultId or profileId — at least one object reference) +// +// And must NEVER contain: +// - cookies, localStorage, sessionStorage field names +// - any plaintext session content +// - cleartext profile blobs +// +// PRD §13.10: "Audit logs track events and object IDs, not plaintext session contents." +// +// Mutations killed by this class: +// - Returning plaintext in audit entries → zero-knowledge field tests fail +// - Omitting eventType → schema tests fail +// - Omitting objectId reference → schema tests fail +// - Not requiring auth → 401 tests fail +// - Returning non-array → type check tests fail +// - Including session data string values → substring check fails +// - Not recording invite/rotation events → event-correlation tests fail + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Audit log contract tests (PRD §9.7 + §13.10). +/// +public sealed class AuditTests(ApiFactory factory) : IClassFixture +{ + private HttpClient AuthClient(string userId = "audit-user-1", string email = "audit@example.com") + { + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BearerToken(userId, email)); + return client; + } + + // Helper: create a vault and return its ID. + private static async Task CreateVaultAsync(HttpClient client, string name = "Audit Vault") + { + var resp = await client.PostAsJsonAsync("/vaults", new { name }); + Assert.Equal(HttpStatusCode.Created, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + return doc.RootElement.GetProperty("id").GetString()!; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // GET /vaults/{id}/audit — basic structure + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Audit endpoint returns 200 with a JSON array. + /// Mutations killed: returning wrong status, returning non-array. + /// + [Fact] + public async Task GetAudit_AuthedUser_Returns200WithArray() + { + using var client = AuthClient("audit-struct-user", "ast@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.GetAsync($"/vaults/{vaultId}/audit"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.Equal(JsonValueKind.Array, doc.RootElement.ValueKind); + } + + /// + /// After creating a vault, the audit log must contain at least one entry. + /// Mutations killed: not recording audit events on vault creation. + /// + [Fact] + public async Task GetAudit_AfterVaultCreate_ContainsAtLeastOneEntry() + { + using var client = AuthClient("audit-create-user", "acr@example.com"); + var vaultId = await CreateVaultAsync(client, "Audit Create Test Vault"); + + var response = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True(doc.RootElement.GetArrayLength() > 0, + "Audit log must contain at least one entry after vault creation"); + } + + /// + /// Each audit entry must contain a non-empty eventType string and at least + /// one object reference field. + /// PRD §9.7: "Audit log for shared profile create/update/use events." + /// Mutations killed: omitting eventType, omitting objectId. + /// + [Fact] + public async Task GetAudit_WhenEntriesExist_EachEntryHasEventTypeAndObjectId() + { + using var client = AuthClient("audit-schema-user", "asc@example.com"); + var vaultId = await CreateVaultAsync(client, "Schema Check Vault"); + + var response = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + foreach (var entry in doc.RootElement.EnumerateArray()) + { + Assert.True( + entry.TryGetProperty("eventType", out var eventTypeProp) && + eventTypeProp.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(eventTypeProp.GetString()), + "Each audit entry must have a non-empty 'eventType' string (PRD §9.7)"); + + bool hasObjectRef = + entry.TryGetProperty("objectId", out _) || + entry.TryGetProperty("vaultId", out _) || + entry.TryGetProperty("profileId", out _); + + Assert.True(hasObjectRef, + "Each audit entry must reference an object ID (PRD §13.10)"); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Zero-knowledge: no plaintext session data in audit entries + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Audit entries must NEVER expose plaintext session content fields. + /// PRD §13.10: "Audit logs track events and object IDs, not plaintext session contents." + /// Mutations killed: including cookies/localStorage/sessionStorage in audit response. + /// + [Fact] + public async Task GetAudit_ResponseNeverContainsPlaintextSessionFields() + { + using var client = AuthClient("audit-zk-user", "azk@example.com"); + var vaultId = await CreateVaultAsync(client, "ZK Audit Vault"); + + var response = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + AssertNoPlaintextSessionFields(doc.RootElement, "audit response root"); + } + + /// + /// Belt-and-suspenders: prohibited field name substrings must not appear in + /// the raw response body string. + /// Mutations killed: any accidental echo of session content as a raw string. + /// + [Fact] + public async Task GetAudit_ResponseNeverContainsSessionContentInStringValues() + { + using var client = AuthClient("audit-raw-user", "araw@example.com"); + var vaultId = await CreateVaultAsync(client, "Raw Check Vault"); + + var response = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + + var prohibitedSubstrings = new[] + { + "\"cookieValue\"", + "\"storageValue\"", + "\"sessionStorage\"", + "\"localStorage\"", + "\"cookies\"", + "\"sessionContent\"", + "\"cookieContent\"", + }; + + foreach (var prohibited in prohibitedSubstrings) + Assert.DoesNotContain(prohibited, body, StringComparison.OrdinalIgnoreCase); + } + + /// + /// After an invite, the audit log must record the invite event. + /// Mutations killed: only recording vault_created, not member_invited. + /// + [Fact] + public async Task GetAudit_AfterInvite_ContainsInviteEvent() + { + using var client = AuthClient("audit-invite-user", "ainv@example.com"); + var vaultId = await CreateVaultAsync(client, "Invite Audit Vault"); + + var inviteResp = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "newmember@example.com", role = "member" }); + Assert.True( + inviteResp.StatusCode == HttpStatusCode.OK || + inviteResp.StatusCode == HttpStatusCode.NoContent, + "Invite must succeed before checking audit log"); + + var auditResp = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, auditResp.StatusCode); + + var body = await auditResp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True(doc.RootElement.GetArrayLength() >= 2, + "Audit log must have at least 2 entries after create+invite"); + + var eventTypes = doc.RootElement.EnumerateArray() + .Select(e => e.TryGetProperty("eventType", out var p) ? p.GetString() : null) + .ToList(); + + Assert.Contains(eventTypes, et => + et != null && et.Contains("invite", StringComparison.OrdinalIgnoreCase)); + } + + /// + /// After key rotation, the audit log must record the rotation event. + /// Mutations killed: not recording key_rotated in the audit log. + /// + [Fact] + public async Task GetAudit_AfterKeyRotation_ContainsRotationEvent() + { + using var client = AuthClient("audit-rotate-user", "arot@example.com"); + var vaultId = await CreateVaultAsync(client, "Rotation Audit Vault"); + + await client.PostAsJsonAsync($"/vaults/{vaultId}/rotate-key", new { }); + + var auditResp = await client.GetAsync($"/vaults/{vaultId}/audit"); + Assert.Equal(HttpStatusCode.OK, auditResp.StatusCode); + + var body = await auditResp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + var eventTypes = doc.RootElement.EnumerateArray() + .Select(e => e.TryGetProperty("eventType", out var p) ? p.GetString() : null) + .ToList(); + + Assert.Contains(eventTypes, et => + et != null && et.Contains("rotat", StringComparison.OrdinalIgnoreCase)); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Auth enforcement + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Without a token, the audit endpoint returns 401. + /// Mutations killed: not protecting the audit endpoint. + /// + [Fact] + public async Task GetAudit_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.GetAsync("/vaults/test-vault-id/audit"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Helpers + // ═══════════════════════════════════════════════════════════════════════════ + + private static readonly HashSet PlaintextSessionFieldNames = + new(StringComparer.OrdinalIgnoreCase) + { + "cookies", + "localStorage", + "sessionStorage", + "cookieValue", + "storageValue", + "cookieContent", + "sessionContent", + }; + + private static void AssertNoPlaintextSessionFields(JsonElement element, string context) + { + if (element.ValueKind == JsonValueKind.Object) + { + foreach (var property in element.EnumerateObject()) + { + Assert.False( + PlaintextSessionFieldNames.Contains(property.Name), + $"PRD §13.10 violation: audit log must not contain plaintext session content. " + + $"Found prohibited field '{property.Name}' at {context}"); + + AssertNoPlaintextSessionFields(property.Value, $"{context}.{property.Name}"); + } + } + else if (element.ValueKind == JsonValueKind.Array) + { + int i = 0; + foreach (var item in element.EnumerateArray()) + AssertNoPlaintextSessionFields(item, $"{context}[{i++}]"); + } + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/AuthTests.cs b/backend/Sessionist.Api.Tests/ContractTests/AuthTests.cs new file mode 100644 index 0000000..895d05e --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/AuthTests.cs @@ -0,0 +1,315 @@ +// PRD §9.7 / §13.9 – Authentication contract tests. +// Google OAuth, email magic-link, JWT refresh. +// +// Every test is designed to kill at least one mutation class: +// - Skipping idToken/email validation → caught by missing-field 400 tests +// - Returning tokens on any input → caught by happy-path schema tests +// - Accepting empty refresh tokens → caught by empty-string 401 test +// - Returning wrong status codes → caught by explicit status assertions +// - Returning 200 on invalid email → caught by invalid-email 400 test + +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Contract tests for the three auth endpoints. +/// PRD §13.9: Google OAuth + email magic-link; short-lived JWT access + refresh. +/// +public sealed class AuthTests(ApiFactory factory) : IClassFixture +{ + private readonly HttpClient _client = factory.CreateClient(); + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /auth/google + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Happy path: valid Google ID-token → 200 with accessToken + refreshToken. + /// Mutations killed: skipping token issuance, wrong status code, missing fields. + /// + [Fact] + public async Task AuthGoogle_ValidIdToken_Returns200WithBothTokens() + { + var response = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "google-id-token-stub" }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True( + doc.RootElement.TryGetProperty("accessToken", out var access) && + access.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(access.GetString()), + "Response must contain a non-empty 'accessToken' string"); + + Assert.True( + doc.RootElement.TryGetProperty("refreshToken", out var refresh) && + refresh.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(refresh.GetString()), + "Response must contain a non-empty 'refreshToken' string"); + } + + /// + /// The returned accessToken must be a syntactically valid JWT (three dot-separated segments). + /// Mutations killed: returning a plain string or fake token in place of a real JWT. + /// + [Fact] + public async Task AuthGoogle_ValidIdToken_AccessTokenIsJwtShaped() + { + var response = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "google-id-token-stub" }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + var accessToken = doc.RootElement.GetProperty("accessToken").GetString()!; + + // A JWT has exactly three base64url segments separated by dots. + var parts = accessToken.Split('.'); + Assert.Equal(3, parts.Length); + Assert.True(parts.All(p => p.Length > 0), "All JWT segments must be non-empty"); + } + + /// + /// Missing idToken field → 400 Bad Request. + /// Mutations killed: accepting any body without validation. + /// + [Fact] + public async Task AuthGoogle_MissingIdToken_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/google", new { }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Empty string idToken → 400 Bad Request. + /// Mutations killed: accepting empty idToken as valid. + /// + [Fact] + public async Task AuthGoogle_EmptyIdToken_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Whitespace-only idToken → 400 Bad Request. + /// Mutations killed: using string.IsNullOrEmpty instead of IsNullOrWhiteSpace. + /// + [Fact] + public async Task AuthGoogle_WhitespaceIdToken_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/google", + new { idToken = " " }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /auth/magic-link + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Happy path: valid email → 200 (link queued/sent). + /// Mutations killed: wrong status code, not accepting valid email. + /// + [Fact] + public async Task AuthMagicLink_ValidEmail_Returns200() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", + new { email = "qa@example.com" }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Syntactically invalid email (no @) → 400. + /// Mutations killed: skipping email format validation. + /// + [Fact] + public async Task AuthMagicLink_InvalidEmail_NoAt_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", + new { email = "not-an-email" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Email with @ at position 0 (no local part) → 400. + /// Mutations killed: only checking Contains('@') without position validation. + /// + [Fact] + public async Task AuthMagicLink_InvalidEmail_AtAtStart_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", + new { email = "@example.com" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Missing email field → 400. + /// Mutations killed: treating missing field as empty/valid. + /// + [Fact] + public async Task AuthMagicLink_MissingEmail_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", new { }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Empty email string → 400. + /// Mutations killed: accepting empty string as valid email. + /// + [Fact] + public async Task AuthMagicLink_EmptyEmail_Returns400() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", + new { email = "" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /auth/refresh + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Happy path: obtain a real refresh token via /auth/google, then exchange it. + /// Mutations killed: not issuing a new accessToken, wrong status code. + /// + [Fact] + public async Task AuthRefresh_ValidRefreshToken_Returns200WithNewAccessToken() + { + // Step 1: get a real refresh token via /auth/google. + var googleResp = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "any-valid-google-token" }); + Assert.Equal(HttpStatusCode.OK, googleResp.StatusCode); + + var googleBody = await googleResp.Content.ReadAsStringAsync(); + using var googleDoc = JsonDocument.Parse(googleBody); + var refreshToken = googleDoc.RootElement.GetProperty("refreshToken").GetString()!; + Assert.False(string.IsNullOrWhiteSpace(refreshToken)); + + // Step 2: exchange the refresh token for a new access token. + var response = await _client.PostAsJsonAsync("/auth/refresh", + new { refreshToken }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True( + doc.RootElement.TryGetProperty("accessToken", out var access) && + access.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(access.GetString()), + "Refresh response must contain a non-empty 'accessToken'"); + } + + /// + /// The new accessToken from a refresh must also be a valid JWT. + /// Mutations killed: returning a non-JWT string as the new access token. + /// + [Fact] + public async Task AuthRefresh_NewAccessToken_IsJwtShaped() + { + var googleResp = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "any-valid-google-token" }); + var googleBody = await googleResp.Content.ReadAsStringAsync(); + using var googleDoc = JsonDocument.Parse(googleBody); + var refreshToken = googleDoc.RootElement.GetProperty("refreshToken").GetString()!; + + var response = await _client.PostAsJsonAsync("/auth/refresh", + new { refreshToken }); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + var accessToken = doc.RootElement.GetProperty("accessToken").GetString()!; + + var parts = accessToken.Split('.'); + Assert.Equal(3, parts.Length); + } + + /// + /// Empty refresh token string → 401 Unauthorized. + /// Mutations killed: accepting empty refresh token. + /// + [Fact] + public async Task AuthRefresh_EmptyRefreshToken_Returns401() + { + var response = await _client.PostAsJsonAsync("/auth/refresh", + new { refreshToken = "" }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// A made-up (never-issued) refresh token → 401. + /// Mutations killed: accepting any non-empty string as a valid refresh token. + /// + [Fact] + public async Task AuthRefresh_FakeRefreshToken_Returns401() + { + var response = await _client.PostAsJsonAsync("/auth/refresh", + new { refreshToken = "totally-made-up-token-that-was-never-issued" }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Missing refreshToken field → 401. + /// Mutations killed: not checking for missing field. + /// + [Fact] + public async Task AuthRefresh_MissingRefreshToken_Returns401() + { + var response = await _client.PostAsJsonAsync("/auth/refresh", new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Auth endpoint security: must NOT require a JWT (they are public) + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// /auth/google must be callable without an Authorization header. + /// Mutations killed: accidentally protecting auth endpoints with [Authorize]. + /// + [Fact] + public async Task AuthGoogle_IsPublic_NoTokenRequired() + { + // No Authorization header — must not return 401. + var response = await _client.PostAsJsonAsync("/auth/google", + new { idToken = "google-id-token-stub" }); + + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// /auth/magic-link must be callable without an Authorization header. + /// + [Fact] + public async Task AuthMagicLink_IsPublic_NoTokenRequired() + { + var response = await _client.PostAsJsonAsync("/auth/magic-link", + new { email = "test@example.com" }); + + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/BillingTests.cs b/backend/Sessionist.Api.Tests/ContractTests/BillingTests.cs new file mode 100644 index 0000000..e11d38c --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/BillingTests.cs @@ -0,0 +1,345 @@ +// PRD §9.7 / §13.9 – Billing contract tests (Stripe seat-based). +// +// POST /billing/checkout → JWT required; create a Stripe Checkout session +// POST /billing/webhook → PUBLIC (no JWT); validate Stripe-Signature, process event +// +// Mutations killed by this class: +// - Not checking Stripe-Signature header → missing-sig 400 tests fail +// - Accepting invalid signatures → bad-sig 400 tests fail +// - Accepting 0/negative seat counts → invalid-seats 400 tests fail +// - Not returning checkoutUrl/sessionId → happy-path schema tests fail +// - Protecting webhook with JWT → IsNotProtectedByJwt tests fail +// - Not protecting checkout with JWT → checkout-no-token 401 tests fail +// - Not binding signature to payload body → different-body 400 test fails + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Billing contract tests (PRD §13.9 / §11.1). +/// Stripe seat-based billing: checkout session creation + webhook handling. +/// +public sealed class BillingTests(ApiFactory factory) : IClassFixture +{ + // The Stripe webhook secret must match what Program.cs uses. + // This is the test/in-memory value only — not a real Stripe secret. + private const string TestWebhookSecret = "whsec_test_secret"; + + private HttpClient AuthClient(string userId = "billing-user-1", string email = "billing@example.com") + { + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BearerToken(userId, email)); + return client; + } + + // Build a valid Stripe-Signature header value using HMAC-SHA256. + private static string BuildStripeSignature(string payload, string secret, string? timestamp = null) + { + timestamp ??= DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(); + var signed = Encoding.UTF8.GetBytes($"{timestamp}.{payload}"); + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); + var hexHash = Convert.ToHexString(hmac.ComputeHash(signed)).ToLowerInvariant(); + return $"t={timestamp},v1={hexHash}"; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /billing/checkout + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Happy path: authed user with valid seat count → 200 with checkoutUrl or sessionId. + /// PRD §11.1: Team = $7/seat/month billed annually. + /// Mutations killed: not returning checkout fields, wrong status code. + /// + [Fact] + public async Task PostBillingCheckout_ValidRequest_Returns200WithCheckoutUrl() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/billing/checkout", new { seats = 5 }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + bool hasUrl = doc.RootElement.TryGetProperty("checkoutUrl", out var urlProp) + && urlProp.ValueKind == JsonValueKind.String + && !string.IsNullOrWhiteSpace(urlProp.GetString()); + + bool hasSessionId = doc.RootElement.TryGetProperty("sessionId", out var sidProp) + && sidProp.ValueKind == JsonValueKind.String + && !string.IsNullOrWhiteSpace(sidProp.GetString()); + + Assert.True(hasUrl || hasSessionId, + "Response must contain 'checkoutUrl' or 'sessionId'"); + } + + /// + /// Minimum valid seat count (1 seat) must be accepted. + /// Mutations killed: off-by-one (rejecting 1 seat). + /// + [Fact] + public async Task PostBillingCheckout_OneSeat_Returns200() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/billing/checkout", new { seats = 1 }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Two different checkout requests must produce distinct session IDs. + /// Mutations killed: always returning the same session ID. + /// + [Fact] + public async Task PostBillingCheckout_TwoRequests_GetDistinctSessionIds() + { + using var client = AuthClient("checkout-distinct-user", "cdn@example.com"); + + var resp1 = await client.PostAsJsonAsync("/billing/checkout", new { seats = 3 }); + var resp2 = await client.PostAsJsonAsync("/billing/checkout", new { seats = 5 }); + + Assert.Equal(HttpStatusCode.OK, resp1.StatusCode); + Assert.Equal(HttpStatusCode.OK, resp2.StatusCode); + + using var doc1 = JsonDocument.Parse(await resp1.Content.ReadAsStringAsync()); + using var doc2 = JsonDocument.Parse(await resp2.Content.ReadAsStringAsync()); + + string? GetAnyId(JsonDocument doc) + { + if (doc.RootElement.TryGetProperty("sessionId", out var sid)) return sid.GetString(); + if (doc.RootElement.TryGetProperty("checkoutUrl", out var url)) return url.GetString(); + return null; + } + + var id1 = GetAnyId(doc1); + var id2 = GetAnyId(doc2); + Assert.NotEqual(id1, id2); + } + + /// + /// Zero or negative seat count → 400 Bad Request. + /// Mutations killed: not validating seat count. + /// + [Theory] + [InlineData(0)] + [InlineData(-1)] + public async Task PostBillingCheckout_InvalidSeatCount_Returns400(int seats) + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/billing/checkout", new { seats }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Missing seats field → 400. + /// Mutations killed: not checking for required seats field. + /// + [Fact] + public async Task PostBillingCheckout_MissingSeats_Returns400() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/billing/checkout", new { }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// /billing/checkout without a token → 401. + /// Mutations killed: not protecting checkout with JWT. + /// + [Fact] + public async Task PostBillingCheckout_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + + var response = await client.PostAsJsonAsync("/billing/checkout", new { seats = 5 }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /billing/webhook + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Happy path: valid Stripe-Signature + event payload → 200. + /// Mutations killed: not accepting valid webhooks, always returning error. + /// + [Fact] + public async Task PostBillingWebhook_ValidSignature_Returns200() + { + var payload = "{\"type\":\"checkout.session.completed\",\"data\":{\"object\":{}}}"; + var sig = BuildStripeSignature(payload, TestWebhookSecret); + + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", sig); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Valid webhook with client_reference_id processes checkout.session.completed. + /// Response must include received:true. + /// Mutations killed: not handling checkout.session.completed type. + /// + [Fact] + public async Task PostBillingWebhook_CheckoutCompleted_Returns200WithReceived() + { + var payload = """{"type":"checkout.session.completed","data":{"object":{"client_reference_id":"user-123","customer":"cus_test"}}}"""; + var sig = BuildStripeSignature(payload, TestWebhookSecret); + + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", sig); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True( + doc.RootElement.TryGetProperty("received", out _), + "Webhook 200 response must contain 'received' field"); + } + + /// + /// Missing Stripe-Signature header → 400. + /// Mutations killed: not checking for Stripe-Signature header. + /// + [Fact] + public async Task PostBillingWebhook_MissingStripeSignature_Returns400() + { + using var client = factory.CreateClient(); + + var payload = new StringContent( + "{\"type\":\"checkout.session.completed\"}", + Encoding.UTF8, "application/json"); + + var response = await client.PostAsync("/billing/webhook", payload); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Syntactically present but invalid Stripe-Signature → 400. + /// Mutations killed: accepting any non-empty signature string. + /// + [Fact] + public async Task PostBillingWebhook_InvalidStripeSignature_Returns400() + { + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent( + "{\"type\":\"checkout.session.completed\",\"data\":{\"object\":{}}}", + Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", "t=fake,v1=invalidsignature"); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// A valid-format signature signed with the WRONG secret → 400. + /// Mutations killed: not actually validating the HMAC (just checking header format). + /// + [Fact] + public async Task PostBillingWebhook_WrongSecretSignature_Returns400() + { + var payload = "{\"type\":\"checkout.session.completed\"}"; + var sig = BuildStripeSignature(payload, "wrong-secret-key"); + + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", sig); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// A valid signature for a DIFFERENT payload body → 400. + /// Mutations killed: not binding the HMAC signature to the actual request body. + /// + [Fact] + public async Task PostBillingWebhook_SignatureForDifferentBody_Returns400() + { + var signedPayload = "{\"type\":\"original.event\"}"; + var actualPayload = "{\"type\":\"checkout.session.completed\"}"; + var sig = BuildStripeSignature(signedPayload, TestWebhookSecret); + + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent(actualPayload, Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", sig); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// /billing/webhook must NOT require a JWT (Stripe calls it without one). + /// Mutations killed: accidentally adding RequireAuthorization() to the webhook route. + /// + [Fact] + public async Task PostBillingWebhook_IsNotProtectedByJwt() + { + // No Authorization header. Should get 400 (invalid sig), NOT 401. + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent( + "{\"type\":\"checkout.session.completed\"}", + Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", "t=fake,v1=invalidsignature"); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Webhook with valid JWT AND valid Stripe-Signature must still return 200. + /// Mutations killed: rejecting requests that happen to carry a Bearer token. + /// + [Fact] + public async Task PostBillingWebhook_WithTokenAndValidSig_Returns200() + { + var payload = "{\"type\":\"customer.subscription.updated\",\"data\":{\"object\":{}}}"; + var sig = BuildStripeSignature(payload, TestWebhookSecret); + + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); + request.Headers.Add("Stripe-Signature", sig); + request.Headers.TryAddWithoutValidation("Authorization", JwtHelper.BearerToken()); + + using var client = factory.CreateClient(); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/HealthTests.cs b/backend/Sessionist.Api.Tests/ContractTests/HealthTests.cs new file mode 100644 index 0000000..0059ac7 --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/HealthTests.cs @@ -0,0 +1,84 @@ +// PRD §9.7 / §13.9 – /health contract tests. +// /health must always return 200 {ok:true} and must be publicly accessible. + +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// /health endpoint contract tests. +/// This test passes both with the stub and with the real implementation. +/// Acts as a canary confirming WebApplicationFactory is set up correctly. +/// +public sealed class HealthTests(ApiFactory factory) : IClassFixture +{ + private readonly HttpClient _client = factory.CreateClient(); + + /// + /// /health returns 200 with {ok:true} — the basic health contract. + /// Mutations killed: returning wrong status, returning ok:false, omitting ok field. + /// + [Fact] + public async Task Health_Returns200_WithOkTrue() + { + var response = await _client.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True( + doc.RootElement.TryGetProperty("ok", out var okProp), + "Response JSON must contain an 'ok' property"); + Assert.Equal(JsonValueKind.True, okProp.ValueKind); + } + + /// + /// /health must be accessible without an Authorization header. + /// Mutations killed: accidentally protecting /health with JWT middleware. + /// + [Fact] + public async Task Health_IsPublic_NoTokenRequired() + { + // No Authorization header — must still return 200. + var response = await _client.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// /health with a valid Bearer token still returns 200. + /// Mutations killed: rejecting authenticated requests on public endpoints. + /// + [Fact] + public async Task Health_WithValidToken_Returns200() + { + using var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BearerToken()); + + var response = await client.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// /health response body must be valid JSON. + /// Mutations killed: returning a non-JSON response body. + /// + [Fact] + public async Task Health_ResponseBodyIsValidJson() + { + var response = await _client.GetAsync("/health"); + var body = await response.Content.ReadAsStringAsync(); + + // Must not throw. + using var doc = JsonDocument.Parse(body); + Assert.NotNull(doc); + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/ProtectedEndpointAuthTests.cs b/backend/Sessionist.Api.Tests/ContractTests/ProtectedEndpointAuthTests.cs new file mode 100644 index 0000000..76541d6 --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/ProtectedEndpointAuthTests.cs @@ -0,0 +1,196 @@ +// PRD §9.7 / §13.9 – Auth-required contract tests. +// Every protected endpoint must return 401 when no bearer token is supplied +// and 401 when a token with a bad signature is supplied. +// +// Mutations killed by this class: +// - Removing JWT middleware entirely → all 401-without-token tests fail +// - Skipping signature validation → bad-signature 401 tests fail +// - Accidentally protecting /billing/webhook → IsNotProtectedByJwt test fails +// - Accidentally protecting /health → health public test fails + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Asserts that all protected endpoints return 401 when no bearer token is +/// supplied, and also when a token with a wrong signature is supplied. +/// +public sealed class ProtectedEndpointAuthTests(ApiFactory factory) : IClassFixture +{ + private readonly HttpClient _client = factory.CreateClient(); + + // ─── Endpoint lists ─────────────────────────────────────────────────────── + + public static IEnumerable ProtectedGetEndpoints => + [ + ["/sync/profiles"], + ["/vaults"], + ["/vaults/test-vault-id/audit"], + ]; + + public static IEnumerable ProtectedPostEndpoints => + [ + ["/vaults"], + ["/vaults/test-vault-id/invite"], + ["/vaults/test-vault-id/rotate-key"], + ["/billing/checkout"], + ]; + + public static IEnumerable ProtectedPutEndpoints => + [ + ["/sync/profiles"], + ]; + + // ─── No-token → 401 ────────────────────────────────────────────────────── + + /// + /// GET endpoints without a token → 401. + /// Mutations killed: removing RequireAuthorization() from GET routes. + /// + [Theory] + [MemberData(nameof(ProtectedGetEndpoints))] + public async Task Get_WithoutToken_Returns401(string path) + { + var response = await _client.GetAsync(path); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// POST endpoints without a token → 401. + /// Mutations killed: removing RequireAuthorization() from POST routes. + /// + [Theory] + [MemberData(nameof(ProtectedPostEndpoints))] + public async Task Post_WithoutToken_Returns401(string path) + { + var response = await _client.PostAsJsonAsync(path, new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// PUT endpoints without a token → 401. + /// Mutations killed: removing RequireAuthorization() from PUT routes. + /// + [Theory] + [MemberData(nameof(ProtectedPutEndpoints))] + public async Task Put_WithoutToken_Returns401(string path) + { + var response = await _client.PutAsJsonAsync(path, new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ─── Badly signed token → 401 ──────────────────────────────────────────── + + /// + /// GET endpoints with a token signed by the wrong key → 401. + /// Mutations killed: skipping JWT signature validation (accepting any token). + /// + [Theory] + [MemberData(nameof(ProtectedGetEndpoints))] + public async Task Get_WithBadlySignedToken_Returns401(string path) + { + using var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BadlySignedBearerToken()); + + var response = await client.GetAsync(path); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// POST endpoints with a token signed by the wrong key → 401. + /// + [Theory] + [MemberData(nameof(ProtectedPostEndpoints))] + public async Task Post_WithBadlySignedToken_Returns401(string path) + { + using var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BadlySignedBearerToken()); + + var response = await client.PostAsJsonAsync(path, new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// PUT endpoints with a token signed by the wrong key → 401. + /// + [Theory] + [MemberData(nameof(ProtectedPutEndpoints))] + public async Task Put_WithBadlySignedToken_Returns401(string path) + { + using var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BadlySignedBearerToken()); + + var response = await client.PutAsJsonAsync(path, new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ─── Malformed Authorization header ────────────────────────────────────── + + /// + /// A completely garbage Authorization header value → must not be 200. + /// Mutations killed: not validating Authorization header format. + /// + [Fact] + public async Task SyncProfiles_Get_GarbageAuthHeader_NotOk() + { + using var client = factory.CreateClient(); + client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "garbage-not-a-jwt"); + + var response = await client.GetAsync("/sync/profiles"); + + Assert.NotEqual(HttpStatusCode.OK, response.StatusCode); + } + + // ─── /billing/webhook is NOT behind JWT auth ────────────────────────────── + + /// + /// /billing/webhook must be publicly reachable (no JWT). + /// Stripe calls it without a Bearer token; if it returned 401 that would + /// break webhook processing. + /// Mutations killed: accidentally adding RequireAuthorization() to the webhook route. + /// + [Fact] + public async Task BillingWebhook_WithoutToken_IsNotUnauthorized() + { + // No auth header; Stripe-Signature is intentionally invalid → get 400 (sig fail). + // But must NOT get 401. + var request = new HttpRequestMessage(HttpMethod.Post, "/billing/webhook"); + request.Content = new StringContent( + "{\"type\":\"checkout.session.completed\"}", + System.Text.Encoding.UTF8, + "application/json"); + request.Headers.Add("Stripe-Signature", "t=fake,v1=invalidsignature"); + + var response = await _client.SendAsync(request); + + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ─── /health is public ──────────────────────────────────────────────────── + + /// + /// /health must be reachable without any token. + /// Mutations killed: accidentally protecting /health. + /// + [Fact] + public async Task Health_WithoutToken_Returns200() + { + var response = await _client.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/SyncProfilesTests.cs b/backend/Sessionist.Api.Tests/ContractTests/SyncProfilesTests.cs new file mode 100644 index 0000000..342d765 --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/SyncProfilesTests.cs @@ -0,0 +1,420 @@ +// PRD §9.7 / §13.10 – Zero-knowledge sync contract tests. +// +// The server MUST: +// PUT /sync/profiles → accept any opaque blob (no plaintext field requirements) +// GET /sync/profiles → return the stored ciphertext blob for the authed user +// +// The server MUST NOT: +// - Require or validate any plaintext session fields in PUT +// - Return cookie/localStorage/sessionStorage field names in GET response +// - Return the same data to two different users (per-user isolation) +// +// Mutations killed by this class: +// - Storing plaintext instead of opaque blob → zero-knowledge tests fail +// - Returning all users' data → isolation test fails +// - Adding plaintext field requirements → no-plaintext-field test fails +// - Leaking session content field names in response → GET schema tests fail +// - Accepting unauthenticated requests → 401 tests fail + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Zero-knowledge profile sync contracts (PRD §13.10). +/// +public sealed class SyncProfilesTests(ApiFactory factory) : IClassFixture +{ + private HttpClient AuthClient(string userId = "test-user-1", string email = "qa@example.com") + { + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BearerToken(userId, email)); + return client; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // PUT /sync/profiles — accept opaque blobs + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// PUT with an opaque ciphertext body must be accepted (200 or 204). + /// The server must not require or validate plaintext session fields. + /// Mutations killed: rejecting opaque blobs, returning wrong status. + /// + [Fact] + public async Task Put_OpaqueCiphertextBlob_IsAccepted() + { + using var client = AuthClient(); + + var opaqueBody = new + { + profileId = "test-profile-id-1", + ciphertext = Convert.ToBase64String(Encoding.UTF8.GetBytes("AES-GCM-encrypted-blob")), + iv = Convert.ToBase64String(new byte[12]), + version = 1 + }; + + var response = await client.PutAsJsonAsync("/sync/profiles", opaqueBody); + + Assert.True( + response.StatusCode == HttpStatusCode.OK || + response.StatusCode == HttpStatusCode.NoContent, + $"Expected 200 or 204 but got {(int)response.StatusCode}"); + } + + /// + /// PUT with only ciphertext and iv fields (no plaintext fields at all) must succeed. + /// Mutations killed: adding plaintext field requirements to the endpoint. + /// + [Fact] + public async Task Put_WithNoPlaintextSessionFields_IsNotRejected() + { + using var client = AuthClient(); + + // Body has ONLY opaque encrypted fields — no cookies, localStorage, etc. + var minimalEncryptedBody = new + { + ciphertext = "c2VjcmV0LWVuY3J5cHRlZC1ibG9i", + iv = "AAAAAAAAAAAAAAAA", + }; + + var response = await client.PutAsJsonAsync("/sync/profiles", minimalEncryptedBody); + + // Must not be 501 (not implemented) or 422 (plaintext field required). + Assert.NotEqual(HttpStatusCode.NotImplemented, response.StatusCode); + Assert.False( + response.StatusCode == HttpStatusCode.UnprocessableEntity && + await BodyContainsPlaintextFieldError(response), + "Server must not reject for missing plaintext session fields (zero-knowledge)"); + } + + /// + /// PUT must NOT return 422 complaining about absent plaintext fields. + /// + [Fact] + public async Task Put_NeverRequiresPlaintextFieldsInBody() + { + using var client = AuthClient(); + + var opaqueOnly = new { blob = "ZW5jcnlwdGVkLWRhdGEtaGVyZQ==" }; + var response = await client.PutAsJsonAsync("/sync/profiles", opaqueOnly); + + Assert.NotEqual(HttpStatusCode.NotImplemented, response.StatusCode); + Assert.NotEqual(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // GET /sync/profiles — return stored ciphertext + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// GET returns 200 and a valid JSON document. + /// Mutations killed: returning wrong status, returning non-JSON. + /// + [Fact] + public async Task Get_ReturnsStoredCiphertextForAuthedUser() + { + using var client = AuthClient("sync-get-user", "sync@example.com"); + + var response = await client.GetAsync("/sync/profiles"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + // Must not contain plaintext session fields. + AssertNoPlaintextSessionFields(doc.RootElement, "/sync/profiles GET response"); + } + + /// + /// After a PUT, GET must return the stored blob (round-trip test). + /// Mutations killed: storing nothing, returning empty after PUT. + /// + [Fact] + public async Task PutThenGet_RoundTrip_ReturnsStoredBlob() + { + using var client = AuthClient("roundtrip-user", "rt@example.com"); + + var blob = new + { + ciphertext = Convert.ToBase64String(Encoding.UTF8.GetBytes("my-encrypted-data")), + iv = "dGVzdGl2MTIzNDU2", + }; + + var putResp = await client.PutAsJsonAsync("/sync/profiles", blob); + Assert.True( + putResp.StatusCode == HttpStatusCode.OK || + putResp.StatusCode == HttpStatusCode.NoContent, + "PUT must succeed before GET round-trip"); + + var getResp = await client.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, getResp.StatusCode); + + var body = await getResp.Content.ReadAsStringAsync(); + Assert.False(string.IsNullOrWhiteSpace(body), "GET body must not be empty after PUT"); + + using var doc = JsonDocument.Parse(body); + if (doc.RootElement.ValueKind == JsonValueKind.Array) + { + Assert.True(doc.RootElement.GetArrayLength() > 0, + "After PUT, GET must return at least one entry"); + } + } + + /// + /// GET response must NEVER contain plaintext session content field names. + /// PRD §13.10: server never stores or returns plaintext session contents. + /// Mutations killed: including cookies/localStorage/sessionStorage in response. + /// + [Fact] + public async Task Get_ResponseNeverContainsPlaintextSessionFieldNames() + { + using var client = AuthClient("zk-check-user", "zk@example.com"); + + var response = await client.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + AssertNoPlaintextSessionFields(doc.RootElement, "GET /sync/profiles response"); + } + + /// + /// Raw response body must not contain any of the prohibited field name strings. + /// Belt-and-suspenders check against accidental payload echo. + /// + [Fact] + public async Task Get_RawBodyNeverContainsProhibitedSubstrings() + { + using var client = AuthClient("raw-check-user", "raw@example.com"); + + var response = await client.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + + var prohibited = new[] + { + "\"cookies\"", "\"localStorage\"", "\"sessionStorage\"", + "\"cookieValue\"", "\"storageValue\"", + }; + + foreach (var p in prohibited) + Assert.DoesNotContain(p, body, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Two different users must see only their own blobs (per-user isolation). + /// Mutations killed: returning all users' data instead of filtering by userId. + /// + [Fact] + public async Task Get_UserIsolation_UserCannotSeeOtherUsersBlobs() + { + using var clientA = AuthClient("isolation-user-a", "a@example.com"); + var blobA = new { ciphertext = "dXNlci1hLWRhdGE=", iv = "aXZhYWFh" }; + await clientA.PutAsJsonAsync("/sync/profiles", blobA); + + using var clientB = AuthClient("isolation-user-b", "b@example.com"); + var blobB = new { ciphertext = "dXNlci1iLWRhdGE=", iv = "aXZiYmJi" }; + await clientB.PutAsJsonAsync("/sync/profiles", blobB); + + // User A's GET must not return User B's ciphertext. + var getResp = await clientA.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, getResp.StatusCode); + + var body = await getResp.Content.ReadAsStringAsync(); + Assert.DoesNotContain("dXNlci1iLWRhdGE=", body, StringComparison.Ordinal); + } + + /// + /// After a PUT, GET must not return a response containing plaintext session field names. + /// This test ensures the check is NOT vacuous (data was stored before checking). + /// Mutations killed: server wrapping stored blob with forbidden field names on response. + /// + [Fact] + public async Task Get_AfterPut_ResponseNeverContainsPlaintextFieldNames() + { + using var client = AuthClient("put-then-zk-user", "pzk@example.com"); + + // Store a blob first so the GET response is non-empty. + var blob = new + { + ciphertext = Convert.ToBase64String(Encoding.UTF8.GetBytes("opaque-encrypted-data")), + iv = "dGVzdGl2aXY=", + }; + var putResp = await client.PutAsJsonAsync("/sync/profiles", blob); + Assert.True( + putResp.StatusCode == HttpStatusCode.OK || + putResp.StatusCode == HttpStatusCode.NoContent, + "PUT must succeed before GET check"); + + // Now GET and verify the response has no plaintext field names. + var getResp = await client.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, getResp.StatusCode); + + var body = await getResp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + // Must have non-empty content (proves the check is not vacuous). + if (doc.RootElement.ValueKind == JsonValueKind.Array) + { + Assert.True(doc.RootElement.GetArrayLength() > 0, + "GET after PUT must return non-empty array"); + } + + // Zero-knowledge assertion on the actual stored data. + AssertNoPlaintextSessionFields(doc.RootElement, "GET /sync/profiles after PUT"); + } + + /// + /// After a PUT, the raw GET response body must not contain prohibited substrings. + /// Non-vacuous version of the raw-body check. + /// Mutations killed: server adding forbidden field names when wrapping the stored blob. + /// + [Fact] + public async Task Get_AfterPut_RawBodyNeverContainsProhibitedSubstrings() + { + using var client = AuthClient("put-then-raw-user", "ptr@example.com"); + + await client.PutAsJsonAsync("/sync/profiles", + new { ciphertext = "b3BhcXVlLWJsb2I=", iv = "dGVzdA==" }); + + var getResp = await client.GetAsync("/sync/profiles"); + Assert.Equal(HttpStatusCode.OK, getResp.StatusCode); + + var body = await getResp.Content.ReadAsStringAsync(); + + var prohibited = new[] + { + "\"cookies\"", "\"localStorage\"", "\"sessionStorage\"", + "\"cookieValue\"", "\"storageValue\"", + }; + foreach (var p in prohibited) + Assert.DoesNotContain(p, body, StringComparison.OrdinalIgnoreCase); + } + + /// + /// If PUT returns a body (e.g. 200 with payload), that body must not contain + /// plaintext session field names either. + /// Mutations killed: PUT response leaking cookies/localStorage/sessionStorage. + /// + [Fact] + public async Task Put_ResponseBody_NeverContainsPlaintextFieldNames() + { + using var client = AuthClient("put-resp-zk-user", "przk@example.com"); + + var blob = new + { + ciphertext = Convert.ToBase64String(Encoding.UTF8.GetBytes("opaque-blob")), + iv = "aXYxMjM0NTY3ODk=", + }; + + var response = await client.PutAsJsonAsync("/sync/profiles", blob); + + // Accept 200 or 204; check body only when there is one. + Assert.True( + response.StatusCode == HttpStatusCode.OK || + response.StatusCode == HttpStatusCode.NoContent, + $"Expected 200 or 204 but got {(int)response.StatusCode}"); + + if (response.StatusCode == HttpStatusCode.OK) + { + var body = await response.Content.ReadAsStringAsync(); + if (!string.IsNullOrWhiteSpace(body)) + { + try + { + using var doc = JsonDocument.Parse(body); + AssertNoPlaintextSessionFields(doc.RootElement, + "PUT /sync/profiles response body"); + } + catch (JsonException) { /* non-JSON body is fine — no plaintext to check */ } + } + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Auth enforcement + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// GET /sync/profiles without a token → 401. + /// + [Fact] + public async Task Get_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.GetAsync("/sync/profiles"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// PUT /sync/profiles without a token → 401. + /// + [Fact] + public async Task Put_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.PutAsJsonAsync("/sync/profiles", + new { ciphertext = "dGVzdA==" }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Helpers + // ═══════════════════════════════════════════════════════════════════════════ + + private static readonly HashSet PlaintextSessionFieldNames = + new(StringComparer.OrdinalIgnoreCase) + { + "cookies", + "localStorage", + "sessionStorage", + "cookieValue", + "storageValue", + "value", + "cookieContent", + "sessionContent", + }; + + private static void AssertNoPlaintextSessionFields(JsonElement element, string context) + { + if (element.ValueKind == JsonValueKind.Object) + { + foreach (var property in element.EnumerateObject()) + { + Assert.False( + PlaintextSessionFieldNames.Contains(property.Name), + $"PRD §13.10 violation: '{property.Name}' is a plaintext session-content " + + $"field and must never appear in server responses ({context})"); + + AssertNoPlaintextSessionFields(property.Value, $"{context}.{property.Name}"); + } + } + else if (element.ValueKind == JsonValueKind.Array) + { + int i = 0; + foreach (var item in element.EnumerateArray()) + AssertNoPlaintextSessionFields(item, $"{context}[{i++}]"); + } + } + + private static async Task BodyContainsPlaintextFieldError(HttpResponseMessage response) + { + var body = await response.Content.ReadAsStringAsync(); + return body.Contains("cookies", StringComparison.OrdinalIgnoreCase) + || body.Contains("localStorage", StringComparison.OrdinalIgnoreCase) + || body.Contains("sessionStorage", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/backend/Sessionist.Api.Tests/ContractTests/VaultTests.cs b/backend/Sessionist.Api.Tests/ContractTests/VaultTests.cs new file mode 100644 index 0000000..4990650 --- /dev/null +++ b/backend/Sessionist.Api.Tests/ContractTests/VaultTests.cs @@ -0,0 +1,444 @@ +// PRD §9.7 / §13.9 – Shared vault contract tests. +// +// Vaults: create, list, invite, key rotation. +// All vault operations require a valid JWT. +// Roles: owner, admin, member. +// +// Mutations killed by this class: +// - Returning 200 instead of 201 on create → PostVaults_ValidName_Returns201 fails +// - Not including id/name in create response → PostVaults_ValidName_Returns201 fails +// - Accepting any role string → invalid-role 400 tests fail +// - Skipping email validation in invite → missing-email 400 tests fail +// - Skipping auth → 401 tests fail +// - Not persisting vaults → list-after-create test fails +// - Always returning the same vault ID → distinct-ids test fails + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Sessionist.Api.Tests.Helpers; +using Xunit; + +namespace Sessionist.Api.Tests.ContractTests; + +/// +/// Vault contract tests (PRD §9.7). +/// +public sealed class VaultTests(ApiFactory factory) : IClassFixture +{ + private HttpClient AuthClient(string userId = "vault-owner-1", string email = "owner@example.com") + { + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + AuthenticationHeaderValue.Parse(JwtHelper.BearerToken(userId, email)); + return client; + } + + // Helper: create a vault owned by the given client and return its ID. + private static async Task CreateVaultAsync(HttpClient client, string name = "Test Vault") + { + var resp = await client.PostAsJsonAsync("/vaults", new { name }); + Assert.Equal(HttpStatusCode.Created, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + return doc.RootElement.GetProperty("id").GetString()!; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /vaults — create + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Creating a vault with a valid name returns 201 with id and name. + /// Mutations killed: wrong status code (200 instead of 201), missing id/name fields. + /// + [Fact] + public async Task PostVaults_ValidName_Returns201WithVaultId() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/vaults", new { name = "QA Team Vault" }); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.True( + doc.RootElement.TryGetProperty("id", out var idProp) && + idProp.ValueKind == JsonValueKind.String && + !string.IsNullOrWhiteSpace(idProp.GetString()), + "Response must contain a non-empty 'id' string"); + + Assert.True( + doc.RootElement.TryGetProperty("name", out var nameProp) && + nameProp.GetString() == "QA Team Vault", + "Response must echo back the vault 'name'"); + } + + /// + /// Each created vault gets a unique ID (not a fixed/hardcoded value). + /// Mutations killed: always returning the same vault ID. + /// + [Fact] + public async Task PostVaults_TwoVaults_GetDistinctIds() + { + using var client = AuthClient("distinct-id-user", "di@example.com"); + + var resp1 = await client.PostAsJsonAsync("/vaults", new { name = "Vault One" }); + var resp2 = await client.PostAsJsonAsync("/vaults", new { name = "Vault Two" }); + + Assert.Equal(HttpStatusCode.Created, resp1.StatusCode); + Assert.Equal(HttpStatusCode.Created, resp2.StatusCode); + + using var doc1 = JsonDocument.Parse(await resp1.Content.ReadAsStringAsync()); + using var doc2 = JsonDocument.Parse(await resp2.Content.ReadAsStringAsync()); + + var id1 = doc1.RootElement.GetProperty("id").GetString(); + var id2 = doc2.RootElement.GetProperty("id").GetString(); + + Assert.NotEqual(id1, id2); + } + + /// + /// Creating a vault with a missing name returns 400. + /// Mutations killed: accepting empty/missing name as valid. + /// + [Fact] + public async Task PostVaults_MissingName_Returns400() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/vaults", new { }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Creating a vault with an empty name returns 400. + /// Mutations killed: IsNullOrEmpty vs IsNullOrWhiteSpace. + /// + [Fact] + public async Task PostVaults_EmptyName_Returns400() + { + using var client = AuthClient(); + + var response = await client.PostAsJsonAsync("/vaults", new { name = "" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // GET /vaults — list + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Listing vaults for an authed user returns 200 and a JSON array. + /// Mutations killed: returning wrong status, returning non-array. + /// + [Fact] + public async Task GetVaults_AuthedUser_Returns200WithArray() + { + using var client = AuthClient("list-vaults-user", "list@example.com"); + + var response = await client.GetAsync("/vaults"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var body = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(body); + + Assert.Equal(JsonValueKind.Array, doc.RootElement.ValueKind); + } + + /// + /// After creating a vault, GET /vaults returns at least that vault. + /// Mutations killed: not persisting vaults, returning empty after create. + /// + [Fact] + public async Task GetVaults_AfterCreate_IncludesCreatedVault() + { + using var client = AuthClient("list-after-create-user", "lac@example.com"); + + var vaultId = await CreateVaultAsync(client, "My Test Vault"); + + var listResp = await client.GetAsync("/vaults"); + Assert.Equal(HttpStatusCode.OK, listResp.StatusCode); + + var listBody = await listResp.Content.ReadAsStringAsync(); + using var listDoc = JsonDocument.Parse(listBody); + + Assert.Equal(JsonValueKind.Array, listDoc.RootElement.ValueKind); + var ids = listDoc.RootElement.EnumerateArray() + .Select(v => v.TryGetProperty("id", out var p) ? p.GetString() : null) + .ToList(); + + Assert.Contains(vaultId, ids); + } + + /// + /// User B must not see vaults created by User A (per-user isolation). + /// Mutations killed: returning all vaults without filtering by userId/membership. + /// + [Fact] + public async Task GetVaults_UserIsolation_UserCannotSeeOtherUsersVaults() + { + // Use a timestamp suffix to ensure unique user IDs even across test runs. + var suffix = Guid.NewGuid().ToString("N")[..8]; + var userAId = $"vault-iso-a-{suffix}"; + var userBId = $"vault-iso-b-{suffix}"; + + // User A creates a vault. + using var clientA = AuthClient(userAId, $"{userAId}@example.com"); + var vaultAId = await CreateVaultAsync(clientA, $"Vault-{userAId}-Only"); + + // User B lists their vaults — must not include user A's vault. + using var clientB = AuthClient(userBId, $"{userBId}@example.com"); + var listResp = await clientB.GetAsync("/vaults"); + Assert.Equal(HttpStatusCode.OK, listResp.StatusCode); + + var listBody = await listResp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(listBody); + Assert.Equal(JsonValueKind.Array, doc.RootElement.ValueKind); + + // The returned IDs must not include user A's vault ID. + var returnedIds = doc.RootElement.EnumerateArray() + .Select(v => v.TryGetProperty("id", out var p) ? p.GetString() : null) + .ToList(); + Assert.DoesNotContain(vaultAId, returnedIds); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /vaults/{id}/invite — invite a member + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Inviting a member by email to an existing vault returns 200 or 204. + /// Mutations killed: returning wrong status, not accepting valid invite. + /// + [Fact] + public async Task PostVaultInvite_ValidEmail_Returns200Or204() + { + using var client = AuthClient("invite-owner-1", "iowner1@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "teammate@example.com", role = "member" }); + + Assert.True( + response.StatusCode == HttpStatusCode.OK || + response.StatusCode == HttpStatusCode.NoContent, + $"Expected 200 or 204 but got {(int)response.StatusCode}"); + } + + /// + /// Inviting with a missing email field returns 400. + /// Mutations killed: skipping email presence check. + /// + [Fact] + public async Task PostVaultInvite_MissingEmail_Returns400() + { + using var client = AuthClient("invite-owner-2", "iowner2@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", new { role = "member" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Inviting with an invalid email format returns 400. + /// Mutations killed: not validating email format. + /// + [Fact] + public async Task PostVaultInvite_InvalidEmailFormat_Returns400() + { + using var client = AuthClient("invite-owner-3", "iowner3@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "not-an-email", role = "member" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Inviting with an invalid role string returns 400. + /// Mutations killed: accepting any role string without validation. + /// + [Fact] + public async Task PostVaultInvite_InvalidRole_Returns400() + { + using var client = AuthClient("invite-owner-4", "iowner4@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "teammate@example.com", role = "superadmin" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// A second invalid role to ensure the validation covers all cases. + /// Mutations killed: only checking against one specific invalid role. + /// + [Fact] + public async Task PostVaultInvite_AnotherInvalidRole_Returns400() + { + using var client = AuthClient("invite-owner-4b", "iowner4b@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "teammate@example.com", role = "god" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Accepted roles per PRD §9.7: owner, admin, member. + /// Each must be accepted when called by the vault owner. + /// Mutations killed: accepting only "member", blocking "owner"/"admin". + /// + [Theory] + [InlineData("owner")] + [InlineData("admin")] + [InlineData("member")] + public async Task PostVaultInvite_ValidRole_IsAccepted(string role) + { + using var client = AuthClient($"role-owner-{role}", $"ro-{role}@example.com"); + var vaultId = await CreateVaultAsync(client); + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/invite", + new { email = "teammate@example.com", role }); + + Assert.True( + response.StatusCode == HttpStatusCode.OK || + response.StatusCode == HttpStatusCode.NoContent, + $"Expected 200 or 204 for role='{role}' but got {(int)response.StatusCode}"); + } + + /// + /// Inviting to a non-existent vault returns 404. + /// Mutations killed: accepting any vault ID without checking existence. + /// + [Fact] + public async Task PostVaultInvite_NonExistentVault_Returns404() + { + using var client = AuthClient("invite-404-user", "i404@example.com"); + + var response = await client.PostAsJsonAsync( + "/vaults/vault-id-that-does-not-exist/invite", + new { email = "teammate@example.com", role = "member" }); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POST /vaults/{id}/rotate-key — key rotation + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// Key rotation on an existing vault returns 200 or 204. + /// PRD §9.7: revocation requires key rotation for future shared material. + /// Mutations killed: returning wrong status, not accepting rotation request. + /// + [Fact] + public async Task PostVaultRotateKey_ValidVault_Returns200Or204() + { + using var client = AuthClient("rotate-owner-1", "rowner1@example.com"); + var vaultId = await CreateVaultAsync(client); + + var payload = new + { + newWrappedKeyPerMember = new Dictionary + { + ["rotate-owner-1"] = Convert.ToBase64String(new byte[32]) + } + }; + + var response = await client.PostAsJsonAsync( + $"/vaults/{vaultId}/rotate-key", payload); + + Assert.True( + response.StatusCode == HttpStatusCode.OK || + response.StatusCode == HttpStatusCode.NoContent, + $"Expected 200 or 204 but got {(int)response.StatusCode}"); + } + + /// + /// Key rotation on a non-existent vault returns 404. + /// Mutations killed: accepting any vault ID for rotation. + /// + [Fact] + public async Task PostVaultRotateKey_NonExistentVault_Returns404() + { + using var client = AuthClient("rotate-404-user", "r404@example.com"); + + var response = await client.PostAsJsonAsync( + "/vaults/non-existent-vault-id/rotate-key", + new { newWrappedKeyPerMember = new Dictionary() }); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // Auth enforcement + // ═══════════════════════════════════════════════════════════════════════════ + + /// + /// GET /vaults without a token → 401. + /// + [Fact] + public async Task GetVaults_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.GetAsync("/vaults"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// POST /vaults without a token → 401. + /// + [Fact] + public async Task PostVaults_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.PostAsJsonAsync("/vaults", new { name = "Test" }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// POST /vaults/{id}/invite without a token → 401. + /// + [Fact] + public async Task PostVaultInvite_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.PostAsJsonAsync( + "/vaults/any-vault-id/invite", + new { email = "x@x.com", role = "member" }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// POST /vaults/{id}/rotate-key without a token → 401. + /// + [Fact] + public async Task PostVaultRotateKey_WithoutToken_Returns401() + { + using var client = factory.CreateClient(); + var response = await client.PostAsJsonAsync( + "/vaults/any-vault-id/rotate-key", new { }); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } +} diff --git a/backend/Sessionist.Api.Tests/Helpers/JwtHelper.cs b/backend/Sessionist.Api.Tests/Helpers/JwtHelper.cs new file mode 100644 index 0000000..ab60fed --- /dev/null +++ b/backend/Sessionist.Api.Tests/Helpers/JwtHelper.cs @@ -0,0 +1,74 @@ +// Helper that produces cryptographically valid Bearer tokens for tests that +// need JWT authentication. The signing key and issuer/audience must match +// exactly what Program.cs configures in its JWT bearer options so that the +// ASP.NET Core middleware will accept tokens produced here. +// +// PRD §13.9: "Short-lived JWT access + refresh." +// The constants below must stay in sync with Program.cs. + +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using Microsoft.IdentityModel.Tokens; + +namespace Sessionist.Api.Tests.Helpers; + +/// +/// Builds cryptographically signed HS256 Bearer tokens accepted by the +/// in-memory implementation's JWT middleware. +/// +public static class JwtHelper +{ + // Must match exactly the constants in Program.cs. + public const string JwtSecret = "sessionist-test-jwt-secret-256bits-padding!!"; + public const string JwtIssuer = "sessionist"; + public const string JwtAudience = "sessionist-client"; + + /// + /// Returns "Bearer <token>" signed with HS256 using the same key as Program.cs. + /// + public static string BearerToken(string userId = "test-user-1", string email = "qa@example.com") + { + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSecret)); + var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + + var claims = new[] + { + new Claim(JwtRegisteredClaimNames.Sub, userId), + new Claim(JwtRegisteredClaimNames.Email, email), + }; + + var token = new JwtSecurityToken( + issuer: JwtIssuer, + audience: JwtAudience, + claims: claims, + expires: DateTime.UtcNow.AddHours(24), + signingCredentials: creds); + + return "Bearer " + new JwtSecurityTokenHandler().WriteToken(token); + } + + /// + /// Returns "Bearer <token>" for a specific userId — useful when tests + /// need to distinguish between different callers (e.g. vault owner vs member). + /// + public static string BearerTokenFor(string userId, string email) + => BearerToken(userId, email); + + /// + /// Returns a syntactically valid but wrongly signed Bearer token. + /// The API must reject this with 401. + /// + public static string BadlySignedBearerToken(string userId = "attacker-1") + { + // Sign with a different key — same structure, wrong signature. + var wrongKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("WRONG-KEY-different-signing-key-padding!!")); + var creds = new SigningCredentials(wrongKey, SecurityAlgorithms.HmacSha256); + var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userId) }; + var token = new JwtSecurityToken( + issuer: JwtIssuer, audience: JwtAudience, + claims: claims, expires: DateTime.UtcNow.AddHours(1), + signingCredentials: creds); + return "Bearer " + new JwtSecurityTokenHandler().WriteToken(token); + } +} diff --git a/backend/Sessionist.Api.Tests/Sessionist.Api.Tests.csproj b/backend/Sessionist.Api.Tests/Sessionist.Api.Tests.csproj new file mode 100644 index 0000000..9918f79 --- /dev/null +++ b/backend/Sessionist.Api.Tests/Sessionist.Api.Tests.csproj @@ -0,0 +1,44 @@ + + + + + + net10.0 + enable + enable + false + + CS8618 + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + diff --git a/backend/Sessionist.Api/Program.cs b/backend/Sessionist.Api/Program.cs new file mode 100644 index 0000000..a3e22d2 --- /dev/null +++ b/backend/Sessionist.Api/Program.cs @@ -0,0 +1,39 @@ +// Sessionist Team backend (P2 — PRD §9.7 / §13.9 / §13.10). +// Minimal API surface. Zero-knowledge: the server stores ciphertext only and +// never receives plaintext session data, master keys, or team keys. +// Every endpoint is a stub (501) until the Team phase begins. + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/health", () => Results.Ok(new { ok = true })); + +// --- Auth (Google OAuth + email magic link; short-lived JWT) --------------- +app.MapPost("/auth/google", () => NotImplemented("auth/google")); +app.MapPost("/auth/magic-link", () => NotImplemented("auth/magic-link")); +app.MapPost("/auth/refresh", () => NotImplemented("auth/refresh")); + +// --- Zero-knowledge sync (ciphertext blobs only) --------------------------- +app.MapGet("/sync/profiles", () => NotImplemented("sync/profiles:list")); +app.MapPut("/sync/profiles", () => NotImplemented("sync/profiles:push")); + +// --- Shared vaults + roles ------------------------------------------------- +app.MapGet("/vaults", () => NotImplemented("vaults:list")); +app.MapPost("/vaults", () => NotImplemented("vaults:create")); +app.MapPost("/vaults/{id}/invite", (string id) => NotImplemented($"vaults/{id}/invite")); +app.MapPost("/vaults/{id}/rotate-key", (string id) => NotImplemented($"vaults/{id}/rotate-key")); + +// --- Audit log (events + object IDs, never plaintext session contents) ------ +app.MapGet("/vaults/{id}/audit", (string id) => NotImplemented($"vaults/{id}/audit")); + +// --- Stripe Billing (seat-based) ------------------------------------------- +app.MapPost("/billing/checkout", () => NotImplemented("billing/checkout")); +app.MapPost("/billing/webhook", () => NotImplemented("billing/webhook")); + +app.Run(); + +static IResult NotImplemented(string endpoint) => + Results.Json(new { error = "not_implemented", endpoint }, statusCode: 501); + +// Test seam: makes Program visible to WebApplicationFactory in the test project. +public partial class Program { } diff --git a/backend/Sessionist.Api/Sessionist.Api.csproj b/backend/Sessionist.Api/Sessionist.Api.csproj new file mode 100644 index 0000000..85b2783 --- /dev/null +++ b/backend/Sessionist.Api/Sessionist.Api.csproj @@ -0,0 +1,23 @@ + + + + + + net10.0 + enable + enable + + + + + diff --git a/backend/Sessionist.Api/appsettings.json b/backend/Sessionist.Api/appsettings.json new file mode 100644 index 0000000..8c042ac --- /dev/null +++ b/backend/Sessionist.Api/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "_comment": "P2 only. ConnectionStrings, Stripe keys, and OAuth secrets are injected via environment/user-secrets, never committed (PRD §13.9)." +} diff --git a/e2e/README.md b/e2e/README.md new file mode 100644 index 0000000..1d39232 --- /dev/null +++ b/e2e/README.md @@ -0,0 +1,313 @@ +# Sessionist E2E Test Suite + +End-to-end tests for the Sessionist MV3 browser extension using +[Playwright](https://playwright.dev). + +> **Status: RED until features land.** +> All specs compile and enumerate correctly (72 tests across 8 files), but they +> will fail against the current skeleton (every service stub throws +> `NotImplementedError`). This is intentional — these tests document the +> required behaviour so that CI goes green automatically as each feature is +> implemented. + +--- + +## Running the tests + +### Prerequisites + +1. Build the extension (required — tests load the built artifact): + + ```bash + npm run build + ``` + + This produces `.output/chrome-mv3/` which the Playwright config loads. + +2. Install Playwright browsers (first time only): + + ```bash + npx playwright install chromium + ``` + +### Run all E2E specs + +```bash +npm run test:e2e +``` + +This command: +- Starts the demo-app server (`e2e/demo-app/server.cjs`) on port 4321. +- Launches a persistent Chromium context with the extension loaded. +- Runs all specs in the `e2e/` directory. + +### Run a single spec file + +```bash +npx playwright test e2e/cookie-editor.spec.ts +``` + +### List all tests without running them (compile check) + +```bash +npx playwright test --list +``` + +### Headed mode (see the browser) + +```bash +npx playwright test --headed +``` + +### Debug mode (step through) + +```bash +npx playwright test --debug e2e/playwright-export.spec.ts +``` + +### New headless mode (Chrome 112+, CI with virtual display) + +Set the environment variable before running: + +```bash +HEADLESS=true npm run test:e2e +``` + +Note: MV3 extensions require headed mode or Chrome's new headless pipeline +(`--headless=new`). Classic headless (`--headless=old`) does not load unpacked +extensions. In CI, use a virtual display (xvfb) or set `HEADLESS=true` to +attempt new-headless mode. + +--- + +## Full coverage map + +**Total: 72 tests in 8 spec files.** All are RED until features land. + +### `onboarding.spec.ts` — PRD §9.5 / §10 flow 1 + +| Test | PRD ref | Status | +|---|---|---| +| Side panel shows onboarding view on first run | §9.5 | RED | +| Onboarding shows "Import cookies" CTA for replacement users | §9.5 | RED | +| Onboarding shows "Capture this session" CTA for dev/QA users | §9.5 | RED | +| No sign-up prompt blocks onboarding flow | §9.5 | RED | +| "Import cookies" navigates to cookie editor (§10 flow 1) | §10 flow 1 | RED | +| Pasting EditThisCookie JSON shows imported cookie | §10 flow 1 | RED | +| Empty-state copy "Coming from EditThisCookie…" is visible | §9.5 | RED | +| "Capture this session" navigates to profiles view | §9.5 | RED | +| First-run onboarding does not require signup | §9.5 | RED | + +### `permission.spec.ts` — PRD §9.6 / §10 flow 2 + +| Test | PRD ref | Status | +|---|---|---| +| Manifest has no `` install-time host_permissions | §14.1 | RED | +| Capture on ungranted site shows permission prompt | §9.6 / §10 flow 2 | RED | +| Granted origin appears in Site Access settings list | §9.6 | RED | +| User can revoke a previously granted origin | §9.6 | RED | +| Declining permission shows graceful explanation, not error | §9.6 | RED | +| Extension remains usable for already-granted sites after decline | §9.6 edge case | RED | + +### `capture-switch.spec.ts` — PRD §9.2 / §10 flow 3 + +| Test | PRD ref | Status | +|---|---|---| +| Full A→B→A cycle reflects identity A in app | §9.2 / §10 flow 3 | RED | +| Pre-switch snapshot is created before switch executes | §9.2 step 2 | RED | +| Per-store switch results are shown after switch completes | §9.2 step 6 | RED | +| Switch never half-applies silently — result shown for every store | §13.6 invariant | RED | +| Recovery snapshot can be restored to undo a switch | §8 principle 5 / §9.2 | RED | + +### `cookie-editor.spec.ts` — PRD §9.1 + +| Test | PRD ref | Status | +|---|---|---| +| Cookie list visible after granting site access | §9.1 | RED | +| Search/filter cookie list narrows to matching names | §9.1 | RED | +| Add a new cookie — appears in the list | §9.1 | RED | +| Edit an existing cookie value | §9.1 | RED | +| Delete a single cookie — removed from list | §9.1 | RED | +| "Delete all" shows inline confirm before deleting | §9.1 | RED | +| "Delete all" confirmed removes all cookies | §9.1 | RED | +| Lock a cookie — disabled for deletion | §9.1 | RED | +| Export cookies as JSON — JSON contains the cookie | §9.1 | RED | +| Import JSON — cookies appear in editor list | §9.1 | RED | +| JSON round-trip: import then export produces same name/value | §9.1 acceptance | RED | + +### `correctness-matrix.spec.ts` — PRD §13.6 (a)–(e) + +| Test | PRD ref | Status | +|---|---|---| +| (a) Alice→Bob→Alice: cookie-session app shows alice | §13.6(a) | RED | +| (a) Switch result shows cookies store as succeeded | §13.6(a) | RED | +| (b) Captures sso_app_user + sso_auth_token; switch restores both | §13.6(b) | RED | +| (b) domainScope lists multiple cookie paths for SSO | §13.6(b) | RED | +| (c) Carol localStorage: capture, clear, switch → restored | §13.6(c) | RED | +| (c) Switch result shows localStorage store as succeeded | §13.6(c) | RED | +| (d) CHIPS partitioned cookie captured and restored on switch | §13.6(d) | RED | +| (d) CHIPS cookie captured with Partitioned attribute preserved | §13.6(d) | RED | +| (e) IndexedDB capture shows "not captured" notice | §13.6(e) | RED | +| (e) IndexedDB switch fails loudly with recoverable snapshot | §13.6(e) | RED | +| (e) IndexedDB app stays cleanly logged-out after switch | §13.6(e) | RED | + +### `playwright-export.spec.ts` — PRD §9.3 / §13.7 + +| Test | PRD ref | Status | +|---|---|---| +| Export view reachable via nav; shows profile selector | §9.3 | RED | +| storageState JSON contains "cookies" array | §9.3 / §13.7 | RED | +| Exported cookie has required Playwright fields | §9.3 / §13.7 | RED | +| localStorage profile exports origins with localStorage entries | §9.3 / §13.7 | RED | +| Copy-to-clipboard button present in export view | §9.3 | RED | +| Download button present in export view | §9.3 | RED | +| Redaction/secrets warning shown in export view | §9.3 | RED | +| Export view empty state when no profiles exist | §9.3 | RED | +| IndexedDB profile export shows disclaimer | §9.3 / §9.2 | RED | +| **§13.7 CAPSTONE**: exported storageState authenticates fresh context (cookie) | §13.7 | RED | +| **§13.7 CAPSTONE**: exported storageState authenticates fresh context (localStorage) | §13.7 | RED | +| **§13.7 CAPSTONE**: exported storageState authenticates fresh context (SSO) | §13.7 | RED | +| storageState JSON is valid Playwright storageState shape | §13.7 | RED | + +### `settings.spec.ts` — PRD §9.8 + +| Test | PRD ref | Status | +|---|---|---| +| Settings view reachable via nav | §9.8 | RED | +| Telemetry opt-in is OFF by default | §9.8 / §15 | RED | +| Telemetry can be opted-in and toggled back off | §9.8 / §15 | RED | +| Theme selector has light/dark/system options | §9.8 | RED | +| Dark theme applies `dark` class to root element | §9.8 | RED | +| Light theme removes `dark` class | §9.8 | RED | +| "Show welcome again" navigates back to onboarding | §9.5 / §9.8 | RED | +| Current plan tier shown (free for fresh install) | §11 | RED | +| License key input and Activate button present | §13.8 | RED | + +### `paywall.spec.ts` — PRD §10 flows 5 & 6 + +| Test | PRD ref | Status | +|---|---|---| +| Saving 4th profile navigates to upgrade view (§10 flow 5) | §10 flow 5 / §9.2 | RED | +| Upgrade view lists Pro features | §11.1 | RED | +| Upgrade view has "Upgrade to Pro" button | §10 flow 5 | RED | +| Pro-gated Puppeteer export redirects free users to upgrade | §9.4 / §11 | RED | +| Pro-gated Selenium export redirects free users to upgrade | §9.4 / §11 | RED | +| Pro-gated cURL export redirects free users to upgrade | §9.4 / §11 | RED | +| Playwright storageState export (free) does NOT redirect to upgrade | §11.1 | RED | +| Upgrade view shows correct price ($29 one-time) | §11.1 | RED | +| §10 flow 6: Team — skipped placeholder (P2) | §9.7 / §10 flow 6 | SKIPPED (P2) | + +--- + +## PRD flows → spec coverage map + +| PRD flow / section | Spec file | Coverage | +|---|---|---| +| §10 flow 1: Replacement import | `onboarding.spec.ts` | Full | +| §10 flow 2: Site permission grant + decline + revoke | `permission.spec.ts` | Full | +| §10 flow 3: Capture A→B→switch back | `capture-switch.spec.ts` | Full | +| §10 flow 4: Export to Playwright storageState | `playwright-export.spec.ts` | Full | +| §10 flow 5: Hit the wall → paywall → upgrade | `paywall.spec.ts` | Full | +| §10 flow 6: Share to team (P2) | `paywall.spec.ts` | Skipped placeholder | +| §9.1: Cookie editor (view/search/add/edit/delete/lock/import/export) | `cookie-editor.spec.ts` | Full | +| §9.2: Capture + transaction switch + pre-switch snapshot + per-store result + recovery | `capture-switch.spec.ts` | Full | +| §9.3: Playwright export UI + download + copy + redaction warning | `playwright-export.spec.ts` | Full | +| §9.6: Permission edge — decline keeps extension usable | `permission.spec.ts` | Full | +| §9.8: Dark mode / theme toggle | `settings.spec.ts` | Full | +| §9.8: Telemetry opt-in off by default | `settings.spec.ts` | Full | +| §9.5 / Settings: "Show welcome again" | `settings.spec.ts` | Full | +| §13.6(a): Single-origin cookie-session | `correctness-matrix.spec.ts` | Full | +| §13.6(b): Multi-domain SSO | `correctness-matrix.spec.ts` | Full | +| §13.6(c): localStorage SPA | `correctness-matrix.spec.ts` | Full | +| §13.6(d): CHIPS partitioned cookie | `correctness-matrix.spec.ts` | Full | +| §13.6(e): IndexedDB — disclosed not captured | `correctness-matrix.spec.ts` | Full | +| §13.7 capstone: storageState round-trip (cookie) | `playwright-export.spec.ts` | Full | +| §13.7 capstone: storageState round-trip (localStorage) | `playwright-export.spec.ts` | Full | + +--- + +## PRD flows judged not directly E2E-testable + +| Flow / requirement | Why not E2E | Where covered | +|---|---|---| +| §9.4: Puppeteer/Selenium/cURL export **output correctness** | Output format verification (exact code snippet syntax) is fragile as E2E and depends on runtime content that only exists once the feature is built. The E2E tests confirm these buttons redirect free users to the upgrade view (gating is correct). | Unit tests in `tests/export/` | +| §13.5: AES-GCM encrypt/decrypt at rest | Crypto operations on internal profile blobs are not observable from the UI without special test hooks. | Unit tests in `tests/storage/` | +| §9.7: Team sync / zero-knowledge vault | P2 — backend not yet built. Placeholder skipped test exists in `paywall.spec.ts`. | `paywall.spec.ts` (skipped) | +| §15: Telemetry event shapes (no session values) | Requires intercepting outbound network calls with specific payload inspection. Telemetry opt-in default is verified; payload correctness is a unit test concern. | Unit tests in `tests/telemetry/` | +| §13.8: Ed25519 license key verification | The client-side license check uses a public key baked into the build. PRD §13.8 notes this is intentionally not anti-tamper — the E2E gate is that activating a valid key upgrades the tier (covered via Settings spec); crypto verification is a unit concern. | Unit tests in `tests/licensing/` | +| Multi-tab coordination warning (P1) | Requires coordinating multiple real browser tabs with timing assumptions; P1 feature, add when implemented. | Unit tests | + +--- + +## What the demo-app provides + +`e2e/demo-app/server.cjs` is a zero-dependency Node HTTP server that serves +auth variants matching the §13.6 correctness matrix: + +| Route | Auth method | Spec scenario | +|---|---|---| +| `GET /` | Landing page with links | Navigation | +| `GET /cookie-session` | `sess_user` cookie | (a) single-origin | +| `GET /multi-domain-sso` | `sso_app_user` + `sso_auth_token` cookies | (b) multi-domain SSO | +| `GET /localstorage-spa` | `localStorage.sessionist_ls_token` (fake JWT) | (c) localStorage SPA | +| `GET /chips-cookie` | `chips_user` cookie with `Partitioned` flag | (d) CHIPS | +| `GET /indexeddb-token` | IndexedDB `sessionist-demo/auth` store | (e) IndexedDB (not captured) | +| `GET /sso` | `sso_auth_token` cookie at path `/sso` | (b) SSO second domain | +| `GET /status` | JSON: current server-readable auth state | Assertion helper | +| `GET /login?variant=&user=` | Convenience redirect (GET mirrors POST) | All cookie variants | +| `GET /logout?variant=` | Convenience redirect (GET mirrors POST) | All cookie variants | +| `POST /login?variant=&user=` | Sets appropriate auth cookie for variant | All cookie variants | +| `POST /logout?variant=` | Clears auth for variant | All cookie variants | + +--- + +## Fixture + +`e2e/fixtures/extension.ts` exports a `test` function extended with: + +| Fixture | Type | Description | +|---|---|---| +| `context` | `BrowserContext` | Persistent context with extension loaded (one per worker). | +| `extensionId` | `string` | Chrome extension ID derived from the service worker URL. | +| `sidepanelUrl` | `string` | `chrome-extension:///sidepanel.html` | +| `openSidePanel(page?)` | `(Page?) => Promise` | Navigate to the side panel and return the page. | +| `demoOrigin` | `string` | `http://localhost:4321` (or `DEMO_PORT` env). | + +Import in specs with: + +```ts +import { test, expect } from './fixtures/extension'; +``` + +--- + +## E2E vs unit/integration split + +### Covered by these E2E specs + +- Full UX flows from the extension side panel to the demo app and back. +- Per-origin permission grant/revoke lifecycle. +- Profile capture → switch → snapshot round-trip (observable from the app). +- The five §13.6 correctness scenarios as observable browser behaviour. +- storageState JSON shape (cookies + origins/localStorage fields). +- The §13.7 capstone: using exported storageState to authenticate a fresh context (cookie, localStorage, and SSO variants). +- Paywall/upsell milestone: save 4th profile → upgrade view. +- Pro-gated export targets redirect free users correctly. +- Theme toggle, dark mode applied, telemetry default off, "show welcome again". + +### Left to unit / integration tests (`tests/`) + +- `cookieService` field mapping (name, value, domain, path, expiry, flags). +- JSON compatibility with specific predecessor formats (EditThisCookie, Cookie-Editor, etc.). +- `profileService.capture()` internals: cookie API calls, localStorage injection. +- `profileService.switch()` transaction sequence: clear → apply → reload. +- Pre-switch snapshot creation logic. +- `playwrightExport.ts` field validation against Playwright's expected shape. +- `permissionService` grant/revoke persistence. +- `entitlementService` Pro gating logic. +- Crypto / AES-GCM encrypt-decrypt round-trips. +- Telemetry event shapes (no cookie/storage values). +- Netscape cookies.txt import/export (P1). +- sessionStorage helper snippet generation (P1). +- Multi-tab coordination warnings (P1). +- Puppeteer/Selenium/cURL export output format correctness (exact code syntax). diff --git a/e2e/capture-switch.spec.ts b/e2e/capture-switch.spec.ts new file mode 100644 index 0000000..7ac1e7d --- /dev/null +++ b/e2e/capture-switch.spec.ts @@ -0,0 +1,266 @@ +/** + * capture-switch.spec.ts + * + * Covers PRD §9.2 (Session profiles) and §10 UX flow 3 (Capture & switch). + * + * These tests are RED until the extension features are implemented. + * + * PRD acceptance criteria tested here: + * - §9.2: Capture identity A, log in as B, capture B, switch back to A + * - §9.2: After switch, the demo app reflects identity A (not B) + * - §9.2: A pre-switch snapshot was created before switch executed + * - §9.2: Per-store result (success/failure) is shown after switch + * - §9.2: Switch takes ≤ 2 clicks after setup + * - §9.2: Switching between identities never leaves state half-applied silently + * + * Left to unit tests: + * - profileService.capture() internals (cookie + localStorage collection) + * - profileService.switch() transaction sequence + * - Pre-switch snapshot creation logic + * - Per-store apply result generation + */ + +import { test, expect } from './fixtures/extension'; + +test.describe('Capture & switch — identity A → B → A (§9.2 / §10 flow 3)', () => { + /** + * Helper: log in to the cookie-session demo app as the given user by + * sending a POST to the demo server's /login endpoint. + */ + async function loginAsCookieUser( + page: import('@playwright/test').Page, + demoOrigin: string, + user: string, + ) { + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=${encodeURIComponent(user)}`, { + waitUntil: 'networkidle', + }); + // The server redirects to /cookie-session after login. + await page.waitForURL(`${demoOrigin}/cookie-session`); + } + + test('full capture-A → capture-B → switch-to-A cycle reflects identity A in app', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + + // ── Step 1: Log in as Alice, open extension, capture profile "Alice" ── + await loginAsCookieUser(demoPage, demoOrigin, 'alice'); + await expect(demoPage.getByTestId('username')).toHaveText('alice'); + + const panel = await openSidePanel(demoPage); + + // Grant site access if needed. + const grantIfNeeded = async () => { + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + }; + + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await grantIfNeeded(); + + const profileNameInput = panel.getByRole('textbox', { name: /profile name/i }); + await profileNameInput.fill('Alice'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + const aliceEntry = panel.getByText('Alice'); + await expect(aliceEntry).toBeVisible({ timeout: 10_000 }); + + // ── Step 2: Log in as Bob, capture profile "Bob" ── + await loginAsCookieUser(demoPage, demoOrigin, 'bob'); + await expect(demoPage.getByTestId('username')).toHaveText('bob'); + + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await profileNameInput.fill('Bob'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + await expect(panel.getByText('Bob')).toBeVisible({ timeout: 10_000 }); + + // ── Step 3: Switch back to Alice (≤ 2 clicks after setup) ── + const aliceProfile = panel.getByTestId('profile-item').filter({ hasText: 'Alice' }); + await aliceProfile.click(); // click 1: select + + const switchBtn = panel.getByRole('button', { name: /switch|apply/i }); + await switchBtn.click(); // click 2: confirm + + // ── Step 4: Assert demo app shows Alice ── + await demoPage.waitForURL(`${demoOrigin}/cookie-session`); + await expect(demoPage.getByTestId('username')).toHaveText('alice', { timeout: 15_000 }); + await expect(demoPage.getByTestId('auth-status')).not.toHaveClass(/logged-out/, { + timeout: 10_000, + }); + }); + + test('a pre-switch snapshot is created before switch executes', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + + await loginAsCookieUser(demoPage, demoOrigin, 'alice'); + const panel = await openSidePanel(demoPage); + + // Capture Alice. + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + await panel.getByRole('textbox', { name: /profile name/i }).fill('Alice'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + // Capture Bob. + await loginAsCookieUser(demoPage, demoOrigin, 'bob'); + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await panel.getByRole('textbox', { name: /profile name/i }).fill('Bob'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + // Switch to Alice. + await panel.getByTestId('profile-item').filter({ hasText: 'Alice' }).click(); + await panel.getByRole('button', { name: /switch|apply/i }).click(); + + // PRD §9.2 step 2: a pre-switch snapshot must be automatically created. + const snapshotList = panel.getByTestId('snapshot-list'); + await expect(snapshotList).toBeVisible({ timeout: 10_000 }); + + // At least one snapshot entry should exist (the auto-snapshot of Bob's state). + const snapshotItems = snapshotList.getByTestId('snapshot-item'); + await expect(snapshotItems).toHaveCount(1, { timeout: 5_000 }); + }); + + test('per-store switch results are shown after switch completes', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + await loginAsCookieUser(demoPage, demoOrigin, 'alice'); + const panel = await openSidePanel(demoPage); + + // Quick capture → switch cycle. + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + await panel.getByRole('textbox', { name: /profile name/i }).fill('Alice'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + await loginAsCookieUser(demoPage, demoOrigin, 'bob'); + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await panel.getByRole('textbox', { name: /profile name/i }).fill('Bob'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + await panel.getByTestId('profile-item').filter({ hasText: 'Alice' }).click(); + await panel.getByRole('button', { name: /switch|apply/i }).click(); + + // PRD §9.2 step 6: surface success/failure per store. + // We expect to see a result summary with at least a "cookies" row. + const switchResult = panel.getByTestId('switch-result'); + await expect(switchResult).toBeVisible({ timeout: 10_000 }); + + const cookieResult = switchResult.getByText(/cookie/i); + await expect(cookieResult).toBeVisible(); + }); + + test('switch never half-applies silently — result is shown for every store', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // This test validates the §13.6 invariant: each store must report success OR + // failure explicitly. No store may silently succeed or silently fail. + const demoPage = await context.newPage(); + + // Use the localStorage SPA to ensure both cookies AND localStorage are in scope. + await demoPage.goto(`${demoOrigin}/localstorage-spa`); + await demoPage.getByRole('button', { name: /log in as carol/i }).click(); + + const panel = await openSidePanel(demoPage); + + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + await panel.getByRole('textbox', { name: /profile name/i }).fill('Carol'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + + // Log out, then switch back. + await demoPage.getByRole('button', { name: /log out/i }).click(); + + await panel.getByTestId('profile-item').filter({ hasText: 'Carol' }).click(); + await panel.getByRole('button', { name: /switch|apply/i }).click(); + + // Every store present in the profile must have an explicit result entry. + const switchResult = panel.getByTestId('switch-result'); + await expect(switchResult).toBeVisible({ timeout: 10_000 }); + + // localStorage result must be shown (even if it says "not captured"). + const localStorageResult = switchResult.getByText(/localStorage|local storage/i); + await expect(localStorageResult).toBeVisible(); + }); + + test('recovery snapshot can be restored to undo a switch', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // PRD §9.2 step 2 + §8 principle 5: "Safety before cleverness. Snapshot + // before destructive changes. Make recovery obvious." + // After a switch, the pre-switch snapshot must be restorable. + const demoPage = await context.newPage(); + + await loginAsCookieUser(demoPage, demoOrigin, 'alice'); + await expect(demoPage.getByTestId('username')).toHaveText('alice'); + + const panel = await openSidePanel(demoPage); + + // Grant if needed. + const grantIfNeeded = async () => { + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + }; + + // Capture Alice. + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await grantIfNeeded(); + await panel.getByRole('textbox', { name: /profile name/i }).fill('Alice-recover'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + await expect(panel.getByText('Alice-recover')).toBeVisible({ timeout: 10_000 }); + + // Log in as Bob, capture Bob. + await loginAsCookieUser(demoPage, demoOrigin, 'bob'); + await expect(demoPage.getByTestId('username')).toHaveText('bob'); + + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + await panel.getByRole('textbox', { name: /profile name/i }).fill('Bob-recover'); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + await expect(panel.getByText('Bob-recover')).toBeVisible({ timeout: 10_000 }); + + // Switch to Alice (creates a pre-switch snapshot of Bob's state). + await panel.getByTestId('profile-item').filter({ hasText: 'Alice-recover' }).click(); + await panel.getByRole('button', { name: /switch|apply/i }).click(); + + // Confirm the switch happened — app shows Alice. + await demoPage.waitForURL(`${demoOrigin}/cookie-session`); + await expect(demoPage.getByTestId('username')).toHaveText('alice', { timeout: 15_000 }); + + // A recovery snapshot should be listed. + const snapshotList = panel.getByTestId('snapshot-list'); + await expect(snapshotList).toBeVisible({ timeout: 10_000 }); + + // Restore the pre-switch snapshot (Bob's state). + const restoreBtn = snapshotList.getByRole('button', { name: /restore/i }).first(); + await expect(restoreBtn).toBeVisible({ timeout: 5_000 }); + await restoreBtn.click(); + + // After restoring Bob's snapshot, the app should show Bob again. + await demoPage.waitForURL(`${demoOrigin}/cookie-session`); + await expect(demoPage.getByTestId('username')).toHaveText('bob', { timeout: 15_000 }); + }); +}); diff --git a/e2e/cookie-editor.spec.ts b/e2e/cookie-editor.spec.ts new file mode 100644 index 0000000..3c4dbed --- /dev/null +++ b/e2e/cookie-editor.spec.ts @@ -0,0 +1,433 @@ +/** + * cookie-editor.spec.ts + * + * Covers PRD §9.1 (Cookie editor — free forever). + * + * These tests are RED until the extension features are implemented. + * + * PRD acceptance criteria tested here: + * - §9.1: View cookies for the active tab's domain + * - §9.1: Search / filter cookie list by name + * - §9.1: Add a new cookie + * - §9.1: Edit an existing cookie (name, value, path, expiry, flags) + * - §9.1: Delete a single cookie + * - §9.1: "Delete all for this site" with inline confirm (bulk delete) + * - §9.1: Protect/lock specific cookies from deletion inside Sessionist operations + * - §9.1: JSON export — exported JSON round-trips without data loss + * - §9.1: JSON import — cookies from pasted JSON appear in the editor + * - §9.1: Exported JSON round-trips (import → export → same set) + * + * Left to unit tests: + * - cookieService field-mapping correctness + * - JSON schema compatibility with common predecessor formats + * - Netscape cookies.txt format (P1) + */ + +import { test, expect } from './fixtures/extension'; + +// --------------------------------------------------------------------------- +// View / add / edit / delete / search / lock +// --------------------------------------------------------------------------- + +test.describe('Cookie editor — view / add / edit / delete / search / lock (§9.1)', () => { + test('cookie list is visible after granting site access', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + // Set a cookie via server login so there is something to display. + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + + // Grant access. + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // The cookie-editor view / cookie list must be visible. + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList).toBeVisible({ timeout: 10_000 }); + + // The 'sess_user' cookie set by the server must appear. + const cookieRow = cookieList.getByText('sess_user'); + await expect(cookieRow).toBeVisible(); + }); + + test('search / filter cookie list narrows results to matching names', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Add a second cookie called "another_cookie" so we have two to filter. + const addBtn = panel.getByRole('button', { name: /^add$/i }); + await addBtn.click(); + const nameField = panel + .getByRole('textbox', { name: /^name$/i }) + .or(panel.getByPlaceholder(/cookie name/i)); + const valueField = panel + .getByRole('textbox', { name: /^value$/i }) + .or(panel.getByPlaceholder(/cookie value/i)); + await nameField.fill('another_cookie'); + await valueField.fill('another_value'); + await panel + .getByRole('button', { name: /save|add|confirm/i }) + .last() + .click(); + + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('sess_user')).toBeVisible({ timeout: 10_000 }); + await expect(cookieList.getByText('another_cookie')).toBeVisible(); + + // Type in the search box — "another" should hide sess_user. + const searchBox = panel + .getByRole('textbox', { name: /search|filter/i }) + .or(panel.locator('[placeholder*="Search"]')); + await searchBox.fill('another'); + + await expect(cookieList.getByText('another_cookie')).toBeVisible({ timeout: 5_000 }); + await expect(cookieList.getByText('sess_user')).not.toBeVisible(); + + // Clearing the search shows all cookies again. + await searchBox.clear(); + await expect(cookieList.getByText('sess_user')).toBeVisible({ timeout: 5_000 }); + await expect(cookieList.getByText('another_cookie')).toBeVisible(); + }); + + test('add a new cookie — appears in the list', async ({ context, openSidePanel, demoOrigin }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Click "Add" button. + const addBtn = panel.getByRole('button', { name: /^add$/i }); + await addBtn.click(); + + // Fill in the cookie form. + const nameField = panel + .getByRole('textbox', { name: /^name$/i }) + .or(panel.getByPlaceholder(/cookie name/i)); + const valueField = panel + .getByRole('textbox', { name: /^value$/i }) + .or(panel.getByPlaceholder(/cookie value/i)); + + await nameField.fill('test_cookie'); + await valueField.fill('test_value_123'); + + const saveBtn = panel.getByRole('button', { name: /save|add|confirm/i }).last(); + await saveBtn.click(); + + // New cookie must appear in the list. + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('test_cookie')).toBeVisible({ timeout: 10_000 }); + await expect(cookieList.getByText('test_value_123')).toBeVisible(); + }); + + test('edit an existing cookie value', async ({ context, openSidePanel, demoOrigin }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Click edit on the sess_user cookie. + const cookieList = panel.getByTestId('cookie-list'); + const sessRow = cookieList.getByTestId('cookie-row').filter({ hasText: 'sess_user' }); + await sessRow.getByRole('button', { name: /edit/i }).click(); + + // Change the value. + const valueField = panel + .getByRole('textbox', { name: /^value$/i }) + .or(panel.getByPlaceholder(/cookie value/i)); + await valueField.clear(); + await valueField.fill('edited_value'); + + await panel + .getByRole('button', { name: /save|update|confirm/i }) + .last() + .click(); + + // Updated value must be visible in the list. + await expect(cookieList.getByText('edited_value')).toBeVisible({ timeout: 10_000 }); + }); + + test('delete a single cookie — removed from the list', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + const cookieList = panel.getByTestId('cookie-list'); + const sessRow = cookieList.getByTestId('cookie-row').filter({ hasText: 'sess_user' }); + await sessRow.getByRole('button', { name: /delete|remove/i }).click(); + + // Confirmation if the UI asks for it. + const confirmBtn = panel.getByRole('button', { name: /confirm|yes|delete/i }); + if (await confirmBtn.isVisible({ timeout: 2_000 }).catch(() => false)) await confirmBtn.click(); + + // Cookie row must be gone. + await expect(cookieList.getByText('sess_user')).not.toBeVisible({ timeout: 10_000 }); + }); + + test('"Delete all" shows inline confirmation before deleting (§9.1)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Verify a cookie exists. + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('sess_user')).toBeVisible({ timeout: 10_000 }); + + // Click "Delete all for this site" — an inline confirmation must appear. + const deleteAllBtn = panel.getByRole('button', { name: /delete all/i }); + await deleteAllBtn.click(); + + // The confirmation prompt must be visible (the UI shows "Delete all cookies for this site?"). + const confirmationStep = panel + .getByText(/delete all cookies for this site/i) + .or(panel.getByRole('button', { name: /yes.*delete|yes, delete all/i })); + await expect(confirmationStep).toBeVisible({ timeout: 5_000 }); + + // Cookies must NOT yet be deleted at this point (no premature action). + await expect(cookieList.getByText('sess_user')).toBeVisible(); + + // Cancel — cookie must still be there. + const cancelBtn = panel.getByRole('button', { name: /cancel/i }); + await cancelBtn.click(); + await expect(cookieList.getByText('sess_user')).toBeVisible({ timeout: 5_000 }); + }); + + test('"Delete all" confirmed removes all cookies for the site', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('sess_user')).toBeVisible({ timeout: 10_000 }); + + // Initiate delete-all and confirm. + await panel.getByRole('button', { name: /delete all/i }).click(); + + // The UI renders the confirmation inline: "Yes, delete all" + const confirmBtn = panel.getByRole('button', { name: /yes.*delete|yes, delete all/i }); + await confirmBtn.click(); + + // All cookies must be gone. + await expect(cookieList.getByTestId('cookie-row')).toHaveCount(0, { timeout: 10_000 }); + }); + + test('lock a cookie — locked cookie is disabled for deletion (§9.1)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // PRD §9.1: "Protect/lock specific cookies from deletion inside Sessionist operations." + // UI: CookieEditorView renders Delete button with disabled={c.locked} and text "Locked". + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + const cookieList = panel.getByTestId('cookie-list'); + const sessRow = cookieList.getByTestId('cookie-row').filter({ hasText: 'sess_user' }); + await expect(sessRow).toBeVisible({ timeout: 10_000 }); + + // Open the cookie for editing by clicking the row (the row itself is a button + // with aria-label "Edit cookie "). + await sessRow.getByRole('button', { name: /edit cookie sess_user/i }).click(); + + // Look for a lock toggle (checkbox or button) in the edit form. + const lockControl = panel + .getByRole('checkbox', { name: /lock/i }) + .or(panel.getByRole('button', { name: /^lock$/i })); + await expect(lockControl).toBeVisible({ timeout: 5_000 }); + + // Enable the lock. + const lockCheckbox = panel.getByRole('checkbox', { name: /lock/i }); + if (await lockCheckbox.isVisible({ timeout: 1_000 }).catch(() => false)) { + await lockCheckbox.check(); + } else { + await panel.getByRole('button', { name: /^lock$/i }).click(); + } + + // Save. + await panel.getByRole('button', { name: /save/i }).last().click(); + + // The delete button for a locked cookie must show "Locked" text and be disabled. + const deleteOrLockedBtn = sessRow.getByRole('button', { name: /locked|delete/i }); + await expect(deleteOrLockedBtn).toBeVisible({ timeout: 10_000 }); + await expect(deleteOrLockedBtn).toBeDisabled(); + await expect(deleteOrLockedBtn).toHaveText(/locked/i); + }); +}); + +// --------------------------------------------------------------------------- +// JSON import / export +// --------------------------------------------------------------------------- + +test.describe('Cookie editor — JSON import / export (§9.1)', () => { + test('export cookies as JSON — displayed JSON contains the cookie', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Click Export (cookie editor toolbar button is labelled "Export"). + const exportBtn = panel.getByRole('button', { name: /^export$/i }); + await exportBtn.click(); + + // JSON is shown in a textarea / pre or downloaded. + const jsonOutput = panel + .getByTestId('cookie-export-json') + .or(panel.getByRole('textbox', { name: /exported json/i })); + await expect(jsonOutput).toBeVisible({ timeout: 10_000 }); + + const jsonText = await jsonOutput.textContent(); + const parsed: Array<{ name: string }> = JSON.parse(jsonText ?? '[]'); + expect(parsed.some((c) => c.name === 'sess_user')).toBe(true); + }); + + test('import JSON — cookies appear in the editor list', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Click Import. + const importBtn = panel.getByRole('button', { name: /^import$/i }); + await importBtn.click(); + + const cookieJson = JSON.stringify([ + { + name: 'imported_test', + value: 'imported_value', + domain: 'localhost', + path: '/', + secure: false, + httpOnly: false, + expirationDate: Math.floor(Date.now() / 1000) + 3600, + sameSite: 'Lax', + }, + ]); + + // The UI shows a textarea with aria-label "Cookie import JSON". + const jsonInput = panel + .getByRole('textbox', { name: /cookie import json/i }) + .or(panel.getByTestId('cookie-import-textarea')); + await jsonInput.fill(cookieJson); + + const confirmBtn = panel.getByRole('button', { name: /^import$/i }).last(); + await confirmBtn.click(); + + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('imported_test')).toBeVisible({ timeout: 10_000 }); + await expect(cookieList.getByText('imported_value')).toBeVisible(); + }); + + test('JSON round-trip: import then export produces the same cookie name/value', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + const originalCookies = [ + { + name: 'rt_cookie', + value: 'round_trip_value', + domain: 'localhost', + path: '/', + secure: false, + httpOnly: false, + expirationDate: Math.floor(Date.now() / 1000) + 7200, + sameSite: 'Lax', + }, + ]; + + // Import. + await panel.getByRole('button', { name: /^import$/i }).click(); + const jsonInput = panel + .getByRole('textbox', { name: /cookie import json/i }) + .or(panel.getByTestId('cookie-import-textarea')); + await jsonInput.fill(JSON.stringify(originalCookies)); + await panel + .getByRole('button', { name: /^import$/i }) + .last() + .click(); + await expect(panel.getByTestId('cookie-list').getByText('rt_cookie')).toBeVisible({ + timeout: 10_000, + }); + + // Export. + await panel.getByRole('button', { name: /^export$/i }).click(); + const jsonOutput = panel + .getByTestId('cookie-export-json') + .or(panel.getByRole('textbox', { name: /exported json/i })); + await expect(jsonOutput).toBeVisible({ timeout: 10_000 }); + + const exportedText = await jsonOutput.textContent(); + const exported: Array<{ name: string; value: string }> = JSON.parse(exportedText ?? '[]'); + + const match = exported.find((c) => c.name === 'rt_cookie'); + expect(match).toBeDefined(); + expect(match?.value).toBe('round_trip_value'); + }); +}); diff --git a/e2e/correctness-matrix.spec.ts b/e2e/correctness-matrix.spec.ts new file mode 100644 index 0000000..3ca2c3e --- /dev/null +++ b/e2e/correctness-matrix.spec.ts @@ -0,0 +1,386 @@ +/** + * correctness-matrix.spec.ts + * + * Covers PRD §13.6 correctness test matrix — five scenarios (a)–(e). + * + * These tests are RED until the extension features are implemented. + * + * From §13.6: + * "E2E-validate capture→switch→restore against at least: + * (a) a single-origin cookie-session app, + * (b) a multi-domain SSO app, + * (c) a localStorage-token SPA, + * (d) a CHIPS/partitioned-cookie case, + * (e) an IndexedDB-token app (to confirm the §9.2 limitation behaves as + * disclosed). + * Each must either switch cleanly OR fail loudly with a recoverable snapshot + * — never half-switch silently." + * + * The demo-app server (e2e/demo-app/server.js) provides all five routes. + * + * Left to unit tests: + * - Cookie serialization for each variant + * - domainScope field population from multi-domain scenarios + * - UnsupportedStoreNotice generation for IndexedDB + */ + +import { test, expect } from './fixtures/extension'; +import type { Page } from '@playwright/test'; + +// ──────────────────────────────────────────────────────────────────────────── +// Shared helpers +// ──────────────────────────────────────────────────────────────────────────── + +/** + * Grant the extension access to the current page origin and capture a profile + * with the given name. Returns after the profile is visible in the panel. + */ +async function captureProfile(panel: Page, name: string): Promise { + await panel.getByRole('button', { name: /capture current|capture session/i }).click(); + + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + + const nameInput = panel.getByRole('textbox', { name: /profile name/i }); + await nameInput.fill(name); + await panel.getByRole('button', { name: /save|confirm/i }).click(); + await expect(panel.getByText(name)).toBeVisible({ timeout: 10_000 }); +} + +/** + * Switch to a named profile and wait for the switch-result summary to appear. + */ +async function switchToProfile(panel: Page, name: string): Promise { + await panel.getByTestId('profile-item').filter({ hasText: name }).click(); + await panel.getByRole('button', { name: /switch|apply/i }).click(); + await expect(panel.getByTestId('switch-result')).toBeVisible({ timeout: 15_000 }); +} + +// ──────────────────────────────────────────────────────────────────────────── +// (a) Single-origin cookie-session app +// ──────────────────────────────────────────────────────────────────────────── + +test.describe('(a) Single-origin cookie-session app', () => { + test('capture alice, switch to bob, switch back to alice — app shows alice', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + await expect(page.getByTestId('username')).toHaveText('alice'); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Alice-cookie'); + + // Switch identities. + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=bob`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + await captureProfile(panel, 'Bob-cookie'); + + // Switch back to Alice. + await switchToProfile(panel, 'Alice-cookie'); + + // App must reflect Alice after tab reload. + await page.waitForLoadState('domcontentloaded'); + await expect(page.getByTestId('username')).toHaveText('alice', { timeout: 15_000 }); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + }); + + test('switch result shows cookies store as succeeded', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Alice-cookie-2'); + + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=bob`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + await captureProfile(panel, 'Bob-cookie-2'); + + await switchToProfile(panel, 'Alice-cookie-2'); + + const result = panel.getByTestId('switch-result'); + // Cookie store must report success. + await expect(result.getByText(/cookie.*success|success.*cookie/i)).toBeVisible(); + }); +}); + +// ──────────────────────────────────────────────────────────────────────────── +// (b) Multi-domain SSO app +// ──────────────────────────────────────────────────────────────────────────── + +test.describe('(b) Multi-domain SSO app', () => { + test('captures both sso_app_user and sso_auth_token cookies; switch restores both', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=multi-domain-sso&user=alice-sso`); + await page.waitForURL(`${demoOrigin}/multi-domain-sso`); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Alice-SSO'); + + // Switch to Bob. + await page.goto(`${demoOrigin}/login?variant=multi-domain-sso&user=bob-sso`); + await page.waitForURL(`${demoOrigin}/multi-domain-sso`); + await captureProfile(panel, 'Bob-SSO'); + + // Switch back to Alice. + await switchToProfile(panel, 'Alice-SSO'); + await page.waitForLoadState('domcontentloaded'); + + // Both cookies must have been restored. The demo app only shows logged-in + // if BOTH cookies are present. + await expect(page.getByTestId('username')).toHaveText('alice-sso', { timeout: 15_000 }); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + }); + + test('domainScope field in the profile UI lists multiple cookie paths/origins', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=multi-domain-sso&user=alice-sso`); + await page.waitForURL(`${demoOrigin}/multi-domain-sso`); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Alice-SSO-scope'); + + // Inspect the profile detail view for the domainScope information. + await panel.getByTestId('profile-item').filter({ hasText: 'Alice-SSO-scope' }).click(); + const detailView = panel.getByTestId('profile-detail'); + await expect(detailView).toBeVisible({ timeout: 10_000 }); + + // The domainScope field must list more than one domain/path for SSO. + const scopeSection = detailView.getByTestId('domain-scope'); + await expect(scopeSection).toBeVisible(); + const scopeItems = scopeSection.getByTestId('domain-scope-item'); + await expect(scopeItems).toHaveCount(2); // app + sso paths + }); +}); + +// ──────────────────────────────────────────────────────────────────────────── +// (c) localStorage-token SPA +// ──────────────────────────────────────────────────────────────────────────── + +test.describe('(c) localStorage-token SPA', () => { + test('capture carol, clear storage, switch to carol — localStorage restored', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/localstorage-spa`); + await page.getByRole('button', { name: /log in as carol/i }).click(); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Carol-LS'); + + // Clear localStorage to simulate a logged-out state. + await page.getByRole('button', { name: /log out/i }).click(); + await expect(page.getByTestId('auth-status')).toHaveClass(/logged-out/); + + // Switch back to Carol. + await switchToProfile(panel, 'Carol-LS'); + await page.waitForLoadState('domcontentloaded'); + + // The app reads localStorage on load; Carol's token should be restored. + await expect(page.getByTestId('username')).toHaveText('carol', { timeout: 15_000 }); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + }); + + test('switch result shows localStorage store as succeeded', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/localstorage-spa`); + await page.getByRole('button', { name: /log in as carol/i }).click(); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Carol-LS-2'); + + await page.getByRole('button', { name: /log out/i }).click(); + + await switchToProfile(panel, 'Carol-LS-2'); + + const result = panel.getByTestId('switch-result'); + await expect(result.getByText(/localStorage.*success|success.*localStorage/i)).toBeVisible(); + }); +}); + +// ──────────────────────────────────────────────────────────────────────────── +// (d) CHIPS / partitioned-cookie case +// ──────────────────────────────────────────────────────────────────────────── + +test.describe('(d) CHIPS / partitioned-cookie case', () => { + test('captures partitioned cookie and restores it on switch', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=chips-cookie&user=dave`); + await page.waitForURL(`${demoOrigin}/chips-cookie`); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Dave-CHIPS'); + + // Log out. + await page.goto(`${demoOrigin}/logout?variant=chips-cookie`); + await page.waitForURL(`${demoOrigin}/chips-cookie`); + await expect(page.getByTestId('auth-status')).toHaveClass(/logged-out/); + + // Switch back to Dave. + await switchToProfile(panel, 'Dave-CHIPS'); + await page.waitForLoadState('domcontentloaded'); + + await expect(page.getByTestId('username')).toHaveText('dave', { timeout: 15_000 }); + }); + + test('CHIPS cookie captured with Partitioned attribute preserved', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // Verify the exported storageState JSON includes the partitioned cookie. + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=chips-cookie&user=dave`); + await page.waitForURL(`${demoOrigin}/chips-cookie`); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Dave-CHIPS-export'); + + // Open export view. + await panel.getByTestId('profile-item').filter({ hasText: 'Dave-CHIPS-export' }).click(); + await panel.getByRole('button', { name: /export.*playwright/i }).click(); + + const exportView = panel.getByTestId('export-view'); + await expect(exportView).toBeVisible({ timeout: 10_000 }); + + // The storageState JSON must include the chips_user cookie. + const jsonOutput = await exportView.getByTestId('storage-state-json').textContent(); + const parsed = JSON.parse(jsonOutput ?? '{}'); + const cookies: Array<{ name: string; partitionKey?: unknown }> = parsed?.cookies ?? []; + const chipsCookie = cookies.find((c) => c.name === 'chips_user'); + expect(chipsCookie).toBeDefined(); + }); +}); + +// ──────────────────────────────────────────────────────────────────────────── +// (e) IndexedDB-token app — disclosed NOT captured +// ──────────────────────────────────────────────────────────────────────────── + +test.describe('(e) IndexedDB-token app — limitation disclosed, not silent', () => { + test('capture on IndexedDB app shows "not captured" notice for IndexedDB store', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/indexeddb-token`); + await page.getByRole('button', { name: /log in as eve/i }).click(); + + // Wait for the page to update (IndexedDB is async). + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/, { + timeout: 10_000, + }); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Eve-IDB'); + + // Inspect the profile — it must surface an UnsupportedStoreNotice for IndexedDB. + await panel.getByTestId('profile-item').filter({ hasText: 'Eve-IDB' }).click(); + const detailView = panel.getByTestId('profile-detail'); + await expect(detailView).toBeVisible({ timeout: 10_000 }); + + // PRD §13.6: "Unsupported stores must be visible in UI as 'not captured'." + const notice = detailView.getByTestId('unsupported-store-notice'); + await expect(notice).toBeVisible(); + await expect(notice.getByText(/IndexedDB/i)).toBeVisible(); + await expect(notice.getByText(/not captured/i)).toBeVisible(); + }); + + test('switch on IndexedDB-auth app fails loudly with a recoverable pre-switch snapshot', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/indexeddb-token`); + await page.getByRole('button', { name: /log in as eve/i }).click(); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/, { + timeout: 10_000, + }); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Eve-IDB-switch'); + + // Log out. + await page.getByRole('button', { name: /log out/i }).click(); + + // Switch to Eve. This should NOT silently succeed — it must either: + // (a) warn before switching that IndexedDB is excluded, or + // (b) complete and then clearly show IndexedDB was not applied. + await switchToProfile(panel, 'Eve-IDB-switch'); + + const result = panel.getByTestId('switch-result'); + await expect(result).toBeVisible({ timeout: 10_000 }); + + // The switch result must NOT show IndexedDB as "succeeded" (it cannot). + const idbResultText = await result.getByText(/IndexedDB/i).textContent(); + // Must contain "not captured", "skipped", "unsupported", or similar — not "success". + expect(idbResultText?.toLowerCase()).not.toMatch(/success/); + expect(idbResultText?.toLowerCase()).toMatch(/not captured|skipped|unsupported|partial/); + + // A pre-switch snapshot must have been created for recovery. + const snapshots = panel.getByTestId('snapshot-list'); + await expect(snapshots).toBeVisible({ timeout: 5_000 }); + await expect(snapshots.getByTestId('snapshot-item')).toHaveCount(1); + }); + + test('IndexedDB app remains logged-out after switch (auth cannot be restored)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // After a switch that cannot restore IndexedDB auth, the app must still + // show "not logged in" — not a corrupt or half-applied state. + const page = await context.newPage(); + await page.goto(`${demoOrigin}/indexeddb-token`); + await page.getByRole('button', { name: /log in as eve/i }).click(); + await expect(page.getByTestId('auth-status')).not.toHaveClass(/logged-out/, { + timeout: 10_000, + }); + + const panel = await openSidePanel(page); + await captureProfile(panel, 'Eve-IDB-clean'); + + await page.getByRole('button', { name: /log out/i }).click(); + await expect(page.getByTestId('auth-status')).toHaveClass(/logged-out/); + + await switchToProfile(panel, 'Eve-IDB-clean'); + await page.waitForLoadState('domcontentloaded'); + + // The app must NOT show a corrupted logged-in state. + // It should be cleanly logged-out (IndexedDB not restored) — which is the + // honest "disclosed not captured" behaviour from PRD §9.2. + await expect(page.getByTestId('auth-status')).toHaveClass(/logged-out/, { timeout: 10_000 }); + }); +}); diff --git a/e2e/demo-app/server.cjs b/e2e/demo-app/server.cjs new file mode 100644 index 0000000..61f0215 --- /dev/null +++ b/e2e/demo-app/server.cjs @@ -0,0 +1,517 @@ +/** + * Sessionist E2E demo-app server + * + * A minimal Node.js HTTP server (no dependencies beyond Node core) that + * simulates the §13.6 correctness-matrix auth scenarios: + * + * GET / — landing page (links to each auth variant) + * GET /cookie-session — (a) single-origin cookie-session app + * GET /multi-domain-sso — (b) multi-domain SSO simulation (sets cookies on + * two different paths to simulate cross-origin scope) + * GET /localstorage-spa — (c) localStorage-token SPA + * GET /chips-cookie — (d) CHIPS / partitioned-cookie app + * GET /indexeddb-token — (e) IndexedDB-token app (auth NOT captured) + * GET /status — JSON: { loggedIn, user, method } based on request + * cookies/headers — used by Playwright assertions + * + * Auth flow per variant: + * POST /login?variant=&user= — "logs in" by setting the appropriate + * auth artifact for that variant + * POST /logout?variant= — clears auth for that variant + * + * Design constraints: + * - Zero npm dependencies: pure Node http + fs. + * - Self-contained HTML served as inline strings. + * - No build step required. + * - CORS permissive (localhost only) for Playwright storageState testing. + */ + +// @ts-check +'use strict'; + +const http = require('http'); +const url = require('url'); + +const PORT = parseInt(process.env.DEMO_PORT || '4321', 10); + +// --------------------------------------------------------------------------- +// HTML templates +// --------------------------------------------------------------------------- + +const page = (title, body) => ` + + + + ${title} — Sessionist Demo App + + + + +

${title}

+ ${body} + +`; + +// --------------------------------------------------------------------------- +// Cookie helpers +// --------------------------------------------------------------------------- + +/** Parse a Cookie header into a name→value map. */ +function parseCookies(header) { + const out = {}; + if (!header) return out; + for (const part of header.split(';')) { + const [k, ...rest] = part.trim().split('='); + if (k) out[k.trim()] = rest.join('=').trim(); + } + return out; +} + +/** Build a Set-Cookie header value. */ +function setCookie(name, value, opts = {}) { + let c = `${name}=${value}; Path=${opts.path || '/'}`; + if (opts.httpOnly) c += '; HttpOnly'; + if (opts.sameSite) c += `; SameSite=${opts.sameSite}`; + if (opts.partitioned) c += '; Partitioned'; + if (opts.maxAge !== undefined) c += `; Max-Age=${opts.maxAge}`; + return c; +} + +/** Build a Set-Cookie header that clears a cookie. */ +function clearCookie(name, path = '/') { + return `${name}=; Path=${path}; Max-Age=0`; +} + +// --------------------------------------------------------------------------- +// Request body helper +// --------------------------------------------------------------------------- + +function readBody(req) { + return new Promise((resolve) => { + let data = ''; + req.on('data', (chunk) => (data += chunk)); + req.on('end', () => resolve(data)); + }); +} + +// --------------------------------------------------------------------------- +// Route handlers +// --------------------------------------------------------------------------- + +function handleRoot(req, res) { + const body = ` +

This demo app simulates five auth variants from PRD §13.6.

+ +

Use POST /login?variant=<v>&user=<name> to log in.

`; + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('Sessionist Demo App', body)); +} + +// (a) Single-origin cookie-session +function handleCookieSession(req, res) { + const cookies = parseCookies(req.headers['cookie']); + const user = cookies['sess_user'] || null; + const loggedIn = Boolean(user); + + const body = ` +
+ ${loggedIn ? `Logged in as ${user}` : 'Not logged in'} +
+

Auth method: session cookie (sess_user)

+
+ + +
+
+ +
`; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('(a) Cookie-Session App', body)); +} + +// (b) Multi-domain SSO simulation +// We simulate multi-domain by using two cookie names on different paths. +function handleMultiDomainSSO(req, res) { + const cookies = parseCookies(req.headers['cookie']); + const appUser = cookies['sso_app_user'] || null; + const authToken = cookies['sso_auth_token'] || null; + const loggedIn = Boolean(appUser && authToken); + + const body = ` +
+ ${ + loggedIn + ? `Logged in as ${appUser} (auth token present)` + : 'Not logged in — both app cookie and auth token required' + } +
+

Auth method: sso_app_user + sso_auth_token cookies (simulates multi-domain scope)

+
+ + +
+
+ +
`; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('(b) Multi-Domain SSO App', body)); +} + +// (c) localStorage SPA +// Auth token is stored in localStorage by the page itself. +function handleLocalStorageSPA(req, res) { + const body = ` +
+ Checking localStorage… +
+

Auth method: localStorage.sessionist_ls_token

+ + + `; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('(c) localStorage SPA', body)); +} + +// (d) CHIPS / partitioned-cookie +function handleCHIPS(req, res) { + const cookies = parseCookies(req.headers['cookie']); + const user = cookies['chips_user'] || null; + const loggedIn = Boolean(user); + + const body = ` +
+ ${loggedIn ? `Logged in as ${user}` : 'Not logged in'} +
+

Auth method: chips_user cookie (Partitioned / CHIPS flag set)

+

Note: CHIPS cookies are partitioned by top-level site. The Partitioned flag + is set in Set-Cookie; whether it is honoured depends on browser support and + the embedding context.

+
+ + +
+
+ +
`; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('(d) CHIPS / Partitioned-Cookie App', body)); +} + +// (e) IndexedDB token — auth intentionally NOT captured by Sessionist +function handleIndexedDB(req, res) { + const body = ` +
+ Checking IndexedDB… +
+

Auth method: IndexedDB — "sessionist-demo" / "auth" store

+

Important: Sessionist MVP does not capture IndexedDB auth tokens. + This scenario must show "not captured" in the UI and fail loudly — not silently + half-switch. See PRD §9.2 and §13.6(e).

+ + + `; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('(e) IndexedDB-Token App', body)); +} + +// --------------------------------------------------------------------------- +// SSO /sso path: used by multi-domain-sso sso_auth_token cookie (path=/sso) +// This page is a minimal status page so the /sso path returns 200 not 404. +// --------------------------------------------------------------------------- +function handleSSOPath(req, res) { + const cookies = parseCookies(req.headers['cookie']); + const authToken = cookies['sso_auth_token'] || null; + const body = ` +
+ ${authToken ? `SSO auth token present: ${authToken}` : 'No SSO auth token'} +
`; + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('SSO Auth Domain', body)); +} + +// JSON status endpoint — returns auth state readable by Playwright assertions +// without having to parse HTML. +function handleStatus(req, res) { + const cookies = parseCookies(req.headers['cookie']); + const status = { + cookieSession: { + loggedIn: Boolean(cookies['sess_user']), + user: cookies['sess_user'] || null, + }, + multiDomainSSO: { + loggedIn: Boolean(cookies['sso_app_user'] && cookies['sso_auth_token']), + user: cookies['sso_app_user'] || null, + }, + chipsCookie: { + loggedIn: Boolean(cookies['chips_user']), + user: cookies['chips_user'] || null, + }, + // localStorage and IndexedDB cannot be read server-side; clients must check + // the respective page DOM or localStorage directly. + }; + res.writeHead(200, { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + }); + res.end(JSON.stringify(status, null, 2)); +} + +// --------------------------------------------------------------------------- +// Login / logout POST handlers +// --------------------------------------------------------------------------- + +async function handleLogin(req, res, query) { + await readBody(req); // consume body (form data) + const params = new URLSearchParams(query.search || ''); + const variant = params.get('variant') || 'cookie-session'; + // Extract user from URL params (fallback to form body parsing is omitted for + // brevity — tests drive login via query string). + const user = params.get('user') || 'testuser'; + + const headers = { Location: `/${variant}` }; + + switch (variant) { + case 'cookie-session': + headers['Set-Cookie'] = setCookie('sess_user', user, { httpOnly: true, sameSite: 'Lax' }); + break; + case 'multi-domain-sso': + headers['Set-Cookie'] = [ + setCookie('sso_app_user', user, { httpOnly: true, sameSite: 'Lax' }), + setCookie('sso_auth_token', 'tok-' + Math.random().toString(36).slice(2), { + httpOnly: true, + sameSite: 'Lax', + path: '/sso', + }), + ]; + break; + case 'chips-cookie': + headers['Set-Cookie'] = setCookie('chips_user', user, { + sameSite: 'None', + partitioned: true, + // Secure would normally be required but localhost exempts it: + }); + break; + default: + break; + } + + res.writeHead(302, headers); + res.end(); +} + +async function handleLogout(req, res, query) { + await readBody(req); + const params = new URLSearchParams(query.search || ''); + const variant = params.get('variant') || 'cookie-session'; + + const headers = { Location: `/${variant}` }; + + switch (variant) { + case 'cookie-session': + headers['Set-Cookie'] = clearCookie('sess_user'); + break; + case 'multi-domain-sso': + headers['Set-Cookie'] = [clearCookie('sso_app_user'), clearCookie('sso_auth_token', '/sso')]; + break; + case 'chips-cookie': + headers['Set-Cookie'] = clearCookie('chips_user'); + break; + default: + break; + } + + res.writeHead(302, headers); + res.end(); +} + +// --------------------------------------------------------------------------- +// Router +// --------------------------------------------------------------------------- + +async function router(req, res) { + const parsed = url.parse(req.url || '/', true); + const pathname = parsed.pathname || '/'; + const method = req.method || 'GET'; + + // CORS preflight + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); + if (method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + if (method === 'GET') { + switch (pathname) { + case '/': + return handleRoot(req, res); + case '/cookie-session': + return handleCookieSession(req, res); + case '/multi-domain-sso': + return handleMultiDomainSSO(req, res); + case '/localstorage-spa': + return handleLocalStorageSPA(req, res); + case '/chips-cookie': + return handleCHIPS(req, res); + case '/indexeddb-token': + return handleIndexedDB(req, res); + case '/sso': + // SSO second-domain path — hosts the sso_auth_token cookie (path=/sso). + return handleSSOPath(req, res); + case '/status': + return handleStatus(req, res); + case '/login': + // GET /login?variant=&user= — convenience redirect for Playwright + // (avoids needing to send a POST; tests can use page.goto). + return handleLogin(req, res, parsed); + case '/logout': + // GET /logout?variant= — convenience redirect (mirrors POST /logout). + return handleLogout(req, res, parsed); + default: + res.writeHead(404, { 'Content-Type': 'text/plain' }); + return res.end('Not found'); + } + } + + if (method === 'POST') { + switch (pathname) { + case '/login': + return handleLogin(req, res, parsed); + case '/logout': + return handleLogout(req, res, parsed); + default: + res.writeHead(404, { 'Content-Type': 'text/plain' }); + return res.end('Not found'); + } + } + + res.writeHead(405, { 'Content-Type': 'text/plain' }); + res.end('Method not allowed'); +} + +// --------------------------------------------------------------------------- +// Start +// --------------------------------------------------------------------------- + +const server = http.createServer((req, res) => { + router(req, res).catch((err) => { + console.error('[demo-app] Error:', err); + if (!res.headersSent) { + res.writeHead(500, { 'Content-Type': 'text/plain' }); + res.end('Internal server error'); + } + }); +}); + +server.listen(PORT, '127.0.0.1', () => { + console.log(`[demo-app] Listening on http://localhost:${PORT}`); +}); + +// Graceful shutdown +process.on('SIGTERM', () => server.close()); +process.on('SIGINT', () => server.close()); diff --git a/e2e/fixtures/extension.ts b/e2e/fixtures/extension.ts new file mode 100644 index 0000000..d986aae --- /dev/null +++ b/e2e/fixtures/extension.ts @@ -0,0 +1,138 @@ +/** + * Playwright fixture: extensionFixture + * + * Launches a persistent browser context with the Sessionist MV3 extension + * loaded and exposes: + * - `extensionId` — the chrome-extension:// ID assigned at runtime + * - `sidepanelUrl` — chrome-extension:///sidepanel.html + * - `context` — the persistent BrowserContext (use for cookie/storage ops) + * - `openSidePanel(page?)` — navigate an existing page (or open a new one) to + * the side panel URL and return it + * - `demoOrigin` — base URL of the local demo app (from DEMO_PORT env) + * + * Usage: + * import { test } from '../fixtures/extension'; + * test('my spec', async ({ extensionId, context, openSidePanel }) => { ... }); + * + * Why persistent context? + * Regular browser.newContext() does not load extensions. Only + * chromium.launchPersistentContext() with --load-extension gives access to + * chrome.* APIs and the extension's service worker. + * + * Extension ID discovery: + * After the context launches, we navigate to chrome://extensions/ and read the + * extension ID from the DOM. An alternative (used here) is to open + * chrome://extensions/ via the extensions management API or look for the + * service-worker registration — both require the extension to have already + * loaded. We use the background page / service worker URL approach: + * context.serviceWorkers() becomes non-empty once the MV3 service worker + * starts; we derive the ID from its URL. + */ + +import path from 'path'; +import { test as base, chromium, type BrowserContext, type Page } from '@playwright/test'; + +const EXTENSION_PATH = path.resolve('.output/chrome-mv3'); +const DEMO_PORT = process.env['DEMO_PORT'] ?? '4321'; +export const DEMO_ORIGIN = `http://localhost:${DEMO_PORT}`; + +export type ExtensionFixtures = { + /** Chrome extension ID (e.g. "abcdefghijklmnopqrstuvwxyzabcdef") */ + extensionId: string; + /** Full chrome-extension://…/sidepanel.html URL */ + sidepanelUrl: string; + /** The persistent BrowserContext that has the extension loaded */ + context: BrowserContext; + /** + * Open the Sessionist side panel in a new (or given) page. + * Returns the page pointed at sidepanel.html. + */ + openSidePanel: (page?: Page) => Promise; + /** Base URL of the local demo app */ + demoOrigin: string; +}; + +/** + * Derive the extension ID from a service-worker URL. + * SW URL format: chrome-extension:///background.js (or similar) + */ +function idFromSwUrl(url: string): string { + const match = /^chrome-extension:\/\/([a-z]{32})\//.exec(url); + if (!match || !match[1]) throw new Error(`Cannot parse extension ID from SW URL: ${url}`); + return match[1]; +} + +export const test = base.extend({ + // eslint-disable-next-line no-empty-pattern + context: async ({}, use) => { + /** + * Each test worker gets its own temporary user-data-dir so that extension + * state does not bleed between tests. Playwright will clean up the dir. + */ + const userDataDir = ''; // empty string → Playwright creates a temp dir + const ctx = await chromium.launchPersistentContext(userDataDir, { + headless: process.env['HEADLESS'] === 'true', + args: [ + `--disable-extensions-except=${EXTENSION_PATH}`, + `--load-extension=${EXTENSION_PATH}`, + '--no-sandbox', + '--disable-infobars', + '--disable-features=ExtensionDisabling', + ], + // Allow Playwright to detect the MV3 service worker: + ignoreHTTPSErrors: true, + }); + + await use(ctx); + await ctx.close(); + }, + + extensionId: async ({ context }, use) => { + /** + * Wait for the extension service worker to register. MV3 extensions use + * service workers instead of background pages. + * + * Playwright exposes context.serviceWorkers() and the 'serviceworker' event. + * We wait up to 10 s for at least one SW that looks like the extension. + */ + let sw = context.serviceWorkers().find((s) => s.url().startsWith('chrome-extension://')); + + if (!sw) { + sw = await Promise.race([ + new Promise((resolve) => { + context.on('serviceworker', (worker) => { + if (worker.url().startsWith('chrome-extension://')) resolve(worker); + }); + }), + new Promise((_, reject) => + setTimeout( + () => reject(new Error('Extension service worker did not start within 10s')), + 10_000, + ), + ), + ]); + } + + const id = idFromSwUrl(sw.url()); + await use(id); + }, + + sidepanelUrl: async ({ extensionId }, use) => { + await use(`chrome-extension://${extensionId}/sidepanel.html`); + }, + + openSidePanel: async ({ context, sidepanelUrl }, use) => { + const helper = async (page?: Page): Promise => { + const target = page ?? (await context.newPage()); + await target.goto(sidepanelUrl, { waitUntil: 'domcontentloaded' }); + return target; + }; + await use(helper); + }, + + demoOrigin: async ({}, use) => { + await use(DEMO_ORIGIN); + }, +}); + +export { expect } from '@playwright/test'; diff --git a/e2e/onboarding.spec.ts b/e2e/onboarding.spec.ts new file mode 100644 index 0000000..113fd15 --- /dev/null +++ b/e2e/onboarding.spec.ts @@ -0,0 +1,193 @@ +/** + * onboarding.spec.ts + * + * Covers PRD §9.5 (Search-intent onboarding) and §10 UX flow 1 + * (Replacement import). + * + * These tests are RED until the extension features are implemented. + * The tests intentionally assert against a working extension; they document + * the required behaviour rather than verifying it today. + * + * PRD acceptance criteria tested here: + * - §9.5: First-run shows onboarding UI (not the main editor) + * - §9.5: "Import cookies" CTA is visible (addresses replacement users) + * - §9.5: "Capture this session" CTA is visible (addresses dev/QA users) + * - §9.5: Copy "Coming from EditThisCookie…" is visible on the welcome screen + * - §9.5: No signup is required to proceed + * - §10 flow 1: import JSON → cookies appear → edit as before (< 30 s) + * - §9.5 / Settings: "Show welcome again" resets and navigates to onboarding + * + * Selector notes (must match OnboardingView.tsx and SettingsView.tsx): + * - data-testid="onboarding-view" — must be added to OnboardingView.tsx + * - data-testid="cookie-editor-view" — must be added to CookieEditorView.tsx + * - Button "Import cookies" — in OnboardingView.tsx + * - Button "Capture this session" — in OnboardingView.tsx + * - Button "Show welcome again" — in SettingsView.tsx + * - Text "Coming from EditThisCookie or another cookie editor?" — in OnboardingView.tsx + * + * Left to unit tests: + * - JSON parsing correctness for specific cookie-editor formats + * - Individual cookie field mapping + */ + +import { test, expect } from './fixtures/extension'; + +test.describe('Onboarding — first-run flow (§9.5 / §10 flow 1)', () => { + test('side panel shows onboarding view on first run, not the main editor', async ({ + openSidePanel, + }) => { + // On first run (no profiles, no settings) the extension must present the + // onboarding / welcome screen, not dump the user straight into the editor. + const panel = await openSidePanel(); + + // The onboarding container must be present. + const onboarding = panel.getByTestId('onboarding-view'); + await expect(onboarding).toBeVisible({ timeout: 10_000 }); + + // The main profiles / cookie-editor view must NOT be the initial focus. + // It may be present in the DOM but should not be the active/first view. + const mainEditor = panel.getByTestId('cookie-editor-view'); + await expect(mainEditor).not.toBeVisible(); + }); + + test('onboarding shows "Import cookies" CTA for replacement users', async ({ openSidePanel }) => { + const panel = await openSidePanel(); + // OnboardingView.tsx button: "Import cookies" + const importCta = panel.getByRole('button', { name: /import cookies/i }); + await expect(importCta).toBeVisible({ timeout: 10_000 }); + }); + + test('onboarding shows "Capture this session" CTA for dev/QA users', async ({ + openSidePanel, + }) => { + const panel = await openSidePanel(); + // OnboardingView.tsx primary button: "Capture this session" + const captureCta = panel.getByRole('button', { name: /capture this session/i }); + await expect(captureCta).toBeVisible({ timeout: 10_000 }); + }); + + test('no sign-up prompt or modal blocks the onboarding flow', async ({ openSidePanel }) => { + const panel = await openSidePanel(); + // There must be no sign-in / create account dialog visible at first run. + const signupModal = panel.getByRole('dialog', { name: /sign.?up|create account|log in/i }); + await expect(signupModal).not.toBeVisible({ timeout: 5_000 }); + }); + + test('replacement import flow — clicking "Import cookies" leads to cookie editor (§10 flow 1)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // Navigate to the demo app first so there is an active tab for the extension + // to work with. + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(); + + // Click the import CTA. + const importCta = panel.getByRole('button', { name: /import cookies/i }); + await importCta.click(); + + // Clicking "Import cookies" should navigate to the cookie editor view. + // The cookie editor's "Import" button should then open the JSON paste form. + const cookieEditorView = panel.getByTestId('cookie-editor-view'); + await expect(cookieEditorView).toBeVisible({ timeout: 10_000 }); + }); + + test('replacement import: pasting EditThisCookie JSON shows imported cookie (§10 flow 1)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // Full §10 flow 1: import JSON → cookies appear → edit as before. + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(); + + // Navigate to the cookie editor via the import CTA. + await panel.getByRole('button', { name: /import cookies/i }).click(); + + // Grant access if needed. + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) await grantBtn.click(); + + // Open the cookie import form. + const importBtn = panel.getByRole('button', { name: /^import$/i }); + await importBtn.click(); + + // Paste an EditThisCookie-compatible JSON payload. + const cookieJson = JSON.stringify([ + { + name: 'imported_session', + value: 'abc123', + domain: 'localhost', + path: '/', + secure: false, + httpOnly: false, + expirationDate: Math.floor(Date.now() / 1000) + 3600, + sameSite: 'Lax', + }, + ]); + + // The cookie import textarea (aria-label: "Cookie import JSON"). + const jsonInput = panel + .getByRole('textbox', { name: /cookie import json/i }) + .or(panel.getByTestId('cookie-import-textarea')); + await jsonInput.fill(cookieJson); + + const confirmBtn = panel.getByRole('button', { name: /^import$/i }).last(); + await confirmBtn.click(); + + // After import the cookie list should show the imported cookie. + const cookieList = panel.getByTestId('cookie-list'); + await expect(cookieList.getByText('imported_session')).toBeVisible({ timeout: 10_000 }); + }); + + test('empty-state copy addresses replacement users without overclaiming (§9.5)', async ({ + openSidePanel, + }) => { + const panel = await openSidePanel(); + // PRD §9.5 mandates copy: "Coming from EditThisCookie or another cookie editor?" + // OnboardingView.tsx:

Coming from EditThisCookie or another cookie editor?

+ const copy = panel.getByText(/coming from editthiscookie/i); + await expect(copy).toBeVisible({ timeout: 10_000 }); + }); + + test('"Capture this session" CTA navigates to profiles view (§9.5)', async ({ + openSidePanel, + }) => { + const panel = await openSidePanel(); + + await panel.getByRole('button', { name: /capture this session/i }).click(); + + // OnboardingView.proceed('profiles') → setView('profiles') → ProfilesView. + const profilesHeading = panel.getByRole('heading', { name: /session profiles/i }); + await expect(profilesHeading).toBeVisible({ timeout: 10_000 }); + }); + + test('first-run onboarding does not require signup (no account required)', async ({ + openSidePanel, + demoOrigin, + context, + }) => { + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + const panel = await openSidePanel(); + + // The user must be able to proceed to either core workflow without being + // asked to create an account or log in. + const importCta = panel.getByRole('button', { name: /import cookies/i }); + await expect(importCta).toBeVisible({ timeout: 10_000 }); + await importCta.click(); + + // Must reach the cookie editor without any account/login barrier. + const cookieEditorView = panel.getByTestId('cookie-editor-view'); + await expect(cookieEditorView).toBeVisible({ timeout: 10_000 }); + + // No login prompt / gate should appear. + const loginModal = panel.getByRole('dialog', { name: /log in|sign up/i }); + await expect(loginModal).not.toBeVisible({ timeout: 3_000 }); + }); +}); diff --git a/e2e/paywall.spec.ts b/e2e/paywall.spec.ts new file mode 100644 index 0000000..e0d76e8 --- /dev/null +++ b/e2e/paywall.spec.ts @@ -0,0 +1,319 @@ +/** + * paywall.spec.ts + * + * Covers PRD §10 UX flow 5 (Hit the wall → paywall/upgrade) and §10 flow 6 + * (Team — P2, placeholder only). + * + * These tests are RED until the extension features are implemented. + * + * PRD acceptance criteria tested here: + * - §10 flow 5: Attempting to save a 4th profile triggers an inline upsell + * (UpgradeView) at a usage milestone, not a hard error at save #4. + * - §10 flow 5: The upsell lists Pro features (unlimited profiles, etc.). + * - §10 flow 5: "Upgrade to Pro" button opens the Stripe checkout URL in a + * new tab. + * - §10 flow 5: Pro-gated export targets (Puppeteer, Selenium, cURL) redirect + * to the upgrade view for free users rather than silently failing. + * - §10 flow 6: Team is P2 — spec is annotated and skipped pending validation. + * + * Left to unit tests: + * - entitlementService: profile-cap enforcement logic. + * - profiles/shouldPromptUpsell: threshold computation. + * - entitlement/startCheckout: checkout URL generation. + * - Ed25519 license-key verification. + */ + +import { test, expect } from './fixtures/extension'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** + * Grant access and capture a named profile from the cookie-session demo app. + * Lightweight version of the captureProfile helper used in other specs. + */ +async function captureProfileFromCookieApp( + panel: import('@playwright/test').Page, + profileName: string, +): Promise { + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + // Grant permission if the prompt appears. + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + + const nameInput = panel.getByRole('textbox', { name: /profile name/i }); + await nameInput.fill(profileName); + await panel.getByRole('button', { name: /save/i }).click(); + + await expect(panel.getByText(profileName)).toBeVisible({ timeout: 10_000 }); +} + +// --------------------------------------------------------------------------- +// §10 flow 5 — Hit the wall: save a 4th profile → inline upsell +// --------------------------------------------------------------------------- + +test.describe('Paywall — §10 flow 5: usage-milestone upsell', () => { + test('saving a 4th profile navigates to the upgrade view (upsell milestone)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + + // Capture the first 3 profiles (within the free limit). + for (const name of ['Profile-1', 'Profile-2', 'Profile-3']) { + await captureProfileFromCookieApp(panel, name); + } + + // Capture a 4th profile — this must trigger the usage-milestone upsell. + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + + const nameInput = panel.getByRole('textbox', { name: /profile name/i }); + await nameInput.fill('Profile-4'); + await panel.getByRole('button', { name: /save/i }).click(); + + // After the 4th save, the extension must show the upgrade/upsell view. + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).toBeVisible({ timeout: 15_000 }); + }); + + test('upgrade view lists Pro features (unlimited profiles, bulk export, etc.)', async ({ + openSidePanel, + }) => { + const panel = await openSidePanel(); + + // Navigate directly to the upgrade view via the nav if exposed, + // or via the "upgrade" view programmatically. + // The upgrade view is at view='upgrade' in the store. + // We reach it by navigating to a page that triggers it, or by finding + // an upgrade CTA. For this assertion-only test, we look for the view. + // If the upgrade view is not directly navigable via the nav, this test + // will be reached only via the paywall flow. We assert its content + // here in isolation by navigating to the Profiles view and checking + // the view component renders when appropriate. + // + // Alternate path: if an "Upgrade" or "Pro" nav link exists, click it. + const upgradeNav = panel.getByRole('button', { name: /upgrade|pro/i }); + if (await upgradeNav.isVisible({ timeout: 3_000 }).catch(() => false)) { + await upgradeNav.click(); + } else { + // Skip checking view content if we can't reach it without hitting the wall. + test.skip(true, 'Upgrade view only reachable via paywall flow in this context'); + return; + } + + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).toBeVisible({ timeout: 10_000 }); + + // PRD §11.1 Pro features that must be listed. + await expect(upgradeView.getByText(/unlimited.*profile|unlimited session/i)).toBeVisible(); + await expect(upgradeView.getByText(/\$29/i)).toBeVisible(); + }); + + test('upgrade view has "Upgrade to Pro" button', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + + // Fill to 4 profiles to trigger the paywall. + for (const name of ['Wall-1', 'Wall-2', 'Wall-3']) { + await captureProfileFromCookieApp(panel, name); + } + + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + + await panel.getByRole('textbox', { name: /profile name/i }).fill('Wall-4'); + await panel.getByRole('button', { name: /save/i }).click(); + + // Upgrade view must show the checkout button. + const upgradeBtn = panel.getByRole('button', { name: /upgrade to pro/i }); + await expect(upgradeBtn).toBeVisible({ timeout: 15_000 }); + // Must be enabled (not greyed out) so the user can act. + await expect(upgradeBtn).toBeEnabled(); + }); + + test('Pro-gated export targets redirect free users to upgrade view', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + await captureProfileFromCookieApp(panel, 'ExportGating-Alice'); + + // Navigate to the Export view. + await panel.getByRole('button', { name: /^export$/i }).click(); + const exportPanel = panel.getByRole('heading', { name: /export/i }); + await expect(exportPanel).toBeVisible({ timeout: 10_000 }); + + // Clicking a Pro-gated export format (Puppeteer) must redirect to upgrade. + await panel.getByRole('button', { name: /puppeteer/i }).click(); + + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).toBeVisible({ timeout: 10_000 }); + }); + + test('Pro-gated Selenium export redirects free users to upgrade view', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + await captureProfileFromCookieApp(panel, 'ExportGating-Selenium'); + + await panel.getByRole('button', { name: /^export$/i }).click(); + await expect(panel.getByRole('heading', { name: /export/i })).toBeVisible({ timeout: 10_000 }); + + await panel.getByRole('button', { name: /selenium/i }).click(); + + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).toBeVisible({ timeout: 10_000 }); + }); + + test('Pro-gated cURL export redirects free users to upgrade view', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + await captureProfileFromCookieApp(panel, 'ExportGating-cURL'); + + await panel.getByRole('button', { name: /^export$/i }).click(); + await expect(panel.getByRole('heading', { name: /export/i })).toBeVisible({ timeout: 10_000 }); + + await panel.getByRole('button', { name: /curl/i }).click(); + + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).toBeVisible({ timeout: 10_000 }); + }); + + test('Playwright storageState export (free) does NOT redirect to upgrade view', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // PRD §11.1: Playwright export is FREE in MVP. Verify the gating is correct. + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + await captureProfileFromCookieApp(panel, 'FreeTierExport-Alice'); + + await panel.getByRole('button', { name: /^export$/i }).click(); + await expect(panel.getByRole('heading', { name: /export/i })).toBeVisible({ timeout: 10_000 }); + + // Click the Playwright export button. + await panel.getByRole('button', { name: /playwright storageState/i }).click(); + + // Must NOT navigate to upgrade view. + const upgradeView = panel.getByTestId('upgrade-view'); + await expect(upgradeView).not.toBeVisible({ timeout: 3_000 }); + + // Must show output in the export textarea. + const exportOutput = panel.getByRole('textbox', { name: /export output/i }); + await expect(exportOutput).toBeVisible({ timeout: 10_000 }); + }); + + test('upgrade view shows correct price ($29 one-time)', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const page = await context.newPage(); + await page.goto(`${demoOrigin}/login?variant=cookie-session&user=alice`); + await page.waitForURL(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(page); + + // Trigger the paywall. + for (const name of ['Price-1', 'Price-2', 'Price-3']) { + await captureProfileFromCookieApp(panel, name); + } + + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + if (await grantBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await grantBtn.click(); + } + + await panel.getByRole('textbox', { name: /profile name/i }).fill('Price-4'); + await panel.getByRole('button', { name: /save/i }).click(); + + // Price must be displayed correctly per PRD §11.1. + await expect(panel.getByText(/\$29/i)).toBeVisible({ timeout: 15_000 }); + await expect(panel.getByText(/one.?time/i)).toBeVisible(); + }); +}); + +// --------------------------------------------------------------------------- +// §10 flow 6 — Team sync & shared vaults (P2) +// --------------------------------------------------------------------------- + +test.describe('Team sync — §10 flow 6 (P2 placeholder)', () => { + test.skip( + true, + 'Team is P2 — build only after install, repeat usage, and Pro-conversion demand are validated (PRD §9.7 / §2.2). ' + + 'This placeholder keeps the flow in the spec tree so it turns green automatically when Team ships.', + ); + + // ─── Team acceptance criteria to implement at P2 ─────────────────────── + // PRD §9.7 / §10 flow 6: + // + // test('Share profile → invite teammates → teammate receives shared profile', async () => { + // // 1. Logged-in Pro/Team user has a saved profile. + // // 2. Clicks "Share profile" → enter teammate email → sends invite. + // // 3. Teammate installs extension → joins vault → profile appears. + // // 4. Server stores only ciphertext; no plaintext session data. + // }); + // + // test('revoking a team member prevents future access to newly shared material', async () => { + // // PRD §9.7: revocation prevents future access but cannot claw back + // // already-decrypted/exported data. + // }); + // + // test('audit log records shared-profile events without plaintext session content', async () => { + // // PRD §9.7 audit log requirement. + // }); + // ─────────────────────────────────────────────────────────────────────── +}); diff --git a/e2e/permission.spec.ts b/e2e/permission.spec.ts new file mode 100644 index 0000000..0e9bdb8 --- /dev/null +++ b/e2e/permission.spec.ts @@ -0,0 +1,191 @@ +/** + * permission.spec.ts + * + * Covers PRD §9.6 (Permission UX) and §10 UX flow 2 (Site permission). + * + * These tests are RED until the extension features are implemented. + * + * PRD acceptance criteria tested here: + * - §9.6: Acting on a site triggers a per-origin grant prompt (not silent) + * - §9.6: Granted origins are stored and shown in "Site access" settings + * - §9.6: User can revoke a previously granted origin + * - §9.6: Declining permission shows a graceful explanation, not an error + * - §9.6: Extension remains usable for already-granted sites after a decline + * - Extension manifest has no at install time (§14.1) + * + * Left to unit tests: + * - permissionService internal grant/revoke logic + * - chrome.permissions.request mocking + * - Persistence of granted-origins list in storage + */ + +import { test, expect } from './fixtures/extension'; + +test.describe('Permission UX — per-origin grant flow (§9.6 / §10 flow 2)', () => { + test('manifest has no install-time host_permissions', async ({ context }) => { + // Open the extension details page and check the manifest loaded into the + // extension's background service worker. We cannot easily read the manifest + // file from inside a test, but we can verify via the extensions management + // page that no broad host permission was requested at install. + // + // The authoritative check is the built manifest.json in .output/chrome-mv3/. + // We perform a runtime check here by verifying the extension does NOT have + // access to an arbitrary site without a grant. + + // Create a new page navigated to a site that was never granted. + const page = await context.newPage(); + await page.goto('about:blank'); + + // If the extension had , it could access this page's cookies + // immediately. We verify it does NOT by checking that the extension's + // cookie-capture trigger fails gracefully. + // + // In practice this assertion will be more nuanced once the extension is + // implemented; for now we ensure the page loads without the extension + // injecting unexpected scripts. + const injectedMarker = await page.evaluate(() => + document.documentElement.getAttribute('data-sessionist-injected'), + ); + expect(injectedMarker).toBeNull(); + }); + + test('clicking "Capture session" on an ungranted site shows permission prompt', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // Navigate to the demo app (a site the extension has not been granted). + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(demoPage); + + // The capture button should be visible. + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + // Sessionist must show a permission-request UI — either: + // (a) a dialog/modal explaining what access is needed, or + // (b) the browser's native permission dialog (cannot assert from Playwright + // in MV3 unless we grant it programmatically). + // + // We assert on the in-extension permission step (option a): + const permissionStep = panel.getByTestId('permission-prompt'); + await expect(permissionStep).toBeVisible({ timeout: 10_000 }); + + // The prompt must explain what access is for. + const promptText = panel.getByText(/allow sessionist/i); + await expect(promptText).toBeVisible(); + + // Domain/origin must be shown explicitly. + const originText = panel.getByText(/localhost/i); + await expect(originText).toBeVisible(); + }); + + test('granted origin appears in Site Access settings list', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(demoPage); + + // Grant access (simulate the user accepting the permission prompt). + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + await grantBtn.click(); + + // Navigate to site-access settings. + const settingsBtn = panel.getByRole('button', { name: /settings|site access/i }); + await settingsBtn.click(); + + const siteAccessView = panel.getByTestId('site-access-view'); + await expect(siteAccessView).toBeVisible({ timeout: 10_000 }); + + // The granted origin must appear in the list. + const grantedOrigin = siteAccessView.getByText(/localhost/i); + await expect(grantedOrigin).toBeVisible(); + }); + + test('user can revoke a previously granted origin', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(demoPage); + + // Grant access. + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + const grantBtn = panel.getByRole('button', { name: /grant|allow/i }); + await grantBtn.click(); + + // Go to site access settings and revoke. + const settingsBtn = panel.getByRole('button', { name: /settings|site access/i }); + await settingsBtn.click(); + + const siteAccessView = panel.getByTestId('site-access-view'); + const revokeBtn = siteAccessView.getByRole('button', { name: /revoke|remove/i }).first(); + await revokeBtn.click(); + + // After revoke, the origin should no longer appear in the list. + const grantedOrigin = siteAccessView.getByText(/localhost/i); + await expect(grantedOrigin).not.toBeVisible({ timeout: 5_000 }); + }); + + test('declining permission shows graceful explanation, not an error', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + const demoPage = await context.newPage(); + await demoPage.goto(`${demoOrigin}/cookie-session`); + + const panel = await openSidePanel(demoPage); + + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + + // Decline the permission. + const declineBtn = panel.getByRole('button', { name: /cancel|deny|decline/i }); + await declineBtn.click(); + + // Must show an explanation, not a thrown error or blank screen. + const explanation = panel.getByTestId('permission-declined-notice'); + await expect(explanation).toBeVisible({ timeout: 10_000 }); + + // The extension UI must still be usable (no crash / white screen). + await expect( + panel.getByTestId('onboarding-view').or(panel.getByTestId('cookie-editor-view')), + ).toBeVisible(); + }); + + test('extension remains usable for already-granted sites after a new-site decline', async ({ + context, + openSidePanel, + demoOrigin, + }) => { + // First grant localhost. + const page1 = await context.newPage(); + await page1.goto(`${demoOrigin}/cookie-session`); + const panel = await openSidePanel(page1); + const captureBtn = panel.getByRole('button', { name: /capture current|capture session/i }); + await captureBtn.click(); + await panel.getByRole('button', { name: /grant|allow/i }).click(); + + // Now navigate to a different origin (simulate by using a different path that + // the extension treats as a different origin — or simply close and reopen). + // For the test, we assert the panel still shows the granted site data. + const siteSection = panel + .getByTestId('site-access-view') + .or(panel.getByTestId('profiles-view')); + await expect(siteSection).toBeVisible({ timeout: 10_000 }); + }); +}); diff --git a/e2e/playwright-export.spec.ts b/e2e/playwright-export.spec.ts new file mode 100644 index 0000000..fe4ccad --- /dev/null +++ b/e2e/playwright-export.spec.ts @@ -0,0 +1,509 @@ +/** + * playwright-export.spec.ts + * + * Covers PRD §9.3 (Playwright export — MVP) and §13.7 (Playwright export + * implementation), specifically the §13.7 acceptance criterion: + * + * "E2E tests should verify that generated state authenticates against a + * controlled demo app." + * + * And §9.3 acceptance: + * + * "A generated Playwright storageState file can be used by a Playwright test + * fixture to authenticate against the same app without manually re-running + * the login flow, assuming that app's auth state is represented by supported + * exported stores." + * + * CAPSTONE TEST: playwright-export.spec.ts is the §13.7 storageState round- + * trip test. It: + * 1. Logs into the demo app and captures a profile. + * 2. Exports the profile as storageState JSON via the extension UI. + * 3. Writes the JSON to a temp file. + * 4. Opens a brand-new Playwright context using storageState: . + * 5. Navigates to the demo app and asserts it shows "logged in" WITHOUT any + * login interaction — the storageState alone provides authentication. + * + * These tests are RED until the extension features are implemented. + * + * Selector notes (must match ExportView.tsx): + * - Navigate to the Export tab via the nav button "Export". + * - Select profile via the