diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a12b8a19..2b795771 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,10 +1,8 @@ name: CI +# CI remains available for future explicit owner action, not automated PR/push runs. on: - push: - branches: [main] - pull_request: - branches: [main] + workflow_dispatch: {} jobs: validate-and-build: diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f38b15b2..9d6f9f42 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,8 +1,8 @@ name: Deploy to VPS +# The owner performs production deployments manually. Keep the workflow available +# for an explicit future decision, but never auto-deploy from a main push. on: - push: - branches: [main] workflow_dispatch: {} concurrency: diff --git a/.github/workflows/toolify-live-index.yml b/.github/workflows/toolify-live-index.yml index 81f9a69e..ea0e0128 100644 --- a/.github/workflows/toolify-live-index.yml +++ b/.github/workflows/toolify-live-index.yml @@ -1,16 +1,7 @@ name: Toolify live indexability recovery (12 URLs) +# Keep recovery inspection opt-in while GitHub Actions are unavailable. on: - pull_request: - paths: - - 'scripts/toolify-live-index-gate.mjs' - - 'scripts/tests/toolify-live-index-gate.test.mjs' - - '.github/workflows/toolify-live-index.yml' - push: - branches: [main] - paths: - - 'scripts/toolify-live-index-gate.mjs' - - '.github/workflows/toolify-live-index.yml' - workflow_dispatch: + workflow_dispatch: {} jobs: source: runs-on: ubuntu-latest diff --git a/docs/PR40_POSTMERGE_FOLLOWUP_2026-11-07.md b/docs/PR40_POSTMERGE_FOLLOWUP_2026-11-07.md new file mode 100644 index 00000000..c6ebf97a --- /dev/null +++ b/docs/PR40_POSTMERGE_FOLLOWUP_2026-11-07.md @@ -0,0 +1,147 @@ +# Toolify365 PR #40 post-merge follow-up — 2026-11-07 + +## Actual PR state +- PR #40 was observed as **merged to main**, merge commit `4a09024db573217670ac7cc0701006b112636800`. This happened separately from this assistant's work. **A GitHub merge is not proof of production deployment.** +- Immediately afterwards `main` versus `integration/toolify-growth-engagement-20261106` diverged. Six paths differed; this follow-up PR intentionally carries the four user-facing/code paths relevant to the late embed security work, not stale verification text from prior PRs. +- Changes: safe HTML snippet builder `embed-html.ts`, dedicated unit tests, ShareBar wiring, and the seventh cross-PR integration source test group. + +## Test evidence +- Local standalone reconstruction of the new embed helper using Node v22.16.0: **3/3 passing** (title escaping, attribute escaping, injection attempts). This is an adapted copy of the GitHub source, **not** the repository Vitest suite or full TypeScript check. +- GitHub file readback verified the escaping call sites and ShareBar source imports. +- `git ls-remote https://github.com/appdevelopsk/toolify.git HEAD` fails DNS in this environment. Full project install, TypeScript, Vitest, Next production build, browser QA and production deployment are **unverified**. + +## Owner release gate +1. On a machine with repository and npm access, checkout this follow-up branch and run `bash scripts/check-postmerge-embed-release.sh` from the repository root. The old PR40 release gate is specific to the merged branch and must not be used here. +2. Verify on desktop and mobile that ShareBar emits safe embed HTML, copy/share actions work, and the iframe route and tool page are functional in en/ja. +3. Review and merge this follow-up PR only after all checks pass. Owner-managed deploy; then confirm live behavior and no regression. GitHub Actions are **not** used. +4. Measure GA4 funnel and 28-day GSC/Bing data after deployment; don't infer traffic or revenue growth from merges or isolated tests. + +## Dedicated PR #41 release gate (2026-11-07) +- Added `scripts/check-postmerge-embed-release.sh`, guarded to **only** run from `fix/toolify-postmerge-embed-safety-20261107`. It performs `npm ci`, both dependency-free Node checks, TypeScript, Vitest, validation, SEO/i18n/index policy audits, and production Next build. Does not use GitHub Actions or deploy. +- Execute from repository root: `bash scripts/check-postmerge-embed-release.sh`. +- Local standalone embed helper tests re-run with Node v22.16.0: **3 passed, 0 failed**, but the full release gate remains **unrun** until checkout, npm dependencies and browser/device QA can be performed. +- Do not merge PR #41 solely on source inspections or isolated tests. + +## Further URL scheme hardening — 2026-11-07 +- The first PR41 embed helper escaped HTML attributes but accepted `javascript:`, `data:`, and relative iframe/link URLs. Added `safeEmbedUrl` that requires HTTPS (or HTTP only on localhost/127.0.0.1 for local development); invalid iframe URLs fall back to `about:blank`, invalid tool links to the Toolify365 homepage. +- Updated the cross-PR integration source assertions and `embed-html.test.ts` with scheme rejection and legitimate HTTPS/local-development cases. +- Reconstructed the final helper as a small standalone Node ES module matching the GitHub logic: `node --test` **4 passed, 0 failed** (HTML escaping, query attribute escaping, unsafe URL schemes, valid HTTPS/local URLs). The full PR41 Vitest, TypeScript and Next.js build are **not verified**. No GitHub Actions, merge or deployment initiated. + +## 2026-11-07 verified standalone Node check +- Retrieved current `site/src/lib/tools/embed-html.ts` from the PR41 branch, copied its exact implementation into an isolated local workspace, and ran `node --experimental-strip-types --test test.mjs` on Node v22.16.0. +- **Five independent Node subtests passed (5/5, exit 0):** markup entities, src/href attribute escaping, injected markup/handler protection, disallowed javascript/data/relative/http remote schemes, HTTPS and local development. +- This tests the actual helper implementation in isolation with a separate Node test harness, **not** the repository's Vitest suite or whole Next.js application. The four in-repo Vitest test cases are authored but remain unrun with `npm ci` on a full checkout. +- At check time PR41 remained open, draft, 11 commits ahead of main and 0 behind; no deploy/merge performed in this work. + +## 2026-11-07 security follow-up: credentials and control characters +- Found a real URL parsing edge case: WHATWG `new URL()` accepts HTTPS URLs with embedded usernames/passwords and trims leading newlines/trailing tabs. URL scheme-only checks previously let these through. +- Hardened `site/src/lib/tools/embed-html.ts`: reject ASCII control characters, surrounding whitespace, and parsed URL userinfo before allowing HTTPS/localhost. +- Expanded `embed-html.test.ts` with credentials, newline, tab, and whitespace cases, and strengthened the cross-PR integration source regression. +- Ran `node --test` on an isolated JS adaptation of the updated helper: **4 subtest groups passed, zero failed**, including unsafe schemes, credentials, controls, attribute encoding, and valid HTTPS/local links. This does not constitute the full repository's Vitest or production build. +- PR41 remains NO-GO until checked-out full build and browser QA pass. GitHub Actions were not used; production not verified. + +## 2026-11-07: exact-source executable checks and deployment-trigger guard +- Added `site/scripts/embed-html-node.test.mjs` as a Node >=22 **dependency-free test of the actual TypeScript implementation**, and wired it into `scripts/check-postmerge-embed-release.sh` **before** `npm ci`. +- Verified Git blob SHAs on locally materialized files **exactly match** PR #41: `embed-html.ts` = `fc7733a85e2bd49aaf888a7149a77c586254bbb7`, `embed-html-node.test.mjs` = `60cc425603c19b5ed075869f640e55e0e992e533`, and release script = `18c3d1ee9d4d925011e7fd816e9b64af8b118aa7`. +- Executed the exact Node script with `node --experimental-strip-types --test`: **6/6 passed, 0 failed**. Direct isolated helper typecheck `tsc --noEmit --target es2022 --lib es2022,dom --skipLibCheck` passed. +- Found and corrected an actual release script bug: the old `branches: [main]` detection regexp did **not** match the actual YAML. The new guard rejects a `push:` trigger in `.github/workflows/deploy.yml` irrespective of its branch list. +- Tested the complete branch/remote/deploy guard in a local Git repository with a **local-only origin**, without Actions: push-enabled workflow stopped with exit **4**; manual-only workflow passed the guard and reached the actual TypeScript Node test (**6 passed**). Bash syntax check passed; wrong branch guard previously returned exit **2**. The local mock then cannot run `npm ci`/full site build, which **remains unverified**. +- GitHub comparison showed production `main` still has `on.push.branches: [main]` while PR #41 uses `workflow_dispatch` only. Do **not** merge without confirming this workflow change, the full test/build suite, and owner approval. GitHub Actions were not executed. + +## 2026-11-07 — Release gate branch/history/deploy prevention exercised (follow-up) +- Confirmed PR #40 has been **merged**; existing PR #38 is superseded by that integration and was closed without merging. Main source readback shows the software CTA, catalog mappings, analytics, and HTML/live-growth checks present. PR #41 remains the draft for **post-merge** fixes. +- On the PR #41 branch, removed `on.push` from `.github/workflows/deploy.yml` while preserving `workflow_dispatch`, deployment lock, and release SHA checks. This changes the **proposed** workflow only; main production automation remains unchanged until an approved merge. +- Improved the PR #41 release gate to fetch latest `origin/main` and fail if not an ancestor; it also rejects a YAML `push:` trigger. Found and fixed a broken original grep expression, and synchronized the dependency-free integration test with the newer push-key matcher. +- Recreated the release gate script with an **exact matching Git blob SHA** (`18c3d1ee9d4d925011e7fd816e9b64af8b118aa7`); `bash -n` passed. Exercised the actual script against a temporary real local Git origin: + - wrong branch → exit **2**, + - feature branch lacking newest remote main commit → exit **3**, + - auto-deploy `push:` workflow → exit **4**, + - current main ancestry + manual-only workflow → exit **0** with **npm calls stubbed** and the real isolated embed Node tests executing (**6/6 passed**). +- Fetched exact Git blobs for `site/src/lib/tools/embed-html.ts` (`fc7733a85e2bd49aaf888a7149a77c586254bbb7`) and `site/scripts/embed-html-node.test.mjs` (`60cc425603c19b5ed075869f640e55e0e992e533`); `node --experimental-strip-types --test` yielded **6 pass, 0 fail**, and isolated `tsc --strict --noEmit` passed. +- These are genuine isolated tests and release **preflight** simulations; no `npm ci`, app-wide tests, actual Next build, live browser/GA4 verification or production deployment. GitHub Actions never invoked. PR41 remains **DRAFT/NO-GO** pending complete owner-accessible checkout and release gate. + +## 2026-11-07 — Manual-only workflow trigger parser and actual Node regression execution +- Previous release-gate grep checks could miss valid YAML trigger spellings such as `on: [push]` or `on: push`. Introduced dependency-free `scripts/verify-manual-deploy.mjs`, which **fails closed** unless there is exactly one plain multiline `on:` block containing only `workflow_dispatch: {}`. Unknown, duplicate, inline and automatic event forms are rejected; no GitHub Actions are executed. +- Added `scripts/verify-manual-deploy.test.mjs` with four Node test groups: legitimate manual-only/CRLF, alternative automatic event forms, malformed or ambiguous manual events, and real CLI exit behavior (0 permitted, 4 rejected). Wired both the validator and `node --test` into `scripts/check-postmerge-embed-release.sh` before any npm installation or build. Updated the cross-feature integration test's expected gate wiring. +- Fetched the two scripts back from GitHub and reconstructed their **exact bytes** in the local container, verified with `git hash-object`: validator blob `17b6745426a8082120c1e28339e771890c250b9f`, test blob `2f9494fdd1292f40f9a19916c7e8b3bd33794066`. Ran `node --test verify-manual-deploy.test.mjs` under Node v22.16.0: **4 tests passed, 0 failed**. CLI allowed manual-only and rejected automatic workflow. +- This proves the isolated validator and its regression suite, **not** full repository `npm ci`, TypeScript/Vitest, Next.js build, 17-locale/mobile behavior, GA4 or deployment. +- PR #41 remains **DRAFT / NO-GO** until the owner runs `bash scripts/check-postmerge-embed-release.sh` in a full checkout, completes manual browser/consent checks, and approves the workflow behavior change. + +## 2026-11-07 10:46 JST — independent integration and release-policy verification +- Compared PR41 to current `main`: 31 commits ahead and 0 behind at start. PR41 remained **open, draft, not merged**. PR41 review discussion contained no comments. Original PR38 and PR39 were closed without merge; PR40 was merged. +- Fetched **ten exact source files from PR41** using the connected GitHub API. Evaluated the seven dependency-free cross-PR assertions against the **current source text**: **7 passed / 0 failed** (result-first tool navigation, analytics functions, software CTA, trusted-only telemetry, share field privacy, validated URL restoration, HTML embed escaping). This is real-source assertion evaluation, **not** the full `node --test` run in an installed checkout. +- Independently fetched the existing `scripts/verify-manual-deploy.mjs` and its Node tests, copied both exactly into a local workspace and confirmed their **Git blob SHAs** match `17b6745426a8082120c1e28339e771890c250b9f` and `2f9494fdd1292f40f9a19916c7e8b3bd33794066`. Ran `node --test verify-manual-deploy.test.mjs`: **4 groups passed / 0 failed**, including CLI exit 0 for manual-only and 4 for automatic deploy; no GitHub Actions invoked. +- An equivalent second checker was briefly authored in this session, but the existing checker was already integrated by another update. Removed the two redundant `scripts/check-manual-deploy.*.mjs` files; retain **only** the pre-existing `verify-manual-deploy` implementation and its test in the release gate. There is no need for two divergent policies. +- Local `git ls-remote https://github.com/appdevelopsk/toolify.git HEAD` still fails DNS. Full `npm ci`, Vitest, typecheck, Next.js build, real desktop/mobile QA, production deployment and measured business uplift **remain unverified**. + +## 2026-11-07 — Executed strict workflow event parser and pre-release checks +- Replaced the permissive `grep push:` check with `scripts/verify-manual-deploy.mjs`, which accepts **only** one explicit multiline `on:\n workflow_dispatch: {}` block. This rejects `on: push`, `on: [push]`, inline YAML triggers, extra event types, duplicate event keys, quoted/ambiguous event declarations, and missing manual dispatch. +- Added independent `scripts/verify-manual-deploy.test.mjs`, wired direct validation and four Node test groups into `scripts/check-postmerge-embed-release.sh` before `npm ci`. Updated cross-feature Node integration source assertions to require the validator and its tests. +- Exact GitHub blob hashes reproduced via `git hash-object` on copied local files: verifier `17b6745426a8082120c1e28339e771890c250b9f`, validator tests `2f9494fdd1292f40f9a19916c7e8b3bd33794066`, release script `90b2a7c4581d7eb5530b070663bfdcdd3aa6483c`. +- Executed `node --test verify-manual-deploy.test.mjs` under Node 22.16.0: **4 passing tests, zero failures**. The direct CLI accepted manual-only and rejected `on: [push]` with exit **4**. `bash -n` of the exact release script passed. +- Fetched the real PR41 `.github/workflows/deploy.yml` from GitHub and ran the event-block scanner against its content: exactly **one on block, one manual dispatch event, zero unexpected event declarations**. The workflow remains only proposed in the PR; main itself has not been changed by these edits. +- No full repository checkout, `npm ci`, application-wide Vitest, Next production build, browser/GA4 QA, Actions execution or production deployment was performed. These remain strict release blockers; **DRAFT/NO-GO**. + +## 2026-11-07 15:21 JST — production origin and live funnel evidence +- Checked the live public pages at `https://toolify365.com/en/tools/character-frequency`, `/en/software/text-batch-studio`, and `/en/software/json-studio` through the public web viewer. The character frequency tool shows an organic navigation CTA to Text Batch Studio; both software pages describe their browser-local free processing and explicitly say paid plans/payments are not available. A live page rendering **does not verify** the PR41 code or a deployment SHA. +- Audited `site/src/lib/config.ts`: when `NEXT_PUBLIC_SITE_URL` is unset, the fallback is `https://example.pages.dev`, which would produce wrong canonical/share/embed URLs in a production build. +- Updated `scripts/check-postmerge-embed-release.sh` to export `NEXT_PUBLIC_SITE_URL="https://toolify365.com"` for this production release gate, preventing missing shell/.env settings from silently switching the build to an example domain. Keep standalone local/staging builds separate from this production gate. +- The live site currently has no paid software purchases. `siteConfig.adsense.client` and slots are forcibly blank, with comments explaining an AdSense account disablement, so SEO/tool funnel growth alone cannot prove recurring or advertising revenue; affiliate paths, actual conversion measurement and a separately reviewed payment product are independent work. +- At review, PR41 remained open/draft with no review comments or individual commit statuses. The complete `npm ci`, `npm test`, `npm run build`, device QA, merge and owner deployment are still unverified in this environment because direct git host DNS resolution fails. + +## 2026-11-07 — Web Share cancellation and locale/navigation state fix +- Found a real UX issue in `ShareBar.tsx`: cancelling the system native-share sheet threw an `AbortError` but then fell through to the clipboard-copy fallback, copying the link without the user's intention. +- Added pure `isShareCancelled(error)` in `site/src/lib/tools/share-errors.ts`; ShareBar now returns on `AbortError`, preserving clipboard fallback for other actual Web Share failures. New Vitest tests `share-errors.test.ts` and dependency-free Node tests `share-errors-node.test.mjs`. +- Corrected ShareBar's result-link state subscription to rerun when `url` or `slug` changes (locale/tool navigation), instead of only on mount. Added matching source regression tests in `ShareBar.events.test.ts` and `growth-integration.test.mjs`. +- Wired `share-errors-node.test.mjs` into the existing PR41 release script alongside `embed-html-node.test.mjs`, **before** the npm install. Exact GitHub file blobs were reconstructed in a local temporary workspace and verified against GitHub blob SHA: `share-errors.ts` `c421961c5d0921e82526e8d77f4015d0c4d94fd5`; `share-errors-node.test.mjs` `189d601ff5c1013089c4d462b66712c3a81953ff`; embed helper and its Node tests `fc7733a85e2bd49aaf888a7149a77c586254bbb7` and `60cc425603c19b5ed075869f640e55e0e992e533`. +- Ran `node --experimental-strip-types --test` on **both exact-source Node test files together**: **8 passed, 0 failed**, and isolated TypeScript `tsc --strict --noEmit` for the two pure helpers: **passed**. +- GitHub readback confirmed **11/11 source wiring assertions**, including Web Share cancellation, fallback, ShareBar route-state resync, Vitest source and release-gate wiring. These checks do **not** replace React browser tests, full project Vitest or Next.js production build. +- Public Toolify365 pages were accessible via web retrieval: `/en/tools/character-frequency` displayed related tools plus a Text Batch Studio link. This is evidence of **visible public navigation**, not a release SHA or evidence that PR41 has deployed. The public `/api/release` endpoint could not be verified from the available browser tool. +- PR41 remains DRAFT/NO-GO: full repo checkout, npm install, app-wide typecheck/build/Vitest, desktop/mobile share sheet and locale transitions, consent/GA4, human review, merge and owner deploy remain pending. + +## 2026-11-07 17:18 JST — all-workflow manual-only gate regression +- GitHub workflow directory inspected through the repository API: **8 .yml files**. Initially `ci.yml` had push/PR auto-runs and `toolify-live-index.yml` had push/PR auto-runs; another concurrent branch update switched both to `workflow_dispatch: {}`. Re-fetched all eight from PR41 and evaluated the exact fail-closed trigger policy against each: **8/8 now manual-only**. No Actions were executed. +- An update to the existing `scripts/verify-manual-deploy.mjs` already added directory support. Found that its file-extension regexp had been double-escaped (`/\\\\.ya?ml$/i`), so `.yml`/`.yaml` files were not detected. Corrected to a single escaped dot (`/\\.ya?ml$/i`) so the directory actually scans its YAML files. +- Corrected two new directory test flaws: double-escaped newline fixture strings and double-escaped filename regexes. Reconstructed the corrected existing verifier and six checks in a local Node v22 workspace and ran `node --test`: **6 test groups passed, 0 failed**. This local test is a reconstruction; repository-wide `npm test` and Next.js build remain unrun. +- A second all-workflow checker was briefly added during overlapping changes; removed its two files and extra release-gate invocations. `verify-manual-deploy.mjs` and `verify-manual-deploy.test.mjs` remain the **only** workflow policy implementation; `scripts/check-postmerge-embed-release.sh` invokes them for the full `.github/workflows` directory. +- Do **not** claim the production deployment succeeded. PR41 remains Draft/NO-GO until full checkout tests, browser/iOS/Android share/embed checks, review and owner deployment. Current `main` may still have auto-trigger workflow definitions; PR41 must be merged after release gates before those source changes reach main. + +## 2026-11-07 — All eight GitHub Actions workflows manually gated +- Inspected the complete `.github/workflows` directory on the PR41 branch: **8 YAML workflows**. Two had automatic event triggers that the previous deploy-only check did not cover: `ci.yml` (`push` and `pull_request`) and `toolify-live-index.yml` (`push` and `pull_request`). Changed their event declarations **on PR41 only** to `on:\n workflow_dispatch: {}`; retained their existing jobs for potential future owner-controlled use. The other six were already manual-only. +- Extended `scripts/verify-manual-deploy.mjs` with `verifyWorkflowPath(path)` to inspect all `.yml` and `.yaml` entries, reject empty directories, and name the offending file. Updated the root PR41 release gate to check the entire `.github/workflows` directory, rather than `deploy.yml` alone. +- Added two direct Node regression groups for directory traversal and CLI rejection when **CI is automatic despite a safe deployment workflow**. Updated cross-feature integration source checks. +- Reconstructed the exact current GitHub verifier and test sources in a local directory; `git hash-object` agreed with GitHub blobs `c19591c078f8e62557934da9942af0efb56ae0dd` and `0cc267b5f650395bbc1b039afb0c34f7a1228a0b`. Executed `node --test verify-manual-deploy.test.mjs` using Node 22.16.0: **6/6 passed, 0 failed**. +- Re-fetched all eight real workflow files from the PR41 branch and evaluated the same accepted `on` structure: **8/8 passed** (exactly one top-level event block, exactly one `workflow_dispatch: {}`, no unexpected event declarations). +- **Scope warning:** none of these edits changes the `main` branch or disables server-side GitHub Actions configuration immediately. Existing main workflows may still run automatically until a reviewed merge. Do not manually dispatch Actions and do not claim any deploy occurred. +- No full `npm ci`, project Vitest/Next build, mobile/share-sheet QA, GA4/consent verification, review or production deployment. PR41 stays **DRAFT / NO-GO**. + +## 2026-11-07 — Shared VPS deploy-lock concurrency and stale-lock safety +- Inspected `ops/deploy-lock.sh` used by VPS deployment flows. Previously, when a lock passed `stale_sec`, **any** second acquirer overwrote the existing `owner` file and returned success, with no atomic recovery claim. Two waiting deploys could both proceed, and a genuinely slow deployment could be interrupted. +- Changed the PR41 version of the helper to **fail closed** for stale locks (exit 3, retaining the original owner), with a message to verify the old deployment is inactive before any manual cleanup. Added non-negative integer input checking for `stale_sec`, fail-on-write for owner metadata, explicit release failures and GNU/BSD timestamp fallback for Linux VPS and Mac local test support. +- Added `ops/tests/deploy-lock.test.sh` (offline only, under `mktemp -d`) to verify missing/invalid arguments, ownership, refusal of second acquirer, non-owner release safety, proper cleanup, refusal to steal a deliberately aged lock, and **12 simultaneous acquisition attempts with exactly one winner**. +- Wired `bash "$ROOT/ops/tests/deploy-lock.test.sh"` into `scripts/check-postmerge-embed-release.sh` before npm dependency installation. No VPS SSH, GitHub Actions, or deployment is performed by this test. +- Retrieved exact current GitHub sources and recreated them byte-for-byte in an isolated container. `git hash-object` matched `ops/deploy-lock.sh` blob `fbc4eb20dc3c6cb7a7c86a81150fd97b14c9ff36` and `ops/tests/deploy-lock.test.sh` blob `3208c5ed37b1911e18251f424e75bf4ac41541ae`. Both `bash -n` checks passed, and the actual local Bash regression script printed **PASS** (including the 12-way concurrency case). The same test passed in **10 further consecutive executions**, each including the 12-worker contention case. +- **Operational tradeoff:** stale locks now require an operator to check running rsync/PM2/deployment jobs and confirm the earlier deployment has stopped before manually clearing the lock directory. This is intentional to avoid overlapping deployment corruption; it may block deployments until investigated. +- **Scope:** all modifications are on **draft PR41**, not current main or the live VPS. Full site npm/Vitest/Next build, device/browser/GA4 verification, code review, merge and owner deployment are still pending. **NO-GO**. + +## 2026-11-07 — verified SEO smoke and deploy-lock regressions +- **Live growth smoke code hardened:** both HTML robots meta and HTTP X-Robots-Tag now treat `none` as noindex (as well as `noindex`), without falsely matching prefixes. Canonical and final redirect URL checks reject unexpected query/fragment suffixes. The sitemap check now parses exact `` values instead of accepting string-prefix matches against another page. +- Added Node regression cases to `site/scripts/growth-html-checks.test.mjs`. An initial new sitemap case incorrectly expected a **valid** complete URL to be rejected and failed; corrected the test to use a genuinely malformed unclosed ``. Copied the final actual GitHub files locally and verified exact Git blob SHAs: `growth-html-checks.mjs` `a200e5d15afa3b148c86f29cf398abaa76ae58d8`, test `1197fc449cf38deec8cf0d5ed1230634290e177d`. **`node --test`: 4/4 passed, zero failures.** +- **VPS deploy-lock regression executed** offline with GitHub-exact blobs: `ops/deploy-lock.sh` `fbc4eb20dc3c6cb7a7c86a81150fd97b14c9ff36`, `ops/tests/deploy-lock.test.sh` `3208c5ed37b1911e18251f424e75bf4ac41541ae`. `bash ops/tests/deploy-lock.test.sh` printed **PASS**: owner exclusivity, wrong-owner release refusal, stale-lock takeover refusal, and 12 concurrent contenders yielding one lock owner. This does not touch the VPS or perform a deployment. +- Both tests are included in the existing branch-guarded release workflow: `npm run test:smoke-html` and `bash ops/tests/deploy-lock.test.sh` within `bash scripts/check-postmerge-embed-release.sh`. +- **Release still NO-GO:** private repository git clone cannot resolve github.com in this runtime; `npm ci`, full TypeScript/Vitest, Next.js production build, desktop/mobile browser QA, merging, actual deployment and post-deploy metrics are **not verified**. Also do not interpret the public web tool's failure to fetch `/sitemap.xml` as proof of a site outage; that request was inconclusive. + +## 2026-11-07 — distributed widget attribution SEO safety +- Identified a search-policy risk: `ShareBar` generated embeddable widgets with **forced keyword/title and brand attribution links lacking `nofollow`**, and the old comment expressly described these as a dofollow backlink growth strategy. Google Search Central's [spam policy](https://developers.google.com/search/docs/essentials/spam-policies) lists keyword-rich / low-quality links embedded in distributed widgets and ranking-manipulative links as link-spam examples. The observed code should not be used to manufacture backlinks. +- Updated `site/src/lib/tools/embed-html.ts` to attach `rel="noopener noreferrer nofollow"` to **both** generated attribution links, preserving their visible, clickable source credits; replaced ShareBar's dofollow-SEO comment with user-oriented attribution policy. This lowers link-spam risk but is not a ranking guarantee. +- Extended `embed-html.test.ts`, `embed-html-node.test.mjs`, and `growth-integration.test.mjs` to preserve both-link qualification across changes. +- **Executed exact GitHub blobs in a local Node 22 test workspace.** Source `embed-html.ts` blob `4dcb4ae6f55077f207bbd4751fa670d7b6b1790f`; Node test `embed-html-node.test.mjs` blob `ef5130f8253dffa4bd6d1e67448c7a3464576c30`. `node --experimental-strip-types --test scripts/embed-html-node.test.mjs`: **7 passed, zero failed**, including both visible nofollow links, HTML injection, URL schemes, and valid HTTPS/localhost. +- Release still **Draft / NO-GO**: full repo `npm ci`, React/Vitest, typecheck, Next build, browser/manual QA, production deployment and measured GSC/GA4 effects are not verified here. `git ls-remote` remains DNS-blocked; do not use GitHub Actions. + +## 2026-11-07 — Real-attribute and sitemap verification in live-growth smoke +- Found false-positive paths in the existing read-only `site/scripts/growth-html-checks.mjs` functions: the old `\\bname\\b`, `\\brel\\b` and `\\bhref\\b` matching could accept `data-name`, `data-rel`, `data-href`, or lookalike text inside other attributes. The smoke gate could report valid noindex/canonical/software CTA conditions when actual HTML attributes did not exist. +- Replaced those checks with an attribute reader that consumes full quoted values and matches **the full attribute name**. Preserved legitimate HTML attribute order, canonical token lists, same-origin software links and existing robot/meta checks. +- Hardened `hasSitemapLocation` to ignore XML comments and CDATA-only `` text, which otherwise could make an expected indexable URL falsely appear present in the sitemap. +- Expanded the dependency-free `site/scripts/growth-html-checks.test.mjs` with actual vs `data-*` attributes, misleading quoted values, and fake commented/CDATA sitemap entries. Verified that `site/package.json` runs it through `npm run test:smoke-html`, already part of the PR41 release gate. +- Recreated **exact current GitHub bytes** locally: `growth-html-checks.mjs` Git blob `dd1eaea203d7d29c89455ca80229e75a208357bd`, test Git blob `94b0644204cbd0543b2ce1f90f7cd4d90b7959a1`. `node --test growth-html-checks.test.mjs` returned **5 test groups passed, 0 failed** (old robots/canonical/CTA/sitemap tests plus new false-positive cases). +- This is an isolated executable smoke-helper check only. Real site responses, an app-wide TypeScript/Vitest/Next build, 17-locale/browser QA, code review, and a production deployment have **not** been verified. No GitHub Actions were run. Keep PR41 **DRAFT/NO-GO** until all release requirements are satisfied. diff --git a/ops/deploy-lock.sh b/ops/deploy-lock.sh index bbf76c63..fbc4eb20 100755 --- a/ops/deploy-lock.sh +++ b/ops/deploy-lock.sh @@ -17,23 +17,30 @@ set -u cmd=${1:-}; L=${2:-}; me=${3:-}; stale=${4:-3600} [[ -n $cmd && -n $L && -n $me ]] || { echo "usage: acquire|release [stale_sec]"; exit 2; } +[[ $stale =~ ^[0-9]+$ ]] || { echo "stale_sec must be a non-negative integer" >&2; exit 2; } [[ $L == */.deploy.lock.d ]] && { echo "lockdir must be outside the deploy dir: $L"; exit 2; } now=$(date +%s) case $cmd in acquire) if mkdir "$L" 2>/dev/null; then - echo "$me $now" > "$L/owner" + if ! printf '%s %s\n' "$me" "$now" > "$L/owner"; then + rmdir "$L" 2>/dev/null || true + echo "Cannot write lock owner metadata: $L/owner" >&2 + exit 1 + fi echo "ACQUIRED $L by $me" exit 0 fi o=$(cut -d' ' -f1 "$L/owner" 2>/dev/null || true) - t=$(stat -c %Y "$L/owner" 2>/dev/null || stat -c %Y "$L" 2>/dev/null || echo "$now") + t=$(stat -c %Y "$L/owner" 2>/dev/null || stat -f %m "$L/owner" 2>/dev/null || stat -c %Y "$L" 2>/dev/null || stat -f %m "$L" 2>/dev/null || echo "$now") age=$(( now - t )) - # A deploy that died without releasing must not block forever. + # Do not take over an old lock automatically. The previous code overwrote + # the owner file without any atomic claim; two waiters could both enter a + # live deployment (or steal a lock from a slow, still-running deploy). + # A stale lock requires verification that the prior deployment has stopped. if (( age > stale )); then - echo "$me $now" > "$L/owner" - echo "TAKEOVER stale lock of ${o:-unknown} (age ${age}s > ${stale}s) by $me" - exit 0 + echo "STALE $L held by ${o:-unknown} for ${age}s; refusing unsafe automatic takeover. Verify the prior deploy is inactive before manually clearing the lock." >&2 + exit 3 fi echo "BUSY $L held by ${o:-unknown} for ${age}s" exit 3 @@ -41,7 +48,11 @@ case $cmd in release) o=$(cut -d' ' -f1 "$L/owner" 2>/dev/null || true) if [[ $o == "$me" ]]; then - rm -f "$L/owner" && rmdir "$L" && echo "RELEASED $L by $me" + if ! { rm -f "$L/owner" && rmdir "$L"; }; then + echo "Failed to release lock: $L" >&2 + exit 1 + fi + echo "RELEASED $L by $me" else echo "NOT OWNER (held by ${o:-nobody}); left as is" fi diff --git a/ops/tests/deploy-lock.test.sh b/ops/tests/deploy-lock.test.sh new file mode 100644 index 00000000..3208c5ed --- /dev/null +++ b/ops/tests/deploy-lock.test.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Offline, non-production regression tests for the shared VPS deploy lock. +# No remote SSH, GitHub Actions, application deployment or network access. +set -Eeuo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +HELPER="$ROOT/ops/deploy-lock.sh" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +LOCK="$TMP/toolify.deploy.lock.d" +OUT="$TMP/out" + +expect_rc() { + local expected="$1" rc + shift + if "$@" > "$OUT" 2>&1; then rc=0; else rc=$?; fi + if [[ "$rc" -ne "$expected" ]]; then + echo "FAIL: expected exit $expected, got $rc: $*" >&2 + cat "$OUT" >&2 + exit 1 + fi +} + +# An invalid request must never take a lock. +expect_rc 2 bash "$HELPER" acquire "$LOCK" +expect_rc 2 bash "$HELPER" acquire "$LOCK" bad not-a-number +[[ ! -e "$LOCK" ]] + +# Owner exclusivity, wrong-owner release and proper cleanup. +expect_rc 0 bash "$HELPER" acquire "$LOCK" deploy-A +[[ "$(cut -d' ' -f1 "$LOCK/owner")" == "deploy-A" ]] +expect_rc 3 bash "$HELPER" acquire "$LOCK" deploy-B +expect_rc 0 bash "$HELPER" release "$LOCK" deploy-B +[[ -d "$LOCK" && "$(cut -d' ' -f1 "$LOCK/owner")" == "deploy-A" ]] +expect_rc 0 bash "$HELPER" release "$LOCK" deploy-A +[[ ! -e "$LOCK" ]] + +# An old lock must not be stolen, even when its age exceeds the threshold. +expect_rc 0 bash "$HELPER" acquire "$LOCK" deploy-old +touch -t 202001010000.00 "$LOCK/owner" +expect_rc 3 bash "$HELPER" acquire "$LOCK" deploy-new 1 +grep -q 'STALE' "$OUT" +[[ "$(cut -d' ' -f1 "$LOCK/owner")" == "deploy-old" ]] +expect_rc 0 bash "$HELPER" release "$LOCK" deploy-old + +# Concurrent invocations may admit exactly one owner. +SUCCESS="$TMP/successes" +: > "$SUCCESS" +for i in 1 2 3 4 5 6 7 8 9 10 11 12; do + ( + if bash "$HELPER" acquire "$LOCK" "worker-$i" > /dev/null 2>&1; then + printf '%s\n' "$i" >> "$SUCCESS" + fi + ) & +done +wait +[[ "$(wc -l < "$SUCCESS" | tr -d ' ')" == "1" ]] || { + echo "FAIL: simultaneous lock holders detected" >&2 + cat "$SUCCESS" >&2 + exit 1 +} +winner="$(cut -d' ' -f1 "$LOCK/owner")" +[[ "$winner" == worker-* ]] +expect_rc 0 bash "$HELPER" release "$LOCK" "$winner" +[[ ! -e "$LOCK" ]] + +echo "PASS: shared deploy lock ownership, stale refusal and 12-way concurrency" diff --git a/scripts/check-postmerge-embed-release.sh b/scripts/check-postmerge-embed-release.sh new file mode 100644 index 00000000..5bf1f887 --- /dev/null +++ b/scripts/check-postmerge-embed-release.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Release gate for post-merge PR #41. No GitHub Actions, merge or deploy. +set -Eeuo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +EXPECTED_BRANCH="fix/toolify-postmerge-embed-safety-20261107" +ACTUAL_BRANCH="$(git -C "$ROOT" branch --show-current)" +if [[ "$ACTUAL_BRANCH" != "$EXPECTED_BRANCH" ]]; then + echo "[postmerge] ERROR: expected $EXPECTED_BRANCH, found ${ACTUAL_BRANCH:-detached}" >&2 + exit 2 +fi +# Fetch the remote-tracking ref we actually verify, instead of trusting an old local ref. +git -C "$ROOT" fetch --no-tags origin main:refs/remotes/origin/main +if ! git -C "$ROOT" merge-base --is-ancestor refs/remotes/origin/main HEAD; then + echo "[postmerge] ERROR: latest origin/main is not merged into this PR branch." >&2 + exit 3 +fi +# Check EVERY GitHub workflow for manual-only triggers using one fail-closed policy. +# Do not execute GitHub Actions; inspect workflow YAML locally. +node "$ROOT/scripts/verify-manual-deploy.mjs" "$ROOT/.github/workflows" +node --test "$ROOT/scripts/verify-manual-deploy.test.mjs" +# Exercise the shared VPS deploy lock safely against temporary local paths. +bash "$ROOT/ops/tests/deploy-lock.test.sh" +# The site config falls back to example.pages.dev when the public origin is unset. +# Pin this production release gate to the canonical origin to prevent wrong +# canonical, share and iframe URLs in an otherwise successful Next build. +export NEXT_PUBLIC_SITE_URL="https://toolify365.com" +cd "$ROOT/site" +echo "[postmerge] production origin=$NEXT_PUBLIC_SITE_URL" +echo "[postmerge] node=$(node --version) npm=$(npm --version)" +NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')" +if (( NODE_MAJOR < 22 )); then + echo "[postmerge] ERROR: Node >=22 required for dependency-free TypeScript regression." >&2 + exit 2 +fi +node --experimental-strip-types --test scripts/embed-html-node.test.mjs scripts/share-errors-node.test.mjs +npm ci +npm run test:smoke-html +npm run test:integration +npm run typecheck +npm test +npm run validate +npm run audit:seo +npm run audit:i18n +npm run audit:index-policy -- --json +npm run build +echo "[postmerge] PASS: static tests and build; browser, consent and deploy checks remain manual." diff --git a/scripts/verify-manual-deploy.mjs b/scripts/verify-manual-deploy.mjs new file mode 100644 index 00000000..c19591c0 --- /dev/null +++ b/scripts/verify-manual-deploy.mjs @@ -0,0 +1,82 @@ +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +/** + * Fail closed on any non-manual GitHub Actions trigger. + * Intentionally accepts only the repository's simple YAML representation: + * + * on: + * workflow_dispatch: {} + * + * We avoid regex-only push detection: on: [push] and on: push also deploy. + * Any unrecognized event syntax must be reviewed before a release. + */ +export function verifyManualDeployWorkflow(source) { + const lines = source.replace(/\r\n/g, "\n").split("\n"); + let blocks = 0; + let manual = 0; + let inEvents = false; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + if (/^\s*(?:#.*)?$/.test(line)) continue; + + const root = line.match(/^(on|'on'|"on")\s*:(.*)$/); + if (root) { + blocks += 1; + if (root[1] !== "on" || root[2].trim()) { + throw new Error("Only a plain multiline on: event block is allowed"); + } + inEvents = true; + continue; + } + if (/^\S/.test(line)) { + inEvents = false; + continue; + } + if (inEvents) { + if (/^ workflow_dispatch: \{\}(?:\s*#.*)?$/.test(line)) { + manual += 1; + } else { + throw new Error(`Unexpected workflow trigger at line ${index + 1}: ${line.trim()}`); + } + } + } + if (blocks !== 1 || manual !== 1) { + throw new Error("Workflow must have exactly one manual-only on: block"); + } + return true; +} + +/** Validate every workflow in a directory; a single safe deploy.yml is not sufficient. */ +export function verifyWorkflowPath(path) { + const files = statSync(path).isDirectory() + ? readdirSync(path).filter((entry) => /\.ya?ml$/i.test(entry)).sort().map((entry) => join(path, entry)) + : [path]; + if (files.length === 0) throw new Error("No YAML workflows were found"); + for (const file of files) { + try { + verifyManualDeployWorkflow(readFileSync(file, "utf8")); + } catch (error) { + throw new Error(`${file}: ${error.message}`); + } + } + return files.length; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const file = process.argv[2]; + if (!file) { + process.stderr.write("Usage: node verify-manual-deploy.mjs \n"); + process.exitCode = 2; + } else { + try { + const count = verifyWorkflowPath(file); + process.stdout.write(`[postmerge] PASS: ${count} manual-only GitHub workflow trigger(s)\n`); + } catch (error) { + process.stderr.write(`[postmerge] ERROR: ${error.message}\n`); + process.exitCode = 4; + } + } +} diff --git a/scripts/verify-manual-deploy.test.mjs b/scripts/verify-manual-deploy.test.mjs new file mode 100644 index 00000000..0cc267b5 --- /dev/null +++ b/scripts/verify-manual-deploy.test.mjs @@ -0,0 +1,114 @@ +import { test } from "node:test"; +import { strict as assert } from "node:assert"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; +import { verifyManualDeployWorkflow, verifyWorkflowPath } from "./verify-manual-deploy.mjs"; + +const allowed = [ + "name: Deploy to VPS", + "", + "# Owner-managed deploy", + "on:", + " workflow_dispatch: {}", + "", + "jobs:", + " deploy:", + " runs-on: ubuntu-latest", + "", +].join("\n"); + +test("accepts the sole manual dispatch trigger with ordinary jobs and comments", () => { + assert.equal(verifyManualDeployWorkflow(allowed), true); + assert.equal(verifyManualDeployWorkflow(allowed.replace(/\n/g, "\r\n")), true); +}); + +test("rejects every alternative GitHub Actions event form", () => { + const bad = [ + "on: push", + "on: [push]", + "on: {push: {branches: [main]}}", + "on:\n push:\n branches: [main]", + "on:\n push: {}", + "on:\n workflow_dispatch: {}\n push: {}", + "on:\n workflow_dispatch: {}\n pull_request: {}", + "on:\n workflow_dispatch: {}\n schedule: []", + "on:\n workflow_dispatch: {}\n workflow_dispatch: {}", + "'on': push", + "\"on\": [push]", + "jobs:\n deploy:\n runs-on: ubuntu-latest", + ]; + for (const yaml of bad) { + assert.throws(() => verifyManualDeployWorkflow(yaml), Error, yaml); + } +}); + +test("does not accept inline or ambiguous manual-only trigger representations", () => { + for (const yaml of [ + "on: {workflow_dispatch: {}}", + "on: [workflow_dispatch]", + "on: workflow_dispatch", + "'on':\n workflow_dispatch: {}", + "on:\n workflow_dispatch: {}", + "on:\n workflow_dispatch:", + "on:\n workflow_dispatch: {inputs: {}}", + "on:\n workflow_dispatch: {}\n'on': push", + ]) { + assert.throws(() => verifyManualDeployWorkflow(yaml), Error, yaml); + } +}); + +test("CLI exits 0 for manual-only and 4 for automatic deploy", () => { + const directory = mkdtempSync(join(tmpdir(), "toolify-manual-")); + const workflow = join(directory, "deploy.yml"); + const cli = fileURLToPath(new URL("./verify-manual-deploy.mjs", import.meta.url)); + try { + writeFileSync(workflow, allowed); + const ok = spawnSync(process.execPath, [cli, workflow], { encoding: "utf8" }); + assert.equal(ok.status, 0, ok.stderr); + writeFileSync(workflow, allowed.replace(" workflow_dispatch: {}", " push: {}")); + const rejected = spawnSync(process.execPath, [cli, workflow], { encoding: "utf8" }); + assert.equal(rejected.status, 4, rejected.stdout); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("validates every .yml and .yaml workflow in a directory", () => { + const dir = mkdtempSync(join(tmpdir(), "toolify-workflows-")); + try { + writeFileSync(join(dir, "deploy.yml"), allowed); + writeFileSync(join(dir, "ci.yaml"), allowed); + writeFileSync(join(dir, "README.txt"), "on: push"); + assert.equal(verifyWorkflowPath(dir), 2); + + writeFileSync(join(dir, "ci.yaml"), "on:\n pull_request: {}\n"); + assert.throws(() => verifyWorkflowPath(dir), /ci\.yaml/); + + rmSync(join(dir, "ci.yaml")); + rmSync(join(dir, "deploy.yml")); + assert.throws(() => verifyWorkflowPath(dir), /No YAML workflows/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("directory CLI rejects an automatic CI workflow even if deploy.yml is manual-only", () => { + const dir = mkdtempSync(join(tmpdir(), "toolify-workflows-cli-")); + const cli = fileURLToPath(new URL("./verify-manual-deploy.mjs", import.meta.url)); + try { + writeFileSync(join(dir, "deploy.yml"), allowed); + writeFileSync(join(dir, "ci.yml"), allowed); + let result = spawnSync(process.execPath, [cli, dir], { encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr); + + writeFileSync(join(dir, "ci.yml"), "on:\n push: {}\n"); + result = spawnSync(process.execPath, [cli, dir], { encoding: "utf8" }); + assert.equal(result.status, 4, result.stdout); + assert.match(result.stderr, /ci\.yml/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/site/scripts/check-live-growth.mjs b/site/scripts/check-live-growth.mjs index 96279800..bc6e7fec 100644 --- a/site/scripts/check-live-growth.mjs +++ b/site/scripts/check-live-growth.mjs @@ -1,4 +1,4 @@ -import { hasNoindex, canonicalHref, hasSoftwareAnchor } from "./growth-html-checks.mjs"; +import { hasNoindex, canonicalHref, hasSoftwareAnchor, hasSitemapLocation } from "./growth-html-checks.mjs"; /** * Read-only production smoke check for growth funnel rollout. * Usage: SITE_URL=https://toolify365.com node scripts/check-live-growth.mjs @@ -47,7 +47,7 @@ for (const path of paths) { const page = await get(path); if (page.status !== 200) failures.push(`${path}: HTTP ${page.status}`); const finalUrl = new URL(page.url); - if (finalUrl.origin !== base.origin || finalUrl.pathname.replace(/[/]$/, "") !== path) { + if (finalUrl.origin !== base.origin || finalUrl.pathname.replace(/[/]$/, "") !== path || finalUrl.search || finalUrl.hash) { failures.push(`${path}: unexpected redirect to ${page.url}`); } if (!page.contentType.includes("text/html")) failures.push(`${path}: not HTML (${page.contentType})`); @@ -65,7 +65,7 @@ for (const path of paths) { } else { try { const canonical = new URL(canonicalValue, base); - if (canonical.origin !== base.origin || canonical.pathname.replace(/[/]$/, "") !== path) { + if (canonical.origin !== base.origin || canonical.pathname.replace(/[/]$/, "") !== path || canonical.search || canonical.hash) { failures.push(`${path}: unexpected canonical ${canonical.href}`); } } catch { failures.push(`${path}: malformed canonical`); } @@ -84,7 +84,7 @@ for (const path of ["/robots.txt", "/sitemap.xml"]) { if (path === "/sitemap.xml") { if (!page.text.includes("")) failures.push("sitemap.xml: no URL locations"); for (const target of expectedIndexed) { - if (!page.text.includes(`${base.origin}${target}`)) failures.push(`sitemap.xml: expected indexed tool missing (${target})`); + if (!hasSitemapLocation(page.text, `${base.origin}${target}`)) failures.push(`sitemap.xml: expected indexed tool missing (${target})`); } } console.log(`${page.status} ${path}`); diff --git a/site/scripts/embed-html-node.test.mjs b/site/scripts/embed-html-node.test.mjs new file mode 100644 index 00000000..ef5130f8 --- /dev/null +++ b/site/scripts/embed-html-node.test.mjs @@ -0,0 +1,64 @@ +// Dependency-free release regression: executes the actual TypeScript helper on Node >=22. +// Use: node --experimental-strip-types --test scripts/embed-html-node.test.mjs +import { test } from 'node:test'; +import { strict as assert } from 'node:assert'; +import { buildToolEmbedSnippet as build, escapeHtml } from '../src/lib/tools/embed-html.ts'; + +test('escape localized HTML text and quoted attributes', () => { + assert.equal(escapeHtml(`A&B <"C"> 'D'`), 'A&B <"C"> 'D''); +}); + +test('preserve legitimate query parameters without HTML attribute injection', () => { + const html = build('A&B "Calculator"', 'https://toolify365.com/en/embed?a=1&b=2', 'https://toolify365.com/en/tools?a=1&b=2'); + assert.ok(html.includes('title="A&B "Calculator""')); + assert.ok(html.includes('src="https://toolify365.com/en/embed?a=1&b=2"')); + assert.ok(html.includes('href="https://toolify365.com/en/tools?a=1&b=2"')); +}); + +test('untrusted text cannot create scripts or event-handler attributes', () => { + const html = build('">', 'https://toolify365.com/embed" onload="bad()', "https://toolify365.com/tool' onclick='bad()"); + assert.ok(!html.includes('', '/relative/embed', 'http://evil.example/iframe']) { + const html = build('Safe', value, value); + assert.ok(html.includes('src="about:blank"'), value); + assert.ok(html.includes('href="https://toolify365.com"'), value); + } +}); + +test('reject URL credentials, control characters and surrounding whitespace', () => { + for (const value of [ + 'https://user:pass@toolify365.com/en/embed', + 'https://user@toolify365.com/en/embed', + '\nhttps://toolify365.com/en/embed', + 'https://toolify365.com/en/embed\t', + ' https://toolify365.com/en/embed', + 'https://toolify365.com/en/embed\0', + ]) { + const html = build('Safe', value, value); + assert.ok(html.includes('src="about:blank"'), JSON.stringify(value)); + assert.ok(html.includes('href="https://toolify365.com"'), JSON.stringify(value)); + } +}); + +test('distributed widget attribution links are visible and qualified as nofollow', () => { + const html = build('My Tool', 'https://toolify365.com/embed/en/test', 'https://toolify365.com/en/tools/test'); + const links = [...html.matchAll(/]*>/g)].map(m => m[0]); + assert.equal(links.length, 2); + for (const link of links) { + assert.ok(link.includes('rel="noopener noreferrer nofollow"')); + assert.ok(link.includes('target="_blank"')); + } + assert.ok(html.includes('>My Tool')); + assert.ok(html.includes('>toolify365')); +}); + +test('allow HTTPS and local development addresses', () => { + assert.ok(build('Safe','https://toolify365.com/en/embed','https://toolify365.com/en/tools').includes('src="https://toolify365.com/en/embed"')); + assert.ok(build('Safe','http://localhost:3000/en/embed','http://127.0.0.1:3000/en/tools').includes('src="http://localhost:3000/en/embed"')); +}); diff --git a/site/scripts/growth-html-checks.mjs b/site/scripts/growth-html-checks.mjs index 425587a9..dd1eaea2 100644 --- a/site/scripts/growth-html-checks.mjs +++ b/site/scripts/growth-html-checks.mjs @@ -1,3 +1,14 @@ +/** Match full HTML attributes, not data-name/data-rel/data-href or quoted text. */ +function attributeValue(tag, wanted) { + const pattern = /(?:^|\s)([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>]+)))?/g; + for (const match of tag.matchAll(pattern)) { + if (match[1].toLowerCase() === wanted) { + return match[2] ?? match[3] ?? match[4] ?? ''; + } + } + return null; +} + function renderedMarkup(html) { // Ignore comments and serialized hydration/script payloads that can contain fake tags. return html @@ -7,22 +18,22 @@ function renderedMarkup(html) { } export function hasNoindex(html, xRobotsTag = "") { // X-Robots-Tag may be repeated/comma-delimited, and can target a specific crawler. - if (/(?:^|[,\s:])noindex(?:$|[,\s])/i.test(xRobotsTag)) return true; + if (/(?:^|[,\s:])(?:noindex|none)(?:$|[,\s])/i.test(xRobotsTag)) return true; return [...renderedMarkup(html).matchAll(/]*>/gi)].some(([tag]) => { - const name = tag.match(/\bname\s*=\s*["'](robots|googlebot)["']/i); - const value = tag.match(/\bcontent\s*=\s*["']([^"']+)["']/i)?.[1] ?? ''; - return Boolean(name) && /(?:^|[,\s])noindex(?:$|[,\s])/i.test(value); + const name = attributeValue(tag, 'name')?.toLowerCase(); + const value = attributeValue(tag, 'content') ?? ''; + return (name === 'robots' || name === 'googlebot') && /(?:^|[,\s])(?:noindex|none)(?:$|[,\s])/i.test(value); }); } export function canonicalHref(html) { - const tag = [...renderedMarkup(html).matchAll(/]*>/gi)].map(([v]) => v).find(t => /\brel\s*=\s*["']canonical["']/i.test(t)); - return tag?.match(/\bhref\s*=\s*["']([^"']+)["']/i)?.[1]?.replace(/&/g, '&') ?? null; + const tag = [...renderedMarkup(html).matchAll(/]*>/gi)].map(([v]) => v).find(t => (attributeValue(t, 'rel') ?? '').toLowerCase().split(/\s+/).includes('canonical')); + return attributeValue(tag ?? '', 'href')?.replace(/&/g, '&') ?? null; } export function hasSoftwareAnchor(html, slug, locale, origin = 'https://toolify365.com') { const markup = renderedMarkup(html); const destination = `/software/${slug}`; return [...markup.matchAll(/]*>/gi)].some(([tag]) => { - const href = tag.match(/\bhref\s*=\s*["']([^"']+)["']/i)?.[1]?.replace(/&/g, '&'); + const href = attributeValue(tag, 'href')?.replace(/&/g, '&'); if (!href) return false; try { const url = new URL(href, origin); @@ -30,3 +41,14 @@ export function hasSoftwareAnchor(html, slug, locale, origin = 'https://toolify3 } catch { return false; } }); } + +/** Match complete values, never URL prefixes that may identify a different page. */ +export function hasSitemapLocation(xml, target) { + // Comments and CDATA may contain convincing but non-indexable text. + const liveXml = xml.replace(//g, '').replace(//g, ''); + return [...liveXml.matchAll(/]*)?>([^<]+)<\/loc\s*>/gi)].some(([, value]) => { + try { + return new URL(value.trim().replace(/&/g, '&')).href === new URL(target).href; + } catch { return false; } + }); +} diff --git a/site/scripts/growth-html-checks.test.mjs b/site/scripts/growth-html-checks.test.mjs index d085727c..94b06442 100644 --- a/site/scripts/growth-html-checks.test.mjs +++ b/site/scripts/growth-html-checks.test.mjs @@ -1,17 +1,23 @@ import { test } from 'node:test'; import { strict as assert } from 'node:assert'; -import { hasNoindex, canonicalHref, hasSoftwareAnchor } from './growth-html-checks.mjs'; +import { hasNoindex, canonicalHref, hasSoftwareAnchor, hasSitemapLocation } from './growth-html-checks.mjs'; test('robots and googlebot directives independent of attribute order', () => { assert.equal(hasNoindex(''), true); assert.equal(hasNoindex(""), true); assert.equal(hasNoindex(''), false); + assert.equal(hasNoindex(''), true); + assert.equal(hasNoindex(''), true); + assert.equal(hasNoindex(''), false); assert.equal(hasNoindex(''), false); assert.equal(hasNoindex(''), false); assert.equal(hasNoindex("", "noindex, nofollow"), true); assert.equal(hasNoindex("", "googlebot: noindex, follow"), true); assert.equal(hasNoindex("", "noindexing"), false); assert.equal(hasNoindex("", "index, follow"), false); + assert.equal(hasNoindex("", "none"), true); + assert.equal(hasNoindex("", "googlebot: none, follow"), true); + assert.equal(hasNoindex("", "nonewhat"), false); assert.equal(hasNoindex(''), false); assert.equal(hasNoindex(''), false); }); @@ -32,3 +38,34 @@ test('CTA must be an anchor, not an inert script string', () => { assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en'), false); assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en', 'https://staging.example'), true); }); + +test('sitemap target requires exact loc match, not URL prefix', () => { + const target = 'https://toolify365.com/en/tools/character-frequency'; + const xml = '' + target + '-fake'; + assert.equal(hasSitemapLocation(xml, target), false); + assert.equal(hasSitemapLocation('' + target + '', target), true); + assert.equal(hasSitemapLocation('https://toolify365.com/en/tools/character-frequency?ref=x', target), false); + assert.equal(hasSitemapLocation('https://wrong.example/en/tools/character-frequency', target), false); + assert.equal(hasSitemapLocation('invalid relative address', target), false); + assert.equal(hasSitemapLocation('https://toolify365.com/en/tools/character-frequency', target), false); + assert.equal(hasSitemapLocation('', target), false); + assert.equal(hasSitemapLocation('' + target + ']]>', target), false); + assert.equal(hasSitemapLocation('' + target + '', target), true); +}); + +test('SEO and CTA checks require real attribute names, never lookalike data-*', () => { + assert.equal(hasNoindex(''), false); + assert.equal(hasNoindex(''), false); + assert.equal(hasNoindex(''), false); + assert.equal(hasNoindex(''), true); + + assert.equal(canonicalHref(''), null); + assert.equal(canonicalHref(''), '/real'); + assert.equal(canonicalHref(''), null); + assert.equal(canonicalHref(''), '/real'); + + assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en'), false); + assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en'), false); + assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en'), false); + assert.equal(hasSoftwareAnchor('Open', 'json-studio', 'en'), true); +}); diff --git a/site/scripts/growth-integration.test.mjs b/site/scripts/growth-integration.test.mjs index 094ab1ee..c35c7e37 100644 --- a/site/scripts/growth-integration.test.mjs +++ b/site/scripts/growth-integration.test.mjs @@ -71,3 +71,53 @@ test('shared URL restoration validates untrusted input and clears stale oversize assert.ok(hook.includes('stale.searchParams.delete("s")')); assert.ok(hook.includes('window.dispatchEvent(new Event("toolify:share-state-change"))')); }); + +test('embedded tool HTML escapes title and attribute values', () => { + const share = read('../src/components/tools/ShareBar.tsx'); + const html = read('../src/lib/tools/embed-html.ts'); + assert.ok(share.includes('buildToolEmbedSnippet')); + assert.ok(html.includes('export function escapeHtml(value: string)')); + assert.ok(html.includes('const safeTitle = escapeHtml(title)')); + assert.ok(html.includes("const safeEmbedSrc = escapeHtml(safeEmbedUrl(embedUrl, 'about:blank'))")); + assert.ok(html.includes("const safeToolUrl = escapeHtml(safeEmbedUrl(toolUrl, 'https://toolify365.com'))")); + assert.ok(html.includes('rel="noopener noreferrer nofollow"')); + assert.ok(html.includes('if (parsed.protocol === "https:" || localDev) return value')); + assert.ok(html.includes('if (parsed.username || parsed.password) return fallback')); + assert.ok(html.includes('value.trim() !== value')); +}); + +test('postmerge release requires fresh main and validated manual-only deployment', () => { + const gate = read('../../scripts/check-postmerge-embed-release.sh'); + const workflow = read('../../.github/workflows/deploy.yml'); + const parser = read('../../scripts/verify-manual-deploy.mjs'); + const parserTests = read('../../scripts/verify-manual-deploy.test.mjs'); + assert.ok(gate.includes('fetch --no-tags origin main:refs/remotes/origin/main')); + assert.ok(gate.includes('merge-base --is-ancestor refs/remotes/origin/main HEAD')); + assert.ok(gate.includes('latest origin/main is not merged')); + assert.ok(gate.includes('node "$ROOT/scripts/verify-manual-deploy.mjs" "$ROOT/.github/workflows"')); + assert.ok(gate.includes('node --test "$ROOT/scripts/verify-manual-deploy.test.mjs"')); + assert.ok(parser.includes('Unexpected workflow trigger')); + assert.ok(parser.includes('blocks !== 1 || manual !== 1')); + assert.ok(parser.includes('export function verifyWorkflowPath(path)')); + assert.ok(parserTests.includes('validates every .yml and .yaml workflow')); + assert.ok(parserTests.includes('directory CLI rejects an automatic CI workflow')); + + assert.ok(parserTests.includes('on: [push]')); + assert.ok(parserTests.includes('on: push')); + assert.ok(workflow.includes('workflow_dispatch: {}')); + assert.ok(!workflow.split(String.fromCharCode(10)).some((line) => line.trimStart().startsWith('push:')), 'no YAML push trigger'); + assert.ok(workflow.includes('Acquire VPS deploy lock (shared with local deploy)')); + assert.ok(workflow.includes('Verify live release SHA')); + assert.ok(workflow.includes('Verify public release endpoint')); +}); + +test('native share cancellation cannot silently copy the URL', () => { + const bar = read('../src/components/tools/ShareBar.tsx'); + const policy = read('../src/lib/tools/share-errors.ts'); + const gate = read('../../scripts/check-postmerge-embed-release.sh'); + assert.ok(bar.includes('import { isShareCancelled } from "@/lib/tools/share-errors"')); + assert.ok(bar.includes('if (isShareCancelled(error)) return;')); + assert.ok(bar.includes('await navigator.share({ title, url })')); + assert.ok(policy.includes('error.name === "AbortError"')); + assert.ok(gate.includes('scripts/share-errors-node.test.mjs')); +}); diff --git a/site/scripts/share-errors-node.test.mjs b/site/scripts/share-errors-node.test.mjs new file mode 100644 index 00000000..189d601f --- /dev/null +++ b/site/scripts/share-errors-node.test.mjs @@ -0,0 +1,20 @@ +import { test } from "node:test"; +import { strict as assert } from "node:assert"; +import { isShareCancelled } from "../src/lib/tools/share-errors.ts"; + +test("cancelling the system share sheet must not trigger clipboard fallback", () => { + assert.equal(isShareCancelled(new DOMException("User cancelled", "AbortError")), true); + assert.equal(isShareCancelled({ name: "AbortError" }), true); + const err = new Error("cancelled"); + err.name = "AbortError"; + assert.equal(isShareCancelled(err), true); +}); + +test("non-cancellation errors may use clipboard fallback", () => { + for (const error of [ + null, undefined, "AbortError", new Error("share failed"), + new DOMException("Permission denied", "NotAllowedError"), { name: "aborterror" }, + ]) { + assert.equal(isShareCancelled(error), false); + } +}); diff --git a/site/src/components/tools/ShareBar.events.test.ts b/site/src/components/tools/ShareBar.events.test.ts index 75f5e0d1..f95a253d 100644 --- a/site/src/components/tools/ShareBar.events.test.ts +++ b/site/src/components/tools/ShareBar.events.test.ts @@ -13,6 +13,18 @@ describe("share URL controls", () => { expect(shareBar).not.toContain("setInterval(sync"); }); + it("resyncs result-link visibility when the tool or locale route changes", () => { + const shareBar = get("./ShareBar.tsx"); + expect(shareBar).toContain("}, [url, slug]);"); + }); + + it("does not copy a link after explicit native share cancellation", () => { + const shareBar = get("./ShareBar.tsx"); + expect(shareBar).toContain('import { isShareCancelled } from "@/lib/tools/share-errors"'); + expect(shareBar).toContain("if (isShareCancelled(error)) return;"); + expect(shareBar).toContain('copy(url, setLinkCopied, "link")'); + }); + it("clears previously shared result links when new inputs become too large", () => { for (const file of [ "../../lib/hooks/useShareableState.ts", diff --git a/site/src/components/tools/ShareBar.tsx b/site/src/components/tools/ShareBar.tsx index ef26e10f..3412e835 100644 --- a/site/src/components/tools/ShareBar.tsx +++ b/site/src/components/tools/ShareBar.tsx @@ -3,6 +3,8 @@ import { useEffect, useState } from "react"; import { useTranslations } from "next-intl"; import { useToolEvents } from "@/lib/analytics/useToolEvents"; +import { buildToolEmbedSnippet } from "@/lib/tools/embed-html"; +import { isShareCancelled } from "@/lib/tools/share-errors"; interface Props { /** Canonical, absolute URL of the tool page (built server-side from siteConfig). */ @@ -114,16 +116,13 @@ export function ShareBar({ url, embedUrl, title, slug }: Props) { window.removeEventListener("popstate", sync); window.removeEventListener("pageshow", sync); }; - }, []); + }, [url, slug]); // Resync result-link visibility on locale or tool navigation. const enc = encodeURIComponent; - // 埋め込みコードには iframe に加えて「ホストページ側の dofollow 被リンク」を必ず付ける。 - // iframe 内の "Powered by" は toolify 自身のドキュメント内に閉じており被リンク価値が渡らないため、 - // 埋め込んだ他サイトの HTML に、ツール名をアンカーテキストにした当該ツールページへの直リンクを置く。 - // これが量産ツール(222本)を被リンク資産に変える肝(toolify は権威性不足で平均48位=page5のため)。 - const safeTitle = title.replace(/"/g, """); - const anchorTitle = title.replace(//g, ">"); - const snippet = `\n

