fix(quality): clear the 44 open SonarCloud issues

Regexes with super-linear backtracking (S8786 x16) are rewritten to stay
linear on long runs; each new pattern gives the same results as the old one
on 150k-450k fuzzed inputs (except where noted) and finishes adversarial
50k-character inputs in under 3 ms:
- tag-generator QUALIFIER_SUFFIX_RE starts just before a `:`/space run
  (`(^|[^:\s])…` + "$1"), never inside one
- timeline-parser matches `line.trimEnd()` with a greedy label, and renders
  with trimEnd(); cleanCpuName collapses whitespace before the patterns
- editor-store endings, Google Play urlPattern (lookahead for `id=`),
  channel-phrase punctuation, SPDX OR/AND split, legal-docs slug and link
  stripping (link text/URL may not contain `[`), base64url padding, and a
  loop for trailing slashes in the worker router

Others:
- S2871: sorts take the shared code-unit comparator (same order as before;
  THIRD_PARTY_NOTICES is unchanged)
- S4822: ErrorBoundary catches the logger import with .catch(), which a
  try/catch never could
- S3516: migrateProfilesState returns a new object
- S7773: Number.parseInt (x10)
- S9379: Modal takes an initialFocusRef (Radix onOpenAutoFocus), so the
  shortcut search box gets focus without an autoFocus attribute
- S2245: generateId drops the Math.random fallback; getRandomValues exists
  everywhere the app runs, and a non-random ID is worse than an error
- S4036: NOSONAR on the dev script's `git` call (PATH lookup by design)
- S6505/S8543: every workflow installs with `npm ci --ignore-scripts`, and CI
  runs `npm run cf:check` instead of `npx wrangler …`
- S6358: Android sets allowBackup="false" — app data is no longer copied to
  Google Drive backups; Backup & Restore moves it to a new phone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-22 15:05:16 +07:00
1 parent abfcd96eb5
commit 886d25b588
28 files changed
+162 -92

No files matched your search

