Files
Stirling-PDF/frontend/portal/src/api/http.test.ts
T
ConnorYohandJames Brunton 14245d33d1 feat(saas): account-link — connected self-hosted billing (Mode A) [WIP, flag-gated] (#6738)
> **Draft / WIP.** Combined-billing **Mode A** (connected self-hosted).
Entirely behind `stirling.billing.account-link.enabled` (default **off**
→ beans absent → 404). Pairs with Stirling-PDF-SaaS PR #313 (twin
migration → `v3`).

## What this does

A self-hosted instance links a SaaS account in the **Portal**, gets a
**device credential**, and authenticates unattended metering/entitlement
with it — no long-lived user JWT on the server. The Portal then surfaces
the team's **billing** (free trial → metered Processor plan) driven by
the live wallet.

```mermaid
sequenceDiagram
  participant Portal as Portal (browser)
  participant Supa as SaaS Supabase Auth
  participant Local as Self-hosted backend
  participant SaaS as SaaS Java (app/saas)
  Portal->>Supa: signIn / signUp (Supabase JS, short-lived JWT)
  Supa-->>Portal: JWT (SDK-refreshed, stays in browser)
  Portal->>Local: hand JWT (same-origin)
  Local->>SaaS: POST /account-link/register (Bearer JWT, leader)
  SaaS-->>Local: { device_id, device_secret }  (secret once)
  Note over Local: store device_secret server-side
  loop unattended
    Local->>SaaS: /api/v1/instance/** (X-Device-Id + X-Device-Secret)
    SaaS-->>Local: entitlement / gate decision
  end
```

**Auth model:** human auth = Supabase JS (ephemeral JWT, kept for
attended portal features). Durable instance auth = a team-bound
**device_id + secret** (SHA-256 stored, shown once), non-user
`ROLE_LINKED_INSTANCE`, path-scoped to `/api/v1/instance/**`. Instance
binds to a **team**, never a user.

## Billing surface (Portal · Mode A states)

`Usage & billing` is state-driven by the link/subscription dimension and
built to the marketing designs, sharing one component layer across
states:

- **Unlinked** → link-account prompt.
- **Linked · Free** — the *Processor trial*: a one-time 500-PDF free
grant ("Process 500 PDFs free, then $X/PDF"), the team's free-editor
fleet, and a leader-only **Switch on the Processor →** (embedded Stripe
Checkout).
- **Linked · Subscribed** — the *Processor plan* dashboard:
PDFs-processed split (API / Agents / Automation), **spend this month**
vs. a **spend limit** meter with a run-rate projection and an **in-place
cap editor** (preset buckets + suggested value + guardrail), Stripe
**invoices** (with billed PDFs per invoice), and the default **payment
method**. Card / subscription changes deep-link to Stripe's hosted
portal.

Manual PDF editing is always free — only Automation / AI / API is
metered; a `$0` cap blocks all metered work (≠ "no cap").

**Shared, not duplicated:** the editor-fleet card, the Enterprise
upsell, and the meter (`@shared/billing` `MeterBar`) render in both the
free and subscribed views; money/cap math lives once in
`@shared/billing`. The page header is a sticky, full-bleed bar.

**New SaaS reads** (defensive — degrade to empty/"—" when the Stripe
mirror lacks a table, never 500):
- `GET /api/v1/payg/payment-method` — default card (brand / last4 /
expiry) from `stripe.payment_methods`.
- Invoice **PDFs processed** — billed line-item quantity from
`stripe.invoice_line_items`.

## Progress