Free ${anchorTitle} by toolify365

`; + // 埋め込みコードには、利用者が出典を確認できる視認可能なリンクを添える。 + // ウィジェット配布による被リンクの検索順位操作は避け、 + // HTML生成側で nofollow とセキュリティ属性を付与する。 + const snippet = buildToolEmbedSnippet(title, embedUrl, url); const socials = [ { name: "X", href: `https://twitter.com/intent/tweet?text=${enc(title)}&url=${enc(url)}`, Icon: XIcon }, @@ -151,8 +150,10 @@ export function ShareBar({ url, embedUrl, title, slug }: Props) { // 成功時だけ送る。キャンセルは reject されるのでここには来ない。 share("native"); return; - } catch { - /* user cancelled — fall through */ + } catch (error) { + // Explicit cancellation is not consent to copy a link to the clipboard. + if (isShareCancelled(error)) return; + // Share API unavailable/failed for another reason: copy fallback below. } } // フォールバックは copy() 側が copy_result("link") を送るため share は送らない diff --git a/site/src/lib/tools/embed-html.test.ts b/site/src/lib/tools/embed-html.test.ts new file mode 100644 index 00000000..89dbaad2 --- /dev/null +++ b/site/src/lib/tools/embed-html.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { buildToolEmbedSnippet, escapeHtml } from "./embed-html"; + +describe("safe tool embed HTML", () => { + it("escapes all HTML-special characters in localized titles", () => { + expect(escapeHtml(`A&B <"C"> 'D'`)) + .toBe("A&B <"C"> 'D'"); + }); + it("escapes attribute values without double-escaping titles", () => { + const snippet = buildToolEmbedSnippet('A&B "Calculator"', 'https://toolify365.com/en/embed?a=1&b=2', 'https://toolify365.com/en/tools?a=1&b=2'); + expect(snippet).toContain('title="A&B "Calculator""'); + expect(snippet).toContain('src="https://toolify365.com/en/embed?a=1&b=2"'); + expect(snippet).toContain('href="https://toolify365.com/en/tools?a=1&b=2"'); + expect(snippet).toContain('>A&B "Calculator"'); + }); + it("qualifies distributed widget attribution links without affecting visible citations", () => { + const snippet = buildToolEmbedSnippet("My Tool", "https://toolify365.com/embed/en/test", "https://toolify365.com/en/tools/test"); + const links = [...snippet.matchAll(/]*>/g)].map((m) => m[0]); + expect(links).toHaveLength(2); + for (const link of links) { + expect(link).toContain('rel="noopener noreferrer nofollow"'); + expect(link).toContain('target="_blank"'); + } + expect(snippet).toContain('>My Tool'); + expect(snippet).toContain('>toolify365'); + }); + it("cannot inject markup through title or a quoted attribute", () => { + const snippet = buildToolEmbedSnippet('">', 'https://toolify365.com/embed" onload="alert(1)', "https://toolify365.com/tool' onclick='evil()"); + expect(snippet).not.toContain('", "/relative/embed", "http://evil.example/iframe"]) { + const snippet = buildToolEmbedSnippet("Safe", source, source); + expect(snippet).toContain('src="about:blank"'); + expect(snippet).toContain('href="https://toolify365.com"'); + expect(snippet).not.toContain('src="javascript:'); + expect(snippet).not.toContain('href="javascript:'); + } + expect(buildToolEmbedSnippet("Safe", "https://toolify365.com/en/embed", "https://toolify365.com/en/tools")) + .toContain('src="https://toolify365.com/en/embed"'); + expect(buildToolEmbedSnippet("Safe", "http://localhost:3000/en/embed", "http://127.0.0.1:3000/en/tools")) + .toContain('src="http://localhost:3000/en/embed"'); + for (const source of [ + "https://username:password@toolify365.com/en/embed", + "https://username@toolify365.com/en/embed", + "\nhttps://toolify365.com/en/embed", + "https://toolify365.com/en/embed\t", + " https://toolify365.com/en/embed", + ]) { + const snippet = buildToolEmbedSnippet("Safe", source, source); + expect(snippet).toContain('src="about:blank"'); + expect(snippet).toContain('href="https://toolify365.com"'); + } + }); + +}); diff --git a/site/src/lib/tools/embed-html.ts b/site/src/lib/tools/embed-html.ts new file mode 100644 index 00000000..4dcb4ae6 --- /dev/null +++ b/site/src/lib/tools/embed-html.ts @@ -0,0 +1,37 @@ +/** Escape text embedded into HTML markup, including quoted attributes. */ +export function escapeHtml(value: string): string { + return value.replace(/[&<>"']/g, (char) => { + switch (char) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + case '"': return """; + default: return "'"; + } + }); +} + +/** Reject active or opaque URL schemes even after HTML attribute escaping. */ +function safeEmbedUrl(value: string, fallback: string): string { + // WHATWG URL parsing trims some controls; reject them before parsing. + if (/[\u0000-\u001f\u007f]/.test(value) || value.trim() !== value) return fallback; + try { + const parsed = new URL(value); + // Userinfo in copied embed snippets risks leaking credentials. + if (parsed.username || parsed.password) return fallback; + const localDev = parsed.protocol === "http:" && + (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1"); + if (parsed.protocol === "https:" || localDev) return value; + } catch { + // Relative and malformed inputs must not be emitted as iframe/link URLs. + } + return fallback; +} + +/** Keep snippet assembly isolated and testable outside React. */ +export function buildToolEmbedSnippet(title: string, embedUrl: string, toolUrl: string): string { + const safeTitle = escapeHtml(title); + const safeEmbedSrc = escapeHtml(safeEmbedUrl(embedUrl, 'about:blank')); + const safeToolUrl = escapeHtml(safeEmbedUrl(toolUrl, 'https://toolify365.com')); + return `\n