+5 -2
View File
@@ -35,7 +35,10 @@ jobs:
with: with:
node-version-file: .node-version node-version-file: .node-version
cache: npm 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 # `tsc` must be TypeScript 7 (@typescript/native). The `typescript` alias
# (@typescript/typescript6, the API typescript-eslint loads) pulls in # (@typescript/typescript6, the API typescript-eslint loads) pulls in
# TypeScript 6 as @typescript/old, which ships a `tsc` too — npm links the # 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 # Validates wrangler.jsonc and bundles the Worker exactly as Workers
# Builds will — without deploying anything. # Builds will — without deploying anything.
- name: Dry-run the Cloudflare deploy - name: Dry-run the Cloudflare deploy
run: npx wrangler deploy --dry-run --outdir .wrangler/dry-run run: npm run cf:check
+2 -3
View File
@@ -29,7 +29,7 @@ jobs:
# Release artifacts are built from a clean install: a cache written # Release artifacts are built from a clean install: a cache written
# by any other workflow must not be able to feed into them. # by any other workflow must not be able to feed into them.
package-manager-cache: false package-manager-cache: false
- run: npm ci - run: npm ci --ignore-scripts
- run: npm run typecheck - run: npm run typecheck
- run: npm run test:run - run: npm run test:run
- run: npm run check:version - run: npm run check:version
@@ -79,8 +79,7 @@ jobs:
toolchain: stable toolchain: stable
targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android 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 - name: Install Tauri CLI
run: cargo install tauri-cli --version "^2" --locked run: cargo install tauri-cli --version "^2" --locked
+2 -2
View File
@@ -33,7 +33,7 @@ jobs:
# Release artifacts are built from a clean install: a cache written # Release artifacts are built from a clean install: a cache written
# by any other workflow must not be able to feed into them. # by any other workflow must not be able to feed into them.
package-manager-cache: false package-manager-cache: false
- run: npm ci - run: npm ci --ignore-scripts
- run: npm run typecheck - run: npm run typecheck
- run: npm run test:run - run: npm run test:run
- run: npm run check:version - run: npm run check:version
@@ -114,7 +114,7 @@ jobs:
libayatana-appindicator3-dev \ libayatana-appindicator3-dev \
librsvg2-dev \ librsvg2-dev \
patchelf patchelf
- run: npm ci - run: npm ci --ignore-scripts
- uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0 - uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -52,7 +52,7 @@ jobs:
with: with:
node-version-file: .node-version node-version-file: .node-version
cache: npm cache: npm
- run: npm ci - run: npm ci --ignore-scripts
- run: npm run build - run: npm run build
- name: rustfmt - name: rustfmt
working-directory: src-tauri working-directory: src-tauri
+15 -8
View File
@@ -79,17 +79,24 @@ export function rewriteHref(href: string, fromFile: string): string {
* hyphen, which also rules out any markup ending up in an attribute. * hyphen, which also rules out any markup ending up in an attribute.
*/ */
function slugify(text: string): string { function slugify(text: string): string {
return text return (
.toLowerCase() text
.replace(/[^\p{L}\p{N}]+/gu, "-") .toLowerCase()
.replace(/^-+|-+$/g, ""); .replace(/[^\p{L}\p{N}]+/gu, "-")
// The line above leaves at most one hyphen in a row.
.replace(/^-|-$/g, "")
);
} }
function stripInlineMarkdown(text: string): string { function stripInlineMarkdown(text: string): string {
return text return (
.replace(/[`*_~]/g, "") text
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") .replace(/[`*_~]/g, "")
.trim(); // 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 } { export function renderMarkdown(source: string, fromFile: string): { title: string; html: string } {
+4 -4
View File
@@ -58,10 +58,10 @@ function readRepoFile(file: string): string {
/** The year HEAD was committed, or this UTC year when git is unavailable. */ /** The year HEAD was committed, or this UTC year when git is unavailable. */
export function headCommitYear(): number { export function headCommitYear(): number {
try { try {
const iso = execFileSync("git", ["log", "-1", "--format=%cI"], { const options = { cwd: ROOT, encoding: "utf8" } as const;
cwd: ROOT, // A dev/CI script: `git` is whichever one the developer's PATH or the CI
encoding: "utf8", // 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)); const year = Number(iso.trim().slice(0, 4));
if (Number.isInteger(year) && year >= 2000) return year; if (Number.isInteger(year) && year >= 2000) return year;
} catch { } catch {
+4 -3
View File
@@ -38,8 +38,9 @@ const ALLOWED = new Set([
/** SPDX expression → allowed? `OR` needs one side, `AND` needs both. */ /** SPDX expression → allowed? `OR` needs one side, `AND` needs both. */
export function licenseAllowed(expression: string): boolean { export function licenseAllowed(expression: string): boolean {
const expr = expression.trim().replace(/^\((.*)\)$/, "$1"); const expr = expression.trim().replace(/^\((.*)\)$/, "$1");
if (/\sOR\s/i.test(expr)) return expr.split(/\s+OR\s+/i).some(licenseAllowed); // Split on the bare operator; each part is trimmed by the recursive call.
if (/\sAND\s/i.test(expr)) return expr.split(/\s+AND\s+/i).every(licenseAllowed); 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); 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; const name = inDependencies ? /^([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1] : undefined;
if (name) names.add(name); if (name) names.add(name);
} }
return [...names].sort(); return [...names].sort(compareCodeUnits);
} }
/** /**
@@ -5,7 +5,11 @@
<!-- AndroidTV support --> <!-- AndroidTV support -->
<uses-feature android:name="android.software.leanback" android:required="false" /> <uses-feature android:name="android.software.leanback" android:required="false" />
<!-- allowBackup="false": the app's data (localStorage in the WebView) stays
on the device and is never copied to Google Drive backups. Users move
it to a new phone with the app's own Backup & Restore file. -->
<application <application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@style/Theme.yt_desc_gen" android:theme="@style/Theme.yt_desc_gen"
+11 -9
View File
@@ -55,21 +55,23 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
// Best-effort: pull the in-app logger lazily so the boundary stays // Best-effort: pull the in-app logger lazily so the boundary stays
// importable from non-React entry points. We never let the logger // importable from non-React entry points. We never let the logger
// itself throw a secondary error — if the log store is missing we // itself throw a secondary error — if the log store is missing we
// fall back to the browser console. // fall back to the browser console. (A try/catch could not catch
try { // 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 // Dynamic import dodges a circular dep with files that themselves
// main.tsx before the store has registered. // import ErrorBoundary, e.g. when the boundary is mounted in
void import("@utils/logger").then(({ logger }) => { // main.tsx before the store has registered.
void import("@utils/logger")
.then(({ logger }) => {
logger.error( logger.error(
"errorBoundary", "errorBoundary",
`[${this.props.label ?? "app"}] ${error.message}`, `[${this.props.label ?? "app"}] ${error.message}`,
info.componentStack ?? error.stack ?? "", info.componentStack ?? error.stack ?? "",
); );
})
.catch(() => {
console.error("ErrorBoundary caught:", error, info);
}); });
} catch {
console.error("ErrorBoundary caught:", error, info);
}
this.props.onError?.(error, info); this.props.onError?.(error, info);
} }
+16 -1
View File
@@ -1,4 +1,4 @@
import type { ReactNode } from "react"; import type { ReactNode, RefObject } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Dialog, VisuallyHidden } from "radix-ui"; import { Dialog, VisuallyHidden } from "radix-ui";
import { X } from "lucide-react"; import { X } from "lucide-react";
@@ -15,6 +15,12 @@ interface ModalProps {
/** Max width: sm 24rem · md 32rem (default) · lg 42rem · xl 56rem. */ /** Max width: sm 24rem · md 32rem (default) · lg 42rem · xl 56rem. */
size?: "sm" | "md" | "lg" | "xl"; size?: "sm" | "md" | "lg" | "xl";
className?: string; 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<HTMLElement | null>;
} }
const SIZES = { sm: "max-w-sm", md: "max-w-lg", lg: "max-w-2xl", xl: "max-w-4xl" } as const; 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, footer,
size = "md", size = "md",
className, className,
initialFocusRef,
}: ModalProps) { }: ModalProps) {
const { t } = useTranslation("ui"); const { t } = useTranslation("ui");
return ( return (
@@ -41,6 +48,14 @@ export function Modal({
<Dialog.Portal> <Dialog.Portal>
<Dialog.Overlay className="bg-overlay animate-fade-in fixed inset-0 z-50 backdrop-blur-[2px]" /> <Dialog.Overlay className="bg-overlay animate-fade-in fixed inset-0 z-50 backdrop-blur-[2px]" />
<Dialog.Content <Dialog.Content
onOpenAutoFocus={
initialFocusRef
? (event) => {
event.preventDefault();
initialFocusRef.current?.focus();
}
: undefined
}
className={clsx( 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", "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", "focus:outline-none",
+12 -3
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from "react"; import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Search } from "lucide-react"; import { Search } from "lucide-react";
import { Modal } from "./Modal"; import { Modal } from "./Modal";
@@ -24,6 +24,9 @@ const SHORTCUTS = [
export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) { export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) {
const { t } = useTranslation("ui"); const { t } = useTranslation("ui");
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
// The search box gets focus when the modal opens (through Radix, not an
// `autoFocus` attribute).
const searchRef = useRef<HTMLInputElement>(null);
// A closed modal has no filter. Deriving this rather than resetting `query` // 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 // 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]); }, [activeQuery, t]);
return ( return (
<Modal open={open} onClose={onClose} title={t("shortcuts.title")} size="sm"> <Modal
open={open}
onClose={onClose}
title={t("shortcuts.title")}
size="sm"
initialFocusRef={searchRef}
>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<label className="border-border bg-surface-0 focus-within:border-accent focus-within:ring-accent/25 h-control rounded-control flex items-center gap-2 border px-3 transition-colors focus-within:ring-2"> <label className="border-border bg-surface-0 focus-within:border-accent focus-within:ring-accent/25 h-control rounded-control flex items-center gap-2 border px-3 transition-colors focus-within:ring-2">
<Search className="text-text-muted size-4 shrink-0" aria-hidden="true" /> <Search className="text-text-muted size-4 shrink-0" aria-hidden="true" />
<input <input
ref={searchRef}
type="search" type="search"
value={activeQuery} value={activeQuery}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
placeholder={t("shortcuts.searchPlaceholder")} placeholder={t("shortcuts.searchPlaceholder")}
aria-label={t("shortcuts.searchPlaceholder")} aria-label={t("shortcuts.searchPlaceholder")}
className="text-text-primary placeholder:text-text-muted w-full bg-transparent text-sm outline-none" className="text-text-primary placeholder:text-text-muted w-full bg-transparent text-sm outline-none"
autoFocus
/> />
</label> </label>
{filtered.length === 0 ? ( {filtered.length === 0 ? (
+5 -2
View File
@@ -140,8 +140,11 @@ export const PLATFORMS: readonly PlatformConfig[] = [
tagName: "Android", tagName: "Android",
label: "Google Play", label: "Google Play",
urlPrefix: "https://play.google.com/store/apps/details?id=", urlPrefix: "https://play.google.com/store/apps/details?id=",
// `id=` first or after other parameters (`?hl=en&id=…`). // `id=` first or after other parameters (`?hl=en&id=…`). The lookahead
urlPattern: /^https:\/\/play\.google\.com\/store\/apps\/details\?(?:[^\s]*&)?id=[\w.]+[^\s]*$/i, // 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", id: "appstore",
+14 -9
View File
@@ -461,15 +461,20 @@ export const CPU_SUGGESTIONS: readonly string[] = [
* Text it doesn't recognise is only trimmed and de-duplicated of spaces. * Text it doesn't recognise is only trimmed and de-duplicated of spaces.
*/ */
export function cleanCpuName(raw: string): string { export function cleanCpuName(raw: string): string {
return raw return (
.replace(/\((?:R|TM|C)\)|[®™©]/gi, "") raw
.replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "") .replace(/\((?:R|TM|C)\)|[®™©]/gi, "")
.replace(/\s+CPU\s*@\s*[\d.]+\s*[GM]Hz\b/i, "") // From here on every whitespace run is a single character, so the
.replace(/\s+@\s*[\d.]+\s*[GM]Hz\b/i, "") // patterns below need only `\s` / `\s?`. A leading `\s+` would be
.replace(/\s+\d{1,3}-Core\s+Processor\b/i, "") // re-tried at every position of a long run (quadratic).
.replace(/\s+(?:with\s+Radeon(?:\s+\w+)?\s+Graphics|Processor)\s*$/i, "") .replace(/\s{2,}/g, " ")
.replace(/\s{2,}/g, " ") .replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "")
.trim(); .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()
);
} }
/** /**
+3 -1
View File
@@ -58,5 +58,7 @@ export function withoutEmptyChannel(text: string, language: SupportedLanguage):
let out = text; let out = text;
for (const pattern of [...DROP[language], ENGLISH]) out = out.replace(pattern, ""); for (const pattern of [...DROP[language], ENGLISH]) out = out.replace(pattern, "");
out = out.split(CHANNEL_SLOT).join(FALLBACK[language]); 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");
} }
+6 -2
View File
@@ -26,8 +26,12 @@ export function youtubeTagsLength(tags: readonly string[]): number {
*/ */
const COMPOSITE_NAME_BUDGET = YT_LIMITS.SINGLE_TAG_MAX - 9; 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 = 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 * Strips characters that YouTube treats as tag delimiters (`,` `;` `|`) plus
@@ -57,7 +61,7 @@ export function tagFriendlyGameName(name: string, budget: number): string {
let prev: string; let prev: string;
do { do {
prev = n; prev = n;
n = n.replace(QUALIFIER_SUFFIX_RE, "").trim(); n = n.replace(QUALIFIER_SUFFIX_RE, "$1").trim();
} while (n !== prev); } while (n !== prev);
if (n.length <= budget) return n; if (n.length <= budget) return n;
+8 -4
View File
@@ -25,9 +25,13 @@ export interface TimelineEntry {
* frames `:FF` dropped, as editors export them), an optional `]` / `)`, * frames `:FF` dropped, as editors export them), an optional `]` / `)`,
* an optional separator (`-`, `–`, `—`, `:`, `|`, `•`) and the label. * an optional separator (`-`, `–`, `—`, `:`, `|`, `•`) and the label.
* "[0:00] Intro", "0:00 - Intro" and "00:00:00:12 Intro" all parse. * "[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 = 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". // Keyword patterns. Order matters — "final boss" must be tried before "boss".
// Each regex captures the optional number group when applicable. // Each regex captures the optional number group when applicable.
@@ -128,7 +132,7 @@ export function parseTimeline(raw: string): TimelineEntry[] {
for (const line of lines) { for (const line of lines) {
if (!line.trim()) continue; if (!line.trim()) continue;
const lineMatch = line.match(LINE_RE); const lineMatch = LINE_RE.exec(line.trimEnd());
if (!lineMatch) { if (!lineMatch) {
// Not a `time label` line — keep the raw text so nothing disappears. // Not a `time label` line — keep the raw text so nothing disappears.
entries.push({ time: "", rawLabel: line.trim() }); 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++) { for (let i = 1; i < m.length - 1; i++) {
const g = m[i]; const g = m[i];
if (g && /^\d+$/.test(g)) { if (g && /^\d+$/.test(g)) {
entry.number = parseInt(g, 10); entry.number = Number.parseInt(g, 10);
break; break;
} }
} }
@@ -200,7 +204,7 @@ export function renderTimeline(
// Collapse the trailing whitespace that creeps in when a numbered // Collapse the trailing whitespace that creeps in when a numbered
// keyword pattern (`"Boss {{n}}"`) interpolates with an empty `n`. // keyword pattern (`"Boss {{n}}"`) interpolates with an empty `n`.
const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar }) const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar })
.replace(/\s+$/u, "") .trimEnd()
.replace(/\s{2,}/gu, " "); .replace(/\s{2,}/gu, " ");
const withRest = entry.rest ? `${translated} ${entry.rest}` : translated; const withRest = entry.rest ? `${translated} ${entry.rest}` : translated;
rendered.push(`${entry.time} ${withRest}`); rendered.push(`${entry.time} ${withRest}`);
+2 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { ensureLanguagesLoaded, hasLanguageBundles } from "@i18n/index"; import { ensureLanguagesLoaded, hasLanguageBundles } from "@i18n/index";
import type { SupportedLanguage } from "@engine/types"; import type { SupportedLanguage } from "@engine/types";
import { compareCodeUnits } from "@utils/sort";
/** /**
* Returns true once every requested language has its locale bundles in * 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 // Stable identity for the requested set — callers pass fresh array
// literals on every render. // literals on every render.
const key = useMemo( const key = useMemo(
() => [...new Set(joined ? joined.split(",") : [])].sort().join(","), () => [...new Set(joined ? joined.split(",") : [])].sort(compareCodeUnits).join(","),
[joined], [joined],
); );
const [readyKey, setReadyKey] = useState<string | null>(() => const [readyKey, setReadyKey] = useState<string | null>(() =>
+2 -2
View File
@@ -101,8 +101,8 @@ export function BatchPage() {
: t(rangeResult.error ?? "", rangeResult.errorParams); : t(rangeResult.error ?? "", rangeResult.errorParams);
const generate = () => { const generate = () => {
const start = parseInt(startPart) || 1; const start = Number.parseInt(startPart) || 1;
const end = parseInt(endPart) || start; const end = Number.parseInt(endPart) || start;
const outputs: BatchResult[] = []; const outputs: BatchResult[] = [];
for (let i = start; i <= Math.min(end, start + 99); i++) { for (let i = start; i <= Math.min(end, start + 99); i++) {
+3 -1
View File
@@ -141,7 +141,9 @@ export function PlaylistPage() {
status, status,
contentType, contentType,
totalVideos: totalVideos:
totalVideosValidation.valid && totalVideos.trim() ? parseInt(totalVideos) : undefined, totalVideosValidation.valid && totalVideos.trim()
? Number.parseInt(totalVideos)
: undefined,
storeLinks: editor.storeLinks, storeLinks: editor.storeLinks,
playlistNote: customNote, playlistNote: customNote,
droppedReasons, droppedReasons,
+2 -2
View File
@@ -155,8 +155,8 @@ export function SocialPage() {
}; };
const bulkGenerate = () => { const bulkGenerate = () => {
const start = parseInt(startPart) || 1; const start = Number.parseInt(startPart) || 1;
const end = parseInt(endPart) || start; const end = Number.parseInt(endPart) || start;
const rows: BulkRow[] = []; const rows: BulkRow[] = [];
// Loop-invariant English translator for the bilingual content-warnings // Loop-invariant English translator for the bilingual content-warnings
// block — `en` is eagerly bundled, so it needs no readiness gate. // block — `en` is eagerly bundled, so it needs no readiness gate.
+5 -3
View File
@@ -930,11 +930,13 @@ export function liftLegacyEndingString(raw: string): EndingEntry[] {
// Match optional "Ending" prefix + number + optional ": rest" tail. // Match optional "Ending" prefix + number + optional ": rest" tail.
// Case-insensitive on the keyword; localised variants ("kết thúc", // Case-insensitive on the keyword; localised variants ("kết thúc",
// "エンディング", "结局") are accepted too. Anything else → name-only. // "エンディング", "结局") are accepted too. Anything else → name-only.
const m = trimmed.match( // `trimmed` has no trailing whitespace, so the pattern needs no `\s*$`; and
/^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)\s*(?::\s*(.+))?\s*$/i, // 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) { if (m) {
const num = parseInt(m[1] ?? "", 10); const num = Number.parseInt(m[1] ?? "", 10);
const name = (m[2] ?? "").trim(); const name = (m[2] ?? "").trim();
if (Number.isFinite(num)) { if (Number.isFinite(num)) {
return [{ number: num, name }]; return [{ number: num, name }];
+4 -2
View File
@@ -74,7 +74,7 @@ export function migrateProfilesState(persistedState: unknown, version: number):
if (!persistedState || typeof persistedState !== "object") return persistedState; if (!persistedState || typeof persistedState !== "object") return persistedState;
const state = persistedState as { profiles?: Array<Record<string, unknown>> }; const state = persistedState as { profiles?: Array<Record<string, unknown>> };
if (!Array.isArray(state.profiles)) return persistedState; 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; if (!p || typeof p !== "object") return p;
let next = p; let next = p;
if (version < 1 && typeof next.thirdPartyAdText !== "string") { 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) }; if (version < 3) next = { ...next, rig: migrateRig(next.rig) };
return next; 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<ProfileState>()( export const useProfileStore = create<ProfileState>()(
+3 -3
View File
@@ -50,9 +50,9 @@ function parseFileDate(name: string): Date | null {
} }
const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length); const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);
if (!/^\d{8}$/.test(datePart)) return null; if (!/^\d{8}$/.test(datePart)) return null;
const y = parseInt(datePart.slice(0, 4), 10); const y = Number.parseInt(datePart.slice(0, 4), 10);
const m = parseInt(datePart.slice(4, 6), 10) - 1; const m = Number.parseInt(datePart.slice(4, 6), 10) - 1;
const d = parseInt(datePart.slice(6, 8), 10); const d = Number.parseInt(datePart.slice(6, 8), 10);
return new Date(y, m, d); return new Date(y, m, d);
} }
+9 -16
View File
@@ -1,28 +1,21 @@
/** /**
* Generate a RFC 4122 v4 UUID. * Generate a RFC 4122 v4 UUID.
* *
* `crypto.randomUUID()` is the fast path, but it only exists in Chrome/WebView * `crypto.randomUUID()` is the fast path, but it only exists in secure
* **92+** — older Android System WebViews (e.g. the Chromium 91 that ships with * contexts (HTTPS, localhost) and in Chromium 92+. Because `generateId()` runs
* some emulator images, or any device whose WebView hasn't been updated) don't * at module load (e.g. the log store's `CURRENT_SESSION_ID`), an unguarded
* have it. Because `generateId()` runs at module load (e.g. the log store's * call would throw during boot wherever it is missing. Fall back to a v4 built
* `CURRENT_SESSION_ID`), an unguarded `crypto.randomUUID()` would throw during * on `crypto.getRandomValues`, which every engine the app supports has — and
* boot and black-screen the whole app on those WebViews. Fall back to a manual * never to `Math.random`, which is not a source of unique IDs.
* v4 built on `crypto.getRandomValues` (present since Chrome 11), and finally
* `Math.random` only if even that is missing.
*/ */
export function generateId(): string { 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(); return c.randomUUID();
} }
const bytes = new Uint8Array(16); const bytes = c.getRandomValues(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);
}
// RFC 4122 §4.4: set the version (4) and variant (10xx) bits. // RFC 4122 §4.4: set the version (4) and variant (10xx) bits.
// (`?? 0` only satisfies noUncheckedIndexedAccess — index 6/8 always exist.) // (`?? 0` only satisfies noUncheckedIndexedAccess — index 6/8 always exist.)
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
+2 -1
View File
@@ -1,5 +1,6 @@
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import { resolve } from "path"; import { resolve } from "path";
import { compareCodeUnits } from "@utils/sort";
interface LocaleSchema { interface LocaleSchema {
ui: Record<string, string[]>; ui: Record<string, string[]>;
@@ -17,5 +18,5 @@ export const LOCALE_SCHEMA = JSON.parse(
/** The leaf keys under one parent path, sorted; empty when the path is missing. */ /** The leaf keys under one parent path, sorted; empty when the path is missing. */
export function schemaKeys(namespace: keyof LocaleSchema, parent: string): string[] { export function schemaKeys(namespace: keyof LocaleSchema, parent: string): string[] {
return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort(); return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort(compareCodeUnits);
} }
+7 -5
View File
@@ -13,9 +13,9 @@ describe("generateId", () => {
expect(generateId()).toMatch(V4); expect(generateId()).toMatch(V4);
}); });
it("falls back to a valid v4 UUID when crypto.randomUUID is missing (Android WebView < 92)", () => { it("falls back to a valid v4 UUID when crypto.randomUUID is missing", () => {
// Chromium 91 has getRandomValues but not randomUUID — the exact gap that // Insecure contexts (and Chromium < 92) have getRandomValues but not
// black-screened the app at boot before the fallback existed. // randomUUID — the gap that once black-screened the app at boot.
const real = globalThis.crypto; const real = globalThis.crypto;
vi.stubGlobal("crypto", { vi.stubGlobal("crypto", {
getRandomValues: (a: Uint8Array<ArrayBuffer>) => real.getRandomValues(a), getRandomValues: (a: Uint8Array<ArrayBuffer>) => real.getRandomValues(a),
@@ -23,9 +23,11 @@ describe("generateId", () => {
expect(generateId()).toMatch(V4); 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); vi.stubGlobal("crypto", undefined);
expect(generateId()).toMatch(V4); expect(() => generateId()).toThrow(TypeError);
}); });
it("produces unique values across many calls", () => { it("produces unique values across many calls", () => {
+5 -1
View File
@@ -22,7 +22,11 @@ const KEY_LABEL = "ytg-gate-v1";
function toBase64Url(bytes: Uint8Array): string { function toBase64Url(bytes: Uint8Array): string {
let binary = ""; let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte); 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<ArrayBuffer> | null { function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
+6 -1
View File
@@ -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. * when the path is not a legal path at all.
*/ */
export function legalAssetPath(url: URL): string | null { 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 === "/legal") return "/legal/";
if (!trimmed.startsWith("/legal/")) return null; if (!trimmed.startsWith("/legal/")) return null;
const id = /^\/legal\/([a-z-]+)$/.exec(trimmed)?.[1]; const id = /^\/legal\/([a-z-]+)$/.exec(trimmed)?.[1];