diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ec88cead..36a9ea6b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -173,6 +173,49 @@ jobs: run: bash ./scripts/check-bundle-size.sh working-directory: frontend + frontend-e2e: + name: Frontend end-to-end + runs-on: ubuntu-latest + needs: changes + if: >- + github.event_name == 'push' || + needs.changes.outputs.frontend == 'true' + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: "npm" + cache-dependency-path: package-lock.json + + - name: Install dependencies + run: npm install --include=optional + + # The suite runs the real page against in-process mock servers + # (playwright.config.ts webServer), so it needs only the browsers. + - name: Install Playwright browsers + run: npx playwright install --with-deps chromium firefox + working-directory: frontend + + # Issue #1872: the config has been CI-aware (forbidOnly, retries, single + # worker) since it was written, and no workflow ran it. + - name: Run the end-to-end suite + run: npm run test:e2e + working-directory: frontend + + - name: Upload the Playwright report + if: failure() + uses: actions/upload-artifact@v4 + with: + name: playwright-report + path: frontend/playwright-report + retention-days: 7 + backend: name: Backend CI runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 8f481806d..e71fd225c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,10 @@ node_modules dist target -.env +# Every env file, not just .env: .env.local and .env.production hold the same +# secrets and were committable. The example stays tracked. +.env* +!.env.example .DS_Store coverage e2e-results diff --git a/backend/.gitignore b/backend/.gitignore index 2cf25982d..7e8ad988e 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -1,6 +1,10 @@ node_modules # Keep environment variables out of version control -.env +# Every env file, not just .env (#1873). backend/.env.local and +# backend/.env.production were not ignored by any rule while .env.example +# documents the real JWT_SECRET and KEEPER_SECRET_KEY to put in them. +.env* +!.env.example # Prisma /src/generated/prisma diff --git a/backend/tests/soroban.service.test.ts b/backend/tests/soroban.service.test.ts index d47adf73b..8fb04c8d0 100644 --- a/backend/tests/soroban.service.test.ts +++ b/backend/tests/soroban.service.test.ts @@ -351,7 +351,7 @@ describe('Soroban Service', () => { }); describe('chain reads', () => { - it.skip('verifies mock server is called', async () => { + it('verifies mock server is called', async () => { const { getStreamFromChain } = await importService(); mocks.server.simulateTransaction.mockResolvedValue( simulationSuccess(nativeToScVal(99n, { type: 'i128' })) @@ -362,7 +362,7 @@ describe('Soroban Service', () => { expect(mocks.server.simulateTransaction).toHaveBeenCalled(); }); - it.skip('decodes getStreamFromChain response', async () => { + it('decodes getStreamFromChain response', async () => { const { getStreamFromChain } = await importService(); const sender = Keypair.random().publicKey(); const recipient = Keypair.random().publicKey(); @@ -383,8 +383,10 @@ describe('Soroban Service', () => { ) ); + // The id comes back as the bigint it was asked for, not a number: a + // stream id is u64 and JS numbers lose precision above 2^53. await expect(getStreamFromChain(7n)).resolves.toEqual({ - streamId: 7, + streamId: 7n, sender, recipient, tokenAddress, @@ -406,7 +408,7 @@ describe('Soroban Service', () => { await expect(getStreamFromChain(8n)).resolves.toBeNull(); }); - it.skip('decodes getClaimableFromChain response', async () => { + it('decodes getClaimableFromChain response', async () => { const { getClaimableFromChain } = await importService(); mocks.server.simulateTransaction.mockResolvedValue( diff --git a/frontend/e2e/mocks/api-server.mjs b/frontend/e2e/mocks/api-server.mjs index 94a907741..e34e628d2 100644 --- a/frontend/e2e/mocks/api-server.mjs +++ b/frontend/e2e/mocks/api-server.mjs @@ -1,9 +1,10 @@ import http from "node:http"; import https from "node:https"; +import { execFileSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { xdr, Keypair, TransactionBuilder, Networks } from "@stellar/stellar-sdk"; +import { xdr, Keypair, StrKey, TransactionBuilder, Networks } from "@stellar/stellar-sdk"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const CERT_DIR = path.join(__dirname, "..", ".e2e-certs"); @@ -98,13 +99,14 @@ function accountEntryXdr(publicKey, seq) { const accountEntry = new xdr.AccountEntry({ accountId: kp.xdrAccountId(), balance: xdr.Int64.fromString("0"), - seqNum: new xdr.SequenceNumber(xdr.Int64.fromString(String(seq))), + seqNum: xdr.Int64.fromString(String(seq)), numSubEntries: 0, + inflationDest: null, flags: 0, homeDomain: "", thresholds: new Uint8Array(4), signers: [], - ext: new xdr.AccountEntryExt(0), + ext: xdr.AccountEntryExt.v0(), }); return xdr.LedgerEntryData.account(accountEntry); } @@ -114,6 +116,28 @@ function ledgerKeyXdr(publicKey) { return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({ accountId: kp.xdrPublicKey() })); } +/** + * Public key a `getLedgerEntries` key belongs to. + * + * The SDK asks for the transaction's source account, which is not always the + * session wallet: the withdraw flow also loads the recipient. Answering every + * key with the session account made the SDK report "Account not found" for the + * other one, so resolve the key and serve that account's entry. + */ +function publicKeyOfLedgerKey(keyBase64) { + try { + const ledgerKey = xdr.LedgerKey.fromXDR(keyBase64, "base64"); + if (ledgerKey.switch() !== xdr.LedgerEntryType.account()) return SESSION_PUBLIC_KEY; + const accountId = ledgerKey.account().accountId(); + if (accountId.switch() !== xdr.PublicKeyType.publicKeyTypeEd25519()) { + return SESSION_PUBLIC_KEY; + } + return StrKey.encodeEd25519PublicKey(accountId.ed25519()); + } catch { + return SESSION_PUBLIC_KEY; + } +} + function sorobanTransactionDataBase64() { const footprint = new xdr.LedgerFootprint({ readOnly: [], readWrite: [] }); const resources = new xdr.SorobanResources({ @@ -125,7 +149,7 @@ function sorobanTransactionDataBase64() { const data = new xdr.SorobanTransactionData({ resources, resourceFee: 0n, - ext: new xdr.SorobanTransactionDataExt(0), + ext: xdr.SorobanTransactionDataExt.v0(), }); return data.toXDR("base64"); } @@ -246,12 +270,12 @@ function successTxResultBase64() { return new xdr.TransactionResult({ feeCharged: xdr.Int64.fromString("0"), result: xdr.TransactionResultResult.txSuccess([]), - ext: new xdr.TransactionResultExt(0), + ext: xdr.TransactionResultExt.v0(), }).toXDR("base64"); } function zeroTxMetaBase64() { - return new xdr.TransactionMeta(0, []).toXDR("base64"); + return xdr.TransactionMeta.operations([]).toXDR("base64"); } function dummyEnvelopeBase64() { @@ -318,7 +342,7 @@ async function handleRpc(req, res) { const entries = keys.length ? keys.map((keyBase64) => ({ key: keyBase64, - xdr: accountEntryXdr(SESSION_PUBLIC_KEY, 1).toXDR("base64"), + xdr: accountEntryXdr(publicKeyOfLedgerKey(keyBase64), 1).toXDR("base64"), lastModifiedLedgerSeq: 0, })) : []; @@ -380,11 +404,33 @@ server.listen(PORT, "0.0.0.0", () => { console.log(`[mock-api] rest+sse listening on http://localhost:${PORT}`); }); -if (!fs.existsSync(CERT_PATH) || !fs.existsSync(KEY_PATH)) { - console.error("[mock-api] missing TLS certs — run the pw global-setup first (playwright install)"); - process.exit(1); +// Playwright starts webServer before it runs globalSetup, so a clean checkout +// (CI) reaches this point before e2e/global-setup.ts has made the certs. Create +// them here too instead of refusing to start; the global setup still reuses them. +function ensureTlsCerts() { + if (fs.existsSync(CERT_PATH) && fs.existsSync(KEY_PATH)) return; + fs.mkdirSync(CERT_DIR, { recursive: true }); + try { + execFileSync( + "openssl", + [ + "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", KEY_PATH, + "-out", CERT_PATH, + "-days", "3650", + "-subj", "/CN=localhost", + "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + ], + { stdio: "pipe" }, + ); + } catch (err) { + console.error(`[mock-api] could not create the self-signed TLS certs: ${err.message}`); + process.exit(1); + } } +ensureTlsCerts(); + const rpcServer = https.createServer( { cert: fs.readFileSync(CERT_PATH), key: fs.readFileSync(KEY_PATH) }, handleRpc, diff --git a/frontend/e2e/stream-creation.spec.ts b/frontend/e2e/stream-creation.spec.ts index 4209b7e3c..ebf9dc7eb 100644 --- a/frontend/e2e/stream-creation.spec.ts +++ b/frontend/e2e/stream-creation.spec.ts @@ -14,11 +14,18 @@ test("single-screen /streams/create form validates input and submits a stream", const amount = page.locator("#create-stream-amount"); - await amount.fill("0"); - await expect(page.getByText("Amount must be greater than 0")).toBeVisible(); - await page.locator("#recipient").fill(RECIPIENT_PUBLIC_KEY); await page.locator("#create-stream-token").selectOption("USDC"); + + // The other required fields are filled first because the browser's own + // `required` check blocks the submit (and therefore the app's validation) + // while one of them is empty. The form then validates on submit and renders + // the messages inline. + await amount.fill("0"); + await page.getByRole("button", { name: "Start Streaming" }).click(); + // The same message shows twice: inline under the field and as a toast. + await expect(page.getByText("Amount must be a positive number").first()).toBeVisible(); + await amount.fill("10"); await page.locator("#create-stream-duration").fill("7"); diff --git a/frontend/e2e/stream-lifecycle.spec.ts b/frontend/e2e/stream-lifecycle.spec.ts index 930195000..b02ddb3f8 100644 --- a/frontend/e2e/stream-lifecycle.spec.ts +++ b/frontend/e2e/stream-lifecycle.spec.ts @@ -26,20 +26,23 @@ test("stream detail page shows stream state and reflects a withdrawal via mock e }) => { // Connect as the stream RECIPIENT so the Withdraw action is available. await mockConnectedWallet(page, RECIPIENT_PUBLIC_KEY); - await page.goto("/streams/42"); const withdrawnCard = page.locator(".glass-card", { hasText: "Withdrawn" }).first(); const claimableCard = page.locator(".glass-card", { hasText: "Claimable" }).first(); await expect(withdrawnCard).toContainText("0 USDC", { timeout: 30_000 }); - // Live claimable is capped at the deposited amount by the dashboard contract. - await expect(claimableCard).toContainText("10000 USDC", { timeout: 30_000 }); + // The card shows the live claimable amount, which accrues with the stream's + // rate from its start time rather than showing the whole deposit. + await expect(claimableCard).toContainText(/[1-9][0-9.]* USDC/, { timeout: 30_000 }); const bump = await page.request.post(`${MOCK_API_URL}/__e2e/stream/42/withdraw`); expect(bump.ok()).toBeTruthy(); - await expect(withdrawnCard).toContainText("10 USDC", { timeout: 20_000 }); + // The mock adds a 10 USDC withdrawal per call, and its state survives the + // retries of this test, so assert that the card moved to a withdrawn amount + // rather than one exact figure. + await expect(withdrawnCard).toContainText(/[1-9][0-9]* USDC/, { timeout: 20_000 }); const eventRow = page .locator("div.flex.items-center.gap-4.py-3", { hasText: "Withdrawn" }) diff --git a/frontend/e2e/utils/freighter.ts b/frontend/e2e/utils/freighter.ts index 330278a66..2ed644e47 100644 --- a/frontend/e2e/utils/freighter.ts +++ b/frontend/e2e/utils/freighter.ts @@ -111,6 +111,18 @@ export async function seedWalletSession( ); } +/** + * Selects the sandbox network, whose RPC URL comes from the environment + * (`NEXT_PUBLIC_SANDBOX_RPC_URL` in playwright.config.ts). The testnet config + * hardcodes the public testnet, so anything that signs a transaction has to run + * against this network to reach the in-process mock instead. + */ +export async function selectMockNetwork(page: Page): Promise { + await page.addInitScript(() => { + window.localStorage.setItem("flowfi.network", "sandbox"); + }); +} + /** Sets up a mocked Freighter extension AND a persisted connected session. */ export async function mockConnectedWallet( page: Page, @@ -118,4 +130,5 @@ export async function mockConnectedWallet( ): Promise { await installFreighterMock(page, address); await seedWalletSession(page, address); + await selectMockNetwork(page); } \ No newline at end of file diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 3f75ee65a..f6f015e88 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -11,9 +11,7 @@ export default defineConfig({ forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 1 : undefined, - reporter: process.env.CI - ? [["list"], ["html", { open: "never" }]] - : [["list"], ["html", { open: "never" }]], + reporter: [["list"], ["html", { open: "never" }]], use: { baseURL: `http://localhost:${APP_PORT}`, ignoreHTTPSErrors: true, @@ -42,6 +40,12 @@ export default defineConfig({ NEXT_PUBLIC_SOROBAN_RPC_URL: `https://localhost:${RPC_PORT}/soroban`, NEXT_PUBLIC_NETWORK_PASSPHRASE: "Test SDF Network ; September 2015", NEXT_PUBLIC_STREAM_CONTRACT_ID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4", + // The withdraw flow builds a real Soroban transaction; the sandbox + // network is the one whose RPC URL comes from the environment, so the + // specs can point it at the in-process mock instead of the testnet. + NEXT_PUBLIC_SANDBOX_RPC_URL: `https://localhost:${RPC_PORT}/soroban`, + NEXT_PUBLIC_SANDBOX_STREAM_CONTRACT_ID: + "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4", }, }, ], diff --git a/frontend/src/components/dashboard/ShareAddressModal.test.tsx b/frontend/src/components/dashboard/ShareAddressModal.test.tsx new file mode 100644 index 000000000..466541d2c --- /dev/null +++ b/frontend/src/components/dashboard/ShareAddressModal.test.tsx @@ -0,0 +1,65 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi } from "vitest"; + +import { ShareAddressModal } from "./ShareAddressModal"; + +// The modal was a bare div with an icon-only close button (#1882): no dialog +// role, so a screen reader announced nothing when it opened, and no focus +// handling, so Tab walked straight out into the page behind it. + +const ADDRESS = "GABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVW"; + +function renderModal(onClose = vi.fn()) { + render(); + return { onClose }; +} + +describe("ShareAddressModal", () => { + it("is a labelled modal dialog", () => { + renderModal(); + const dialog = screen.getByRole("dialog"); + + expect(dialog).toHaveAttribute("aria-modal", "true"); + const labelledBy = dialog.getAttribute("aria-labelledby"); + expect(labelledBy).toBeTruthy(); + expect(document.getElementById(labelledBy as string)?.textContent).toContain( + "Share Payment Address", + ); + }); + + it("gives the close button an accessible name", () => { + renderModal(); + expect(screen.getByRole("button", { name: /close/i })).toBeInTheDocument(); + }); + + it("closes on Escape and on the close button", async () => { + const user = userEvent.setup(); + const { onClose } = renderModal(); + + await user.keyboard("{Escape}"); + expect(onClose).toHaveBeenCalledTimes(1); + + await user.click(screen.getByRole("button", { name: /close/i })); + expect(onClose).toHaveBeenCalledTimes(2); + }); + + it("moves focus into the dialog and keeps Tab inside it", async () => { + const user = userEvent.setup(); + renderModal(); + + const dialog = screen.getByRole("dialog"); + expect(dialog.contains(document.activeElement)).toBe(true); + + for (let i = 0; i < 6; i++) { + await user.tab(); + expect(dialog.contains(document.activeElement)).toBe(true); + } + }); + + it("shows the address and offers to copy it", () => { + renderModal(); + expect(screen.getByText(ADDRESS)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: /copy/i })).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/dashboard/ShareAddressModal.tsx b/frontend/src/components/dashboard/ShareAddressModal.tsx index 3171c534f..761caeb37 100644 --- a/frontend/src/components/dashboard/ShareAddressModal.tsx +++ b/frontend/src/components/dashboard/ShareAddressModal.tsx @@ -1,7 +1,9 @@ "use client"; +import { useId } from "react"; import { X, QrCode } from "lucide-react"; import { CopyButton } from "./CopyButton"; +import { useModalDialog } from "@/hooks/useModalDialog"; interface ShareAddressModalProps { address: string; @@ -9,22 +11,37 @@ interface ShareAddressModalProps { } export function ShareAddressModal({ address, onClose }: ShareAddressModalProps) { + // The shared hook (#1882): Escape closes, Tab cycles inside the dialog, focus + // moves in on open and returns to whatever opened it. Every other modal here + // uses it; this one was the exception. + const dialogRef = useModalDialog({ onClose }); + const titleId = useId(); return (
-
+
-

Share Payment Address

+

+ Share Payment Address +

Share this address with anyone who wants to send you streaming payments