feat(web): Turnstile gate, in-site legal pages and clean URLs on ytgenerator.stream
A Worker (worker/) now sits in front of the static build, configured from the same wrangler.jsonc. Cloudflare builds and deploys it; nothing in GitHub Actions does. Gate - First visit shows a branded check page (8 languages, Accept-Language) with Cloudflare Turnstile. The token is verified server-side against TURNSTILE_SECRET: success, hostname, action "enter", age <= 300 s. Only Cloudflare's own test-key results skip the hostname/action check, so `npm run cf:dev` works with the published test keys. - Pass -> `__Host-ytg_gate` (HttpOnly, Secure, SameSite=Lax, 24 h): an HMAC over expiry + a user-agent hash, keyed from the Turnstile secret, so no second secret exists and a cookie copied into a scraper is useless. - The page reloads in place instead of redirecting, so there is no `next` parameter to open-redirect with; /__gate/status lets the page tell a cookie-blocking browser what is wrong instead of looping; after one failure it waits for a click rather than resubmitting. - Missing secret = deployment mistake: the site stays up without the gate and the Worker logs it, instead of locking every visitor out. - The agree box on the gate records `ytg_terms`, which the app reads on boot so web visitors meet one blocking screen, not two. Headers and static files - worker/headers.ts sets CSP (nonce + strict-dynamic on the gate, no script at all on legal pages), nosniff, Referrer-Policy, Permissions-Policy, COOP, CORP, X-Frame-Options on everything the Worker returns; _headers covers the files served directly; a test keeps the two baselines identical. - `not_found_handling: "404-page"` (a static 404.html) instead of the SPA fallback, which would have handed index.html past the gate for any excluded path. The Worker serves the shell itself by fetching "/" - not "/index.html", which html_handling would 307 back to the home page. - security.txt (RFC 9116) is generated per build so Expires stays ~6 months ahead; the Web Analytics beacon is injected into the web build only. - theme-init.js applies the saved theme before first paint (no inline script). Legal in-site - build-plugins/legal-docs.ts renders TERMS, PRIVACY, DISCLAIMER (+ vi), LICENSE, THIRD_PARTY_NOTICES, SECURITY, NOTICE and CODE_OF_CONDUCT at build time into static /legal pages (public, before the gate) and a lazy `virtual:legal-docs` module for the in-app Legal Center, which works offline on desktop and Android and never leaves the webview. - PRIVACY, TERMS and SECURITY rewritten for Cloudflare hosting, Turnstile, Web Analytics and the two cookies; contacts moved to the poli0981.dev aliases (privacy@, legal@, dmca@, copyright@, security@, code@). - CURRENT_TERMS_VERSION 1 -> 2: the Privacy Policy changed materially. App - Web uses BrowserRouter (real paths; analytics can count them), Tauri keeps HashRouter; old /#/x bookmarks are rewritten to /x before the router reads them. Consent is a layout route; /legal sits outside it. - <html lang> follows the UI language; a stale chunk after a deploy triggers one reload instead of an error page. .gitattributes pins LF everywhere so Windows checkouts stop failing Prettier. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c6e43f8e13
commit
5ced6b4a86
55 files changed
+3547
-328
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# Copy to .dev.vars for `npm run cf:dev`. These are Cloudflare's public
|
||||
# Turnstile TEST keys: the widget always passes and the secret accepts only the
|
||||
# dummy token it produces. Never put the real secret in a file.
|
||||
TURNSTILE_SITE_KEY=1x00000000000000000000AA
|
||||
TURNSTILE_SECRET=1x0000000000000000000000000000000AA
|
||||
@@ -0,0 +1,13 @@
|
||||
# LF in the repository and in every checkout, on every OS. Prettier enforces
|
||||
# `endOfLine: "lf"`, and a Windows checkout with core.autocrlf=true otherwise
|
||||
# turns every file it touches (checkout, stash, rebase) into a formatting
|
||||
# failure that CI never sees.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Binary assets — never touch.
|
||||
*.png binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.jks binary
|
||||
*.keystore binary
|
||||
*.woff2 binary
|
||||
+1
-1
@@ -6,7 +6,7 @@ By participating in this project — opening issues, submitting pull requests, c
|
||||
|
||||
## Reporting
|
||||
|
||||
Report violations privately to the maintainer: `lopop05905@proton.me`.
|
||||
Report violations privately to the maintainer: `code@poli0981.dev`.
|
||||
|
||||
All reports are reviewed and investigated promptly and fairly. The maintainer is obligated to respect the privacy and security of the reporter.
|
||||
|
||||
|
||||
+3
-2
@@ -6,7 +6,8 @@
|
||||
|
||||
- **GitHub**: <https://github.com/poli0981>
|
||||
- **YouTube** (reference channel): <https://www.youtube.com/@SkullMute>
|
||||
- **Email** (security & private contact): `lopop05905@proton.me`
|
||||
- **Website**: <https://poli0981.dev/> · all channels at <https://poli0981.dev/links/>
|
||||
- **Email**: `code@poli0981.dev` (project) · `security@poli0981.dev` (vulnerabilities, see [SECURITY.md](./SECURITY.md))
|
||||
- **Areas of responsibility**: all — core engine, locale management, UI, Tauri desktop shell, releases, CI/CD.
|
||||
|
||||
## Maintainer Responsibilities
|
||||
@@ -19,7 +20,7 @@
|
||||
|
||||
## Becoming a Maintainer
|
||||
|
||||
There is currently no formal pathway. The project has been solo since inception. If you'd like to help maintain a specific area — most realistically, native-speaker review for one of the AI-translated locales (JA / ES / KO / ZH) — open an issue describing what you'd like to take on.
|
||||
There is currently no formal pathway. The project has been solo since inception. If you'd like to help maintain a specific area — most realistically, native-speaker review for one of the AI-translated locales (JA / ES / KO / ZH / PT-BR / ID) — open an issue describing what you'd like to take on.
|
||||
|
||||
Persistent, high-quality contributions over time are the path. There is no application form.
|
||||
|
||||
|
||||
+64
-44
@@ -1,75 +1,95 @@
|
||||
# Privacy Policy
|
||||
|
||||
**Effective:** 2026-05-14
|
||||
**Effective:** 2026-09-30
|
||||
|
||||
YTDescGen is an **offline-first** template engine for generating YouTube video metadata. This document describes what data the application handles, where it lives, and what it never collects.
|
||||
This policy covers YTDescGen — the web app at **https://ytgenerator.stream** and the desktop (Windows, macOS, Linux) and Android apps built from the same source. It is maintained by **poli0981 (SkullMute)**, who is responsible for it. Questions and requests: **privacy@poli0981.dev**.
|
||||
|
||||
## What We Collect
|
||||
## In short
|
||||
|
||||
**Nothing.** The application sends no data to any server controlled by the maintainer.
|
||||
- There is **no account** and **no YTDescGen server that receives your work**. Everything you type — profiles, presets, templates, drafts, history — is stored **on your own device** and nowhere else.
|
||||
- The **web app** is delivered through **Cloudflare**. To do that, Cloudflare necessarily sees technical request data (such as your IP address), runs a one-time **Turnstile** bot check before you enter, and provides **cookieless** visit statistics (**Cloudflare Web Analytics**).
|
||||
- The **desktop and Android apps** have none of that: no analytics, no bot check, no telemetry.
|
||||
- Nothing is sold, shared for advertising, or used to profile you.
|
||||
|
||||
There is no analytics provider, no telemetry, no crash reporter, no A/B testing, no advertising network, no behavioral tracking. There is no backend.
|
||||
## 1. What stays on your device
|
||||
|
||||
## What Stays on Your Device
|
||||
### Web app
|
||||
|
||||
### Web version (GitHub Pages)
|
||||
Your work is saved in your browser's **`localStorage`** for `ytgenerator.stream`:
|
||||
|
||||
The web build stores your work in your browser's **`localStorage`** only. Keys used:
|
||||
|
||||
| Key prefix | Purpose |
|
||||
| Key | Contents |
|
||||
| --- | --- |
|
||||
| `ytdesc:editor` | Current editor draft |
|
||||
| `ytdesc:settings` | Theme, default language, accordion state, hashtag preferences |
|
||||
| `ytdesc:profiles` | Saved channel / social / rig profiles |
|
||||
| `ytdesc:presets` | Saved game presets |
|
||||
| `ytdesc:templates` | Saved full-form snapshots |
|
||||
| `ytdesc:history` | Recently generated outputs |
|
||||
| `ytdesc:logs` | Application event log |
|
||||
| `ytdescgen-settings` | Theme, languages, editor preferences, the version of these terms you accepted and when |
|
||||
| `ytdescgen-profiles` | Saved channel profiles (channel name, social links, contact emails, PC rig) |
|
||||
| `ytdescgen-presets` | Saved game presets (game name, genres, store links) |
|
||||
| `ytdescgen-templates` | Saved full-form templates |
|
||||
| `ytdescgen-history` | Recently generated titles, descriptions and tags |
|
||||
| `ytdescgen-editor-draft` | The draft currently open in the editor |
|
||||
| `ytdescgen-logs` | The app's own event log (errors, imports, exports) |
|
||||
|
||||
`localStorage` is scoped to the origin and never transmitted. Clearing your browser data, browsing in a private/incognito window, or signing out wipes all of it.
|
||||
This data never leaves your browser unless **you** export it. Clearing site data, using a private window, or a "clear cookies and site data on exit" setting erases it.
|
||||
|
||||
### Desktop version (Tauri)
|
||||
### Desktop and Android apps
|
||||
|
||||
The desktop build uses the operating system's standard application-data directory:
|
||||
The apps keep the same data in the app's own WebView storage and application-data folder (the event log and automatic backups live there too):
|
||||
|
||||
- **Windows**: `%APPDATA%\com.skullmute.ytdescgen`
|
||||
- **macOS**: `~/Library/Application Support/com.skullmute.ytdescgen`
|
||||
- **Linux**: `~/.config/com.skullmute.ytdescgen`
|
||||
- **Windows:** `%APPDATA%\com.skullmute.ytdescgen` and `%LOCALAPPDATA%\com.skullmute.ytdescgen`
|
||||
- **macOS:** `~/Library/Application Support/com.skullmute.ytdescgen`
|
||||
- **Linux:** `~/.local/share/com.skullmute.ytdescgen`
|
||||
- **Android:** the app's private storage (removed when you uninstall the app or clear its data)
|
||||
|
||||
The same key set as the web version is stored as JSON files there. Uninstalling the application or deleting that directory removes everything.
|
||||
Uninstalling the app or deleting those folders removes everything. The apps make no network requests of their own; links you choose to open (store pages, donation pages, this policy on the web) open in your browser.
|
||||
|
||||
## Third-Party Services
|
||||
## 2. What the web app's hosting provider processes
|
||||
|
||||
The application does **not** call third-party APIs at runtime.
|
||||
The web app is hosted on **Cloudflare Workers**. Cloudflare acts as a service provider (processor) for the site and handles:
|
||||
|
||||
Optional links you may click — donation buttons, store links you paste into a draft, social links you save to your profile — navigate **away** from the application to third-party sites. Those sites have their own privacy policies; the maintainer is not responsible for them.
|
||||
- **Delivery and security.** Every request carries technical data — IP address, browser user-agent, requested URL, referrer, date and time. Cloudflare uses it to deliver the site, keep it available and protect it from abuse. Error and request logs for the site's Worker (Cloudflare Workers Logs) are kept by Cloudflare for a short period (currently up to 7 days) and are used only to fix problems.
|
||||
- **Turnstile bot check.** Before you enter, [Cloudflare Turnstile](https://www.cloudflare.com/products/turnstile/) runs a check — usually invisible — that evaluates technical browser and device signals and your IP address to tell people from automated traffic. Its data handling is described in Cloudflare's [Turnstile Privacy Addendum](https://www.cloudflare.com/turnstile-privacy-policy/). YTDescGen receives only a pass/fail result.
|
||||
- **Cloudflare Web Analytics.** Aggregate, **cookieless** statistics: page views, referrer, country, browser, operating system and device type, and page-load performance. It sets no cookies, uses no local storage and does not fingerprint visitors. See [Cloudflare's Web Analytics privacy notes](https://www.cloudflare.com/web-analytics/) and the [Cloudflare Privacy Policy](https://www.cloudflare.com/privacypolicy/).
|
||||
|
||||
YouTube oEmbed, the Steam store API, Twitch helix, and similar services are **not** fetched by this application.
|
||||
Cloudflare operates a global network, so this data may be processed outside your country under Cloudflare's data-processing terms (including the EU Standard Contractual Clauses).
|
||||
|
||||
## Cookies / Local Storage Distinction
|
||||
## 3. Cookies
|
||||
|
||||
The web version uses **`localStorage`**, not cookies. No cookie is set by the application. GitHub Pages itself may issue a session cookie at the platform level — that is GitHub's, not ours, and is governed by [GitHub's Privacy Statement](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement).
|
||||
The web app sets exactly two cookies, both first-party and both needed for the bot check:
|
||||
|
||||
The first-run consent acknowledgement (added in v0.28.0) is recorded **inside the existing settings record** — a `legalConsentVersion` number plus a local timestamp — not as a separate cookie or storage key. It never leaves your device.
|
||||
| Cookie | Purpose | Lifetime |
|
||||
| --- | --- | --- |
|
||||
| `__Host-ytg_gate` | Remembers that this browser passed the Turnstile check. Contains only an expiry time, a shortened one-way hash of your browser's user-agent string and a signature — no identifier. `HttpOnly`, `Secure`. | 24 hours |
|
||||
| `ytg_terms` | Records which version of these Terms and this Privacy Policy you agreed to on the check page, so the app does not ask twice. | 1 year |
|
||||
|
||||
## Children's Privacy
|
||||
There are no advertising, tracking or third-party analytics cookies. Cloudflare's own security systems may set strictly necessary cookies of their own as described in Cloudflare's [cookie policy](https://www.cloudflare.com/cookie-policy/).
|
||||
|
||||
This application is not directed at children under 13 and does not knowingly process any personal data from anyone.
|
||||
## 4. Legal bases (EEA/UK)
|
||||
|
||||
## GDPR / CCPA / Equivalent Rights
|
||||
- Operating and securing the web app, including the bot check and its cookies: **legitimate interests** (Art. 6(1)(f) GDPR); the cookies are strictly necessary for a service you request, so they need no separate consent.
|
||||
- Aggregate, cookieless visit statistics: **legitimate interests** in understanding how the site is used.
|
||||
- Everything in section 1 is processed only on your device, by you.
|
||||
|
||||
Because no data ever leaves your device:
|
||||
## 5. What is never done
|
||||
|
||||
- **Right to access**: your data is already accessible — open DevTools → Application → Local Storage on the web, or browse the application-data directory on desktop.
|
||||
- **Right to erasure**: clear your browser's site data (web) or delete the application-data directory / uninstall the app (desktop).
|
||||
- **Right to portability**: use the in-app **Export** action in `Profiles` / `Presets` / `Templates` / `History` / `Logs` to download JSON.
|
||||
- **Right to object / restrict processing**: not applicable — no processing happens off-device.
|
||||
- **Right to know what is sold or shared**: nothing. Nothing is sold or shared.
|
||||
- No selling or renting of data, no advertising networks, no behavioural profiling.
|
||||
- No YouTube, Google, Steam or other third-party account access — the app never sees your channel.
|
||||
- No crash reporting or telemetry from the desktop or Android apps.
|
||||
|
||||
## Changes to This Policy
|
||||
## 6. Your rights
|
||||
|
||||
If this policy changes, the change is committed to the repository under `PRIVACY.md` with the `Effective` date updated. There is no notification mechanism because the application has no way to reach you.
|
||||
- **Access and portability:** your content is already on your device; use the export buttons in **Settings** and **Profiles** to save it as a file.
|
||||
- **Erasure:** clear site data (web) or uninstall the app / delete its folders (desktop, Android).
|
||||
- **Data processed by Cloudflare:** write to **privacy@poli0981.dev**. Because YTDescGen has no accounts, it holds no data that can be looked up by your name or email; requests about Cloudflare's own processing can also go to Cloudflare directly.
|
||||
- You may also complain to your local data-protection authority.
|
||||
|
||||
## Contact
|
||||
## 7. Children
|
||||
|
||||
`lopop05905@proton.me`
|
||||
YTDescGen is not directed at children under 13 (or the minimum age of digital consent in your country) and does not knowingly process their personal data.
|
||||
|
||||
## 8. Changes
|
||||
|
||||
Changes are published at [ytgenerator.stream/legal/privacy](https://ytgenerator.stream/legal/privacy) and in the repository's `PRIVACY.md`, with the **Effective** date updated. When a change is material, the app asks you to review and accept it again on your next visit.
|
||||
|
||||
## 9. Contact
|
||||
|
||||
- Privacy and data requests: **privacy@poli0981.dev**
|
||||
- Security issues: **security@poli0981.dev** (see the [Security Policy](SECURITY.md))
|
||||
- Everything else: **contact@poli0981.dev** · [poli0981.dev/links](https://poli0981.dev/links/)
|
||||
+17
-9
@@ -2,12 +2,12 @@
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Only the latest released version of YTDescGen receives security updates. This is a solo open-source project; there are no LTS branches.
|
||||
Only the latest released version of YTDescGen receives security updates, and the web app at https://ytgenerator.stream always runs the latest `main`. This is a solo open-source project; there are no LTS branches.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | --------- |
|
||||
| 0.13.x | ✅ |
|
||||
| < 0.13 | ❌ |
|
||||
| 1.0.x | ✅ |
|
||||
| < 1.0 | ❌ |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
@@ -15,14 +15,16 @@ Please report security issues **privately**. Do not open a public issue.
|
||||
|
||||
**Preferred channels (in order):**
|
||||
|
||||
1. **GitHub Security Advisory** — open a draft advisory in this repository's `Security` tab.
|
||||
2. **Email** — `lopop05905@proton.me` with subject prefix `[SECURITY]`.
|
||||
1. **GitHub Security Advisory** — [open a draft advisory](https://github.com/poli0981/youtube-generator/security/advisories/new) in this repository.
|
||||
2. **Email** — **security@poli0981.dev** with the subject prefix `[SECURITY]`.
|
||||
|
||||
The same contacts are published in [`/.well-known/security.txt`](https://ytgenerator.stream/.well-known/security.txt) (RFC 9116).
|
||||
|
||||
Include:
|
||||
|
||||
- A description of the issue and its potential impact.
|
||||
- Steps to reproduce, ideally a minimal proof-of-concept.
|
||||
- The affected version (`node -p "require('./package.json').version"`).
|
||||
- The affected version (About page, or `node -p "require('./package.json').version"`) or URL.
|
||||
- Whether the issue is already public.
|
||||
|
||||
## Response Timeline
|
||||
@@ -35,16 +37,22 @@ Include:
|
||||
|
||||
In scope:
|
||||
|
||||
- The web bundle deployed to GitHub Pages.
|
||||
- The Tauri desktop binaries (Windows, macOS, Linux).
|
||||
- The web app at `ytgenerator.stream`, including its Cloudflare Worker (`worker/`): the Turnstile gate, its cookies, and the security headers.
|
||||
- The desktop binaries (Windows, macOS, Linux) and the Android APK published on the GitHub releases page, including the Tauri commands in `src-tauri/`.
|
||||
- CI/CD workflows in `.github/workflows/`.
|
||||
|
||||
Out of scope:
|
||||
|
||||
- Vulnerabilities in third-party dependencies — report those upstream and we'll bump.
|
||||
- Issues requiring physical access to the user's device.
|
||||
- Cloudflare's own platform (Turnstile, Workers, the CDN) — report to [Cloudflare](https://www.cloudflare.com/disclosure/).
|
||||
- Volumetric denial-of-service, rate-limit or spam findings, and automated scanner output without a demonstrated impact.
|
||||
- Issues requiring physical access to the user's device, or a malicious browser extension.
|
||||
- Self-XSS in user-supplied template content (the app deliberately renders user input as plain text in the preview).
|
||||
|
||||
## Safe Harbour
|
||||
|
||||
Good-faith research that follows this policy — no data destruction, no privacy violations of other users, no service degradation, and private reporting — will not be pursued.
|
||||
|
||||
## No Bounty
|
||||
|
||||
This is a solo open-source project. Credit in release notes and a thank-you in `MAINTAINERS.md` is the only reward we can offer.
|
||||
@@ -1,14 +1,14 @@
|
||||
# Terms of Use
|
||||
|
||||
**Effective:** 2026-05-14
|
||||
**Effective:** 2026-09-30
|
||||
|
||||
These terms govern your use of YTDescGen — both the web version hosted at the project's GitHub Pages URL and any Tauri desktop binaries distributed under this project.
|
||||
These terms govern your use of YTDescGen — the web app at **https://ytgenerator.stream** and the desktop and Android apps distributed from this project's [GitHub releases](https://github.com/poli0981/youtube-generator/releases). By using YTDescGen you agree to them, together with the [Privacy Policy](PRIVACY.md) and the [Disclaimer](DISCLAIMER.md).
|
||||
|
||||
## License
|
||||
|
||||
YTDescGen is licensed under the **[Apache License 2.0](./LICENSE)**. You may use, modify, and redistribute it under those terms.
|
||||
YTDescGen's source code is licensed under the **[Apache License 2.0](LICENSE)**. You may use, modify, and redistribute it under those terms.
|
||||
|
||||
Apache 2.0 grants a patent license (Section 3) and an irrevocable copyright license (Section 2). It does **not** grant trademark rights — see Section 6 of the LICENSE.
|
||||
Apache 2.0 grants a patent license (Section 3) and an irrevocable copyright license (Section 2). It does **not** grant trademark rights — see Section 6 of the LICENSE. The name "YTDescGen" and its logo identify this project; forks should use their own name.
|
||||
|
||||
## Acceptable Use
|
||||
|
||||
@@ -21,18 +21,19 @@ You may use YTDescGen for any lawful purpose. You may **not** use it to:
|
||||
- Violate applicable law in your jurisdiction, including but not limited to **GDPR** (EU), **CCPA / CPRA** (California), **PIPL** (China), **LGPD** (Brazil), the **Vietnamese Cybersecurity Law**, or equivalent data-protection / cybercrime regulation in your country.
|
||||
- Bypass YouTube's policies on metadata (misleading thumbnails / titles / tags) using the application.
|
||||
|
||||
## GitHub Terms
|
||||
## The web app
|
||||
|
||||
If you use the web version hosted on GitHub Pages, your use is also subject to:
|
||||
The web app is hosted on Cloudflare. To keep it available for people, it asks each browser to pass a short **Cloudflare Turnstile** check before entering. When using the web app you must not:
|
||||
|
||||
- [GitHub's Terms of Service](https://docs.github.com/en/site-policy/github-terms/github-terms-of-service)
|
||||
- [GitHub's Acceptable Use Policies](https://docs.github.com/en/site-policy/acceptable-use-policies)
|
||||
- Attempt to bypass, automate, or defeat the check, or reuse its cookies outside the browser that earned them.
|
||||
- Scrape, crawl at volume, load-test, or otherwise place an unreasonable load on the site.
|
||||
- Probe for vulnerabilities outside the process in the [Security Policy](SECURITY.md).
|
||||
|
||||
These apply alongside this document; in case of conflict, GitHub's policies govern the hosted artifact.
|
||||
The web app is provided free of charge and may be changed, rate-limited, or taken offline at any time without notice. The desktop and Android apps work without it.
|
||||
|
||||
## No Warranty
|
||||
|
||||
See [DISCLAIMER.md](./DISCLAIMER.md) and `LICENSE` §§ 7–8. The software is provided **as-is** with no warranty of any kind, express or implied.
|
||||
See [DISCLAIMER.md](DISCLAIMER.md) and `LICENSE` §§ 7–8. The software is provided **as-is** with no warranty of any kind, express or implied.
|
||||
|
||||
## Generated Content
|
||||
|
||||
@@ -43,6 +44,10 @@ YTDescGen produces text intended to be pasted into YouTube descriptions. **You
|
||||
- Not including misleading information, copyright-infringing material, or any prohibited content listed in YouTube's policies.
|
||||
- Truthful representation of run-type, difficulty, blind status, mod / cheat usage, and similar disclosures the application optionally exposes.
|
||||
|
||||
## Copyright Complaints
|
||||
|
||||
If you believe material in this project's repository, releases or website infringes your copyright, send a notice to **dmca@poli0981.dev** with: identification of the work, the location of the material, your contact details, a good-faith statement that the use is not authorised, and a statement — under penalty of perjury — that the notice is accurate and that you are the owner or authorised to act for the owner. Licensing and attribution questions go to **copyright@poli0981.dev**.
|
||||
|
||||
## Contributions
|
||||
|
||||
By submitting a contribution (issue, pull request, comment, locale translation, screenshot, log dump), you agree:
|
||||
@@ -50,18 +55,18 @@ By submitting a contribution (issue, pull request, comment, locale translation,
|
||||
1. Your contribution is licensed under Apache 2.0, the same as the project.
|
||||
2. You have the right to grant that license (you wrote it, or it's compatibly licensed and credited).
|
||||
3. You will not include malicious code or knowingly vulnerable dependencies.
|
||||
4. You will follow the [Code of Conduct](./CODE_OF_CONDUCT.md) and [Contributing Guide](./CONTRIBUTING.md).
|
||||
4. You will follow the [Code of Conduct](CODE_OF_CONDUCT.md) and [Contributing Guide](CONTRIBUTING.md).
|
||||
|
||||
Violations may result in your contribution being closed and, in severe cases, a permanent ban from the repository — see `CONTRIBUTING.md` § "Auto-ignored Contributions".
|
||||
Violations may result in your contribution being closed and, in severe cases, a permanent ban from the repository — see `CONTRIBUTING.md` § "Auto-ignored Contributions". Contributions made on GitHub are also subject to [GitHub's Terms of Service](https://docs.github.com/en/site-policy/github-terms/github-terms-of-service).
|
||||
|
||||
## Termination
|
||||
|
||||
These terms remain in effect for as long as you use the software. Your rights under Apache 2.0 are perpetual subject to that license's termination clauses (notably § 3 patent retaliation).
|
||||
These terms remain in effect for as long as you use the software. Your rights under Apache 2.0 are perpetual subject to that license's termination clauses (notably § 3 patent retaliation). Access to the web app may be refused to anyone who breaks the rules in "The web app" above.
|
||||
|
||||
## Changes
|
||||
|
||||
Updates to these terms are committed under `TERMS.md` with the `Effective` date updated. Continued use of the software after a change constitutes acceptance.
|
||||
Updates are published at [ytgenerator.stream/legal/terms](https://ytgenerator.stream/legal/terms) and in the repository's `TERMS.md`, with the `Effective` date updated. When a change is material, the app asks you to review and accept it again; continued use after that constitutes acceptance.
|
||||
|
||||
## Contact
|
||||
|
||||
`lopop05905@proton.me`
|
||||
Legal questions: **legal@poli0981.dev** · Everything else: **contact@poli0981.dev**
|
||||
@@ -0,0 +1,333 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { posix, resolve } from "path";
|
||||
import { Marked, type Tokens } from "marked";
|
||||
import type { Plugin } from "vite";
|
||||
import { LOGO_SVG, SITE_ORIGIN } from "../src/config/brand.ts";
|
||||
import { LEGAL_DOCS, legalDocPath, type LegalDoc, type LegalDocId } from "../src/config/legal.ts";
|
||||
|
||||
/**
|
||||
* Renders the repo-root legal documents at build time, twice:
|
||||
*
|
||||
* 1. `virtual:legal-docs` — { [id]: { title, effective, html: { en, vi? } } },
|
||||
* imported lazily by the in-app Legal Center, so desktop and Android carry
|
||||
* the documents offline and nothing is fetched from GitHub any more.
|
||||
* 2. `dist/legal/<id>.html` (+ `<id>.vi.html`, `index.html`) — plain pages
|
||||
* with no script, which the Cloudflare Worker serves to anyone, before the
|
||||
* Turnstile gate: people must be able to read the Terms and the Privacy
|
||||
* Policy before they are asked to agree to them.
|
||||
*
|
||||
* `marked` runs only here, in Node — it adds nothing to the app bundle.
|
||||
*/
|
||||
|
||||
const VIRTUAL_ID = "virtual:legal-docs";
|
||||
const RESOLVED_VIRTUAL_ID = `\0${VIRTUAL_ID}`;
|
||||
const REPO_BLOB = "https://github.com/poli0981/youtube-generator/blob/main/";
|
||||
const ROOT = resolve(import.meta.dirname, "..");
|
||||
|
||||
type DocLang = "en" | "vi";
|
||||
|
||||
export interface RenderedLegalDoc {
|
||||
title: string;
|
||||
/** ISO date from an `**Effective:**` / `**Last updated:**` line, if any. */
|
||||
effective: string | null;
|
||||
html: Partial<Record<DocLang, string>>;
|
||||
}
|
||||
|
||||
/** Repo-relative source file → document id, for cross-document links. */
|
||||
const SOURCE_TO_ID: ReadonlyMap<string, LegalDocId> = new Map(
|
||||
LEGAL_DOCS.flatMap((doc): [string, LegalDocId][] =>
|
||||
doc.sourceVi
|
||||
? [
|
||||
[doc.source, doc.id],
|
||||
[doc.sourceVi, doc.id],
|
||||
]
|
||||
: [[doc.source, doc.id]],
|
||||
),
|
||||
);
|
||||
|
||||
/** Titles for the plain-text sources, which have no heading to read. */
|
||||
const PLAIN_TEXT_TITLES: Partial<Record<LegalDocId, string>> = {
|
||||
license: "Apache License 2.0",
|
||||
notice: "NOTICE",
|
||||
};
|
||||
|
||||
const HTML_ESCAPES: Readonly<Record<string, string>> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
};
|
||||
|
||||
export function escapeHtml(text: string): string {
|
||||
return text.replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch] ?? ch);
|
||||
}
|
||||
|
||||
/** Point relative links at the in-site page, or at GitHub for anything else. */
|
||||
export function rewriteHref(href: string, fromFile: string): string {
|
||||
if (/^(?:[a-z][a-z0-9+.-]*:|#)/i.test(href)) return href;
|
||||
const hashAt = href.indexOf("#");
|
||||
const pathPart = hashAt >= 0 ? href.slice(0, hashAt) : href;
|
||||
const hash = hashAt >= 0 ? href.slice(hashAt) : "";
|
||||
const resolved = posix.normalize(posix.join(posix.dirname(fromFile), pathPart));
|
||||
const id = SOURCE_TO_ID.get(resolved);
|
||||
return id ? `${legalDocPath(id)}${hash}` : `${REPO_BLOB}${resolved}${hash}`;
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/<[^>]+>/g, "")
|
||||
.replace(/[`*_~[\]()]/g, "")
|
||||
.trim()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
function stripInlineMarkdown(text: string): string {
|
||||
return text
|
||||
.replace(/[`*_~]/g, "")
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function renderMarkdown(source: string, fromFile: string): { title: string; html: string } {
|
||||
// Links are rewritten in the renderer rather than a `walkTokens` hook: that
|
||||
// hook only runs inside `marked.parse()`, and this renders via
|
||||
// `lexer()` + `parser()` so it can read the title from the tokens.
|
||||
const marked = new Marked({
|
||||
gfm: true,
|
||||
renderer: {
|
||||
heading({ tokens, depth, text }) {
|
||||
const inner = this.parser.parseInline(tokens);
|
||||
return `<h${depth} id="${slugify(text)}">${inner}</h${depth}>\n`;
|
||||
},
|
||||
link({ href, title, tokens }) {
|
||||
const inner = this.parser.parseInline(tokens);
|
||||
const target = rewriteHref(href, fromFile);
|
||||
const external = /^https?:/i.test(target);
|
||||
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
|
||||
const rel = external ? ` target="_blank" rel="noopener noreferrer"` : "";
|
||||
return `<a href="${escapeHtml(target)}"${titleAttr}${rel}>${inner}</a>`;
|
||||
},
|
||||
},
|
||||
});
|
||||
const tokens = marked.lexer(source);
|
||||
const h1 = tokens.find((t): t is Tokens.Heading => t.type === "heading" && t.depth === 1);
|
||||
const html = marked.parser(tokens);
|
||||
return { title: h1 ? stripInlineMarkdown(h1.text) : "", html };
|
||||
}
|
||||
|
||||
export function extractEffectiveDate(source: string): string | null {
|
||||
const match =
|
||||
/\*\*(?:Effective(?: date)?|Last updated|Ngày hiệu lực|Cập nhật lần cuối):?\*\*:?\s*(\d{4}-\d{2}-\d{2})/i.exec(
|
||||
source,
|
||||
);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function readSource(file: string): string {
|
||||
return readFileSync(resolve(ROOT, file), "utf8").replace(/\r\n/g, "\n");
|
||||
}
|
||||
|
||||
function renderSource(doc: LegalDoc, file: string): { title: string; html: string } {
|
||||
const text = readSource(file);
|
||||
if (file.endsWith(".md")) return renderMarkdown(text, file);
|
||||
return {
|
||||
title: PLAIN_TEXT_TITLES[doc.id] ?? doc.id,
|
||||
html: `<pre class="plain">${escapeHtml(text.trim())}</pre>`,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderAllLegalDocs(): Record<LegalDocId, RenderedLegalDoc> {
|
||||
const out = {} as Record<LegalDocId, RenderedLegalDoc>;
|
||||
for (const doc of LEGAL_DOCS) {
|
||||
const en = renderSource(doc, doc.source);
|
||||
const rendered: RenderedLegalDoc = {
|
||||
title: en.title,
|
||||
effective: extractEffectiveDate(readSource(doc.source)),
|
||||
html: { en: en.html },
|
||||
};
|
||||
if (doc.sourceVi) rendered.html.vi = renderSource(doc, doc.sourceVi).html;
|
||||
out[doc.id] = rendered;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Static pages
|
||||
|
||||
const PAGE_CSS = `
|
||||
:root{color-scheme:dark light;--bg:#0b0b12;--card:#12121a;--border:#262636;--text:#e7e7ef;--muted:#9a9ab0;--link:#a5a6fb;--code:#1b1b27;font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif}
|
||||
@media (prefers-color-scheme:light){:root{--bg:#f7f7fb;--card:#fff;--border:#e3e3ee;--text:#17171f;--muted:#5b5b70;--link:#4f46e5;--code:#f1f1f7}}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--text);line-height:1.65}
|
||||
a{color:var(--link)}
|
||||
a:focus-visible{outline:2px solid var(--link);outline-offset:2px}
|
||||
.top{position:sticky;top:0;z-index:1;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 20px;background:color-mix(in srgb,var(--bg) 86%,transparent);backdrop-filter:blur(10px);border-bottom:1px solid var(--border)}
|
||||
.brand{display:flex;align-items:center;gap:10px;color:var(--text);text-decoration:none;font-weight:700;letter-spacing:-.01em}
|
||||
.brand svg{width:28px;height:28px}
|
||||
.open{font-size:14px;font-weight:600;text-decoration:none;padding:7px 14px;border-radius:10px;color:#fff;background:linear-gradient(135deg,#6366f1,#a855f7)}
|
||||
.layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:32px;max-width:1080px;margin:0 auto;padding:32px 20px 64px}
|
||||
nav p{margin:0 0 8px;font-size:12px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
nav ul{list-style:none;margin:0;padding:0;position:sticky;top:76px}
|
||||
nav a{display:block;padding:6px 10px;border-radius:8px;color:var(--muted);text-decoration:none;font-size:14px}
|
||||
nav a:hover{color:var(--text);background:var(--card)}
|
||||
nav a[aria-current=page]{color:var(--text);background:var(--card);font-weight:600}
|
||||
article{min-width:0;background:var(--card);border:1px solid var(--border);border-radius:16px;padding:28px 32px}
|
||||
.meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin:0 0 20px;font-size:13px;color:var(--muted)}
|
||||
article h1{font-size:28px;line-height:1.25;margin:0 0 8px;letter-spacing:-.015em}
|
||||
article h2{font-size:20px;margin:32px 0 10px;padding-top:8px;border-top:1px solid var(--border)}
|
||||
article h3{font-size:16px;margin:24px 0 8px}
|
||||
article p,article li{font-size:15px}
|
||||
article table{width:100%;border-collapse:collapse;margin:16px 0;font-size:14px;display:block;overflow-x:auto}
|
||||
article th,article td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--border);vertical-align:top}
|
||||
article code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.88em;background:var(--code);padding:.12em .38em;border-radius:6px}
|
||||
article pre{background:var(--code);padding:16px;border-radius:12px;overflow-x:auto;font-size:13px;line-height:1.55}
|
||||
article pre code{background:none;padding:0}
|
||||
article pre.plain{white-space:pre-wrap;word-break:break-word}
|
||||
article blockquote{margin:16px 0;padding:4px 16px;border-left:3px solid #6366f1;color:var(--muted)}
|
||||
.cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px;margin-top:20px}
|
||||
.cards a{display:block;padding:16px;border:1px solid var(--border);border-radius:12px;text-decoration:none;color:var(--text);background:var(--bg)}
|
||||
.cards a:hover{border-color:#6366f1}
|
||||
.cards span{display:block;font-size:13px;color:var(--muted);margin-top:4px;line-height:1.5}
|
||||
footer{max-width:1080px;margin:0 auto;padding:0 20px 40px;font-size:13px;color:var(--muted)}
|
||||
@media (max-width:760px){.layout{grid-template-columns:1fr;padding-top:20px}nav ul{position:static;display:flex;flex-wrap:wrap;gap:4px}article{padding:20px 18px}}
|
||||
`;
|
||||
|
||||
/** One-line summaries for the static Legal index (English, like the pages). */
|
||||
const DOC_SUMMARIES: Readonly<Record<LegalDocId, string>> = {
|
||||
terms: "What you may and may not do with YTDescGen and what it generates.",
|
||||
privacy: "What stays on your device, and what Cloudflare processes on the web.",
|
||||
disclaimer: "No warranty, AI-assisted development and translations, no affiliation.",
|
||||
license: "The Apache License 2.0 the source code is released under.",
|
||||
"third-party": "Open-source libraries, fonts and services YTDescGen relies on.",
|
||||
security: "How to report a vulnerability privately, and what is in scope.",
|
||||
notice: "The Apache-2.0 NOTICE file with copyright and attribution.",
|
||||
conduct: "Contributor Covenant rules for the project's community spaces.",
|
||||
};
|
||||
|
||||
function pageShell(options: {
|
||||
title: string;
|
||||
canonicalPath: string;
|
||||
description: string;
|
||||
activeId: LegalDocId | null;
|
||||
body: string;
|
||||
lang: DocLang;
|
||||
}): string {
|
||||
const nav = LEGAL_DOCS.map((doc) => {
|
||||
const current = doc.id === options.activeId ? ' aria-current="page"' : "";
|
||||
return `<li><a href="${legalDocPath(doc.id)}"${current}>${escapeHtml(TITLE_BY_ID[doc.id])}</a></li>`;
|
||||
}).join("");
|
||||
return `<!doctype html>
|
||||
<html lang="${options.lang}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<meta name="theme-color" content="#0b0b12">
|
||||
<title>${escapeHtml(options.title)} — YTDescGen</title>
|
||||
<meta name="description" content="${escapeHtml(options.description)}">
|
||||
<link rel="canonical" href="${SITE_ORIGIN}${options.canonicalPath}">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<style>${PAGE_CSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="top"><a class="brand" href="/">${LOGO_SVG}<span>YTDescGen</span></a><a class="open" href="/">Open the app</a></header>
|
||||
<div class="layout">
|
||||
<nav aria-label="Legal documents"><p>Legal</p><ul>${nav}</ul></nav>
|
||||
<main>${options.body}</main>
|
||||
</div>
|
||||
<footer>© ${new Date().getUTCFullYear()} poli0981 (SkullMute) · Source code under the Apache License 2.0 · <a href="https://github.com/poli0981/youtube-generator">GitHub</a> · <a href="mailto:contact@poli0981.dev">contact@poli0981.dev</a></footer>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
const TITLE_BY_ID: Record<LegalDocId, string> = {
|
||||
terms: "Terms of Use",
|
||||
privacy: "Privacy Policy",
|
||||
disclaimer: "Disclaimer",
|
||||
license: "License (Apache-2.0)",
|
||||
"third-party": "Third-Party Notices",
|
||||
security: "Security Policy",
|
||||
notice: "NOTICE",
|
||||
conduct: "Code of Conduct",
|
||||
};
|
||||
|
||||
function docPage(id: LegalDocId, doc: RenderedLegalDoc, lang: DocLang): string {
|
||||
const html = doc.html[lang] ?? doc.html.en ?? "";
|
||||
// The documents state their own effective date, so the meta line only
|
||||
// carries the language switch.
|
||||
const meta: string[] = [];
|
||||
if (doc.html.vi) {
|
||||
meta.push(
|
||||
lang === "en"
|
||||
? `<a href="${legalDocPath(id)}?lang=vi" hreflang="vi" lang="vi">Tiếng Việt</a>`
|
||||
: `<a href="${legalDocPath(id)}" hreflang="en" lang="en">English</a>`,
|
||||
);
|
||||
}
|
||||
const metaLine = meta.length ? `<p class="meta">${meta.join(" · ")}</p>` : "";
|
||||
// Plain-text sources carry no <h1>; give them one.
|
||||
const heading = /^\s*<h1[\s>]/.test(html) ? "" : `<h1>${escapeHtml(TITLE_BY_ID[id])}</h1>`;
|
||||
return pageShell({
|
||||
title: TITLE_BY_ID[id],
|
||||
canonicalPath: legalDocPath(id),
|
||||
description: DOC_SUMMARIES[id],
|
||||
activeId: id,
|
||||
lang,
|
||||
body: `<article>${heading}${metaLine}${html}</article>`,
|
||||
});
|
||||
}
|
||||
|
||||
function indexPage(): string {
|
||||
const cards = LEGAL_DOCS.map(
|
||||
(doc) =>
|
||||
`<a href="${legalDocPath(doc.id)}"><strong>${escapeHtml(TITLE_BY_ID[doc.id])}</strong><span>${escapeHtml(DOC_SUMMARIES[doc.id])}</span></a>`,
|
||||
).join("");
|
||||
return pageShell({
|
||||
title: "Legal",
|
||||
canonicalPath: "/legal",
|
||||
description: "Terms, privacy, licensing and security information for YTDescGen.",
|
||||
activeId: null,
|
||||
lang: "en",
|
||||
body: `<article><h1>Legal</h1><p>Terms, privacy, licensing and security information for YTDescGen — the same documents the app shows in its Legal Center.</p><div class="cards">${cards}</div></article>`,
|
||||
});
|
||||
}
|
||||
|
||||
export function legalDocsPlugin(options: { emitStaticPages: boolean }): Plugin {
|
||||
return {
|
||||
name: "ytdescgen:legal-docs",
|
||||
resolveId(id) {
|
||||
return id === VIRTUAL_ID ? RESOLVED_VIRTUAL_ID : null;
|
||||
},
|
||||
load(id) {
|
||||
if (id !== RESOLVED_VIRTUAL_ID) return null;
|
||||
for (const doc of LEGAL_DOCS) {
|
||||
this.addWatchFile(resolve(ROOT, doc.source));
|
||||
if (doc.sourceVi) this.addWatchFile(resolve(ROOT, doc.sourceVi));
|
||||
}
|
||||
return `export const LEGAL_CONTENT = ${JSON.stringify(renderAllLegalDocs())};\n`;
|
||||
},
|
||||
generateBundle() {
|
||||
if (!options.emitStaticPages) return;
|
||||
const docs = renderAllLegalDocs();
|
||||
this.emitFile({ type: "asset", fileName: "legal/index.html", source: indexPage() });
|
||||
for (const doc of LEGAL_DOCS) {
|
||||
const rendered = docs[doc.id];
|
||||
this.emitFile({
|
||||
type: "asset",
|
||||
fileName: `legal/${doc.id}.html`,
|
||||
source: docPage(doc.id, rendered, "en"),
|
||||
});
|
||||
if (rendered.html.vi) {
|
||||
this.emitFile({
|
||||
type: "asset",
|
||||
fileName: `legal/${doc.id}.vi.html`,
|
||||
source: docPage(doc.id, rendered, "vi"),
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Plugin } from "vite";
|
||||
import { SITE_ORIGIN } from "../src/config/brand.ts";
|
||||
import { legalDocPath } from "../src/config/legal.ts";
|
||||
|
||||
/**
|
||||
* Build steps that only make sense for the web deployment on
|
||||
* ytgenerator.stream — never for the Tauri desktop / Android bundles, which
|
||||
* stay free of network beacons (their CSP would block them anyway).
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Cloudflare Web Analytics snippet, byte-for-byte as issued for this
|
||||
* site. Cookieless; allowed by the app shell's CSP (worker/headers.ts).
|
||||
*/
|
||||
export const CF_WEB_ANALYTICS_SNIPPET = `<!-- Cloudflare Web Analytics -->
|
||||
<script type='module' src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "84187c3714aa49e1ad8ef93ad6d422e7"}'>
|
||||
</script>
|
||||
<!-- End Cloudflare Web Analytics -->`;
|
||||
|
||||
export function cloudflareWebAnalytics(): Plugin {
|
||||
return {
|
||||
name: "ytdescgen:cf-web-analytics",
|
||||
apply: "build",
|
||||
transformIndexHtml: {
|
||||
order: "post",
|
||||
handler(html) {
|
||||
return html.replace("</body>", `${CF_WEB_ANALYTICS_SNIPPET}\n </body>`);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Days until the generated security.txt expires (RFC 9116 wants < 1 year). */
|
||||
export const SECURITY_TXT_LIFETIME_DAYS = 180;
|
||||
|
||||
/**
|
||||
* RFC 9116 security.txt, regenerated on every build so `Expires` always sits
|
||||
* ~6 months ahead of the last deploy instead of silently lapsing.
|
||||
*/
|
||||
export function renderSecurityTxt(now: Date): string {
|
||||
const expires = new Date(now.getTime() + SECURITY_TXT_LIFETIME_DAYS * 86_400_000);
|
||||
return [
|
||||
"# Security contact for YTDescGen — https://ytgenerator.stream",
|
||||
"# Scope, response times and disclosure policy are in the Policy link below.",
|
||||
"Contact: mailto:security@poli0981.dev",
|
||||
"Contact: https://github.com/poli0981/youtube-generator/security/advisories/new",
|
||||
`Expires: ${expires.toISOString().replace(/\.\d{3}Z$/, "Z")}`,
|
||||
"Preferred-Languages: en, vi",
|
||||
`Canonical: ${SITE_ORIGIN}/.well-known/security.txt`,
|
||||
`Policy: ${SITE_ORIGIN}${legalDocPath("security")}`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function securityTxt(): Plugin {
|
||||
return {
|
||||
name: "ytdescgen:security-txt",
|
||||
apply: "build",
|
||||
generateBundle() {
|
||||
this.emitFile({
|
||||
type: "asset",
|
||||
fileName: ".well-known/security.txt",
|
||||
source: renderSecurityTxt(new Date()),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" sizes="16x16 32x32 48x48" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<script src="/theme-init.js"></script>
|
||||
|
||||
<!-- OpenGraph -->
|
||||
<meta property="og:type" content="website" />
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
"project": [
|
||||
"src/**/*.{ts,tsx}",
|
||||
"scripts/**/*.ts",
|
||||
"tests/**/*.ts"
|
||||
"tests/**/*.ts",
|
||||
"worker/**/*.ts",
|
||||
"build-plugins/**/*.ts"
|
||||
],
|
||||
"ignoreExportsUsedInFile": true,
|
||||
"ignoreDependencies": [
|
||||
|
||||
Generated
+14
@@ -40,6 +40,7 @@
|
||||
"eslint": "^10.8.1",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"knip": "^6.32.2",
|
||||
"marked": "18.0.14",
|
||||
"postcss": "^8.5.26",
|
||||
"prettier": "^3.9.6",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
@@ -5806,6 +5807,19 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/marked": {
|
||||
"version": "18.0.14",
|
||||
"resolved": "https://registry.npmjs.org/marked/-/marked-18.0.14.tgz",
|
||||
"integrity": "sha512-mBHK6FBHuBAlhgRe88w9F0O1AbwwXJUcQibUbC/QcdTbVGAD7aWza+xt3N6oT/jCZx3/OMeS+8rnuiHZcQ9s7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"marked": "bin/marked.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/min-indent": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
|
||||
|
||||
+5
-4
@@ -11,13 +11,13 @@
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"lint": "eslint src/ tests/ scripts/",
|
||||
"lint:fix": "eslint src/ tests/ scripts/ --fix",
|
||||
"lint": "eslint src/ tests/ scripts/ worker/ build-plugins/",
|
||||
"lint:fix": "eslint src/ tests/ scripts/ worker/ build-plugins/ --fix",
|
||||
"knip": "knip",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:all": "tsc --noEmit -p tsconfig.check.json",
|
||||
"format": "prettier --write \"{src,tests,scripts}/**/*.{ts,tsx,css}\"",
|
||||
"format:check": "prettier --check \"{src,tests,scripts}/**/*.{ts,tsx,css}\"",
|
||||
"format": "prettier --write \"{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}\"",
|
||||
"format:check": "prettier --check \"{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}\"",
|
||||
"check:version": "tsx scripts/check-version-sync.ts",
|
||||
"validate:locales": "tsx scripts/validate-locales.ts",
|
||||
"generate:locale": "tsx scripts/generate-locale-template.ts",
|
||||
@@ -60,6 +60,7 @@
|
||||
"eslint": "^10.8.1",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"knip": "^6.32.2",
|
||||
"marked": "18.0.14",
|
||||
"postcss": "^8.5.26",
|
||||
"prettier": "^3.9.6",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta name="robots" content="noindex" />
|
||||
<title>Page not found — YTDescGen</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark light;
|
||||
--bg: #0b0b12;
|
||||
--card: #13131c;
|
||||
--border: #262636;
|
||||
--text: #ececf3;
|
||||
--muted: #9a9ab0;
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root { --bg: #f6f6fb; --card: #fff; --border: #e3e3ee; --text: #16161f; --muted: #5d5d72; }
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px 16px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
main {
|
||||
max-width: 420px;
|
||||
text-align: center;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 20px;
|
||||
padding: 32px 24px;
|
||||
}
|
||||
svg { width: 48px; height: 48px; }
|
||||
p.code { margin: 16px 0 4px; font: 700 44px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; letter-spacing: -0.02em; }
|
||||
h1 { font-size: 18px; margin: 8px 0; }
|
||||
p { color: var(--muted); font-size: 14px; line-height: 1.55; }
|
||||
a.btn { display: inline-block; margin-top: 12px; padding: 10px 18px; border-radius: 12px; color: #fff; font-weight: 600; text-decoration: none; background: linear-gradient(135deg, #6366f1, #a855f7); }
|
||||
a.btn:focus-visible { outline: 2px solid #a5a6fb; outline-offset: 2px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<svg viewBox="0 0 512 512" aria-hidden="true"><defs><linearGradient id="g" x1="40" y1="24" x2="472" y2="488" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6366F1"/><stop offset="1" stop-color="#A855F7"/></linearGradient></defs><rect width="512" height="512" rx="120" fill="url(#g)"/><path d="M176 118c0-17.9 19.4-29.1 34.9-20.1l128.2 74c15.5 9 15.5 31.2 0 40.2l-128.2 74C195.4 295.1 176 283.9 176 266z" fill="#fff"/><rect x="136" y="322" width="240" height="32" rx="16" fill="#fff" fill-opacity=".92"/><rect x="136" y="374" width="160" height="32" rx="16" fill="#fff" fill-opacity=".6"/></svg>
|
||||
<p class="code">404</p>
|
||||
<h1>This page doesn't exist</h1>
|
||||
<p>The link may be old or mistyped. YTDescGen itself lives at the home page.</p>
|
||||
<a class="btn" href="/">Open YTDescGen</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
// Applies the saved theme and UI language before the first paint, so a
|
||||
// light-theme user never sees the dark default flash. A separate file rather
|
||||
// than an inline <script> so the Content-Security-Policy needs no exception.
|
||||
(function () {
|
||||
var root = document.documentElement;
|
||||
var theme = "dark";
|
||||
var lang = null;
|
||||
try {
|
||||
var raw = localStorage.getItem("ytdescgen-settings");
|
||||
var state = raw ? JSON.parse(raw).state : null;
|
||||
if (state && state.theme === "light") theme = "light";
|
||||
if (state && typeof state.appLanguage === "string") lang = state.appLanguage;
|
||||
} catch (e) {
|
||||
/* storage blocked or corrupt: keep the defaults */
|
||||
}
|
||||
root.classList.toggle("dark", theme === "dark");
|
||||
root.classList.toggle("light", theme === "light");
|
||||
root.style.colorScheme = theme;
|
||||
if (lang) root.lang = lang;
|
||||
})();
|
||||
@@ -2,21 +2,21 @@ YTDescGen — Installation & Terms Notice
|
||||
=======================================
|
||||
|
||||
By installing and using YTDescGen, you confirm that you have read and agree
|
||||
to the following documents:
|
||||
to the following documents (also readable inside the app under About > Legal):
|
||||
|
||||
Terms of Use: https://github.com/poli0981/youtube-generator/blob/main/TERMS.md
|
||||
Privacy Policy: https://github.com/poli0981/youtube-generator/blob/main/PRIVACY.md
|
||||
Disclaimer: https://github.com/poli0981/youtube-generator/blob/main/DISCLAIMER.md
|
||||
License: https://github.com/poli0981/youtube-generator/blob/main/LICENSE
|
||||
Terms of Use: https://ytgenerator.stream/legal/terms
|
||||
Privacy Policy: https://ytgenerator.stream/legal/privacy
|
||||
Disclaimer: https://ytgenerator.stream/legal/disclaimer
|
||||
License: https://ytgenerator.stream/legal/license
|
||||
|
||||
In short:
|
||||
|
||||
* YTDescGen is free, open-source software, provided AS IS, WITHOUT WARRANTY
|
||||
OF ANY KIND. You use it at your own risk (see the Disclaimer and License
|
||||
sections 7-8).
|
||||
* It works fully offline. It does not collect, transmit, or sell any
|
||||
personal data; your profiles, history, and generated text stay on your
|
||||
device (see the Privacy Policy).
|
||||
* The desktop app works fully offline. It has no analytics or telemetry and
|
||||
does not collect, transmit, or sell any personal data; your profiles,
|
||||
history, and generated text stay on your device (see the Privacy Policy).
|
||||
* You are responsible for ensuring the titles, descriptions, and tags you
|
||||
generate comply with YouTube's policies and applicable law (see the
|
||||
Terms of Use).
|
||||
|
||||
+140
-126
@@ -1,5 +1,5 @@
|
||||
import { lazy, Suspense, useEffect, type ReactNode } from "react";
|
||||
import { HashRouter, Routes, Route } from "react-router-dom";
|
||||
import { BrowserRouter, HashRouter, Outlet, Routes, Route } from "react-router-dom";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
import toast from "react-hot-toast";
|
||||
import { AppShell } from "@components/layout/AppShell";
|
||||
@@ -14,6 +14,7 @@ import { checkDataFileHealth } from "@utils/storage-adapter";
|
||||
import { hydrateLogStore } from "@store/log-store";
|
||||
import { useSettingsStore } from "@store/settings-store";
|
||||
import i18n from "@i18n/index";
|
||||
import { IS_TAURI } from "@utils/platform";
|
||||
|
||||
const ProfilesPage = lazy(() =>
|
||||
import("@pages/ProfilesPage").then((m) => ({ default: m.ProfilesPage })),
|
||||
@@ -31,6 +32,15 @@ const PlaylistPage = lazy(() =>
|
||||
);
|
||||
const LogPage = lazy(() => import("@pages/LogPage").then((m) => ({ default: m.LogPage })));
|
||||
const AboutPage = lazy(() => import("@pages/AboutPage").then((m) => ({ default: m.AboutPage })));
|
||||
// Lazy on purpose: the rendered legal HTML travels with this chunk only.
|
||||
const LegalPage = lazy(() => import("@pages/LegalPage").then((m) => ({ default: m.LegalPage })));
|
||||
|
||||
/**
|
||||
* Real paths on the web (ytgenerator.stream serves the shell for every route,
|
||||
* and Cloudflare Web Analytics counts page views by path); hash routing inside
|
||||
* Tauri, whose asset protocol has no server-side fallback to rely on.
|
||||
*/
|
||||
const Router = IS_TAURI ? HashRouter : BrowserRouter;
|
||||
|
||||
function PageLoader() {
|
||||
return <div className="text-text-muted flex items-center justify-center p-12">Loading...</div>;
|
||||
@@ -53,6 +63,25 @@ function PageBoundary({ label, children }: { label: string; children: ReactNode
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.28.0 first-run legal consent gate, as a layout route: until the user
|
||||
* accepts the current terms version, every app route renders the gate instead.
|
||||
* The Legal Center routes sit outside this guard so the gate can open each
|
||||
* document in place.
|
||||
*/
|
||||
function ConsentGuard() {
|
||||
const legalConsentVersion = useSettingsStore((s) => s.legalConsentVersion);
|
||||
return needsConsent(legalConsentVersion) ? <ConsentGate /> : <Outlet />;
|
||||
}
|
||||
|
||||
const TOASTER_OPTIONS = {
|
||||
style: {
|
||||
background: "var(--surface-2)",
|
||||
color: "var(--text-primary)",
|
||||
border: "1px solid var(--border)",
|
||||
},
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
useEffect(() => {
|
||||
checkDataFileHealth().then((msg) => {
|
||||
@@ -97,138 +126,123 @@ export default function App() {
|
||||
return () => unsub();
|
||||
}, []);
|
||||
|
||||
// v0.28.0: first-run legal consent gate. Until the user accepts the current
|
||||
// terms version, render the gate INSTEAD of the router so nothing in the app
|
||||
// is reachable. The whole tree stays inside the root ErrorBoundary
|
||||
// (main.tsx), so a gate render error still degrades to the error page.
|
||||
const legalConsentVersion = useSettingsStore((s) => s.legalConsentVersion);
|
||||
|
||||
if (needsConsent(legalConsentVersion)) {
|
||||
return (
|
||||
<>
|
||||
<ConsentGate />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
toastOptions={{
|
||||
style: {
|
||||
background: "var(--surface-2)",
|
||||
color: "var(--text-primary)",
|
||||
border: "1px solid var(--border)",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<HashRouter>
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route element={<AppShell />}>
|
||||
<Route
|
||||
index
|
||||
element={
|
||||
<ErrorBoundary label="Editor">
|
||||
<EditorPage />
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="output"
|
||||
element={
|
||||
<ErrorBoundary label="Output">
|
||||
<OutputPage />
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="profiles"
|
||||
element={
|
||||
<PageBoundary label="Profiles">
|
||||
<ProfilesPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="history"
|
||||
element={
|
||||
<PageBoundary label="History">
|
||||
<HistoryPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="settings"
|
||||
element={
|
||||
<PageBoundary label="Settings">
|
||||
<SettingsPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="batch"
|
||||
element={
|
||||
<PageBoundary label="Batch">
|
||||
<BatchPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="social"
|
||||
element={
|
||||
<PageBoundary label="Social">
|
||||
<SocialPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="playlist"
|
||||
element={
|
||||
<PageBoundary label="Playlist">
|
||||
<PlaylistPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="logs"
|
||||
element={
|
||||
<PageBoundary label="Logs">
|
||||
<LogPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="about"
|
||||
element={
|
||||
<PageBoundary label="About">
|
||||
<AboutPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
{/* Designed error pages — siblings of the AppShell group so they
|
||||
<Route
|
||||
path="/legal"
|
||||
element={
|
||||
<PageBoundary label="Legal">
|
||||
<LegalPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/legal/:docId"
|
||||
element={
|
||||
<PageBoundary label="Legal">
|
||||
<LegalPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route element={<ConsentGuard />}>
|
||||
<Route element={<AppShell />}>
|
||||
<Route
|
||||
index
|
||||
element={
|
||||
<ErrorBoundary label="Editor">
|
||||
<EditorPage />
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="output"
|
||||
element={
|
||||
<ErrorBoundary label="Output">
|
||||
<OutputPage />
|
||||
</ErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="profiles"
|
||||
element={
|
||||
<PageBoundary label="Profiles">
|
||||
<ProfilesPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="history"
|
||||
element={
|
||||
<PageBoundary label="History">
|
||||
<HistoryPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="settings"
|
||||
element={
|
||||
<PageBoundary label="Settings">
|
||||
<SettingsPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="batch"
|
||||
element={
|
||||
<PageBoundary label="Batch">
|
||||
<BatchPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="social"
|
||||
element={
|
||||
<PageBoundary label="Social">
|
||||
<SocialPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="playlist"
|
||||
element={
|
||||
<PageBoundary label="Playlist">
|
||||
<PlaylistPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="logs"
|
||||
element={
|
||||
<PageBoundary label="Logs">
|
||||
<LogPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="about"
|
||||
element={
|
||||
<PageBoundary label="About">
|
||||
<AboutPage />
|
||||
</PageBoundary>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
{/* Designed error pages — siblings of the AppShell group so they
|
||||
render full-screen with no Sidebar/Header. `403/419/500` are
|
||||
route-reachable for future triggers; `*` is the live 404 for
|
||||
any mistyped hash path. */}
|
||||
<Route path="/403" element={<ErrorPage kind="forbidden" />} />
|
||||
<Route path="/419" element={<ErrorPage kind="expired" />} />
|
||||
<Route path="/500" element={<ErrorPage kind="serverError" />} />
|
||||
<Route path="/offline" element={<ErrorPage kind="offline" />} />
|
||||
<Route path="*" element={<ErrorPage kind="notFound" />} />
|
||||
any mistyped path. */}
|
||||
<Route path="/403" element={<ErrorPage kind="forbidden" />} />
|
||||
<Route path="/419" element={<ErrorPage kind="expired" />} />
|
||||
<Route path="/500" element={<ErrorPage kind="serverError" />} />
|
||||
<Route path="/offline" element={<ErrorPage kind="offline" />} />
|
||||
<Route path="*" element={<ErrorPage kind="notFound" />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
<OfflineBanner />
|
||||
</HashRouter>
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
toastOptions={{
|
||||
style: {
|
||||
background: "var(--surface-2)",
|
||||
color: "var(--text-primary)",
|
||||
border: "1px solid var(--border)",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Router>
|
||||
<Toaster position="bottom-right" toastOptions={TOASTER_OPTIONS} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ExternalLink, ShieldCheck } from "lucide-react";
|
||||
import { ChevronRight, ShieldCheck } from "lucide-react";
|
||||
import { Button } from "@components/ui/Button";
|
||||
import { Checkbox } from "@components/ui/Checkbox";
|
||||
import { useDocumentTitle } from "@hooks/use-document-title";
|
||||
import { useSettingsStore } from "@store/settings-store";
|
||||
import { LEGAL_DOCS } from "@config/legal";
|
||||
import { LEGAL_DOCS, legalDocPath } from "@config/legal";
|
||||
|
||||
/** The documents a user agrees to on this screen. */
|
||||
const CONSENT_DOCS = LEGAL_DOCS.filter((doc) => doc.consent);
|
||||
|
||||
/**
|
||||
* First-run legal consent gate. Rendered full-screen and **non-dismissible**
|
||||
@@ -13,10 +17,12 @@ import { LEGAL_DOCS } from "@config/legal";
|
||||
* in place of the router until the user accepts the current terms version.
|
||||
*
|
||||
* Layout mirrors the v0.27.0 ErrorPage fullscreen pattern. Acceptance is
|
||||
* recorded in the settings store (`acceptLegalConsent`), which dual-writes to
|
||||
* localStorage + the Tauri settings file; the gate then yields to the app.
|
||||
* Re-shows automatically when CURRENT_TERMS_VERSION is bumped, and in fresh /
|
||||
* incognito storage.
|
||||
* recorded in the settings store (`acceptLegalConsent`); the gate then yields
|
||||
* to the app. Re-shows automatically when CURRENT_TERMS_VERSION is bumped, and
|
||||
* in fresh / incognito storage. Each document opens in the in-app Legal Center
|
||||
* (a route outside the consent guard), so reading one never leaves the app.
|
||||
* On the web, agreeing on the Cloudflare gate page counts too — see
|
||||
* `acceptConsentFromGate` in main.tsx.
|
||||
*/
|
||||
export function ConsentGate() {
|
||||
const { t } = useTranslation("ui");
|
||||
@@ -45,17 +51,15 @@ export function ConsentGate() {
|
||||
</div>
|
||||
|
||||
<div className="grid w-full max-w-md gap-2 sm:grid-cols-2">
|
||||
{LEGAL_DOCS.map((doc) => (
|
||||
<a
|
||||
{CONSENT_DOCS.map((doc) => (
|
||||
<Link
|
||||
key={doc.id}
|
||||
href={doc.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
to={legalDocPath(doc.id)}
|
||||
className="border-border bg-surface-1 text-text-primary hover:border-accent hover:bg-surface-2 flex items-center gap-3 rounded-lg border px-3 py-2.5 text-sm transition-colors"
|
||||
>
|
||||
<span className="flex-1 truncate text-left">{t(doc.labelKey)}</span>
|
||||
<ExternalLink className="text-text-muted h-3.5 w-3.5 shrink-0" />
|
||||
</a>
|
||||
<ChevronRight className="text-text-muted h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import clsx from "clsx";
|
||||
import { Button } from "@components/ui/Button";
|
||||
import { useDocumentTitle } from "@hooks/use-document-title";
|
||||
import { ABOUT } from "@config/about";
|
||||
import { IS_TAURI } from "@utils/platform";
|
||||
import { resolveErrorMeta, severityTextClass, type ErrorKind } from "@config/error-pages";
|
||||
|
||||
interface ErrorPageProps {
|
||||
@@ -24,10 +25,11 @@ interface ErrorPageProps {
|
||||
* the contained boundary card.
|
||||
*
|
||||
* Intentionally **router-agnostic**: the root ErrorBoundary in `main.tsx`
|
||||
* mounts *outside* `<HashRouter>`, so calling `useNavigate()` here would throw
|
||||
* mounts *outside* the router, so calling `useNavigate()` here would throw
|
||||
* "useNavigate may be used only in the context of a Router" inside the very
|
||||
* crash path it is meant to handle. Navigation is therefore plain hash anchors
|
||||
* (`#/`) + `history.back()`, which work whether or not a Router is above.
|
||||
* crash path it is meant to handle. Navigation is therefore a plain location
|
||||
* change ({@link goHome}) + `history.back()`, which work whether or not a
|
||||
* Router is above.
|
||||
*
|
||||
* The dispatcher itself calls no hooks, so each variant component owns its own
|
||||
* unconditional hook calls (no hook-order hazard across the branch).
|
||||
@@ -40,6 +42,12 @@ export function ErrorPage(props: ErrorPageProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Home without a router: hash routing in Tauri, real paths on the web. */
|
||||
function goHome(): void {
|
||||
if (IS_TAURI) window.location.hash = "#/";
|
||||
else window.location.assign("/");
|
||||
}
|
||||
|
||||
function FullscreenError({ kind }: ErrorPageProps) {
|
||||
const { t } = useTranslation("ui");
|
||||
const meta = resolveErrorMeta(kind);
|
||||
@@ -64,12 +72,7 @@ function FullscreenError({ kind }: ErrorPageProps) {
|
||||
<p className="text-text-secondary text-sm">{description}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-center gap-3">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => {
|
||||
window.location.hash = "#/";
|
||||
}}
|
||||
>
|
||||
<Button variant="primary" onClick={goHome}>
|
||||
<House className="h-4 w-4" />
|
||||
{t("errorPages.actions.home")}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Brand constants shared by the app, the build plugins and the Cloudflare
|
||||
* Worker. The canonical artwork lives in `assets/brand/logo.svg`; this inline
|
||||
* copy is for places that cannot load a file (the Worker's gate page, the
|
||||
* prerendered legal pages, the static 404) and must stay visually identical.
|
||||
*/
|
||||
|
||||
export const SITE_ORIGIN = "https://ytgenerator.stream";
|
||||
|
||||
export const BRAND_GRADIENT = { from: "#6366F1", to: "#A855F7" } as const;
|
||||
|
||||
/** The app mark as an inline SVG string (`aria-hidden`; pair it with text). */
|
||||
export const LOGO_SVG = `<svg viewBox="0 0 512 512" aria-hidden="true" focusable="false"><defs><linearGradient id="ytg-g" x1="40" y1="24" x2="472" y2="488" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${BRAND_GRADIENT.from}"/><stop offset="1" stop-color="${BRAND_GRADIENT.to}"/></linearGradient></defs><rect width="512" height="512" rx="120" fill="url(#ytg-g)"/><path d="M176 118c0-17.9 19.4-29.1 34.9-20.1l128.2 74c15.5 9 15.5 31.2 0 40.2l-128.2 74C195.4 295.1 176 283.9 176 266z" fill="#fff"/><rect x="136" y="322" width="240" height="32" rx="16" fill="#fff" fill-opacity=".92"/><rect x="136" y="374" width="160" height="32" rx="16" fill="#fff" fill-opacity=".6"/></svg>`;
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
*
|
||||
* YTDescGen is a pure-client SPA (HashRouter, no backend), so `forbidden` /
|
||||
* `expired` / `serverError` never arise from the app's own logic today — they
|
||||
* exist as designed, route-reachable pages (`/#/403`, `/#/419`, `/#/500`)
|
||||
* exist as designed, route-reachable pages (`/403`, `/419`, `/500`)
|
||||
* ready to be wired to future triggers (a Tauri command failure, a future
|
||||
* sync backend). The kinds that *do* fire:
|
||||
* - `notFound` — the catch-all `*` route (a mistyped hash path)
|
||||
* - `notFound` — the catch-all `*` route (a mistyped path)
|
||||
* - `offline` — `navigator.onLine` flips false (see use-online-status)
|
||||
* - `runtime` — a render crash caught by ErrorBoundary
|
||||
*/
|
||||
|
||||
+88
-17
@@ -1,11 +1,72 @@
|
||||
const DOC_BASE = "https://github.com/poli0981/youtube-generator/blob/main";
|
||||
/**
|
||||
* Legal documents, served in-site since v1.0.0.
|
||||
*
|
||||
* The Markdown/plain-text files at the repo root stay the single source of
|
||||
* truth. At build time `build-plugins/legal-docs.ts` renders each one twice:
|
||||
* into the lazily-loaded `virtual:legal-docs` module the in-app Legal Center
|
||||
* reads (so the desktop and Android builds carry them offline), and into a
|
||||
* static `dist/legal/<id>.html` page that the Cloudflare Worker serves to
|
||||
* visitors who have not passed the Turnstile gate yet — the Terms and Privacy
|
||||
* Policy must be readable *before* anyone is asked to agree to them.
|
||||
*
|
||||
* This module is imported by the app, the Vite plugin and the Worker, so it
|
||||
* must stay free of browser- or React-only imports.
|
||||
*/
|
||||
|
||||
export type LegalDocId =
|
||||
| "terms"
|
||||
| "privacy"
|
||||
| "disclaimer"
|
||||
| "license"
|
||||
| "third-party"
|
||||
| "security"
|
||||
| "notice"
|
||||
| "conduct";
|
||||
|
||||
export interface LegalDoc {
|
||||
readonly id: "terms" | "privacy" | "disclaimer" | "license";
|
||||
/** i18n key under the `consentGate` ui section. */
|
||||
readonly id: LegalDocId;
|
||||
/** i18n key (ui namespace) for the document's display name. */
|
||||
readonly labelKey: string;
|
||||
/** Absolute GitHub blob URL — opens in the system browser via target="_blank". */
|
||||
readonly url: string;
|
||||
/** Repo-relative source file rendered at build time. */
|
||||
readonly source: string;
|
||||
/** Repo-relative Vietnamese translation, when one exists. */
|
||||
readonly sourceVi?: string;
|
||||
/** Listed on the first-run consent gate (the documents a user agrees to). */
|
||||
readonly consent: boolean;
|
||||
}
|
||||
|
||||
/** Display order = array order, in the Legal Center and on the consent gate. */
|
||||
export const LEGAL_DOCS: readonly LegalDoc[] = [
|
||||
{ id: "terms", labelKey: "legal.docs.terms", source: "TERMS.md", consent: true },
|
||||
{ id: "privacy", labelKey: "legal.docs.privacy", source: "PRIVACY.md", consent: true },
|
||||
{
|
||||
id: "disclaimer",
|
||||
labelKey: "legal.docs.disclaimer",
|
||||
source: "DISCLAIMER.md",
|
||||
sourceVi: "docs/i18n/vi/DISCLAIMER.md",
|
||||
consent: true,
|
||||
},
|
||||
{ id: "license", labelKey: "legal.docs.license", source: "LICENSE", consent: true },
|
||||
{
|
||||
id: "third-party",
|
||||
labelKey: "legal.docs.thirdParty",
|
||||
source: "THIRD_PARTY_NOTICES.md",
|
||||
consent: false,
|
||||
},
|
||||
{ id: "security", labelKey: "legal.docs.security", source: "SECURITY.md", consent: false },
|
||||
{ id: "notice", labelKey: "legal.docs.notice", source: "NOTICE", consent: false },
|
||||
{ id: "conduct", labelKey: "legal.docs.conduct", source: "CODE_OF_CONDUCT.md", consent: false },
|
||||
];
|
||||
|
||||
export const LEGAL_DOC_IDS: readonly LegalDocId[] = LEGAL_DOCS.map((d) => d.id);
|
||||
|
||||
export function isLegalDocId(value: string): value is LegalDocId {
|
||||
return (LEGAL_DOC_IDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/** In-site path of a document — the same URL on the static page and in the app. */
|
||||
export function legalDocPath(id: LegalDocId): string {
|
||||
return `/legal/${id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,22 +74,32 @@ export interface LegalDoc {
|
||||
* Terms / Privacy / Disclaimer change materially — every user whose stored
|
||||
* `legalConsentVersion` is below this re-sees the first-run consent gate.
|
||||
*
|
||||
* v0.28.0 ships the first gate at version 1 (docs dated 2026-05-14).
|
||||
* 1 — v0.28.0: first gate (documents dated 2026-05-14).
|
||||
* 2 — v1.0.0: web hosting moved to Cloudflare (Turnstile + Web Analytics
|
||||
* added to the Privacy Policy).
|
||||
*/
|
||||
export const CURRENT_TERMS_VERSION = 1;
|
||||
export const CURRENT_TERMS_VERSION = 2;
|
||||
|
||||
/**
|
||||
* The documents surfaced on the consent gate and the About → Legal section.
|
||||
* Stored at the repo root and served from GitHub so they are always current;
|
||||
* the in-app links open them in the browser (Tauri routes target="_blank" to
|
||||
* the system browser). Order = display order.
|
||||
* Cookie the Cloudflare Worker sets when a visitor ticks "I agree" on the
|
||||
* Turnstile gate page. Deliberately readable from JavaScript: the web app uses
|
||||
* it to record the same acceptance locally, so a web visitor meets one
|
||||
* blocking screen instead of two. Never set in the desktop / Android builds.
|
||||
*/
|
||||
export const LEGAL_DOCS: readonly LegalDoc[] = [
|
||||
{ id: "terms", labelKey: "consentGate.docTerms", url: `${DOC_BASE}/TERMS.md` },
|
||||
{ id: "privacy", labelKey: "consentGate.docPrivacy", url: `${DOC_BASE}/PRIVACY.md` },
|
||||
{ id: "disclaimer", labelKey: "consentGate.docDisclaimer", url: `${DOC_BASE}/DISCLAIMER.md` },
|
||||
{ id: "license", labelKey: "consentGate.docLicense", url: `${DOC_BASE}/LICENSE` },
|
||||
];
|
||||
export const TERMS_COOKIE = "ytg_terms";
|
||||
|
||||
/** Parse the accepted terms version out of a `document.cookie`-style string. */
|
||||
export function termsVersionFromCookie(cookieHeader: string | null | undefined): number | null {
|
||||
if (!cookieHeader) return null;
|
||||
for (const part of cookieHeader.split(";")) {
|
||||
const eq = part.indexOf("=");
|
||||
if (eq < 0 || part.slice(0, eq).trim() !== TERMS_COOKIE) continue;
|
||||
const raw = part.slice(eq + 1).trim();
|
||||
if (!/^\d{1,4}$/.test(raw)) return null;
|
||||
return Number(raw);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the consent gate must be shown — the user has not yet accepted the
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
"errorPages.serverError": ["title", "description"],
|
||||
"errorPages.offline": ["title", "description"],
|
||||
"errorPages.runtime": ["title", "description"],
|
||||
"consentGate": ["title", "intro", "agreeLabel", "continue", "mustAgree", "docTerms", "docPrivacy", "docDisclaimer", "docLicense"],
|
||||
"consentGate": ["title", "intro", "agreeLabel", "continue", "mustAgree"],
|
||||
"videoTypes": ["full", "part", "full_demo", "demo_part", "boss", "boss_nohit", "ending", "speedrun", "100percent", "dlc", "newgame_plus", "challenge", "side_quest", "secret", "comparison", "guide", "mods", "collectibles", "livestream", "gacha_quest"],
|
||||
"genres": ["action", "hack_slash", "beatemup", "platformer", "horror", "survival_horror", "psychological_horror", "rpg", "jrpg", "action_rpg", "crpg", "fps", "arena_shooter", "tactical_fps", "boomer_shooter", "extraction_shooter", "shmup", "openworld", "indie", "soulslike", "racing", "story", "simulation", "city_builder", "fighting", "stealth", "survival_craft", "roguelike", "metroidvania", "mmo", "rhythm", "puzzle", "tower_defense", "card_game", "deck_builder", "auto_battler", "battle_royale", "tactical", "space", "farming", "fmv", "visual_novel"],
|
||||
"rig": ["os", "cpu", "gpu", "ram", "storage", "monitor", "capture", "motherboard", "controller", "video_editor"],
|
||||
@@ -200,7 +200,10 @@
|
||||
"validation": ["emailInvalid", "emailMaxExceeded", "urlInvalid", "urlPrefixMismatch", "playlistUrlInvalid", "messengerUrlInvalid", "zaloUrlInvalid", "signalUrlInvalid", "instagramInviteUrlInvalid", "facebookGroupUrlInvalid", "numberRequired", "numberInvalid", "numberNotInteger", "numberOutOfRange", "rangeEndBeforeStart", "rangeTooLarge", "emailMaxReached", "fieldTooLong"],
|
||||
"logs": ["title", "emptyState", "clearAll", "clearConfirm", "clearPersistedConfirm", "clearSession", "searchPlaceholder", "exportJson", "exportTxt", "sessionCurrent", "sessionLabel", "entriesShort"],
|
||||
"playlist": ["title", "status", "contentType", "totalVideos", "customNote", "generatePlaylist", "droppedReasonsLabel", "droppedReasonCustomLabel", "droppedReasonCustomPlaceholder", "pinnedComment"],
|
||||
"playlist.droppedReasons": ["boring", "performance", "bugs", "delisted", "low_views", "time"]
|
||||
"playlist.droppedReasons": ["boring", "performance", "bugs", "delisted", "low_views", "time"],
|
||||
"legal": ["title", "intro", "englishOnly", "back", "allDocuments", "loading", "notFound", "language"],
|
||||
"legal.docs": ["terms", "privacy", "disclaimer", "license", "thirdParty", "security", "notice", "conduct"],
|
||||
"legal.summaries": ["terms", "privacy", "disclaimer", "license", "thirdParty", "security", "notice", "conduct"]
|
||||
},
|
||||
"templates": {
|
||||
"title": ["separator", "suffix"],
|
||||
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "Before you start",
|
||||
"intro": "YTDescGen is a free, offline-first tool. Please review the documents below. By continuing, you confirm you have read and agree to them.",
|
||||
"intro": "YTDescGen is free and open source. Please review the documents below — each one opens right here. By continuing, you confirm you have read and agree to them.",
|
||||
"agreeLabel": "I have read and agree to the Terms of Use, Privacy Policy, Disclaimer, and License.",
|
||||
"continue": "Continue",
|
||||
"mustAgree": "Please check the box to continue.",
|
||||
"docTerms": "Terms of Use",
|
||||
"docPrivacy": "Privacy Policy",
|
||||
"docDisclaimer": "Disclaimer",
|
||||
"docLicense": "License (Apache-2.0)"
|
||||
"mustAgree": "Please check the box to continue."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "Full Gameplay",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "Strict Mode: {{count}} field(s) need fixing",
|
||||
"fixHint": "Fix these in the Editor, or turn Strict Mode off in Settings."
|
||||
},
|
||||
"legal": {
|
||||
"title": "Legal",
|
||||
"intro": "Terms, privacy, licensing and security for YTDescGen — the same documents published at ytgenerator.stream/legal.",
|
||||
"englishOnly": "Documents are published in English; the Disclaimer also has a Vietnamese version.",
|
||||
"back": "Back",
|
||||
"allDocuments": "All documents",
|
||||
"loading": "Loading document…",
|
||||
"notFound": "That document doesn't exist.",
|
||||
"language": "Document language",
|
||||
"docs": {
|
||||
"terms": "Terms of Use",
|
||||
"privacy": "Privacy Policy",
|
||||
"disclaimer": "Disclaimer",
|
||||
"license": "License (Apache-2.0)",
|
||||
"thirdParty": "Third-party notices",
|
||||
"security": "Security policy",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "Code of Conduct"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "What you may and may not do with YTDescGen and what it generates.",
|
||||
"privacy": "What stays on your device, and what Cloudflare processes on the web.",
|
||||
"disclaimer": "No warranty, AI-assisted development and translations, no affiliation.",
|
||||
"license": "The Apache License 2.0 the source code is released under.",
|
||||
"thirdParty": "Open-source libraries, fonts and services YTDescGen relies on.",
|
||||
"security": "How to report a vulnerability privately, and what is in scope.",
|
||||
"notice": "The Apache-2.0 NOTICE file with copyright and attribution.",
|
||||
"conduct": "Contributor Covenant rules for the project's community spaces."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "Antes de empezar",
|
||||
"intro": "YTDescGen es una herramienta gratuita y con prioridad sin conexión. Revisa los documentos siguientes. Al continuar, confirmas que los has leído y los aceptas.",
|
||||
"intro": "YTDescGen es gratuito y de código abierto. Revisa los documentos de abajo: cada uno se abre aquí mismo. Al continuar, confirmas que los has leído y los aceptas.",
|
||||
"agreeLabel": "He leído y acepto los Términos de Uso, la Política de Privacidad, el Aviso Legal y la Licencia.",
|
||||
"continue": "Continuar",
|
||||
"mustAgree": "Marca la casilla para continuar.",
|
||||
"docTerms": "Términos de Uso",
|
||||
"docPrivacy": "Política de Privacidad",
|
||||
"docDisclaimer": "Aviso Legal",
|
||||
"docLicense": "Licencia (Apache-2.0)"
|
||||
"mustAgree": "Marca la casilla para continuar."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "Gameplay Completo",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "Modo estricto: {{count}} campo(s) por corregir",
|
||||
"fixHint": "Corrígelos en el Editor o desactiva el Modo estricto en Ajustes."
|
||||
},
|
||||
"legal": {
|
||||
"title": "Información legal",
|
||||
"intro": "Términos, privacidad, licencias y seguridad de YTDescGen: los mismos documentos publicados en ytgenerator.stream/legal.",
|
||||
"englishOnly": "Los documentos se publican en inglés; el Descargo de responsabilidad también tiene versión en vietnamita.",
|
||||
"back": "Volver",
|
||||
"allDocuments": "Todos los documentos",
|
||||
"loading": "Cargando documento…",
|
||||
"notFound": "Ese documento no existe.",
|
||||
"language": "Idioma del documento",
|
||||
"docs": {
|
||||
"terms": "Términos de uso",
|
||||
"privacy": "Política de privacidad",
|
||||
"disclaimer": "Descargo de responsabilidad",
|
||||
"license": "Licencia (Apache-2.0)",
|
||||
"thirdParty": "Avisos de terceros",
|
||||
"security": "Política de seguridad",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "Código de conducta"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "Lo que puedes y no puedes hacer con YTDescGen y con lo que genera.",
|
||||
"privacy": "Qué se queda en tu dispositivo y qué procesa Cloudflare en la versión web.",
|
||||
"disclaimer": "Sin garantía, desarrollo y traducciones asistidos por IA, sin afiliación.",
|
||||
"license": "La Licencia Apache 2.0 bajo la que se publica el código fuente.",
|
||||
"thirdParty": "Bibliotecas de código abierto, fuentes y servicios en los que se basa YTDescGen.",
|
||||
"security": "Cómo informar de una vulnerabilidad en privado y qué está dentro del alcance.",
|
||||
"notice": "El archivo NOTICE de Apache-2.0 con derechos de autor y atribución.",
|
||||
"conduct": "Normas del Contributor Covenant para los espacios comunitarios del proyecto."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "Sebelum mulai",
|
||||
"intro": "YTDescGen adalah alat gratis yang mengutamakan mode offline. Silakan baca dokumen di bawah. Dengan melanjutkan, kamu menyatakan telah membaca dan menyetujuinya.",
|
||||
"intro": "YTDescGen gratis dan bersumber terbuka. Silakan tinjau dokumen di bawah — setiap dokumen dapat dibuka di sini. Dengan melanjutkan, Anda menyatakan telah membaca dan menyetujuinya.",
|
||||
"agreeLabel": "Saya telah membaca dan menyetujui Ketentuan Penggunaan, Kebijakan Privasi, Disclaimer, dan Lisensi.",
|
||||
"continue": "Lanjutkan",
|
||||
"mustAgree": "Centang kotaknya untuk melanjutkan.",
|
||||
"docTerms": "Ketentuan Penggunaan",
|
||||
"docPrivacy": "Kebijakan Privasi",
|
||||
"docDisclaimer": "Disclaimer",
|
||||
"docLicense": "Lisensi (Apache-2.0)"
|
||||
"mustAgree": "Centang kotaknya untuk melanjutkan."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "Gameplay Lengkap",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "Mode Ketat: {{count}} kolom perlu diperbaiki",
|
||||
"fixHint": "Perbaiki di Editor, atau matikan Mode Ketat di Pengaturan."
|
||||
},
|
||||
"legal": {
|
||||
"title": "Informasi hukum",
|
||||
"intro": "Ketentuan, privasi, lisensi, dan keamanan YTDescGen — dokumen yang sama dengan yang diterbitkan di ytgenerator.stream/legal.",
|
||||
"englishOnly": "Dokumen diterbitkan dalam bahasa Inggris; Penafian juga tersedia dalam bahasa Vietnam.",
|
||||
"back": "Kembali",
|
||||
"allDocuments": "Semua dokumen",
|
||||
"loading": "Memuat dokumen…",
|
||||
"notFound": "Dokumen itu tidak ada.",
|
||||
"language": "Bahasa dokumen",
|
||||
"docs": {
|
||||
"terms": "Ketentuan Penggunaan",
|
||||
"privacy": "Kebijakan Privasi",
|
||||
"disclaimer": "Penafian",
|
||||
"license": "Lisensi (Apache-2.0)",
|
||||
"thirdParty": "Pemberitahuan pihak ketiga",
|
||||
"security": "Kebijakan keamanan",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "Kode Etik"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "Apa yang boleh dan tidak boleh Anda lakukan dengan YTDescGen dan hasilnya.",
|
||||
"privacy": "Apa yang tetap di perangkat Anda, dan apa yang diproses Cloudflare di versi web.",
|
||||
"disclaimer": "Tanpa jaminan, pengembangan dan terjemahan dibantu AI, tanpa afiliasi.",
|
||||
"license": "Lisensi Apache 2.0 yang berlaku untuk kode sumber.",
|
||||
"thirdParty": "Pustaka sumber terbuka, font, dan layanan yang digunakan YTDescGen.",
|
||||
"security": "Cara melaporkan kerentanan secara pribadi, dan cakupannya.",
|
||||
"notice": "Berkas NOTICE Apache-2.0 berisi hak cipta dan atribusi.",
|
||||
"conduct": "Aturan Contributor Covenant untuk ruang komunitas proyek."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "始める前に",
|
||||
"intro": "YTDescGen は無料・オフライン優先のツールです。下記の文書をご確認ください。続行すると、これらを読み同意したことになります。",
|
||||
"intro": "YTDescGen は無料のオープンソースツールです。以下の文書をご確認ください(このアプリ内で開けます)。続行すると、内容を読み同意したものとみなされます。",
|
||||
"agreeLabel": "利用規約、プライバシーポリシー、免責事項、およびライセンスを読み、同意します。",
|
||||
"continue": "続行",
|
||||
"mustAgree": "続行するにはチェックを入れてください。",
|
||||
"docTerms": "利用規約",
|
||||
"docPrivacy": "プライバシーポリシー",
|
||||
"docDisclaimer": "免責事項",
|
||||
"docLicense": "ライセンス (Apache-2.0)"
|
||||
"mustAgree": "続行するにはチェックを入れてください。"
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "フルゲームプレイ",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "厳格モード: {{count}} 件の項目に修正が必要です",
|
||||
"fixHint": "エディタで修正するか、設定で厳格モードをオフにしてください。"
|
||||
},
|
||||
"legal": {
|
||||
"title": "法的情報",
|
||||
"intro": "YTDescGen の利用規約、プライバシー、ライセンス、セキュリティ。ytgenerator.stream/legal で公開しているものと同じ文書です。",
|
||||
"englishOnly": "文書は英語で公開しています(免責事項のみベトナム語版もあります)。",
|
||||
"back": "戻る",
|
||||
"allDocuments": "すべての文書",
|
||||
"loading": "文書を読み込んでいます…",
|
||||
"notFound": "その文書は存在しません。",
|
||||
"language": "文書の言語",
|
||||
"docs": {
|
||||
"terms": "利用規約",
|
||||
"privacy": "プライバシーポリシー",
|
||||
"disclaimer": "免責事項",
|
||||
"license": "ライセンス(Apache-2.0)",
|
||||
"thirdParty": "サードパーティ通知",
|
||||
"security": "セキュリティポリシー",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "行動規範"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "YTDescGen と生成された内容について、できること・できないこと。",
|
||||
"privacy": "端末に残るデータと、Web 版で Cloudflare が処理するデータ。",
|
||||
"disclaimer": "無保証、AI 支援による開発と翻訳、提携関係なし。",
|
||||
"license": "ソースコードに適用される Apache License 2.0。",
|
||||
"thirdParty": "YTDescGen が利用しているオープンソースライブラリ、フォント、サービス。",
|
||||
"security": "脆弱性を非公開で報告する方法と対象範囲。",
|
||||
"notice": "著作権と帰属を記した Apache-2.0 の NOTICE ファイル。",
|
||||
"conduct": "プロジェクトのコミュニティに適用される Contributor Covenant の規則。"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "시작하기 전에",
|
||||
"intro": "YTDescGen은 무료이며 오프라인을 우선하는 도구입니다. 아래 문서를 검토해 주세요. 계속하면 문서를 읽고 동의한 것으로 간주됩니다.",
|
||||
"intro": "YTDescGen은 무료 오픈 소스 도구입니다. 아래 문서를 확인해 주세요. 각 문서는 바로 여기에서 열립니다. 계속하면 문서를 읽고 동의한 것으로 간주됩니다.",
|
||||
"agreeLabel": "이용약관, 개인정보 처리방침, 면책 조항 및 라이선스를 읽고 동의합니다.",
|
||||
"continue": "계속",
|
||||
"mustAgree": "계속하려면 체크박스를 선택하세요.",
|
||||
"docTerms": "이용약관",
|
||||
"docPrivacy": "개인정보 처리방침",
|
||||
"docDisclaimer": "면책 조항",
|
||||
"docLicense": "라이선스 (Apache-2.0)"
|
||||
"mustAgree": "계속하려면 체크박스를 선택하세요."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "전체 게임플레이",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "엄격 모드: {{count}}개 항목을 수정해야 합니다",
|
||||
"fixHint": "편집기에서 수정하거나 설정에서 엄격 모드를 끄세요."
|
||||
},
|
||||
"legal": {
|
||||
"title": "법적 고지",
|
||||
"intro": "YTDescGen의 약관, 개인정보, 라이선스, 보안 문서입니다. ytgenerator.stream/legal에 게시된 것과 같은 내용입니다.",
|
||||
"englishOnly": "문서는 영어로 게시됩니다. 면책 조항은 베트남어 버전도 있습니다.",
|
||||
"back": "뒤로",
|
||||
"allDocuments": "모든 문서",
|
||||
"loading": "문서를 불러오는 중…",
|
||||
"notFound": "해당 문서가 없습니다.",
|
||||
"language": "문서 언어",
|
||||
"docs": {
|
||||
"terms": "이용약관",
|
||||
"privacy": "개인정보 처리방침",
|
||||
"disclaimer": "면책 조항",
|
||||
"license": "라이선스(Apache-2.0)",
|
||||
"thirdParty": "타사 고지",
|
||||
"security": "보안 정책",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "행동 강령"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "YTDescGen과 생성된 결과물로 할 수 있는 일과 할 수 없는 일.",
|
||||
"privacy": "기기에 남는 데이터와 웹 버전에서 Cloudflare가 처리하는 데이터.",
|
||||
"disclaimer": "보증 없음, AI 지원 개발 및 번역, 제휴 관계 없음.",
|
||||
"license": "소스 코드에 적용되는 Apache License 2.0.",
|
||||
"thirdParty": "YTDescGen이 사용하는 오픈 소스 라이브러리, 글꼴, 서비스.",
|
||||
"security": "취약점을 비공개로 제보하는 방법과 적용 범위.",
|
||||
"notice": "저작권과 출처 표시를 담은 Apache-2.0 NOTICE 파일.",
|
||||
"conduct": "프로젝트 커뮤니티 공간에 적용되는 Contributor Covenant 규칙."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "Antes de começar",
|
||||
"intro": "O YTDescGen é uma ferramenta gratuita e offline-first. Leia os documentos abaixo. Ao continuar, você confirma que leu e concorda com eles.",
|
||||
"intro": "O YTDescGen é gratuito e de código aberto. Revise os documentos abaixo — cada um abre aqui mesmo. Ao continuar, você confirma que os leu e concorda com eles.",
|
||||
"agreeLabel": "Li e concordo com os Termos de Uso, a Política de Privacidade, o Aviso Legal e a Licença.",
|
||||
"continue": "Continuar",
|
||||
"mustAgree": "Marque a caixa para continuar.",
|
||||
"docTerms": "Termos de Uso",
|
||||
"docPrivacy": "Política de Privacidade",
|
||||
"docDisclaimer": "Aviso Legal",
|
||||
"docLicense": "Licença (Apache-2.0)"
|
||||
"mustAgree": "Marque a caixa para continuar."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "Gameplay completa",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "Modo estrito: {{count}} campo(s) precisam de correção",
|
||||
"fixHint": "Corrija no Editor ou desative o Modo estrito nas Configurações."
|
||||
},
|
||||
"legal": {
|
||||
"title": "Informações legais",
|
||||
"intro": "Termos, privacidade, licenças e segurança do YTDescGen — os mesmos documentos publicados em ytgenerator.stream/legal.",
|
||||
"englishOnly": "Os documentos são publicados em inglês; o Aviso de isenção também tem versão em vietnamita.",
|
||||
"back": "Voltar",
|
||||
"allDocuments": "Todos os documentos",
|
||||
"loading": "Carregando documento…",
|
||||
"notFound": "Esse documento não existe.",
|
||||
"language": "Idioma do documento",
|
||||
"docs": {
|
||||
"terms": "Termos de Uso",
|
||||
"privacy": "Política de Privacidade",
|
||||
"disclaimer": "Aviso de isenção de responsabilidade",
|
||||
"license": "Licença (Apache-2.0)",
|
||||
"thirdParty": "Avisos de terceiros",
|
||||
"security": "Política de segurança",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "Código de Conduta"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "O que você pode e não pode fazer com o YTDescGen e com o que ele gera.",
|
||||
"privacy": "O que fica no seu dispositivo e o que a Cloudflare processa na versão web.",
|
||||
"disclaimer": "Sem garantia, desenvolvimento e traduções com auxílio de IA, sem afiliação.",
|
||||
"license": "A Licença Apache 2.0 sob a qual o código-fonte é publicado.",
|
||||
"thirdParty": "Bibliotecas de código aberto, fontes e serviços usados pelo YTDescGen.",
|
||||
"security": "Como relatar uma vulnerabilidade de forma privada e o que está no escopo.",
|
||||
"notice": "O arquivo NOTICE da Apache-2.0 com direitos autorais e atribuição.",
|
||||
"conduct": "Regras do Contributor Covenant para os espaços da comunidade do projeto."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "Trước khi bắt đầu",
|
||||
"intro": "YTDescGen là công cụ miễn phí, ưu tiên hoạt động ngoại tuyến. Vui lòng xem các tài liệu bên dưới. Khi tiếp tục, bạn xác nhận đã đọc và đồng ý với chúng.",
|
||||
"intro": "YTDescGen miễn phí và mã nguồn mở. Hãy xem các văn bản bên dưới — mỗi văn bản đều mở ngay tại đây. Khi tiếp tục, bạn xác nhận đã đọc và đồng ý với chúng.",
|
||||
"agreeLabel": "Tôi đã đọc và đồng ý với Điều khoản Sử dụng, Chính sách Bảo mật, Tuyên bố Miễn trừ và Giấy phép.",
|
||||
"continue": "Tiếp tục",
|
||||
"mustAgree": "Vui lòng tích vào ô để tiếp tục.",
|
||||
"docTerms": "Điều khoản Sử dụng",
|
||||
"docPrivacy": "Chính sách Bảo mật",
|
||||
"docDisclaimer": "Tuyên bố Miễn trừ",
|
||||
"docLicense": "Giấy phép (Apache-2.0)"
|
||||
"mustAgree": "Vui lòng tích vào ô để tiếp tục."
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "Full Gameplay",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "Strict Mode: {{count}} trường cần sửa",
|
||||
"fixHint": "Hãy sửa trong tab Editor, hoặc tắt Strict Mode trong Cài đặt."
|
||||
},
|
||||
"legal": {
|
||||
"title": "Pháp lý",
|
||||
"intro": "Điều khoản, quyền riêng tư, giấy phép và bảo mật của YTDescGen — cùng nội dung được đăng tại ytgenerator.stream/legal.",
|
||||
"englishOnly": "Các văn bản được công bố bằng tiếng Anh; riêng Tuyên bố miễn trừ có thêm bản tiếng Việt.",
|
||||
"back": "Quay lại",
|
||||
"allDocuments": "Tất cả văn bản",
|
||||
"loading": "Đang tải văn bản…",
|
||||
"notFound": "Văn bản này không tồn tại.",
|
||||
"language": "Ngôn ngữ văn bản",
|
||||
"docs": {
|
||||
"terms": "Điều khoản sử dụng",
|
||||
"privacy": "Chính sách quyền riêng tư",
|
||||
"disclaimer": "Tuyên bố miễn trừ trách nhiệm",
|
||||
"license": "Giấy phép (Apache-2.0)",
|
||||
"thirdParty": "Thông báo bên thứ ba",
|
||||
"security": "Chính sách bảo mật",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "Quy tắc ứng xử"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "Những gì bạn được và không được làm với YTDescGen và nội dung nó tạo ra.",
|
||||
"privacy": "Dữ liệu nào ở lại trên thiết bị của bạn, và Cloudflare xử lý gì trên bản web.",
|
||||
"disclaimer": "Không bảo hành, phát triển và dịch thuật có hỗ trợ AI, không liên kết với bên nào.",
|
||||
"license": "Giấy phép Apache 2.0 áp dụng cho mã nguồn.",
|
||||
"thirdParty": "Thư viện mã nguồn mở, phông chữ và dịch vụ mà YTDescGen sử dụng.",
|
||||
"security": "Cách báo cáo lỗ hổng một cách riêng tư và phạm vi áp dụng.",
|
||||
"notice": "Tệp NOTICE theo Apache-2.0 với thông tin bản quyền và ghi công.",
|
||||
"conduct": "Quy tắc Contributor Covenant cho các không gian cộng đồng của dự án."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,14 +826,10 @@
|
||||
},
|
||||
"consentGate": {
|
||||
"title": "开始之前",
|
||||
"intro": "YTDescGen 是一款免费、离线优先的工具。请查看以下文档。继续即表示您已阅读并同意这些文档。",
|
||||
"intro": "YTDescGen 免费且开源。请查看下方文档——每份文档都可以直接在这里打开。继续即表示你已阅读并同意这些文档。",
|
||||
"agreeLabel": "我已阅读并同意《使用条款》《隐私政策》《免责声明》和《许可证》。",
|
||||
"continue": "继续",
|
||||
"mustAgree": "请勾选复选框以继续。",
|
||||
"docTerms": "使用条款",
|
||||
"docPrivacy": "隐私政策",
|
||||
"docDisclaimer": "免责声明",
|
||||
"docLicense": "许可证 (Apache-2.0)"
|
||||
"mustAgree": "请勾选复选框以继续。"
|
||||
},
|
||||
"videoTypes": {
|
||||
"full": "完整游戏实况",
|
||||
@@ -1149,5 +1145,35 @@
|
||||
"strict": {
|
||||
"blockedTitle": "严格模式:{{count}} 个字段需要修正",
|
||||
"fixHint": "请在编辑器中修正,或在设置中关闭严格模式。"
|
||||
},
|
||||
"legal": {
|
||||
"title": "法律信息",
|
||||
"intro": "YTDescGen 的条款、隐私、许可与安全文档——与 ytgenerator.stream/legal 上发布的内容相同。",
|
||||
"englishOnly": "文档以英文发布;免责声明另有越南语版本。",
|
||||
"back": "返回",
|
||||
"allDocuments": "全部文档",
|
||||
"loading": "正在加载文档…",
|
||||
"notFound": "该文档不存在。",
|
||||
"language": "文档语言",
|
||||
"docs": {
|
||||
"terms": "使用条款",
|
||||
"privacy": "隐私政策",
|
||||
"disclaimer": "免责声明",
|
||||
"license": "许可证(Apache-2.0)",
|
||||
"thirdParty": "第三方声明",
|
||||
"security": "安全政策",
|
||||
"notice": "NOTICE",
|
||||
"conduct": "行为准则"
|
||||
},
|
||||
"summaries": {
|
||||
"terms": "使用 YTDescGen 及其生成内容时可以做和不可以做的事。",
|
||||
"privacy": "哪些数据留在你的设备上,以及网页版中 Cloudflare 会处理哪些数据。",
|
||||
"disclaimer": "不提供担保、由 AI 协助开发与翻译、与任何方无关联。",
|
||||
"license": "源代码所采用的 Apache License 2.0。",
|
||||
"thirdParty": "YTDescGen 所依赖的开源库、字体和服务。",
|
||||
"security": "如何私下报告漏洞,以及适用范围。",
|
||||
"notice": "包含版权与署名信息的 Apache-2.0 NOTICE 文件。",
|
||||
"conduct": "适用于项目社区空间的 Contributor Covenant 规则。"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,70 @@ import i18n, { ensureLanguagesLoaded } from "@i18n/index";
|
||||
import { useSettingsStore } from "@store/settings-store";
|
||||
import { useEditorStore } from "@store/editor-store";
|
||||
import { installExternalLinkHandler } from "@utils/open-external";
|
||||
import { IS_TAURI } from "@utils/platform";
|
||||
import { CURRENT_TERMS_VERSION, needsConsent, termsVersionFromCookie } from "@config/legal";
|
||||
import "./styles/globals.css";
|
||||
|
||||
const root = document.getElementById("root");
|
||||
if (!root) throw new Error("Root element not found");
|
||||
|
||||
/**
|
||||
* v1.0.0 moved the web build from hash routes (`/#/output`) to real paths
|
||||
* (`/output`). Rewrite an old bookmark in place before the router reads the
|
||||
* URL. Tauri keeps hash routing, so this is web-only.
|
||||
*/
|
||||
function migrateHashUrl(): void {
|
||||
if (IS_TAURI || !window.location.hash.startsWith("#/")) return;
|
||||
window.history.replaceState(null, "", window.location.hash.slice(1) || "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cloudflare gate page asks for the same Terms/Privacy agreement as the
|
||||
* in-app consent screen and records it in the `ytg_terms` cookie. Carry that
|
||||
* acceptance over before the first render so a web visitor meets one blocking
|
||||
* screen, not two. Only ever upgrades; never set on desktop / Android.
|
||||
*/
|
||||
function acceptConsentFromGate(): void {
|
||||
if (IS_TAURI) return;
|
||||
const fromGate = termsVersionFromCookie(document.cookie);
|
||||
const settings = useSettingsStore.getState();
|
||||
if (
|
||||
fromGate !== null &&
|
||||
fromGate >= CURRENT_TERMS_VERSION &&
|
||||
needsConsent(settings.legalConsentVersion)
|
||||
) {
|
||||
settings.acceptLegalConsent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After a deploy, a tab opened on the previous build asks for chunk files that
|
||||
* no longer exist. Reload once to pick up the new build instead of rendering
|
||||
* an error page; the session flag stops a reload loop if the failure is real.
|
||||
*/
|
||||
function reloadOnStaleChunks(): void {
|
||||
window.addEventListener("vite:preloadError", (event) => {
|
||||
try {
|
||||
if (sessionStorage.getItem("ytdescgen-chunk-reload")) return;
|
||||
sessionStorage.setItem("ytdescgen-chunk-reload", "1");
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
migrateHashUrl();
|
||||
acceptConsentFromGate();
|
||||
reloadOnStaleChunks();
|
||||
|
||||
// Screen readers and the browser's own translation/spell-check key off
|
||||
// <html lang>, which index.html fixes at "en".
|
||||
i18n.on("languageChanged", (lng) => {
|
||||
document.documentElement.lang = lng;
|
||||
});
|
||||
|
||||
/**
|
||||
* Lazy-loaded locales (v0.26): fetch the persisted UI + output languages
|
||||
* before first paint so a non-English user never sees an English flash
|
||||
@@ -48,6 +107,7 @@ function applyPersistedTheme(): void {
|
||||
const { theme } = useSettingsStore.getState();
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
document.documentElement.classList.toggle("light", theme === "light");
|
||||
document.documentElement.style.colorScheme = theme;
|
||||
}
|
||||
|
||||
// Top-level safety net. Per-route boundaries in App.tsx catch most
|
||||
|
||||
+10
-11
@@ -1,4 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
ExternalLink,
|
||||
Github,
|
||||
@@ -15,12 +16,13 @@ import {
|
||||
Heart,
|
||||
Sparkles,
|
||||
DollarSign,
|
||||
FileText,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { ABOUT, type AboutSocialId } from "@config/about";
|
||||
import { DONATE, type DonateId } from "@config/donate";
|
||||
import { THIRD_PARTY } from "@config/third-party";
|
||||
import { LEGAL_DOCS } from "@config/legal";
|
||||
import { LEGAL_DOCS, legalDocPath } from "@config/legal";
|
||||
import { useDocumentTitle } from "@hooks/use-document-title";
|
||||
|
||||
interface SocialLinkConfig {
|
||||
@@ -126,11 +128,6 @@ export function AboutPage() {
|
||||
label={t("about.discussionsLabel")}
|
||||
/>
|
||||
<ExternalLinkRow href={ABOUT.githubAuthor} icon={Github} label={t("about.authorLabel")} />
|
||||
<ExternalLinkRow
|
||||
href={ABOUT.licenseUrl}
|
||||
icon={ExternalLink}
|
||||
label={`${t("about.licenseLabel")} · ${ABOUT.license}`}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -140,12 +137,14 @@ export function AboutPage() {
|
||||
</h2>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{LEGAL_DOCS.map((doc) => (
|
||||
<ExternalLinkRow
|
||||
<Link
|
||||
key={doc.id}
|
||||
href={doc.url}
|
||||
icon={ExternalLink}
|
||||
label={t(doc.labelKey)}
|
||||
/>
|
||||
to={legalDocPath(doc.id)}
|
||||
className="border-border bg-surface-1 text-text-primary hover:border-accent hover:bg-surface-2 flex items-center gap-3 rounded-lg border px-3 py-2.5 text-sm transition-colors"
|
||||
>
|
||||
<FileText className="text-text-muted h-4 w-4 shrink-0" aria-hidden />
|
||||
<span className="flex-1 truncate">{t(doc.labelKey)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { useState, type MouseEvent } from "react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ArrowLeft, ChevronRight, FileText } from "lucide-react";
|
||||
import clsx from "clsx";
|
||||
import { LEGAL_CONTENT } from "virtual:legal-docs";
|
||||
import { LEGAL_DOCS, isLegalDocId, legalDocPath, type LegalDoc } from "@config/legal";
|
||||
import { useDocumentTitle } from "@hooks/use-document-title";
|
||||
|
||||
/** `legal.docs.thirdParty` → `legal.summaries.thirdParty`. */
|
||||
function summaryKey(doc: LegalDoc): string {
|
||||
return doc.labelKey.replace("legal.docs.", "legal.summaries.");
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-app Legal Center (v1.0.0). Lives outside the consent guard so the
|
||||
* first-run consent screen can open each document in place — which also keeps
|
||||
* the desktop and Android builds from ever navigating their webview to a web
|
||||
* page. Content comes from `virtual:legal-docs`, rendered at build time from
|
||||
* the Markdown files at the repo root, so it matches ytgenerator.stream/legal
|
||||
* word for word and works offline.
|
||||
*/
|
||||
export function LegalPage() {
|
||||
const { t } = useTranslation("ui");
|
||||
const navigate = useNavigate();
|
||||
const { docId } = useParams();
|
||||
const [lang, setLang] = useState<"en" | "vi">("en");
|
||||
|
||||
const doc = docId && isLegalDocId(docId) ? LEGAL_DOCS.find((d) => d.id === docId) : undefined;
|
||||
const content = doc ? LEGAL_CONTENT[doc.id] : undefined;
|
||||
const html = content
|
||||
? ((lang === "vi" ? content.html.vi : undefined) ?? content.html.en ?? "")
|
||||
: "";
|
||||
// Plain-text sources (LICENSE, NOTICE) render as a <pre> with no heading.
|
||||
const needsHeading = !/^\s*<h1[\s>]/.test(html);
|
||||
useDocumentTitle(doc ? t(doc.labelKey) : t("legal.title"));
|
||||
|
||||
const goBack = (): void => {
|
||||
// A deep link opened in a fresh tab has nothing to go back to.
|
||||
if (window.history.length > 1) navigate(-1);
|
||||
else navigate(doc ? "/legal" : "/");
|
||||
};
|
||||
|
||||
// Links inside the rendered Markdown are plain <a> tags. Route in-site ones
|
||||
// through the router (a real navigation would reload the web app and, in
|
||||
// Tauri, leave the app entirely) and turn #anchors into scrolls so the hash
|
||||
// router never mistakes them for routes.
|
||||
const onArticleClick = (event: MouseEvent<HTMLElement>): void => {
|
||||
const anchor = (event.target as HTMLElement).closest("a");
|
||||
const href = anchor?.getAttribute("href");
|
||||
if (!href) return;
|
||||
if (href.startsWith("#")) {
|
||||
event.preventDefault();
|
||||
document.getElementById(decodeURIComponent(href.slice(1)))?.scrollIntoView();
|
||||
return;
|
||||
}
|
||||
if (href === "/legal" || href.startsWith("/legal/")) {
|
||||
event.preventDefault();
|
||||
navigate(href.split(/[?#]/)[0] ?? "/legal");
|
||||
}
|
||||
};
|
||||
|
||||
const docNav = (
|
||||
<nav aria-label={t("legal.allDocuments")} className="flex flex-col gap-1">
|
||||
{LEGAL_DOCS.map((d) => (
|
||||
<Link
|
||||
key={d.id}
|
||||
to={legalDocPath(d.id)}
|
||||
aria-current={d.id === doc?.id ? "page" : undefined}
|
||||
className={clsx(
|
||||
"rounded-lg px-3 py-2 text-sm transition-colors",
|
||||
d.id === doc?.id
|
||||
? "bg-surface-2 text-text-primary font-medium"
|
||||
: "text-text-secondary hover:bg-surface-1 hover:text-text-primary",
|
||||
)}
|
||||
>
|
||||
{t(d.labelKey)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="bg-surface-0 min-h-screen">
|
||||
<header className="border-border bg-surface-0/90 sticky top-0 z-10 flex items-center gap-3 border-b px-4 py-3 backdrop-blur">
|
||||
<button
|
||||
type="button"
|
||||
onClick={goBack}
|
||||
className="text-text-secondary hover:bg-surface-2 hover:text-text-primary flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" aria-hidden />
|
||||
{t("legal.back")}
|
||||
</button>
|
||||
<Link to="/legal" className="text-text-primary text-sm font-semibold">
|
||||
{t("legal.title")}
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<div className="mx-auto grid max-w-5xl gap-8 px-4 py-8 md:grid-cols-[200px_minmax(0,1fr)]">
|
||||
<aside className="hidden md:block">
|
||||
<div className="sticky top-20">{docNav}</div>
|
||||
</aside>
|
||||
|
||||
<main className="min-w-0">
|
||||
{!docId && (
|
||||
<section>
|
||||
<h1 className="text-text-primary text-2xl font-semibold">{t("legal.title")}</h1>
|
||||
<p className="text-text-secondary mt-2 text-sm">{t("legal.intro")}</p>
|
||||
<p className="text-text-muted mt-1 text-xs">{t("legal.englishOnly")}</p>
|
||||
<ul className="mt-6 grid gap-3 sm:grid-cols-2">
|
||||
{LEGAL_DOCS.map((d) => (
|
||||
<li key={d.id}>
|
||||
<Link
|
||||
to={legalDocPath(d.id)}
|
||||
className="border-border bg-surface-1 hover:border-accent group flex items-start gap-3 rounded-xl border p-4 transition-colors"
|
||||
>
|
||||
<FileText className="text-accent mt-0.5 h-4 w-4 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="text-text-primary block text-sm font-medium">
|
||||
{t(d.labelKey)}
|
||||
</span>
|
||||
<span className="text-text-muted mt-1 block text-xs leading-relaxed">
|
||||
{t(summaryKey(d))}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight
|
||||
className="text-text-muted group-hover:text-accent mt-0.5 h-4 w-4 shrink-0"
|
||||
aria-hidden
|
||||
/>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{docId && !content && (
|
||||
<section className="py-12 text-center">
|
||||
<p className="text-text-secondary">{t("legal.notFound")}</p>
|
||||
<Link to="/legal" className="text-accent mt-3 inline-block text-sm">
|
||||
{t("legal.allDocuments")}
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{doc && content && (
|
||||
<>
|
||||
<div className="mb-4 md:hidden">{docNav}</div>
|
||||
{needsHeading && (
|
||||
<h1 className="text-text-primary mb-2 text-2xl font-semibold">{t(doc.labelKey)}</h1>
|
||||
)}
|
||||
<div className="mb-4 flex flex-wrap items-center gap-3">
|
||||
{content.html.vi && (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t("legal.language")}
|
||||
className="border-border ml-auto flex rounded-lg border p-0.5"
|
||||
>
|
||||
{(["en", "vi"] as const).map((code) => (
|
||||
<button
|
||||
key={code}
|
||||
type="button"
|
||||
aria-pressed={lang === code}
|
||||
onClick={() => setLang(code)}
|
||||
className={clsx(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium",
|
||||
lang === code
|
||||
? "bg-accent text-white"
|
||||
: "text-text-secondary hover:text-text-primary",
|
||||
)}
|
||||
>
|
||||
{code === "en" ? "English" : "Tiếng Việt"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<article
|
||||
lang={lang}
|
||||
onClick={onArticleClick}
|
||||
className="legal-prose border-border bg-surface-1 rounded-2xl border px-5 py-6 sm:px-8"
|
||||
// Build-time HTML rendered from the repo's own Markdown files
|
||||
// (build-plugins/legal-docs.ts) — never user input.
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -113,3 +113,109 @@ body {
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-border-strong;
|
||||
}
|
||||
|
||||
/*
|
||||
* Legal Center documents (src/pages/LegalPage.tsx). The HTML is rendered at
|
||||
* build time from the repo's Markdown, so it arrives as bare elements that
|
||||
* utility classes cannot reach — style them by descendant here instead.
|
||||
*/
|
||||
.legal-prose {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.7;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.legal-prose h1 {
|
||||
color: var(--text-primary);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
.legal-prose h2 {
|
||||
color: var(--text-primary);
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
margin: 2rem 0 0.625rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.legal-prose h3 {
|
||||
color: var(--text-primary);
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 1.5rem 0 0.5rem;
|
||||
}
|
||||
.legal-prose p,
|
||||
.legal-prose ul,
|
||||
.legal-prose ol,
|
||||
.legal-prose table,
|
||||
.legal-prose pre,
|
||||
.legal-prose blockquote {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
.legal-prose ul,
|
||||
.legal-prose ol {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
.legal-prose ul {
|
||||
list-style: disc;
|
||||
}
|
||||
.legal-prose ol {
|
||||
list-style: decimal;
|
||||
}
|
||||
.legal-prose li + li {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.legal-prose a {
|
||||
color: var(--accent);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.legal-prose strong {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.legal-prose code {
|
||||
font-family: var(--font-mono-stack);
|
||||
font-size: 0.85em;
|
||||
background: var(--surface-2);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.1em 0.35em;
|
||||
}
|
||||
.legal-prose pre {
|
||||
background: var(--surface-2);
|
||||
border-radius: 0.75rem;
|
||||
padding: 1rem;
|
||||
overflow-x: auto;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.legal-prose pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
.legal-prose pre.plain {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.legal-prose table {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.legal-prose th,
|
||||
.legal-prose td {
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.legal-prose th {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
.legal-prose blockquote {
|
||||
border-left: 3px solid var(--accent);
|
||||
padding-left: 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
Vendored
+16
@@ -22,3 +22,19 @@ interface SaveFilePickerOptions {
|
||||
interface Window {
|
||||
showSaveFilePicker?: (options?: SaveFilePickerOptions) => Promise<FileSystemFileHandle>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build-time rendered legal documents (build-plugins/legal-docs.ts). Imported
|
||||
* lazily by the Legal Center so the HTML never lands in the main chunk.
|
||||
*/
|
||||
declare module "virtual:legal-docs" {
|
||||
import type { LegalDocId } from "@config/legal";
|
||||
|
||||
export interface RenderedLegalDoc {
|
||||
title: string;
|
||||
effective: string | null;
|
||||
html: { en?: string; vi?: string };
|
||||
}
|
||||
|
||||
export const LEGAL_CONTENT: Record<LegalDocId, RenderedLegalDoc>;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
extractEffectiveDate,
|
||||
renderAllLegalDocs,
|
||||
renderMarkdown,
|
||||
rewriteHref,
|
||||
} from "../../build-plugins/legal-docs";
|
||||
import { LEGAL_DOC_IDS } from "@config/legal";
|
||||
|
||||
describe("rewriteHref", () => {
|
||||
it.each([
|
||||
["LICENSE", "TERMS.md", "/legal/license"],
|
||||
["./DISCLAIMER.md", "TERMS.md", "/legal/disclaimer"],
|
||||
["PRIVACY.md#cookies", "TERMS.md", "/legal/privacy#cookies"],
|
||||
["../../../PRIVACY.md", "docs/i18n/vi/DISCLAIMER.md", "/legal/privacy"],
|
||||
[
|
||||
"CONTRIBUTING.md",
|
||||
"TERMS.md",
|
||||
"https://github.com/poli0981/youtube-generator/blob/main/CONTRIBUTING.md",
|
||||
],
|
||||
[
|
||||
"./docs/I18N.md#adding",
|
||||
"README.md",
|
||||
"https://github.com/poli0981/youtube-generator/blob/main/docs/I18N.md#adding",
|
||||
],
|
||||
["https://example.com/x", "TERMS.md", "https://example.com/x"],
|
||||
["mailto:legal@poli0981.dev", "TERMS.md", "mailto:legal@poli0981.dev"],
|
||||
["#section", "TERMS.md", "#section"],
|
||||
])("%s (from %s) → %s", (href, from, expected) => {
|
||||
expect(rewriteHref(href, from)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderMarkdown", () => {
|
||||
it("reads the title and gives headings anchor ids", () => {
|
||||
const { title, html } = renderMarkdown(
|
||||
"# Privacy Policy\n\n## 3. Cookies\n\nText.",
|
||||
"PRIVACY.md",
|
||||
);
|
||||
expect(title).toBe("Privacy Policy");
|
||||
expect(html).toContain('<h2 id="3-cookies">3. Cookies</h2>');
|
||||
});
|
||||
|
||||
it("opens external links in a new tab and keeps in-site links in place", () => {
|
||||
const { html } = renderMarkdown(
|
||||
"[site](https://example.com) and [privacy](PRIVACY.md)",
|
||||
"TERMS.md",
|
||||
);
|
||||
expect(html).toContain(
|
||||
'<a href="https://example.com" target="_blank" rel="noopener noreferrer">site</a>',
|
||||
);
|
||||
expect(html).toContain('<a href="/legal/privacy">privacy</a>');
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractEffectiveDate", () => {
|
||||
it("finds the effective date line", () => {
|
||||
expect(extractEffectiveDate("# X\n\n**Effective:** 2026-09-30\n")).toBe("2026-09-30");
|
||||
expect(extractEffectiveDate("# X\n\nno date")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderAllLegalDocs (the real repository files)", () => {
|
||||
const docs = renderAllLegalDocs();
|
||||
|
||||
it("renders every document with a title and HTML", () => {
|
||||
for (const id of LEGAL_DOC_IDS) {
|
||||
expect(docs[id].title, id).not.toBe("");
|
||||
expect(docs[id].html.en?.length ?? 0, id).toBeGreaterThan(100);
|
||||
}
|
||||
});
|
||||
|
||||
it("carries the Vietnamese Disclaimer", () => {
|
||||
expect(docs.disclaimer.html.vi).toBeTruthy();
|
||||
});
|
||||
|
||||
it("dates the Terms and the Privacy Policy", () => {
|
||||
expect(docs.terms.effective).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
||||
expect(docs.privacy.effective).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
||||
});
|
||||
|
||||
it("no longer sends readers to GitHub for another legal document", () => {
|
||||
for (const id of LEGAL_DOC_IDS) {
|
||||
const html = docs[id].html.en ?? "";
|
||||
expect(html, id).not.toMatch(
|
||||
/github\.com\/[^"]+\/blob\/main\/(TERMS|PRIVACY|DISCLAIMER|SECURITY|LICENSE)/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the current contact addresses, not the retired one", () => {
|
||||
const all = LEGAL_DOC_IDS.map((id) => docs[id].html.en ?? "").join("\n");
|
||||
expect(all).not.toContain("lopop05905@proton.me");
|
||||
expect(docs.privacy.html.en).toContain("privacy@poli0981.dev");
|
||||
expect(docs.security.html.en).toContain("security@poli0981.dev");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
CF_WEB_ANALYTICS_SNIPPET,
|
||||
SECURITY_TXT_LIFETIME_DAYS,
|
||||
cloudflareWebAnalytics,
|
||||
renderSecurityTxt,
|
||||
} from "../../build-plugins/web-only";
|
||||
|
||||
describe("security.txt", () => {
|
||||
const now = new Date("2026-09-30T00:00:00Z");
|
||||
const txt = renderSecurityTxt(now);
|
||||
const field = (name: string) =>
|
||||
txt
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(`${name}: `))
|
||||
.map((line) => line.slice(name.length + 2));
|
||||
|
||||
it("names the security mailbox and GitHub advisories as contacts", () => {
|
||||
expect(field("Contact")).toEqual([
|
||||
"mailto:security@poli0981.dev",
|
||||
"https://github.com/poli0981/youtube-generator/security/advisories/new",
|
||||
]);
|
||||
});
|
||||
|
||||
it("expires under a year after the build, as RFC 9116 recommends", () => {
|
||||
const [expires] = field("Expires");
|
||||
const days = (Date.parse(expires!) - now.getTime()) / 86_400_000;
|
||||
expect(days).toBe(SECURITY_TXT_LIFETIME_DAYS);
|
||||
expect(days).toBeLessThan(365);
|
||||
expect(expires).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
|
||||
});
|
||||
|
||||
it("points Canonical and Policy at the live site", () => {
|
||||
expect(field("Canonical")).toEqual(["https://ytgenerator.stream/.well-known/security.txt"]);
|
||||
expect(field("Policy")).toEqual(["https://ytgenerator.stream/legal/security"]);
|
||||
expect(field("Preferred-Languages")).toEqual(["en, vi"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cloudflare Web Analytics", () => {
|
||||
it("embeds the site's beacon token", () => {
|
||||
expect(CF_WEB_ANALYTICS_SNIPPET).toContain('"token": "84187c3714aa49e1ad8ef93ad6d422e7"');
|
||||
expect(CF_WEB_ANALYTICS_SNIPPET).toContain(
|
||||
"src='https://static.cloudflareinsights.com/beacon.min.js'",
|
||||
);
|
||||
});
|
||||
|
||||
it("injects the snippet right before </body>", () => {
|
||||
const plugin = cloudflareWebAnalytics();
|
||||
const transform = plugin.transformIndexHtml as {
|
||||
handler: (html: string) => string;
|
||||
};
|
||||
const out = transform.handler("<html><body><div id=root></div></body></html>");
|
||||
expect(out).toBe(
|
||||
`<html><body><div id=root></div>${CF_WEB_ANALYTICS_SNIPPET}\n </body></html>`,
|
||||
);
|
||||
});
|
||||
});
|
||||
+64
-11
@@ -1,9 +1,19 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { needsConsent, CURRENT_TERMS_VERSION, LEGAL_DOCS } from "@config/legal";
|
||||
import {
|
||||
CURRENT_TERMS_VERSION,
|
||||
LEGAL_DOCS,
|
||||
LEGAL_DOC_IDS,
|
||||
TERMS_COOKIE,
|
||||
isLegalDocId,
|
||||
legalDocPath,
|
||||
needsConsent,
|
||||
termsVersionFromCookie,
|
||||
} from "@config/legal";
|
||||
|
||||
/**
|
||||
* Guards for the pure legal config driving the v0.28.0 consent gate. The gate
|
||||
* is a boot-time blocker, so the version logic must be exactly right: anything
|
||||
* Guards for the pure legal config driving the consent gate, the in-app Legal
|
||||
* Center, the static /legal pages and the Cloudflare Worker. The gate is a
|
||||
* boot-time blocker, so the version logic must be exactly right: anything
|
||||
* below the current version (or a non-number) re-shows the gate; the current
|
||||
* version (or higher) lets the app through.
|
||||
*/
|
||||
@@ -28,19 +38,62 @@ describe("needsConsent", () => {
|
||||
expect(needsConsent(undefined as unknown as number)).toBe(true);
|
||||
expect(needsConsent(NaN)).toBe(true);
|
||||
});
|
||||
|
||||
it("re-asks users who accepted v1 — the v1.0.0 Privacy Policy changed materially", () => {
|
||||
expect(CURRENT_TERMS_VERSION).toBeGreaterThanOrEqual(2);
|
||||
expect(needsConsent(1)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("LEGAL_DOCS", () => {
|
||||
it("covers all four documents with absolute https GitHub URLs + consentGate label keys", () => {
|
||||
expect(LEGAL_DOCS.map((d) => d.id)).toEqual(["terms", "privacy", "disclaimer", "license"]);
|
||||
for (const doc of LEGAL_DOCS) {
|
||||
expect(doc.url).toMatch(/^https:\/\/github\.com\/poli0981\/youtube-generator\/blob\/main\//);
|
||||
expect(doc.labelKey).toMatch(/^consentGate\.doc/);
|
||||
it("lists the consent documents first, in agreement order", () => {
|
||||
expect(LEGAL_DOCS.filter((d) => d.consent).map((d) => d.id)).toEqual([
|
||||
"terms",
|
||||
"privacy",
|
||||
"disclaimer",
|
||||
"license",
|
||||
]);
|
||||
});
|
||||
|
||||
it("has unique ids, label keys and sources", () => {
|
||||
for (const key of ["id", "labelKey", "source"] as const) {
|
||||
expect(new Set(LEGAL_DOCS.map((d) => d[key])).size).toBe(LEGAL_DOCS.length);
|
||||
}
|
||||
});
|
||||
|
||||
it("has a unique id and url per doc", () => {
|
||||
expect(new Set(LEGAL_DOCS.map((d) => d.id)).size).toBe(LEGAL_DOCS.length);
|
||||
expect(new Set(LEGAL_DOCS.map((d) => d.url)).size).toBe(LEGAL_DOCS.length);
|
||||
it("keys every label under legal.docs and points every source at a repo file", () => {
|
||||
for (const doc of LEGAL_DOCS) {
|
||||
expect(doc.labelKey).toMatch(/^legal\.docs\.[a-zA-Z]+$/);
|
||||
expect(doc.source).toMatch(/^[A-Z_]+(\.md)?$/);
|
||||
}
|
||||
});
|
||||
|
||||
it("serves every document under /legal/<id>", () => {
|
||||
for (const id of LEGAL_DOC_IDS) {
|
||||
expect(legalDocPath(id)).toBe(`/legal/${id}`);
|
||||
expect(isLegalDocId(id)).toBe(true);
|
||||
}
|
||||
expect(isLegalDocId("nope")).toBe(false);
|
||||
expect(isLegalDocId("")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("termsVersionFromCookie", () => {
|
||||
it("reads the version the gate page recorded", () => {
|
||||
expect(termsVersionFromCookie(`a=1; ${TERMS_COOKIE}=2; b=3`)).toBe(2);
|
||||
expect(termsVersionFromCookie(`${TERMS_COOKIE}=12`)).toBe(12);
|
||||
});
|
||||
|
||||
it("returns null when absent, empty or malformed", () => {
|
||||
expect(termsVersionFromCookie(undefined)).toBeNull();
|
||||
expect(termsVersionFromCookie("")).toBeNull();
|
||||
expect(termsVersionFromCookie("other=2")).toBeNull();
|
||||
expect(termsVersionFromCookie(`${TERMS_COOKIE}=abc`)).toBeNull();
|
||||
expect(termsVersionFromCookie(`${TERMS_COOKIE}=-1`)).toBeNull();
|
||||
expect(termsVersionFromCookie(`${TERMS_COOKIE}=99999`)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not match a cookie whose name merely ends with the same text", () => {
|
||||
expect(termsVersionFromCookie(`x${TERMS_COOKIE}=2`)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
deriveGateKey,
|
||||
readCookie,
|
||||
signGateToken,
|
||||
userAgentHash,
|
||||
verifyGateToken,
|
||||
} from "../../worker/cookie";
|
||||
|
||||
const NOW = 1_790_000_000;
|
||||
|
||||
describe("gate cookie", () => {
|
||||
it("round-trips a freshly signed token", async () => {
|
||||
const key = await deriveGateKey("secret-a");
|
||||
const ua = await userAgentHash("Mozilla/5.0 test");
|
||||
const token = await signGateToken(key, NOW + 3600, ua);
|
||||
expect(token).toMatch(/^v1\.\d+\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+$/);
|
||||
await expect(verifyGateToken(key, token, NOW, ua)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an expired token", async () => {
|
||||
const key = await deriveGateKey("secret-a");
|
||||
const ua = await userAgentHash("ua");
|
||||
const token = await signGateToken(key, NOW - 1, ua);
|
||||
await expect(verifyGateToken(key, token, NOW, ua)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a token presented by a different User-Agent", async () => {
|
||||
const key = await deriveGateKey("secret-a");
|
||||
const token = await signGateToken(key, NOW + 3600, await userAgentHash("browser A"));
|
||||
await expect(verifyGateToken(key, token, NOW, await userAgentHash("scraper B"))).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a token signed with another secret", async () => {
|
||||
const ua = await userAgentHash("ua");
|
||||
const token = await signGateToken(await deriveGateKey("old-secret"), NOW + 3600, ua);
|
||||
await expect(verifyGateToken(await deriveGateKey("new-secret"), token, NOW, ua)).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects any tampering with the payload or signature", async () => {
|
||||
const key = await deriveGateKey("secret-a");
|
||||
const ua = await userAgentHash("ua");
|
||||
const token = await signGateToken(key, NOW + 60, ua);
|
||||
const [v, exp, hash, sig] = token.split(".") as [string, string, string, string];
|
||||
const extended = [v, String(Number(exp) + 999_999), hash, sig].join(".");
|
||||
const flipped = [v, exp, hash, sig.slice(0, -1) + (sig.endsWith("A") ? "B" : "A")].join(".");
|
||||
for (const bad of [extended, flipped, `v2.${exp}.${hash}.${sig}`, "", "v1", "a.b.c.d"]) {
|
||||
await expect(verifyGateToken(key, bad, NOW, ua)).resolves.toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("derives a stable key per secret", async () => {
|
||||
const ua = await userAgentHash("ua");
|
||||
const token = await signGateToken(await deriveGateKey("s"), NOW + 10, ua);
|
||||
await expect(verifyGateToken(await deriveGateKey("s"), token, NOW, ua)).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readCookie", () => {
|
||||
it("finds a cookie among others and trims whitespace", () => {
|
||||
expect(readCookie("a=1; __Host-ytg_gate=v1.x.y.z ; b=2", "__Host-ytg_gate")).toBe("v1.x.y.z");
|
||||
});
|
||||
|
||||
it("returns null for a missing header or name", () => {
|
||||
expect(readCookie(null, "a")).toBeNull();
|
||||
expect(readCookie("b=1", "a")).toBeNull();
|
||||
expect(readCookie("xa=1", "a")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { GATE_STRINGS, pickGateLang, type GateLang } from "../../worker/gate-i18n";
|
||||
import { renderGatePage, escapeHtml } from "../../worker/gate-page";
|
||||
|
||||
describe("pickGateLang", () => {
|
||||
it.each([
|
||||
[null, "en"],
|
||||
["", "en"],
|
||||
["vi-VN,vi;q=0.9,en;q=0.8", "vi"],
|
||||
["ja", "ja"],
|
||||
["es-MX", "es"],
|
||||
["ko-KR", "ko"],
|
||||
["zh-TW,zh;q=0.8", "zh"],
|
||||
["pt-PT", "pt-BR"],
|
||||
["in", "id"],
|
||||
["id-ID", "id"],
|
||||
["fr-FR,fr;q=0.9", "en"],
|
||||
["fr;q=1, vi;q=0.5", "vi"],
|
||||
["en;q=0.2, ja;q=0.9", "ja"],
|
||||
["vi;q=0, en", "en"],
|
||||
] as const)("%s → %s", (header, lang) => {
|
||||
expect(pickGateLang(header)).toBe(lang);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gate strings", () => {
|
||||
const langs = Object.keys(GATE_STRINGS) as GateLang[];
|
||||
|
||||
it("covers the app's eight languages", () => {
|
||||
expect(langs.sort()).toEqual(["en", "es", "id", "ja", "ko", "pt-BR", "vi", "zh"]);
|
||||
});
|
||||
|
||||
it("fills every field and keeps every placeholder in every language", () => {
|
||||
for (const lang of langs) {
|
||||
const t = GATE_STRINGS[lang];
|
||||
for (const [key, value] of Object.entries(t)) {
|
||||
expect(value.trim(), `${lang}.${key}`).not.toBe("");
|
||||
}
|
||||
expect(t.agree, lang).toContain("{terms}");
|
||||
expect(t.agree, lang).toContain("{privacy}");
|
||||
expect(t.returning, lang).toContain("{terms}");
|
||||
expect(t.returning, lang).toContain("{privacy}");
|
||||
expect(t.dataNote, lang).toContain("{hours}");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderGatePage", () => {
|
||||
const base = {
|
||||
lang: "en" as const,
|
||||
nonce: "n0nce",
|
||||
siteKey: "0xSITE",
|
||||
returning: false,
|
||||
origin: "https://ytgenerator.stream",
|
||||
hours: 24,
|
||||
};
|
||||
|
||||
it("links the Terms and Privacy Policy in the agreement line", () => {
|
||||
const html = renderGatePage(base);
|
||||
expect(html).toContain(
|
||||
'<a href="/legal/terms" target="_blank" rel="noopener">Terms of Use</a>',
|
||||
);
|
||||
expect(html).toContain('href="/legal/privacy"');
|
||||
expect(html).toContain('id="agree"');
|
||||
expect(html).toContain("for 24 hours");
|
||||
});
|
||||
|
||||
it("puts the configuration in a JSON block that cannot close its <script>", () => {
|
||||
const html = renderGatePage({ ...base, siteKey: "</script><script>alert(1)</script>" });
|
||||
const block = /<script id="ytg-gate" type="application\/json">([^<]*)<\/script>/.exec(html);
|
||||
expect(block).not.toBeNull();
|
||||
expect(JSON.parse(block![1]!).siteKey).toBe("</script><script>alert(1)</script>");
|
||||
});
|
||||
|
||||
it("nonces its only executable script", () => {
|
||||
const html = renderGatePage(base);
|
||||
const scripts = html.match(/<script(?![^>]*type="application\/json")[^>]*>/g) ?? [];
|
||||
expect(scripts).toEqual(['<script nonce="n0nce">']);
|
||||
});
|
||||
|
||||
it("escapes HTML-significant characters", () => {
|
||||
expect(escapeHtml(`<a href="x">&'`)).toBe("<a href="x">&'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { APP_CSP, BASELINE_HEADERS, LEGAL_CSP, gateCsp } from "../../worker/headers";
|
||||
|
||||
/** Parse the `/*` block of public/_headers into name → value. */
|
||||
function staticHeadersForAllPaths(): Record<string, string> {
|
||||
const text = readFileSync(resolve(import.meta.dirname, "../../public/_headers"), "utf8");
|
||||
const out: Record<string, string> = {};
|
||||
let inBlock = false;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
if (line.startsWith("#") || line.trim() === "") continue;
|
||||
if (!line.startsWith(" ")) {
|
||||
inBlock = line.trim() === "/*";
|
||||
continue;
|
||||
}
|
||||
if (!inBlock) continue;
|
||||
const colon = line.indexOf(":");
|
||||
out[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("security headers", () => {
|
||||
const staticHeaders = staticHeadersForAllPaths();
|
||||
|
||||
it("gives Worker responses the same baseline as static files", () => {
|
||||
for (const [name, value] of Object.entries(BASELINE_HEADERS)) {
|
||||
if (name === "Cross-Origin-Resource-Policy") continue; // set per path in _headers
|
||||
expect(staticHeaders[name], name).toBe(value);
|
||||
}
|
||||
});
|
||||
|
||||
it("serves the app shell under the same CSP either way", () => {
|
||||
expect(staticHeaders["Content-Security-Policy"]).toBe(APP_CSP);
|
||||
});
|
||||
|
||||
it("never sets HSTS — the zone edge owns it", () => {
|
||||
expect(Object.keys(staticHeaders).map((h) => h.toLowerCase())).not.toContain(
|
||||
"strict-transport-security",
|
||||
);
|
||||
expect(Object.keys(BASELINE_HEADERS).map((h) => h.toLowerCase())).not.toContain(
|
||||
"strict-transport-security",
|
||||
);
|
||||
});
|
||||
|
||||
it("lets only the analytics beacon in beside our own scripts", () => {
|
||||
expect(APP_CSP).toContain("script-src 'self' https://static.cloudflareinsights.com;");
|
||||
expect(APP_CSP).toContain("connect-src 'self' https://cloudflareinsights.com;");
|
||||
expect(APP_CSP).not.toContain("'unsafe-eval'");
|
||||
expect(APP_CSP).toMatch(/script-src [^;]*$|script-src [^;]*;/);
|
||||
expect(APP_CSP.match(/script-src ([^;]*)/)?.[1]).not.toContain("'unsafe-inline'");
|
||||
});
|
||||
|
||||
it("allows Turnstile only on the gate page, with a per-request nonce", () => {
|
||||
const csp = gateCsp("abc123");
|
||||
expect(csp).toContain(
|
||||
"script-src 'nonce-abc123' 'strict-dynamic' https://challenges.cloudflare.com",
|
||||
);
|
||||
expect(csp).toContain("frame-src https://challenges.cloudflare.com");
|
||||
expect(APP_CSP).not.toContain("challenges.cloudflare.com");
|
||||
});
|
||||
|
||||
it("allows no script at all on the prerendered legal pages", () => {
|
||||
expect(LEGAL_CSP).toContain("default-src 'none'");
|
||||
expect(LEGAL_CSP).not.toContain("script-src");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,316 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { CURRENT_TERMS_VERSION, TERMS_COOKIE } from "@config/legal";
|
||||
import { deriveGateKey, signGateToken, userAgentHash } from "../../worker/cookie";
|
||||
import { GATE_COOKIE, type Deps, type Env } from "../../worker/env";
|
||||
import { APP_CSP, LEGAL_CSP } from "../../worker/headers";
|
||||
import { handleRequest, legalAssetPath } from "../../worker/router";
|
||||
|
||||
const ORIGIN = "https://ytgenerator.stream";
|
||||
const UA = "Mozilla/5.0 (Windows NT 10.0) Test";
|
||||
const NOW = Date.parse("2026-09-30T12:00:00Z");
|
||||
const SECRET = "test-secret";
|
||||
|
||||
/** An ASSETS binding that records what it was asked for. */
|
||||
function fakeAssets() {
|
||||
const calls: { url: string; method: string }[] = [];
|
||||
const binding = {
|
||||
calls,
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
calls.push({ url: url.pathname + url.search, method: request.method });
|
||||
if (url.pathname === "/legal/not-found") return new Response("404 page", { status: 404 });
|
||||
return new Response(`asset:${url.pathname}`, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": url.pathname.endsWith(".js") ? "text/javascript" : "text/html" },
|
||||
});
|
||||
},
|
||||
};
|
||||
return binding;
|
||||
}
|
||||
|
||||
function makeEnv(overrides: Partial<Env> = {}) {
|
||||
const assets = fakeAssets();
|
||||
const env: Env = {
|
||||
ASSETS: assets,
|
||||
TURNSTILE_SITE_KEY: "site-key",
|
||||
TURNSTILE_SECRET: SECRET,
|
||||
GATE_TTL_SECONDS: "86400",
|
||||
...overrides,
|
||||
};
|
||||
return { env, assets };
|
||||
}
|
||||
|
||||
function makeDeps(siteverifyBody: unknown = {}): Deps & { fetch: ReturnType<typeof vi.fn> } {
|
||||
return {
|
||||
now: () => NOW,
|
||||
fetch: vi.fn(async () => Response.json(siteverifyBody)),
|
||||
randomId: () => "nonce-1234",
|
||||
};
|
||||
}
|
||||
|
||||
async function gateCookie(ua = UA): Promise<string> {
|
||||
const key = await deriveGateKey(SECRET);
|
||||
const token = await signGateToken(key, Math.floor(NOW / 1000) + 3600, await userAgentHash(ua));
|
||||
return `${GATE_COOKIE}=${token}`;
|
||||
}
|
||||
|
||||
function req(path: string, init: RequestInit & { headers?: Record<string, string> } = {}) {
|
||||
return new Request(`${ORIGIN}${path}`, {
|
||||
...init,
|
||||
headers: { "User-Agent": UA, ...init.headers },
|
||||
});
|
||||
}
|
||||
|
||||
describe("worker routing — before the gate", () => {
|
||||
it("answers a page request with the gate page, not the app", async () => {
|
||||
const { env, assets } = makeEnv();
|
||||
const res = await handleRequest(req("/output"), env, makeDeps());
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Content-Type")).toContain("text/html");
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(res.headers.get("Vary")).toContain("Cookie");
|
||||
expect(res.headers.get("Content-Security-Policy")).toContain("'nonce-nonce1234'");
|
||||
const html = await res.text();
|
||||
expect(html).toContain('id="enter"');
|
||||
expect(html).toContain('<script nonce="nonce1234">');
|
||||
expect(assets.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("speaks the visitor's language", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/", { headers: { "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.5" } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
const html = await res.text();
|
||||
expect(html).toContain('<html lang="vi">');
|
||||
expect(html).toContain("Vào YTDescGen");
|
||||
});
|
||||
|
||||
it("skips the agree checkbox for a visitor who already accepted these terms", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/", { headers: { Cookie: `${TERMS_COOKIE}=${CURRENT_TERMS_VERSION}` } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(await res.text()).not.toContain('id="agree"');
|
||||
});
|
||||
|
||||
it("refuses sub-resources instead of sending the gate page", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/data.json", { headers: { "Sec-Fetch-Dest": "empty" } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("rejects methods other than GET and HEAD", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(req("/", { method: "PUT" }), env, makeDeps());
|
||||
expect(res.status).toBe(405);
|
||||
});
|
||||
|
||||
it("treats a gate cookie from another browser as absent", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/", { headers: { Cookie: await gateCookie("Some Other Browser") } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(await res.text()).toContain('id="enter"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("worker routing — legal pages are always public", () => {
|
||||
it.each([
|
||||
["/legal", "/legal/"],
|
||||
["/legal/", "/legal/"],
|
||||
["/legal/privacy", "/legal/privacy"],
|
||||
["/legal/privacy/", "/legal/privacy"],
|
||||
["/legal/disclaimer?lang=vi", "/legal/disclaimer.vi"],
|
||||
["/legal/terms?lang=vi", "/legal/terms"],
|
||||
["/legal/unknown", "/legal/not-found"],
|
||||
["/legal/Privacy", "/legal/not-found"],
|
||||
])("%s → %s", (path, asset) => {
|
||||
expect(legalAssetPath(new URL(`${ORIGIN}${path}`))).toBe(asset);
|
||||
});
|
||||
|
||||
it("is not a legal path at all for other routes", () => {
|
||||
expect(legalAssetPath(new URL(`${ORIGIN}/legality`))).toBeNull();
|
||||
expect(legalAssetPath(new URL(`${ORIGIN}/`))).toBeNull();
|
||||
});
|
||||
|
||||
it("serves the prerendered page with a script-free CSP, cookie or not", async () => {
|
||||
const { env, assets } = makeEnv();
|
||||
const res = await handleRequest(req("/legal/privacy"), env, makeDeps());
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.text()).toBe("asset:/legal/privacy");
|
||||
expect(res.headers.get("Content-Security-Policy")).toBe(LEGAL_CSP);
|
||||
expect(assets.calls).toEqual([{ url: "/legal/privacy", method: "GET" }]);
|
||||
});
|
||||
|
||||
it("passes through the 404 page for unknown documents", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(req("/legal/nope"), env, makeDeps());
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
});
|
||||
|
||||
describe("worker routing — after the gate", () => {
|
||||
it("serves the SPA shell for deep links without redirecting to /", async () => {
|
||||
const { env, assets } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/output", { headers: { Cookie: await gateCookie() } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.text()).toBe("asset:/");
|
||||
expect(assets.calls).toEqual([{ url: "/", method: "GET" }]);
|
||||
expect(res.headers.get("Content-Security-Policy")).toBe(APP_CSP);
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-cache");
|
||||
expect(res.headers.get("X-Frame-Options")).toBe("DENY");
|
||||
});
|
||||
|
||||
it("keeps HEAD requests as HEAD", async () => {
|
||||
const { env, assets } = makeEnv();
|
||||
await handleRequest(
|
||||
req("/settings", { method: "HEAD", headers: { Cookie: await gateCookie() } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(assets.calls).toEqual([{ url: "/", method: "HEAD" }]);
|
||||
});
|
||||
|
||||
it("passes files with an extension straight to the asset store", async () => {
|
||||
const { env, assets } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
req("/some/file.js", { headers: { Cookie: await gateCookie() } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(await res.text()).toBe("asset:/some/file.js");
|
||||
expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff");
|
||||
expect(assets.calls).toEqual([{ url: "/some/file.js", method: "GET" }]);
|
||||
});
|
||||
|
||||
it("reports cookie status for the gate page's blocked-cookie check", async () => {
|
||||
const { env } = makeEnv();
|
||||
const ok = await handleRequest(
|
||||
req("/__gate/status", { headers: { Cookie: await gateCookie() } }),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
const missing = await handleRequest(req("/__gate/status"), env, makeDeps());
|
||||
expect(ok.status).toBe(204);
|
||||
expect(missing.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("worker routing — /__gate/verify", () => {
|
||||
const goodSiteverify = {
|
||||
success: true,
|
||||
hostname: "ytgenerator.stream",
|
||||
action: "enter",
|
||||
challenge_ts: "2026-09-30T11:59:30Z",
|
||||
};
|
||||
|
||||
function verify(body: unknown, headers: Record<string, string> = {}) {
|
||||
return req("/__gate/verify", {
|
||||
method: "POST",
|
||||
headers: { Origin: ORIGIN, "Content-Type": "application/json", ...headers },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
it("sets the gate and terms cookies after a valid token", async () => {
|
||||
const { env } = makeEnv();
|
||||
const deps = makeDeps(goodSiteverify);
|
||||
const res = await handleRequest(
|
||||
verify({ token: "tok", consent: true }, { "CF-Connecting-IP": "203.0.113.5" }),
|
||||
env,
|
||||
deps,
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const cookies = res.headers.getSetCookie();
|
||||
expect(cookies).toHaveLength(2);
|
||||
expect(cookies[0]).toMatch(
|
||||
/^__Host-ytg_gate=v1\.\d+\.[\w-]+\.[\w-]+; Path=\/; Max-Age=86400; HttpOnly; Secure; SameSite=Lax$/,
|
||||
);
|
||||
expect(cookies[1]).toBe(
|
||||
`${TERMS_COOKIE}=${CURRENT_TERMS_VERSION}; Path=/; Max-Age=31536000; Secure; SameSite=Lax`,
|
||||
);
|
||||
const body = (deps.fetch.mock.calls[0] as unknown as [string, RequestInit])[1]
|
||||
.body as URLSearchParams;
|
||||
expect(body.get("remoteip")).toBe("203.0.113.5");
|
||||
|
||||
// The minted cookie is accepted on the next request from the same browser.
|
||||
const gate = cookies[0]!.split(";")[0]!;
|
||||
const next = await handleRequest(req("/", { headers: { Cookie: gate } }), env, makeDeps());
|
||||
expect(await next.text()).toBe("asset:/");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"a foreign origin",
|
||||
verify({ token: "t", consent: true }, { Origin: "https://evil.example" }),
|
||||
403,
|
||||
],
|
||||
[
|
||||
"a non-JSON body",
|
||||
verify("token=t", { "Content-Type": "application/x-www-form-urlencoded" }),
|
||||
415,
|
||||
],
|
||||
["broken JSON", verify("{nope"), 400],
|
||||
["a missing token", verify({ consent: true }), 400],
|
||||
["no consent", verify({ token: "t" }), 400],
|
||||
["an oversized body", verify({ token: "t", consent: true, pad: "x".repeat(9000) }), 413],
|
||||
])("refuses %s", async (_label, request, status) => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(request, env, makeDeps(goodSiteverify));
|
||||
expect(res.status).toBe(status);
|
||||
expect(res.headers.getSetCookie()).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a token Cloudflare minted for another hostname", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(
|
||||
verify({ token: "t", consent: true }),
|
||||
env,
|
||||
makeDeps({ ...goodSiteverify, hostname: "attacker.example" }),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.json()).toEqual({ ok: false, error: "hostname-mismatch" });
|
||||
});
|
||||
|
||||
it("only accepts POST", async () => {
|
||||
const { env } = makeEnv();
|
||||
const res = await handleRequest(req("/__gate/verify"), env, makeDeps());
|
||||
expect(res.status).toBe(405);
|
||||
});
|
||||
});
|
||||
|
||||
describe("worker routing — missing secret", () => {
|
||||
it("keeps the site up without the gate and refuses verification", async () => {
|
||||
const { env } = makeEnv({ TURNSTILE_SECRET: "" });
|
||||
const errors = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const page = await handleRequest(req("/output"), env, makeDeps());
|
||||
expect(await page.text()).toBe("asset:/");
|
||||
const res = await handleRequest(
|
||||
req("/__gate/verify", {
|
||||
method: "POST",
|
||||
headers: { Origin: ORIGIN, "Content-Type": "application/json" },
|
||||
body: "{}",
|
||||
}),
|
||||
env,
|
||||
makeDeps(),
|
||||
);
|
||||
expect(res.status).toBe(503);
|
||||
errors.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { SITEVERIFY_URL } from "../../worker/env";
|
||||
import { evaluateSiteverify, parseSiteverify, siteverify } from "../../worker/turnstile";
|
||||
|
||||
const NOW = Date.parse("2026-09-30T12:00:00Z");
|
||||
const good = {
|
||||
success: true,
|
||||
hostname: "ytgenerator.stream",
|
||||
action: "enter",
|
||||
challengeTs: "2026-09-30T11:59:00Z",
|
||||
errorCodes: [],
|
||||
testing: false,
|
||||
};
|
||||
|
||||
describe("evaluateSiteverify", () => {
|
||||
it("accepts a fresh token for this hostname and action", () => {
|
||||
expect(evaluateSiteverify(good, { hostname: "ytgenerator.stream", nowMs: NOW })).toEqual({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ ...good, success: false }, "not-success"],
|
||||
[{ ...good, hostname: "evil.example" }, "hostname-mismatch"],
|
||||
[{ ...good, action: "login" }, "action-mismatch"],
|
||||
[{ ...good, challengeTs: undefined }, "missing-timestamp"],
|
||||
[{ ...good, challengeTs: "2026-09-30T11:54:00Z" }, "token-too-old"],
|
||||
] as const)("refuses %o with %s", (result, reason) => {
|
||||
expect(evaluateSiteverify(result, { hostname: "ytgenerator.stream", nowMs: NOW })).toEqual({
|
||||
ok: false,
|
||||
reason,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("test keys", () => {
|
||||
it("accepts Cloudflare's dummy answer only when it is flagged as a test result", () => {
|
||||
const dummy = parseSiteverify({
|
||||
success: true,
|
||||
hostname: "example.com",
|
||||
challenge_ts: "2026-09-30T11:59:50Z",
|
||||
"error-codes": [],
|
||||
metadata: { result_with_testing_key: true },
|
||||
});
|
||||
expect(dummy.testing).toBe(true);
|
||||
expect(evaluateSiteverify(dummy, { hostname: "localhost", nowMs: NOW })).toEqual({ ok: true });
|
||||
expect(
|
||||
evaluateSiteverify({ ...dummy, testing: false }, { hostname: "localhost", nowMs: NOW }),
|
||||
).toEqual({ ok: false, reason: "hostname-mismatch" });
|
||||
});
|
||||
|
||||
it("still refuses a failed or stale test result", () => {
|
||||
const base = {
|
||||
success: true,
|
||||
testing: true,
|
||||
errorCodes: [],
|
||||
challengeTs: "2026-09-30T11:00:00Z",
|
||||
};
|
||||
expect(evaluateSiteverify(base, { hostname: "x", nowMs: NOW })).toEqual({
|
||||
ok: false,
|
||||
reason: "token-too-old",
|
||||
});
|
||||
expect(evaluateSiteverify({ ...base, success: false }, { hostname: "x", nowMs: NOW })).toEqual({
|
||||
ok: false,
|
||||
reason: "not-success",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSiteverify", () => {
|
||||
it("maps Cloudflare's field names", () => {
|
||||
expect(
|
||||
parseSiteverify({
|
||||
success: true,
|
||||
hostname: "h",
|
||||
action: "a",
|
||||
challenge_ts: "t",
|
||||
"error-codes": ["x", 1],
|
||||
}),
|
||||
).toEqual({
|
||||
success: true,
|
||||
hostname: "h",
|
||||
action: "a",
|
||||
challengeTs: "t",
|
||||
errorCodes: ["x"],
|
||||
testing: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("never treats a malformed body as success", () => {
|
||||
expect(parseSiteverify(null).success).toBe(false);
|
||||
expect(parseSiteverify("yes").success).toBe(false);
|
||||
expect(parseSiteverify({ success: "true" }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("siteverify", () => {
|
||||
it("posts secret, token, remote IP and idempotency key", async () => {
|
||||
const fetchMock = vi.fn(async () => Response.json({ success: true }));
|
||||
await siteverify(fetchMock as unknown as typeof fetch, {
|
||||
secret: "s3cret",
|
||||
token: "tok",
|
||||
remoteIp: "203.0.113.9",
|
||||
idempotencyKey: "idem",
|
||||
});
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(SITEVERIFY_URL);
|
||||
expect(init.method).toBe("POST");
|
||||
const body = init.body as URLSearchParams;
|
||||
expect(body.get("secret")).toBe("s3cret");
|
||||
expect(body.get("response")).toBe("tok");
|
||||
expect(body.get("remoteip")).toBe("203.0.113.9");
|
||||
expect(body.get("idempotency_key")).toBe("idem");
|
||||
});
|
||||
|
||||
it("turns HTTP and network failures into a refusal instead of throwing", async () => {
|
||||
const httpError = vi.fn(async () => new Response("down", { status: 503 }));
|
||||
const networkError = vi.fn(async () => {
|
||||
throw new TypeError("fetch failed");
|
||||
});
|
||||
const params = { secret: "s", token: "t", remoteIp: null, idempotencyKey: "i" };
|
||||
await expect(siteverify(httpError as unknown as typeof fetch, params)).resolves.toMatchObject({
|
||||
success: false,
|
||||
errorCodes: ["http-503"],
|
||||
});
|
||||
await expect(
|
||||
siteverify(networkError as unknown as typeof fetch, params),
|
||||
).resolves.toMatchObject({ success: false, errorCodes: ["network-error"] });
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -14,5 +14,5 @@
|
||||
// never sees these, which is why the base config leaves them out.
|
||||
"types": ["vitest/globals", "node"]
|
||||
},
|
||||
"include": ["src", "tests", "scripts"]
|
||||
"include": ["src", "tests", "scripts", "worker", "build-plugins"]
|
||||
}
|
||||
+12
-1
@@ -1,11 +1,19 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import path from "path";
|
||||
import { legalDocsPlugin } from "./build-plugins/legal-docs.ts";
|
||||
import { cloudflareWebAnalytics, securityTxt } from "./build-plugins/web-only.ts";
|
||||
|
||||
const isTauri = !!process.env.TAURI_ENV_PLATFORM;
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [
|
||||
react(),
|
||||
// In-app Legal Center content for every build; the static /legal pages,
|
||||
// security.txt and the analytics beacon only for the web deployment.
|
||||
legalDocsPlugin({ emitStaticPages: !isTauri }),
|
||||
...(isTauri ? [] : [securityTxt(), cloudflareWebAnalytics()]),
|
||||
],
|
||||
// Both builds are served from the root: the web build from
|
||||
// https://ytgenerator.stream (Cloudflare Workers static assets, see
|
||||
// wrangler.jsonc) and the Tauri build from its own asset protocol. The old
|
||||
@@ -33,6 +41,9 @@ export default defineConfig({
|
||||
// modern default. Desktop WebViews are evergreen, so a lower
|
||||
// target is a harmless no-op there.
|
||||
target: isTauri ? "es2020" : undefined,
|
||||
// Never inline assets as data: URIs — the Tauri CSP only allows 'self'
|
||||
// for images and fonts, so an inlined icon would silently fail there.
|
||||
assetsInlineLimit: 0,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// Vite 8 bundles with Rolldown, which only accepts the function form of
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* The gate cookie: proof that this browser passed Turnstile recently.
|
||||
*
|
||||
* Format: `v1.<expiresAt>.<uaHash>.<signature>`
|
||||
*
|
||||
* - `expiresAt` — Unix seconds; checked on every request.
|
||||
* - `uaHash` — first 16 base64url chars of SHA-256(User-Agent). Binds the
|
||||
* cookie to the browser that solved the challenge, so a
|
||||
* cookie lifted into a scraper with a different UA is dead.
|
||||
* A browser update changes the UA and simply re-shows the
|
||||
* gate, which is cheap.
|
||||
* - signature — HMAC-SHA256 over `v1.<expiresAt>.<uaHash>`.
|
||||
*
|
||||
* The HMAC key is derived from the Turnstile secret (HMAC(secret, label)), so
|
||||
* the deployment needs no second secret, and rotating the Turnstile secret
|
||||
* invalidates every outstanding gate cookie as a side effect.
|
||||
*/
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
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(/=+$/, "");
|
||||
}
|
||||
|
||||
function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
|
||||
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
||||
try {
|
||||
const binary = atob(padded);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const keyCache = new Map<string, Promise<CryptoKey>>();
|
||||
|
||||
/** The HMAC key for gate cookies, derived once per secret per isolate. */
|
||||
export function deriveGateKey(secret: string): Promise<CryptoKey> {
|
||||
let key = keyCache.get(secret);
|
||||
if (!key) {
|
||||
key = (async () => {
|
||||
const master = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
encoder.encode(secret),
|
||||
{ name: "HMAC", hash: "SHA-256" },
|
||||
false,
|
||||
["sign"],
|
||||
);
|
||||
const derived = await crypto.subtle.sign("HMAC", master, encoder.encode(KEY_LABEL));
|
||||
return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, [
|
||||
"sign",
|
||||
"verify",
|
||||
]);
|
||||
})();
|
||||
keyCache.set(secret, key);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export async function userAgentHash(userAgent: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(userAgent));
|
||||
return toBase64Url(new Uint8Array(digest)).slice(0, 16);
|
||||
}
|
||||
|
||||
export async function signGateToken(
|
||||
key: CryptoKey,
|
||||
expiresAt: number,
|
||||
uaHash: string,
|
||||
): Promise<string> {
|
||||
const payload = `v1.${expiresAt}.${uaHash}`;
|
||||
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
|
||||
return `${payload}.${toBase64Url(new Uint8Array(signature))}`;
|
||||
}
|
||||
|
||||
/** True only for an unexpired, untampered token minted for this User-Agent. */
|
||||
export async function verifyGateToken(
|
||||
key: CryptoKey,
|
||||
token: string,
|
||||
nowSeconds: number,
|
||||
uaHash: string,
|
||||
): Promise<boolean> {
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 4) return false;
|
||||
const [version, expiresRaw, tokenUa, signatureRaw] = parts as [string, string, string, string];
|
||||
if (version !== "v1" || !/^\d{1,12}$/.test(expiresRaw)) return false;
|
||||
if (Number(expiresRaw) <= nowSeconds) return false;
|
||||
if (tokenUa !== uaHash) return false;
|
||||
const signature = fromBase64Url(signatureRaw);
|
||||
if (!signature) return false;
|
||||
return crypto.subtle.verify(
|
||||
"HMAC",
|
||||
key,
|
||||
signature,
|
||||
encoder.encode(`${version}.${expiresRaw}.${tokenUa}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** Read one cookie out of a `Cookie` request header. */
|
||||
export function readCookie(header: string | null, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(";")) {
|
||||
const eq = part.indexOf("=");
|
||||
if (eq < 0) continue;
|
||||
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Bindings and constants for the Cloudflare Worker that fronts
|
||||
* https://ytgenerator.stream.
|
||||
*
|
||||
* The Worker only uses standard Web APIs (fetch, Request, Response, Web
|
||||
* Crypto), so it type-checks against the DOM lib and runs unchanged under
|
||||
* Vitest in Node. The static-assets binding is described structurally rather
|
||||
* than through `@cloudflare/workers-types`.
|
||||
*/
|
||||
|
||||
/** The `ASSETS` binding from `wrangler.jsonc` — serves files out of `dist/`. */
|
||||
export interface AssetsBinding {
|
||||
fetch(request: Request): Promise<Response>;
|
||||
}
|
||||
|
||||
export interface Env {
|
||||
ASSETS: AssetsBinding;
|
||||
/** Public Turnstile sitekey (`vars` in wrangler.jsonc). */
|
||||
TURNSTILE_SITE_KEY: string;
|
||||
/** Turnstile secret — a dashboard Secret, never committed. */
|
||||
TURNSTILE_SECRET: string;
|
||||
/** How long a passed check lasts, in seconds (string, from `vars`). */
|
||||
GATE_TTL_SECONDS?: string;
|
||||
}
|
||||
|
||||
/** Everything the router needs from the outside world, injectable in tests. */
|
||||
export interface Deps {
|
||||
/** Current time in milliseconds since the epoch. */
|
||||
now(): number;
|
||||
fetch: typeof fetch;
|
||||
/** A fresh random string: CSP nonces and siteverify idempotency keys. */
|
||||
randomId(): string;
|
||||
}
|
||||
|
||||
export const GATE_COOKIE = "__Host-ytg_gate";
|
||||
export const VERIFY_PATH = "/__gate/verify";
|
||||
/** 204 when the request carries a valid gate cookie — lets the gate page
|
||||
* detect a browser that silently refused to store it. */
|
||||
export const STATUS_PATH = "/__gate/status";
|
||||
export const TURNSTILE_ACTION = "enter";
|
||||
export const SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
||||
|
||||
/** Turnstile tokens are valid for 300 s; anything older is refused. */
|
||||
export const MAX_TOKEN_AGE_SECONDS = 300;
|
||||
|
||||
const DEFAULT_GATE_TTL_SECONDS = 86_400;
|
||||
const MIN_GATE_TTL_SECONDS = 300;
|
||||
const MAX_GATE_TTL_SECONDS = 30 * 86_400;
|
||||
|
||||
/** The configured gate lifetime, clamped to [5 min, 30 days]. */
|
||||
export function gateTtlSeconds(env: Env): number {
|
||||
const parsed = Number.parseInt(env.GATE_TTL_SECONDS ?? "", 10);
|
||||
if (!Number.isFinite(parsed)) return DEFAULT_GATE_TTL_SECONDS;
|
||||
return Math.min(MAX_GATE_TTL_SECONDS, Math.max(MIN_GATE_TTL_SECONDS, parsed));
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Copy for the Turnstile gate page, in the app's eight languages.
|
||||
*
|
||||
* `{terms}` / `{privacy}` become links; `{hours}` is the gate lifetime. The
|
||||
* page is the first thing every web visitor sees, so it follows the visitor's
|
||||
* `Accept-Language` rather than defaulting to English.
|
||||
*/
|
||||
|
||||
export type GateLang = "en" | "vi" | "ja" | "es" | "ko" | "zh" | "pt-BR" | "id";
|
||||
|
||||
export interface GateStrings {
|
||||
title: string;
|
||||
metaDescription: string;
|
||||
heading: string;
|
||||
lead: string;
|
||||
agree: string;
|
||||
returning: string;
|
||||
termsLink: string;
|
||||
privacyLink: string;
|
||||
enter: string;
|
||||
checking: string;
|
||||
entering: string;
|
||||
failed: string;
|
||||
widgetError: string;
|
||||
noscript: string;
|
||||
dataNote: string;
|
||||
protectedBy: string;
|
||||
security: string;
|
||||
}
|
||||
|
||||
export const GATE_STRINGS: Readonly<Record<GateLang, GateStrings>> = {
|
||||
en: {
|
||||
title: "Quick check — YTDescGen",
|
||||
metaDescription:
|
||||
"Generate YouTube titles, descriptions and tags for gameplay no-commentary videos — in 8 languages, in your browser or on desktop.",
|
||||
heading: "Just a quick check",
|
||||
lead: "This keeps automated traffic out of YTDescGen. It usually finishes on its own in a second or two.",
|
||||
agree: "I agree to the {terms} and have read the {privacy}.",
|
||||
returning: "By continuing you agree to the {terms} and the {privacy}.",
|
||||
termsLink: "Terms of Use",
|
||||
privacyLink: "Privacy Policy",
|
||||
enter: "Enter YTDescGen",
|
||||
checking: "Checking your browser…",
|
||||
entering: "Verified — opening YTDescGen…",
|
||||
failed: "The check didn't go through. Please try again.",
|
||||
widgetError:
|
||||
"The check couldn't load. Allow challenges.cloudflare.com in your content blocker, or try another browser.",
|
||||
noscript: "YTDescGen needs JavaScript enabled to complete this check.",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile processes technical signals (such as your IP address and browser details) to run this check. YTDescGen only keeps a signed cookie that remembers you passed, for {hours} hours.",
|
||||
protectedBy: "Protected by Cloudflare Turnstile",
|
||||
security: "Security",
|
||||
},
|
||||
vi: {
|
||||
title: "Kiểm tra nhanh — YTDescGen",
|
||||
metaDescription:
|
||||
"Tạo tiêu đề, mô tả và tag YouTube cho video gameplay không bình luận — 8 ngôn ngữ, ngay trên trình duyệt hoặc máy tính.",
|
||||
heading: "Kiểm tra nhanh một chút",
|
||||
lead: "Bước này giúp chặn lưu lượng tự động vào YTDescGen. Thường chỉ mất một hai giây và tự hoàn tất.",
|
||||
agree: "Tôi đồng ý với {terms} và đã đọc {privacy}.",
|
||||
returning: "Tiếp tục đồng nghĩa với việc bạn đồng ý với {terms} và {privacy}.",
|
||||
termsLink: "Điều khoản sử dụng",
|
||||
privacyLink: "Chính sách quyền riêng tư",
|
||||
enter: "Vào YTDescGen",
|
||||
checking: "Đang kiểm tra trình duyệt…",
|
||||
entering: "Đã xác minh — đang mở YTDescGen…",
|
||||
failed: "Kiểm tra chưa thành công. Vui lòng thử lại.",
|
||||
widgetError:
|
||||
"Không tải được bước kiểm tra. Hãy cho phép challenges.cloudflare.com trong trình chặn nội dung hoặc dùng trình duyệt khác.",
|
||||
noscript: "YTDescGen cần bật JavaScript để hoàn tất bước kiểm tra này.",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile xử lý một số tín hiệu kỹ thuật (như địa chỉ IP và thông tin trình duyệt) để chạy bước kiểm tra. YTDescGen chỉ lưu một cookie đã ký để ghi nhớ bạn đã qua kiểm tra trong {hours} giờ.",
|
||||
protectedBy: "Được bảo vệ bởi Cloudflare Turnstile",
|
||||
security: "Bảo mật",
|
||||
},
|
||||
ja: {
|
||||
title: "確認 — YTDescGen",
|
||||
metaDescription:
|
||||
"実況なしのゲームプレイ動画向けに、YouTube のタイトル・説明文・タグを8言語で生成。ブラウザでもデスクトップでも。",
|
||||
heading: "かんたんな確認です",
|
||||
lead: "自動アクセスから YTDescGen を守るための確認です。通常は1〜2秒で自動的に完了します。",
|
||||
agree: "{terms}に同意し、{privacy}を読みました。",
|
||||
returning: "続行すると、{terms}と{privacy}に同意したものとみなされます。",
|
||||
termsLink: "利用規約",
|
||||
privacyLink: "プライバシーポリシー",
|
||||
enter: "YTDescGen に入る",
|
||||
checking: "ブラウザを確認しています…",
|
||||
entering: "確認できました — YTDescGen を開いています…",
|
||||
failed: "確認に失敗しました。もう一度お試しください。",
|
||||
widgetError:
|
||||
"確認を読み込めませんでした。コンテンツブロッカーで challenges.cloudflare.com を許可するか、別のブラウザをお試しください。",
|
||||
noscript: "この確認を完了するには JavaScript を有効にしてください。",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile は確認のために技術的な情報(IP アドレスやブラウザ情報など)を処理します。YTDescGen が保存するのは、確認済みであることを{hours}時間記憶する署名付き Cookie だけです。",
|
||||
protectedBy: "Cloudflare Turnstile による保護",
|
||||
security: "セキュリティ",
|
||||
},
|
||||
es: {
|
||||
title: "Comprobación rápida — YTDescGen",
|
||||
metaDescription:
|
||||
"Genera títulos, descripciones y etiquetas de YouTube para vídeos de gameplay sin comentarios — en 8 idiomas, en el navegador o en escritorio.",
|
||||
heading: "Una comprobación rápida",
|
||||
lead: "Esto mantiene el tráfico automatizado fuera de YTDescGen. Normalmente termina solo en uno o dos segundos.",
|
||||
agree: "Acepto los {terms} y he leído la {privacy}.",
|
||||
returning: "Al continuar, aceptas los {terms} y la {privacy}.",
|
||||
termsLink: "Términos de uso",
|
||||
privacyLink: "Política de privacidad",
|
||||
enter: "Entrar en YTDescGen",
|
||||
checking: "Comprobando tu navegador…",
|
||||
entering: "Verificado — abriendo YTDescGen…",
|
||||
failed: "La comprobación no se completó. Inténtalo de nuevo.",
|
||||
widgetError:
|
||||
"No se pudo cargar la comprobación. Permite challenges.cloudflare.com en tu bloqueador de contenido o prueba con otro navegador.",
|
||||
noscript: "YTDescGen necesita JavaScript activado para completar esta comprobación.",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile procesa señales técnicas (como tu dirección IP y datos del navegador) para realizar esta comprobación. YTDescGen solo guarda una cookie firmada que recuerda que la superaste durante {hours} horas.",
|
||||
protectedBy: "Protegido por Cloudflare Turnstile",
|
||||
security: "Seguridad",
|
||||
},
|
||||
ko: {
|
||||
title: "빠른 확인 — YTDescGen",
|
||||
metaDescription:
|
||||
"무해설 게임플레이 영상용 YouTube 제목·설명·태그를 8개 언어로 생성하세요 — 브라우저 또는 데스크톱에서.",
|
||||
heading: "잠깐 확인할게요",
|
||||
lead: "자동화된 트래픽으로부터 YTDescGen을 보호하기 위한 확인입니다. 보통 1~2초 안에 자동으로 끝납니다.",
|
||||
agree: "{terms}에 동의하며 {privacy}을 읽었습니다.",
|
||||
returning: "계속하면 {terms} 및 {privacy}에 동의하는 것으로 간주됩니다.",
|
||||
termsLink: "이용약관",
|
||||
privacyLink: "개인정보 처리방침",
|
||||
enter: "YTDescGen 들어가기",
|
||||
checking: "브라우저를 확인하는 중…",
|
||||
entering: "확인 완료 — YTDescGen을 여는 중…",
|
||||
failed: "확인에 실패했습니다. 다시 시도해 주세요.",
|
||||
widgetError:
|
||||
"확인 화면을 불러오지 못했습니다. 콘텐츠 차단기에서 challenges.cloudflare.com을 허용하거나 다른 브라우저를 사용해 보세요.",
|
||||
noscript: "이 확인을 완료하려면 JavaScript를 켜 주세요.",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile은 확인을 위해 기술적 신호(IP 주소, 브라우저 정보 등)를 처리합니다. YTDescGen은 확인을 통과했음을 {hours}시간 동안 기억하는 서명된 쿠키만 저장합니다.",
|
||||
protectedBy: "Cloudflare Turnstile로 보호됨",
|
||||
security: "보안",
|
||||
},
|
||||
zh: {
|
||||
title: "快速验证 — YTDescGen",
|
||||
metaDescription:
|
||||
"为无解说游戏视频生成 YouTube 标题、描述和标签——支持 8 种语言,可在浏览器或桌面端使用。",
|
||||
heading: "快速验证一下",
|
||||
lead: "这一步用于阻挡自动化流量访问 YTDescGen,通常一两秒内会自动完成。",
|
||||
agree: "我同意{terms},并已阅读{privacy}。",
|
||||
returning: "继续即表示你同意{terms}和{privacy}。",
|
||||
termsLink: "使用条款",
|
||||
privacyLink: "隐私政策",
|
||||
enter: "进入 YTDescGen",
|
||||
checking: "正在检查你的浏览器…",
|
||||
entering: "验证通过 — 正在打开 YTDescGen…",
|
||||
failed: "验证未通过,请重试。",
|
||||
widgetError: "无法加载验证。请在内容拦截器中允许 challenges.cloudflare.com,或换一个浏览器。",
|
||||
noscript: "YTDescGen 需要启用 JavaScript 才能完成验证。",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile 会处理一些技术信号(例如 IP 地址和浏览器信息)来完成验证。YTDescGen 只会保存一个签名 Cookie,用于在 {hours} 小时内记住你已通过验证。",
|
||||
protectedBy: "由 Cloudflare Turnstile 保护",
|
||||
security: "安全",
|
||||
},
|
||||
"pt-BR": {
|
||||
title: "Verificação rápida — YTDescGen",
|
||||
metaDescription:
|
||||
"Gere títulos, descrições e tags do YouTube para vídeos de gameplay sem comentários — em 8 idiomas, no navegador ou no desktop.",
|
||||
heading: "Só uma verificação rápida",
|
||||
lead: "Isso mantém o tráfego automatizado longe do YTDescGen. Normalmente termina sozinho em um ou dois segundos.",
|
||||
agree: "Concordo com os {terms} e li a {privacy}.",
|
||||
returning: "Ao continuar, você concorda com os {terms} e a {privacy}.",
|
||||
termsLink: "Termos de Uso",
|
||||
privacyLink: "Política de Privacidade",
|
||||
enter: "Entrar no YTDescGen",
|
||||
checking: "Verificando seu navegador…",
|
||||
entering: "Verificado — abrindo o YTDescGen…",
|
||||
failed: "A verificação não foi concluída. Tente novamente.",
|
||||
widgetError:
|
||||
"Não foi possível carregar a verificação. Permita challenges.cloudflare.com no seu bloqueador de conteúdo ou use outro navegador.",
|
||||
noscript: "O YTDescGen precisa do JavaScript ativado para concluir esta verificação.",
|
||||
dataNote:
|
||||
"O Cloudflare Turnstile processa sinais técnicos (como seu endereço IP e dados do navegador) para fazer esta verificação. O YTDescGen guarda apenas um cookie assinado que lembra que você passou, por {hours} horas.",
|
||||
protectedBy: "Protegido pelo Cloudflare Turnstile",
|
||||
security: "Segurança",
|
||||
},
|
||||
id: {
|
||||
title: "Pemeriksaan singkat — YTDescGen",
|
||||
metaDescription:
|
||||
"Buat judul, deskripsi, dan tag YouTube untuk video gameplay tanpa komentar — dalam 8 bahasa, di browser atau desktop.",
|
||||
heading: "Pemeriksaan singkat",
|
||||
lead: "Ini menjaga YTDescGen dari lalu lintas otomatis. Biasanya selesai sendiri dalam satu atau dua detik.",
|
||||
agree: "Saya menyetujui {terms} dan telah membaca {privacy}.",
|
||||
returning: "Dengan melanjutkan, Anda menyetujui {terms} dan {privacy}.",
|
||||
termsLink: "Ketentuan Penggunaan",
|
||||
privacyLink: "Kebijakan Privasi",
|
||||
enter: "Masuk ke YTDescGen",
|
||||
checking: "Memeriksa browser Anda…",
|
||||
entering: "Terverifikasi — membuka YTDescGen…",
|
||||
failed: "Pemeriksaan tidak berhasil. Silakan coba lagi.",
|
||||
widgetError:
|
||||
"Pemeriksaan tidak dapat dimuat. Izinkan challenges.cloudflare.com di pemblokir konten Anda atau coba browser lain.",
|
||||
noscript: "YTDescGen memerlukan JavaScript yang aktif untuk menyelesaikan pemeriksaan ini.",
|
||||
dataNote:
|
||||
"Cloudflare Turnstile memproses sinyal teknis (seperti alamat IP dan detail browser) untuk menjalankan pemeriksaan ini. YTDescGen hanya menyimpan cookie bertanda tangan yang mengingat bahwa Anda lolos, selama {hours} jam.",
|
||||
protectedBy: "Dilindungi oleh Cloudflare Turnstile",
|
||||
security: "Keamanan",
|
||||
},
|
||||
};
|
||||
|
||||
const PREFIX_TO_LANG: ReadonlyArray<[string, GateLang]> = [
|
||||
["vi", "vi"],
|
||||
["ja", "ja"],
|
||||
["es", "es"],
|
||||
["ko", "ko"],
|
||||
["zh", "zh"],
|
||||
["pt", "pt-BR"],
|
||||
["id", "id"],
|
||||
["in", "id"], // legacy ISO 639 code for Indonesian
|
||||
["en", "en"],
|
||||
];
|
||||
|
||||
/** Pick the best supported language from an `Accept-Language` header. */
|
||||
export function pickGateLang(acceptLanguage: string | null): GateLang {
|
||||
if (!acceptLanguage) return "en";
|
||||
const ranked = acceptLanguage
|
||||
.split(",")
|
||||
.map((part, index) => {
|
||||
const [tag = "", ...params] = part.trim().split(";");
|
||||
const q = params
|
||||
.map((p) => p.trim())
|
||||
.find((p) => p.startsWith("q="))
|
||||
?.slice(2);
|
||||
const weight = q === undefined ? 1 : Number(q);
|
||||
return { tag: tag.toLowerCase(), weight: Number.isFinite(weight) ? weight : 0, index };
|
||||
})
|
||||
.filter((entry) => entry.tag && entry.weight > 0)
|
||||
.sort((a, b) => b.weight - a.weight || a.index - b.index);
|
||||
for (const { tag } of ranked) {
|
||||
const primary = tag.split("-")[0] ?? "";
|
||||
const match = PREFIX_TO_LANG.find(([prefix]) => primary === prefix);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return "en";
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { LOGO_SVG } from "../src/config/brand";
|
||||
import { legalDocPath } from "../src/config/legal";
|
||||
import { STATUS_PATH, TURNSTILE_ACTION, VERIFY_PATH } from "./env";
|
||||
import { GATE_STRINGS, type GateLang } from "./gate-i18n";
|
||||
|
||||
/**
|
||||
* The Turnstile gate page. Served at whatever URL the visitor asked for, so a
|
||||
* successful check just reloads the same URL — there is no `next` parameter to
|
||||
* validate and nothing to open-redirect.
|
||||
*/
|
||||
|
||||
export interface GatePageOptions {
|
||||
lang: GateLang;
|
||||
nonce: string;
|
||||
siteKey: string;
|
||||
/** The visitor already accepted the current terms (the `ytg_terms` cookie). */
|
||||
returning: boolean;
|
||||
/** e.g. `https://ytgenerator.stream` — for canonical / OpenGraph URLs. */
|
||||
origin: string;
|
||||
/** Gate lifetime in hours, quoted in the data note. */
|
||||
hours: number;
|
||||
}
|
||||
|
||||
const HTML_ESCAPES: Readonly<Record<string, string>> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
};
|
||||
|
||||
export function escapeHtml(text: string): string {
|
||||
return text.replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch] ?? ch);
|
||||
}
|
||||
|
||||
/** JSON that is safe inside a <script> element. */
|
||||
function scriptJson(value: unknown): string {
|
||||
// Only "<" matters: it is what could close the <script> element early. It is
|
||||
// replaced by its six-character JSON escape (backslash, "u003c").
|
||||
const escapedLt = "\\" + "u003c";
|
||||
return JSON.stringify(value).replace(/</g, escapedLt);
|
||||
}
|
||||
|
||||
function link(href: string, label: string): string {
|
||||
return `<a href="${escapeHtml(href)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
|
||||
}
|
||||
|
||||
/** Fill `{terms}` / `{privacy}` with links; everything else is escaped text. */
|
||||
function withLinks(template: string, links: Readonly<Record<string, string>>): string {
|
||||
return template
|
||||
.split(/(\{[a-z]+\})/)
|
||||
.map((piece) => {
|
||||
const key = /^\{([a-z]+)\}$/.exec(piece)?.[1];
|
||||
return key && links[key] !== undefined ? links[key] : escapeHtml(piece);
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
const STYLES = `
|
||||
:root{color-scheme:dark light;--bg:#0b0b12;--card:#13131c;--border:#262636;--text:#ececf3;--muted:#9a9ab0;--link:#a5a6fb;--danger:#f87171;font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif}
|
||||
@media (prefers-color-scheme:light){:root{--bg:#f6f6fb;--card:#fff;--border:#e3e3ee;--text:#16161f;--muted:#5d5d72;--link:#4f46e5;--danger:#dc2626}}
|
||||
*{box-sizing:border-box}
|
||||
html,body{min-height:100%}
|
||||
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:24px 16px;color:var(--text);background:radial-gradient(1100px 560px at 88% -12%,rgba(124,58,237,.24),transparent 60%),radial-gradient(900px 520px at -12% 112%,rgba(79,70,229,.18),transparent 60%),var(--bg)}
|
||||
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--border);border-radius:20px;padding:28px 24px;box-shadow:0 24px 64px -28px rgba(0,0,0,.55)}
|
||||
.brand{display:flex;align-items:center;gap:10px;font-weight:700;font-size:15px;letter-spacing:-.01em;margin:0 0 20px}
|
||||
.brand svg{width:32px;height:32px}
|
||||
h1{font-size:20px;line-height:1.3;margin:0 0 6px;letter-spacing:-.01em}
|
||||
.lead{margin:0 0 18px;color:var(--muted);font-size:14px;line-height:1.55}
|
||||
#ts{min-height:65px;margin:0 0 14px}
|
||||
.agree{display:flex;gap:10px;align-items:flex-start;font-size:13.5px;line-height:1.5;margin:0 0 16px;cursor:pointer}
|
||||
.agree input{margin:2px 0 0;width:16px;height:16px;flex:none;accent-color:#6366f1}
|
||||
.fine{font-size:13px;line-height:1.5;color:var(--muted);margin:0 0 16px}
|
||||
a{color:var(--link)}
|
||||
button{width:100%;height:42px;border:0;border-radius:12px;background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;font:inherit;font-weight:600;font-size:14.5px;cursor:pointer;transition:filter .15s,opacity .15s}
|
||||
button:disabled{opacity:.45;cursor:not-allowed}
|
||||
button:not(:disabled):hover{filter:brightness(1.08)}
|
||||
a:focus-visible,button:focus-visible,input:focus-visible{outline:2px solid var(--link);outline-offset:2px}
|
||||
.status{min-height:20px;margin:12px 0 0;font-size:13px;line-height:1.45;color:var(--muted);text-align:center}
|
||||
.status.err{color:var(--danger)}
|
||||
.note{margin:16px 0 0;padding-top:14px;border-top:1px solid var(--border);font-size:12px;line-height:1.55;color:var(--muted)}
|
||||
footer{font-size:12px;color:var(--muted);text-align:center;line-height:1.8}
|
||||
footer a{color:inherit}
|
||||
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
|
||||
`;
|
||||
|
||||
/** Client script — tiny, dependency-free, CSP-nonced. */
|
||||
const CLIENT_SCRIPT = `
|
||||
(function(){
|
||||
var cfg = JSON.parse(document.getElementById("ytg-gate").textContent);
|
||||
var enter = document.getElementById("enter");
|
||||
var agree = document.getElementById("agree");
|
||||
var status = document.getElementById("status");
|
||||
// Submit on its own the first time; after a failure wait for a click, so a
|
||||
// widget that re-issues tokens can never loop against a refusing server.
|
||||
var token = null, widgetId = null, busy = false, auto = true;
|
||||
function say(msg, isError){ status.textContent = msg || ""; status.className = isError ? "status err" : "status"; }
|
||||
function ready(){ return !!token && !busy && (!agree || agree.checked); }
|
||||
function sync(){ enter.disabled = !ready(); }
|
||||
function fail(msg){
|
||||
busy = false; token = null; auto = false; say(msg, true); sync();
|
||||
if (window.turnstile && widgetId !== null) { try { window.turnstile.reset(widgetId); } catch (e) {} }
|
||||
}
|
||||
function submit(){
|
||||
if (!ready()) return;
|
||||
busy = true; sync(); say(cfg.s.checking);
|
||||
fetch(cfg.verify, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: token, consent: true }) })
|
||||
.then(function(res){ if (!res.ok) throw new Error("verify"); return fetch(cfg.status, { credentials: "same-origin", cache: "no-store" }); })
|
||||
.then(function(res){ if (res.status !== 204) throw new Error("cookie"); say(cfg.s.entering); window.location.reload(); })
|
||||
.catch(function(err){ fail(err && err.message === "cookie" ? cfg.s.cookies : cfg.s.failed); });
|
||||
}
|
||||
enter.addEventListener("click", submit);
|
||||
if (agree) agree.addEventListener("change", function(){ sync(); if (agree.checked && auto) submit(); });
|
||||
window.ytgTurnstileReady = function(){
|
||||
widgetId = window.turnstile.render("#ts", {
|
||||
sitekey: cfg.siteKey, action: cfg.action, theme: "auto", language: "auto", size: "flexible",
|
||||
callback: function(t){ token = t; sync(); if (auto && (!agree || agree.checked)) submit(); },
|
||||
"expired-callback": function(){ token = null; sync(); },
|
||||
"error-callback": function(){ token = null; say(cfg.s.widgetError, true); sync(); return true; }
|
||||
});
|
||||
};
|
||||
var s = document.createElement("script");
|
||||
s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=ytgTurnstileReady";
|
||||
s.async = true; s.defer = true;
|
||||
s.onerror = function(){ say(cfg.s.widgetError, true); };
|
||||
document.head.appendChild(s);
|
||||
})();
|
||||
`;
|
||||
|
||||
const COOKIES_BLOCKED: Readonly<Record<GateLang, string>> = {
|
||||
en: "Your browser blocked the cookie that remembers this check. Allow cookies for ytgenerator.stream and try again.",
|
||||
vi: "Trình duyệt đã chặn cookie ghi nhớ bước kiểm tra. Hãy cho phép cookie cho ytgenerator.stream rồi thử lại.",
|
||||
ja: "確認を記憶する Cookie がブラウザにブロックされました。ytgenerator.stream の Cookie を許可してから再試行してください。",
|
||||
es: "Tu navegador bloqueó la cookie que recuerda esta comprobación. Permite las cookies de ytgenerator.stream e inténtalo de nuevo.",
|
||||
ko: "브라우저가 확인 결과를 기억하는 쿠키를 차단했습니다. ytgenerator.stream의 쿠키를 허용한 뒤 다시 시도해 주세요.",
|
||||
zh: "浏览器拦截了用于记住验证结果的 Cookie。请允许 ytgenerator.stream 的 Cookie 后重试。",
|
||||
"pt-BR":
|
||||
"Seu navegador bloqueou o cookie que lembra esta verificação. Permita cookies para ytgenerator.stream e tente de novo.",
|
||||
id: "Browser Anda memblokir cookie yang mengingat pemeriksaan ini. Izinkan cookie untuk ytgenerator.stream lalu coba lagi.",
|
||||
};
|
||||
|
||||
export function renderGatePage(options: GatePageOptions): string {
|
||||
const t = GATE_STRINGS[options.lang];
|
||||
const links = {
|
||||
terms: link(legalDocPath("terms"), t.termsLink),
|
||||
privacy: link(legalDocPath("privacy"), t.privacyLink),
|
||||
};
|
||||
const consentBlock = options.returning
|
||||
? `<p class="fine">${withLinks(t.returning, links)}</p>`
|
||||
: `<label class="agree"><input type="checkbox" id="agree"><span>${withLinks(t.agree, links)}</span></label>`;
|
||||
const config = {
|
||||
siteKey: options.siteKey,
|
||||
action: TURNSTILE_ACTION,
|
||||
verify: VERIFY_PATH,
|
||||
status: STATUS_PATH,
|
||||
s: {
|
||||
checking: t.checking,
|
||||
entering: t.entering,
|
||||
failed: t.failed,
|
||||
widgetError: t.widgetError,
|
||||
cookies: COOKIES_BLOCKED[options.lang],
|
||||
},
|
||||
};
|
||||
const origin = escapeHtml(options.origin);
|
||||
const dataNote = escapeHtml(t.dataNote.replace("{hours}", String(options.hours)));
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="${options.lang}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<meta name="theme-color" content="#0b0b12">
|
||||
<title>YTDescGen · ${escapeHtml(t.heading)}</title>
|
||||
<meta name="description" content="${escapeHtml(t.metaDescription)}">
|
||||
<link rel="canonical" href="${origin}/">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="YTDescGen">
|
||||
<meta property="og:title" content="YTDescGen — YouTube Title, Description & Tag Generator">
|
||||
<meta property="og:description" content="${escapeHtml(t.metaDescription)}">
|
||||
<meta property="og:url" content="${origin}/">
|
||||
<meta property="og:image" content="${origin}/og-image.png">
|
||||
<meta property="og:image:width" content="1200">
|
||||
<meta property="og:image:height" content="630">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:image" content="${origin}/og-image.png">
|
||||
<style>${STYLES}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main aria-labelledby="gate-title">
|
||||
<div class="brand">${LOGO_SVG}<span>YTDescGen</span></div>
|
||||
<h1 id="gate-title">${escapeHtml(t.heading)}</h1>
|
||||
<p class="lead">${escapeHtml(t.lead)}</p>
|
||||
<div id="ts"></div>
|
||||
${consentBlock}
|
||||
<button id="enter" type="button" disabled>${escapeHtml(t.enter)}</button>
|
||||
<p id="status" class="status" role="status" aria-live="polite"></p>
|
||||
<noscript><p class="status err">${escapeHtml(t.noscript)}</p></noscript>
|
||||
<p class="note">${dataNote}</p>
|
||||
</main>
|
||||
<footer>${escapeHtml(t.protectedBy)} · ${link(legalDocPath("privacy"), t.privacyLink)} · ${link(legalDocPath("terms"), t.termsLink)} · ${link(legalDocPath("security"), t.security)}</footer>
|
||||
<script id="ytg-gate" type="application/json">${scriptJson(config)}</script>
|
||||
<script nonce="${options.nonce}">${CLIENT_SCRIPT}</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Security headers for every HTML response the Worker produces.
|
||||
*
|
||||
* `public/_headers` covers the static files Cloudflare serves directly, but
|
||||
* Cloudflare does not apply `_headers` rules to responses generated by Worker
|
||||
* code — so the app shell, the gate page and the static legal pages get their
|
||||
* headers here. `tests/worker/headers.test.ts` keeps the shared baseline in
|
||||
* step with `public/_headers`.
|
||||
*
|
||||
* HSTS is deliberately absent: the zone edge already sends
|
||||
* `max-age=31536000; includeSubDomains; preload`, and a second copy from the
|
||||
* origin risks a merged, malformed header.
|
||||
*/
|
||||
|
||||
export const BASELINE_HEADERS: Readonly<Record<string, string>> = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||
"Permissions-Policy":
|
||||
"accelerometer=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=(), browsing-topics=()",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Resource-Policy": "same-origin",
|
||||
"X-Frame-Options": "DENY",
|
||||
};
|
||||
|
||||
/** CSP for the React app shell (index.html). */
|
||||
export const APP_CSP = [
|
||||
"default-src 'self'",
|
||||
// Cloudflare Web Analytics beacon (manual snippet, web build only).
|
||||
"script-src 'self' https://static.cloudflareinsights.com",
|
||||
"connect-src 'self' https://cloudflareinsights.com",
|
||||
"img-src 'self' data: blob:",
|
||||
// sonner / Radix / Motion set inline styles; no inline <script> is allowed.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"font-src 'self' data:",
|
||||
"manifest-src 'self'",
|
||||
"worker-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"upgrade-insecure-requests",
|
||||
].join("; ");
|
||||
|
||||
/** CSP for the Turnstile gate page — its one inline script carries a nonce. */
|
||||
export function gateCsp(nonce: string): string {
|
||||
return [
|
||||
"default-src 'none'",
|
||||
`script-src 'nonce-${nonce}' 'strict-dynamic' https://challenges.cloudflare.com`,
|
||||
"frame-src https://challenges.cloudflare.com",
|
||||
"connect-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"style-src 'unsafe-inline'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
/** CSP for the prerendered legal pages: no script at all. */
|
||||
export const LEGAL_CSP = [
|
||||
"default-src 'none'",
|
||||
"img-src 'self' data:",
|
||||
"style-src 'unsafe-inline'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
].join("; ");
|
||||
|
||||
/**
|
||||
* Copy a response with the baseline headers, a CSP and a cache policy.
|
||||
* Responses from `env.ASSETS` have immutable headers, so this always rebuilds.
|
||||
*/
|
||||
export function withSecurityHeaders(
|
||||
response: Response,
|
||||
options: { csp: string; cacheControl: string; varyCookie?: boolean },
|
||||
): Response {
|
||||
const headers = new Headers(response.headers);
|
||||
for (const [name, value] of Object.entries(BASELINE_HEADERS)) headers.set(name, value);
|
||||
headers.set("Content-Security-Policy", options.csp);
|
||||
headers.set("Cache-Control", options.cacheControl);
|
||||
if (options.varyCookie) headers.append("Vary", "Cookie");
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
/** A small plain-text response with the baseline headers. */
|
||||
export function plainResponse(status: number, message: string, extra?: HeadersInit): Response {
|
||||
const headers = new Headers(extra);
|
||||
headers.set("Content-Type", "text/plain; charset=utf-8");
|
||||
headers.set("Cache-Control", "no-store");
|
||||
for (const [name, value] of Object.entries(BASELINE_HEADERS)) headers.set(name, value);
|
||||
return new Response(message, { status, headers });
|
||||
}
|
||||
|
||||
/** A JSON response for the verify endpoint. */
|
||||
export function jsonResponse(status: number, body: unknown, extra?: HeadersInit): Response {
|
||||
const headers = new Headers(extra);
|
||||
headers.set("Content-Type", "application/json; charset=utf-8");
|
||||
headers.set("Cache-Control", "no-store");
|
||||
for (const [name, value] of Object.entries(BASELINE_HEADERS)) headers.set(name, value);
|
||||
return new Response(JSON.stringify(body), { status, headers });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Env } from "./env";
|
||||
import { handleRequest } from "./router";
|
||||
|
||||
/**
|
||||
* Cloudflare Worker entry for https://ytgenerator.stream — the Turnstile gate
|
||||
* and security headers in front of the static web build. Routing lives in
|
||||
* ./router.ts so it can be tested without the Workers runtime.
|
||||
*/
|
||||
export default {
|
||||
fetch(request: Request, env: Env): Promise<Response> {
|
||||
return handleRequest(request, env, {
|
||||
now: () => Date.now(),
|
||||
fetch: (input, init) => fetch(input, init),
|
||||
randomId: () => crypto.randomUUID(),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,235 @@
|
||||
import { CURRENT_TERMS_VERSION, LEGAL_DOCS, TERMS_COOKIE, isLegalDocId } from "../src/config/legal";
|
||||
import { deriveGateKey, readCookie, signGateToken, userAgentHash, verifyGateToken } from "./cookie";
|
||||
import { GATE_COOKIE, STATUS_PATH, VERIFY_PATH, gateTtlSeconds, type Deps, type Env } from "./env";
|
||||
import { renderGatePage } from "./gate-page";
|
||||
import { pickGateLang } from "./gate-i18n";
|
||||
import {
|
||||
APP_CSP,
|
||||
BASELINE_HEADERS,
|
||||
LEGAL_CSP,
|
||||
gateCsp,
|
||||
jsonResponse,
|
||||
plainResponse,
|
||||
withSecurityHeaders,
|
||||
} from "./headers";
|
||||
import { evaluateSiteverify, siteverify } from "./turnstile";
|
||||
|
||||
/**
|
||||
* Request routing for ytgenerator.stream.
|
||||
*
|
||||
* `wrangler.jsonc` sends everything except hashed build output and a handful
|
||||
* of public files (icons, robots, security.txt …) through here first:
|
||||
*
|
||||
* /__gate/verify POST: check a Turnstile token, set the gate cookie
|
||||
* /__gate/status 204 if the gate cookie is valid (cookie-blocked check)
|
||||
* /legal, /legal/* the prerendered legal pages — always public, so the
|
||||
* Terms and Privacy Policy can be read before agreeing
|
||||
* everything else gate cookie valid → the file or the SPA shell;
|
||||
* otherwise → the gate page (documents) or 403
|
||||
*/
|
||||
|
||||
const MAX_VERIFY_BODY_BYTES = 8 * 1024;
|
||||
const MAX_TOKEN_LENGTH = 2048;
|
||||
const TERMS_COOKIE_MAX_AGE = 365 * 86_400;
|
||||
|
||||
let warnedMissingSecret = false;
|
||||
|
||||
function hasFileExtension(pathname: string): boolean {
|
||||
const last = pathname.slice(pathname.lastIndexOf("/") + 1);
|
||||
return /\.[A-Za-z0-9]{1,8}$/.test(last);
|
||||
}
|
||||
|
||||
/** Would a browser render this response as a page? */
|
||||
function isDocumentRequest(request: Request, url: URL): boolean {
|
||||
const dest = request.headers.get("Sec-Fetch-Dest");
|
||||
if (dest) return dest === "document" || dest === "iframe";
|
||||
return !hasFileExtension(url.pathname) || url.pathname.endsWith(".html");
|
||||
}
|
||||
|
||||
async function hasValidGateCookie(request: Request, env: Env, nowMs: number): Promise<boolean> {
|
||||
const token = readCookie(request.headers.get("Cookie"), GATE_COOKIE);
|
||||
if (!token) return false;
|
||||
const key = await deriveGateKey(env.TURNSTILE_SECRET);
|
||||
const ua = await userAgentHash(request.headers.get("User-Agent") ?? "");
|
||||
return verifyGateToken(key, token, Math.floor(nowMs / 1000), ua);
|
||||
}
|
||||
|
||||
function acceptedTerms(request: Request): boolean {
|
||||
const raw = readCookie(request.headers.get("Cookie"), TERMS_COOKIE);
|
||||
return raw !== null && /^\d{1,4}$/.test(raw) && Number(raw) >= CURRENT_TERMS_VERSION;
|
||||
}
|
||||
|
||||
async function handleVerify(request: Request, env: Env, deps: Deps, url: URL): Promise<Response> {
|
||||
if (request.method !== "POST") {
|
||||
return plainResponse(405, "Method Not Allowed", { Allow: "POST" });
|
||||
}
|
||||
// Same-origin only: the page that asks for verification is ours.
|
||||
if (request.headers.get("Origin") !== url.origin) {
|
||||
return jsonResponse(403, { ok: false, error: "bad-origin" });
|
||||
}
|
||||
if (!(request.headers.get("Content-Type") ?? "").includes("application/json")) {
|
||||
return jsonResponse(415, { ok: false, error: "bad-content-type" });
|
||||
}
|
||||
const raw = await request.text();
|
||||
if (raw.length > MAX_VERIFY_BODY_BYTES) {
|
||||
return jsonResponse(413, { ok: false, error: "too-large" });
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = JSON.parse(raw);
|
||||
} catch {
|
||||
return jsonResponse(400, { ok: false, error: "bad-json" });
|
||||
}
|
||||
const record = typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
|
||||
const token = record.token;
|
||||
if (typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN_LENGTH) {
|
||||
return jsonResponse(400, { ok: false, error: "bad-token" });
|
||||
}
|
||||
// The gate page only posts once its "I agree" box is ticked (or the visitor
|
||||
// already agreed); the flag is what makes setting `ytg_terms` honest.
|
||||
if (record.consent !== true) {
|
||||
return jsonResponse(400, { ok: false, error: "consent-required" });
|
||||
}
|
||||
|
||||
const nowMs = deps.now();
|
||||
const result = await siteverify(deps.fetch, {
|
||||
secret: env.TURNSTILE_SECRET,
|
||||
token,
|
||||
remoteIp: request.headers.get("CF-Connecting-IP"),
|
||||
idempotencyKey: deps.randomId(),
|
||||
});
|
||||
const verdict = evaluateSiteverify(result, { hostname: url.hostname, nowMs });
|
||||
if (!verdict.ok) {
|
||||
console.warn("gate: verification refused", verdict.reason, result.errorCodes.join(","));
|
||||
return jsonResponse(403, { ok: false, error: verdict.reason });
|
||||
}
|
||||
|
||||
const ttl = gateTtlSeconds(env);
|
||||
const key = await deriveGateKey(env.TURNSTILE_SECRET);
|
||||
const ua = await userAgentHash(request.headers.get("User-Agent") ?? "");
|
||||
const gateToken = await signGateToken(key, Math.floor(nowMs / 1000) + ttl, ua);
|
||||
|
||||
const headers = new Headers();
|
||||
headers.append(
|
||||
"Set-Cookie",
|
||||
`${GATE_COOKIE}=${gateToken}; Path=/; Max-Age=${ttl}; HttpOnly; Secure; SameSite=Lax`,
|
||||
);
|
||||
// Readable by the app on purpose (see TERMS_COOKIE in src/config/legal.ts).
|
||||
headers.append(
|
||||
"Set-Cookie",
|
||||
`${TERMS_COOKIE}=${CURRENT_TERMS_VERSION}; Path=/; Max-Age=${TERMS_COOKIE_MAX_AGE}; Secure; SameSite=Lax`,
|
||||
);
|
||||
return jsonResponse(200, { ok: true }, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* `/legal` → the index page; `/legal/<id>` → that document (`?lang=vi` → its
|
||||
* Vietnamese page, when one exists); anything else under /legal → 404; null
|
||||
* when the path is not a legal path at all.
|
||||
*/
|
||||
export function legalAssetPath(url: URL): string | null {
|
||||
const trimmed = url.pathname.replace(/\/+$/, "");
|
||||
if (trimmed === "/legal") return "/legal/";
|
||||
if (!trimmed.startsWith("/legal/")) return null;
|
||||
const id = /^\/legal\/([a-z-]+)$/.exec(trimmed)?.[1];
|
||||
if (id === undefined || !isLegalDocId(id)) return "/legal/not-found";
|
||||
const hasVietnamese = LEGAL_DOCS.some((doc) => doc.id === id && doc.sourceVi);
|
||||
return url.searchParams.get("lang") === "vi" && hasVietnamese
|
||||
? `/legal/${id}.vi`
|
||||
: `/legal/${id}`;
|
||||
}
|
||||
|
||||
async function serveLegal(request: Request, env: Env, url: URL, assetPath: string) {
|
||||
const assetUrl = new URL(assetPath, url);
|
||||
const res = await env.ASSETS.fetch(new Request(assetUrl, { method: request.method }));
|
||||
return withSecurityHeaders(res, {
|
||||
csp: LEGAL_CSP,
|
||||
cacheControl: res.ok ? "public, max-age=300" : "no-store",
|
||||
});
|
||||
}
|
||||
|
||||
async function serveAppShell(request: Request, env: Env, url: URL): Promise<Response> {
|
||||
// Fetch "/" — not "/index.html", which `html_handling` would answer with a
|
||||
// 307 back to "/", collapsing every deep link onto the home page.
|
||||
const shell = await env.ASSETS.fetch(
|
||||
new Request(new URL("/", url), { method: request.method, headers: request.headers }),
|
||||
);
|
||||
return withSecurityHeaders(shell, { csp: APP_CSP, cacheControl: "no-cache", varyCookie: true });
|
||||
}
|
||||
|
||||
/** Pass a file through, adding the headers `_headers` would have added. */
|
||||
async function serveFile(request: Request, env: Env): Promise<Response> {
|
||||
const res = await env.ASSETS.fetch(request);
|
||||
const headers = new Headers(res.headers);
|
||||
for (const [name, value] of Object.entries(BASELINE_HEADERS)) headers.set(name, value);
|
||||
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
||||
}
|
||||
|
||||
function serveGate(request: Request, env: Env, deps: Deps, url: URL): Response {
|
||||
const nonce = deps.randomId().replace(/[^A-Za-z0-9]/g, "");
|
||||
const html = renderGatePage({
|
||||
lang: pickGateLang(request.headers.get("Accept-Language")),
|
||||
nonce,
|
||||
siteKey: env.TURNSTILE_SITE_KEY,
|
||||
returning: acceptedTerms(request),
|
||||
origin: url.origin,
|
||||
hours: Math.round(gateTtlSeconds(env) / 3600),
|
||||
});
|
||||
const res = new Response(request.method === "HEAD" ? null : html, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
return withSecurityHeaders(res, {
|
||||
csp: gateCsp(nonce),
|
||||
cacheControl: "no-store",
|
||||
varyCookie: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleRequest(request: Request, env: Env, deps: Deps): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === VERIFY_PATH) {
|
||||
if (!env.TURNSTILE_SECRET) return jsonResponse(503, { ok: false, error: "not-configured" });
|
||||
return handleVerify(request, env, deps, url);
|
||||
}
|
||||
|
||||
const method = request.method;
|
||||
if (method !== "GET" && method !== "HEAD") {
|
||||
return plainResponse(405, "Method Not Allowed", { Allow: "GET, HEAD" });
|
||||
}
|
||||
|
||||
const legal = legalAssetPath(url);
|
||||
if (legal !== null) return serveLegal(request, env, url, legal);
|
||||
|
||||
// A missing secret is a deployment mistake, not an attack: keep the site
|
||||
// reachable (the app still shows its own consent screen) and say so loudly
|
||||
// in the Worker logs instead of locking every visitor out.
|
||||
if (!env.TURNSTILE_SECRET) {
|
||||
if (!warnedMissingSecret) {
|
||||
console.error("gate: TURNSTILE_SECRET is not set — serving without the Turnstile gate");
|
||||
warnedMissingSecret = true;
|
||||
}
|
||||
return hasFileExtension(url.pathname)
|
||||
? serveFile(request, env)
|
||||
: serveAppShell(request, env, url);
|
||||
}
|
||||
|
||||
const passed = await hasValidGateCookie(request, env, deps.now());
|
||||
|
||||
if (url.pathname === STATUS_PATH) {
|
||||
return new Response(null, {
|
||||
status: passed ? 204 : 401,
|
||||
headers: { "Cache-Control": "no-store", ...BASELINE_HEADERS },
|
||||
});
|
||||
}
|
||||
|
||||
if (passed) {
|
||||
return hasFileExtension(url.pathname)
|
||||
? serveFile(request, env)
|
||||
: serveAppShell(request, env, url);
|
||||
}
|
||||
|
||||
if (!isDocumentRequest(request, url)) return plainResponse(403, "Forbidden");
|
||||
return serveGate(request, env, deps, url);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { MAX_TOKEN_AGE_SECONDS, SITEVERIFY_URL, TURNSTILE_ACTION } from "./env";
|
||||
|
||||
/** The subset of Turnstile's siteverify response the gate relies on. */
|
||||
export interface SiteverifyResult {
|
||||
success: boolean;
|
||||
hostname?: string;
|
||||
action?: string;
|
||||
challengeTs?: string;
|
||||
errorCodes: string[];
|
||||
/** Cloudflare's dummy test secret answered (local `wrangler dev` only). */
|
||||
testing: boolean;
|
||||
}
|
||||
|
||||
function asStringArray(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
|
||||
}
|
||||
|
||||
/** Narrow siteverify's JSON without trusting its shape. */
|
||||
export function parseSiteverify(json: unknown): SiteverifyResult {
|
||||
if (typeof json !== "object" || json === null) {
|
||||
return { success: false, errorCodes: ["bad-response"], testing: false };
|
||||
}
|
||||
const record = json as Record<string, unknown>;
|
||||
const metadata =
|
||||
typeof record.metadata === "object" && record.metadata !== null
|
||||
? (record.metadata as Record<string, unknown>)
|
||||
: {};
|
||||
return {
|
||||
success: record.success === true,
|
||||
hostname: typeof record.hostname === "string" ? record.hostname : undefined,
|
||||
action: typeof record.action === "string" ? record.action : undefined,
|
||||
challengeTs: typeof record.challenge_ts === "string" ? record.challenge_ts : undefined,
|
||||
errorCodes: asStringArray(record["error-codes"]),
|
||||
testing: metadata.result_with_testing_key === true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Turnstile token server-side. Network and HTTP failures resolve to
|
||||
* `success: false` with an explanatory code rather than throwing, so the
|
||||
* caller has one path to handle.
|
||||
*/
|
||||
export async function siteverify(
|
||||
fetchImpl: typeof fetch,
|
||||
params: { secret: string; token: string; remoteIp: string | null; idempotencyKey: string },
|
||||
): Promise<SiteverifyResult> {
|
||||
const body = new URLSearchParams({
|
||||
secret: params.secret,
|
||||
response: params.token,
|
||||
idempotency_key: params.idempotencyKey,
|
||||
});
|
||||
if (params.remoteIp) body.set("remoteip", params.remoteIp);
|
||||
try {
|
||||
const res = await fetchImpl(SITEVERIFY_URL, { method: "POST", body });
|
||||
if (!res.ok) return { success: false, errorCodes: [`http-${res.status}`], testing: false };
|
||||
return parseSiteverify(await res.json());
|
||||
} catch {
|
||||
return { success: false, errorCodes: ["network-error"], testing: false };
|
||||
}
|
||||
}
|
||||
|
||||
export type VerdictReason =
|
||||
"not-success" | "hostname-mismatch" | "action-mismatch" | "token-too-old" | "missing-timestamp";
|
||||
|
||||
/**
|
||||
* The checks Cloudflare recommends on top of `success`: the token was minted
|
||||
* for this hostname and this action, and it is not older than its 300 s life.
|
||||
*/
|
||||
export function evaluateSiteverify(
|
||||
result: SiteverifyResult,
|
||||
expected: { hostname: string; nowMs: number },
|
||||
): { ok: true } | { ok: false; reason: VerdictReason } {
|
||||
if (!result.success) return { ok: false, reason: "not-success" };
|
||||
// Cloudflare's published test secret (used by `npm run cf:dev`) answers for
|
||||
// "example.com" with no action. Only that secret can produce this flag, so a
|
||||
// production deployment with its real secret is never relaxed.
|
||||
if (!result.testing) {
|
||||
if (result.hostname !== expected.hostname) return { ok: false, reason: "hostname-mismatch" };
|
||||
if (result.action !== TURNSTILE_ACTION) return { ok: false, reason: "action-mismatch" };
|
||||
}
|
||||
const solvedAt = result.challengeTs ? Date.parse(result.challengeTs) : Number.NaN;
|
||||
if (!Number.isFinite(solvedAt)) return { ok: false, reason: "missing-timestamp" };
|
||||
if (expected.nowMs - solvedAt > MAX_TOKEN_AGE_SECONDS * 1000) {
|
||||
return { ok: false, reason: "token-too-old" };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
+33
-3
@@ -8,6 +8,8 @@
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
// Must match the Worker the repository is connected to in the dashboard.
|
||||
"name": "youtube-generator",
|
||||
// The Turnstile gate + security headers in front of the static build.
|
||||
"main": "worker/index.ts",
|
||||
// Keep at or below the date the pinned wrangler's local runtime supports.
|
||||
"compatibility_date": "2026-09-25",
|
||||
|
||||
@@ -21,9 +23,37 @@
|
||||
|
||||
"assets": {
|
||||
"directory": "./dist",
|
||||
// The app uses hash routing, so every navigation lands on `/`; unknown
|
||||
// paths fall back to the app shell, which renders its own 404 page.
|
||||
"not_found_handling": "single-page-application"
|
||||
"binding": "ASSETS",
|
||||
// NOT the SPA fallback: any path excluded from the Worker below would then
|
||||
// get index.html without passing the gate. The Worker serves the app shell
|
||||
// itself for gated routes; misses on public paths get dist/404.html.
|
||||
"not_found_handling": "404-page",
|
||||
// Everything goes through the Worker first, except content-hashed build
|
||||
// output and the public files crawlers, browsers and the manifest fetch
|
||||
// without cookies. Negative patterns win.
|
||||
"run_worker_first": [
|
||||
"/*",
|
||||
"!/assets/*",
|
||||
"!/icons/*",
|
||||
"!/.well-known/*",
|
||||
"!/favicon.svg",
|
||||
"!/favicon.ico",
|
||||
"!/apple-touch-icon.png",
|
||||
"!/og-image.png",
|
||||
"!/manifest.webmanifest",
|
||||
"!/robots.txt",
|
||||
"!/sitemap.xml",
|
||||
"!/theme-init.js",
|
||||
"!/404.html"
|
||||
]
|
||||
},
|
||||
|
||||
"vars": {
|
||||
// Public by design — the widget embeds it in the page. The matching
|
||||
// secret is the dashboard Secret TURNSTILE_SECRET (never committed).
|
||||
"TURNSTILE_SITE_KEY": "0x4AAAAAAFKFAMUx9rQ5H6bQ",
|
||||
// How long a passed check lasts before the gate shows again.
|
||||
"GATE_TTL_SECONDS": "86400"
|
||||
},
|
||||
|
||||
"observability": { "enabled": true }
|
||||
|
||||
Reference in new issue
Block a user