diff --git a/deploy/monitor/classify_error_log.py b/deploy/monitor/classify_error_log.py index 5318f8647..d7ffef032 100644 --- a/deploy/monitor/classify_error_log.py +++ b/deploy/monitor/classify_error_log.py @@ -51,6 +51,9 @@ CODE_THRESHOLDS = { "bulk_export": 1, "templated_questions": 1, "bulk_profiles": 1, + # BUG-2359: report files written without their export code (the code request + # failed when the export sheet opened). A few in a window means it keeps failing. + "export_unmarked": 3, } SIGNAL_MARKERS = ("[agent-observability]", "[ops-signal]") diff --git a/deploy/monitor/notify-feishu.sh b/deploy/monitor/notify-feishu.sh index e2a54d792..76d7c5894 100644 --- a/deploy/monitor/notify-feishu.sh +++ b/deploy/monitor/notify-feishu.sh @@ -144,6 +144,7 @@ alert_label() { bulk_export) printf '同一账号一小时(或一天)内导出很多份报告(requestId 是账号代号,后台客户页可搜)' ;; templated_questions) printf '同一账号把同一个问题换着很多人的星盘问(requestId 是账号代号,后台客户页可搜)' ;; bulk_profiles) printf '同一账号一小时内新建很多个星盘档案(requestId 是账号代号,后台客户页可搜)' ;; + export_unmarked) printf '报告导出时没拿到导出编号,文件照常导出但不带编号(取号接口可能出错)' ;; provider_error) printf '模型供应商调用失败' ;; timeout) printf '回答超时' ;; empty_answer) printf '模型回答为空' ;; diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index a203d60b3..073aee9ed 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -32979,11 +32979,12 @@ - 根因:导出完全在浏览器里完成,服务器不知道谁在何时导出了什么,文件里也没有任何与账号相关的标识。 - 修复: - 新表 `public.report_exports`(迁移 `20261126030000_report_exports.sql`,只加不改):导出编号(24 位十六进制,服务器随机生成)、账号、报告、类型、格式、语言、整篇/自选、时间;不存报告正文。只能通过 `record_report_export`(service_role,报告必须是本账号的,每账号每天最多 500 次)写入;后台通过 `admin_lookup_report_exports`(需 `admin.customers.read`)查;admin_runtime 另有 select 授权和 RLS 读取策略(BUG-1935 的教训),app_runtime 与 authenticated 读不到。账号注销时随账号删除。 - - 导出时先 `POST /api/report-exports` 取编号,再写文件(`lib/report-export-code.ts`);取不到编号就不出文件,弹错误提示。 + - 打开导出框时先 `POST /api/report-exports` 取编号(`lib/report-export-code.ts`),点击时同步写文件,下载不在 await 之后(手机 Safari、微信会拦异步触发的下载)。写完后后台发一次确认(`confirm_report_export`,记实际导出的语言、范围和 `exported_at`)。点击时还没拿到编号(断网、接口出错)也照常导出,文件不带编号,不弹错误;服务器记一行 `[ops-signal] export_unmarked`(不含账号和报告),监控 5 分钟内 3 次告警。 - 编号写进文件两处,互相独立(`lib/report-watermark.ts`):①零宽字符(U+2060 包住 96 个 U+200B/U+200C),放在标题和最多三个二级标题的 `#` 之后(标题以数字开头时放在行尾,首尾都是数字的标题跳过),不进表格、代码块、数字、日期和「判断依据」部分;②标题后(和最后一个标记标题后)的空行改成只含空格和制表符的行,Markdown 里仍是空行,纯文本查看器里也看不见,清掉零宽字符后仍能读出。Markdown 没有隐藏的元数据位置(front matter、HTML 注释在很多查看器里可见),所以不用。 - - 后台「导出溯源」页(`/admin/report-exports`):粘贴内容或选文件,浏览器里读出编号,只把编号发给服务器,列出账号邮箱、导出时间、报告类型、范围、语言。 + - 后台「导出溯源」页(`/admin/report-exports`):粘贴内容或选文件,浏览器里读出编号,只把编号发给服务器,列出账号邮箱、导出时间(确认没到时显示打开导出的时间)、报告类型、范围、语言。打开导出框但没导出的编号也会留一行(没有 `exported_at`)。 - 隐私政策在 BUG-2402「防止滥用」一条之后加一句:导出的文件带看不见的导出编号,用于防止未经允许的转载。 - 验证:新增 `frontend/tests/report-watermark-2359.test.ts`(10 条:五种导出(个人中英、年运、合盘中英)编号往返;清掉零宽字符或清掉行尾空白后仍能读出;去掉标记后文本逐字相同、micromark+GFM 渲染的 HTML 相同、没有新增可见字符、标题和日期仍能搜到;标记不进代码块/表格/数字/判断依据;英文版过站点英文检查 `ordinaryOutputLeaks`;CRLF 与无标题导出;浏览器先取编号、取不到不出文件;服务器只为登录账号、合法参数记录;后台只收编号、需 admin.customers.read;迁移文本;隐私政策一句)和 `frontend/tests/database-report-exports-2359.test.ts`(真实 PostgreSQL,CI 跑)。`database-local-business` 表清单、`tests/test_api_server_security.py` 后台路由清单按原值/新值/原因补上。`tests/test_report_english_public_leak_2324.py` 通过。 +- 已知限制:点击时编号还没回来(打开后立刻点)的那一份不带编号;编号请求本身失败时,`export_unmarked` 那一行也可能发不出去。 - 未覆盖:浏览器自带打印(存为 PDF)不经过服务器,不带编号;产品没有服务端 PDF / docx 导出,没有文件写入路径。聊天「分享」复制到剪贴板的对话不是报告导出,未加。 - 防复发:导出只有 `report-export-drawer.tsx` 一处写文件,测试钉住它调用 `watermarkedExportText`。 - 关联记录:BUG-2362(导出标题)、BUG-2324(英文检查)、BUG-2402(隐私政策同类说明)、BUG-1935(admin_runtime 读取策略)。 diff --git a/frontend/DESIGN.md b/frontend/DESIGN.md index d1e92aefd..560c60307 100644 --- a/frontend/DESIGN.md +++ b/frontend/DESIGN.md @@ -671,10 +671,10 @@ Action results and errors never take page layout. They are toasts from `src/lib/ ### Personal report reader - **Buttons on the report surfaces:** the BUG-1078 report-only override (2026-09-28) was replaced the same day by the site-wide solid-button pair (BUG-1079, see Button); report buttons look as before. Outline buttons there (the header 「生成报告」 while submitting) now fade like outline buttons elsewhere instead of the report-only grey. The selected export preset is `--color-canvas-muted` + `--color-ink` + a `--color-ink-secondary` edge, not the `--color-action-soft` fill (a red-brown block in dark mode). -- **导出报告 sheet (redesigned 2026-09-30, product: 「分块导出太丑」):** a component-library Sheet. Desktop slides in from the right (`data-side="right"`, width `min(520px, 92vw)`, max 520px). Below 767px it slides up from the bottom (`data-side="bottom"`, up to 85dvh). App colours only. Top to bottom: title 「导出报告」 with a × (读屏名「关闭导出」); segmented tabs for language (`aria-label="导出语言"`, 中文 / English) only when an English edition exists. They start on the edition being read and do not switch the page. There is no AI caption. Without an English edition, opening the sheet raises one info toast (id `report-export-english`) saying why. Then two segmented tabs (`aria-label="导出范围"`) 「整篇报告」 (subline counts 章正文 / 张分盘 / 张核对表) and 「自选章节」 (the second tab also carries 「只带走需要的部分」); only in 自选, a plain checklist grouped 正文 / 分盘 / 核对表, each group one tri-state checkbox (✓ / − / empty) plus a chevron, 正文 open and the other groups folded. Rows are borderless 44px lines, no per-block character counts. The footer button does not show a file size: 「导出整篇」 / 「导出 N 项」 / disabled 「先勾选要导出的部分」. Selected states (issue #90, 2026-10-21, overrides the 2026-09-30 neutral rule): the scope card's border and radio dot, checked / mixed boxes, and the selected language segment use `--color-action-strong` (text `--color-action`); backgrounds stay neutral; never `--color-action-soft` or `--color-action-fill` (BUG-1078: no dark red-brown block in dark mode). The language segment and the 整篇 / 自选 cards (`report-export-mode`) match `[data-active]` or `[aria-selected="true"]`, the same mark the chart-page tabs use. They do not look for `aria-checked` or `aria-pressed` alone. Escape, backdrop or × dismisses; focus returns without scrolling. No spinner or clipboard; the one fetch is the export code (below). +- **导出报告 sheet (redesigned 2026-09-30, product: 「分块导出太丑」):** a component-library Sheet. Desktop slides in from the right (`data-side="right"`, width `min(520px, 92vw)`, max 520px). Below 767px it slides up from the bottom (`data-side="bottom"`, up to 85dvh). App colours only. Top to bottom: title 「导出报告」 with a × (读屏名「关闭导出」); segmented tabs for language (`aria-label="导出语言"`, 中文 / English) only when an English edition exists. They start on the edition being read and do not switch the page. There is no AI caption. Without an English edition, opening the sheet raises one info toast (id `report-export-english`) saying why. Then two segmented tabs (`aria-label="导出范围"`) 「整篇报告」 (subline counts 章正文 / 张分盘 / 张核对表) and 「自选章节」 (the second tab also carries 「只带走需要的部分」); only in 自选, a plain checklist grouped 正文 / 分盘 / 核对表, each group one tri-state checkbox (✓ / − / empty) plus a chevron, 正文 open and the other groups folded. Rows are borderless 44px lines, no per-block character counts. The footer button does not show a file size: 「导出整篇」 / 「导出 N 项」 / disabled 「先勾选要导出的部分」. Selected states (issue #90, 2026-10-21, overrides the 2026-09-30 neutral rule): the scope card's border and radio dot, checked / mixed boxes, and the selected language segment use `--color-action-strong` (text `--color-action`); backgrounds stay neutral; never `--color-action-soft` or `--color-action-fill` (BUG-1078: no dark red-brown block in dark mode). The language segment and the 整篇 / 自选 cards (`report-export-mode`) match `[data-active]` or `[aria-selected="true"]`, the same mark the chart-page tabs use. They do not look for `aria-checked` or `aria-pressed` alone. Escape, backdrop or × dismisses; focus returns without scrolling. No spinner or clipboard; the one fetch is the export code, on open (below). - **Export selection:** 整篇 = every block of the chosen edition; 自选 starts with all 正文 chapters ticked. Switching the sheet's language resets the checklist to that edition's chapters (block ids differ per edition). Presets 常用 / 全部分盘 / 仅核对表 and 全选 were retired with the redesign. - **Export content:** 中文报告保存了解读时,导出列表在摘要之后列出「解读」,整篇和自选的默认正文均包含它。文件沿用页面的节标题、段落与「计算依据」标签。没有解读的报告沿用原正文。 Selected chart/table blocks append new content; selecting all groups is not byte-identical to body-only. D13 requires safe SVG in each chart, reusing the projected engine SVG or the existing hook-free Vedic drawing; offline fallback uses readable monochrome glyphs/legend and presentation attributes. No chart JSON fences or internal audit fields. Fact-table labels/precision/subtables match the reader. Full body uses the historical filename; excerpt adds `-节选`. The existing downloader appends `.md`. Chinese chart house lines use `SIGN_ZH`(白羊、金牛……,不带「座」). English chart house lines keep the English sign name. -- **Export code (BUG-2359, 2026-11-26):** pressing the footer button first asks `POST /api/report-exports` for this export's code, then writes the file. The code is invisible in the file (zero-width marks after the `#` of the title and up to three `##` headings; the blank line after the title becomes spaces and tabs), never inside a number, date, table or fence; the page, the file name and the rendered text are unchanged. Without a code there is no file: the error is an error toast and the sheet stays open. The admin page 「导出溯源」 (antd, like the rest of the admin) takes pasted text or a chosen file and lists account email, export time, report, scope and language. +- **Export code (BUG-2359, 2026-11-26):** opening the sheet asks `POST /api/report-exports` for this export's code; the footer button writes the file synchronously (Mobile Safari / WeChat block downloads started after an await) and confirms the code in the background. The code is invisible in the file (zero-width marks after the `#` of the title and up to three `##` headings; the blank line after the title becomes spaces and tabs), never inside a number, date, table or fence; the page, the file name and the rendered text are unchanged. Without a code at the click the file is still written, unmarked, with the usual 「已导出」 toast; the server logs one `export_unmarked` ops line. The admin page 「导出溯源」 (antd, like the rest of the admin) takes pasted text or a chosen file and lists account email, export time, report, scope and language. - **Structure:** inside the app shell, like every other secondary page — `/reports/[reportId]` was the last standalone full-screen route, and opening a report used to drop the reader out of the app entirely. 「个人报告」 sits in the 46px header; below it the reader owns its own scroll boundary, carrying the sticky screen chrome (back and the labelled 「导出」 button) and then the longform Markdown body beside a persistent TOC rail. Every phase — loading, generating, timed-out, and each error — renders inside the same shell, so the way back is always the rail. The five-chapter writer document is storage-only and is not rendered. Reports without Markdown show “旧版本报告,请重新生成”. - **Reading basis fallback (BUG-1860):** when 「依据与边界」 fails the post-check, the same section shows one explanation and a list with one calculation-backed line per claim. Each line names its ceiling, required evidence that is missing or near a boundary, and disclosures. The Markdown reading carries the same list. Other withheld sections keep their one-line placeholder. diff --git a/frontend/src/app/api/report-exports/route.ts b/frontend/src/app/api/report-exports/route.ts index 976e05d0d..56b458ef9 100644 --- a/frontend/src/app/api/report-exports/route.ts +++ b/frontend/src/app/api/report-exports/route.ts @@ -8,8 +8,9 @@ import { createServerSupabaseClient } from "@/lib/supabase/server"; export const runtime = "nodejs"; /** - * POST /api/report-exports — BUG-2359: an export code for the file the browser is about to - * write (personal, annual or pair report). The code goes into the file invisibly + * POST /api/report-exports — BUG-2359: an export code issued when the export sheet opens + * (personal, annual or pair report), confirmed when the file is written; or a log line when a + * file had to be written without one (lib/report-export-record.ts). The code goes into the file invisibly * (lib/report-watermark.ts); the admin 「导出溯源」 page reads it back to the account. */ export async function POST(request: Request) { @@ -25,5 +26,6 @@ export async function POST(request: Request) { body: await request.json().catch(() => null), client: context.service, }); + if (result.status === 204) return new Response(null, { status: 204 }); return NextResponse.json(result.body, { status: result.status, headers: { "cache-control": "no-store" } }); } diff --git a/frontend/src/components/admin/report-export-lookup.tsx b/frontend/src/components/admin/report-export-lookup.tsx index 7bff2f3ef..af88ac5ce 100644 --- a/frontend/src/components/admin/report-export-lookup.tsx +++ b/frontend/src/components/admin/report-export-lookup.tsx @@ -22,7 +22,8 @@ const { Text, Title } = Typography; */ const columns: TableColumnsType = [ { title: "账号邮箱", dataIndex: "email", render: (value: string | null) => value ?? 账号已注销 }, - { title: "导出时间", dataIndex: "createdAt", render: (value: string) => formatAdminDate(value) }, + // The code is issued when the export sheet opens; 导出时间 is when the file was written with it. + { title: "导出时间", dataIndex: "exportedAt", render: (value: string | null, row) => value ? formatAdminDate(value) : {formatAdminDate(row.createdAt)}(打开导出的时间) }, { title: "报告", dataIndex: "kind", render: (value: string) => EXPORT_KIND_LABEL[value] ?? value }, { title: "范围", dataIndex: "scope", render: (value: string) => EXPORT_SCOPE_LABEL[value] ?? value }, { title: "语言", dataIndex: "language", render: (value: string) => EXPORT_LANGUAGE_LABEL[value] ?? value }, diff --git a/frontend/src/components/personal-report/report-export-drawer.tsx b/frontend/src/components/personal-report/report-export-drawer.tsx index 657e38653..718c85282 100644 --- a/frontend/src/components/personal-report/report-export-drawer.tsx +++ b/frontend/src/components/personal-report/report-export-drawer.tsx @@ -1,10 +1,10 @@ "use client"; -import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; import { ChevronRight, X } from "lucide-react"; import { detectPrintRestriction } from "@/lib/client-report-export"; import { downloadMarkdownReport } from "@/lib/consultation-report-export"; -import { watermarkedExportText } from "@/lib/report-export-code"; +import { markExportText, reportExportWritten, requestReportExportCode } from "@/lib/report-export-code"; import { trackReportExport } from "@/components/page-view-beacon"; import { notifyError, notifyInfo, notifySuccess } from "@/lib/notify"; import { joinExportBlocks, type ReportExportBlock } from "@/lib/report-export-blocks"; @@ -83,6 +83,19 @@ export function ReportExportDrawer({ editions, initialLanguage = "zh", englishEd const labels = GROUP_LABELS[language]; const needle = filter.trim().toLowerCase(); const exporting = useRef(false); + // BUG-2359: this export's code, fetched when the sheet opens so the click never waits. + const exportCode = useRef(null); + const exportKind = format ?? "personal"; + const alive = useRef(true); + const fetchExportCode = useCallback(() => { + void requestReportExportCode({ reportId: reportId ?? null, kind: exportKind, language: initialLanguage, scope: "whole" }) + .then((code) => { if (alive.current && code && !exportCode.current) exportCode.current = code; }); + }, [reportId, exportKind, initialLanguage]); + useEffect(() => { + alive.current = true; + fetchExportCode(); + return () => { alive.current = false; }; + }, [fetchExportCode]); const selected = useMemo( () => (mode === "whole" ? blocks : blocks.filter(block => selection.has(block.id))), @@ -123,25 +136,27 @@ export function ReportExportDrawer({ editions, initialLanguage = "zh", englishEd return; } exporting.current = true; - const body = blocks.filter(block => block.group === "body"); - const full = mode === "whole" || (body.length > 0 && body.every(block => selection.has(block.id))); - const subject = subjectName && typeof subjectName === "object" ? subjectName[language] : subjectName; - // BUG-2359: the file carries this export's code invisibly (lib/report-watermark.ts). - void watermarkedExportText(joinExportBlocks(selected), { - reportId: reportId ?? null, - kind: format ?? "personal", - language, - scope: full ? "whole" : "pick", - }).then((text) => { + try { + const body = blocks.filter(block => block.group === "body"); + const full = mode === "whole" || (body.length > 0 && body.every(block => selection.has(block.id))); + const subject = subjectName && typeof subjectName === "object" ? subjectName[language] : subjectName; + // BUG-2359: the file carries this export's code invisibly (lib/report-watermark.ts); without + // one at hand it is written unmarked. Synchronous: the download stays inside the click. + const code = exportCode.current; + // A code is used once. A successful export closes the sheet; the next opening fetches a new one. + exportCode.current = null; + const text = markExportText(joinExportBlocks(selected), code); // BUG-2362: the report list titles its rows with this same builder. downloadMarkdownReport(reportExportTitle(format ?? "personal", subject, reportDate, language, full), text); + reportExportWritten(code, { language, scope: full ? "whole" : "pick" }); trackReportExport(); onClose(); notifySuccess("已导出"); - }).catch((cause: unknown) => { + } catch (cause) { exporting.current = false; + fetchExportCode(); notifyError(cause instanceof Error ? cause.message : "报告暂不可导出"); - }); + } } const summary = exportSummary(counts, language, format); diff --git a/frontend/src/lib/admin/report-export-lookup.ts b/frontend/src/lib/admin/report-export-lookup.ts index 50a38705c..2cf890799 100644 --- a/frontend/src/lib/admin/report-export-lookup.ts +++ b/frontend/src/lib/admin/report-export-lookup.ts @@ -11,6 +11,7 @@ export type ReportExportLookupRow = Readonly<{ language: string; scope: string; created_at: string | Date; + exported_at: string | Date | null; }>; export type ReportExportLookupRecord = Readonly<{ @@ -23,6 +24,8 @@ export type ReportExportLookupRecord = Readonly<{ language: string; scope: string; createdAt: string; + /** When the file was written with this code; null when the sheet was opened but not confirmed. */ + exportedAt: string | null; }>; export const MAX_LOOKUP_CODES = 20; @@ -35,6 +38,11 @@ export function parseLookupCodes(value: string | null): string[] | null { return codes.length ? codes : null; } +function iso(value: string | Date | null): string | null { + if (value === null || value === undefined) return null; + return value instanceof Date ? value.toISOString() : String(value); +} + export function lookupRecord(row: ReportExportLookupRow): ReportExportLookupRecord { return { exportId: row.export_code, @@ -45,7 +53,8 @@ export function lookupRecord(row: ReportExportLookupRow): ReportExportLookupReco format: row.format, language: row.language, scope: row.scope, - createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at), + createdAt: iso(row.created_at)!, + exportedAt: iso(row.exported_at), }; } diff --git a/frontend/src/lib/ops-signal.ts b/frontend/src/lib/ops-signal.ts index a7127f2b0..aea9482a5 100644 --- a/frontend/src/lib/ops-signal.ts +++ b/frontend/src/lib/ops-signal.ts @@ -19,6 +19,8 @@ export const opsSignalCodes = [ "bulk_export", "templated_questions", "bulk_profiles", + // BUG-2359: a report file was written without its export code (none at hand at the click). + "export_unmarked", ] as const; export type OpsSignalCode = (typeof opsSignalCodes)[number]; diff --git a/frontend/src/lib/report-export-code.ts b/frontend/src/lib/report-export-code.ts index eaf3f7a95..0845f8645 100644 --- a/frontend/src/lib/report-export-code.ts +++ b/frontend/src/lib/report-export-code.ts @@ -1,8 +1,10 @@ import { embedReportWatermark, EXPORT_CODE_PATTERN } from "./report-watermark.ts"; /** - * BUG-2359: ask the server for this export's code, then write it into the file text invisibly. - * Fails (throws with a plain sentence) when the code cannot be had: an export is always traceable. + * BUG-2359: the export code is fetched when the export sheet opens, so the click writes the file + * synchronously (Mobile Safari and WeChat drop a download started after an await). At the click + * the file gets the code and the code is confirmed; with no code at hand the file is written + * anyway, unmarked, and the server logs one ops line. An export is never blocked by the code. */ export type ReportExportCodeRequest = Readonly<{ reportId?: string | null; @@ -11,25 +13,46 @@ export type ReportExportCodeRequest = Readonly<{ scope: "whole" | "pick"; }>; -export async function requestReportExportCode(request: ReportExportCodeRequest, fetcher: typeof fetch = fetch): Promise { - let response: Response; - try { - response = await fetcher("/api/report-exports", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ ...request, reportId: request.reportId ?? null }), - cache: "no-store", - }); - } catch { - throw new Error("网络连接不上,请稍后再导出。"); - } - const body = (await response.json().catch(() => null)) as { exportId?: unknown; error?: unknown } | null; - if (!response.ok || typeof body?.exportId !== "string" || !EXPORT_CODE_PATTERN.test(body.exportId)) { - throw new Error(typeof body?.error === "string" && body.error ? body.error : "报告暂不可导出,请稍后再试"); - } - return body.exportId; +const ENDPOINT = "/api/report-exports"; + +function post(fetcher: typeof fetch, body: Record, keepalive = false): Promise { + return fetcher(ENDPOINT, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + cache: "no-store", + keepalive, + }); } -export async function watermarkedExportText(markdown: string, request: ReportExportCodeRequest, fetcher: typeof fetch = fetch): Promise { - return embedReportWatermark(markdown, await requestReportExportCode(request, fetcher)); +/** Resolves to the code, or null when it cannot be had (never throws). */ +export async function requestReportExportCode(request: ReportExportCodeRequest, fetcher: typeof fetch = fetch): Promise { + try { + const response = await post(fetcher, { action: "issue", ...request, reportId: request.reportId ?? null }); + const body = (await response.json().catch(() => null)) as { exportId?: unknown } | null; + return response.ok && typeof body?.exportId === "string" && EXPORT_CODE_PATTERN.test(body.exportId) ? body.exportId : null; + } catch { + return null; + } +} + +/** The click: the file text, marked when a code is at hand. Pure and synchronous. */ +export function markExportText(markdown: string, code: string | null): string { + return code ? embedReportWatermark(markdown, code) : markdown; +} + +/** + * After the file is written: confirm the code with the edition and scope exported, or, with no + * code, have the server log one `export_unmarked` line. Background; never waited for, never throws. + */ +export function reportExportWritten( + code: string | null, + exported: Readonly<{ language: "zh" | "en"; scope: "whole" | "pick" }>, + fetcher: typeof fetch = fetch, +): void { + try { + void post(fetcher, code ? { action: "confirm", exportId: code, ...exported } : { action: "unmarked" }, true).catch(() => undefined); + } catch { + // The file is written either way. + } } diff --git a/frontend/src/lib/report-export-record.ts b/frontend/src/lib/report-export-record.ts index 99500a822..534f32258 100644 --- a/frontend/src/lib/report-export-record.ts +++ b/frontend/src/lib/report-export-record.ts @@ -1,10 +1,18 @@ import { randomBytes } from "node:crypto"; +import { logOpsSignal, type OpsSignalSink } from "./ops-signal.ts"; +import { EXPORT_CODE_PATTERN } from "./report-watermark.ts"; + /** * BUG-2359: POST /api/report-exports, kept apart from the route so it can be tested without Next. - * The signed-in account asks for an export code just before the browser writes the file; the - * server makes the code and stores (code, account, report, kind, format, edition, scope) through - * public.record_report_export. Nothing of the report text is sent or stored. + * Three calls, one body field `action`: + * - "issue" (default): the export sheet just opened; the server makes a code and stores + * (code, account, report, kind, format, edition, scope) through public.record_report_export. + * - "confirm": the file was written with that code; edition and scope as exported + * (public.confirm_report_export, own unconfirmed code only). + * - "unmarked": the file was written without a code (none was at hand at the click). Only an + * `[ops-signal] export_unmarked` line is logged; nothing about the account or the report. + * Nothing of the report text is sent or stored. */ type RpcClient = { rpc: (fn: string, args: Record) => PromiseLike<{ data: unknown; error: { message?: string } | null }>; @@ -19,16 +27,25 @@ export type ReportExportRequest = Readonly<{ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu; +function languageOf(value: unknown): "zh" | "en" | null { + const language = value ?? "zh"; + return language === "zh" || language === "en" ? language : null; +} + +function scopeOf(value: unknown): "whole" | "pick" | null { + const scope = value ?? "whole"; + return scope === "whole" || scope === "pick" ? scope : null; +} + export function parseReportExportRequest(body: unknown): ReportExportRequest | null { if (!body || typeof body !== "object") return null; const value = body as Record; const reportId = value.reportId === null || value.reportId === undefined || value.reportId === "" ? null : value.reportId; if (reportId !== null && (typeof reportId !== "string" || !UUID.test(reportId))) return null; if (value.kind !== "personal" && value.kind !== "annual" && value.kind !== "synastry") return null; - const language = value.language ?? "zh"; - if (language !== "zh" && language !== "en") return null; - const scope = value.scope ?? "whole"; - if (scope !== "whole" && scope !== "pick") return null; + const language = languageOf(value.language); + const scope = scopeOf(value.scope); + if (!language || !scope) return null; return { reportId: reportId as string | null, kind: value.kind, language, scope }; } @@ -37,7 +54,8 @@ export function newExportCode(): string { } export type ReportExportResult = - | { status: 200; body: { exportId: string } } + | { status: 200; body: { exportId: string } | { confirmed: boolean } } + | { status: 204; body: null } | { status: 400 | 401 | 403 | 429 | 503; body: { error: string } }; export async function recordReportExport(input: { @@ -45,8 +63,28 @@ export async function recordReportExport(input: { body: unknown; client: RpcClient; code?: string; + sink?: OpsSignalSink; }): Promise { + const action = input.body && typeof input.body === "object" ? (input.body as Record).action ?? "issue" : "issue"; if (!input.userId) return { status: 401, body: { error: "请先登录" } }; + if (action === "unmarked") { + logOpsSignal({ errorCode: "export_unmarked", route: "/api/report-exports" }, input.sink); + return { status: 204, body: null }; + } + if (action === "confirm") { + const value = input.body as Record; + const language = languageOf(value.language); + const scope = scopeOf(value.scope); + if (typeof value.exportId !== "string" || !EXPORT_CODE_PATTERN.test(value.exportId) || !language || !scope) { + return { status: 400, body: { error: "导出请求格式不正确" } }; + } + const { data, error } = await input.client.rpc("confirm_report_export", { + p_user_id: input.userId, p_export_code: value.exportId, p_language: language, p_scope: scope, + }); + if (error) return { status: 503, body: { error: "暂时没能记录导出" } }; + return { status: 200, body: { confirmed: data === true } }; + } + if (action !== "issue") return { status: 400, body: { error: "导出请求格式不正确" } }; const parsed = parseReportExportRequest(input.body); if (!parsed) return { status: 400, body: { error: "导出请求格式不正确" } }; const code = input.code ?? newExportCode(); diff --git a/frontend/supabase/migrations/20261126030000_report_exports.sql b/frontend/supabase/migrations/20261126030000_report_exports.sql index 1cb09fe9e..f7cf041bf 100644 --- a/frontend/supabase/migrations/20261126030000_report_exports.sql +++ b/frontend/supabase/migrations/20261126030000_report_exports.sql @@ -4,8 +4,11 @@ begin; -- export code, so a file re-posted elsewhere can be traced to the account that -- exported it. Add-only. -- --- One row per export: the random code written into the file, the account, the --- report, its kind, file format, edition and scope. No report text is stored. +-- One row per export code: the random code written into the file, the account, +-- the report, its kind, file format, edition and scope. No report text is stored. +-- The code is issued when the export sheet opens (so the click can write the +-- file without waiting, which Mobile Safari / WeChat require); the click then +-- confirms it with the edition and scope actually exported (exported_at). -- Rows go with the account when it is deleted (account deletion removes every -- public table row keyed by user_id). @@ -17,7 +20,8 @@ create table if not exists public.report_exports ( format text not null default 'markdown' check (format in ('markdown')), language text not null default 'zh' check (language in ('zh', 'en')), scope text not null default 'whole' check (scope in ('whole', 'pick')), - created_at timestamptz not null default clock_timestamp() + created_at timestamptz not null default clock_timestamp(), + exported_at timestamptz ); create index if not exists report_exports_user_created_idx @@ -66,12 +70,41 @@ $$; revoke all on function public.record_report_export(uuid, text, uuid, text, text, text) from public, anon, authenticated; grant execute on function public.record_report_export(uuid, text, uuid, text, text, text) to service_role; +-- The click: the account's own unconfirmed code, with the edition and scope +-- of the file written. Returns false when there is no such code. +create or replace function public.confirm_report_export( + p_user_id uuid, + p_export_code text, + p_language text, + p_scope text +) +returns boolean +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_updated integer; +begin + update public.report_exports e + set exported_at = clock_timestamp(), + language = coalesce(p_language, e.language), + scope = coalesce(p_scope, e.scope) + where e.export_code = p_export_code and e.user_id = p_user_id and e.exported_at is null; + get diagnostics v_updated = row_count; + return v_updated > 0; +end; +$$; + +revoke all on function public.confirm_report_export(uuid, text, text, text) from public, anon, authenticated; +grant execute on function public.confirm_report_export(uuid, text, text, text) to service_role; + -- Admin side: the codes found in a pasted text or file, to the account email -- and export time. Same permission as reading customer profiles. create or replace function public.admin_lookup_report_exports(p_actor_user_id uuid, p_codes text[]) returns table ( export_code text, user_id uuid, email text, report_id uuid, kind text, - format text, language text, scope text, created_at timestamptz + format text, language text, scope text, created_at timestamptz, exported_at timestamptz ) language plpgsql stable @@ -86,7 +119,7 @@ begin return; end if; return query - select e.export_code, e.user_id, u.email, e.report_id, e.kind, e.format, e.language, e.scope, e.created_at + select e.export_code, e.user_id, u.email, e.report_id, e.kind, e.format, e.language, e.scope, e.created_at, e.exported_at from public.report_exports e left join identity.users u on u.id = e.user_id where e.export_code = any (p_codes[1:20]) diff --git a/frontend/tests/annual-md-export-20261113.test.tsx b/frontend/tests/annual-md-export-20261113.test.tsx index b4d590128..3604a9c1b 100644 --- a/frontend/tests/annual-md-export-20261113.test.tsx +++ b/frontend/tests/annual-md-export-20261113.test.tsx @@ -95,7 +95,7 @@ test("annual export supports old snapshots with separate windows and a single-co test("annual drawer shows two groups and downloads the selected appendix with the range start date", async () => { const h = createClientLifecycleHarness(); - const restoreFetch = installReportExportCodeStub(); + const stub = installReportExportCodeStub(); const createUrl = URL.createObjectURL; const revokeUrl = URL.revokeObjectURL; const create = document.createElement; @@ -128,6 +128,9 @@ test("annual drawer shows two groups and downloads the selected appendix with th }; await h.render(); await h.event(byLabel("导出报告")); + // 新增:打开导出框后等取号落定(测试里由桩回答),点击仍同步写文件;文件里读得出编号 + // 原因:BUG-2359 导出文件带看不见的导出编号 + await h.idle(); assert.match(byText("tab", "整篇报告").text, /7 节正文,计算依据 \d+ 项/); assert.ok(!nodes().some((node) => node.getAttribute("aria-label") === "导出语言")); await h.event(byText("tab", "自选章节")); @@ -136,10 +139,6 @@ test("annual drawer shows two groups and downloads the selected appendix with th await h.event(byLabel("正文", "checkbox")); await h.event(byLabel("计算依据", "checkbox")); await h.event(byText("button", "导出 ")); - // 原值:按下后文件立即写出 - // 新值:先向服务器取导出编号(测试里由桩回答),等它落定再读文件;文件里读得出编号 - // 原因:BUG-2359 导出文件带看不见的导出编号 - await h.idle(); // 原值: "年运报告-2026-08-04.md" // 新值: "虚构甲-年运报告-2026-08-04.md" // 原因: BUG-2066,导出文件名前面带上这份报告是谁的 @@ -151,7 +150,7 @@ test("annual drawer shows two groups and downloads the selected appendix with th assert.deepEqual(extractExportCodes(markdown), [STUB_EXPORT_CODE]); assert.deepEqual(h.errors, []); } finally { - restoreFetch(); + stub.restore(); await h.close(); document.createElement = create; URL.createObjectURL = createUrl; diff --git a/frontend/tests/database-report-exports-2359.test.ts b/frontend/tests/database-report-exports-2359.test.ts index 579efa927..c7faabef4 100644 --- a/frontend/tests/database-report-exports-2359.test.ts +++ b/frontend/tests/database-report-exports-2359.test.ts @@ -69,6 +69,14 @@ test("report export codes: own reports only, admin lookup by permission, admin_r assert.throws(() => record(otherId, "1".repeat(24), reportId), /report_export_not_owned/); assert.throws(() => record(ownerId, "not-a-code", null), /report_exports_export_code_check|violates check/); + // The click confirms the code with what was exported: own code once, nobody else's. + const confirm = (user: string) => lastLine(fixture.psqlAs(...SERVICE, + `set role service_role; select public.confirm_report_export('${user}'::uuid, '${CODE}', 'en', 'pick');`)); + assert.equal(confirm(otherId), "f"); + assert.equal(confirm(ownerId), "t"); + assert.equal(confirm(ownerId), "f"); + assert.equal(fixture.psql(`select language || '|' || scope || '|' || (exported_at is not null) from public.report_exports where export_code = '${CODE}'`), "en|pick|true"); + const lookup = (actor: string) => lastLine(fixture.psqlAs(...ADMIN, `select email || '|' || kind || '|' || coalesce(report_id::text, '') from public.admin_lookup_report_exports('${actor}', array['${CODE}'])`)); assert.equal(lookup(adminId), `owner-2359@example.invalid|personal|${reportId}`); diff --git a/frontend/tests/helpers/report-export-code-stub.ts b/frontend/tests/helpers/report-export-code-stub.ts index f4172140c..a9a473d3d 100644 --- a/frontend/tests/helpers/report-export-code-stub.ts +++ b/frontend/tests/helpers/report-export-code-stub.ts @@ -1,15 +1,22 @@ -// BUG-2359: the export sheet asks POST /api/report-exports for a code before it writes the file. -// Component tests answer that one request with a fixed code; every other fetch is left alone. +// BUG-2359: the export sheet asks POST /api/report-exports for a code when it opens, then confirms +// it (or reports an unmarked file) after the click. Component tests answer those requests; every +// other fetch is left alone. `offline` makes the code request fail like a dropped network. export const STUB_EXPORT_CODE = "0f1e2d3c4b5a69788796a5b4"; -export function installReportExportCodeStub(): () => void { +export type ExportCodeStub = { restore: () => void; bodies: Record[] }; + +export function installReportExportCodeStub(options: { offline?: boolean } = {}): ExportCodeStub { const original = globalThis.fetch; + const bodies: Record[] = []; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { if (String(input) === "/api/report-exports") { - return new Response(JSON.stringify({ exportId: STUB_EXPORT_CODE }), { status: 200, headers: { "content-type": "application/json" } }); + const body = JSON.parse(String(init?.body ?? "{}")) as Record; + bodies.push(body); + if (options.offline && body.action === "issue") throw new TypeError("Failed to fetch"); + if (body.action === "issue") return new Response(JSON.stringify({ exportId: STUB_EXPORT_CODE }), { status: 200 }); + return new Response(null, { status: body.action === "unmarked" ? 204 : 200 }); } return original(input, init); }) as typeof fetch; - return () => { globalThis.fetch = original; }; + return { restore: () => { globalThis.fetch = original; }, bodies }; } - diff --git a/frontend/tests/report-export-drawer.test.tsx b/frontend/tests/report-export-drawer.test.tsx index 6faa967bb..778b7e70e 100644 --- a/frontend/tests/report-export-drawer.test.tsx +++ b/frontend/tests/report-export-drawer.test.tsx @@ -96,7 +96,7 @@ test("drawer download uses the existing Blob downloader exactly once and only th // 新值:自选里只开「核对表」组、关掉正文组后按「导出 8 项 · …」,toast「已导出」,文件名为节选;内容仍是这些块逐字节拼接 // 原因:2026-09-30 重设计去掉套餐 const h = createClientLifecycleHarness(); - const restoreFetch = installReportExportCodeStub(); + const stub = installReportExportCodeStub(); const oldCreate = URL.createObjectURL; const oldRevoke = URL.revokeObjectURL; let blob: Blob | undefined; @@ -119,23 +119,63 @@ test("drawer download uses the existing Blob downloader exactly once and only th }) as typeof document.createElement; try { await h.render( { closed += 1; }} />); + // BUG-2359: the code is fetched when the sheet opens; the click below writes the file at once. + await h.idle(); await h.event(tab(h, "自选章节")); await h.event(namedCheck(h, "正文")); await h.event(namedCheck(h, "核对表")); const tables = blocks.filter(block => block.group === "table"); await h.event(button(h, `导出 ${tables.length} 项`)); - await h.idle(); assert.equal(clicked, 1); assert.equal(closed, 1); assert.deepEqual(successes, ["已导出"]); assert.equal(filename, exportFilename("2026-09-24", false) + ".md"); // 原值:文件内容 === joinExportBlocks(tables) // 新值:去掉导出编号后 === joinExportBlocks(tables),文件里读得出编号 - // 原因:BUG-2359 导出文件带看不见的导出编号(先向服务器取号再写文件) + // 原因:BUG-2359 导出文件带看不见的导出编号(打开导出框时取号,点击时同步写文件) const text = await blob?.text() ?? ""; assert.equal(stripReportWatermark(text), joinExportBlocks(tables)); assert.deepEqual(extractExportCodes(text), [STUB_EXPORT_CODE]); - } finally { toast.success = successBefore; URL.createObjectURL = oldCreate; URL.revokeObjectURL = oldRevoke; restoreFetch(); await h.close(); } + assert.deepEqual(stub.bodies.map((body) => body.action), ["issue", "confirm"]); + assert.deepEqual(stub.bodies[1], { action: "confirm", exportId: STUB_EXPORT_CODE, language: "zh", scope: "pick" }); + } finally { toast.success = successBefore; URL.createObjectURL = oldCreate; URL.revokeObjectURL = oldRevoke; stub.restore(); await h.close(); } +}); + +test("BUG-2359 without a code at the click the file is still exported, unmarked, and the server is told", async () => { + const h = createClientLifecycleHarness(); + const stub = installReportExportCodeStub({ offline: true }); + const oldCreate = URL.createObjectURL; + const oldRevoke = URL.revokeObjectURL; + const successBefore = toast.success; + const errorBefore = toast.error; + const successes: string[] = []; + const errors: string[] = []; + toast.success = (message) => { successes.push(String(message)); return 1; }; + toast.error = (message) => { errors.push(String(message)); return 1; }; + let blob: Blob | undefined; + let clicked = 0; + const document = globalThis.document; + const originalCreate = document.createElement.bind(document); + URL.createObjectURL = value => { blob = value as Blob; return "blob:test"; }; + URL.revokeObjectURL = () => {}; + document.createElement = ((tag: string) => tag === "a" + ? { set download(_value: string) {}, click() { clicked += 1; }, remove() {} } as unknown as HTMLAnchorElement + : originalCreate(tag)) as typeof document.createElement; + try { + await h.render( {}} />); + await h.idle(); + await h.event(button(h, "导出整篇")); + assert.equal(clicked, 1); + assert.equal(await blob?.text(), joinExportBlocks(blocks)); + assert.deepEqual(successes, ["已导出"]); + assert.deepEqual(errors, []); + assert.deepEqual(stub.bodies.map((body) => body.action), ["issue", "unmarked"]); + assert.deepEqual(stub.bodies[1], { action: "unmarked" }); + } finally { + toast.success = successBefore; toast.error = errorBefore; + URL.createObjectURL = oldCreate; URL.revokeObjectURL = oldRevoke; document.createElement = originalCreate; + stub.restore(); await h.close(); + } }); test("download failure and WeChat restrictions leave drawer open without a success close", async () => { @@ -150,12 +190,11 @@ test("download failure and WeChat restrictions leave drawer open without a succe toast.success = () => { successes += 1; return 1; }; toast.error = (message) => { errors.push(String(message)); return 1; }; let closed = 0; - const restoreFetch = installReportExportCodeStub(); + const stub = installReportExportCodeStub(); try { await h.render( { closed += 1; }} />); URL.createObjectURL = () => { throw new Error("下载失败"); }; await h.event(button(h, "导出整篇")); - await h.idle(); // 原值: h.container.text 含「下载失败」/「系统浏览器」(抽屉底部 role="alert" 一行) // 新值: 两句都是 error toast;抽屉仍开着、没有成功提示(主语不变) // 原因: 2026-09-30 产品「报错和提示不要占页面布局」 @@ -170,7 +209,7 @@ test("download failure and WeChat restrictions leave drawer open without a succe toast.success = successBefore; toast.error = errorBefore; URL.createObjectURL = oldCreate; - restoreFetch(); + stub.restore(); if (navigatorDescriptor) Object.defineProperty(globalThis, "navigator", navigatorDescriptor); else Reflect.deleteProperty(globalThis, "navigator"); await h.close(); } diff --git a/frontend/tests/report-watermark-2359.test.ts b/frontend/tests/report-watermark-2359.test.ts index 6e37f6030..5929d554c 100644 --- a/frontend/tests/report-watermark-2359.test.ts +++ b/frontend/tests/report-watermark-2359.test.ts @@ -11,7 +11,7 @@ import { gfm, gfmHtml } from "micromark-extension-gfm"; import { buildAnnualExportBlocks } from "../src/lib/annual-report-export.ts"; import { annualSolarReturns, annualTithiReturns, buildAppendix, type AnnualSnapshot } from "../src/lib/annual-report-generate.ts"; import { buildReportExportBlocks, joinExportBlocks } from "../src/lib/report-export-blocks.ts"; -import { requestReportExportCode, watermarkedExportText } from "../src/lib/report-export-code.ts"; +import { markExportText, reportExportWritten, requestReportExportCode } from "../src/lib/report-export-code.ts"; import { newExportCode, recordReportExport } from "../src/lib/report-export-record.ts"; import { lookupRecord, parseLookupCodes } from "../src/lib/admin/report-export-lookup.ts"; import { ordinaryOutputLeaks } from "../src/lib/report-public-projection.ts"; @@ -156,21 +156,35 @@ test("BUG-2359 CRLF text, a headless export and unrelated invisible text", () => assert.throws(() => zeroWidthMark("not-a-code")); }); -test("BUG-2359 the browser asks the server for the code before writing the file", async () => { - const calls: { url: string; body: unknown }[] = []; +test("BUG-2359 the code is fetched before the click; the click writes the file synchronously", async () => { + const calls: { url: string; body: unknown; keepalive?: boolean }[] = []; const fetcher = (async (url: string, init?: RequestInit) => { - calls.push({ url, body: JSON.parse(String(init?.body)) }); + calls.push({ url, body: JSON.parse(String(init?.body)), keepalive: init?.keepalive }); return new Response(JSON.stringify({ exportId: CODE }), { status: 200 }); }) as unknown as typeof fetch; - const text = await watermarkedExportText("# 报告\n\n## 一节\n\n正文。\n", { reportId: "21200000-0000-4000-8000-000000032359", kind: "personal", language: "zh", scope: "whole" }, fetcher); + const code = await requestReportExportCode({ reportId: "21200000-0000-4000-8000-000000032359", kind: "personal", language: "zh", scope: "whole" }, fetcher); + assert.equal(code, CODE); + assert.deepEqual(calls[0], { url: "/api/report-exports", body: { action: "issue", reportId: "21200000-0000-4000-8000-000000032359", kind: "personal", language: "zh", scope: "whole" }, keepalive: false }); + // The click: a plain string, no promise. + const text = markExportText("# 报告\n\n## 一节\n\n正文。\n", code); + assert.equal(typeof text, "string"); assert.deepEqual(extractExportCodes(text), [CODE]); - assert.deepEqual(calls, [{ url: "/api/report-exports", body: { reportId: "21200000-0000-4000-8000-000000032359", kind: "personal", language: "zh", scope: "whole" } }]); - // No code, no file: the error is shown and nothing is downloaded. - const failing = (async () => new Response(JSON.stringify({ error: "报告不属于当前账号" }), { status: 403 })) as unknown as typeof fetch; - await assert.rejects(requestReportExportCode({ kind: "annual", language: "zh", scope: "pick" }, failing), /报告不属于当前账号/); + reportExportWritten(code, { language: "en", scope: "pick" }, fetcher); + assert.deepEqual(calls[1], { url: "/api/report-exports", body: { action: "confirm", exportId: CODE, language: "en", scope: "pick" }, keepalive: true }); + // No code (network down, refused): resolves null, the file is written unmarked and one log call goes out. + const failing = (async () => new Response(JSON.stringify({ error: "x" }), { status: 503 })) as unknown as typeof fetch; + assert.equal(await requestReportExportCode({ kind: "annual", language: "zh", scope: "whole" }, failing), null); + const offline = (async () => { throw new TypeError("network"); }) as unknown as typeof fetch; + assert.equal(await requestReportExportCode({ kind: "annual", language: "zh", scope: "whole" }, offline), null); + assert.equal(markExportText("# 报告\n", null), "# 报告\n"); + reportExportWritten(null, { language: "zh", scope: "whole" }, fetcher); + assert.deepEqual(calls[2], { url: "/api/report-exports", body: { action: "unmarked" }, keepalive: true }); + assert.doesNotThrow(() => reportExportWritten(null, { language: "zh", scope: "whole" }, offline)); const drawer = read("../src/components/personal-report/report-export-drawer.tsx"); - assert.match(drawer, /watermarkedExportText\(joinExportBlocks\(selected\)/); - assert.doesNotMatch(drawer, /downloadMarkdownReport\([^)]*joinExportBlocks/); + const click = drawer.slice(drawer.indexOf("function download()"), drawer.indexOf("const summary = exportSummary")); + assert.doesNotMatch(click, /await|\.then\(/u, "the click handler never waits"); + assert.match(click, /markExportText\(joinExportBlocks\(selected\), code\)/); + assert.match(drawer, /useEffect\(\(\) => \{\n\s+alive\.current = true;\n\s+fetchExportCode\(\);/); }); test("BUG-2359 the server records one row per export for the signed-in account only", async () => { @@ -185,6 +199,20 @@ test("BUG-2359 the server records one row per export for the signed-in account o assert.deepEqual(rpcs, [{ fn: "record_report_export", args: { p_user_id: "user-1", p_export_code: CODE, p_report_id: "21200000-0000-4000-8000-000000032359", p_kind: "synastry", p_language: "en", p_scope: "pick" } }]); const notOwned = { rpc: async () => ({ data: null, error: { message: "report_export_not_owned" } }) }; assert.equal((await recordReportExport({ userId: "user-1", body: { kind: "personal", reportId: "21200000-0000-4000-8000-000000032359" }, client: notOwned })).status, 403); + // Confirm: own code, edition and scope as written. + const confirmed: { fn: string; args: Record }[] = []; + const confirmClient = { rpc: async (fn: string, args: Record) => { confirmed.push({ fn, args }); return { data: true, error: null }; } }; + assert.deepEqual(await recordReportExport({ userId: "user-1", body: { action: "confirm", exportId: CODE, language: "zh", scope: "whole" }, client: confirmClient }), { status: 200, body: { confirmed: true } }); + assert.deepEqual(confirmed, [{ fn: "confirm_report_export", args: { p_user_id: "user-1", p_export_code: CODE, p_language: "zh", p_scope: "whole" } }]); + assert.equal((await recordReportExport({ userId: "user-1", body: { action: "confirm", exportId: "bad" }, client: confirmClient })).status, 400); + // Unmarked: one ops line, nothing about the account or the report; signed-in only. + const lines: string[] = []; + assert.deepEqual(await recordReportExport({ userId: "user-1", body: { action: "unmarked", kind: "personal" }, client: confirmClient, sink: (line) => lines.push(line) }), { status: 204, body: null }); + assert.deepEqual(lines, ['[ops-signal] {"errorCode":"export_unmarked","route":"/api/report-exports"}']); + assert.equal((await recordReportExport({ userId: null, body: { action: "unmarked" }, client: confirmClient, sink: (line) => lines.push(line) })).status, 401); + assert.equal(lines.length, 1); + assert.match(read("../../deploy/monitor/classify_error_log.py"), /"export_unmarked": 3,/); + assert.match(read("../../deploy/monitor/notify-feishu.sh"), /export_unmarked\) printf/); assert.match(newExportCode(), /^[0-9a-f]{24}$/u); assert.notEqual(newExportCode(), newExportCode()); }); @@ -193,8 +221,8 @@ test("BUG-2359 the admin lookup takes only codes, needs admin.customers.read, an assert.deepEqual(parseLookupCodes(`${CODE},${CODE.toUpperCase()}, bad ,`), [CODE]); assert.equal(parseLookupCodes("nothing"), null); assert.equal(parseLookupCodes(Array.from({ length: 30 }, (_, i) => i.toString(16).padStart(24, "a")).join(","))?.length, 20); - assert.deepEqual(lookupRecord({ export_code: CODE, user_id: "u", email: "fictional@example.invalid", report_id: null, kind: "annual", format: "markdown", language: "zh", scope: "whole", created_at: new Date("2026-11-26T01:00:00Z") }), { - exportId: CODE, userId: "u", email: "fictional@example.invalid", reportId: null, kind: "annual", format: "markdown", language: "zh", scope: "whole", createdAt: "2026-11-26T01:00:00.000Z", + assert.deepEqual(lookupRecord({ export_code: CODE, user_id: "u", email: "fictional@example.invalid", report_id: null, kind: "annual", format: "markdown", language: "zh", scope: "whole", created_at: new Date("2026-11-26T01:00:00Z"), exported_at: null }), { + exportId: CODE, userId: "u", email: "fictional@example.invalid", reportId: null, kind: "annual", format: "markdown", language: "zh", scope: "whole", createdAt: "2026-11-26T01:00:00.000Z", exportedAt: null, }); const route = read("../src/app/api/admin/report-exports/route.ts"); assert.match(route, /requirePermission\("admin\.customers\.read"\)/); @@ -218,6 +246,8 @@ test("BUG-2359 the migration is additive, server-written, and admin-readable thr assert.match(sql, /create policy report_exports_admin_runtime_read\s+on public\.report_exports\s+for select to admin_runtime using \(true\)/); assert.match(sql, /revoke all on table public\.report_exports from app_runtime/); assert.match(sql, /report_export_not_owned/); + assert.match(sql, /grant execute on function public\.confirm_report_export\(uuid, text, text, text\) to service_role/); + assert.match(sql, /exported_at timestamptz\n\);/); }); test("BUG-2359 the privacy policy says exports carry an invisible identifier", () => {