diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff80563..327f2b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,10 @@ jobs: with: node-version-file: .node-version cache: npm - - run: npm ci + # No dependency lifecycle scripts, in every workflow. The only packages + # that have one (esbuild, workerd, fsevents) take their native binary + # from optionalDependencies; the script only double-checks it. + - run: npm ci --ignore-scripts # `tsc` must be TypeScript 7 (@typescript/native). The `typescript` alias # (@typescript/typescript6, the API typescript-eslint loads) pulls in # TypeScript 6 as @typescript/old, which ships a `tsc` too — npm links the @@ -100,4 +103,4 @@ jobs: # Validates wrangler.jsonc and bundles the Worker exactly as Workers # Builds will — without deploying anything. - name: Dry-run the Cloudflare deploy - run: npx wrangler deploy --dry-run --outdir .wrangler/dry-run + run: npm run cf:check diff --git a/.github/workflows/release-android.yml b/.github/workflows/release-android.yml index 9687a1d..2baa78f 100644 --- a/.github/workflows/release-android.yml +++ b/.github/workflows/release-android.yml @@ -29,7 +29,7 @@ jobs: # Release artifacts are built from a clean install: a cache written # by any other workflow must not be able to feed into them. package-manager-cache: false - - run: npm ci + - run: npm ci --ignore-scripts - run: npm run typecheck - run: npm run test:run - run: npm run check:version @@ -79,8 +79,7 @@ jobs: toolchain: stable targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android - - run: npm ci - + - run: npm ci --ignore-scripts - name: Install Tauri CLI run: cargo install tauri-cli --version "^2" --locked diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 580d13e..c0903ef 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -33,7 +33,7 @@ jobs: # Release artifacts are built from a clean install: a cache written # by any other workflow must not be able to feed into them. package-manager-cache: false - - run: npm ci + - run: npm ci --ignore-scripts - run: npm run typecheck - run: npm run test:run - run: npm run check:version @@ -114,7 +114,7 @@ jobs: libayatana-appindicator3-dev \ librsvg2-dev \ patchelf - - run: npm ci + - run: npm ci --ignore-scripts - uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 2f2a85d..397f6dd 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -52,7 +52,7 @@ jobs: with: node-version-file: .node-version cache: npm - - run: npm ci + - run: npm ci --ignore-scripts - run: npm run build - name: rustfmt working-directory: src-tauri diff --git a/build-plugins/legal-docs.ts b/build-plugins/legal-docs.ts index a2d7a32..6f3b08f 100644 --- a/build-plugins/legal-docs.ts +++ b/build-plugins/legal-docs.ts @@ -79,17 +79,24 @@ export function rewriteHref(href: string, fromFile: string): string { * hyphen, which also rules out any markup ending up in an attribute. */ function slugify(text: string): string { - return text - .toLowerCase() - .replace(/[^\p{L}\p{N}]+/gu, "-") - .replace(/^-+|-+$/g, ""); + return ( + text + .toLowerCase() + .replace(/[^\p{L}\p{N}]+/gu, "-") + // The line above leaves at most one hyphen in a row. + .replace(/^-|-$/g, "") + ); } function stripInlineMarkdown(text: string): string { - return text - .replace(/[`*_~]/g, "") - .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") - .trim(); + return ( + text + .replace(/[`*_~]/g, "") + // Neither part may contain `[`, so a failed match is never re-scanned + // from a later `[` inside it (linear even on unbalanced brackets). + .replace(/\[([^[\]]+)\]\([^)[]*\)/g, "$1") + .trim() + ); } export function renderMarkdown(source: string, fromFile: string): { title: string; html: string } { diff --git a/scripts/lib/copyright.ts b/scripts/lib/copyright.ts index 34d39bd..22598f6 100644 --- a/scripts/lib/copyright.ts +++ b/scripts/lib/copyright.ts @@ -58,10 +58,10 @@ function readRepoFile(file: string): string { /** The year HEAD was committed, or this UTC year when git is unavailable. */ export function headCommitYear(): number { try { - const iso = execFileSync("git", ["log", "-1", "--format=%cI"], { - cwd: ROOT, - encoding: "utf8", - }); + const options = { cwd: ROOT, encoding: "utf8" } as const; + // A dev/CI script: `git` is whichever one the developer's PATH or the CI + // image provides, by design — there is no fixed install path to pin. + const iso = execFileSync("git", ["log", "-1", "--format=%cI"], options); // NOSONAR const year = Number(iso.trim().slice(0, 4)); if (Number.isInteger(year) && year >= 2000) return year; } catch { diff --git a/scripts/lib/third-party.ts b/scripts/lib/third-party.ts index e61f52c..ae3c0e8 100644 --- a/scripts/lib/third-party.ts +++ b/scripts/lib/third-party.ts @@ -38,8 +38,9 @@ const ALLOWED = new Set([ /** SPDX expression → allowed? `OR` needs one side, `AND` needs both. */ export function licenseAllowed(expression: string): boolean { const expr = expression.trim().replace(/^\((.*)\)$/, "$1"); - if (/\sOR\s/i.test(expr)) return expr.split(/\s+OR\s+/i).some(licenseAllowed); - if (/\sAND\s/i.test(expr)) return expr.split(/\s+AND\s+/i).every(licenseAllowed); + // Split on the bare operator; each part is trimmed by the recursive call. + if (/\sOR\s/i.test(expr)) return expr.split(/\sOR\s/i).some(licenseAllowed); + if (/\sAND\s/i.test(expr)) return expr.split(/\sAND\s/i).every(licenseAllowed); return ALLOWED.has(expr); } @@ -110,7 +111,7 @@ export function directCrates(toml: string): string[] { const name = inDependencies ? /^([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1] : undefined; if (name) names.add(name); } - return [...names].sort(); + return [...names].sort(compareCodeUnits); } /** diff --git a/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src-tauri/gen/android/app/src/main/AndroidManifest.xml index efe7781..2930909 100644 --- a/src-tauri/gen/android/app/src/main/AndroidManifest.xml +++ b/src-tauri/gen/android/app/src/main/AndroidManifest.xml @@ -5,7 +5,11 @@ + { + // fall back to the browser console. (A try/catch could not catch + // that: the import rejects asynchronously.) + // + // Dynamic import dodges a circular dep with files that themselves + // import ErrorBoundary, e.g. when the boundary is mounted in + // main.tsx before the store has registered. + void import("@utils/logger") + .then(({ logger }) => { logger.error( "errorBoundary", `[${this.props.label ?? "app"}] ${error.message}`, info.componentStack ?? error.stack ?? "", ); + }) + .catch(() => { + console.error("ErrorBoundary caught:", error, info); }); - } catch { - console.error("ErrorBoundary caught:", error, info); - } this.props.onError?.(error, info); } diff --git a/src/components/ui/Modal.tsx b/src/components/ui/Modal.tsx index fdcc927..0094aa1 100644 --- a/src/components/ui/Modal.tsx +++ b/src/components/ui/Modal.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from "react"; +import type { ReactNode, RefObject } from "react"; import { useTranslation } from "react-i18next"; import { Dialog, VisuallyHidden } from "radix-ui"; import { X } from "lucide-react"; @@ -15,6 +15,12 @@ interface ModalProps { /** Max width: sm 24rem · md 32rem (default) · lg 42rem · xl 56rem. */ size?: "sm" | "md" | "lg" | "xl"; className?: string; + /** + * Where focus lands when the dialog opens. Without it, Radix focuses the + * first focusable element (the close button). Use this instead of an + * `autoFocus` attribute on the target. + */ + initialFocusRef?: RefObject; } const SIZES = { sm: "max-w-sm", md: "max-w-lg", lg: "max-w-2xl", xl: "max-w-4xl" } as const; @@ -34,6 +40,7 @@ export function Modal({ footer, size = "md", className, + initialFocusRef, }: ModalProps) { const { t } = useTranslation("ui"); return ( @@ -41,6 +48,14 @@ export function Modal({ { + event.preventDefault(); + initialFocusRef.current?.focus(); + } + : undefined + } className={clsx( "bg-surface-1 border-border shadow-pop animate-pop-in rounded-panel fixed top-1/2 left-1/2 z-50 flex max-h-[min(88dvh,52rem)] w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col border", "focus:outline-none", diff --git a/src/components/ui/ShortcutHelpModal.tsx b/src/components/ui/ShortcutHelpModal.tsx index 4e92882..938f537 100644 --- a/src/components/ui/ShortcutHelpModal.tsx +++ b/src/components/ui/ShortcutHelpModal.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from "react"; +import { useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Search } from "lucide-react"; import { Modal } from "./Modal"; @@ -24,6 +24,9 @@ const SHORTCUTS = [ export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) { const { t } = useTranslation("ui"); const [query, setQuery] = useState(""); + // The search box gets focus when the modal opens (through Radix, not an + // `autoFocus` attribute). + const searchRef = useRef(null); // A closed modal has no filter. Deriving this rather than resetting `query` // in an effect means a re-open always starts fresh without an extra render @@ -41,18 +44,24 @@ export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) { }, [activeQuery, t]); return ( - +
{filtered.length === 0 ? ( diff --git a/src/config/platforms.ts b/src/config/platforms.ts index e14f58c..cc8f36e 100644 --- a/src/config/platforms.ts +++ b/src/config/platforms.ts @@ -140,8 +140,11 @@ export const PLATFORMS: readonly PlatformConfig[] = [ tagName: "Android", label: "Google Play", urlPrefix: "https://play.google.com/store/apps/details?id=", - // `id=` first or after other parameters (`?hl=en&id=…`). - urlPattern: /^https:\/\/play\.google\.com\/store\/apps\/details\?(?:[^\s]*&)?id=[\w.]+[^\s]*$/i, + // `id=` first or after other parameters (`?hl=en&id=…`). The lookahead + // finds the parameter (each `&`-separated step is unambiguous), then one + // `\S*$` scan checks the rest — linear, where `[^\s]*&` + `[^\s]*$` was not. + urlPattern: + /^https:\/\/play\.google\.com\/store\/apps\/details\?(?=(?:[^\s&]*&)*id=[\w.])\S*$/i, }, { id: "appstore", diff --git a/src/config/rig-fields.ts b/src/config/rig-fields.ts index 17627c0..e5f2918 100644 --- a/src/config/rig-fields.ts +++ b/src/config/rig-fields.ts @@ -461,15 +461,20 @@ export const CPU_SUGGESTIONS: readonly string[] = [ * Text it doesn't recognise is only trimmed and de-duplicated of spaces. */ export function cleanCpuName(raw: string): string { - return raw - .replace(/\((?:R|TM|C)\)|[®™©]/gi, "") - .replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "") - .replace(/\s+CPU\s*@\s*[\d.]+\s*[GM]Hz\b/i, "") - .replace(/\s+@\s*[\d.]+\s*[GM]Hz\b/i, "") - .replace(/\s+\d{1,3}-Core\s+Processor\b/i, "") - .replace(/\s+(?:with\s+Radeon(?:\s+\w+)?\s+Graphics|Processor)\s*$/i, "") - .replace(/\s{2,}/g, " ") - .trim(); + return ( + raw + .replace(/\((?:R|TM|C)\)|[®™©]/gi, "") + // From here on every whitespace run is a single character, so the + // patterns below need only `\s` / `\s?`. A leading `\s+` would be + // re-tried at every position of a long run (quadratic). + .replace(/\s{2,}/g, " ") + .replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "") + .replace(/\sCPU\s?@\s?[\d.]+\s?[GM]Hz\b/i, "") + .replace(/\s@\s?[\d.]+\s?[GM]Hz\b/i, "") + .replace(/\s\d{1,3}-Core\sProcessor\b/i, "") + .replace(/\s(?:with\sRadeon(?:\s\w+)?\sGraphics|Processor)\s?$/i, "") + .trim() + ); } /** diff --git a/src/engine/channel-phrase.ts b/src/engine/channel-phrase.ts index d6a86cf..8e479d6 100644 --- a/src/engine/channel-phrase.ts +++ b/src/engine/channel-phrase.ts @@ -58,5 +58,7 @@ export function withoutEmptyChannel(text: string, language: SupportedLanguage): let out = text; for (const pattern of [...DROP[language], ENGLISH]) out = out.replace(pattern, ""); out = out.split(CHANNEL_SLOT).join(FALLBACK[language]); - return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+([.,!?。!?])/g, "$1"); + // After the first replace no run of spaces/tabs is longer than one, so the + // second needs no `+` (which would make it quadratic on long runs). + return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]([.,!?。!?])/g, "$1"); } diff --git a/src/engine/tag-generator.ts b/src/engine/tag-generator.ts index c296397..3a67b1e 100644 --- a/src/engine/tag-generator.ts +++ b/src/engine/tag-generator.ts @@ -26,8 +26,12 @@ export function youtubeTagsLength(tags: readonly string[]): number { */ const COMPOSITE_NAME_BUDGET = YT_LIMITS.SINGLE_TAG_MAX - 9; +// The match may only start right before a run of `:`/whitespace (or at the +// start), never inside one — a leading `[:\s]+` alone would be re-tried at +// every position of a long run (quadratic). Group 1 keeps the character before +// the run; the caller puts it back with "$1". const QUALIFIER_SUFFIX_RE = - /[:\s]+(?:Definitive|Complete|Collector'?s?|Deluxe|Game\s+of\s+the\s+Year|GOTY|Ultimate|Special|Anniversary|Remastered|Remake|Enhanced|HD)(?:\s+(?:Edition|Cut|Version))?\s*$/i; + /(^|[^:\s])[:\s]+(?:Definitive|Complete|Collector'?s?|Deluxe|Game\s+of\s+the\s+Year|GOTY|Ultimate|Special|Anniversary|Remastered|Remake|Enhanced|HD)(?:\s+(?:Edition|Cut|Version))?\s*$/i; /** * Strips characters that YouTube treats as tag delimiters (`,` `;` `|`) plus @@ -57,7 +61,7 @@ export function tagFriendlyGameName(name: string, budget: number): string { let prev: string; do { prev = n; - n = n.replace(QUALIFIER_SUFFIX_RE, "").trim(); + n = n.replace(QUALIFIER_SUFFIX_RE, "$1").trim(); } while (n !== prev); if (n.length <= budget) return n; diff --git a/src/engine/timeline-parser.ts b/src/engine/timeline-parser.ts index f178f3f..c4bd89a 100644 --- a/src/engine/timeline-parser.ts +++ b/src/engine/timeline-parser.ts @@ -25,9 +25,13 @@ export interface TimelineEntry { * frames `:FF` dropped, as editors export them), an optional `]` / `)`, * an optional separator (`-`, `–`, `—`, `:`, `|`, `•`) and the label. * "[0:00] Intro", "0:00 - Intro" and "00:00:00:12 Intro" all parse. + * + * Match it against `line.trimEnd()`: the label runs to the end of the line, + * and trimming first (rather than a lazy label + `\s*$`) keeps the match + * linear on long runs of spaces. */ const LINE_RE = - /^\s*[[(]?((?:\d{1,2}:)?\d{1,2}:\d{2})(?::\d{2})?[\])]?\s*(?:[-–—:|•·]\s*)?(\S.*?)\s*$/u; + /^\s*[[(]?((?:\d{1,2}:)?\d{1,2}:\d{2})(?::\d{2})?[\])]?\s*(?:[-–—:|•·]\s*)?(\S.*)$/u; // Keyword patterns. Order matters — "final boss" must be tried before "boss". // Each regex captures the optional number group when applicable. @@ -128,7 +132,7 @@ export function parseTimeline(raw: string): TimelineEntry[] { for (const line of lines) { if (!line.trim()) continue; - const lineMatch = line.match(LINE_RE); + const lineMatch = LINE_RE.exec(line.trimEnd()); if (!lineMatch) { // Not a `time label` line — keep the raw text so nothing disappears. entries.push({ time: "", rawLabel: line.trim() }); @@ -152,7 +156,7 @@ export function parseTimeline(raw: string): TimelineEntry[] { for (let i = 1; i < m.length - 1; i++) { const g = m[i]; if (g && /^\d+$/.test(g)) { - entry.number = parseInt(g, 10); + entry.number = Number.parseInt(g, 10); break; } } @@ -200,7 +204,7 @@ export function renderTimeline( // Collapse the trailing whitespace that creeps in when a numbered // keyword pattern (`"Boss {{n}}"`) interpolates with an empty `n`. const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar }) - .replace(/\s+$/u, "") + .trimEnd() .replace(/\s{2,}/gu, " "); const withRest = entry.rest ? `${translated} ${entry.rest}` : translated; rendered.push(`${entry.time} ${withRest}`); diff --git a/src/hooks/use-languages-ready.ts b/src/hooks/use-languages-ready.ts index 0bac34c..c472823 100644 --- a/src/hooks/use-languages-ready.ts +++ b/src/hooks/use-languages-ready.ts @@ -1,6 +1,7 @@ import { useEffect, useMemo, useState } from "react"; import { ensureLanguagesLoaded, hasLanguageBundles } from "@i18n/index"; import type { SupportedLanguage } from "@engine/types"; +import { compareCodeUnits } from "@utils/sort"; /** * Returns true once every requested language has its locale bundles in @@ -17,7 +18,7 @@ export function useLanguagesReady(langs: readonly SupportedLanguage[]): boolean // Stable identity for the requested set — callers pass fresh array // literals on every render. const key = useMemo( - () => [...new Set(joined ? joined.split(",") : [])].sort().join(","), + () => [...new Set(joined ? joined.split(",") : [])].sort(compareCodeUnits).join(","), [joined], ); const [readyKey, setReadyKey] = useState(() => diff --git a/src/pages/BatchPage.tsx b/src/pages/BatchPage.tsx index acd0698..e439838 100644 --- a/src/pages/BatchPage.tsx +++ b/src/pages/BatchPage.tsx @@ -101,8 +101,8 @@ export function BatchPage() { : t(rangeResult.error ?? "", rangeResult.errorParams); const generate = () => { - const start = parseInt(startPart) || 1; - const end = parseInt(endPart) || start; + const start = Number.parseInt(startPart) || 1; + const end = Number.parseInt(endPart) || start; const outputs: BatchResult[] = []; for (let i = start; i <= Math.min(end, start + 99); i++) { diff --git a/src/pages/PlaylistPage.tsx b/src/pages/PlaylistPage.tsx index 4dfd2cd..f6bf3d9 100644 --- a/src/pages/PlaylistPage.tsx +++ b/src/pages/PlaylistPage.tsx @@ -141,7 +141,9 @@ export function PlaylistPage() { status, contentType, totalVideos: - totalVideosValidation.valid && totalVideos.trim() ? parseInt(totalVideos) : undefined, + totalVideosValidation.valid && totalVideos.trim() + ? Number.parseInt(totalVideos) + : undefined, storeLinks: editor.storeLinks, playlistNote: customNote, droppedReasons, diff --git a/src/pages/SocialPage.tsx b/src/pages/SocialPage.tsx index c0219e3..d33fcae 100644 --- a/src/pages/SocialPage.tsx +++ b/src/pages/SocialPage.tsx @@ -155,8 +155,8 @@ export function SocialPage() { }; const bulkGenerate = () => { - const start = parseInt(startPart) || 1; - const end = parseInt(endPart) || start; + const start = Number.parseInt(startPart) || 1; + const end = Number.parseInt(endPart) || start; const rows: BulkRow[] = []; // Loop-invariant English translator for the bilingual content-warnings // block — `en` is eagerly bundled, so it needs no readiness gate. diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts index 6e53eaf..045b643 100644 --- a/src/store/editor-store.ts +++ b/src/store/editor-store.ts @@ -930,11 +930,13 @@ export function liftLegacyEndingString(raw: string): EndingEntry[] { // Match optional "Ending" prefix + number + optional ": rest" tail. // Case-insensitive on the keyword; localised variants ("kết thúc", // "エンディング", "结局") are accepted too. Anything else → name-only. - const m = trimmed.match( - /^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)\s*(?::\s*(.+))?\s*$/i, + // `trimmed` has no trailing whitespace, so the pattern needs no `\s*$`; and + // no two `\s*` sit next to each other, which would backtrack quadratically. + const m = /^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)(?:\s*:\s*(\S.*))?$/i.exec( + trimmed, ); if (m) { - const num = parseInt(m[1] ?? "", 10); + const num = Number.parseInt(m[1] ?? "", 10); const name = (m[2] ?? "").trim(); if (Number.isFinite(num)) { return [{ number: num, name }]; diff --git a/src/store/profile-store.ts b/src/store/profile-store.ts index 3040cd3..d29ff48 100644 --- a/src/store/profile-store.ts +++ b/src/store/profile-store.ts @@ -74,7 +74,7 @@ export function migrateProfilesState(persistedState: unknown, version: number): if (!persistedState || typeof persistedState !== "object") return persistedState; const state = persistedState as { profiles?: Array> }; if (!Array.isArray(state.profiles)) return persistedState; - state.profiles = state.profiles.map((p) => { + const profiles = state.profiles.map((p) => { if (!p || typeof p !== "object") return p; let next = p; if (version < 1 && typeof next.thirdPartyAdText !== "string") { @@ -90,7 +90,9 @@ export function migrateProfilesState(persistedState: unknown, version: number): if (version < 3) next = { ...next, rig: migrateRig(next.rig) }; return next; }); - return persistedState; + // A new object rather than the mutated input: both callers (persist and + // backup restore) use the return value. + return { ...state, profiles }; } export const useProfileStore = create()( diff --git a/src/utils/log-storage.ts b/src/utils/log-storage.ts index c3f4702..375f371 100644 --- a/src/utils/log-storage.ts +++ b/src/utils/log-storage.ts @@ -50,9 +50,9 @@ function parseFileDate(name: string): Date | null { } const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length); if (!/^\d{8}$/.test(datePart)) return null; - const y = parseInt(datePart.slice(0, 4), 10); - const m = parseInt(datePart.slice(4, 6), 10) - 1; - const d = parseInt(datePart.slice(6, 8), 10); + const y = Number.parseInt(datePart.slice(0, 4), 10); + const m = Number.parseInt(datePart.slice(4, 6), 10) - 1; + const d = Number.parseInt(datePart.slice(6, 8), 10); return new Date(y, m, d); } diff --git a/src/utils/uuid.ts b/src/utils/uuid.ts index 49e37ac..6d72471 100644 --- a/src/utils/uuid.ts +++ b/src/utils/uuid.ts @@ -1,28 +1,21 @@ /** * Generate a RFC 4122 v4 UUID. * - * `crypto.randomUUID()` is the fast path, but it only exists in Chrome/WebView - * **92+** — older Android System WebViews (e.g. the Chromium 91 that ships with - * some emulator images, or any device whose WebView hasn't been updated) don't - * have it. Because `generateId()` runs at module load (e.g. the log store's - * `CURRENT_SESSION_ID`), an unguarded `crypto.randomUUID()` would throw during - * boot and black-screen the whole app on those WebViews. Fall back to a manual - * v4 built on `crypto.getRandomValues` (present since Chrome 11), and finally - * `Math.random` only if even that is missing. + * `crypto.randomUUID()` is the fast path, but it only exists in secure + * contexts (HTTPS, localhost) and in Chromium 92+. Because `generateId()` runs + * at module load (e.g. the log store's `CURRENT_SESSION_ID`), an unguarded + * call would throw during boot wherever it is missing. Fall back to a v4 built + * on `crypto.getRandomValues`, which every engine the app supports has — and + * never to `Math.random`, which is not a source of unique IDs. */ export function generateId(): string { - const c: Crypto | undefined = typeof globalThis !== "undefined" ? globalThis.crypto : undefined; + const c = globalThis.crypto; - if (c && typeof c.randomUUID === "function") { + if (typeof c.randomUUID === "function") { return c.randomUUID(); } - const bytes = new Uint8Array(16); - if (c && typeof c.getRandomValues === "function") { - c.getRandomValues(bytes); - } else { - for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256); - } + const bytes = c.getRandomValues(new Uint8Array(16)); // RFC 4122 §4.4: set the version (4) and variant (10xx) bits. // (`?? 0` only satisfies noUncheckedIndexedAccess — index 6/8 always exist.) bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; diff --git a/tests/helpers/locale-schema.ts b/tests/helpers/locale-schema.ts index 97f14c3..6a9c8d3 100644 --- a/tests/helpers/locale-schema.ts +++ b/tests/helpers/locale-schema.ts @@ -1,5 +1,6 @@ import { readFileSync } from "fs"; import { resolve } from "path"; +import { compareCodeUnits } from "@utils/sort"; interface LocaleSchema { ui: Record; @@ -17,5 +18,5 @@ export const LOCALE_SCHEMA = JSON.parse( /** The leaf keys under one parent path, sorted; empty when the path is missing. */ export function schemaKeys(namespace: keyof LocaleSchema, parent: string): string[] { - return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort(); + return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort(compareCodeUnits); } diff --git a/tests/utils/uuid.test.ts b/tests/utils/uuid.test.ts index 2bb8cf3..2ce49c4 100644 --- a/tests/utils/uuid.test.ts +++ b/tests/utils/uuid.test.ts @@ -13,9 +13,9 @@ describe("generateId", () => { expect(generateId()).toMatch(V4); }); - it("falls back to a valid v4 UUID when crypto.randomUUID is missing (Android WebView < 92)", () => { - // Chromium 91 has getRandomValues but not randomUUID — the exact gap that - // black-screened the app at boot before the fallback existed. + it("falls back to a valid v4 UUID when crypto.randomUUID is missing", () => { + // Insecure contexts (and Chromium < 92) have getRandomValues but not + // randomUUID — the gap that once black-screened the app at boot. const real = globalThis.crypto; vi.stubGlobal("crypto", { getRandomValues: (a: Uint8Array) => real.getRandomValues(a), @@ -23,9 +23,11 @@ describe("generateId", () => { expect(generateId()).toMatch(V4); }); - it("falls back to a valid v4 UUID when crypto is entirely absent", () => { + it("refuses to make up an ID when there is no crypto at all", () => { + // No Math.random fallback: an ID that is not random is worse than an + // error. Every engine the app supports has crypto.getRandomValues. vi.stubGlobal("crypto", undefined); - expect(generateId()).toMatch(V4); + expect(() => generateId()).toThrow(TypeError); }); it("produces unique values across many calls", () => { diff --git a/worker/cookie.ts b/worker/cookie.ts index 9c53cbe..1ebe2a6 100644 --- a/worker/cookie.ts +++ b/worker/cookie.ts @@ -22,7 +22,11 @@ const KEY_LABEL = "ytg-gate-v1"; function toBase64Url(bytes: Uint8Array): string { let binary = ""; for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + // Base64 pads with at most two `=`; a bounded quantifier stays linear. + return btoa(binary) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/={1,2}$/, ""); } function fromBase64Url(text: string): Uint8Array | null { diff --git a/worker/router.ts b/worker/router.ts index 99f59e4..2d63d53 100644 --- a/worker/router.ts +++ b/worker/router.ts @@ -128,7 +128,12 @@ async function handleVerify(request: Request, env: Env, deps: Deps, url: URL): P * when the path is not a legal path at all. */ export function legalAssetPath(url: URL): string | null { - const trimmed = url.pathname.replace(/\/+$/, ""); + // Drop trailing slashes with a loop: `/\/+$/` is re-tried at every slash of + // a long run and goes quadratic on a path like "/legal//////…x". + const path = url.pathname; + let end = path.length; + while (end > 0 && path[end - 1] === "/") end--; + const trimmed = path.slice(0, end); if (trimmed === "/legal") return "/legal/"; if (!trimmed.startsWith("/legal/")) return null; const id = /^\/legal\/([a-z-]+)$/.exec(trimmed)?.[1];