- [x] Schema: `V22 linked_instance` (+ Supabase twin in #313)
- [x] `AccountLinkController` register / list / revoke (leader-only,
team from caller)
- [x] Device-credential filter (path-scoped, constant-time,
revocation-aware) + `SupabaseSecurityConfig` wiring (conditional)
- [x] `GET /api/v1/instance/whoami` + **`/entitlement`** (reuses
`EntitlementService`/`TeamBillingService`) + tests
- [x] Self-hosted backend (`app/proprietary`): orchestrator + instance
gate (dark + **fail-open**) + tests
- [x] Portal: in-app Supabase login modal + register hand-off +
`LinkContext` (unlinked default) + "Linked instances" view — all
`@shared` Storybook components
- [x] **Portal billing surface** — free (Processor trial) + subscribed
(Processor plan) Usage views to marketing spec; link-state derived from
the **live wallet**; in-place cap editor; over-cap banner
- [x] **SaaS reads** — payment-method endpoint + invoice billed-units
(defensive `stripe.*` mirror DAOs) + tests
- [x] Orphan guard: block leaving/accepting away from a team whose
departure orphans its linked instances
- [ ] Metering Step 2 (lease + reconcile loop) + bounded fail-open
cutoff
- [ ] Proprietary hardening (SaaS base-url config, secret-at-rest, finer
billable classification) + HTTP integration test
- [ ] Cross-repo Stripe lifecycle certified end-to-end (subscribe →
meter → cancel → 402)
- [ ] Admin ⟺ SaaS-leader enforcement (separate portal-team-mgmt
workstream)

## Verification — all green
| Gate | Result |
|---|---|
| `STIRLING_FLAVOR=saas :saas:test` | BUILD SUCCESSFUL (account-link +
payg, incl. `PaygPaymentMethodControllerTest`,
`PaygInvoicesControllerTest`) |
| `:proprietary:test` | BUILD SUCCESSFUL (account-link + entitlement
cache/interceptor) |
| portal | tsc 0 · eslint 0 · **vitest 55** · storybook build (all
billing stories) |
| frontend post-sync | typecheck shared + portal + editor (saas +
desktop): 0 |

## Screenshots — billing UI
_Latest Storybook renders (Portal/Billing). Drag each capture below its
caption — kept out of the repo._

**Linked · Free — Processor trial**


<img width="1648" height="503" alt="01-free-processor-trial"
src="https://github.com/user-attachments/assets/afe6238a-d3b4-47fd-8ea2-cbaed8b0a653"
/>

**Linked · Subscribed — Processor plan dashboard**

<img width="1648" height="930" alt="02-subscribed-processor-plan"
src="https://github.com/user-attachments/assets/329e6808-a9a9-4e65-99af-5a8a5e6bf4ab"
/>

**Spend limit — in-place cap editor**

<img width="1648" height="411" alt="03-spend-limit-editor"
src="https://github.com/user-attachments/assets/acc95096-bf8e-4ab0-a32c-3c20dc94f816"
/>


## Review feedback applied
Reworked the portal after first-pass feedback: linking signs in via the
**shared Supabase login** (SSO + email/password) — no bespoke form; the
**device secret is never shown in or sent to the FE** (the local backend
registers + stores it server-side); billing copy reads **PDFs**, not
"units"; the wallet surface uses **`@shared` components** matching the
SaaS Plan page. Re-verified including an assertion the link response
carries no `deviceSecret`/`deviceId`.

**Synced onto unified auth + in-app login (2026-06-23).** Merged `main`
incl. **#6725 unified auth** (`frontend/shared/auth`); the link flow
uses a shared `useSupabaseLogin` hook + `SupabaseLoginForm`, a portal
`LinkAccountModal`, and `useAccountLink.completeLink(session)` (+
on-mount SSO redirect-return). Config: `VITE_SAAS_SUPABASE_URL` +
`VITE_SAAS_SUPABASE_ANON_KEY`. The local `/account-link/link` call
carries the Spring admin bearer with the SaaS JWT in the body. **SSO**
needs the SaaS Supabase project to allow-list the portal redirect URL
(email/password works without it).

## Assumptions / open
- **Proprietary remains a scaffold** (placeholder SaaS base-url,
plaintext device secret at rest, coarse billable classification).
- Payment-method + invoice-quantity render only when
`stripe.payment_methods` / `stripe.invoice_line_items` are in the
Sync-Engine target (confirm in the Supabase/Sync-Engine config);
otherwise they degrade gracefully.
- A self-contained local HTML report + manual E2E runbook live in
`notes/account-link-report/` (dev artifacts, outside the repo).

---------

Co-authored-by: James Brunton <jbrunton96@gmail.com>
2026-06-29 13:35:07 +00:00

132 lines
4.2 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* api/http apiClient routing + error branches — the module exists specifically
* to make portal→backend routing explicit after /v1/billing/wallet once fell
* through to the local backend. The happy-path routing (saas hits the absolute
* base with the Supabase bearer) is covered in api/link.test.ts; here we pin the
* error/edge branches that gate the billing UI's error surface.
*/
const { getSession, getStoredTokenMock } = vi.hoisted(() => ({
getSession: vi.fn(),
getStoredTokenMock: vi.fn(),
}));
vi.mock("@shared/auth", () => ({ getStoredToken: getStoredTokenMock }));
vi.mock("@shared/auth/supabase/supabaseClient", () => ({
getSupabaseClient: () => ({ auth: { getSession } }),
configureSupabase: vi.fn(),
}));
vi.mock("@portal/auth/saasSupabase", () => ({ ensureSaasSupabase: vi.fn() }));
import {
apiClient,
HttpError,
SaasNotLinkedError,
SaasUnconfiguredError,
} from "@portal/api/http";
const fetchMock = vi.fn();
beforeEach(() => {
vi.stubGlobal("fetch", fetchMock);
fetchMock.mockReset();
getSession.mockReset();
getStoredTokenMock.mockReset();
});
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
function ok(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
describe("apiClient.saas", () => {
it("throws SaasUnconfiguredError when VITE_SAAS_API_URL is unset", async () => {
vi.stubEnv("VITE_SAAS_API_URL", "");
await expect(
apiClient.saas.json("/api/v1/payg/wallet"),
).rejects.toBeInstanceOf(SaasUnconfiguredError);
expect(fetchMock).not.toHaveBeenCalled();
});
it("throws SaasNotLinkedError when there is no SaaS session", async () => {
vi.stubEnv("VITE_SAAS_API_URL", "https://saas.test.local");
getSession.mockResolvedValue({ data: { session: null } });
await expect(
apiClient.saas.json("/api/v1/payg/wallet"),
).rejects.toBeInstanceOf(SaasNotLinkedError);
expect(fetchMock).not.toHaveBeenCalled();
});
it("attaches the Supabase bearer and hits the absolute SaaS base", async () => {
vi.stubEnv("VITE_SAAS_API_URL", "https://saas.test.local");
getSession.mockResolvedValue({
data: { session: { access_token: "supabase_tok" } },
});
fetchMock.mockResolvedValue(ok({ status: "free" }));
const body = await apiClient.saas.json<{ status: string }>(
"/api/v1/payg/wallet",
);
expect(body.status).toBe("free");
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("https://saas.test.local/api/v1/payg/wallet");
expect((init.headers as Record<string, string>).Authorization).toBe(
"Bearer supabase_tok",
);
});
});
describe("apiClient.local", () => {
it("attaches the Spring admin bearer and stays same-origin", async () => {
getStoredTokenMock.mockReturnValue("spring_tok");
fetchMock.mockResolvedValue(ok({ linked: false }));
await apiClient.local.json("/api/v1/account-link/status");
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("/api/v1/account-link/status");
expect((init.headers as Record<string, string>).Authorization).toBe(
"Bearer spring_tok",
);
});
it("returns undefined for a 204 response", async () => {
getStoredTokenMock.mockReturnValue("spring_tok");
fetchMock.mockResolvedValue(new Response(null, { status: 204 }));
const result = await apiClient.local.json("/api/v1/account-link/unlink", {
method: "POST",
});
expect(result).toBeUndefined();
});
it("throws HttpError with the status and parsed body on non-2xx", async () => {
getStoredTokenMock.mockReturnValue("spring_tok");
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ error: "nope" }), {
status: 500,
statusText: "Internal Server Error",
headers: { "Content-Type": "application/json" },
}),
);
const err = await apiClient.local
.json("/api/v1/account-link/status")
.catch((e: unknown) => e);
expect(err).toBeInstanceOf(HttpError);
expect((err as HttpError).status).toBe(500);
expect((err as HttpError).body).toEqual({ error: "nope" });
});
});