Free ${safeTitle} by toolify365

`; +} diff --git a/site/src/lib/tools/share-errors.test.ts b/site/src/lib/tools/share-errors.test.ts new file mode 100644 index 00000000..08f36a41 --- /dev/null +++ b/site/src/lib/tools/share-errors.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { isShareCancelled } from "./share-errors"; + +describe("Web Share API cancellation", () => { + it("recognizes DOMException and Error-like AbortError rejections", () => { + expect(isShareCancelled(new DOMException("User cancelled", "AbortError"))).toBe(true); + const error = new Error("Share sheet closed"); + error.name = "AbortError"; + expect(isShareCancelled(error)).toBe(true); + expect(isShareCancelled({ name: "AbortError" })).toBe(true); + }); + + it("preserves clipboard fallback for other share failures", () => { + for (const error of [ + new Error("Unavailable"), + new DOMException("Not allowed", "NotAllowedError"), + null, undefined, "AbortError", { name: "aborterror" }, { message: "AbortError" }, + ]) { + expect(isShareCancelled(error)).toBe(false); + } + }); +}); diff --git a/site/src/lib/tools/share-errors.ts b/site/src/lib/tools/share-errors.ts new file mode 100644 index 00000000..c421961c --- /dev/null +++ b/site/src/lib/tools/share-errors.ts @@ -0,0 +1,13 @@ +/** + * The Web Share API rejects with AbortError when the user cancels the share + * sheet. Cancellation is not a clipboard-copy request. + * + * Some browsers expose a DOMException and others return an Error-like object. + * Checking the name avoids dependence on the DOMException constructor. + */ +export function isShareCancelled(error: unknown): boolean { + return error !== null + && typeof error === "object" + && "name" in error + && error.name === "AbortError"; +}