mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
Make uploads and every other write work over plain HTTP
crypto.randomUUID() is [SecureContext] in the Web Cryptography IDL, so a page served over plain HTTP never gets it. Measured in Chromium against http://<lan-ip>: isSecureContext false, randomUUID and subtle undefined, getRandomValues still a function. The document vault minted its queue id and Idempotency-Key that way, inside the file-input change handler. On a LAN self-host the call threw before a queue row existed, so picking a file produced no upload, no error and no trace — the picker simply looked inert, and the only way through was to reach the app over HTTPS. The client transport has minted a default Idempotency-Key the same way since v1.37.18, which put every apiPost and apiPatch on the same footing: on such a host nothing wrote at all. Add randomId(), which prefers the platform call and otherwise assembles a v4 UUID from getRandomValues — the same CSPRNG, the same 122 bits, no secure context required — and route every browser-side call site through it. Nothing in an upload needs one: the bytes travel over multipart XHR and every cryptographic operation happens on the server. Passkeys, web push and home-screen install still need HTTPS; browsers withhold those outright. A structural guard fails a direct crypto.randomUUID() anywhere outside the two server-side files that may keep it, so the class cannot return one call site at a time. Also point the CSV and JSON import cards straight at the import guide. They resolved through a redirect under the integrations tree, which is the wrong place for a guide that is not an integration runbook. The suite that covered those links pinned the old spelling rather than the guarantee; it now asserts an absolute docs-site URL, no internal path, and new-tab hygiene.
This commit is contained in:
1 parent
295d70988d
commit
5556478691
17 files changed
+634
-33
No files matched your search
@@ -47,6 +47,7 @@ import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { ListRow } from "@/components/ui/list-row";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { randomId } from "@/lib/random-id";
|
||||
import type { BackupRow, BackupsList } from "@/types/backups";
|
||||
import type { BackupScheduleStatus } from "@/lib/jobs/backup-schedule-status";
|
||||
import type {
|
||||
@@ -781,7 +782,7 @@ export function BackupsSection() {
|
||||
// Idempotency-Key prevents a double-click from re-running the
|
||||
// destructive transaction. Include the row id so two different
|
||||
// backups can both be restored independently in the same minute.
|
||||
const idempotencyKey = `restore-${row.id}-${crypto.randomUUID()}`;
|
||||
const idempotencyKey = `restore-${row.id}-${randomId()}`;
|
||||
return apiPost<{ restored: true; skipped?: RestoreSkipSummary }>(
|
||||
`/api/admin/backups/${row.id}/restore`,
|
||||
{ confirm: "RESTORE" },
|
||||
|
||||
@@ -22,6 +22,7 @@ import { SettingsCard } from "@/components/settings/settings-card";
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { apiDelete } from "@/lib/api/api-fetch";
|
||||
import { randomId } from "@/lib/random-id";
|
||||
|
||||
/**
|
||||
* The literal an admin must type to arm the wipe. Mirrors the Backups
|
||||
@@ -46,7 +47,7 @@ export function DangerZoneSection() {
|
||||
mutationFn: async () => {
|
||||
// Idempotency-Key prevents a double-submit from re-running the
|
||||
// destructive transaction, matching the Backups restore path.
|
||||
const idempotencyKey = `admin-data-wipe-${crypto.randomUUID()}`;
|
||||
const idempotencyKey = `admin-data-wipe-${randomId()}`;
|
||||
// The server returns one count per table that actually held rows. It
|
||||
// used to return nine fixed names, which is how nobody noticed the
|
||||
// wipe had stopped covering the schema: the result line read the same
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
apiPost,
|
||||
} from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { randomId } from "@/lib/random-id";
|
||||
import { toastWrittenOutcome } from "@/components/outcome/outcome-toast";
|
||||
|
||||
import {
|
||||
@@ -225,7 +226,7 @@ export function useCycleInsights() {
|
||||
|
||||
/** A fresh idempotency key per write attempt (matches the iOS Outbox shape). */
|
||||
function idempotencyKey(): string {
|
||||
return crypto.randomUUID();
|
||||
return randomId();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The vault upload on a plain-HTTP origin — the reported failure.
|
||||
*
|
||||
* A self-hoster on plain HTTP over a LAN picked a file and nothing
|
||||
* happened: no queue row, no request, no error toast. The upload minted an
|
||||
* `Idempotency-Key` (and its local queue id) with `crypto.randomUUID()`,
|
||||
* which a non-secure context does not expose — measured in Chromium on
|
||||
* `http://<lan-ip>`: `isSecureContext` false, `crypto.randomUUID`
|
||||
* undefined, `crypto.getRandomValues` still a function. The call threw
|
||||
* synchronously inside the file-input change handler, so the throw had
|
||||
* nowhere to surface and the picker looked inert.
|
||||
*
|
||||
* Watched red: restoring `crypto.randomUUID()` in `uploadViaXhr` fails
|
||||
* "sends the multipart POST" with the plain-HTTP TypeError, and the
|
||||
* secure-context case stays green — which is the whole shape of the bug.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { uploadViaXhr } from "../use-document-upload";
|
||||
|
||||
const UUID_V4 =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
|
||||
/**
|
||||
* Bound BEFORE any stubbing: `vi.stubGlobal("crypto", …)` replaces
|
||||
* `globalThis.crypto`, so a stub that delegated through the global would
|
||||
* call itself.
|
||||
*/
|
||||
const realGetRandomValues = globalThis.crypto.getRandomValues.bind(
|
||||
globalThis.crypto,
|
||||
);
|
||||
|
||||
/**
|
||||
* The `crypto` a plain-HTTP origin actually hands the page: real
|
||||
* `getRandomValues`, no `randomUUID`, no `subtle`.
|
||||
*/
|
||||
function insecureCrypto(): Crypto {
|
||||
return { getRandomValues: realGetRandomValues } as Crypto;
|
||||
}
|
||||
|
||||
interface SentRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
body: FormData | null;
|
||||
}
|
||||
|
||||
const sent: SentRequest[] = [];
|
||||
|
||||
/** Minimal XHR double that records the request and resolves with a 201. */
|
||||
class FakeXhr {
|
||||
status = 0;
|
||||
responseText = "";
|
||||
upload = { addEventListener: () => {} };
|
||||
private listeners = new Map<string, () => void>();
|
||||
private request: SentRequest = {
|
||||
method: "",
|
||||
url: "",
|
||||
headers: {},
|
||||
body: null,
|
||||
};
|
||||
|
||||
open(method: string, url: string): void {
|
||||
this.request.method = method;
|
||||
this.request.url = url;
|
||||
}
|
||||
|
||||
setRequestHeader(name: string, value: string): void {
|
||||
this.request.headers[name] = value;
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: () => void): void {
|
||||
this.listeners.set(type, listener);
|
||||
}
|
||||
|
||||
send(body: FormData): void {
|
||||
this.request.body = body;
|
||||
sent.push(this.request);
|
||||
this.status = 201;
|
||||
this.responseText = JSON.stringify({
|
||||
data: { id: "doc-1", fileName: "scan.pdf" },
|
||||
error: null,
|
||||
});
|
||||
this.listeners.get("load")?.();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sent.length = 0;
|
||||
vi.stubGlobal("XMLHttpRequest", FakeXhr);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function pdf(): File {
|
||||
return new File([new Uint8Array([1, 2, 3])], "scan.pdf", {
|
||||
type: "application/pdf",
|
||||
});
|
||||
}
|
||||
|
||||
describe("vault upload on a plain-HTTP origin", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("crypto", insecureCrypto());
|
||||
});
|
||||
|
||||
it("has no crypto.randomUUID to call — the control", () => {
|
||||
expect(typeof (crypto as Crypto).randomUUID).toBe("undefined");
|
||||
});
|
||||
|
||||
it("sends the multipart POST", async () => {
|
||||
const result = await uploadViaXhr(pdf(), {}, () => {});
|
||||
|
||||
expect(sent).toHaveLength(1);
|
||||
expect(sent[0]!.method).toBe("POST");
|
||||
expect(sent[0]!.url).toBe("/api/documents/inbound");
|
||||
expect(sent[0]!.body?.get("file")).toBeInstanceOf(File);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("still carries a v4 Idempotency-Key", async () => {
|
||||
await uploadViaXhr(pdf(), {}, () => {});
|
||||
|
||||
expect(sent[0]!.headers["Idempotency-Key"]).toMatch(UUID_V4);
|
||||
});
|
||||
|
||||
it("still forwards the episode link on a deep-link upload", async () => {
|
||||
await uploadViaXhr(pdf(), { episodeId: "ep-1" }, () => {});
|
||||
|
||||
expect(sent[0]!.body?.get("episodeIds")).toBe("ep-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("vault upload in a secure context", () => {
|
||||
it("is unchanged — a v4 Idempotency-Key and one POST", async () => {
|
||||
await uploadViaXhr(pdf(), {}, () => {});
|
||||
|
||||
expect(sent).toHaveLength(1);
|
||||
expect(sent[0]!.headers["Idempotency-Key"]).toMatch(UUID_V4);
|
||||
expect(typeof globalThis.crypto.randomUUID).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import { useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { randomId } from "@/lib/random-id";
|
||||
import { invalidateKeys, queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
parseUploadResponse,
|
||||
@@ -103,8 +104,14 @@ async function downscaleImage(file: File): Promise<File> {
|
||||
}
|
||||
}
|
||||
|
||||
/** One multipart POST via XHR, reporting upload progress. */
|
||||
function uploadViaXhr(
|
||||
/**
|
||||
* One multipart POST via XHR, reporting upload progress.
|
||||
*
|
||||
* Exported for the unit test: this function mints the `Idempotency-Key`,
|
||||
* and it did so with `crypto.randomUUID()`, which a plain-HTTP origin does
|
||||
* not expose. The test drives it with that property absent.
|
||||
*/
|
||||
export function uploadViaXhr(
|
||||
file: File,
|
||||
options: EnqueueOptions,
|
||||
onProgress: (fraction: number) => void,
|
||||
@@ -114,7 +121,7 @@ function uploadViaXhr(
|
||||
xhr.open("POST", "/api/documents/inbound");
|
||||
// Retry-safe by construction: the server honours Idempotency-Key, so a
|
||||
// network blip that DID land server-side cannot double-store on retry.
|
||||
xhr.setRequestHeader("Idempotency-Key", crypto.randomUUID());
|
||||
xhr.setRequestHeader("Idempotency-Key", randomId());
|
||||
xhr.upload.addEventListener("progress", (event) => {
|
||||
if (event.lengthComputable && event.total > 0) {
|
||||
onProgress(event.loaded / event.total);
|
||||
@@ -263,7 +270,7 @@ export function useDocumentUpload(
|
||||
if (files.length === 0) return;
|
||||
const fresh: UploadQueueItem[] = [];
|
||||
for (const file of files) {
|
||||
const localId = crypto.randomUUID();
|
||||
const localId = randomId();
|
||||
// Client pre-flight against the server's configured cap: an obvious
|
||||
// giant (a CD image) fails instantly and locally — friendly reason,
|
||||
// no wasted transfer. The server re-enforces regardless.
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { randomId } from "@/lib/random-id";
|
||||
import { apiDelete, apiFetchRaw, apiGet } from "@/lib/api/api-fetch";
|
||||
import type { CoachScope } from "@/lib/ai/coach/types";
|
||||
import type { CoachLaunchScope } from "@/lib/insights/coach-launch-context";
|
||||
@@ -528,7 +529,7 @@ export function CoachConversation({
|
||||
try {
|
||||
response = await apiFetchRaw("/api/documents/inbound", {
|
||||
method: "POST",
|
||||
headers: { "Idempotency-Key": crypto.randomUUID() },
|
||||
headers: { "Idempotency-Key": randomId() },
|
||||
body: form,
|
||||
});
|
||||
} catch {
|
||||
|
||||
@@ -3,28 +3,45 @@
|
||||
*
|
||||
* The app serves no `/docs` tree, so the old internal
|
||||
* `/docs/integrations/data-import` href 404'd for every user who
|
||||
* clicked it. The guide lives at `docs.healthlog.dev`; the link goes
|
||||
* through `INTEGRATION_DOCS_BASE` so the host lives in exactly one
|
||||
* place (the same constant every Settings → Integrations card uses).
|
||||
* clicked it. That is the property this suite exists to hold.
|
||||
*
|
||||
* It used to assert `INTEGRATION_DOCS_BASE` and `data-import` by name.
|
||||
* Both were how the link happened to be built, not what it had to be:
|
||||
* the guide is not an integration runbook, it lives under `/guides/`,
|
||||
* and `${INTEGRATION_DOCS_BASE}/data-import` only resolved through a
|
||||
* redirect. Pinning the spelling would have made the correction fail a
|
||||
* green suite, so the assertions now name the guarantee — an absolute
|
||||
* `docs.healthlog.dev` URL, no internal path, new-tab hygiene — and
|
||||
* `IMPORT_GUIDE_URL` owns the address in one place for both cards.
|
||||
*
|
||||
* Watched red: restoring `href="/docs/integrations/data-import"` in
|
||||
* either card fails the matching assertion below.
|
||||
* either card fails the internal-path assertion; dropping `rel` fails
|
||||
* the hygiene one.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { IMPORT_GUIDE_URL } from "../constants";
|
||||
|
||||
const CARDS = ["csv-import-card.tsx", "json-import-card.tsx"] as const;
|
||||
|
||||
describe("import-card docs links", () => {
|
||||
it("resolves to an absolute docs-site guide, not a redirect stop", () => {
|
||||
expect(IMPORT_GUIDE_URL).toMatch(
|
||||
/^https:\/\/docs\.healthlog\.dev\/guides\/[a-z0-9-]+\/$/,
|
||||
);
|
||||
});
|
||||
|
||||
for (const card of CARDS) {
|
||||
it(`${card} links the external docs site, never an internal /docs path`, () => {
|
||||
const source = readFileSync(join(__dirname, "..", card), "utf8");
|
||||
|
||||
expect(source).not.toContain('href="/docs');
|
||||
expect(source).toContain("INTEGRATION_DOCS_BASE");
|
||||
expect(source).toContain("data-import");
|
||||
expect(source).toContain("IMPORT_GUIDE_URL");
|
||||
// External link hygiene for a new-tab docs jump.
|
||||
expect(source).toContain('rel="noopener noreferrer"');
|
||||
expect(source).toContain('target="_blank"');
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -4,3 +4,14 @@
|
||||
* before it ever reaches the route and feeds the live character counter.
|
||||
*/
|
||||
export const MAX_PASTE_CHARS = 16 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The CSV / JSON import guide on the public docs site.
|
||||
*
|
||||
* Both import cards used `${INTEGRATION_DOCS_BASE}/data-import`, which is
|
||||
* the wrong tree — the guide is not an integration runbook, and that path
|
||||
* now only resolves through a redirect. This is the canonical address, so
|
||||
* the link goes straight to the page. Kept here rather than in each card
|
||||
* because both cards point at the same guide.
|
||||
*/
|
||||
export const IMPORT_GUIDE_URL = "https://docs.healthlog.dev/guides/import-csv/";
|
||||
@@ -14,10 +14,9 @@ import { SettingsCardActions } from "@/components/settings/_card-actions";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { INTEGRATION_DOCS_BASE } from "@/components/settings/integrations/setup-guide-link";
|
||||
import { apiFetchRaw } from "@/lib/api/api-fetch";
|
||||
import { ImportCardShell } from "./import-card-shell";
|
||||
import { MAX_PASTE_CHARS } from "./constants";
|
||||
import { IMPORT_GUIDE_URL, MAX_PASTE_CHARS } from "./constants";
|
||||
import { EXAMPLE_CSV } from "./import-examples";
|
||||
import {
|
||||
CsvImportResultView,
|
||||
@@ -154,7 +153,7 @@ export function CsvImportCard() {
|
||||
{/* The import guide lives on the external docs site — the app
|
||||
itself serves no /docs tree, so an internal link 404s. */}
|
||||
<a
|
||||
href={`${INTEGRATION_DOCS_BASE}/data-import`}
|
||||
href={IMPORT_GUIDE_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline underline-offset-2"
|
||||
|
||||
@@ -8,10 +8,9 @@ import { SettingsCardActions } from "@/components/settings/_card-actions";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { INTEGRATION_DOCS_BASE } from "@/components/settings/integrations/setup-guide-link";
|
||||
import { apiFetchRaw } from "@/lib/api/api-fetch";
|
||||
import { ImportCardShell } from "./import-card-shell";
|
||||
import { MAX_PASTE_CHARS } from "./constants";
|
||||
import { IMPORT_GUIDE_URL, MAX_PASTE_CHARS } from "./constants";
|
||||
import {
|
||||
EXAMPLE_IMPORT_DOWNLOAD_HREF,
|
||||
parseImportJson,
|
||||
@@ -170,7 +169,7 @@ export function JsonImportCard() {
|
||||
{/* The import guide lives on the external docs site — the app
|
||||
itself serves no /docs tree, so an internal link 404s. */}
|
||||
<a
|
||||
href={`${INTEGRATION_DOCS_BASE}/data-import`}
|
||||
href={IMPORT_GUIDE_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline underline-offset-2"
|
||||
|
||||
Reference in new issue
Block a user