From 9e123783a3efd0bb7a8642ce9d62e4aeed1d069f Mon Sep 17 00:00:00 2001 From: Alfon Date: Thu, 29 Oct 2026 11:29:04 +0800 Subject: [PATCH 01/12] 1.6.0: Sieve Pro, open core Sieve Pro is a one-time purchase ($24, sold through Polar) that adds new features on top of Sieve; everything Sieve did before stays free. Like BlockNSFW's Supporter extras, the features are not open source: they live in a private repository checked out at pro-private/ (ignored here), and pro/ holds an empty stand-in for each. Every protection stays in this repository, so a build from it blocks exactly what the store version does. - common/pro.js: the licence check, open source on purpose since it is the one network request Pro makes. It sends the key and the store's organisation id to Polar's public validate endpoint, on entry and about weekly from Settings only. Offline keeps the last answer; only a clear no turns Pro off. The Sieve Pro benefit id is required before anything is sent, because the store is shared with BlockNSFW. - pro/: stand-ins for seal.js, urge.js, streaks.js, settings.js and features.js (which says null). pro/README.md explains. - build-pro.mjs, called by build-chrome.ps1 and build-firefox.ps1: copies pro-private/pro over the stand-ins. A plain build includes Pro when it is checked out; -Zip refuses without it, with uncommitted Pro changes, or while common/pro.js cannot sell yet; -OpenSource leaves it out, and CI now builds that way and asserts the stand-ins shipped. - Hooks that do nothing without Pro: the Guardian gate checks for a running seal first (sealed dialog and emergency key in guardian-prompt.js); the block page hands its category to the urge screen; the popup shows a running seal and tracked streaks; Settings gains a Sieve Pro section (licence box plus the feature groups' markup) that is removed when the build carries no Pro features. - rules/gambling-rules.json now redirects with ?category=gambling, so blocks from the bundled gambling list are counted on the dashboard at last. - PRIVACY.md describes the licence check and declares it; README.md and the 1.6.0 release notes say what Pro is and what stays free. Tests: test/pro-test.mjs (licence, 16) and test/pro-standins-test.mjs (the stand-ins stay empty, pro-private is never tracked, every hook checks Pro is there). Verified in headless Edge from dist/chrome: 38 checks with Pro, and the open-source build with none of it. Firefox lint: 0 errors, 15 warnings (baseline 17) both ways. Not done yet: Sieve Pro's benefit id and checkout link in common/pro.js, and Firefox's data_collection_permissions. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 13 +- .gitignore | 5 + PRIVACY.md | 72 ++++++++-- README.md | 6 + background/service-worker.js | 1 + build-chrome.ps1 | 34 ++++- build-firefox.ps1 | 34 ++++- build-pro.mjs | 116 ++++++++++++++++ common/changelog.js | 13 ++ common/guardian-prompt.js | 122 ++++++++++++++++- common/pro.js | 231 +++++++++++++++++++++++++++++++ manifest.firefox.json | 3 +- manifest.json | 3 +- options/options.css | 177 ++++++++++++++++++++++++ options/options.html | 220 ++++++++++++++++++++++++++++++ options/options.js | 164 ++++++++++++++++++++++ package.json | 5 +- pages/blocked.html | 163 ++++++++++++++++++++++ pages/blocked.js | 16 ++- popup/popup.css | 12 ++ popup/popup.html | 5 + popup/popup.js | 37 +++++ pro/README.md | 26 ++++ pro/features.js | 6 + pro/seal.js | 5 + pro/settings.js | 4 + pro/streaks.js | 4 + pro/urge.js | 4 + rules/gambling-rules.json | 2 +- test/pro-standins-test.mjs | 88 ++++++++++++ test/pro-test.mjs | 254 +++++++++++++++++++++++++++++++++++ 31 files changed, 1817 insertions(+), 28 deletions(-) create mode 100644 build-pro.mjs create mode 100644 common/pro.js create mode 100644 pro/README.md create mode 100644 pro/features.js create mode 100644 pro/seal.js create mode 100644 pro/settings.js create mode 100644 pro/streaks.js create mode 100644 pro/urge.js create mode 100644 test/pro-standins-test.mjs create mode 100644 test/pro-test.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 18cfe87..4d96388 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -37,13 +37,16 @@ jobs: shell: pwsh run: node build-cookie-engine.mjs + # -OpenSource: Sieve Pro lives in a private repository CI cannot see + # (pro/README.md), so CI packages with its empty stand-ins. Every + # protection is in this repository and is built and checked here. - name: Package Chrome build shell: pwsh - run: powershell -ExecutionPolicy Bypass -File .\build-chrome.ps1 -Zip + run: powershell -ExecutionPolicy Bypass -File .\build-chrome.ps1 -Zip -OpenSource - name: Package Firefox build shell: pwsh - run: powershell -ExecutionPolicy Bypass -File .\build-firefox.ps1 -Zip + run: powershell -ExecutionPolicy Bypass -File .\build-firefox.ps1 -Zip -OpenSource - name: Validate expected outputs shell: pwsh @@ -84,12 +87,16 @@ jobs: } # Dev-only trees must never be shipped. - $forbidden = @("node_modules", "src", "vendor", "test", "_metadata") + $forbidden = @("node_modules", "src", "vendor", "test", "_metadata", "pro-private") foreach ($browser in @("chrome", "firefox")) { foreach ($dir in $forbidden) { $p = "dist\$browser\$dir" if (Test-Path $p) { throw "Dev-only path leaked into build: $p" } } + # An open-source build carries Sieve Pro's stand-ins, never Pro. + if (-not (Select-String -Path "dist\$browser\pro\features.js" -SimpleMatch "SieveProFeatures = null" -Quiet)) { + throw "The open-source $browser build carries Sieve Pro, or lost its stand-in" + } } # Each build must carry the correct manifest. diff --git a/.gitignore b/.gitignore index a3d22b8..8878ce5 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,11 @@ store-assets/ # Packaged extension builds produced by build-chrome.ps1 / build-firefox.ps1 dist/ +# Sieve Pro: a separate private repository, checked out here and copied over +# the stand-ins in pro/ by the build (pro/README.md). Never part of this one; +# test/pro-standins-test.mjs fails if anything under it is ever tracked. +/pro-private/ + # Packaged extension artifacts / signing keys — never commit these *.zip *.crx diff --git a/PRIVACY.md b/PRIVACY.md index 72d50fa..2b3be28 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy Policy for Sieve -**Last updated: October 8, 2026** +**Last updated: October 29, 2026** ## The short version @@ -21,8 +21,19 @@ today", so it can compare them on your next visit. It is described [below](#what-the-dark-pattern-blocker-remembers), stays on your device, and can be erased with one button. +There is one exception to "nothing is sent": **Sieve Pro**, the optional one-time +purchase. If you buy it and type in your licence key, that key, and nothing +else, is sent to Polar, the company that sells Sieve Pro for us, to check that +it is valid. That happens when you enter it and about once a week after that, and +only from Sieve's settings page. It is described +[below](#sieve-pro-licence-check). Without Pro, nothing changes. + Sieve is open source, so anyone can verify these claims: - +. The one exception is Sieve Pro's +features (the Seal, the urge screen and streaks), which are not open source. +They make no network requests and keep everything on your device, and the +licence check, the only request Pro makes, is part of the open-source code +(`common/pro.js`), so what it sends can be checked by anyone. --- @@ -43,6 +54,11 @@ third party. | Screen-time tally, **only if you turn Usage Insights on** | Show you where your time goes | Yes | | What a page claimed, while the Dark Pattern Blocker is on | Tell a fake countdown or stock number from a real one on your next visit — see [below](#what-the-dark-pattern-blocker-remembers) | Yes | | Free-trial reminders, **only the ones you ask for** | Remind you before a free trial starts charging — see [below](#free-trial-reminders) | Yes | +| When the block page last stopped each kind of site | One date and time per kind (gambling, dating, games, AI tools, trading, your own blocked sites) and your longest gap, for Sieve Pro's streaks — never the site or its address | Yes | +| Sieve Pro licence key, **only if you enter one** | Turn on the Pro features | Kept on your device; checked with Polar — see [below](#sieve-pro-licence-check) | +| Seal, **only if you start one** | When it ends, and its emergency key stored as a **hash**, never in plain text | Yes | +| Urge screen, **only what you fill in** | Your reason, an optional photo (shrunk to fit 800 pixels), and a contact's name and number or email address, shown on the block page | Yes | +| Streak settings, **only for what you track** | The day you stopped, and what it used to cost you, to count streaks and money kept | Yes | Sieve also reads the content of web pages you visit **in the page itself** — for example, to mask profanity, hide toxic comments, remove dark patterns, or count @@ -107,12 +123,32 @@ what was already measured; **Clear history** is what erases it. This data is never transmitted anywhere, is not used for any purpose other than drawing your own report back to you, and is deleted with the extension. +### Sieve Pro licence check + +Sieve Pro is sold by Polar (polar.sh), who handle the payment, the receipt and +the licence key. Sieve itself never sees your payment details or your email +address. + +When you type a licence key into Sieve's settings, Sieve sends **that key and +Sieve's own shop ID** to Polar's licence service +(`api.polar.sh`) to ask whether it is valid. It asks again about once a week, only +when you open Sieve's settings page, so a refunded key stops working. Nothing +else is sent: not your browsing, not your settings, not anything the Pro features +keep. Polar knows which purchase the key belongs to, because they sold it, and +may see your IP address, as with any web request. + +The key is kept on your device so it can be checked again. **Remove the key from +this browser** in Sieve's settings deletes it. The Pro features themselves (the +Seal, the urge screen and streaks) run entirely on your device, like the rest of +Sieve. + --- ## What Sieve does NOT do - It does **not** create an account or ask you to log in. -- It does **not** collect your name, email, location, or any identifier. +- It does **not** collect your name, email, location, or any identifier. (A Sieve + Pro licence key you type in is sent to Polar to check it, as described above.) - It does **not** upload your browsing history, the URLs you visit, page content, keystrokes, or activity — to us or to anyone else. (If you switch on Usage Insights, a site-name-and-duration tally is kept **on your device**, as @@ -126,7 +162,8 @@ drawing your own report back to you, and is deleted with the extension. ## Network activity (full transparency) Sieve makes outbound network requests only to **download files to your device** — -never to upload anything about you. Specifically: +never to upload anything about you — with the one exception of the Sieve Pro +licence check. Specifically: - **Blocklists** — publicly available lists (for example, known gambling, scam, malware, and phishing domains) are downloaded so protection stays current. @@ -141,8 +178,12 @@ never to upload anything about you. Specifically: optional in-app notice to show (for example, a new feature). It sends no information about you, and if the file is unreachable nothing is shown. You can dismiss any notice permanently. +- **Sieve Pro licence check, only if you enter a licence key** — the key and + Sieve's shop ID are sent to Polar's licence service (`api.polar.sh`) when you + enter it, then about once a week when you open the settings page. See + [above](#sieve-pro-licence-check). -These are all **downloads to your device**. They do not include your identity, your +Apart from that licence check, these are all **downloads to your device**. They do not include your identity, your browsing history, page content, or any personal information beyond the normal network request needed to fetch a file. As with any web request, the host serving a file (a blocklist provider, the model host, GitHub for the announcement, or the @@ -170,17 +211,20 @@ Sieve requests only the permissions needed to filter content locally: ## Chrome Web Store data disclosure In the Chrome Web Store's terms, "collect" means transferring data off the -user's device. Sieve transfers nothing, so it declares that it does **not** -collect any of the following: personally identifiable information, health -information, financial and payment information, authentication information, -personal communications, location, web history, user activity, or website -content. - -To be plain about the three cases where that wording could mislead: if you switch +user's device. The only thing Sieve transfers is a Sieve Pro licence key, if you +enter one, to Polar to check it. Sieve declares that as **authentication +information**, used only to check the licence, never sold, and never used for +anything else. It declares that it does **not** collect any of the following: +personally identifiable information, health information, financial and payment +information, personal communications, location, web history, user activity, or +website content. + +To be plain about the cases where that wording could mislead: if you switch on Usage Insights, a tally of site names and durations is written **to your own browser storage**; the Dark Pattern Blocker writes the numbers described -above under scrambled codes; and a free-trial reminder you ask for keeps that -site's name and dates. You can erase any of them at any time. Nothing about +above under scrambled codes; a free-trial reminder you ask for keeps that +site's name and dates; and Sieve Pro's streaks and urge screen keep what is +listed in the table above. You can erase any of them at any time. Nothing about them is ever sent to us or to a third party, which is why the declaration above is still accurate. diff --git a/README.md b/README.md index e3a1c9d..0064bc9 100644 --- a/README.md +++ b/README.md @@ -187,3 +187,9 @@ licensed under [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/), Sieve elects the CC arm of EasyList's GPLv3 / CC BY-SA 3.0 dual licence; BY-SA's "Collection" clause is what keeps the rest of the project MIT. Editing that one file means editing a BY-SA file — see [`data/ATTRIBUTION-easylist.md`](data/ATTRIBUTION-easylist.md). + +**Sieve Pro** (the Seal, the urge screen and streaks) is not open source and is not in +this repository: [`pro/`](pro/README.md) holds empty stand-ins, and the store versions +of Sieve carry the real files. Every protection is here, so a build from this +repository blocks exactly what the store version does. Build one with +`build-chrome.ps1 -OpenSource` (or `build-firefox.ps1 -OpenSource`). diff --git a/background/service-worker.js b/background/service-worker.js index 1762cc8..4551e15 100644 --- a/background/service-worker.js +++ b/background/service-worker.js @@ -553,6 +553,7 @@ const DOOMSCROLL_CS_FILES = [ "common/doomscroll-sites.js", "common/access-code.js", "common/cooloff.js", + "pro/seal.js", "common/theme.js", "common/guardian-prompt.js", "content/pause-overlay.js", diff --git a/build-chrome.ps1 b/build-chrome.ps1 index e930f84..e062c2a 100644 --- a/build-chrome.ps1 +++ b/build-chrome.ps1 @@ -9,11 +9,23 @@ # engine) so the copied artifacts are guaranteed fresh. Requires # `npm install` to have been run. # -Zip Also produce dist/sieve-chrome.zip. +# -OpenSource +# Build without Sieve Pro, on purpose: pro\ keeps its empty +# stand-ins. What CI builds, and what anyone can build from GitHub. +# -Sandbox With -Zip: a test package whose Pro may use Polar's sandbox. +# Never upload one. +# +# Sieve Pro comes from a private repository checked out at pro-private\ (see +# pro\README.md and build-pro.mjs). A plain build includes it when that +# checkout is there; a store package (-Zip) refuses to build without it, or +# while common\pro.js cannot sell through Polar's live store yet. [CmdletBinding()] param( [switch]$Bundle, - [switch]$Zip + [switch]$Zip, + [switch]$OpenSource, + [switch]$Sandbox ) $ErrorActionPreference = "Stop" @@ -24,6 +36,8 @@ $OutDir = Join-Path $ScriptDir "dist\chrome" $ManifestSrc = Join-Path $SrcDir "manifest.json" $ManifestDst = Join-Path $OutDir "manifest.json" +$ProKind = if ($OpenSource) { "open-source" } elseif ($Zip -and $Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } + # Whole folders copied verbatim into the build. Anything not listed here # (node_modules, src, vendor, cookie-rules-extra, test, _metadata, docs) is # dev-only and never shipped. @@ -37,6 +51,7 @@ $RuntimeFolders = @( "options", "pages", "popup", + "pro", "rules" ) $RuntimeFiles = @( @@ -49,6 +64,7 @@ $RequiredAssets = @( "background\service-worker.js", "background\ad-tracker-stats.js", "background\retired-tracker-blocker.js", + "pro\features.js", "content\cookie-engine.bundle.js", "content\toxic-model.bundle.js", "content\youtube-ads.js", @@ -85,6 +101,11 @@ if ($Bundle) { if ($LASTEXITCODE -ne 0) { throw "build-cookie-engine.mjs failed" } } +# Checked before anything is cleaned, so a refused package leaves dist\ as it was. +Write-Host "==> Checking Sieve Pro ($ProKind build)" -ForegroundColor Cyan +& node (Join-Path $SrcDir "build-pro.mjs") --check $ProKind +if ($LASTEXITCODE -ne 0) { throw "This build cannot be made (see above)." } + Write-Host "==> Cleaning $OutDir" -ForegroundColor Cyan if (Test-Path $OutDir) { Remove-Item -Path $OutDir -Recurse -Force @@ -110,6 +131,10 @@ foreach ($file in $RuntimeFiles) { } } +Write-Host "==> Sieve Pro" -ForegroundColor Cyan +& node (Join-Path $SrcDir "build-pro.mjs") $OutDir $ProKind +if ($LASTEXITCODE -ne 0) { throw "build-pro.mjs failed" } + Write-Host "==> Stripping comments from the packaged JavaScript" -ForegroundColor Cyan # The source is heavily commented on purpose; the package does not need any of # it. This removes comments ONLY - every statement keeps its own line and its @@ -152,4 +177,11 @@ if ($Zip) { } Write-Host "==> Chrome build complete: $OutDir" -ForegroundColor Green +# The stand-in's statement survives comment stripping; the real file's does not exist. +if (Select-String -Path (Join-Path $OutDir "pro\features.js") -SimpleMatch "SieveProFeatures = null" -Quiet) { + Write-Host "==> Sieve Pro: not included" -ForegroundColor Yellow +} else { + Write-Host "==> Sieve Pro: included" -ForegroundColor Green +} +if ($ProKind -eq "sandbox") { Write-Host "==> TEST PACKAGE: Sieve Pro may use Polar's sandbox. Never upload it to a store." -ForegroundColor Yellow } if ($Zip) { Write-Host "==> Zip: $ZipPath" -ForegroundColor Green } diff --git a/build-firefox.ps1 b/build-firefox.ps1 index 51d165f..2de9554 100644 --- a/build-firefox.ps1 +++ b/build-firefox.ps1 @@ -10,11 +10,23 @@ # `npm install` to have been run. # -Zip Also produce dist/sieve-firefox.zip (forward-slash entry paths, # which Firefox / AMO require). +# -OpenSource +# Build without Sieve Pro, on purpose: pro\ keeps its empty +# stand-ins. What CI builds, and what anyone can build from GitHub. +# -Sandbox With -Zip: a test package whose Pro may use Polar's sandbox. +# Never upload one. +# +# Sieve Pro comes from a private repository checked out at pro-private\ (see +# pro\README.md and build-pro.mjs). A plain build includes it when that +# checkout is there; a store package (-Zip) refuses to build without it, or +# while common\pro.js cannot sell through Polar's live store yet. [CmdletBinding()] param( [switch]$Bundle, - [switch]$Zip + [switch]$Zip, + [switch]$OpenSource, + [switch]$Sandbox ) $ErrorActionPreference = "Stop" @@ -25,6 +37,8 @@ $OutDir = Join-Path $ScriptDir "dist\firefox" $ManifestSrc = Join-Path $SrcDir "manifest.firefox.json" $ManifestDst = Join-Path $OutDir "manifest.json" +$ProKind = if ($OpenSource) { "open-source" } elseif ($Zip -and $Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } + # Whole folders copied verbatim into the build. Anything not listed here # (node_modules, src, vendor, cookie-rules-extra, test, _metadata, docs) is # dev-only and never shipped. @@ -37,6 +51,7 @@ $RuntimeFolders = @( "options", "pages", "popup", + "pro", "rules" ) $RuntimeFiles = @( @@ -49,6 +64,7 @@ $RequiredAssets = @( "background\service-worker.js", "background\ad-tracker-stats.js", "background\retired-tracker-blocker.js", + "pro\features.js", "content\cookie-engine.bundle.js", "content\youtube-ads.js", "content\youtube-ads-bridge.js", @@ -84,6 +100,11 @@ if ($Bundle) { if ($LASTEXITCODE -ne 0) { throw "build-cookie-engine.mjs failed" } } +# Checked before anything is cleaned, so a refused package leaves dist\ as it was. +Write-Host "==> Checking Sieve Pro ($ProKind build)" -ForegroundColor Cyan +& node (Join-Path $SrcDir "build-pro.mjs") --check $ProKind +if ($LASTEXITCODE -ne 0) { throw "This build cannot be made (see above)." } + Write-Host "==> Cleaning $OutDir" -ForegroundColor Cyan if (Test-Path $OutDir) { Remove-Item -Path $OutDir -Recurse -Force @@ -109,6 +130,10 @@ foreach ($file in $RuntimeFiles) { } } +Write-Host "==> Sieve Pro" -ForegroundColor Cyan +& node (Join-Path $SrcDir "build-pro.mjs") $OutDir $ProKind +if ($LASTEXITCODE -ne 0) { throw "build-pro.mjs failed" } + Write-Host "==> Removing Chrome-only payload" -ForegroundColor Cyan # content\toxic-model.bundle.js is 638 KB of TensorFlow.js, and its ONLY consumer # is offscreen\toxic-offscreen.html. Firefox has no chrome.offscreen, so that @@ -160,4 +185,11 @@ if ($Zip) { } Write-Host "==> Firefox build complete: $OutDir" -ForegroundColor Green +# The stand-in's statement survives comment stripping; the real file's does not exist. +if (Select-String -Path (Join-Path $OutDir "pro\features.js") -SimpleMatch "SieveProFeatures = null" -Quiet) { + Write-Host "==> Sieve Pro: not included" -ForegroundColor Yellow +} else { + Write-Host "==> Sieve Pro: included" -ForegroundColor Green +} +if ($ProKind -eq "sandbox") { Write-Host "==> TEST PACKAGE: Sieve Pro may use Polar's sandbox. Never upload it to a store." -ForegroundColor Yellow } if ($Zip) { Write-Host "==> Zip: $ZipPath" -ForegroundColor Green } diff --git a/build-pro.mjs b/build-pro.mjs new file mode 100644 index 0000000..ddbc28b --- /dev/null +++ b/build-pro.mjs @@ -0,0 +1,116 @@ +// build-pro.mjs +// Puts Sieve Pro into a build, or deliberately leaves it out. Called twice by +// build-chrome.ps1 and build-firefox.ps1: +// +// node build-pro.mjs --check before dist\ is cleaned, so a +// refused package leaves it as it was +// node build-pro.mjs after the runtime folders are copied +// +// is one of: +// store a package for the stores (-Zip): Pro must be included, from a +// clean pro-private checkout, selling through Polar's live store +// sandbox a test package (-Zip -Sandbox): Pro included, any store mode; +// never upload one +// dev a plain build: Pro included when pro-private is checked out +// open-source without Pro on purpose (-OpenSource): the stand-ins stay +// +// Sieve Pro is not open source. Its files live in a private repository checked +// out at pro-private\ (ignored by this one); pro\ here holds an empty stand-in +// of the same name for each (pro/README.md). Only those names are copied, so +// nothing else in the private repository (its tests, its notes) can reach a +// package. + +import { readFileSync, readdirSync, existsSync, copyFileSync, rmSync, statSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { execFileSync } from "node:child_process"; +import vm from "node:vm"; + +const ROOT = dirname(fileURLToPath(import.meta.url)); +const STANDINS = join(ROOT, "pro"); +const PRIVATE = join(ROOT, "pro-private"); +const REAL = join(PRIVATE, "pro"); +const KINDS = ["store", "sandbox", "dev", "open-source"]; +// Every real file starts by saying it is Sieve Pro; that line is how a real +// file is told from a stand-in. +const MARK = "(Sieve Pro; pro-private/, not open source)"; + +function fail(message) { + console.error(`build-pro: ${message}`); + process.exit(1); +} + +function standInNames() { + return readdirSync(STANDINS).filter((f) => f.endsWith(".js")).sort(); +} + +// The licence settings, read the way the extension reads them. +function proConfig() { + const sandbox = { window: {} }; + vm.runInNewContext(readFileSync(join(ROOT, "common", "pro.js"), "utf8"), sandbox); + return sandbox.window.SievePro.CONFIG; +} + +function checkPrivate(kind) { + if (!existsSync(REAL)) { + if (kind === "store" || kind === "sandbox") { + fail("a store package needs Sieve Pro. Check out the private repository at pro-private\\, or pass -OpenSource to package without it."); + } + return false; + } + const names = standInNames(); + for (const name of readdirSync(REAL).filter((f) => f.endsWith(".js"))) { + if (!names.includes(name)) fail(`pro-private\\pro\\${name} has no stand-in in pro\\, so it would never ship. Add one.`); + } + for (const name of names) { + const real = join(REAL, name); + if (!existsSync(real)) fail(`pro-private\\pro is missing ${name}`); + if (statSync(real).size === 0) fail(`pro-private\\pro\\${name} is empty`); + const text = readFileSync(real, "utf8"); + if (!text.split("\n", 1)[0].includes(MARK)) fail(`pro-private\\pro\\${name} does not start by saying it is Sieve Pro (${MARK})`); + if (text === readFileSync(join(STANDINS, name), "utf8")) fail(`pro-private\\pro\\${name} is only the stand-in`); + } + return true; +} + +function checkStore() { + const c = proConfig(); + const missing = []; + if (c.mode !== "live") missing.push(`mode is "${c.mode}", not "live"`); + if (!c.organizationId) missing.push("no organizationId"); + if (!Array.isArray(c.benefitIds) || c.benefitIds.length === 0) missing.push("no benefitIds"); + if (!c.checkoutUrl) missing.push("no checkoutUrl"); + if (missing.length) fail(`common/pro.js cannot sell Sieve Pro yet: ${missing.join(", ")}. Fill it in from the Polar dashboard, or pass -Sandbox for a test package.`); + + let dirty = ""; + try { + dirty = execFileSync("git", ["status", "--porcelain", "--", "pro"], { cwd: PRIVATE, encoding: "utf8" }); + } catch { + fail("pro-private\\ is not a git checkout, so this package could not be traced to a commit."); + } + if (dirty.trim()) fail(`pro-private\\pro has changes that are not committed:\n${dirty}`); +} + +const args = process.argv.slice(2); + +if (args[0] === "--check") { + const kind = args[1]; + if (!KINDS.includes(kind)) fail(`unknown kind "${kind}"`); + if (kind === "open-source") process.exit(0); + checkPrivate(kind); + if (kind === "store") checkStore(); + process.exit(0); +} + +const [outDir, kind] = args; +if (!outDir || !KINDS.includes(kind)) fail("usage: node build-pro.mjs "); +const outPro = join(outDir, "pro"); +if (!existsSync(outPro)) fail(`${outPro} is missing: is "pro" in the build's runtime folders?`); +rmSync(join(outPro, "README.md"), { force: true }); + +if (kind === "open-source" || !checkPrivate(kind)) { + console.log("Sieve Pro: not included (the stand-ins stay)"); + process.exit(0); +} +for (const name of standInNames()) copyFileSync(join(REAL, name), join(outPro, name)); +console.log(`Sieve Pro: included (${standInNames().join(", ")})`); diff --git a/common/changelog.js b/common/changelog.js index eb014c2..3fc47c4 100644 --- a/common/changelog.js +++ b/common/changelog.js @@ -13,6 +13,19 @@ // =========================================================================== const SIEVE_CHANGELOG = [ + { + version: "1.6.0", + date: "November 2026", + items: [ + "New: Sieve Pro, a one-time purchase with no subscription. Everything Sieve did before stays free, and always will. Pro adds three new things on top, all running on your device like the rest of Sieve.", + "The Seal locks your protection until a date you choose: a week, 30 days, 90 days or a year. Until then nothing that weakens it can be changed, not with your PIN and not by waiting out a cool-off. You get one emergency key, shown once, to print or hand to someone you trust. It is the only way to end a seal early. Extending a seal is always allowed; shortening one is not.", + "The urge screen changes what you see when Sieve stops you at a blocked site. Instead of a notice, the page leads with ninety seconds of breathing, then your own reason in your own words, a photo if you chose one, and one tap to text, call or email someone you trust. Go back and Allow stay underneath, exactly as before.", + "Streaks count the days since you last tried to open a gambling site, a dating site, or any other kind you track, and what it would have cost: “23 days · about $1,140 kept”. They show in the toolbar popup and in settings, with your best run and the next milestone.", + "Sieve Pro is sold by Polar, who send the licence key with your receipt. Entering it sends that key, and nothing else, to Polar to check it, and again about once a week when you open the settings. The privacy policy explains exactly what is sent.", + "If Pro ever ends, for example after a refund, a seal you already started still runs to its date. Losing Pro never weakens your protection.", + "A fix for the Protection Dashboard: blocks from the gambling list built into Sieve were not being counted, only those from the downloaded list.", + ], + }, { version: "1.5.1", date: "October 2026", diff --git a/common/guardian-prompt.js b/common/guardian-prompt.js index d6c17ea..924dfdd 100644 --- a/common/guardian-prompt.js +++ b/common/guardian-prompt.js @@ -12,6 +12,9 @@ // With a cool-off set (common/cooloff.js) the change must first wait it // out: until then the dialog only offers to start or call off the wait, and // resolves false. Once the wait is over, the PIN is asked for as before. +// While a Seal runs (Sieve Pro, pro/seal.js) the change is refused before +// any of that, and only the seal's emergency key — which ends the seal — +// gets through to the cool-off and the PIN. // // SieveGuardian.gateToggleOff(checkbox, actionName) -> Promise // Helper for on/off switches. Returns true if the change may proceed. @@ -271,6 +274,7 @@ cancelBtn.textContent = "Cancel"; codeExpected = ""; cool = null; + seal = null; stage = "pin"; } @@ -356,10 +360,82 @@ } } + // --- seal stage --------------------------------------------------------- + // + // Shown INSTEAD of everything else while a Seal runs. The change is refused; + // the one thing on offer is the emergency key, which ends the seal and hands + // over to the cool-off and the PIN exactly as if there had been no seal. + let seal = null; // { until } while it is showing + + function showSealed(actionName, info) { + const S = window.SieveSeal; + const { title } = codeElements(); + stage = "sealed"; + seal = info; + title.textContent = `Sealed until ${S.formatDay(info.until)}`; + subEl.textContent = actionName || "This change is protected."; + input.hidden = true; + errorEl.hidden = true; + coolEl.hidden = false; + setCoolText([ + "You sealed your protection until ", + { strong: S.formatWhen(info.until) }, + ". Until then nothing that weakens it can be changed — not with your PIN, and not after a cool-off. Only the emergency key ends it early.", + ]); + cancelBtn.textContent = "Use emergency key"; + confirmBtn.textContent = "Close"; + confirmBtn.focus(); + } + + function askForSealKey() { + const { title } = codeElements(); + stage = "sealkey"; + title.textContent = "End the seal early"; + setCoolText([ + "Type the emergency key you were given when the seal started. It ends the whole seal; your PIN and cool-off still apply after it.", + ]); + input.hidden = false; + input.type = "text"; + input.classList.add("code-input"); + input.placeholder = "XXXX-XXXX-XXXX-XXXX-XXXX"; + input.value = ""; + errorEl.hidden = false; + errorEl.textContent = ""; + errorEl.dataset.tone = ""; + cancelBtn.textContent = "Back"; + confirmBtn.textContent = "End the seal"; + input.focus(); + } + + async function sealKeySubmit() { + let ended = false; + try { + ended = await window.SieveSeal.breakWithKey(input.value); + } catch (err) { + console.warn("[Sieve] could not check the emergency key:", err); + } + if (ended) { + finish(true); + return; + } + errorEl.textContent = "That key doesn't match."; + errorEl.dataset.tone = ""; + input.focus(); + } + // The left-hand button: Cancel / Never mind, or — while a request is // waiting — Cancel request, which calls the change off. Always free, since - // it can only keep protection where it is. + // it can only keep protection where it is. On the seal it leads to the + // emergency key and back. async function dismiss() { + if (stage === "sealed") { + askForSealKey(); + return; + } + if (stage === "sealkey") { + showSealed(pending && pending.actionName, seal); + return; + } if (stage === "cooloff" && cool && cool.info.state !== "none") { try { await window.SieveCooloff.cancel(cool.info.key); @@ -371,6 +447,14 @@ } async function submit() { + if (stage === "sealed") { + finish(false); + return; + } + if (stage === "sealkey") { + await sealKeySubmit(); + return; + } if (stage === "cooloff") { await cooloffSubmit(); return; @@ -468,6 +552,34 @@ } } + // The running seal, or null when there is none (or this page did not load + // pro/seal.js, an empty stand-in in an open-source build). A failed read + // goes on without it, as the cool-off does. + async function sealFor() { + const S = window.SieveSeal; + if (!S) return null; + try { + const info = await S.check(); + return info.sealed ? info : null; + } catch (err) { + console.warn("[Sieve] seal check failed, going on without it:", err); + return null; + } + } + + // Resolves true only when the emergency key ended the seal. + function askSealed(actionName, info, critical) { + build(); + if (pending) finish(false); + return new Promise((resolve) => { + pending = { resolve, actionName, critical, cooloffKey: null }; + resetToPinStage(); + raise(); + overlay.hidden = false; + showSealed(actionName, info); + }); + } + function askToWait(actionName, info, critical) { build(); if (pending) finish(false); @@ -487,6 +599,12 @@ async function confirmUnlock(actionName, opts) { const critical = !!(opts && opts.critical); + // A seal comes before everything else: while it runs, nothing that weakens + // protection goes through. Its emergency key ends it, and then the rest of + // the gate runs as usual. + const running = await sealFor(); + if (running && !(await askSealed(actionName, running, critical))) return false; + // The cool-off comes first and does not depend on a PIN: it is the lock // that still works for someone on their own. const cooloff = await cooloffFor(actionName); @@ -536,6 +654,8 @@ // Resolves true when no cool-off applies or the wait is over (using up the // request), false otherwise — so a caller can await it after its PIN check. async function requireCooloff(actionName) { + const running = await sealFor(); + if (running && !(await askSealed(actionName, running, true))) return false; const cooloff = await cooloffFor(actionName); if (!cooloff) return true; if (cooloff.state === "ready") { diff --git a/common/pro.js b/common/pro.js new file mode 100644 index 0000000..ad89782 --- /dev/null +++ b/common/pro.js @@ -0,0 +1,231 @@ +// common/pro.js +// Sieve — Sieve Pro, the one-time purchase that unlocks the Pro features. +// +// Everything Sieve did before Pro stays free. Pro adds new things on top (the +// Seal, the urge screen, streaks), and this module answers one question for all +// of them: has this browser got a valid Pro licence? +// +// This file is open source on purpose, like BlockNSFW's shared/supporter.js: +// it is the one part of Pro that talks to the network, so anyone can read +// exactly what it sends. The features themselves are not open source; store +// builds copy them over the stand-ins in pro/ (pro/README.md). +// +// The licence is a key sold through Polar (polar.sh), which emails it to the +// buyer. It is checked against Polar's public licence endpoint, which needs no +// secret and is made for apps that run on the buyer's own machine. Three +// decisions here are load-bearing: +// +// - The only things ever sent are the key and Sieve's organisation id, and +// only from the settings page: when a key is entered, then at most once a +// week. Never from a website, never from the popup. +// - Being offline is not being refunded. A network error, a timeout or a +// server error keeps whatever was last known; only a clear answer from +// Polar (revoked, disabled, unknown key) turns Pro off. +// - Losing Pro never weakens a protection that is already running. That rule +// lives in each feature (a running Seal is honoured without asking this +// module), but it is why nothing here clears or changes their state. +// +// Like the PIN, this lives in this browser's storage. It is not copy +// protection: anyone can edit an extension's code. The people who pay are the +// honest ones, and this is built for them. + +(() => { + "use strict"; + + if (window.SievePro) return; + + const LICENCE_KEY = "proLicence"; + + // From the Polar dashboard: Monolab's store, the one BlockNSFW's Supporter + // sells through too. `mode` is "sandbox" while testing with Polar's test + // store and "live" for real purchases; a key from one does not open the + // other, and the sandbox has its own organisation and benefit ids. + const CONFIG = { + mode: "live", + organizationId: "354a2f6c-8ea7-46a7-87c5-f97645c12e29", + api: { sandbox: "https://sandbox-api.polar.sh", live: "https://api.polar.sh" }, + // The benefit(s) that grant Sieve Pro. Required: every product in the store + // shares the organisation id, so this is what tells a Sieve Pro key from a + // BlockNSFW one. Until it is set, Pro cannot be activated. + benefitIds: [], + // Without it the settings page hides the Buy button. + checkoutUrl: "", + priceLabel: "$24", + }; + + const DAY = 24 * 60 * 60 * 1000; + const REFRESH_EVERY_MS = 7 * DAY; + const TIMEOUT_MS = 15000; + + // "granted" is the only status that unlocks anything. "invalid" is ours: + // a key Polar does not know, or one for a different product. + const STATUSES = ["granted", "revoked", "disabled", "invalid"]; + + function normalizeLicence(raw) { + if (!raw || typeof raw !== "object") return null; + const key = typeof raw.key === "string" ? raw.key.trim() : ""; + if (!key) return null; + return { + key, + displayKey: typeof raw.displayKey === "string" && raw.displayKey ? raw.displayKey : maskKey(key), + status: STATUSES.includes(raw.status) ? raw.status : "invalid", + benefitId: typeof raw.benefitId === "string" ? raw.benefitId : "", + expiresAt: Number.isFinite(raw.expiresAt) ? raw.expiresAt : null, + checkedAt: Number.isFinite(raw.checkedAt) ? raw.checkedAt : 0, + }; + } + + // "****-E304DA": enough to tell two keys apart, not enough to use one. + function maskKey(key) { + const tail = String(key).replace(/[^A-Za-z0-9]/g, "").slice(-6).toUpperCase(); + return tail ? `****-${tail}` : "****"; + } + + // A pure decision, so it can be tested without storage. + function isProState(licence, now = Date.now()) { + const l = normalizeLicence(licence); + if (!l || l.status !== "granted") return false; + return l.expiresAt === null || now < l.expiresAt; + } + + function isConfigured() { + return !!CONFIG.organizationId && CONFIG.benefitIds.length > 0; + } + + function apiBase() { + return CONFIG.api[CONFIG.mode] || CONFIG.api.live; + } + + async function getLicence() { + const stored = await chrome.storage.local.get(LICENCE_KEY); + return normalizeLicence(stored[LICENCE_KEY]); + } + + async function isPro(now = Date.now()) { + try { + return isProState(await getLicence(), now); + } catch { + return false; + } + } + + // Polar's answer, read into our own shape. + // { ok: true, status, benefitId, displayKey, expiresAt } a clear answer + // { ok: false, offline: true } no clear answer + function readAnswer(body) { + const status = STATUSES.includes(body && body.status) ? body.status : "invalid"; + const benefitId = body && typeof body.benefit_id === "string" ? body.benefit_id : ""; + const wrongProduct = !CONFIG.benefitIds.includes(benefitId); + const expires = body && body.expires_at ? Date.parse(body.expires_at) : NaN; + return { + ok: true, + status: wrongProduct ? "invalid" : status, + benefitId, + displayKey: body && typeof body.display_key === "string" ? body.display_key : "", + expiresAt: Number.isFinite(expires) ? expires : null, + }; + } + + async function validate(key) { + if (!isConfigured()) return { ok: false, offline: true, reason: "not-configured" }; + const controller = typeof AbortController === "function" ? new AbortController() : null; + const timer = controller ? setTimeout(() => controller.abort(), TIMEOUT_MS) : null; + let res; + try { + res = await fetch(`${apiBase()}/v1/customer-portal/license-keys/validate`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ key, organization_id: CONFIG.organizationId }), + credentials: "omit", + cache: "no-store", + signal: controller ? controller.signal : undefined, + }); + } catch { + return { ok: false, offline: true }; + } finally { + if (timer) clearTimeout(timer); + } + + if (res.ok) { + let body = null; + try { + body = await res.json(); + } catch { + return { ok: false, offline: true }; + } + return readAnswer(body); + } + // A 4xx is Polar saying no: an unknown key (404), a malformed one (422), a + // key it will not validate (403). Rate limits and timeouts are not answers. + if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) { + return { ok: true, status: "invalid", benefitId: "", displayKey: "", expiresAt: null }; + } + return { ok: false, offline: true }; + } + + function licenceFrom(key, answer, now) { + return normalizeLicence({ + key, + displayKey: answer.displayKey || maskKey(key), + status: answer.status, + benefitId: answer.benefitId, + expiresAt: answer.expiresAt, + checkedAt: now, + }); + } + + // Enter a key from the settings page. Only a granted key is kept: a mistyped + // one should not replace a good licence already stored. + // { ok: true } Pro is on + // { ok: false, status } Polar said no (status says why) + // { ok: false, offline: true } could not ask; try again later + async function activate(rawKey, now = Date.now()) { + const key = String(rawKey == null ? "" : rawKey).trim(); + if (!key) return { ok: false, status: "invalid" }; + const answer = await validate(key); + if (!answer.ok) return answer; + if (answer.status !== "granted") return { ok: false, status: answer.status }; + if (answer.expiresAt !== null && now >= answer.expiresAt) return { ok: false, status: "revoked" }; + await chrome.storage.local.set({ [LICENCE_KEY]: licenceFrom(key, answer, now) }); + return { ok: true }; + } + + // Re-check a stored licence once it is a week old. A refund shows up here as + // "revoked", which is kept (so the settings page can say what happened) + // rather than deleted. + async function refreshIfDue(now = Date.now()) { + const licence = await getLicence(); + if (!licence) return { checked: false }; + // A clock moved backwards would otherwise postpone the check for as long + // as it was moved; checking early costs nothing. + const age = now - licence.checkedAt; + if (age >= 0 && age < REFRESH_EVERY_MS) return { checked: false }; + const answer = await validate(licence.key); + if (!answer.ok) return { checked: false, offline: true }; + await chrome.storage.local.set({ [LICENCE_KEY]: licenceFrom(licence.key, answer, now) }); + return { checked: true, status: answer.status }; + } + + // Taking the key out is the person's own call and needs no gate: Pro going + // away never weakens a protection that is already running. + async function forget() { + await chrome.storage.local.remove(LICENCE_KEY); + } + + window.SievePro = { + LICENCE_KEY, + CONFIG, + REFRESH_EVERY_MS, + normalizeLicence, + maskKey, + isProState, + isConfigured, + apiBase, + getLicence, + isPro, + validate, + activate, + refreshIfDue, + forget, + }; +})(); diff --git a/manifest.firefox.json b/manifest.firefox.json index 07f3e68..055d7f4 100644 --- a/manifest.firefox.json +++ b/manifest.firefox.json @@ -2,7 +2,7 @@ "manifest_version": 3, "name": "Sieve – Content Filter & Site Blocker", "short_name": "Sieve", - "version": "1.5.1", + "version": "1.6.0", "description": "Clean Internet Suite — blocks gambling, dark patterns, and doomscrolling.", "icons": { "16": "icons/icon-16.png", @@ -95,6 +95,7 @@ "common/doomscroll-sites.js", "common/access-code.js", "common/cooloff.js", + "pro/seal.js", "common/theme.js", "common/guardian-prompt.js", "content/pause-overlay.js", diff --git a/manifest.json b/manifest.json index 88c3761..b0e81e9 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 3, "name": "Sieve – Content Filter & Site Blocker", "short_name": "Sieve", - "version": "1.5.1", + "version": "1.6.0", "description": "Clean Internet Suite — blocks gambling, dark patterns, and doomscrolling.", "icons": { "16": "icons/icon-16.png", @@ -95,6 +95,7 @@ "common/doomscroll-sites.js", "common/access-code.js", "common/cooloff.js", + "pro/seal.js", "common/theme.js", "common/guardian-prompt.js", "content/pause-overlay.js", diff --git a/options/options.css b/options/options.css index fa46ad8..df80e8d 100644 --- a/options/options.css +++ b/options/options.css @@ -2393,3 +2393,180 @@ html.preload .loading-veil { flex: 1 0 calc(100% - 64px); } } + +/* ========================================================================== + Sieve Pro — the licence, the Seal, the urge screen, streaks + ========================================================================== */ + +/* Without a licence the Pro groups stay visible but asleep, with a line in + the margin saying why. As everywhere, nothing is green unless it is on. */ +.pro-feature.is-locked .group-body { + opacity: 0.55; +} + +.pro-note { + margin-top: 10px; + font-family: var(--font-mono); + font-size: 11.5px; + line-height: 1.5; + color: var(--ink-3); +} + +.pro-note a { + color: var(--ink); +} + +/* The Seal's four states each sit in their own box inside one field, so the + field's own spacing rules (.field > .hint) do not reach them. */ +#seal-card .hint { + margin-top: 12px; +} + +.pro-feature .field > .sub-label:first-child { + margin-top: 0; +} + +/* The emergency key: read off the screen once, then off paper. */ +.seal-key { + margin: 0 0 12px; + padding: 14px 16px; + font-family: var(--font-mono); + font-size: 20px; + line-height: 1.4; + letter-spacing: 0.12em; + overflow-wrap: anywhere; + color: var(--ink); + background: var(--raised); + border: 1px dashed var(--rule-strong); + border-radius: var(--r-1); + user-select: all; +} + +.print-only { + display: none; +} + +/* Print sends the key alone: everything else is hidden, and the key's box + is lifted out of the page so nothing around it takes up the sheet. */ +@media print { + html.print-seal-key body * { + visibility: hidden; + } + + html.print-seal-key #seal-key-box, + html.print-seal-key #seal-key-box * { + visibility: visible; + } + + html.print-seal-key #seal-key-box { + position: fixed; + top: 0; + left: 0; + right: 0; + padding: 24px; + } + + html.print-seal-key .print-only { + display: block; + margin-bottom: 16px; + font-size: 13px; + } + + html.print-seal-key .no-print { + display: none; + } +} + +.urge-preview { + display: block; + width: 120px; + height: 120px; + margin-bottom: 4px; + object-fit: cover; + border: 1px solid var(--rule); + border-radius: var(--r-1); +} + +.urge-contact-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1.4fr); + gap: var(--s-2); +} + +.urge-contact-cell .sub-label { + margin-top: 0; +} + +.streak-list { + list-style: none; +} + +.streak-row + .streak-row { + border-top: 1px solid var(--rule); +} + +.streak-list .streak-row:first-child > .switch-row { + padding-top: 0; +} + +.streak-detail { + padding: 0 0 18px; +} + +.streak-figure { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 2px 12px; +} + +.streak-days { + font-family: var(--font-serif); + font-size: 30px; + line-height: 1.15; + letter-spacing: -0.015em; + color: var(--ink); +} + +.streak-kept { + font-size: 14px; + color: var(--ink-2); +} + +.streak-detail > .meta { + margin-top: 2px; +} + +.streak-inputs { + display: flex; + flex-wrap: wrap; + gap: 0 24px; +} + +.streak-cell .sub-label { + margin: 14px 0 6px; +} + +.streak-cell .input[type="date"] { + width: auto; +} + +.streak-cost-row { + display: flex; + flex-wrap: wrap; + gap: var(--s-2); +} + +.streak-cost-row .input { + width: auto; +} + +.streak-cost-row input.input { + width: 7.5rem; +} + +@container (max-width: 560px) { + .urge-contact-row { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/options/options.html b/options/options.html index edfd91f..91fa411 100644 --- a/options/options.html +++ b/options/options.html @@ -70,6 +70,10 @@ 09Lock 10Advanced + + + + diff --git a/options/options.js b/options/options.js index 372d3ad..5fb84db 100644 --- a/options/options.js +++ b/options/options.js @@ -2246,11 +2246,17 @@ function setupLicence(store, onChange) { const activateBtn = document.getElementById("pro-activate"); const errorEl = document.getElementById("pro-error"); const forgetBtn = document.getElementById("pro-forget"); + const forgetError = document.getElementById("pro-forget-error"); + const forgetHint = document.getElementById("pro-forget-hint"); + const portalLink = document.getElementById("pro-portal"); if (P.CONFIG.checkoutUrl) { buyLink.href = P.CONFIG.checkoutUrl; buyActions.hidden = false; } + portalLink.href = P.portalUrl(); + + const CONSENT_MSG = "Firefox asks before Sieve sends the key to Polar to check it. Press Activate again and choose Allow."; function render(raw) { const licence = P.normalizeLicence(raw); @@ -2260,15 +2266,24 @@ function setupLicence(store, onChange) { buyField.hidden = on; ownedField.hidden = !licence; if (!licence) return; + const key = licence.displayKey; if (on) { - ownedText.textContent = `Pro is on, with key ${licence.displayKey}. Thank you for supporting Sieve.`; + const places = licence.limit + ? ` It works in up to ${licence.limit} browsers at once; this one is “${P.deviceLabel()}”.` + : ""; + ownedText.textContent = `Pro is on, with key ${key}.${places} Thank you for supporting Sieve.`; + } else if (licence.status === "removed") { + ownedText.textContent = + `This browser's place on key ${key} was given back, so Pro is off here. ` + + "Enter the key again to take a place back, if one is free."; } else if (licence.status === "revoked" || licence.status === "disabled") { ownedText.textContent = - `Key ${licence.displayKey} was refunded or turned off, so Pro is off. ` + + `Key ${key} was refunded or turned off, so Pro is off. ` + "A seal you already started still runs to its date."; } else { - ownedText.textContent = `Key ${licence.displayKey} is not a Sieve Pro key, so Pro is off.`; + ownedText.textContent = `Key ${key} is not a Sieve Pro key, so Pro is off.`; } + forgetHint.hidden = !(on && licence.activationId); checkedEl.textContent = licence.checkedAt ? `Last checked ${proShortDate(licence.checkedAt)}` : ""; } @@ -2279,11 +2294,14 @@ function setupLicence(store, onChange) { errorEl.textContent = "Paste the licence key from your receipt email."; return; } + // Firefox's question has to come straight from this click, before + // anything else is awaited. Everywhere else it is a yes at once. + const consent = P.askConsent(); activateBtn.disabled = true; activateBtn.textContent = "Checking…"; let result; try { - result = await P.activate(key); + result = (await consent) ? await P.activate(key) : { ok: false, offline: true, reason: "no-consent" }; } catch { result = { ok: false, offline: true }; } @@ -2293,8 +2311,15 @@ function setupLicence(store, onChange) { keyInput.value = ""; // the storage listener below shows the rest } else if (result.reason === "not-configured") { errorEl.textContent = "Sieve Pro is not on sale yet."; + } else if (result.reason === "no-consent") { + errorEl.textContent = CONSENT_MSG; } else if (result.offline) { errorEl.textContent = "Could not reach the licence check. Check your connection and try again."; + } else if (result.status === "full") { + const where = result.limit === 1 ? "one browser" : `${result.limit || "as many"} browsers`; + errorEl.textContent = + `That key is already in ${where}, as many as it allows. Remove it from one of them first: ` + + "in Sieve's settings there, or on your purchases page."; } else if (result.status === "revoked" || result.status === "disabled") { errorEl.textContent = "That key was refunded or turned off."; } else { @@ -2306,8 +2331,25 @@ function setupLicence(store, onChange) { keyInput.addEventListener("keydown", (e) => { if (e.key === "Enter") activate(); }); + // Pro going away weakens no protection, so taking the key out is not gated. - forgetBtn.addEventListener("click", () => P.forget()); + forgetBtn.addEventListener("click", async () => { + forgetError.textContent = ""; + forgetBtn.disabled = true; + let result; + try { + result = await P.release(); + } catch { + result = { ok: false, offline: true }; + } + forgetBtn.disabled = false; + if (!result.ok) { + forgetError.textContent = + result.reason === "no-consent" + ? "Firefox no longer lets Sieve send the key, so this browser keeps its place. Allow it in Firefox's add-on settings, or free the place on your purchases page." + : "Could not reach the licence check, so this browser keeps its place. Try again when you're online."; + } + }); chrome.storage.onChanged.addListener((changes, area) => { if (area !== "local" || !changes[P.LICENCE_KEY]) return; diff --git a/test/pro-test.mjs b/test/pro-test.mjs index 61227f5..3b3064e 100644 --- a/test/pro-test.mjs +++ b/test/pro-test.mjs @@ -4,8 +4,9 @@ // The ways this goes wrong are all unfair to someone: a paying user losing Pro // because their Wi-Fi dropped during the weekly check, a mistyped key wiping a // good licence, a refunded key carrying on for ever, a key for another product -// counting as this one. Polar is replaced by a fake fetch; the real endpoint is -// checked by hand with a sandbox key. +// counting as this one, a browser's place on the key lost because "Remove" +// was pressed offline, or Firefox's consent skipped. Polar is replaced by a +// fake fetch; the real endpoints are checked by hand with a sandbox key. // // node --test test/ @@ -21,7 +22,25 @@ function keysOf(arg) { return Object.keys(arg); } +// The manifest the module reads to know whether it is the Firefox build, and +// the consent Firefox would give. +let manifest = {}; +let consent = { granted: true, answer: true, requests: 0 }; + globalThis.chrome = { + runtime: { getManifest: () => manifest }, + permissions: { + async contains(p) { + assert.deepEqual(p, { data_collection: ["authenticationInfo"] }); + return consent.granted; + }, + async request(p) { + assert.deepEqual(p, { data_collection: ["authenticationInfo"] }); + consent.requests++; + if (consent.answer) consent.granted = true; + return consent.answer; + }, + }, storage: { local: { async get(arg) { @@ -52,91 +71,131 @@ P.CONFIG.benefitIds = ["benefit-pro"]; const DAY = 24 * 3600000; const T0 = Date.UTC(2026, 9, 29, 9, 0, 0); const KEY = "SIEVE-1C285B2D-6CE6-4BC7-B8BE-ADB6A7E304DA"; +const FIREFOX = { + browser_specific_settings: { + gecko: { data_collection_permissions: { required: ["none"], optional: ["authenticationInfo"] } }, + }, +}; -// Every call the module makes, and the answer to give it. +// Every call the module makes, and Polar's answer to each endpoint. let calls = []; -let answer = null; - -function respond(status, body) { - answer = () => ({ - ok: status >= 200 && status < 300, - status, - json: async () => body, - }); -} +let answers = {}; -function goOffline() { - answer = () => { - throw new TypeError("Failed to fetch"); - }; -} +const reply = (status, body = null) => () => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, +}); +const offline = () => () => { + throw new TypeError("Failed to fetch"); +}; globalThis.fetch = async (url, init) => { - calls.push({ url, body: JSON.parse(init.body), credentials: init.credentials }); - return answer(); + const endpoint = url.split("/license-keys/")[1]; + calls.push({ url, endpoint, body: JSON.parse(init.body), credentials: init.credentials }); + const answer = answers[endpoint]; + if (!answer) throw new Error(`unexpected call to ${endpoint}`); + return answer(JSON.parse(init.body)); }; function reset() { backing.clear(); calls = []; - answer = null; + answers = {}; + manifest = {}; + consent = { granted: true, answer: true, requests: 0 }; } -const GRANTED = { status: "granted", benefit_id: "benefit-pro", display_key: "****-E304DA", expires_at: null }; +const GRANTED = { status: "granted", benefit_id: "benefit-pro", display_key: "****-E304DA", expires_at: null, limit_activations: null }; +const LIMITED = { ...GRANTED, limit_activations: 3 }; +const stored = () => backing.get(P.LICENCE_KEY); +const endpoints = () => calls.map((c) => c.endpoint); test("only a granted, unexpired licence is Pro", () => { assert.equal(P.isProState(null, T0), false); assert.equal(P.isProState({ key: KEY, status: "granted" }, T0), true); - assert.equal(P.isProState({ key: KEY, status: "revoked" }, T0), false); - assert.equal(P.isProState({ key: KEY, status: "disabled" }, T0), false); - assert.equal(P.isProState({ key: KEY, status: "something new" }, T0), false); + for (const status of ["revoked", "disabled", "invalid", "removed", "something new"]) { + assert.equal(P.isProState({ key: KEY, status }, T0), false, status); + } assert.equal(P.isProState({ key: "", status: "granted" }, T0), false); assert.equal(P.isProState({ key: KEY, status: "granted", expiresAt: T0 + 1 }, T0), true); assert.equal(P.isProState({ key: KEY, status: "granted", expiresAt: T0 }, T0), false); }); -test("activating sends only the key and the organisation, and keeps a granted key", async () => { +test("no limit: one check, sending only the key and the organisation, and the key is kept", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); assert.deepEqual(await P.activate(` ${KEY} `, T0), { ok: true }); - assert.equal(calls.length, 1); + assert.deepEqual(endpoints(), ["validate"]); assert.match(calls[0].url, /^https:\/\/api\.polar\.sh\/v1\/customer-portal\/license-keys\/validate$/); assert.deepEqual(calls[0].body, { key: KEY, organization_id: "org-test" }); assert.equal(calls[0].credentials, "omit"); - - const stored = backing.get(P.LICENCE_KEY); - assert.equal(stored.key, KEY); - assert.equal(stored.displayKey, "****-E304DA"); - assert.equal(stored.checkedAt, T0); + assert.equal(stored().key, KEY); + assert.equal(stored().displayKey, "****-E304DA"); + assert.equal(stored().activationId, ""); assert.equal(await P.isPro(T0), true); }); -test("a key for another product does not count", async () => { +test("a limit of 3: the key takes one place, named for this browser", async () => { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); + assert.deepEqual(await P.activate(KEY, T0), { ok: true }); + + assert.deepEqual(endpoints(), ["validate", "activate"]); + assert.deepEqual(calls[1].body, { key: KEY, organization_id: "org-test", label: P.deviceLabel() }); + assert.match(P.deviceLabel(), /^Sieve · /); + assert.equal(stored().activationId, "act-1"); + assert.equal(stored().limit, 3); +}); + +test("every place taken: refused, with the limit to say so, nothing kept", async () => { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(403, { error: "NotPermitted" }); + assert.deepEqual(await P.activate(KEY, T0), { ok: false, status: "full", limit: 3 }); + assert.equal(backing.has(P.LICENCE_KEY), false); +}); + +test("the same key entered again here keeps its place instead of taking a second", async () => { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); + await P.activate(KEY, T0); + calls = []; + + assert.deepEqual(await P.activate(KEY, T0 + DAY), { ok: true }); + assert.deepEqual(endpoints(), ["validate"]); + assert.equal(calls[0].body.activation_id, "act-1"); + assert.equal(stored().activationId, "act-1"); +}); + +test("a key for another product does not count (the store is shared with BlockNSFW)", async () => { reset(); - respond(200, { ...GRANTED, benefit_id: "benefit-warden-only" }); + answers.validate = reply(200, { ...GRANTED, benefit_id: "blocknsfw-supporter" }); assert.deepEqual(await P.activate(KEY, T0), { ok: false, status: "invalid" }); assert.equal(backing.has(P.LICENCE_KEY), false); }); test("an unknown or refunded key is refused and does not replace a good one", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); await P.activate(KEY, T0); - respond(404, { error: "ResourceNotFound" }); + answers.validate = reply(404, { error: "ResourceNotFound" }); assert.deepEqual(await P.activate("SIEVE-TYPO", T0 + 1), { ok: false, status: "invalid" }); - respond(200, { ...GRANTED, status: "revoked" }); + answers.validate = reply(200, { ...GRANTED, status: "revoked" }); assert.deepEqual(await P.activate("SIEVE-OTHER", T0 + 2), { ok: false, status: "revoked" }); - assert.equal(backing.get(P.LICENCE_KEY).key, KEY); + assert.equal(stored().key, KEY); assert.equal(await P.isPro(T0 + 3), true); }); test("offline, rate-limited or a server error: no answer, nothing changes", async () => { - for (const setUp of [goOffline, () => respond(500, {}), () => respond(429, {}), () => respond(408, {})]) { + for (const answer of [offline(), reply(500), reply(429), reply(408)]) { reset(); - setUp(); + answers.validate = answer; const result = await P.activate(KEY, T0); assert.equal(result.ok, false); assert.equal(result.offline, true); @@ -146,67 +205,187 @@ test("offline, rate-limited or a server error: no answer, nothing changes", asyn test("an empty key never reaches the network", async () => { reset(); - respond(200, GRANTED); assert.deepEqual(await P.activate(" ", T0), { ok: false, status: "invalid" }); assert.equal(calls.length, 0); }); test("the weekly check runs once a week, not on every page load", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); await P.activate(KEY, T0); calls = []; assert.deepEqual(await P.refreshIfDue(T0 + 6 * DAY), { checked: false }); assert.equal(calls.length, 0); - assert.deepEqual(await P.refreshIfDue(T0 + 7 * DAY), { checked: true, status: "granted" }); assert.equal(calls.length, 1); - assert.equal(backing.get(P.LICENCE_KEY).checkedAt, T0 + 7 * DAY); + assert.equal(stored().checkedAt, T0 + 7 * DAY); }); -test("a dropped connection during the weekly check keeps Pro", async () => { +test("the weekly check asks with this browser's place", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); await P.activate(KEY, T0); - - goOffline(); - assert.deepEqual(await P.refreshIfDue(T0 + 30 * DAY), { checked: false, offline: true }); - assert.equal(await P.isPro(T0 + 30 * DAY), true); + calls = []; + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "granted" }); + assert.equal(calls[0].body.activation_id, "act-1"); }); -test("a refund shows up at the weekly check, and the key is kept to say so", async () => { +test("a place given back on the purchases page reads as removed, not refunded", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); await P.activate(KEY, T0); - respond(200, { ...GRANTED, status: "revoked" }); - assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "revoked" }); + // Asked with the old place: no. Asked without it: the key itself still works. + answers.validate = (body) => (body.activation_id ? reply(404)() : reply(200, LIMITED)()); + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "removed" }); assert.equal(await P.isPro(T0 + 8 * DAY), false); - assert.equal(backing.get(P.LICENCE_KEY).status, "revoked"); - assert.equal(backing.get(P.LICENCE_KEY).key, KEY); + assert.equal(stored().activationId, ""); + + // Entering the key again takes a place back. + answers.activate = reply(200, { id: "act-2" }); + assert.deepEqual(await P.activate(KEY, T0 + 9 * DAY), { ok: true }); + assert.equal(stored().activationId, "act-2"); +}); + +test("a refund with a place held reads as revoked", async () => { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); + await P.activate(KEY, T0); + answers.validate = (body) => (body.activation_id ? reply(404)() : reply(200, { ...LIMITED, status: "revoked" })()); + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "revoked" }); + assert.equal(stored().key, KEY, "kept, so Settings can say what happened"); +}); + +test("a limit set in Polar after the key was entered: a place is taken at the next check", async () => { + reset(); + answers.validate = reply(200, GRANTED); + await P.activate(KEY, T0); + + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-late" }); + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "granted" }); + assert.equal(stored().activationId, "act-late"); + + // ...or, with every place already taken, this browser is the one without. + reset(); + answers.validate = reply(200, GRANTED); + await P.activate(KEY, T0); + answers.validate = reply(200, LIMITED); + answers.activate = reply(403); + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: true, status: "removed" }); +}); + +test("a dropped connection during the weekly check keeps Pro", async () => { + reset(); + answers.validate = reply(200, GRANTED); + await P.activate(KEY, T0); + answers.validate = offline(); + assert.deepEqual(await P.refreshIfDue(T0 + 30 * DAY), { checked: false, offline: true }); + assert.equal(await P.isPro(T0 + 30 * DAY), true); +}); + +test("a key that is no longer granted is not checked again every week", async () => { + reset(); + backing.set(P.LICENCE_KEY, { key: KEY, status: "revoked", checkedAt: T0 }); + assert.deepEqual(await P.refreshIfDue(T0 + 30 * DAY), { checked: false }); + assert.equal(calls.length, 0); }); test("a clock moved backwards does not postpone the check", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); await P.activate(KEY, T0); calls = []; assert.equal((await P.refreshIfDue(T0 - 365 * DAY)).checked, true); assert.equal(calls.length, 1); }); -test("forgetting the key turns Pro off", async () => { +test("remove: the place is given back first, then the key forgotten", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); await P.activate(KEY, T0); - await P.forget(); - assert.equal(await P.isPro(T0), false); + calls = []; + + answers.deactivate = reply(204); + assert.deepEqual(await P.release(), { ok: true }); + assert.deepEqual(endpoints(), ["deactivate"]); + assert.deepEqual(calls[0].body, { key: KEY, organization_id: "org-test", activation_id: "act-1" }); + assert.equal(backing.has(P.LICENCE_KEY), false); +}); + +test("remove offline keeps the key, so the place is not left taken", async () => { + for (const answer of [offline(), reply(500)]) { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); + await P.activate(KEY, T0); + answers.deactivate = answer; + assert.deepEqual(await P.release(), { ok: false, offline: true }); + assert.equal(stored().activationId, "act-1"); + } +}); + +test("remove: a place Polar no longer has is gone already, and a key with no place just goes", async () => { + reset(); + answers.validate = reply(200, LIMITED); + answers.activate = reply(200, { id: "act-1" }); + await P.activate(KEY, T0); + answers.deactivate = reply(404); + assert.deepEqual(await P.release(), { ok: true }); + assert.equal(backing.has(P.LICENCE_KEY), false); + + reset(); + answers.validate = reply(200, GRANTED); + await P.activate(KEY, T0); + calls = []; + assert.deepEqual(await P.release(), { ok: true }); + assert.equal(calls.length, 0); +}); + +test("Firefox: nothing is sent without its consent, and it is asked from Activate", async () => { + reset(); + manifest = FIREFOX; + consent = { granted: false, answer: false, requests: 0 }; + answers.validate = reply(200, GRANTED); + + assert.equal(P.needsConsent(), true); + assert.deepEqual(await P.activate(KEY, T0), { ok: false, offline: true, reason: "no-consent" }); + assert.equal(calls.length, 0); + + assert.equal(await P.askConsent(), false); + consent.answer = true; + assert.equal(await P.askConsent(), true); + assert.equal(consent.requests, 2); + assert.deepEqual(await P.activate(KEY, T0), { ok: true }); +}); + +test("Firefox: consent withdrawn later stops the weekly check, and Pro stays as it was", async () => { + reset(); + manifest = FIREFOX; + answers.validate = reply(200, GRANTED); + await P.activate(KEY, T0); + consent.granted = false; + calls = []; + assert.deepEqual(await P.refreshIfDue(T0 + 8 * DAY), { checked: false, offline: true }); + assert.equal(calls.length, 0); + assert.equal(await P.isPro(T0 + 8 * DAY), true); +}); + +test("Chrome and Edge never ask", async () => { + reset(); + assert.equal(P.needsConsent(), false); + assert.equal(await P.askConsent(), true); + assert.equal(consent.requests, 0); }); test("without an organisation id nothing is sent", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); P.CONFIG.organizationId = ""; try { const result = await P.activate(KEY, T0); @@ -217,9 +396,9 @@ test("without an organisation id nothing is sent", async () => { } }); -test("without Sieve Pro's benefit named, nothing is sent (the store is shared with BlockNSFW)", async () => { +test("without Sieve Pro's benefit named, nothing is sent", async () => { reset(); - respond(200, { ...GRANTED, benefit_id: "blocknsfw-supporter" }); + answers.validate = reply(200, { ...GRANTED, benefit_id: "blocknsfw-supporter" }); P.CONFIG.benefitIds = []; try { assert.equal(P.isConfigured(), false); @@ -231,13 +410,14 @@ test("without Sieve Pro's benefit named, nothing is sent (the store is shared wi } }); -test("sandbox mode asks Polar's test store", async () => { +test("sandbox mode asks Polar's test store, and shows its purchases page", async () => { reset(); - respond(200, GRANTED); + answers.validate = reply(200, GRANTED); P.CONFIG.mode = "sandbox"; try { await P.activate(KEY, T0); assert.match(calls[0].url, /^https:\/\/sandbox-api\.polar\.sh\//); + assert.match(P.portalUrl(), /^https:\/\/sandbox\.polar\.sh\//); } finally { P.CONFIG.mode = "live"; } @@ -246,6 +426,7 @@ test("sandbox mode asks Polar's test store", async () => { test("the shipped config is the live store", () => { assert.equal(P.CONFIG.mode, "live"); assert.equal(P.apiBase(), "https://api.polar.sh"); + assert.equal(P.portalUrl(), "https://polar.sh/monolab/portal"); }); test("the masked key shows the tail only", () => { From 5360e1129cce92bc388f928dcc6d3056c9a14b60 Mon Sep 17 00:00:00 2001 From: Alfon Date: Thu, 29 Oct 2026 12:43:12 +0800 Subject: [PATCH 03/12] Sieve Pro: Polar sandbox store, and sandbox test builds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit common/pro.js now holds both of Monolab's Polar stores side by side, since the sandbox is a separate copy with its own ids: - stores.sandbox: organisation 35c82b93-…, the "Sieve Pro" product's licence-key benefit 128feed7-… ("Sieve Lifetime Code"), and its checkout link. All read back from the sandbox checkout itself. - stores.live: Monolab's live organisation, as before; its benefit id and checkout link are still to come, so store packages keep refusing. - The price label follows the product: $24.99. `build-chrome.ps1 -Sandbox` (or build-firefox.ps1), with or without -Zip, now makes a test build whose own copy of common/pro.js says mode "sandbox"; the source and every other build stay live. build-pro.mjs checks the sandbox store is complete for such a build, and the live one for a store package. Checked against Polar's real sandbox from a -Sandbox build in headless Edge: the Buy button opens the sandbox checkout at $24.99, and a made-up key goes to the sandbox validate endpoint with only the key and the organisation, comes back 404, and Settings says it was not recognised, storing nothing. The full yes path waits on a real sandbox key. Tests: 829 public, 30 private. Co-Authored-By: Claude Opus 5.5 --- build-chrome.ps1 | 6 ++--- build-firefox.ps1 | 6 ++--- build-pro.mjs | 44 ++++++++++++++++++++++++------- common/pro.js | 65 +++++++++++++++++++++++++++++++--------------- options/options.js | 4 +-- test/pro-test.mjs | 41 +++++++++++++++++++---------- 6 files changed, 115 insertions(+), 51 deletions(-) diff --git a/build-chrome.ps1 b/build-chrome.ps1 index e062c2a..6f9824f 100644 --- a/build-chrome.ps1 +++ b/build-chrome.ps1 @@ -12,8 +12,8 @@ # -OpenSource # Build without Sieve Pro, on purpose: pro\ keeps its empty # stand-ins. What CI builds, and what anyone can build from GitHub. -# -Sandbox With -Zip: a test package whose Pro may use Polar's sandbox. -# Never upload one. +# -Sandbox A test build whose Pro uses Polar's sandbox store (with -Zip, a +# test package). Never upload one. # # Sieve Pro comes from a private repository checked out at pro-private\ (see # pro\README.md and build-pro.mjs). A plain build includes it when that @@ -36,7 +36,7 @@ $OutDir = Join-Path $ScriptDir "dist\chrome" $ManifestSrc = Join-Path $SrcDir "manifest.json" $ManifestDst = Join-Path $OutDir "manifest.json" -$ProKind = if ($OpenSource) { "open-source" } elseif ($Zip -and $Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } +$ProKind = if ($OpenSource) { "open-source" } elseif ($Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } # Whole folders copied verbatim into the build. Anything not listed here # (node_modules, src, vendor, cookie-rules-extra, test, _metadata, docs) is diff --git a/build-firefox.ps1 b/build-firefox.ps1 index 2de9554..48b724f 100644 --- a/build-firefox.ps1 +++ b/build-firefox.ps1 @@ -13,8 +13,8 @@ # -OpenSource # Build without Sieve Pro, on purpose: pro\ keeps its empty # stand-ins. What CI builds, and what anyone can build from GitHub. -# -Sandbox With -Zip: a test package whose Pro may use Polar's sandbox. -# Never upload one. +# -Sandbox A test build whose Pro uses Polar's sandbox store (with -Zip, a +# test package). Never upload one. # # Sieve Pro comes from a private repository checked out at pro-private\ (see # pro\README.md and build-pro.mjs). A plain build includes it when that @@ -37,7 +37,7 @@ $OutDir = Join-Path $ScriptDir "dist\firefox" $ManifestSrc = Join-Path $SrcDir "manifest.firefox.json" $ManifestDst = Join-Path $OutDir "manifest.json" -$ProKind = if ($OpenSource) { "open-source" } elseif ($Zip -and $Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } +$ProKind = if ($OpenSource) { "open-source" } elseif ($Sandbox) { "sandbox" } elseif ($Zip) { "store" } else { "dev" } # Whole folders copied verbatim into the build. Anything not listed here # (node_modules, src, vendor, cookie-rules-extra, test, _metadata, docs) is diff --git a/build-pro.mjs b/build-pro.mjs index ddbc28b..5809ae4 100644 --- a/build-pro.mjs +++ b/build-pro.mjs @@ -9,8 +9,9 @@ // is one of: // store a package for the stores (-Zip): Pro must be included, from a // clean pro-private checkout, selling through Polar's live store -// sandbox a test package (-Zip -Sandbox): Pro included, any store mode; -// never upload one +// sandbox a test build (-Sandbox, with or without -Zip): Pro included, +// and this build's own copy of common/pro.js switched to Polar's +// sandbox store; never upload one // dev a plain build: Pro included when pro-private is checked out // open-source without Pro on purpose (-OpenSource): the stand-ins stay // @@ -20,7 +21,7 @@ // nothing else in the private repository (its tests, its notes) can reach a // package. -import { readFileSync, readdirSync, existsSync, copyFileSync, rmSync, statSync } from "node:fs"; +import { readFileSync, readdirSync, existsSync, copyFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { execFileSync } from "node:child_process"; @@ -73,14 +74,26 @@ function checkPrivate(kind) { return true; } +// What a store in common/pro.js still lacks before it can sell Sieve Pro. +function storeGaps(name) { + const s = (proConfig().stores || {})[name] || {}; + const missing = []; + if (!s.organizationId) missing.push("no organizationId"); + if (!Array.isArray(s.benefitIds) || s.benefitIds.length === 0) missing.push("no benefitIds"); + if (!s.checkoutUrl) missing.push("no checkoutUrl"); + return missing; +} + +function checkSandbox() { + const missing = storeGaps("sandbox"); + if (missing.length) fail(`common/pro.js has no complete sandbox store: ${missing.join(", ")}.`); +} + function checkStore() { const c = proConfig(); - const missing = []; - if (c.mode !== "live") missing.push(`mode is "${c.mode}", not "live"`); - if (!c.organizationId) missing.push("no organizationId"); - if (!Array.isArray(c.benefitIds) || c.benefitIds.length === 0) missing.push("no benefitIds"); - if (!c.checkoutUrl) missing.push("no checkoutUrl"); - if (missing.length) fail(`common/pro.js cannot sell Sieve Pro yet: ${missing.join(", ")}. Fill it in from the Polar dashboard, or pass -Sandbox for a test package.`); + const missing = storeGaps("live"); + if (c.mode !== "live") missing.unshift(`mode is "${c.mode}", not "live"`); + if (missing.length) fail(`common/pro.js cannot sell Sieve Pro yet: ${missing.join(", ")}. Fill in stores.live from the Polar dashboard, or pass -Sandbox for a test package.`); let dirty = ""; try { @@ -99,6 +112,7 @@ if (args[0] === "--check") { if (kind === "open-source") process.exit(0); checkPrivate(kind); if (kind === "store") checkStore(); + if (kind === "sandbox") checkSandbox(); process.exit(0); } @@ -114,3 +128,15 @@ if (kind === "open-source" || !checkPrivate(kind)) { } for (const name of standInNames()) copyFileSync(join(REAL, name), join(outPro, name)); console.log(`Sieve Pro: included (${standInNames().join(", ")})`); + +// A sandbox build switches its own copy of the licence check to Polar's test +// store. The source, and every other build, stays live. +if (kind === "sandbox") { + const file = join(outDir, "common", "pro.js"); + const text = readFileSync(file, "utf8"); + // \r? because a Windows checkout may have CRLF line endings. + const live = /^([ \t]*)mode: "live",(\r?)$/m; + if ((text.match(new RegExp(live.source, "gm")) || []).length !== 1) fail(`${file}: expected exactly one mode: "live", line`); + writeFileSync(file, text.replace(live, '$1mode: "sandbox",$2')); + console.log("Sieve Pro: this build uses Polar's sandbox store"); +} diff --git a/common/pro.js b/common/pro.js index 7cc3bb5..36b4120 100644 --- a/common/pro.js +++ b/common/pro.js @@ -47,24 +47,41 @@ const LICENCE_KEY = "proLicence"; // From the Polar dashboard: Monolab's store, the one BlockNSFW's Supporter - // sells through too. `mode` is "sandbox" while testing with Polar's test - // store and "live" for real purchases; a key from one does not open the - // other, and the sandbox has its own organisation and benefit ids. + // sells through too. `mode` is "live" for real purchases and "sandbox" for + // Polar's test store, which is a separate copy with its own organisation, + // product and benefit; a key from one does not open the other. Shipped + // builds are live; `build-chrome.ps1 -Sandbox` makes a test build that + // switches this one word in its own copy (build-pro.mjs). const CONFIG = { mode: "live", - organizationId: "354a2f6c-8ea7-46a7-87c5-f97645c12e29", - api: { sandbox: "https://sandbox-api.polar.sh", live: "https://api.polar.sh" }, - // Where buyers find their key and see the browsers it is on. - portal: { sandbox: "https://sandbox.polar.sh/monolab/portal", live: "https://polar.sh/monolab/portal" }, - // The benefit(s) that grant Sieve Pro. Required: every product in the store - // shares the organisation id, so this is what tells a Sieve Pro key from a - // BlockNSFW one. Until it is set, Pro cannot be activated. - benefitIds: [], - // Without it the settings page hides the Buy button. - checkoutUrl: "", - priceLabel: "$24", + stores: { + live: { + organizationId: "354a2f6c-8ea7-46a7-87c5-f97645c12e29", + // The benefit(s) that grant Sieve Pro. Required: every product in the + // store shares the organisation id, so this is what tells a Sieve Pro + // key from a BlockNSFW one. Until it is set, Pro cannot be activated. + benefitIds: [], + // Without it the settings page hides the Buy button. + checkoutUrl: "", + api: "https://api.polar.sh", + // Where buyers find their key and see the browsers it is on. + portal: "https://polar.sh/monolab/portal", + }, + sandbox: { + organizationId: "35c82b93-77a2-4b87-8478-39fc5dd4e666", + benefitIds: ["128feed7-d174-4ea4-a623-8bb26140935a"], + checkoutUrl: "https://sandbox-api.polar.sh/v1/checkout-links/polar_cl_nMckDrg0py2tVxqLjBPTm96ZqBomNzo7lS5nV2amxgc/redirect", + api: "https://sandbox-api.polar.sh", + portal: "https://sandbox.polar.sh/monolab/portal", + }, + }, + priceLabel: "$24.99", }; + function store() { + return CONFIG.stores[CONFIG.mode] || CONFIG.stores.live; + } + const DAY = 24 * 60 * 60 * 1000; const REFRESH_EVERY_MS = 7 * DAY; const TIMEOUT_MS = 15000; @@ -109,15 +126,20 @@ } function isConfigured() { - return !!CONFIG.organizationId && CONFIG.benefitIds.length > 0; + const s = store(); + return !!s.organizationId && s.benefitIds.length > 0; } function apiBase() { - return CONFIG.api[CONFIG.mode] || CONFIG.api.live; + return store().api; } function portalUrl() { - return CONFIG.portal[CONFIG.mode] || CONFIG.portal.live; + return store().portal; + } + + function checkoutUrl() { + return store().checkoutUrl; } // What this browser is called on the purchases page, so a buyer can tell @@ -210,7 +232,7 @@ function readAnswer(body) { const status = STATUSES.includes(body && body.status) ? body.status : "invalid"; const benefitId = body && typeof body.benefit_id === "string" ? body.benefit_id : ""; - const wrongProduct = !CONFIG.benefitIds.includes(benefitId); + const wrongProduct = !store().benefitIds.includes(benefitId); const expires = body && body.expires_at ? Date.parse(body.expires_at) : NaN; const limit = Math.floor(Number(body && body.limit_activations)); return { @@ -226,7 +248,7 @@ async function validate(key, activationId) { if (!isConfigured()) return { ok: false, offline: true, reason: "not-configured" }; if (!(await hasConsent())) return { ok: false, offline: true, reason: "no-consent" }; - const payload = { key, organization_id: CONFIG.organizationId }; + const payload = { key, organization_id: store().organizationId }; if (activationId) payload.activation_id = activationId; const r = await call("/v1/customer-portal/license-keys/validate", payload); if (r.offline) return { ok: false, offline: true }; @@ -240,7 +262,7 @@ async function takePlace(key, limit) { const r = await call("/v1/customer-portal/license-keys/activate", { key, - organization_id: CONFIG.organizationId, + organization_id: store().organizationId, label: deviceLabel(), }); if (r.offline) return { ok: false, offline: true }; @@ -371,7 +393,7 @@ if (!(await hasConsent())) return { ok: false, offline: true, reason: "no-consent" }; const r = await call("/v1/customer-portal/license-keys/deactivate", { key: licence.key, - organization_id: CONFIG.organizationId, + organization_id: store().organizationId, activation_id: licence.activationId, }); // 404: Polar has no such place any more, which is what was asked for. @@ -392,6 +414,7 @@ isConfigured, apiBase, portalUrl, + checkoutUrl, deviceLabel, needsConsent, hasConsent, diff --git a/options/options.js b/options/options.js index 5fb84db..04f287a 100644 --- a/options/options.js +++ b/options/options.js @@ -2250,8 +2250,8 @@ function setupLicence(store, onChange) { const forgetHint = document.getElementById("pro-forget-hint"); const portalLink = document.getElementById("pro-portal"); - if (P.CONFIG.checkoutUrl) { - buyLink.href = P.CONFIG.checkoutUrl; + if (P.checkoutUrl()) { + buyLink.href = P.checkoutUrl(); buyActions.hidden = false; } portalLink.href = P.portalUrl(); diff --git a/test/pro-test.mjs b/test/pro-test.mjs index 3b3064e..a6f09ee 100644 --- a/test/pro-test.mjs +++ b/test/pro-test.mjs @@ -65,8 +65,11 @@ globalThis.window = globalThis; await import("../common/pro.js"); const P = globalThis.SievePro; -P.CONFIG.organizationId = "org-test"; -P.CONFIG.benefitIds = ["benefit-pro"]; +// The config as shipped, before the tests point the live store at test ids. +const SHIPPED = structuredClone(P.CONFIG); +const LIVE = P.CONFIG.stores.live; +LIVE.organizationId = "org-test"; +LIVE.benefitIds = ["benefit-pro"]; const DAY = 24 * 3600000; const T0 = Date.UTC(2026, 9, 29, 9, 0, 0); @@ -386,47 +389,59 @@ test("Chrome and Edge never ask", async () => { test("without an organisation id nothing is sent", async () => { reset(); answers.validate = reply(200, GRANTED); - P.CONFIG.organizationId = ""; + LIVE.organizationId = ""; try { const result = await P.activate(KEY, T0); assert.equal(result.ok, false); assert.equal(calls.length, 0); } finally { - P.CONFIG.organizationId = "org-test"; + LIVE.organizationId = "org-test"; } }); test("without Sieve Pro's benefit named, nothing is sent", async () => { reset(); answers.validate = reply(200, { ...GRANTED, benefit_id: "blocknsfw-supporter" }); - P.CONFIG.benefitIds = []; + LIVE.benefitIds = []; try { assert.equal(P.isConfigured(), false); const result = await P.activate(KEY, T0); assert.equal(result.ok, false); assert.equal(calls.length, 0); } finally { - P.CONFIG.benefitIds = ["benefit-pro"]; + LIVE.benefitIds = ["benefit-pro"]; } }); -test("sandbox mode asks Polar's test store, and shows its purchases page", async () => { +test("sandbox mode uses the test store's own ids, address, checkout and purchases page", async () => { reset(); - answers.validate = reply(200, GRANTED); + const sandbox = SHIPPED.stores.sandbox; + answers.validate = reply(200, { ...GRANTED, benefit_id: sandbox.benefitIds[0] }); P.CONFIG.mode = "sandbox"; try { - await P.activate(KEY, T0); + assert.deepEqual(await P.activate(KEY, T0), { ok: true }); assert.match(calls[0].url, /^https:\/\/sandbox-api\.polar\.sh\//); + assert.equal(calls[0].body.organization_id, sandbox.organizationId); + assert.equal(P.checkoutUrl(), sandbox.checkoutUrl); assert.match(P.portalUrl(), /^https:\/\/sandbox\.polar\.sh\//); } finally { P.CONFIG.mode = "live"; } }); -test("the shipped config is the live store", () => { - assert.equal(P.CONFIG.mode, "live"); - assert.equal(P.apiBase(), "https://api.polar.sh"); - assert.equal(P.portalUrl(), "https://polar.sh/monolab/portal"); +test("the shipped config: live mode, Monolab's live store, and a complete sandbox", () => { + assert.equal(SHIPPED.mode, "live"); + const { live, sandbox } = SHIPPED.stores; + assert.equal(live.organizationId, "354a2f6c-8ea7-46a7-87c5-f97645c12e29"); + assert.equal(live.api, "https://api.polar.sh"); + assert.equal(live.portal, "https://polar.sh/monolab/portal"); + // The live store's benefit and checkout are filled in at launch; a store + // package refuses to build until they are (build-pro.mjs). + assert.notEqual(sandbox.organizationId, live.organizationId, "the sandbox is a separate store"); + assert.match(sandbox.organizationId, /^[0-9a-f-]{36}$/); + assert.equal(sandbox.benefitIds.length, 1); + assert.match(sandbox.checkoutUrl, /^https:\/\/sandbox-api\.polar\.sh\/v1\/checkout-links\/polar_cl_\w+\/redirect$/); + assert.equal(sandbox.api, "https://sandbox-api.polar.sh"); }); test("the masked key shows the tail only", () => { From 70c02ac6ab58871cb26ed231c32b442a701160b1 Mon Sep 17 00:00:00 2001 From: Alfon Date: Thu, 29 Oct 2026 13:30:55 +0800 Subject: [PATCH 04/12] The Seal: free and open source, with a witness like BlockNSFW's Pact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Seal is a protection, so it leaves Sieve Pro: everything that protects stays free and open source, as in BlockNSFW, and Pro is now the urge screen and streaks. common/seal.js and its tests come back to this repository, its settings move from Settings › Sieve Pro to Settings › Lock (after Cool-off), and the popup shows a running seal with or without Pro. The way out early is now held by a witness by default, as for the Pact: - common/totp.js and common/qr.js are ported from BlockNSFW's shared/ (standard TOTP, RFC 6238; its own QR encoder, no CDN), with their tests (the RFC 4226/6238 vectors, Reed-Solomon worked examples, a Seal key read back block by block). - Starting a seal with a witness shows a QR code to scan into their authenticator app, the key to type if they can't, and eight recovery codes, with a "Print for your witness" sheet. The seal starts only once their app shows a code that works, so a bad scan cannot leave a seal with no way out, and that code is spent so it cannot end the seal. The key and codes leave the page as it starts; recovery codes are kept only as hashes. - The Sealed dialog asks for the witness's six digits or a recovery code. Five wrong codes lock entry for 5 minutes, doubling to an hour. Codes are checked one at a time and the button waits, so a burst of guesses cannot slip past the count (found in the browser check; test added). - A printed key stays as the choice for someone with nobody to ask. Seals stored before today read as key seals. Tests: 876 public (seal 23, totp 11, qr 12), 18 private. Headless Edge, open-source build: 20 checks covering pairing, a wrong and a right code, the dialog, the spent code, the lockout, recovery and fresh codes, the printed key, the popup without Pro, and 390px. Pro build: 26 checks. Firefox lint unchanged: 0 errors, 15 warnings. Co-Authored-By: Claude Opus 5.5 --- PRIVACY.md | 8 +- README.md | 3 +- background/service-worker.js | 3 +- common/changelog.js | 7 +- common/guardian-prompt.js | 53 +++-- common/pro.js | 11 +- common/qr.js | 408 +++++++++++++++++++++++++++++++++++ common/seal.js | 383 ++++++++++++++++++++++++++++++++ common/totp.js | 242 +++++++++++++++++++++ manifest.firefox.json | 3 +- manifest.json | 3 +- options/options.css | 81 ++++++- options/options.html | 216 +++++++++++-------- options/options.js | 266 ++++++++++++++++++++++- pages/blocked.html | 3 +- popup/popup.css | 4 +- popup/popup.html | 5 +- popup/popup.js | 18 +- pro/README.md | 6 +- pro/seal.js | 5 - test/pro-standins-test.mjs | 35 ++- test/qr-test.mjs | 190 ++++++++++++++++ test/seal-test.mjs | 295 +++++++++++++++++++++++++ test/totp-test.mjs | 109 ++++++++++ 24 files changed, 2191 insertions(+), 166 deletions(-) create mode 100644 common/qr.js create mode 100644 common/seal.js create mode 100644 common/totp.js delete mode 100644 pro/seal.js create mode 100644 test/qr-test.mjs create mode 100644 test/seal-test.mjs create mode 100644 test/totp-test.mjs diff --git a/PRIVACY.md b/PRIVACY.md index 1c89746..456b88c 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -31,7 +31,7 @@ described [below](#sieve-pro-licence-check). Without Pro, nothing changes. Sieve is open source, so anyone can verify these claims: . The one exception is Sieve Pro's -features (the Seal, the urge screen and streaks), which are not open source. +features (the urge screen and streaks), which are not open source. They make no network requests and keep everything on your device, and the licence check, the only request Pro makes, is part of the open-source code (`common/pro.js`), so what it sends can be checked by anyone. @@ -57,7 +57,7 @@ third party. | Free-trial reminders, **only the ones you ask for** | Remind you before a free trial starts charging — see [below](#free-trial-reminders) | Yes | | When the block page last stopped each kind of site | One date and time per kind (gambling, dating, games, AI tools, trading, your own blocked sites) and your longest gap, for Sieve Pro's streaks — never the site or its address | Yes | | Sieve Pro licence key, **only if you enter one** | Turn on the Pro features | Kept on your device; checked with Polar — see [below](#sieve-pro-licence-check) | -| Seal, **only if you start one** | When it ends, and its emergency key stored as a **hash**, never in plain text | Yes | +| Seal, **only if you start one** | When it ends, and its way out: either the key your witness's authenticator app shares with Sieve (needed to check their codes) and their recovery codes as **hashes**, or the emergency key as a **hash**. A witness's app works offline; nothing is sent to them, us or anyone | Yes | | Urge screen, **only what you fill in** | Your reason, an optional photo (shrunk to fit 800 pixels), and a contact's name and number or email address, shown on the block page | Yes | | Streak settings, **only for what you track** | The day you stopped, and what it used to cost you, to count streaks and money kept | Yes | @@ -150,8 +150,8 @@ extension sends. If you say no, nothing is sent and Pro stays off. Nobody who does not activate Pro is ever asked. The key is kept on your device so it can be checked again. The Pro features -themselves (the Seal, the urge screen and streaks) run entirely on your device, -like the rest of Sieve. +themselves (the urge screen and streaks) run entirely on your device, like the +rest of Sieve. --- diff --git a/README.md b/README.md index 0064bc9..991ba2e 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ tracking, nothing leaves your browser. - **Doomscroll Stopper** — a daily time limit on endless feeds, with a gentle pause overlay. - **Guardian self-lock** — an optional PIN that gates *weakening* your protection (turning things off, allowlisting) while strengthening it stays free. - **Cool-off** — an optional wait (1 hour to 7 days) before anything that weakens your protection unlocks. The change is asked for first and unlocks only once the wait is over, for that one change, once, for a day; nothing turns off by itself, and a request can be called off at any time. Works with or without a PIN. +- **Seal** — lock your protection until a date (a week, 30 or 90 days, a year). Until then nothing that weakens it can be changed, not with the PIN and not after a cool-off. The only way out early is held by a **witness** — someone you trust scans a QR code into their authenticator app, and you ask them for the six digits it shows (standard TOTP, no server; eight hashed recovery codes for a lost phone; five wrong codes lock entry for a while) — or, for someone with nobody to ask, by an emergency key shown once and stored only as a hash. Extending is always allowed, shortening never. Like BlockNSFW's Pact. - **Protection Dashboard** — a today/this-week breakdown of everything Sieve blocked for you, including an **Ads** section counting ad-network requests, the YouTube and Facebook ads removed, the ad-blocker walls cleared and the empty ad slots hidden. Only running totals are stored — never which site or which ad network. The request counter reads back which of Sieve's own block rules fired, which Chrome allows and Firefox does not, so they stay at zero on Firefox while the blocking itself is unaffected. - **Usage Insights** — an opt-in screen-time report: total time, a per-day and per-hour curve, and which sites took it. Only the tab you are looking at counts, the clock stops when you step away, and the record never leaves your device (7/30/90-day retention, clearable at any time). @@ -188,7 +189,7 @@ Sieve elects the CC arm of EasyList's GPLv3 / CC BY-SA 3.0 dual licence; BY-SA's "Collection" clause is what keeps the rest of the project MIT. Editing that one file means editing a BY-SA file — see [`data/ATTRIBUTION-easylist.md`](data/ATTRIBUTION-easylist.md). -**Sieve Pro** (the Seal, the urge screen and streaks) is not open source and is not in +**Sieve Pro** (the urge screen and streaks) is not open source and is not in this repository: [`pro/`](pro/README.md) holds empty stand-ins, and the store versions of Sieve carry the real files. Every protection is here, so a build from this repository blocks exactly what the store version does. Build one with diff --git a/background/service-worker.js b/background/service-worker.js index 4551e15..c81dfea 100644 --- a/background/service-worker.js +++ b/background/service-worker.js @@ -553,7 +553,8 @@ const DOOMSCROLL_CS_FILES = [ "common/doomscroll-sites.js", "common/access-code.js", "common/cooloff.js", - "pro/seal.js", + "common/totp.js", + "common/seal.js", "common/theme.js", "common/guardian-prompt.js", "content/pause-overlay.js", diff --git a/common/changelog.js b/common/changelog.js index 787c849..9f03d3a 100644 --- a/common/changelog.js +++ b/common/changelog.js @@ -17,12 +17,13 @@ const SIEVE_CHANGELOG = [ version: "1.6.0", date: "November 2026", items: [ - "New: Sieve Pro, a one-time purchase with no subscription. Everything Sieve did before stays free, and always will. Pro adds three new things on top, all running on your device like the rest of Sieve.", - "The Seal locks your protection until a date you choose: a week, 30 days, 90 days or a year. Until then nothing that weakens it can be changed, not with your PIN and not by waiting out a cool-off. You get one emergency key, shown once, to print or hand to someone you trust. It is the only way to end a seal early. Extending a seal is always allowed; shortening one is not.", + "New, and free: the Seal, in Settings › Lock. It locks your protection until a date you choose: a week, 30 days, 90 days or a year. Until then nothing that weakens it can be changed, not with your PIN and not by waiting out a cool-off. Extending a seal is always allowed; shortening one is not.", + "The way out early is held by a witness: someone you trust scans a QR code into the authenticator app they already use, and you ask them for the six digits it shows. They also keep eight recovery codes in case their phone is lost. Nothing is sent anywhere, and five wrong codes lock entry for a while. The seal only starts once their app has shown a code that works. If there is nobody to ask, choose a printed emergency key instead.", + "A running seal shows in the toolbar popup, with the day it ends.", + "New: Sieve Pro, a one-time purchase with no subscription. Every protection stays free, the Seal included, and always will. Pro adds two things on top, for the hard moments and for seeing how far you have come, running on your device like the rest of Sieve.", "The urge screen changes what you see when Sieve stops you at a blocked site. Instead of a notice, the page leads with ninety seconds of breathing, then your own reason in your own words, a photo if you chose one, and one tap to text, call or email someone you trust. Go back and Allow stay underneath, exactly as before.", "Streaks count the days since you last tried to open a gambling site, a dating site, or any other kind you track, and what it would have cost: “23 days · about $1,140 kept”. They show in the toolbar popup and in settings, with your best run and the next milestone.", "Sieve Pro is sold by Polar, who send the licence key with your receipt. One key works in up to three browsers at once, and “Remove from this browser” frees a place for another. Entering it sends that key and a plain name for the browser to Polar to check it, and again about once a week when you open the settings. Firefox asks your permission first. The privacy policy explains exactly what is sent.", - "If Pro ever ends, for example after a refund, a seal you already started still runs to its date. Losing Pro never weakens your protection.", "A fix for the Protection Dashboard: blocks from the gambling list built into Sieve were not being counted, only those from the downloaded list.", ], }, diff --git a/common/guardian-prompt.js b/common/guardian-prompt.js index 924dfdd..1376135 100644 --- a/common/guardian-prompt.js +++ b/common/guardian-prompt.js @@ -12,7 +12,7 @@ // With a cool-off set (common/cooloff.js) the change must first wait it // out: until then the dialog only offers to start or call off the wait, and // resolves false. Once the wait is over, the PIN is asked for as before. -// While a Seal runs (Sieve Pro, pro/seal.js) the change is refused before +// While a Seal runs (common/seal.js) the change is refused before // any of that, and only the seal's emergency key — which ends the seal — // gets through to the cool-off and the PIN. // @@ -363,9 +363,17 @@ // --- seal stage --------------------------------------------------------- // // Shown INSTEAD of everything else while a Seal runs. The change is refused; - // the one thing on offer is the emergency key, which ends the seal and hands - // over to the cool-off and the PIN exactly as if there had been no seal. - let seal = null; // { until } while it is showing + // the one thing on offer is the seal's way out — a code from its witness, + // or its printed key — which ends the seal and hands over to the cool-off + // and the PIN exactly as if there had been no seal. + let seal = null; // SieveSeal.check()'s answer while it is showing + + const byWitness = () => !!seal && seal.exit === "witness"; + + function lockedLine(retryAt) { + const minutes = Math.max(1, Math.ceil((retryAt - Date.now()) / 60000)); + return `Too many wrong codes. Try again in ${minutes} min${minutes === 1 ? "" : "s"}.`; + } function showSealed(actionName, info) { const S = window.SieveSeal; @@ -380,9 +388,11 @@ setCoolText([ "You sealed your protection until ", { strong: S.formatWhen(info.until) }, - ". Until then nothing that weakens it can be changed — not with your PIN, and not after a cool-off. Only the emergency key ends it early.", + byWitness() + ? ". Until then nothing that weakens it can be changed — not with your PIN, and not after a cool-off. Only a code from your witness ends it early." + : ". Until then nothing that weakens it can be changed — not with your PIN, and not after a cool-off. Only the emergency key ends it early.", ]); - cancelBtn.textContent = "Use emergency key"; + cancelBtn.textContent = byWitness() ? "Ask your witness" : "Use emergency key"; confirmBtn.textContent = "Close"; confirmBtn.focus(); } @@ -392,15 +402,17 @@ stage = "sealkey"; title.textContent = "End the seal early"; setCoolText([ - "Type the emergency key you were given when the seal started. It ends the whole seal; your PIN and cool-off still apply after it.", + byWitness() + ? "Ask your witness for the six digits their authenticator app shows for Sieve, or for one of their recovery codes. It ends the whole seal; your PIN and cool-off still apply after it." + : "Type the emergency key you were given when the seal started. It ends the whole seal; your PIN and cool-off still apply after it.", ]); input.hidden = false; input.type = "text"; input.classList.add("code-input"); - input.placeholder = "XXXX-XXXX-XXXX-XXXX-XXXX"; + input.placeholder = byWitness() ? "123456 or XXXX-XXXX" : "XXXX-XXXX-XXXX-XXXX-XXXX"; input.value = ""; errorEl.hidden = false; - errorEl.textContent = ""; + errorEl.textContent = seal && seal.lockedUntil ? lockedLine(seal.lockedUntil) : ""; errorEl.dataset.tone = ""; cancelBtn.textContent = "Back"; confirmBtn.textContent = "End the seal"; @@ -408,18 +420,28 @@ } async function sealKeySubmit() { - let ended = false; + // One code at a time (common/seal.js counts the wrong ones). + if (confirmBtn.disabled) return; + confirmBtn.disabled = true; + let result = { ok: false }; try { - ended = await window.SieveSeal.breakWithKey(input.value); + result = await window.SieveSeal.breakWith(input.value); } catch (err) { - console.warn("[Sieve] could not check the emergency key:", err); + console.warn("[Sieve] could not check the seal's code:", err); + } finally { + confirmBtn.disabled = false; } - if (ended) { + if (result.ok) { finish(true); return; } - errorEl.textContent = "That key doesn't match."; + if (result.locked) { + errorEl.textContent = lockedLine(result.retryAt); + } else { + errorEl.textContent = byWitness() ? "That code doesn't match. Ask for the newest one." : "That key doesn't match."; + } errorEl.dataset.tone = ""; + input.value = ""; input.focus(); } @@ -553,8 +575,7 @@ } // The running seal, or null when there is none (or this page did not load - // pro/seal.js, an empty stand-in in an open-source build). A failed read - // goes on without it, as the cool-off does. + // common/seal.js). A failed read goes on without it, as the cool-off does. async function sealFor() { const S = window.SieveSeal; if (!S) return null; diff --git a/common/pro.js b/common/pro.js index 36b4120..464b0cc 100644 --- a/common/pro.js +++ b/common/pro.js @@ -1,9 +1,9 @@ // common/pro.js // Sieve — Sieve Pro, the one-time purchase that unlocks the Pro features. // -// Everything Sieve did before Pro stays free. Pro adds new things on top (the -// Seal, the urge screen, streaks), and this module answers one question for all -// of them: has this browser got a valid Pro licence? +// Every protection stays free, the Seal included. Pro adds comfort and insight +// on top (the urge screen, streaks), and this module answers one question for +// both: has this browser got a valid Pro licence? // // This file is open source on purpose, like BlockNSFW's shared/supporter.js: // it is the one part of Pro that talks to the network, so anyone can read @@ -31,9 +31,8 @@ // server error keeps whatever was last known; only a clear answer from // Polar (revoked, disabled, unknown key, this browser's place given back) // turns Pro off. -// - Losing Pro never weakens a protection that is already running. That rule -// lives in each feature (a running Seal is honoured without asking this -// module), but it is why nothing here clears or changes their state. +// - Losing Pro never weakens a protection. Nothing that protects asks this +// module anything, and nothing here clears or changes their state. // // Like the PIN, this lives in this browser's storage. It is not copy // protection: anyone can edit an extension's code. The people who pay are the diff --git a/common/qr.js b/common/qr.js new file mode 100644 index 0000000..5ecefb7 --- /dev/null +++ b/common/qr.js @@ -0,0 +1,408 @@ +// common/qr.js +// A small QR Code encoder, so a Seal's witness can scan its key into their +// authenticator app. Sieve loads nothing from a CDN, so this is written here +// instead of vendored. +// +// Scope is deliberately narrow: byte mode, error correction level M, +// versions 1 to 10 (up to 213 bytes; an otpauth:// key is about 90). The +// structure follows ISO/IEC 18004 and the layout of Project Nayuki's QR Code +// generator (MIT), re-implemented for this one use. It returns a matrix of +// booleans (true = dark); the page draws it. +// +// Ported from BlockNSFW's shared/qr.js, kept as it is there. Loaded as a +// classic - + + + diff --git a/options/options.js b/options/options.js index 04f287a..1e1dcef 100644 --- a/options/options.js +++ b/options/options.js @@ -592,7 +592,7 @@ function optionsDefaults() { seenWhatsNewVersion: "", // Warden band on the Overview — folded to its one-line bar by the × wardenFolded: false, - // Sieve Pro — the licence (common/pro.js), the Seal (pro/seal.js), and + // The Seal (common/seal.js), and Sieve Pro: the licence (common/pro.js), // the urge screen and streaks (pro/streaks.js). The urge screen's photo // has its own key, read separately, so this batch never carries an image. proLicence: null, @@ -733,7 +733,8 @@ async function applyStoredSettings(store) { setupGuardian(store); // self-lock PIN status panel setupAccessCode(); // optional second layer over that PIN setupCooloff(store); // a wait before any weakening change unlocks - setupPro(store); // Sieve Pro: licence, Seal, urge screen, streaks + setupSeal(store); // lock protection until a date (free) + setupPro(store); // Sieve Pro: licence, urge screen, streaks setupDarkPatterns(store); // Module 3A — relocated from the popup setupToxicSites(store); // per-site toggles — relocated from the popup @@ -2166,18 +2167,264 @@ function setupCooloff(store) { renderRequests(); } +// =========================================================================== +// The Seal — lock protection until a date (common/seal.js). Free, like every +// other protection. Starting or extending a seal strengthens protection, so +// neither goes through the Guardian gate; there is no control that shortens +// one. Refusing weakening changes while it runs happens in the gate itself +// (common/guardian-prompt.js), so this group only starts, shows and extends. +// =========================================================================== + +const SEAL_DAY_MS = 24 * 60 * 60 * 1000; +const SVG_NS = "http://www.w3.org/2000/svg"; + +// The witness's QR code, drawn as one SVG path (common/qr.js). Always dark +// on white, whatever the page's theme: that is what a camera reads. +function drawSealQr(container, text) { + const qr = window.SieveQr.encode(text); + const span = qr.size + 8; // the four-module quiet zone on each side + const svg = document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("viewBox", `0 0 ${span} ${span}`); + svg.setAttribute("shape-rendering", "crispEdges"); + svg.setAttribute("aria-hidden", "true"); + const paper = document.createElementNS(SVG_NS, "rect"); + paper.setAttribute("width", String(span)); + paper.setAttribute("height", String(span)); + paper.setAttribute("fill", "#ffffff"); + const ink = document.createElementNS(SVG_NS, "path"); + ink.setAttribute("d", window.SieveQr.toPath(qr)); + ink.setAttribute("fill", "#000000"); + svg.append(paper, ink); + container.replaceChildren(svg); +} + +// Print one part of the seal (its key, or the witness's sheet) and nothing +// else on the page (options.css, html.print-seal). +function printSealPart(el) { + const root = document.documentElement; + el.classList.add("is-printing"); + root.classList.add("print-seal"); + window.addEventListener( + "afterprint", + () => { + root.classList.remove("print-seal"); + el.classList.remove("is-printing"); + }, + { once: true }, + ); + window.print(); +} + +function setupSeal(store) { + const S = window.SieveSeal; + const badge = document.getElementById("seal-badge"); + const boxes = { + start: document.getElementById("seal-start"), + confirm: document.getElementById("seal-confirm"), + key: document.getElementById("seal-key-box"), + running: document.getElementById("seal-running"), + }; + const lengthEl = document.getElementById("seal-length"); + const beginBtn = document.getElementById("seal-begin"); + const confirmText = document.getElementById("seal-confirm-text"); + const cancelBtn = document.getElementById("seal-cancel"); + const goBtn = document.getElementById("seal-go"); + const witnessBox = document.getElementById("seal-witness"); + const witnessHead = document.getElementById("seal-witness-print-head"); + const qrBox = document.getElementById("seal-qr"); + const secretEl = document.getElementById("seal-secret"); + const recoveryList = document.getElementById("seal-recovery"); + const codeInput = document.getElementById("seal-witness-code"); + const codeError = document.getElementById("seal-witness-error"); + const printWitnessBtn = document.getElementById("seal-print-witness"); + const keyBox = boxes.key; + const keyEl = document.getElementById("seal-key"); + const printHead = document.getElementById("seal-print-head"); + const printBtn = document.getElementById("seal-print"); + const doneBtn = document.getElementById("seal-key-done"); + const runningText = document.getElementById("seal-running-text"); + const runningHint = document.getElementById("seal-running-hint"); + const extendLength = document.getElementById("seal-extend-length"); + const extendBtn = document.getElementById("seal-extend"); + + let current = S.stateOf(store.proSeal) === "sealed" ? S.normalizeSeal(store.proSeal) : null; + // "start" | "confirm" | "key". The key stays on screen until it is put away, + // even though the seal is already running underneath it. + let mode = "start"; + // The witness's key and recovery codes while pairing, and only then: never + // stored until their app shows a code that works, and wiped from the page + // once the seal starts or the pairing is called off. + let pairing = null; + + const exitChosen = () => { + const picked = document.querySelector('input[name="sealExit"]:checked'); + return picked ? picked.value : "witness"; + }; + + function show(name) { + for (const [k, box] of Object.entries(boxes)) box.hidden = k !== name; + } + + function clearPairing() { + pairing = null; + qrBox.replaceChildren(); + secretEl.textContent = ""; + recoveryList.replaceChildren(); + witnessHead.textContent = ""; + codeInput.value = ""; + codeError.textContent = ""; + witnessBox.hidden = true; + printWitnessBtn.hidden = true; + } + + function render() { + const now = Date.now(); + const sealed = !!current && now < current.until; + // A running seal is a protection switched on, so it is the green badge. + badge.textContent = sealed ? "On" : "Off"; + badge.classList.toggle("on", sealed); + if (mode === "key") return show("key"); + if (sealed) { + mode = "start"; + const days = Math.ceil((current.until - now) / SEAL_DAY_MS); + runningText.textContent = + `Sealed until ${S.formatWhen(current.until)} — ${days === 1 ? "1 day" : `${days} days`} to go.`; + if (current.exit === "witness") { + const left = current.witness.recovery.filter((r) => !r.used).length; + runningHint.textContent = + "Your witness holds the way out. To end it early, try any protected change, choose " + + `“Ask your witness” and type the code their app shows (or one of their ${left} recovery codes). ` + + "Your PIN and cool-off apply again after it."; + } else { + runningHint.textContent = + "Your printed key is the way out. To end it early, try any protected change and choose " + + "“Use emergency key”. Your PIN and cool-off apply again after it."; + } + return show("running"); + } + show(mode === "confirm" ? "confirm" : "start"); + } + + beginBtn.addEventListener("click", () => { + const until = Date.now() + Number(lengthEl.value) * SEAL_DAY_MS; + const exit = exitChosen(); + confirmText.textContent = + `Seal your protection until ${S.formatWhen(until)}? Until then you will not be able to ` + + "switch a blocker off, allow a site, remove your PIN or shorten your cool-off. " + + (exit === "witness" ? "Only a code from your witness will end it early." : "Only the emergency key will end it early."); + clearPairing(); + if (exit === "witness") { + pairing = S.pairWitness(); + drawSealQr(qrBox, pairing.uri); + secretEl.textContent = window.SieveTotp.formatSecret(pairing.secret); + for (const code of pairing.recoveryCodes) { + const li = document.createElement("li"); + li.textContent = code; + recoveryList.appendChild(li); + } + witnessHead.textContent = + `Sieve · you are the witness for a seal that ends ${S.formatWhen(until)}. When they ask, ` + + "read them the six digits your authenticator app shows for “Sieve: Seal”, or one of these codes."; + witnessBox.hidden = false; + printWitnessBtn.hidden = false; + } + mode = "confirm"; + render(); + (exit === "witness" ? codeInput : goBtn).focus(); + }); + + cancelBtn.addEventListener("click", () => { + clearPairing(); + mode = "start"; + render(); + beginBtn.focus(); + }); + + goBtn.addEventListener("click", async () => { + const days = Number(lengthEl.value); + goBtn.disabled = true; + let result; + try { + result = pairing ? await S.startWithWitness(days, pairing, codeInput.value) : await S.start(days); + } catch (err) { + console.warn("[Sieve] could not start the seal:", err); + result = { ok: false }; + } + goBtn.disabled = false; + if (result.reason === "wrong-code") { + codeError.textContent = "That code doesn't match. Check the app shows “Sieve: Seal”, and type the newest code."; + codeInput.select(); + return; + } + if (!result.ok) { + clearPairing(); + mode = "start"; + render(); + return; + } + if (pairing) { + // Running now; the witness's key and codes leave the page. + clearPairing(); + mode = "start"; + render(); + return; + } + keyEl.textContent = result.key; + printHead.textContent = + `Sieve · emergency key for the seal that ends ${S.formatWhen(result.until)}. ` + + "Typing it into Sieve ends the seal early."; + mode = "key"; + render(); + doneBtn.focus(); + }); + + codeInput.addEventListener("keydown", (e) => { + if (e.key === "Enter") goBtn.click(); + }); + + // Print one part of the seal alone, not the settings page around it. + printBtn.addEventListener("click", () => printSealPart(keyBox)); + printWitnessBtn.addEventListener("click", () => printSealPart(witnessBox)); + + doneBtn.addEventListener("click", () => { + // Gone from the page as well as from storage: it was shown once. + keyEl.textContent = ""; + printHead.textContent = ""; + mode = "start"; + render(); + }); + + extendBtn.addEventListener("click", async () => { + try { + await S.extend(Number(extendLength.value)); + } catch (err) { + console.warn("[Sieve] could not extend the seal:", err); + } + }); + + chrome.storage.onChanged.addListener((changes, area) => { + if (area !== "local" || !changes[S.SEAL_KEY]) return; + const next = changes[S.SEAL_KEY].newValue; + current = S.stateOf(next) === "sealed" ? S.normalizeSeal(next) : null; + render(); + }); + + // Days to go, and the moment a seal ends. + setInterval(render, 60 * 1000); + + return { render }; +} + // =========================================================================== // Sieve Pro — the licence box, and the section the Pro features live in. -// Everything Sieve did before Pro stays free and open source. The features -// themselves (the Seal, the urge screen, streaks) are not: a store build copies -// them from a private repository over the empty stand-ins in pro/ (see +// Everything that protects stays free and open source, the Seal included. The +// Pro features (the urge screen, streaks) are not: a store build copies them +// from a private repository over the empty stand-ins in pro/ (see // pro/README.md). An open-source build keeps the stand-ins, so this section is // taken out of the page, and every protection works exactly the same. // // In a store build the groups are shown to everyone and work only with a -// licence. Losing it never weakens a protection already running, so a running -// seal is shown (and honoured, in common/guardian-prompt.js) whatever the -// licence says. +// licence. // =========================================================================== function proShortDate(ms) { @@ -2211,7 +2458,7 @@ function setupPro(store) { document.getElementById("nav-pro-group").hidden = !navShown; document.getElementById("nav-pro").hidden = !navShown; - const { seal, urge, streaks } = window.SieveProSettings.setup(store); + const { urge, streaks } = window.SieveProSettings.setup(store); enhanceSwitchRows(document.getElementById("section-pro")); function applyPro() { @@ -2221,7 +2468,6 @@ function setupPro(store) { if (note) note.hidden = pro; for (const control of card.querySelectorAll(".pro-control")) control.disabled = !pro; } - seal.render(); urge.render(pro); streaks.render(pro); } diff --git a/pages/blocked.html b/pages/blocked.html index c0e89e5..dbac8f2 100644 --- a/pages/blocked.html +++ b/pages/blocked.html @@ -645,7 +645,8 @@

This page is blocked

- + + diff --git a/popup/popup.css b/popup/popup.css index 0e30a75..678a641 100644 --- a/popup/popup.css +++ b/popup/popup.css @@ -116,8 +116,8 @@ body { display: none; } -/* Sieve Pro's lines: a running seal, and each tracked streak. Ink, not - green — a streak is a count, not something switched on. */ +/* A running seal, and each streak tracked with Sieve Pro. Ink, not green — + a streak is a count, not something switched on. */ .status-pro { display: flex; flex-direction: column; diff --git a/popup/popup.html b/popup/popup.html index 81da2c3..c29acf0 100644 --- a/popup/popup.html +++ b/popup/popup.html @@ -27,7 +27,7 @@ Checking… - + @@ -162,7 +162,8 @@

- + + diff --git a/popup/popup.js b/popup/popup.js index f84b977..ea16514 100644 --- a/popup/popup.js +++ b/popup/popup.js @@ -143,9 +143,9 @@ async function updateStatusBanner() { } } -// Sieve Pro, under the summary: a running seal, and each tracked streak with -// the money kept. A seal shows with or without Pro, since it is honoured with -// or without it; streaks show only with Pro. +// Under the summary: a running seal (free, common/seal.js), then each streak +// tracked with Sieve Pro, with the money kept. Without Pro — or in an +// open-source build, where pro/streaks.js is an empty stand-in — only the seal. const PRO_LINE_KEYS = ["proLicence", "proSeal", "proHabits", "habitAttempts"]; async function updateProLines() { @@ -153,13 +153,15 @@ async function updateProLines() { const P = window.SievePro; const S = window.SieveSeal; const ST = window.SieveStreaks; - if (!el || !P || !S || !ST) return; + if (!el) return; const now = Date.now(); const lines = []; try { - const seal = await S.check(now); - if (seal.sealed) lines.push(`Sealed until ${S.formatDay(seal.until)}`); - if (await P.isPro(now)) { + if (S) { + const seal = await S.check(now); + if (seal.sealed) lines.push(`Sealed until ${S.formatDay(seal.until)}`); + } + if (P && ST && (await P.isPro(now))) { for (const row of (await ST.summary(now)).slice(0, 3)) { const parts = [row.label, row.days === 0 ? "starting today" : ST.daysLabel(row.days)]; if (row.keptLabel) parts.push(`about ${row.keptLabel} kept`); @@ -167,7 +169,7 @@ async function updateProLines() { } } } catch (err) { - console.warn("[Sieve] popup: could not read Pro state:", err); + console.warn("[Sieve] popup: could not read the seal or streaks:", err); } el.textContent = ""; for (const line of lines) { diff --git a/pro/README.md b/pro/README.md index d85c920..799a549 100644 --- a/pro/README.md +++ b/pro/README.md @@ -4,10 +4,9 @@ The files in this folder are empty stand-ins for **Sieve Pro**: | File | The feature | | --- | --- | -| `seal.js` | The Seal: lock your protection until a date, with one emergency key | | `urge.js` | The urge screen, on the block page, and recording attempts for streaks | | `streaks.js` | Streaks and money kept, and the habits the urge screen knows about | -| `settings.js` | The Seal, urge screen and streaks groups in Settings › Sieve Pro | +| `settings.js` | The urge screen and streaks groups in Settings › Sieve Pro | | `features.js` | Which Pro features a build carries (here: none) | Sieve Pro is not open source. It lives in a separate, private repository and @@ -17,7 +16,8 @@ Edge Add-ons and Firefox Add-ons carry it. **Every protection is open source and here**: every blocker and its lists, the filters, the Dark Pattern Blocker, the Doomscroll Stopper, the Guardian -Lock, the cool-off, and everything else that decides what is blocked. A build +Lock, the cool-off, the Seal, and everything else that decides what is +blocked or guards your settings. A build made from this repository protects exactly as the store version does. Without Pro, Settings has no Sieve Pro section, and the block page is the plain notice. diff --git a/pro/seal.js b/pro/seal.js deleted file mode 100644 index a0202f8..0000000 --- a/pro/seal.js +++ /dev/null @@ -1,5 +0,0 @@ -// pro/seal.js — an empty stand-in. See pro/README.md. -// -// The Seal. Without it, there is no seal to start, and the Guardian gate -// (common/guardian-prompt.js) finds no SieveSeal and goes straight on to the -// cool-off and the PIN, as it always has. diff --git a/test/pro-standins-test.mjs b/test/pro-standins-test.mjs index 30f4554..039fe0b 100644 --- a/test/pro-standins-test.mjs +++ b/test/pro-standins-test.mjs @@ -19,7 +19,7 @@ const read = (...p) => readFileSync(join(ROOT, ...p), "utf8"); const STANDINS = readdirSync(DIR).filter((f) => !f.endsWith(".md")).sort(); test("the stand-ins are the Pro files, and the README names each", () => { - assert.deepEqual(STANDINS, ["features.js", "seal.js", "settings.js", "streaks.js", "urge.js"]); + assert.deepEqual(STANDINS, ["features.js", "settings.js", "streaks.js", "urge.js"]); const readme = read("pro", "README.md"); for (const f of STANDINS) assert.ok(readme.includes("`" + f + "`"), `pro/README.md names ${f}`); }); @@ -47,12 +47,12 @@ test("the private repository can never be committed here", () => { }); test("everything that uses Pro checks it is there first", () => { - // The Guardian gate: no SieveSeal, no seal. - assert.match(read("common", "guardian-prompt.js"), /const S = window\.SieveSeal;\s*if \(!S\) return null;/); // The block page: no SieveUrge, the plain notice. assert.match(read("pages", "blocked.js"), /if \(window\.SieveUrge\) \{/); - // The popup: no seal or streaks, no Pro lines. - assert.match(read("popup", "popup.js"), /if \(!el \|\| !P \|\| !S \|\| !ST\) return;/); + // The popup: no streaks without Pro and pro/streaks.js; the seal line needs neither. + const popup = read("popup", "popup.js"); + assert.match(popup, /if \(P && ST && \(await P\.isPro\(now\)\)\) \{/); + assert.match(popup, /if \(S\) \{\s*const seal = await S\.check\(now\);/); // Settings: no features, no section at all. const options = read("options", "options.js"); assert.match(options, /Array\.isArray\(window\.SieveProFeatures\)/); @@ -61,17 +61,34 @@ test("everything that uses Pro checks it is there first", () => { test("pages load Pro from pro/, never from anywhere a stand-in cannot replace", () => { const pages = { - "options/options.html": ["../pro/seal.js", "../pro/features.js", "../pro/streaks.js", "../pro/settings.js"], - "popup/popup.html": ["../pro/seal.js", "../pro/streaks.js"], - "pages/blocked.html": ["../pro/seal.js", "../pro/streaks.js", "../pro/urge.js"], + "options/options.html": ["../pro/features.js", "../pro/streaks.js", "../pro/settings.js"], + "popup/popup.html": ["../pro/streaks.js"], + "pages/blocked.html": ["../pro/streaks.js", "../pro/urge.js"], }; for (const [page, scripts] of Object.entries(pages)) { const html = read(...page.split("/")); for (const s of scripts) assert.ok(html.includes(``), `${page} loads ${s}`); } +}); + +test("the Seal is a free protection: open source, loaded from common/, never from pro/", () => { + for (const page of ["options/options.html", "popup/popup.html", "pages/blocked.html"]) { + const html = read(...page.split("/")); + assert.ok(html.includes(''), `${page} loads common/seal.js`); + assert.ok(!html.includes("pro/seal.js"), `${page} does not look for the Seal in pro/`); + } for (const manifest of ["manifest.json", "manifest.firefox.json"]) { - assert.ok(read(manifest).includes('"pro/seal.js"'), `${manifest} injects pro/seal.js with the pause screen`); + assert.ok(read(manifest).includes('"common/seal.js"'), `${manifest} injects common/seal.js with the pause screen`); } + // Its settings live in the open-source page, in the Lock section, and never wait on Pro. + const options = read("options", "options.js"); + assert.match(options, /^function setupSeal\(store\) \{/m); + assert.match(options, /setupSeal\(store\);/); + const html = read("options", "options.html"); + const lock = html.slice(html.indexOf('id="section-security"'), html.indexOf('id="section-advanced"')); + assert.ok(lock.includes('id="seal-card"'), "the Seal is in Settings › Lock"); + const sealCard = lock.slice(lock.indexOf('id="seal-card"'), lock.indexOf('id="desktop-guard-card"')); + assert.doesNotMatch(sealCard, /pro-(feature|control|note)/, "nothing in the Seal group waits on Pro"); }); test("the builds copy pro/ and hand it to build-pro.mjs", () => { diff --git a/test/qr-test.mjs b/test/qr-test.mjs new file mode 100644 index 0000000..85d3cef --- /dev/null +++ b/test/qr-test.mjs @@ -0,0 +1,190 @@ +// test/qr-test.mjs +// The QR encoder (common/qr.js) is checked against published worked examples +// where they exist (the Reed-Solomon codewords), against the code's own +// algebra where they don't (BCH format and version words), and against the +// layout rules a scanner relies on (finder patterns, timing, module counts). +// Ported from BlockNSFW's tests/qr.test.js. +// +// node --test test/ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const QrCode = require("../common/qr.js"); +const Q = QrCode._internal; + +const SEAL_URI = "otpauth://totp/Sieve:Seal?secret=JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP&issuer=Sieve"; + +test('Reed-Solomon: the "HELLO WORLD" 1-Q worked example', () => { + const data = [32, 91, 11, 120, 209, 114, 220, 77, 67, 64, 236, 17, 236]; + assert.deepEqual(Q.rsRemainder(data, Q.rsDivisor(13)), [168, 72, 22, 82, 217, 54, 156, 0, 46, 15, 180, 122, 16]); +}); + +test('Reed-Solomon: the "01234567" 1-M example from the standard', () => { + const data = [16, 32, 12, 86, 97, 128, 236, 17, 236, 17, 236, 17, 236, 17, 236, 17]; + assert.deepEqual(Q.rsRemainder(data, Q.rsDivisor(10)), [165, 36, 212, 193, 237, 54, 199, 135, 44, 85]); +}); + +test("data capacity at level M matches the standard tables", () => { + assert.equal(Q.dataCodewords(1), 16); + assert.equal(Q.dataCodewords(2), 28); + assert.equal(Q.dataCodewords(5), 86); + assert.equal(Q.dataCodewords(7), 124); + assert.equal(Q.dataCodewords(10), 216); +}); + +test("alignment pattern centres match the standard table", () => { + assert.deepEqual(Q.alignmentPositions(1), []); + assert.deepEqual(Q.alignmentPositions(2), [6, 18]); + assert.deepEqual(Q.alignmentPositions(7), [6, 22, 38]); + assert.deepEqual(Q.alignmentPositions(10), [6, 28, 50]); +}); + +function readFormatWord(matrix) { + let bits = 0; + for (let i = 0; i <= 5; i++) if (matrix.modules[i][8]) bits |= 1 << i; + if (matrix.modules[7][8]) bits |= 1 << 6; + if (matrix.modules[8][8]) bits |= 1 << 7; + if (matrix.modules[8][7]) bits |= 1 << 8; + for (let i = 9; i < 15; i++) if (matrix.modules[8][14 - i]) bits |= 1 << i; + return bits; +} + +function polyMod(value, generator, generatorDegree) { + let v = value; + for (let bit = 31; bit >= generatorDegree; bit--) { + if ((v >>> bit) & 1) v ^= generator << (bit - generatorDegree); + } + return v; +} + +test("format words are valid BCH(15,5) codewords for level M and every mask", () => { + for (let mask = 0; mask < 8; mask++) { + const matrix = new Q.Matrix(1); + matrix.drawFormatBits(mask); + const word = readFormatWord(matrix) ^ 0x5412; + assert.equal(polyMod(word, 0x537, 10), 0, `mask ${mask}`); + assert.equal(word >>> 10, mask, "level M is 00, so the data bits are the mask"); + } +}); + +test("both copies of the format word agree, and the dark module is set", () => { + const matrix = new Q.Matrix(3); + matrix.drawFormatBits(5); + const size = matrix.size; + let second = 0; + for (let i = 0; i < 8; i++) if (matrix.modules[8][size - 1 - i]) second |= 1 << i; + for (let i = 8; i < 15; i++) if (matrix.modules[size - 15 + i][8]) second |= 1 << i; + assert.equal(second, readFormatWord(matrix)); + assert.equal(matrix.modules[size - 8][8], true); +}); + +test("version 7 carries the version word from the standard (0x07C94)", () => { + const matrix = new Q.Matrix(7); + matrix.drawVersion(); + let bits = 0; + for (let i = 0; i < 18; i++) { + if (matrix.modules[Math.floor(i / 3)][matrix.size - 11 + (i % 3)]) bits |= 1 << i; + } + assert.equal(bits, 0x07c94); +}); + +test("every non-function module holds a data bit, for versions 1 to 10", () => { + for (let version = 1; version <= 10; version++) { + const matrix = new Q.Matrix(version); + matrix.drawFunctionPatterns(); + let free = 0; + for (const row of matrix.isFunction) for (const used of row) if (!used) free++; + assert.equal(free, Q.rawDataModules(version), `version ${version}`); + } +}); + +test("finder patterns and timing patterns are where scanners look", () => { + const qr = QrCode.encode(SEAL_URI); + const m = qr.modules; + const s = qr.size; + for (const [ox, oy] of [[0, 0], [s - 7, 0], [0, s - 7]]) { + for (let i = 0; i < 7; i++) { + assert.equal(m[oy][ox + i], true); + assert.equal(m[oy + 6][ox + i], true); + assert.equal(m[oy + i][ox], true); + assert.equal(m[oy + i][ox + 6], true); + } + assert.equal(m[oy + 1][ox + 1], false); + assert.equal(m[oy + 3][ox + 3], true); + } + for (let i = 8; i < s - 8; i++) { + assert.equal(m[6][i], i % 2 === 0); + assert.equal(m[i][6], i % 2 === 0); + } +}); + +const MASKS = [ + (x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, (x) => x % 3 === 0, (x, y) => (x + y) % 3 === 0, + (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => (x * y) % 2 + (x * y) % 3 === 0, + (x, y) => ((x * y) % 2 + (x * y) % 3) % 2 === 0, (x, y) => ((x + y) % 2 + (x * y) % 3) % 2 === 0, +]; + +// Undo the mask named in the format word and walk the zigzag, the way a +// scanner does, and return the raw codeword bytes. +function readCodewords(qr) { + const blank = new Q.Matrix(qr.version); + blank.drawFunctionPatterns(); + const mask = (readFormatWord({ modules: qr.modules }) ^ 0x5412) >>> 10; + const bits = []; + const size = qr.size; + for (let right = size - 1; right >= 1; right -= 2) { + if (right === 6) right = 5; + for (let vert = 0; vert < size; vert++) { + for (let j = 0; j < 2; j++) { + const x = right - j; + const y = ((right + 1) & 2) === 0 ? size - 1 - vert : vert; + if (!blank.isFunction[y][x]) bits.push(qr.modules[y][x] !== MASKS[mask](x, y) ? 1 : 0); + } + } + } + const bytes = []; + for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0)); + return bytes; +} + +test("reading a one-block code back gives its data and error correction", () => { + const text = "otpauth://totp/Sieve?secret=ABCDEFGH"; + const qr = QrCode.encode(text); + assert.ok(qr.version <= 3, "versions 1-3 at level M are a single block"); + const bytes = readCodewords(qr); + const data = Q.encodeData([...new TextEncoder().encode(text)], qr.version); + assert.deepEqual(bytes.slice(0, data.length), data); + assert.deepEqual(bytes.slice(data.length), Q.rsRemainder(data, Q.rsDivisor(bytes.length - data.length))); +}); + +test("a Seal key, read back, de-interleaves into valid blocks that carry the whole key", () => { + // Undo the column-by-column interleaving independently of the encoder. + const qr = QrCode.encode(SEAL_URI); + const bytes = readCodewords(qr); + const data = Q.encodeData([...new TextEncoder().encode(SEAL_URI)], qr.version); + const ECC = [10, 16, 26, 18, 24, 16, 18, 22, 22, 26][qr.version - 1]; + const BLOCKS = [1, 1, 1, 2, 2, 4, 4, 4, 5, 5][qr.version - 1]; + const raw = Math.floor(Q.rawDataModules(qr.version) / 8); + const short = Math.floor(raw / BLOCKS) - ECC; + assert.equal(raw % BLOCKS, 0, "this test assumes equal blocks"); + for (let block = 0; block < BLOCKS; block++) { + const blockData = []; + for (let i = 0; i < short; i++) blockData.push(bytes[i * BLOCKS + block]); + const blockEcc = []; + for (let i = 0; i < ECC; i++) blockEcc.push(bytes[short * BLOCKS + i * BLOCKS + block]); + assert.deepEqual(blockData, data.slice(block * short, block * short + short), `block ${block} data`); + assert.deepEqual(blockEcc, Q.rsRemainder(blockData, Q.rsDivisor(ECC)), `block ${block} ecc`); + } +}); + +test("toPath draws one square per dark module, inside a 4-module quiet zone", () => { + const qr = QrCode.encode("hi"); + const path = QrCode.toPath(qr); + let dark = 0; + for (const row of qr.modules) for (const cell of row) if (cell) dark++; + assert.equal((path.match(/M/g) || []).length, dark); + assert.ok(path.startsWith("M4 4"), "the top-left finder starts after the quiet zone"); +}); diff --git a/test/seal-test.mjs b/test/seal-test.mjs new file mode 100644 index 0000000..56bd0ab --- /dev/null +++ b/test/seal-test.mjs @@ -0,0 +1,295 @@ +// test/seal-test.mjs +// Sieve — tests for common/seal.js, the Seal. +// +// A seal that can be shortened, a key that is stored readable, a key that only +// works typed exactly as printed, or a seal that quietly outlives its date — +// each of those breaks the one promise it makes. The dialog that refuses a +// change is checked in a real browser; this covers the bookkeeping. +// +// node --test test/ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; + +const backing = new Map(); + +function keysOf(arg) { + if (arg == null) return [...backing.keys()]; + if (typeof arg === "string") return [arg]; + if (Array.isArray(arg)) return arg; + return Object.keys(arg); +} + +globalThis.chrome = { + storage: { + local: { + async get(arg) { + const out = {}; + for (const key of keysOf(arg)) { + if (backing.has(key)) out[key] = structuredClone(backing.get(key)); + else if (arg && typeof arg === "object" && !Array.isArray(arg)) out[key] = arg[key]; + } + return out; + }, + async set(patch) { + for (const [key, value] of Object.entries(patch)) backing.set(key, structuredClone(value)); + }, + async remove(arg) { + for (const key of keysOf(arg)) backing.delete(key); + }, + }, + }, +}; + +globalThis.window = globalThis; +// Pages load common/totp.js as a classic script before seal.js; under Node it +// is a CommonJS module, so it is handed over by name the way a page would. +const Totp = createRequire(import.meta.url)("../common/totp.js"); +globalThis.SieveTotp = Totp; +await import("../common/seal.js"); +const S = globalThis.SieveSeal; + +const DAY = 24 * 3600000; +const T0 = Date.UTC(2026, 9, 29, 9, 0, 0); + +function reset() { + backing.clear(); +} + +test("a key is twenty characters in five groups, with no look-alike characters", () => { + for (let i = 0; i < 200; i++) { + const key = S.generateKey(); + assert.match(key, /^[A-Z2-9]{4}(-[A-Z2-9]{4}){4}$/); + assert.doesNotMatch(key, /[01IO]/); + } + assert.notEqual(S.generateKey(), S.generateKey()); +}); + +test("starting a seal gives the key once and stores only its hash", async () => { + reset(); + const result = await S.start(30, T0); + assert.equal(result.ok, true); + assert.equal(result.until, T0 + 30 * DAY); + + const stored = backing.get(S.SEAL_KEY); + const raw = S.normalizeKey(result.key); + assert.equal(JSON.stringify(stored).includes(raw), false); + assert.equal(JSON.stringify(stored).includes(result.key), false); + assert.match(stored.keyHash, /^[0-9a-f]{64}$/); + assert.match(stored.keySalt, /^[0-9a-f]{32}$/); +}); + +test("only the offered lengths can be chosen", async () => { + reset(); + assert.deepEqual(await S.start(1, T0), { ok: false, reason: "bad-duration" }); + assert.deepEqual(await S.start(-30, T0), { ok: false, reason: "bad-duration" }); + assert.equal(backing.has(S.SEAL_KEY), false); + for (const days of S.DURATIONS) { + reset(); + assert.equal((await S.start(days, T0)).ok, true); + } +}); + +test("a seal holds until its date, then ends on the clock alone", async () => { + reset(); + await S.start(7, T0); + assert.equal((await S.check(T0)).sealed, true); + assert.equal((await S.check(T0 + 7 * DAY - 1)).sealed, true); + assert.equal((await S.check(T0 + 7 * DAY)).sealed, false); + // An ended seal is dropped as it is found. + assert.equal(backing.has(S.SEAL_KEY), false); +}); + +test("a running seal cannot be restarted (which would mint a new key)", async () => { + reset(); + await S.start(30, T0); + assert.deepEqual(await S.start(7, T0 + DAY), { ok: false, reason: "already-sealed" }); + assert.equal(backing.get(S.SEAL_KEY).until, T0 + 30 * DAY); +}); + +test("extending adds days and keeps the key", async () => { + reset(); + const { key } = await S.start(7, T0); + const result = await S.extend(30, T0 + DAY); + assert.deepEqual(result, { ok: true, until: T0 + 37 * DAY }); + assert.equal(await S.matchesKey(key, T0 + DAY), true); + assert.deepEqual(await S.extend(30, T0 + 40 * DAY), { ok: false, reason: "not-sealed" }); +}); + +test("there is no way to shorten a seal", () => { + assert.equal(typeof S.shorten, "undefined"); + assert.equal(typeof S.clear, "undefined"); + assert.equal(typeof S.setUntil, "undefined"); +}); + +test("the emergency key ends the seal; a wrong key does nothing", async () => { + reset(); + const { key } = await S.start(90, T0); + assert.equal((await S.breakWith("ABCD-EFGH-JKLM-NPQR-STUV", T0 + DAY)).ok, false); + assert.equal((await S.breakWith("", T0 + DAY)).ok, false); + assert.equal((await S.check(T0 + DAY)).sealed, true); + + assert.deepEqual(await S.breakWith(key, T0 + DAY), { ok: true }); + assert.equal((await S.check(T0 + DAY)).sealed, false); + assert.equal(backing.has(S.SEAL_KEY), false); +}); + +test("the key is accepted however it is typed back from paper", async () => { + reset(); + const { key } = await S.start(30, T0); + const plain = S.normalizeKey(key); + for (const typed of [key, plain, plain.toLowerCase(), ` ${key.replace(/-/g, " ")} `, key.toLowerCase()]) { + assert.equal(await S.matchesKey(typed, T0), true, `typed as ${JSON.stringify(typed)}`); + } +}); + +test("with no seal, a code does nothing", async () => { + reset(); + assert.deepEqual(await S.breakWith("ABCD-EFGH-JKLM-NPQR-STUV", T0), { ok: false, reason: "not-sealed" }); +}); + +test("a damaged record reads as no seal rather than a lock with no way out", () => { + assert.equal(S.stateOf({ until: T0 + DAY, startedAt: T0 }, T0), "none"); + assert.equal(S.stateOf({ until: "soon", startedAt: T0, keySalt: "a", keyHash: "b" }, T0), "none"); + assert.equal(S.stateOf({ until: T0 + DAY, startedAt: T0, exit: "witness", witness: {} }, T0), "none"); + assert.equal(S.stateOf(null, T0), "none"); +}); + +test("a seal from before witnesses (no exit) still reads as a key seal", () => { + const legacy = { until: T0 + DAY, startedAt: T0, keySalt: "a", keyHash: "b" }; + assert.equal(S.stateOf(legacy, T0), "sealed"); + assert.equal(S.normalizeSeal(legacy).exit, "key"); +}); + +// --- the witness ------------------------------------------------------------ + +async function sealWithWitness(days = 30, at = T0) { + const pairing = S.pairWitness(); + const code = await Totp.totp(pairing.secret, at); + const result = await S.startWithWitness(days, pairing, code, at); + return { pairing, result }; +} + +test("pairing makes a scannable key and eight recovery codes, and stores nothing yet", () => { + reset(); + const pairing = S.pairWitness(); + assert.equal(Totp.base32Decode(pairing.secret).length, 20); + assert.equal(pairing.uri, `otpauth://totp/Sieve:Seal?secret=${pairing.secret}&issuer=Sieve`); + assert.equal(pairing.recoveryCodes.length, 8); + assert.equal(backing.size, 0); +}); + +test("the seal starts only once the witness's app shows a code that works", async () => { + reset(); + const pairing = S.pairWitness(); + assert.deepEqual(await S.startWithWitness(30, pairing, "000000", T0), { ok: false, reason: "wrong-code" }); + assert.deepEqual(await S.startWithWitness(30, pairing, "", T0), { ok: false, reason: "wrong-code" }); + assert.equal(backing.has(S.SEAL_KEY), false); + + const code = await Totp.totp(pairing.secret, T0); + assert.deepEqual(await S.startWithWitness(30, pairing, code, T0), { ok: true, until: T0 + 30 * DAY }); + const info = await S.check(T0); + assert.equal(info.exit, "witness"); + assert.equal(info.recoveryLeft, 8); +}); + +test("recovery codes are stored only as hashes", async () => { + reset(); + const { pairing } = await sealWithWitness(); + const stored = JSON.stringify(backing.get(S.SEAL_KEY)); + for (const c of pairing.recoveryCodes) { + assert.equal(stored.includes(c), false); + assert.equal(stored.includes(c.replace("-", "")), false); + } +}); + +test("the code that started the seal cannot end it", async () => { + reset(); + const { pairing } = await sealWithWitness(); + const sameCode = await Totp.totp(pairing.secret, T0); + assert.equal((await S.breakWith(sameCode, T0 + 10000)).ok, false); + assert.equal((await S.check(T0 + 10000)).sealed, true); +}); + +test("a fresh code from the witness's app ends the seal", async () => { + reset(); + const { pairing } = await sealWithWitness(); + const later = T0 + 3 * DAY; + const code = await Totp.totp(pairing.secret, later); + assert.deepEqual(await S.breakWith(code, later), { ok: true }); + assert.equal((await S.check(later)).sealed, false); +}); + +test("a recovery code ends the seal, typed any way; a made-up one does not", async () => { + reset(); + const { pairing } = await sealWithWitness(); + assert.equal((await S.breakWith("ACDE-FGHJ", T0 + DAY)).ok, false); + const typed = pairing.recoveryCodes[3].toLowerCase().replace("-", " "); + assert.deepEqual(await S.breakWith(typed, T0 + DAY), { ok: true }); +}); + +test("a printed key does not open a witness's seal, nor a witness code a key's", async () => { + reset(); + const { key } = await S.start(30, T0); + assert.equal((await S.breakWith("123456", T0 + DAY)).ok, false); + reset(); + await sealWithWitness(); + assert.equal(await S.matchesKey(key, T0 + DAY), false); +}); + +test("five wrong codes lock entry for 5 minutes, then 10, up to an hour", async () => { + reset(); + const { pairing } = await sealWithWitness(); + let at = T0 + DAY; + for (let i = 1; i <= 4; i++) assert.deepEqual(await S.breakWith("000000", at), { ok: false }); + assert.deepEqual(await S.breakWith("000000", at), { ok: false, locked: true, retryAt: at + 5 * 60000 }); + + // While locked, even the right code waits. + const right = await Totp.totp(pairing.secret, at + 60000); + assert.deepEqual(await S.breakWith(right, at + 60000), { ok: false, locked: true, retryAt: at + 5 * 60000 }); + assert.equal((await S.check(at + 60000)).lockedUntil, at + 5 * 60000); + + at += 5 * 60000; + for (let i = 1; i <= 4; i++) await S.breakWith("000000", at); + assert.equal((await S.breakWith("000000", at)).retryAt, at + 10 * 60000); + + assert.equal(S.lockFor(5), 5 * 60000); + assert.equal(S.lockFor(10), 10 * 60000); + assert.equal(S.lockFor(25), 60 * 60000); + assert.equal(S.lockFor(40), 60 * 60000); + assert.equal(S.lockFor(7), 0); + + // Once the lock is over, the right code still works. + at += 10 * 60000; + const code = await Totp.totp(pairing.secret, at); + assert.deepEqual(await S.breakWith(code, at), { ok: true }); +}); + +test("a burst of guesses fired together still counts every one, and locks", async () => { + reset(); + await sealWithWitness(); + const at = T0 + DAY; + const results = await Promise.all(["111111", "222222", "333333", "444444", "555555", "666666"].map((c) => S.breakWith(c, at))); + assert.equal(backing.get(S.SEAL_KEY).failures, 5, "the sixth was refused by the lock, uncounted"); + assert.equal(results.filter((r) => r.locked).length, 2); + assert.equal(results[5].retryAt, at + 5 * 60000); +}); + +test("extending a witness's seal keeps the witness", async () => { + reset(); + const { pairing } = await sealWithWitness(7); + await S.extend(30, T0 + DAY); + const later = T0 + 20 * DAY; + assert.equal((await S.check(later)).sealed, true); + assert.deepEqual(await S.breakWith(await Totp.totp(pairing.secret, later), later), { ok: true }); +}); + +test("the seal is free: it starts and holds with no Pro licence at all", async () => { + reset(); + // Sieve Pro's licence is a separate key; nothing here reads it. + assert.equal((await S.start(30, T0)).ok, true); + assert.equal((await S.check(T0 + DAY)).sealed, true); + backing.set("proLicence", { key: "SIEVE-X", status: "revoked" }); + assert.equal((await S.check(T0 + DAY)).sealed, true); +}); diff --git a/test/totp-test.mjs b/test/totp-test.mjs new file mode 100644 index 0000000..d94528d --- /dev/null +++ b/test/totp-test.mjs @@ -0,0 +1,109 @@ +// test/totp-test.mjs +// Witness codes are only useful if they match what an ordinary authenticator +// app shows, so these pin common/totp.js to the published test vectors rather +// than to itself. Ported from BlockNSFW's tests/totp.test.js. +// +// node --test test/ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const Totp = require("../common/totp.js"); + +// RFC 4226 and RFC 6238 both use the ASCII secret "12345678901234567890". +const RFC_SECRET = Totp.base32Encode(new TextEncoder().encode("12345678901234567890")); + +test("base32 round-trips bytes", () => { + const bytes = new Uint8Array([0, 1, 2, 250, 251, 252, 253, 254, 255, 17]); + assert.deepEqual([...Totp.base32Decode(Totp.base32Encode(bytes))], [...bytes]); +}); + +test("base32Decode accepts spaces, lower case and padding, and refuses junk", () => { + const secret = Totp.base32Encode(new Uint8Array([104, 105, 33])); + const typed = secret.toLowerCase().replace(/(.{2})/g, "$1 ") + "==="; + assert.deepEqual([...Totp.base32Decode(typed)], [104, 105, 33]); + assert.equal(Totp.base32Decode("not base32 !"), null); + assert.equal(Totp.base32Decode(""), null); +}); + +test("hotp matches the RFC 4226 test vectors", async () => { + const expected = ["755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"]; + const bytes = Totp.base32Decode(RFC_SECRET); + for (let counter = 0; counter < expected.length; counter++) { + assert.equal(await Totp.hotp(bytes, counter), expected[counter], `counter ${counter}`); + } +}); + +test("8-digit TOTP matches the RFC 6238 SHA-1 test vectors", async () => { + const bytes = Totp.base32Decode(RFC_SECRET); + const vectors = [ + [59, "94287082"], + [1111111109, "07081804"], + [1111111111, "14050471"], + [1234567890, "89005924"], + [2000000000, "69279037"], + [20000000000, "65353130"], + ]; + for (const [seconds, code] of vectors) { + assert.equal(await Totp.hotp(bytes, Totp.counterAt(seconds * 1000), 8), code, `T=${seconds}`); + } +}); + +test("verify accepts the current code and one step either side", async () => { + const now = 1234567890 * 1000; + for (const offset of [-30000, 0, 30000]) { + const code = await Totp.totp(RFC_SECRET, now + offset); + assert.equal((await Totp.verify(RFC_SECRET, code, { times: [now] })).ok, true, `offset ${offset}`); + } +}); + +test("verify refuses a code from two minutes ago", async () => { + const now = 1234567890 * 1000; + const old = await Totp.totp(RFC_SECRET, now - 120000); + assert.equal((await Totp.verify(RFC_SECRET, old, { times: [now] })).ok, false); +}); + +test("verify refuses a code that was already used", async () => { + const now = 1234567890 * 1000; + const code = await Totp.totp(RFC_SECRET, now); + const first = await Totp.verify(RFC_SECRET, code, { times: [now] }); + assert.equal(first.ok, true); + const again = await Totp.verify(RFC_SECRET, code, { times: [now], lastCounter: first.counter }); + assert.equal(again.ok, false); +}); + +test("verify ignores spaces in a typed code and refuses the wrong length", async () => { + const now = 1234567890 * 1000; + const code = await Totp.totp(RFC_SECRET, now); + assert.equal((await Totp.verify(RFC_SECRET, code.slice(0, 3) + " " + code.slice(3), { times: [now] })).ok, true); + assert.equal((await Totp.verify(RFC_SECRET, code.slice(0, 5), { times: [now] })).ok, false); +}); + +test("generateSecret makes 160-bit keys that differ", () => { + const a = Totp.generateSecret(); + const b = Totp.generateSecret(); + assert.equal(Totp.base32Decode(a).length, 20); + assert.notEqual(a, b); +}); + +test("otpauthUri is the format authenticator apps read, named for Sieve", () => { + assert.equal( + Totp.otpauthUri("JBSWY3DPEHPK3PXP", "Seal"), + "otpauth://totp/Sieve:Seal?secret=JBSWY3DPEHPK3PXP&issuer=Sieve", + ); +}); + +test("recovery codes are unambiguous, and their hashes ignore case and dashes", async () => { + const codes = Totp.generateRecoveryCodes(); + assert.equal(codes.length, 8); + assert.equal(new Set(codes).size, 8); + for (const code of codes) { + assert.match(code, /^[ACDEFGHJKMNPQRTUVWXY34679]{4}-[ACDEFGHJKMNPQRTUVWXY34679]{4}$/); + assert.equal(Totp.looksLikeRecoveryCode(code), true); + } + const [first] = codes; + assert.equal(await Totp.hashRecoveryCode(first), await Totp.hashRecoveryCode(first.toLowerCase().replace("-", " "))); + assert.equal(Totp.looksLikeRecoveryCode("123456"), false); +}); From 2484d7b224e298abaab2483165d87e9c47ad10e2 Mon Sep 17 00:00:00 2001 From: Alfon Date: Thu, 29 Oct 2026 22:25:40 +0800 Subject: [PATCH 05/12] Sieve Pro: urge-screen designs, voice, proof it passes, your progress The additions chosen on 2026-10-29, ported from BlockNSFW's extras: - The urge screen's centre can be a breathing ring, an enso or a river. - Proof it passes: "I'm OK now" puts the minute an urge passed on a dial, and the dial runs through them the next time. - A message in your own voice (or a song), recorded in Settings and played on the urge screen; kept in IndexedDB on the device. - Streaks gain a savings goal. - Your progress (pages/progress.html): when it tends to get hard, by weekday and hour; the dial; a letter for every month and year. Free foundation they read: common/attempts.js keeps WHEN the block page stopped you (habits only, never threats or addresses; 5-minute merge, 400 days), written by the service worker on SIEVE_RECORD_ATTEMPT; and monthly stats are folded in the stats prune. The pro/ files here are the public stand-ins; the features live in the private repo. Co-Authored-By: Claude Opus 5.5 --- PRIVACY.md | 15 +- README.md | 4 +- background/service-worker.js | 4 + common/attempts.js | 163 ++++++++++ common/changelog.js | 11 +- common/stats.js | 41 +++ options/options.css | 114 +++++++ options/options.html | 43 ++- options/options.js | 13 +- pages/blocked.html | 525 ++++++++++++++++++++++++++++++- pages/blocked.js | 15 + pages/progress.css | 577 +++++++++++++++++++++++++++++++++++ pages/progress.html | 151 +++++++++ pages/progress.js | 16 + popup/popup.css | 24 ++ popup/popup.js | 56 +++- pro/README.md | 8 +- pro/designs.js | 4 + pro/insights.js | 5 + pro/progress.js | 5 + pro/voice.js | 4 + test/attempts-test.mjs | 114 +++++++ test/pro-standins-test.mjs | 13 +- test/stats-months-test.mjs | 43 +++ 24 files changed, 1935 insertions(+), 33 deletions(-) create mode 100644 common/attempts.js create mode 100644 pages/progress.css create mode 100644 pages/progress.html create mode 100644 pages/progress.js create mode 100644 pro/designs.js create mode 100644 pro/insights.js create mode 100644 pro/progress.js create mode 100644 pro/voice.js create mode 100644 test/attempts-test.mjs create mode 100644 test/stats-months-test.mjs diff --git a/PRIVACY.md b/PRIVACY.md index 456b88c..e305663 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -31,7 +31,7 @@ described [below](#sieve-pro-licence-check). Without Pro, nothing changes. Sieve is open source, so anyone can verify these claims: . The one exception is Sieve Pro's -features (the urge screen and streaks), which are not open source. +features (the urge screen, streaks and Your progress), which are not open source. They make no network requests and keep everything on your device, and the licence check, the only request Pro makes, is part of the open-source code (`common/pro.js`), so what it sends can be checked by anyone. @@ -56,10 +56,14 @@ third party. | What a page claimed, while the Dark Pattern Blocker is on | Tell a fake countdown or stock number from a real one on your next visit — see [below](#what-the-dark-pattern-blocker-remembers) | Yes | | Free-trial reminders, **only the ones you ask for** | Remind you before a free trial starts charging — see [below](#free-trial-reminders) | Yes | | When the block page last stopped each kind of site | One date and time per kind (gambling, dating, games, AI tools, trading, your own blocked sites) and your longest gap, for Sieve Pro's streaks — never the site or its address | Yes | +| When the block page stopped you, for the kinds of site you block for yourself | The time and the kind (gambling, dating, games, AI tools, trading, your own blocked sites) of each stop, kept for a year, so Sieve Pro can show when it tends to get hard and write your month — never the site or its address, and never threats such as scam or malware sites. Kept for everyone, Pro or not | Yes | +| Monthly block totals | The Protection Dashboard keeps its daily counts for 30 days; as a day leaves, its counts are added to its month, for about two years — counts only, never a site | Yes | +| Urges waited out, **only if you press "I'm OK now"** | When, how long it took, and the kind of site, to draw Sieve Pro's Proof it passes dial | Yes | +| A message in your own voice, **only if you record or choose one** | The recording or sound file, stored in the extension's own database in your browser, and played on the urge screen. The microphone is used only while you record | Yes | | Sieve Pro licence key, **only if you enter one** | Turn on the Pro features | Kept on your device; checked with Polar — see [below](#sieve-pro-licence-check) | | Seal, **only if you start one** | When it ends, and its way out: either the key your witness's authenticator app shares with Sieve (needed to check their codes) and their recovery codes as **hashes**, or the emergency key as a **hash**. A witness's app works offline; nothing is sent to them, us or anyone | Yes | | Urge screen, **only what you fill in** | Your reason, an optional photo (shrunk to fit 800 pixels), and a contact's name and number or email address, shown on the block page | Yes | -| Streak settings, **only for what you track** | The day you stopped, and what it used to cost you, to count streaks and money kept | Yes | +| Streak settings, **only for what you track** | The day you stopped, what it used to cost you, and what you are saving for, to count streaks, money kept and how close the goal is | Yes | Sieve also reads the content of web pages you visit **in the page itself** — for example, to mask profanity, hide toxic comments, remove dark patterns, or count @@ -150,8 +154,8 @@ extension sends. If you say no, nothing is sent and Pro stays off. Nobody who does not activate Pro is ever asked. The key is kept on your device so it can be checked again. The Pro features -themselves (the urge screen and streaks) run entirely on your device, like the -rest of Sieve. +themselves (the urge screen, streaks and Your progress) run entirely on your +device, like the rest of Sieve. --- @@ -234,7 +238,8 @@ To be plain about the cases where that wording could mislead: if you switch on Usage Insights, a tally of site names and durations is written **to your own browser storage**; the Dark Pattern Blocker writes the numbers described above under scrambled codes; a free-trial reminder you ask for keeps that -site's name and dates; and Sieve Pro's streaks and urge screen keep what is +site's name and dates; the block page keeps when it stopped you, by kind of +site; and Sieve Pro's streaks, urge screen and voice message keep what is listed in the table above. You can erase any of them at any time. Nothing about them is ever sent to us or to a third party, which is why the declaration above is still accurate. diff --git a/README.md b/README.md index 991ba2e..82993e0 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,9 @@ Sieve elects the CC arm of EasyList's GPLv3 / CC BY-SA 3.0 dual licence; BY-SA's "Collection" clause is what keeps the rest of the project MIT. Editing that one file means editing a BY-SA file — see [`data/ATTRIBUTION-easylist.md`](data/ATTRIBUTION-easylist.md). -**Sieve Pro** (the urge screen and streaks) is not open source and is not in +**Sieve Pro** (the urge screen with its designs and voice message, streaks with a +savings goal, and Your progress: hardest hours, proof it passes, the month and +year letters) is not open source and is not in this repository: [`pro/`](pro/README.md) holds empty stand-ins, and the store versions of Sieve carry the real files. Every protection is here, so a build from this repository blocks exactly what the store version does. Build one with diff --git a/background/service-worker.js b/background/service-worker.js index c81dfea..c42be9a 100644 --- a/background/service-worker.js +++ b/background/service-worker.js @@ -29,10 +29,14 @@ import "./trial-reminders.js"; // Dark Pattern Blocker — the free-trial remind // lives. The settings page and the content script load the same file, so all // three agree on what an entry means. import "../common/keyword-pattern.js"; +// Also a plain script: the attempt record (when the block page stopped a habit), +// which this worker alone writes so two block pages cannot lose an entry. +import "../common/attempts.js"; import { buildCustomBlockRules } from "./custom-block-rules.js"; // blocked-sites list -> dynamic rules import { installStatsListener, installStatsAlarmHandler, scheduleStatsMidnightAlarm } from "../common/stats.js"; // Shared Protection Dashboard stats store installStatsListener(); +self.SieveAttempts.installListener(); installStatsAlarmHandler(); scheduleStatsMidnightAlarm(); diff --git a/common/attempts.js b/common/attempts.js new file mode 100644 index 0000000..a0f71b1 --- /dev/null +++ b/common/attempts.js @@ -0,0 +1,163 @@ +// common/attempts.js +// Sieve — the attempt record: when the block page stopped a site from a list +// someone chose to block for themselves. +// +// The block page already counts blocks per day for the dashboard +// (common/stats.js). This keeps the moments themselves, a time and the kind of +// site, because "when" is the one thing a daily count throws away and the one +// someone trying to stop most wants to know: Friday nights after eleven, the +// evening after payday. Sieve Pro reads it (when it's hardest, your month and +// your year); nothing that blocks does. +// +// Only habits are recorded: the kinds of site a person turns on to stop +// themselves (gambling, dating, their own blocked sites, games, AI tools, +// trading). Threats, such as scam sites, malware and phishing, are not urges +// and never appear here. +// +// It is written for everyone, Pro or not, on this device, next to the daily +// counts, so someone who buys Pro later sees the months before. Nothing is +// sent anywhere. +// +// Storage, chrome.storage.local: +// sieveAttempts { v: 1, since: , a: [[, ], ...] } oldest first +// +// One urge often reaches the block page more than once: a reload, a second +// try, a site that hops through two of its own domains. A repeat of the same +// category within MERGE_MS of the last one is the same attempt, not a new one. +// The record keeps KEEP_DAYS (a year and a little, so a whole year can be +// told) and at most MAX entries. +// +// The service worker writes it (installListener), so two block pages opening +// at once cannot lose one another's entry; pages only read it. + +(() => { + "use strict"; + + const root = typeof self !== "undefined" ? self : globalThis; + if (root.SieveAttempts) return; + + const KEY = "sieveAttempts"; + const MESSAGE = "SIEVE_RECORD_ATTEMPT"; + const DAY = 24 * 60 * 60 * 1000; + const MERGE_MS = 5 * 60 * 1000; + const KEEP_DAYS = 400; + const MAX = 6000; + + // The block page's ?category= values that are habits. pro/streaks.js groups + // them into the habits a person tracks. + const CATEGORIES = [ + "gambling", + "prediction-markets", + "dating", + "custom-blocked", + "games-portals", + "games-stores", + "games-platforms", + "games-streaming", + "ai-chatbots", + "ai-writing", + "ai-companions", + "trading", + ]; + + function normalize(raw) { + const src = raw && typeof raw === "object" ? raw : {}; + const list = Array.isArray(src.a) ? src.a : []; + const a = list + .filter( + (e) => + Array.isArray(e) && + Number.isFinite(e[0]) && + e[0] > 0 && + typeof e[1] === "string" && + CATEGORIES.includes(e[1]), + ) + .map((e) => [Math.floor(e[0]), e[1]]) + .sort((x, y) => x[0] - y[0]); + let since = Number.isFinite(src.since) && src.since > 0 ? Math.floor(src.since) : null; + if (a.length && (since === null || a[0][0] < since)) since = a[0][0]; + return { v: 1, since, a }; + } + + // The record with this attempt in it, pruned to the window. `added` is false + // for a category that is not a habit and for a repeat inside MERGE_MS. + function add(raw, category, now = Date.now()) { + const record = normalize(raw); + const cutoff = now - KEEP_DAYS * DAY; + record.a = record.a.filter((e) => e[0] >= cutoff && e[0] <= now); + if (record.since === null) record.since = now; + if (!CATEGORIES.includes(category)) return { record, added: false }; + for (let i = record.a.length - 1; i >= 0; i--) { + if (now - record.a[i][0] >= MERGE_MS) break; + if (record.a[i][1] === category) return { record, added: false }; + } + record.a.push([now, category]); + if (record.a.length > MAX) record.a = record.a.slice(record.a.length - MAX); + return { record, added: true }; + } + + // The attempts between two moments, optionally only some categories. + function between(record, from, to, categories) { + const want = Array.isArray(categories) ? categories : null; + return normalize(record).a.filter( + (e) => e[0] >= from && e[0] < to && (!want || want.includes(e[1])), + ); + } + + async function get() { + const stored = await chrome.storage.local.get(KEY); + return normalize(stored[KEY]); + } + + // Writes queue behind one another in the one context that writes. + let writing = Promise.resolve(); + + function record(category, now = Date.now()) { + const run = writing.then(async () => { + const stored = await chrome.storage.local.get(KEY); + const before = normalize(stored[KEY]); + const { record: next, added } = add(before, category, now); + // The worker wakes often; a wake that changes nothing writes nothing. + if (added || next.since !== before.since || next.a.length !== before.a.length) { + await chrome.storage.local.set({ [KEY]: next }); + } + return added; + }); + writing = run.catch(() => {}); + return run; + } + + // Called once by the service worker. Only the block page sends the message. + // The record starts counting now if it has never started, so a month that + // passes without one attempt can still be told as a clear month. + function installListener() { + chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (!message || message.type !== MESSAGE) return false; + const page = chrome.runtime.getURL("pages/blocked.html"); + if (!sender || typeof sender.url !== "string" || !sender.url.startsWith(page)) return false; + record(message.category) + .then((added) => sendResponse({ ok: true, added })) + .catch((err) => { + console.warn("[Sieve] could not record the attempt:", err); + sendResponse({ ok: false }); + }); + return true; + }); + record(null).catch(() => {}); + } + + root.SieveAttempts = { + KEY, + MESSAGE, + MERGE_MS, + KEEP_DAYS, + MAX, + CATEGORIES, + normalize, + add, + between, + get, + record, + installListener, + }; +})(); diff --git a/common/changelog.js b/common/changelog.js index 9f03d3a..459d7c2 100644 --- a/common/changelog.js +++ b/common/changelog.js @@ -20,9 +20,14 @@ const SIEVE_CHANGELOG = [ "New, and free: the Seal, in Settings › Lock. It locks your protection until a date you choose: a week, 30 days, 90 days or a year. Until then nothing that weakens it can be changed, not with your PIN and not by waiting out a cool-off. Extending a seal is always allowed; shortening one is not.", "The way out early is held by a witness: someone you trust scans a QR code into the authenticator app they already use, and you ask them for the six digits it shows. They also keep eight recovery codes in case their phone is lost. Nothing is sent anywhere, and five wrong codes lock entry for a while. The seal only starts once their app has shown a code that works. If there is nobody to ask, choose a printed emergency key instead.", "A running seal shows in the toolbar popup, with the day it ends.", - "New: Sieve Pro, a one-time purchase with no subscription. Every protection stays free, the Seal included, and always will. Pro adds two things on top, for the hard moments and for seeing how far you have come, running on your device like the rest of Sieve.", - "The urge screen changes what you see when Sieve stops you at a blocked site. Instead of a notice, the page leads with ninety seconds of breathing, then your own reason in your own words, a photo if you chose one, and one tap to text, call or email someone you trust. Go back and Allow stay underneath, exactly as before.", - "Streaks count the days since you last tried to open a gambling site, a dating site, or any other kind you track, and what it would have cost: “23 days · about $1,140 kept”. They show in the toolbar popup and in settings, with your best run and the next milestone.", + "New: Sieve Pro, a one-time purchase with no subscription. Every protection stays free, the Seal included, and always will. Pro adds help for the hard moments and a way to see how far you have come, running on your device like the rest of Sieve.", + "The urge screen changes what you see when Sieve stops you at a blocked site. Instead of a notice, the page leads with something to do while the urge passes, then your own reason in your own words, a photo if you chose one, a message in your own voice, and one tap to text, call or email someone you trust. Go back and Allow stay underneath, exactly as before.", + "At its centre, choose a breathing ring, an ensō (hold to breathe in, let go to breathe out, and a brush draws one circle a breath), or a river to lead from the spring to the sea, a small puzzle with no clock and no score for the minutes an urge takes.", + "Proof it passes: press “I'm OK now” when an urge has passed, and it becomes a dot on a dial at the minute it passed. The next time, the dial's hand runs through them while you wait: “Your urges pass. Usually by minute 6.” In your hardest hours, the urge screen says so.", + "Record a message for yourself in Settings, or choose a song or a voice note from someone you love. The urge screen plays it with a tap, or by itself if you ask. It stays on your device; the microphone is on only while you record.", + "Streaks count the days since you last tried to open a gambling site, a dating site, or any other kind you track, and what it would have cost: “23 days · about $1,140 kept”. Give the money a goal, such as a trip or a debt paid off, and see how close it is. They show in the toolbar popup and in settings, with your best run and the next milestone.", + "Your progress, a page of its own: when it tends to get hard, by weekday and hour; the dial of every urge you have waited out; a letter after every month, with clear days, money kept and the month before beside it, ready to print for a counsellor or sponsor; and your year on one calendar. The toolbar popup says when a new month's letter is waiting.", + "To make that possible, the block page now keeps when it stopped you, as well as how many times, for the kinds of site you block for yourself (never threats such as scam sites, and never the site's address). It is kept on your device for a year, for everyone, so Pro can show the months before you bought it.", "Sieve Pro is sold by Polar, who send the licence key with your receipt. One key works in up to three browsers at once, and “Remove from this browser” frees a place for another. Entering it sends that key and a plain name for the browser to Polar to check it, and again about once a week when you open the settings. Firefox asks your permission first. The privacy policy explains exactly what is sent.", "A fix for the Protection Dashboard: blocks from the gambling list built into Sieve were not being counted, only those from the downloaded list.", ], diff --git a/common/stats.js b/common/stats.js index acc4d7b..2f97ffc 100644 --- a/common/stats.js +++ b/common/stats.js @@ -230,6 +230,10 @@ export function installStatsListener() { const STATS_MIDNIGHT_ALARM = "sieveStatsMidnight"; const STATS_RETENTION_DAYS = 30; +// Month totals of the days the window has let go of: { "2026-09": { gambling: 12, ... } }. +export const STATS_MONTHS_KEY = "sieveStatsMonths"; +const STATS_MONTHS_KEPT = 25; +const MONTH_RE = /^\d{4}-\d{2}$/; // Timestamp of the next local midnight. function nextMidnight() { @@ -242,6 +246,11 @@ function nextMidnight() { // Remove daily buckets older than the retention window. Weekly rollups only // need 7 days; we keep 30 so prior-day data survives midnight cleanly and // leaves headroom for future features. +// +// A day leaving the window is added to its month first (STATS_MONTHS_KEY), so +// a month can still be counted after its days are gone: a month's total is its +// folded days plus the daily buckets still here, and a day is only ever in one +// of the two. Only counts are kept, never anything about a site. async function pruneOldStats() { // Land the buffer first, or a prune would read stats that do not yet include // the pending counts and write back a version missing them. @@ -251,12 +260,44 @@ async function pruneOldStats() { cutoff.setDate(cutoff.getDate() - STATS_RETENTION_DAYS); const cutoffStr = localDateStr(cutoff); const pruned = {}; + const leaving = {}; for (const [date, dayStats] of Object.entries(stats)) { if (date >= cutoffStr) pruned[date] = dayStats; + else leaving[date] = dayStats; + } + if (Object.keys(leaving).length) { + const stored = await chrome.storage.local.get({ [STATS_MONTHS_KEY]: {} }); + const months = foldIntoMonths(stored[STATS_MONTHS_KEY], leaving, cutoff); + // Months first: a worker torn down between the two writes then keeps a + // day twice for a night, rather than losing it. + await chrome.storage.local.set({ [STATS_MONTHS_KEY]: months }); } await writeAllStats(pruned); } +// The month totals with these days added in, keeping STATS_MONTHS_KEPT months +// back from `now`. Exported for tests. +export function foldIntoMonths(months, days, now = new Date()) { + const out = {}; + const src = months && typeof months === "object" ? months : {}; + for (const [month, counts] of Object.entries(src)) { + if (MONTH_RE.test(month) && counts && typeof counts === "object") out[month] = { ...counts }; + } + for (const [date, dayStats] of Object.entries(days || {})) { + const month = date.slice(0, 7); + if (!MONTH_RE.test(month) || !dayStats || typeof dayStats !== "object") continue; + const into = out[month] || (out[month] = {}); + for (const [category, count] of Object.entries(dayStats)) { + const n = Number(count); + if (Number.isFinite(n) && n > 0) into[category] = (into[category] || 0) + n; + } + } + const oldest = new Date(now.getFullYear(), now.getMonth() - STATS_MONTHS_KEPT + 1, 1); + const oldestStr = localDateStr(oldest).slice(0, 7); + for (const month of Object.keys(out)) if (month < oldestStr) delete out[month]; + return out; +} + async function handleStatsMidnightAlarm() { await pruneOldStats(); scheduleStatsMidnightAlarm(); diff --git a/options/options.css b/options/options.css index a6f8bc6..dcfbd28 100644 --- a/options/options.css +++ b/options/options.css @@ -2628,6 +2628,120 @@ html.preload .loading-veil { width: 7.5rem; } +.streak-goal .streak-cost-row input[type="text"].input { + width: 15rem; + max-width: 100%; +} + +/* The savings goal: how far the money kept has come. Ink, not green — a goal + is progress, not something switched on. */ +.goal { + max-width: 28rem; + margin-top: 10px; +} + +.goal-text { + margin: 0 0 6px; + font-size: 14px; + color: var(--ink-2); +} + +.goal-track { + height: 6px; + background: var(--rule); + border-radius: 3px; + overflow: hidden; +} + +.goal-fill { + display: block; + height: 100%; + width: 0; + background: var(--ink); + border-radius: 3px; +} + +/* The urge screen's centre: a still picture of each design to choose from. */ +.design-choices { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); + gap: var(--s-2); + margin-top: 10px; +} + +.design-choice { + position: relative; + display: grid; + gap: 8px; + padding: 12px; + border: 1px solid var(--rule); + border-radius: var(--r-1); + cursor: pointer; +} + +.design-choice:has(input:checked) { + border-color: var(--ink); + box-shadow: inset 0 0 0 1px var(--ink); +} + +.design-choice:has(input:focus-visible) { + outline: 2px solid var(--ink); + outline-offset: 2px; +} + +.design-choice:has(input:disabled) { + cursor: default; +} + +.design-choice input { + position: absolute; + opacity: 0; + pointer-events: none; +} + +.design-thumb { + width: 100%; + height: auto; + aspect-ratio: 3 / 2; + border-radius: var(--r-1); + background: var(--wash); +} + +.design-thumb .thumb-ink, +.design-thumb .thumb-line { + fill: none; + stroke: var(--ink); +} + +.design-thumb .thumb-line { + stroke: var(--ink-3); +} + +.design-thumb .thumb-wash { + fill: var(--rule); +} + +.design-thumb .thumb-dot { + fill: var(--ink); +} + +.design-text { + display: grid; + gap: 2px; +} + +.design-name { + font-weight: 600; + font-size: 14px; + color: var(--ink); +} + +.design-blurb { + font-size: 13px; + line-height: 1.45; + color: var(--ink-2); +} + @container (max-width: 560px) { .urge-contact-row { grid-template-columns: minmax(0, 1fr); diff --git a/options/options.html b/options/options.html index ef188c3..b1419cb 100644 --- a/options/options.html +++ b/options/options.html @@ -1797,9 +1797,10 @@

Sieve Pro

Your licence Free

- The urge screen and streaks are Sieve Pro: $24.99 once, - no subscription. Every protection, the Seal included, stays free. Bought it? Paste - the licence key from your receipt email. + The urge screen, streaks with a savings goal, and your progress (your hardest + hours, proof your urges pass, a letter every month) are Sieve Pro: + $24.99 once, no subscription. Every protection, the + Seal included, stays free. Bought it? Paste the licence key from your receipt email.

@@ -1839,9 +1840,10 @@

Your licence Free

Urge screen Off

- When you land on a blocked site, the page leads with ninety seconds of breathing - instead of a notice, then your own reason, in your own words, and one tap to someone - you trust. Go back and Allow stay underneath, as they are now. + When you land on a blocked site, the page leads with something to do while the urge + passes instead of a notice: breathing, an ensō to draw or a river to lead to the + sea. Then your own reason in your own words, a message in your own voice, and one + tap to someone you trust. Go back and Allow stay underneath, as they are now.

@@ -1902,6 +1904,14 @@

Someone to reach

The button opens your own phone, messaging or email app. Sieve sends nothing.

+ +
+
+

At the centre

+

What you see first. Each is something to do with your hands while the urge rises and falls.

+ +
+
@@ -1920,6 +1930,25 @@

Streaks

+ +
+
+

Your progress

+

+ When it tends to get hard, by weekday and hour. Proof that your urges pass, from + the ones you’ve waited out. And a letter after every month, with your year on + one calendar. Read from what Sieve already keeps on this device. +

+ +
+
+ +
+
@@ -1989,6 +2018,8 @@

Why I made Sieve

+ + diff --git a/options/options.js b/options/options.js index 1e1dcef..e2a9a5b 100644 --- a/options/options.js +++ b/options/options.js @@ -593,13 +593,16 @@ function optionsDefaults() { // Warden band on the Overview — folded to its one-line bar by the × wardenFolded: false, // The Seal (common/seal.js), and Sieve Pro: the licence (common/pro.js), - // the urge screen and streaks (pro/streaks.js). The urge screen's photo - // has its own key, read separately, so this batch never carries an image. + // the urge screen and streaks (pro/streaks.js), and the note about a + // voice message (pro/voice.js). The urge screen's photo has its own key, + // read separately, and the sound lives in IndexedDB, so this batch never + // carries an image or a recording. proLicence: null, proSeal: null, proUrge: {}, proHabits: {}, habitAttempts: {}, + proVoice: null, }; for (const t of DARK_PATTERN_TYPES) { d[t.key] = t.default !== undefined ? t.default : true; @@ -2458,7 +2461,8 @@ function setupPro(store) { document.getElementById("nav-pro-group").hidden = !navShown; document.getElementById("nav-pro").hidden = !navShown; - const { urge, streaks } = window.SieveProSettings.setup(store); + // Each Pro group returns its render(pro); this page needs no list of them. + const groups = Object.values(window.SieveProSettings.setup(store) || {}); enhanceSwitchRows(document.getElementById("section-pro")); function applyPro() { @@ -2468,8 +2472,7 @@ function setupPro(store) { if (note) note.hidden = pro; for (const control of card.querySelectorAll(".pro-control")) control.disabled = !pro; } - urge.render(pro); - streaks.render(pro); + for (const group of groups) if (group && typeof group.render === "function") group.render(pro); } setupLicence(store, (next) => { diff --git a/pages/blocked.html b/pages/blocked.html index dbac8f2..70bfdbf 100644 --- a/pages/blocked.html +++ b/pages/blocked.html @@ -383,13 +383,514 @@ margin-bottom: 36px; } + .urge-hour { + margin: 12px 0 0; + max-width: 46ch; + font-size: 14px; + line-height: 1.5; + color: var(--ink-2); + } + + .urge-stage { + position: relative; + width: 168px; + margin-top: 32px; + } + .breath { position: relative; display: grid; place-items: center; width: 168px; height: 168px; - margin-top: 32px; + } + + /* Proof it passes: the breathing ring sits inside the dial of the urges + already waited out, each a dot at the minute it passed. The ring at + its fullest stays inside the innermost dots. */ + .urge-stage.has-dial { + display: grid; + place-items: center; + width: min(320px, 100%); + aspect-ratio: 1; + } + + .urge-stage.has-dial .breath { + width: 41%; + height: 41%; + } + + .urge-stage.has-dial .breath-word { + max-width: 78%; + font-size: 15px; + line-height: 1.2; + text-align: center; + } + + .urge-stage.has-dial + .urge-design + .urge-count { + width: min(320px, 100%); + } + + .dial { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + overflow: visible; + } + + .dial-ring { + fill: none; + stroke: var(--rule-strong); + stroke-width: 1; + } + + .dial-tick { + stroke: var(--ink-3); + stroke-width: 1; + } + + .dial-label { + font-family: var(--font-mono); + font-size: 11px; + fill: var(--ink-3); + } + + .dial-arc { + fill: none; + stroke: var(--ink); + stroke-width: 2; + } + + .dial-hand { + stroke: var(--ink); + stroke-width: 1.5; + stroke-linecap: round; + } + + .dial-usual { + stroke: var(--ink-2); + stroke-width: 3; + } + + .dial-dot { + fill: var(--ink-3); + } + + .dial-dot.is-ahead { + fill: none; + stroke: var(--ink-3); + stroke-width: 1; + } + + .dial-dot.is-passed, + .dial-new { + fill: var(--ink); + } + + .urge-proof { + margin: 14px 0 0; + max-width: 46ch; + font-size: 15px; + line-height: 1.5; + color: var(--ink-2); + } + + .urge-voice { + margin-top: 14px; + } + + /* ---- Urge screen designs (pro/designs.js) ---------------------------- + The ensō: the Zen circle drawn one breath at a time; ink on paper, and + the page signed in ink after the fifth breath. The river: tiles turned + until the ink runs from the spring to the sea. */ + + .urge-design { + margin-top: 28px; + } + + .btn-link { + margin-top: 8px; + padding: 0; + border: 0; + background: none; + color: var(--ink); + font: inherit; + font-size: 14px; + text-decoration: underline; + text-underline-offset: 3px; + cursor: pointer; + } + + .enso-stage { + display: flex; + align-items: flex-end; + gap: 14px; + } + + .enso-frame { + position: relative; + width: min(calc(100% - 3rem), 22rem); + aspect-ratio: 1; + } + + .enso { + display: block; + width: 100%; + height: 100%; + overflow: visible; + } + + .enso-path { + fill: none; + stroke: var(--rule-strong); + stroke-width: 1.2; + } + + .enso-stroke { + fill: none; + stroke: var(--ink); + stroke-linecap: round; + } + + .enso-bristle { + opacity: 0.4; + } + + .enso-dry circle { + fill: none; + stroke: var(--paper); + } + + .enso-pool, + .enso-drops circle { + fill: var(--ink); + } + + /* The breath drives the brush: the in-breath takes it halfway round, the + longer out-breath closes it, and between breaths the ink fades. */ + .enso-ink { + opacity: 0; + } + + .enso-stage[data-phase="in"] .enso-ink, + .enso-stage[data-phase="out"] .enso-ink, + .enso-stage[data-phase="done"] .enso-ink { + opacity: 1; + } + + .enso-stage[data-phase="rest"] .enso-ink { + transition: opacity 0.9s var(--ease); + } + + .enso-stage[data-phase="in"] .enso-stroke { + transition: stroke-dashoffset 4s cubic-bezier(0.35, 0, 0.6, 1); + } + + .enso-stage[data-phase="out"] .enso-stroke { + transition: stroke-dashoffset 6s cubic-bezier(0.25, 0, 0.35, 1); + } + + .enso-hold { + position: absolute; + inset: 8%; + padding: 0; + border: 0; + border-radius: 50%; + background: transparent; + cursor: pointer; + touch-action: none; + user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; + -webkit-tap-highlight-color: transparent; + } + + .enso-hold:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 6px; + } + + .enso-cue { + position: absolute; + inset: 0; + display: grid; + place-items: center; + font-family: var(--font-serif); + font-size: 17px; + color: var(--ink-2); + pointer-events: none; + } + + .enso-stage[data-phase="done"] .enso-cue { + opacity: 0; + } + + /* On a wide screen the breath is named under the circle once it has + begun; on a phone it stays inside, where the thumb and eyes are. */ + @media (min-width: 561px) { + .enso-stage:not([data-phase="idle"]) .enso-cue { + opacity: 0; + } + } + + .enso-signature { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding-bottom: 6%; + } + + .enso-inscription { + margin: 0; + writing-mode: vertical-rl; + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.15em; + text-transform: uppercase; + color: var(--ink-3); + } + + .enso-seal { + flex: none; + width: 2rem; + height: 2rem; + opacity: 0; + transform: scale(1.1); + transition: + opacity 0.3s var(--ease), + transform 0.3s var(--ease); + } + + .enso-stage[data-phase="done"] .enso-seal { + opacity: 1; + transform: none; + } + + .enso-stage.is-still .enso-seal { + transform: none; + } + + .enso-seal-stone { + fill: var(--ink); + } + + .enso-seal-cut { + fill: none; + stroke: var(--paper); + stroke-width: 2.4; + stroke-linecap: round; + } + + .enso-seal-border { + stroke-width: 1.1; + } + + .enso-phase { + margin: 16px 0 0; + min-height: 1.3em; + font-family: var(--font-serif); + font-size: 19px; + } + + .enso-tally { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + margin-top: 10px; + } + + .enso-slots { + display: flex; + gap: 8px; + } + + .enso-slot { + width: 2rem; + height: 2rem; + overflow: visible; + } + + .enso-slot-guide { + fill: none; + stroke: var(--ink-3); + stroke-width: 1.2; + stroke-dasharray: 1.4 3.2; + } + + .enso-slot.is-drawn .enso-slot-guide { + display: none; + } + + .enso-slot-ink { + fill: none; + stroke: var(--ink); + stroke-linecap: round; + } + + .enso-count, + .river-moves { + font-family: var(--font-mono); + font-size: 12px; + letter-spacing: 0.04em; + font-variant-numeric: tabular-nums; + color: var(--ink-3); + } + + .enso-done { + margin-top: 14px; + } + + .enso-done-line, + .river-status { + margin: 0; + font-size: 15px; + line-height: 1.5; + } + + /* The board: 720 x 600 in the drawing's units, the tiles in the middle + 600, the spring and the sea in the 60 either side. */ + .river-play { + position: relative; + width: min(100%, 30rem); + aspect-ratio: 6 / 5; + } + + .river-ends { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + overflow: visible; + pointer-events: none; + } + + .river-grid { + position: absolute; + inset: 0 calc(100% / 12); + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + grid-template-rows: repeat(6, minmax(0, 1fr)); + gap: 1px; + padding: 1px; + background: var(--rule-strong); + } + + .river-tile { + position: relative; + min-width: 0; + min-height: 0; + padding: 0; + border: 0; + border-radius: 0; + background: var(--paper); + color: inherit; + cursor: pointer; + overflow: hidden; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + transition: background-color 0.2s var(--ease); + } + + .river-tile:focus-visible { + z-index: 1; + outline: 2px solid var(--ink); + outline-offset: -3px; + } + + .river-piece { + display: block; + width: 100%; + height: 100%; + transition: transform 0.24s var(--ease); + } + + /* A channel is its banks with the paper between them, until the ink + fills it. */ + .river-bank { + fill: none; + stroke: var(--ink-3); + stroke-width: 25; + } + + .river-water { + fill: none; + stroke: var(--paper); + stroke-width: 21; + transition: stroke 0.2s var(--ease); + } + + @media (hover: hover) { + .river-play:not(.is-solved) .river-tile:hover { + background: var(--raised); + } + .river-play:not(.is-solved) .river-tile:hover:not(.is-wet) .river-water { + stroke: var(--raised); + } + } + + .river-tile.is-wet .river-water, + .river-source { + stroke: var(--ink); + } + + .river-pool { + fill: var(--ink); + } + + .river-waves { + fill: none; + stroke: var(--ink-3); + stroke-width: 1.5px; + stroke-linecap: round; + vector-effect: non-scaling-stroke; + } + + .river-seal { + fill: var(--ink); + opacity: 0; + transition: opacity 0.2s var(--ease) 0.2s; + } + + .river-play.is-solved .river-tile { + cursor: default; + } + + .river-play.is-solved .river-mouth, + .river-play.is-solved .river-waves { + stroke: var(--ink); + } + + .river-play.is-solved .river-seal { + opacity: 1; + } + + .river-play.is-still .river-piece, + .river-play.is-still .river-water, + .river-play.is-still .river-seal { + transition: none; + } + + .river-tally { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 12px; + margin: 16px 0 8px; + } + + .river-count { + font-family: var(--font-mono); + font-size: 30px; + line-height: 1; + font-variant-numeric: tabular-nums; + } + + .river-unit { + font-size: 14px; + color: var(--ink-2); } .breath-ring { @@ -582,17 +1083,28 @@

This will pass.

circle until it does.

-
- - Breathe in + + + +
+ +
+ + Breathe in +
+

1:30

+ @@ -600,6 +1112,7 @@

This will pass.

+
@@ -649,7 +1162,11 @@

This page is blocked

+ + + + diff --git a/pages/blocked.js b/pages/blocked.js index 738568f..87ecbdf 100644 --- a/pages/blocked.js +++ b/pages/blocked.js @@ -266,6 +266,21 @@ } recordBlockView(); + // The attempt record (common/attempts.js): when, as well as how many, for + // the habits someone blocks for themselves. The service worker decides + // whether this category is one, and keeps it on this device. + function recordAttempt() { + if (new URLSearchParams(location.search).get("resolved")) return; + try { + chrome.runtime + .sendMessage({ type: "SIEVE_RECORD_ATTEMPT", category }) + .catch(() => {}); + } catch (err) { + // Extension context may be unavailable in unusual conditions. + } + } + recordAttempt(); + // Streaks and the urge screen (Sieve Pro): records this attempt for the // habit the category belongs to, and with Pro and the urge screen on, leads // the page with it. See pro/urge.js (an empty stand-in in an open-source diff --git a/pages/progress.css b/pages/progress.css new file mode 100644 index 0000000..c227f84 --- /dev/null +++ b/pages/progress.css @@ -0,0 +1,577 @@ +/* ========================================================================== + Sieve — Your progress (Sieve Pro) + Layout only; tokens come from common/sieve-ui.css. Ink on paper, and + nothing green: green means a protection is on, and nothing here is one. + A clear day is a filled ink dot, a day a blocked site stopped you is a + ring, and days before the record began are a hairline. + ========================================================================== */ + +.pg { + width: min(860px, 100%); + margin: 0 auto; + padding: 0 32px 80px; +} + +.pg-letterhead { + display: flex; + align-items: center; + justify-content: space-between; + padding: 28px 0 20px; + border-bottom: 1px solid var(--rule); +} + +.pg-back { + display: inline-flex; + align-items: center; + gap: 8px; + margin-left: -6px; + padding: 4px 6px; + font-size: 13px; + color: var(--ink-2); + text-decoration: none; + border-radius: var(--r-1); + transition: color var(--t-press) var(--ease), background-color var(--t-press) var(--ease); +} + +.pg-back:hover { + color: var(--ink); + background: var(--wash); +} + +.pg-back svg { + width: 15px; + height: 15px; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.brand .mark { + width: 22px; + height: 22px; +} + +.pg-head { + padding: 48px 0 8px; +} + +.pg-title { + margin: 8px 0 0; + font-family: var(--font-serif); + font-size: clamp(34px, 6vw, 46px); + font-weight: 400; + line-height: 1.08; + letter-spacing: -0.02em; +} + +.pg-sub { + max-width: 56ch; + margin: 14px 0 0; + font-size: 15px; + line-height: 1.6; + color: var(--ink-2); +} + +.pg-note { + margin-top: 36px; + padding: 24px 0; + border-top: 1px solid var(--rule); +} + +.pg-note p { + max-width: 58ch; + font-size: 15px; + line-height: 1.6; + color: var(--ink-2); +} + +.pg-actions { + display: flex; + flex-wrap: wrap; + gap: var(--s-2); + margin-top: 18px; +} + +/* ---- Which habits -------------------------------------------------------- */ + +.pg-habits { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 28px; +} + +.pg-habits:empty { + display: none; +} + +.pg-chip { + padding: 6px 12px; + border: 1px solid var(--rule-strong); + border-radius: 999px; + background: transparent; + color: var(--ink-2); + font: inherit; + font-size: 13px; + cursor: pointer; + transition: color var(--t-press) var(--ease), border-color var(--t-press) var(--ease); +} + +.pg-chip:hover { + color: var(--ink); + border-color: var(--ink); +} + +.pg-chip[aria-pressed="true"] { + color: var(--paper); + background: var(--ink); + border-color: var(--ink); +} + +.pg-chip:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 2px; +} + +/* ---- Parts --------------------------------------------------------------- */ + +.pg-part { + margin-top: 40px; + padding-top: 24px; + border-top: 1px solid var(--rule); +} + +.pg-part-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 16px; +} + +.pg-h { + margin: 10px 0 0; + font-family: var(--font-serif); + font-size: 26px; + font-weight: 400; + line-height: 1.2; + letter-spacing: -0.01em; +} + +.pg-lede { + max-width: 58ch; + margin: 10px 0 0; + font-size: 15px; + line-height: 1.6; + color: var(--ink-2); +} + +.pg-meta { + margin: 12px 0 0; + font-family: var(--font-mono); + font-size: 12px; + letter-spacing: 0.04em; + color: var(--ink-3); +} + +.pg-try { + max-width: 58ch; + margin: 14px 0 0; + padding-left: 14px; + border-left: 2px solid var(--ink); + font-size: 15px; + line-height: 1.55; +} + +.pg-empty { + max-width: 58ch; + margin: 12px 0 0; + font-size: 15px; + line-height: 1.6; + color: var(--ink-2); +} + +.pg-empty a, +.pg-note a { + color: var(--ink); +} + +.pg-nav { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.pg-nav .btn { + min-width: 34px; + padding: 4px 10px; + font-size: 18px; + line-height: 1; +} + +.pg-nav-label { + min-width: 9.5em; + font-family: var(--font-mono); + font-size: 12px; + letter-spacing: 0.06em; + text-align: center; + text-transform: uppercase; + color: var(--ink-2); +} + +/* ---- Streaks ------------------------------------------------------------- */ + +.pg-streak-list { + margin: 14px 0 0; + padding: 0; + list-style: none; +} + +.pg-streak { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 4px 24px; + padding: 14px 0; +} + +.pg-streak + .pg-streak { + border-top: 1px solid var(--rule); +} + +.pg-streak-name { + font-size: 14px; + color: var(--ink-2); +} + +.pg-streak-days { + font-family: var(--font-serif); + font-size: 34px; + line-height: 1.1; + letter-spacing: -0.015em; +} + +.pg-streak-side { + align-self: end; + font-size: 14px; + line-height: 1.5; + text-align: right; + color: var(--ink-2); +} + +.pg-goal { + grid-column: 1 / -1; + max-width: 30rem; + margin-top: 6px; +} + +.pg-goal-text { + margin: 0 0 6px; + font-size: 14px; + color: var(--ink-2); +} + +.pg-goal-track { + height: 6px; + background: var(--rule); + border-radius: 3px; + overflow: hidden; +} + +.pg-goal-fill { + display: block; + height: 100%; + background: var(--ink); + border-radius: 3px; +} + +/* ---- When it's hardest: seven weekdays by twenty-four hours --------------- */ + +.heat { + display: grid; + grid-template-columns: 2.6em repeat(24, minmax(0, 1fr)); + gap: 2px; + margin-top: 18px; + max-width: 44rem; +} + +.heat-day, +.heat-hour { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.04em; + color: var(--ink-3); +} + +.heat-hour { + white-space: nowrap; + overflow: visible; +} + +.heat-day { + align-self: center; +} + +.heat-cell { + aspect-ratio: 1; + border-radius: 2px; + background: var(--wash); +} + +.heat-cell.l1 { background: color-mix(in srgb, var(--ink) 18%, transparent); } +.heat-cell.l2 { background: color-mix(in srgb, var(--ink) 38%, transparent); } +.heat-cell.l3 { background: color-mix(in srgb, var(--ink) 62%, transparent); } +.heat-cell.l4 { background: var(--ink); } + +.heat-cell.is-hard { + box-shadow: 0 0 0 1.5px var(--paper), 0 0 0 3px var(--ink); +} + +/* ---- Proof it passes ----------------------------------------------------- */ + +.pg-proof { + display: grid; + grid-template-columns: minmax(0, 240px) minmax(0, 1fr); + align-items: center; + gap: 28px; + margin-top: 10px; +} + +.pg-proof .dial { + width: 100%; + height: auto; + overflow: visible; +} + +.dial-ring { fill: none; stroke: var(--rule-strong); stroke-width: 1; } +.dial-tick { stroke: var(--ink-3); stroke-width: 1; } +.dial-label { font-family: var(--font-mono); font-size: 11px; fill: var(--ink-3); } +.dial-arc { fill: none; stroke: var(--ink); stroke-width: 2; } +.dial-hand { stroke: var(--ink); stroke-width: 1.5; stroke-linecap: round; } +.dial-usual { stroke: var(--ink-2); stroke-width: 3; } +.dial-dot { fill: var(--ink); } +.dial-new { fill: var(--ink); } + +/* ---- Your month: a letter, and the month on one calendar ------------------ */ + +.pg-figures { + display: flex; + flex-wrap: wrap; + gap: 18px 36px; + margin-top: 20px; +} + +.pg-figure { + display: grid; + gap: 2px; +} + +.pg-figure-n { + font-family: var(--font-serif); + font-size: 30px; + line-height: 1.1; +} + +.pg-figure-what { + font-size: 13px; + color: var(--ink-2); +} + +.cal { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: 4px; + max-width: 26rem; + margin-top: 22px; +} + +.cal-weekday { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.06em; + text-align: center; + text-transform: uppercase; + color: var(--ink-3); +} + +.cal-day { + position: relative; + display: grid; + place-items: center; + aspect-ratio: 1; + font-family: var(--font-mono); + font-size: 11px; + color: var(--ink-3); +} + +.cal-day .day-mark { + position: absolute; + inset: 14%; + width: auto; + height: auto; +} + +.cal-day span { + position: relative; +} + +.cal-day.is-clear span { + color: var(--paper); +} + +.cal-day.is-urge span, +.cal-day.is-today span { + color: var(--ink); +} + +.cal-day.is-today { + outline: 1px solid var(--ink); + outline-offset: -1px; + border-radius: var(--r-1); +} + +.day-mark { + display: inline-block; + width: 10px; + height: 10px; + border-radius: 50%; + vertical-align: -1px; +} + +.day-mark.is-clear { + background: var(--ink); +} + +.day-mark.is-urge { + box-shadow: inset 0 0 0 1.5px var(--ink); +} + +.day-mark.is-before { + box-shadow: inset 0 0 0 1px var(--rule-strong); + border-radius: 2px; +} + +.pg-key { + display: flex; + flex-wrap: wrap; + gap: 6px 18px; + margin-top: 12px; + font-size: 12px; + color: var(--ink-3); +} + +.pg-closing { + margin: 20px 0 0; + font-family: var(--font-serif); + font-size: 19px; + font-style: italic; +} + +.pg-closing:empty { + display: none; +} + +/* ---- Your year: every day on one calendar --------------------------------- */ + +.year { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(10.5rem, 1fr)); + gap: 18px 22px; + margin-top: 20px; +} + +.year-month-name { + margin: 0 0 6px; + font-family: var(--font-mono); + font-size: 11px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--ink-2); +} + +.year-month-count { + color: var(--ink-3); +} + +.year-days { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: 3px; + max-width: 8.5rem; +} + +.year-day { + aspect-ratio: 1; + border-radius: 50%; +} + +.year-day.is-clear { background: var(--ink); } +.year-day.is-urge { box-shadow: inset 0 0 0 1.5px var(--ink); } +.year-day.is-today { box-shadow: inset 0 0 0 1.5px var(--ink-3); border-radius: 2px; } +.year-day.is-before, +.year-day.is-ahead { box-shadow: inset 0 0 0 1px var(--rule); border-radius: 2px; } + +/* ---- Foot ------------------------------------------------------------------ */ + +.pg-foot { + margin-top: 64px; +} + +.pg-foot .kicker { + margin-top: 12px; +} + +/* ---- Small screens --------------------------------------------------------- */ + +@media (max-width: 560px) { + .pg { + padding: 0 16px 64px; + } + .pg-head { + padding-top: 32px; + } + .pg-proof { + grid-template-columns: minmax(0, 1fr); + } + .pg-proof .dial { + max-width: 240px; + } + .heat { + grid-template-columns: 2.2em repeat(24, minmax(0, 1fr)); + gap: 1px; + } + .heat-hour { + font-size: 8px; + } + .pg-streak { + grid-template-columns: minmax(0, 1fr); + } + .pg-streak-side { + text-align: left; + } +} + +/* ---- Print: the month's letter, on its own -------------------------------- */ + +@media print { + body { + background: #fff; + } + .pg-letterhead .pg-back, + .pg-head, + .pg-habits, + .pg-no-print, + .pg-nav .btn, + .pg-foot { + display: none !important; + } + .pg-part:not(.pg-letter) { + display: none !important; + } + .pg-letter { + margin-top: 24px; + border-top: 0; + } +} diff --git a/pages/progress.html b/pages/progress.html new file mode 100644 index 0000000..76b956c --- /dev/null +++ b/pages/progress.html @@ -0,0 +1,151 @@ + + + + + + + Sieve — Your progress + + + + + + +
+
+ + + Settings + + + + Sieve + +
+ +
+

Sieve Pro

+

Your progress

+

+ Read from what Sieve keeps in this browser: when a blocked site stopped you, the urges + you waited out, and the streaks you count. Nothing here was sent anywhere. +

+
+ + + + + + + + + +
+ +

Sieve · on this device · patterns, never causes

+
+
+ + + + + + + + + + diff --git a/pages/progress.js b/pages/progress.js new file mode 100644 index 0000000..bc463ba --- /dev/null +++ b/pages/progress.js @@ -0,0 +1,16 @@ +// pages/progress.js +// Sieve — starts the Your progress page. What fills it is Sieve Pro +// (pro/progress.js, not open source); in a build without it, that file is an +// empty stand-in and the page says Sieve Pro is not part of this build. + +(() => { + "use strict"; + + if (!window.SieveProgress) { + document.getElementById("pg-absent").hidden = false; + return; + } + window.SieveProgress.start().catch((err) => { + console.warn("[Sieve] Your progress could not be read:", err); + }); +})(); diff --git a/popup/popup.css b/popup/popup.css index 678a641..6df5ed4 100644 --- a/popup/popup.css +++ b/popup/popup.css @@ -128,6 +128,30 @@ body { color: var(--ink-2); } +.status-pro-link { + align-self: flex-start; + margin-top: 2px; + padding: 0; + border: 0; + background: none; + color: var(--ink); + font: inherit; + text-decoration: underline; + text-decoration-color: var(--rule-strong); + text-underline-offset: 3px; + cursor: pointer; +} + +.status-pro-link:hover { + text-decoration-color: var(--ink); +} + +.status-pro-link:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 2px; + border-radius: 2px; +} + /* ---- Blocks of switches --------------------------------------------------- */ .block { diff --git a/popup/popup.js b/popup/popup.js index ea16514..458d8c7 100644 --- a/popup/popup.js +++ b/popup/popup.js @@ -144,9 +144,31 @@ async function updateStatusBanner() { } // Under the summary: a running seal (free, common/seal.js), then each streak -// tracked with Sieve Pro, with the money kept. Without Pro — or in an -// open-source build, where pro/streaks.js is an empty stand-in — only the seal. -const PRO_LINE_KEYS = ["proLicence", "proSeal", "proHabits", "habitAttempts"]; +// tracked with Sieve Pro, with the money kept and how far toward the goal, +// and a way to Your progress (saying so when last month's letter is waiting). +// Without Pro — or in an open-source build, where pro/streaks.js is an empty +// stand-in — only the seal. +const PRO_LINE_KEYS = ["proLicence", "proSeal", "proHabits", "habitAttempts", "proMonthSeen"]; + +// The month just ended, as "2026-10", and its name, while its letter is new: +// the first week of the next month, if the attempt record began before it +// ended and the letter has not been opened. +async function waitingLetter(now) { + const d = new Date(now); + if (d.getDate() > 7) return null; + const prev = new Date(d.getFullYear(), d.getMonth() - 1, 1); + const key = `${prev.getFullYear()}-${String(prev.getMonth() + 1).padStart(2, "0")}`; + const stored = await chrome.storage.local.get(["proMonthSeen", "sieveAttempts"]); + const since = stored.sieveAttempts && stored.sieveAttempts.since; + const thisMonth = new Date(d.getFullYear(), d.getMonth(), 1).getTime(); + if (stored.proMonthSeen === key || !Number.isFinite(since) || since >= thisMonth) return null; + return prev.toLocaleDateString([], { month: "long" }); +} + +function openProgress(hash) { + chrome.tabs.create({ url: chrome.runtime.getURL(`pages/progress.html${hash || ""}`) }); + window.close(); +} async function updateProLines() { const el = document.getElementById("status-pro"); @@ -165,17 +187,39 @@ async function updateProLines() { for (const row of (await ST.summary(now)).slice(0, 3)) { const parts = [row.label, row.days === 0 ? "starting today" : ST.daysLabel(row.days)]; if (row.keptLabel) parts.push(`about ${row.keptLabel} kept`); + if (row.goalProgress) { + parts.push( + row.goalProgress.reached + ? `enough for ${row.goal.name}` + : `${Math.floor(row.goalProgress.share * 100)}% to ${row.goal.name}`, + ); + } lines.push(parts.join(" · ")); } + const month = await waitingLetter(now); + lines.push( + month + ? { text: `Your ${month} letter is ready`, hash: "#month" } + : { text: "Your progress", hash: "" }, + ); } } catch (err) { console.warn("[Sieve] popup: could not read the seal or streaks:", err); } el.textContent = ""; for (const line of lines) { - const span = document.createElement("span"); - span.textContent = line; - el.appendChild(span); + if (typeof line === "string") { + const span = document.createElement("span"); + span.textContent = line; + el.appendChild(span); + continue; + } + const link = document.createElement("button"); + link.type = "button"; + link.className = "status-pro-link"; + link.textContent = `${line.text} →`; + link.addEventListener("click", () => openProgress(line.hash)); + el.appendChild(link); } el.hidden = lines.length === 0; } diff --git a/pro/README.md b/pro/README.md index 799a549..abab204 100644 --- a/pro/README.md +++ b/pro/README.md @@ -5,8 +5,12 @@ The files in this folder are empty stand-ins for **Sieve Pro**: | File | The feature | | --- | --- | | `urge.js` | The urge screen, on the block page, and recording attempts for streaks | -| `streaks.js` | Streaks and money kept, and the habits the urge screen knows about | -| `settings.js` | The urge screen and streaks groups in Settings › Sieve Pro | +| `streaks.js` | Streaks, money kept and the savings goal, and the habits the urge screen knows about | +| `insights.js` | When it's hardest, proof it passes, and the month and year letters | +| `designs.js` | The ensō and the river, for the centre of the urge screen | +| `voice.js` | A message in your own voice, recorded in Settings and played on the urge screen | +| `progress.js` | The Your progress page (`pages/progress.html`) | +| `settings.js` | The urge screen, voice and streaks groups in Settings › Sieve Pro | | `features.js` | Which Pro features a build carries (here: none) | Sieve Pro is not open source. It lives in a separate, private repository and diff --git a/pro/designs.js b/pro/designs.js new file mode 100644 index 0000000..4a9b132 --- /dev/null +++ b/pro/designs.js @@ -0,0 +1,4 @@ +// pro/designs.js — an empty stand-in. See pro/README.md. +// +// The ensō and the river, which Sieve Pro can put at the centre of the urge +// screen. Without it, there is no urge screen to put them in. diff --git a/pro/insights.js b/pro/insights.js new file mode 100644 index 0000000..d0dd7ec --- /dev/null +++ b/pro/insights.js @@ -0,0 +1,5 @@ +// pro/insights.js — an empty stand-in. See pro/README.md. +// +// What Sieve Pro reads from the records Sieve keeps on this device: when it's +// hardest, proof it passes, and the month and year letters. Without it, the +// urge screen and the Your progress page find no SieveInsights. diff --git a/pro/progress.js b/pro/progress.js new file mode 100644 index 0000000..e84d4a7 --- /dev/null +++ b/pro/progress.js @@ -0,0 +1,5 @@ +// pro/progress.js — an empty stand-in. See pro/README.md. +// +// What fills the Your progress page (pages/progress.html). Without it, +// pages/progress.js finds no SieveProgress and the page says Sieve Pro is not +// part of this build. diff --git a/pro/voice.js b/pro/voice.js new file mode 100644 index 0000000..41603d4 --- /dev/null +++ b/pro/voice.js @@ -0,0 +1,4 @@ +// pro/voice.js — an empty stand-in. See pro/README.md. +// +// A message in your own voice for the urge screen. Without it, there is no +// urge screen to play it on, and Settings has no Sieve Pro section. diff --git a/test/attempts-test.mjs b/test/attempts-test.mjs new file mode 100644 index 0000000..28237c8 --- /dev/null +++ b/test/attempts-test.mjs @@ -0,0 +1,114 @@ +// test/attempts-test.mjs +// Sieve — tests for common/attempts.js, the record of when the block page +// stopped a habit. +// +// What could go wrong here goes wrong quietly: a reload counted as a second +// urge, a scam block counted as one, a burst of block pages losing entries, a +// record that grows for ever. Sieve Pro's insights read this record, so a +// wrong entry becomes a wrong "your hardest hours" months later. +// +// node --test test/ + +import test from "node:test"; +import assert from "node:assert/strict"; + +const backing = new Map(); +let listener = null; + +globalThis.chrome = { + runtime: { + getURL: (path) => `chrome-extension://sieve/${path}`, + onMessage: { addListener: (fn) => { listener = fn; } }, + }, + storage: { + local: { + async get(arg) { + const keys = typeof arg === "string" ? [arg] : Array.isArray(arg) ? arg : Object.keys(arg || {}); + const out = {}; + for (const key of keys) if (backing.has(key)) out[key] = structuredClone(backing.get(key)); + return out; + }, + async set(patch) { + // Slow writes, so overlapping read-modify-writes would lose entries. + await new Promise((r) => setTimeout(r, 2)); + for (const [k, v] of Object.entries(patch)) backing.set(k, structuredClone(v)); + }, + }, + }, +}; +globalThis.window = globalThis; + +await import("../common/attempts.js"); +const A = globalThis.SieveAttempts; + +const T0 = Date.UTC(2026, 9, 1, 12); +const MIN = 60 * 1000; +const DAY = 24 * 60 * MIN; + +test("only habits are recorded; threats never are", () => { + assert.equal(A.add(null, "gambling", T0).added, true); + for (const threat of ["scam", "malware", "phishing", "ads", "piracy", null, undefined, ""]) { + assert.equal(A.add(null, threat, T0).added, false, String(threat)); + } +}); + +test("a repeat of the same habit within five minutes is the same attempt", () => { + let r = A.add(null, "gambling", T0).record; + assert.equal(A.add(r, "gambling", T0 + 4 * MIN).added, false); + r = A.add(r, "gambling", T0 + 5 * MIN).record; + assert.equal(r.a.length, 2); + // A different habit inside the window is its own attempt. + const other = A.add(r, "dating", T0 + 6 * MIN); + assert.equal(other.added, true); + // and does not hide a repeat of the first behind it + assert.equal(A.add(other.record, "gambling", T0 + 7 * MIN).added, false); +}); + +test("the record keeps about a year, and at most MAX entries", () => { + let r = A.add(null, "gambling", T0 - (A.KEEP_DAYS + 1) * DAY).record; + r = A.add(r, "gambling", T0).record; + assert.deepEqual(r.a.map((e) => e[0]), [T0]); + const many = { since: T0, a: Array.from({ length: A.MAX + 5 }, (_, i) => [T0 + i * 10 * MIN, "dating"]) }; + const last = T0 + (A.MAX + 5) * 10 * MIN; + const out = A.add(many, "dating", last).record; + assert.equal(out.a.length, A.MAX); + assert.equal(out.a[out.a.length - 1][0], last); +}); + +test("normalize drops junk, sorts, and starts the record at its first entry", () => { + const n = A.normalize({ since: T0, a: [[T0 - DAY, "trading"], [T0 + 1, "nope"], ["x", "dating"], [T0 + 2, "dating"]] }); + assert.deepEqual(n.a, [[T0 - DAY, "trading"], [T0 + 2, "dating"]]); + assert.equal(n.since, T0 - DAY); + assert.deepEqual(A.normalize(undefined), { v: 1, since: null, a: [] }); +}); + +test("between picks a window, and optionally some categories", () => { + const r = { a: [[T0, "gambling"], [T0 + DAY, "dating"], [T0 + 2 * DAY, "prediction-markets"]] }; + assert.equal(A.between(r, T0, T0 + 3 * DAY).length, 3); + assert.deepEqual(A.between(r, T0, T0 + 3 * DAY, ["gambling", "prediction-markets"]).map((e) => e[1]), + ["gambling", "prediction-markets"]); + assert.equal(A.between(r, T0 + 1, T0 + DAY).length, 0); +}); + +test("only the block page can write, and a burst of pages loses nothing", async () => { + backing.clear(); + A.installListener(); + await new Promise((r) => setTimeout(r, 20)); + assert.ok(backing.get(A.KEY).since > 0, "the record starts counting when the worker starts"); + + const send = (category, url) => + new Promise((resolve) => { + const handled = listener({ type: A.MESSAGE, category }, { url }, resolve); + if (!handled) resolve(null); + }); + assert.equal(await send("gambling", "chrome-extension://sieve/options/options.html"), null); + assert.equal(await send("gambling", "https://evil.example/pages/blocked.html"), null); + + const page = "chrome-extension://sieve/pages/blocked.html?category="; + const answers = await Promise.all( + ["gambling", "dating", "trading", "ai-chatbots", "custom-blocked"].map((c) => send(c, page + c)), + ); + assert.ok(answers.every((a) => a && a.ok && a.added)); + assert.equal(backing.get(A.KEY).a.length, 5); + assert.equal(listener({ type: "SOMETHING_ELSE" }, { url: page }, () => {}), false); +}); diff --git a/test/pro-standins-test.mjs b/test/pro-standins-test.mjs index 039fe0b..06fb319 100644 --- a/test/pro-standins-test.mjs +++ b/test/pro-standins-test.mjs @@ -19,7 +19,16 @@ const read = (...p) => readFileSync(join(ROOT, ...p), "utf8"); const STANDINS = readdirSync(DIR).filter((f) => !f.endsWith(".md")).sort(); test("the stand-ins are the Pro files, and the README names each", () => { - assert.deepEqual(STANDINS, ["features.js", "settings.js", "streaks.js", "urge.js"]); + assert.deepEqual(STANDINS, [ + "designs.js", + "features.js", + "insights.js", + "progress.js", + "settings.js", + "streaks.js", + "urge.js", + "voice.js", + ]); const readme = read("pro", "README.md"); for (const f of STANDINS) assert.ok(readme.includes("`" + f + "`"), `pro/README.md names ${f}`); }); @@ -49,6 +58,8 @@ test("the private repository can never be committed here", () => { test("everything that uses Pro checks it is there first", () => { // The block page: no SieveUrge, the plain notice. assert.match(read("pages", "blocked.js"), /if \(window\.SieveUrge\) \{/); + // Your progress: no SieveProgress, a page that says Pro is not in this build. + assert.match(read("pages", "progress.js"), /if \(!window\.SieveProgress\) \{\s*document\.getElementById\("pg-absent"\)\.hidden = false;/); // The popup: no streaks without Pro and pro/streaks.js; the seal line needs neither. const popup = read("popup", "popup.js"); assert.match(popup, /if \(P && ST && \(await P\.isPro\(now\)\)\) \{/); diff --git a/test/stats-months-test.mjs b/test/stats-months-test.mjs new file mode 100644 index 0000000..e91623e --- /dev/null +++ b/test/stats-months-test.mjs @@ -0,0 +1,43 @@ +// test/stats-months-test.mjs +// Sieve — the month totals common/stats.js keeps as daily buckets leave its +// 30-day window, so Sieve Pro's month letter can still count a month after +// its days are gone. +// +// node --test test/ + +import test from "node:test"; +import assert from "node:assert/strict"; + +globalThis.chrome = { storage: { local: {} }, runtime: {}, alarms: {} }; +const { foldIntoMonths } = await import("../common/stats.js"); + +test("days fold into their month and add to what is there", () => { + const months = foldIntoMonths( + { "2026-09": { gambling: 2 } }, + { + "2026-09-29": { gambling: 3, ads: 40 }, + "2026-09-30": { gambling: 1 }, + "2026-10-01": { dating: 2 }, + }, + new Date(2026, 10, 3), + ); + assert.deepEqual(months, { + "2026-09": { gambling: 6, ads: 40 }, + "2026-10": { dating: 2 }, + }); +}); + +test("junk is ignored, and only about two years of months are kept", () => { + const months = foldIntoMonths( + { "2024-01": { gambling: 5 }, nonsense: { a: 1 }, "2026-01": "x" }, + { "2026-02-01": { gambling: -1, dating: "2", scam: NaN }, bad: { a: 1 } }, + new Date(2026, 1, 10), + ); + assert.deepEqual(months, { "2026-02": { dating: 2 } }); +}); + +test("the input is not changed", () => { + const before = { "2026-09": { gambling: 2 } }; + foldIntoMonths(before, { "2026-09-01": { gambling: 1 } }, new Date(2026, 9, 1)); + assert.deepEqual(before, { "2026-09": { gambling: 2 } }); +}); From c05f0aedf4eb8de30e0aeb4de3a683995a5199e6 Mon Sep 17 00:00:00 2001 From: Alfon Date: Thu, 29 Oct 2026 22:54:07 +0800 Subject: [PATCH 06/12] Sieve Pro: plans, what works for you, and a heads-up before the hard hours The public half of three Pro features (the logic is pro/coach.js in the private repo; pro/coach.js here is its empty stand-in): - The urge screen gains markup for the plan that fits the moment, the person's own things to try instead, and two questions after "I'm OK now" that turn what happened into a plan. - Settings gains a "Plans for the hard moments" group and a things-to-try list in the urge screen group; Your progress gains "What works for you" and "Your plans" (the month and year become parts 06 and 07). - background/heads-up.js (open source) shows the heads-up: one alarm on the next moment Pro stored in proHeadsUp, a notification with only the stored words, dropped if more than 30 minutes late, and stopped when the switch is off or the licence lapses. - "notifications" is an optional permission, asked for only when the heads-up is switched on in Settings; never at install. Changelog (1.6.0) and the privacy policy describe the new records and the permission. test/heads-up-test.mjs (7); npm test 892 pass. Co-Authored-By: Claude Opus 5.5 --- PRIVACY.md | 10 ++- background/heads-up.js | 154 ++++++++++++++++++++++++++++++++ background/service-worker.js | 1 + common/changelog.js | 4 + manifest.firefox.json | 3 + manifest.json | 3 + options/options.css | 113 +++++++++++++++++++++++ options/options.html | 29 +++++- options/options.js | 4 + pages/blocked.html | 147 ++++++++++++++++++++++++++++++ pages/progress.css | 75 +++++++++++++++- pages/progress.html | 36 +++++++- pro/README.md | 9 +- pro/coach.js | 6 ++ test/heads-up-test.mjs | 168 +++++++++++++++++++++++++++++++++++ test/pro-standins-test.mjs | 5 +- 16 files changed, 753 insertions(+), 14 deletions(-) create mode 100644 background/heads-up.js create mode 100644 pro/coach.js create mode 100644 test/heads-up-test.mjs diff --git a/PRIVACY.md b/PRIVACY.md index e305663..a8ee650 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -31,7 +31,7 @@ described [below](#sieve-pro-licence-check). Without Pro, nothing changes. Sieve is open source, so anyone can verify these claims: . The one exception is Sieve Pro's -features (the urge screen, streaks and Your progress), which are not open source. +features (the urge screen, plans, streaks and Your progress), which are not open source. They make no network requests and keep everything on your device, and the licence check, the only request Pro makes, is part of the open-source code (`common/pro.js`), so what it sends can be checked by anyone. @@ -60,6 +60,9 @@ third party. | Monthly block totals | The Protection Dashboard keeps its daily counts for 30 days; as a day leaves, its counts are added to its month, for about two years — counts only, never a site | Yes | | Urges waited out, **only if you press "I'm OK now"** | When, how long it took, and the kind of site, to draw Sieve Pro's Proof it passes dial | Yes | | A message in your own voice, **only if you record or choose one** | The recording or sound file, stored in the extension's own database in your browser, and played on the urge screen. The microphone is used only while you record | Yes | +| Plans for the hard moments, **only if you write one** | Your two lines in your own words, the kind of site and the time each is for, to show on Sieve Pro's urge screen when that moment comes | Yes | +| What you picked to try instead, **only if you pick one** | Your list of things to try, and for each pick on the urge screen when it was, the kind of site and which one, kept for a year, so Sieve Pro can tell you how long you tended to stay away after each | Yes | +| A heads-up before your hardest hours, **only if you turn it on** | The times to give it and the words it says, worked out from the record above, for Sieve Pro's heads-up notification | Yes | | Sieve Pro licence key, **only if you enter one** | Turn on the Pro features | Kept on your device; checked with Polar — see [below](#sieve-pro-licence-check) | | Seal, **only if you start one** | When it ends, and its way out: either the key your witness's authenticator app shares with Sieve (needed to check their codes) and their recovery codes as **hashes**, or the emergency key as a **hash**. A witness's app works offline; nothing is sent to them, us or anyone | Yes | | Urge screen, **only what you fill in** | Your reason, an optional photo (shrunk to fit 800 pixels), and a contact's name and number or email address, shown on the block page | Yes | @@ -154,8 +157,8 @@ extension sends. If you say no, nothing is sent and Pro stays off. Nobody who does not activate Pro is ever asked. The key is kept on your device so it can be checked again. The Pro features -themselves (the urge screen, streaks and Your progress) run entirely on your -device, like the rest of Sieve. +themselves (the urge screen, plans, the heads-up, streaks and Your progress) run +entirely on your device, like the rest of Sieve. --- @@ -218,6 +221,7 @@ Sieve requests only the permissions needed to filter content locally: - **tabs** — open the local "blocked"/settings pages and close popup/hijack tabs. It does not read your browser history. If you switch Usage Insights on, it also reads the site name of the tab you are looking at, in order to time it. - **idle** — used only by Usage Insights, to stop the clock when you step away or lock the screen. It reports how long it has been since you touched the keyboard or mouse; it cannot see what you typed. - **offscreen** — run the optional toxicity model locally, off the main page. +- **notifications** (optional, never asked for at install) — asked for only if you turn on Sieve Pro's heads-up before your hardest hours, and used only to show it. The notification's words are worked out on your device; nothing is sent. - **scripting** — run Sieve's own filters in pages. For example, the Dark Pattern Blocker's on-page notes are added only to a page where it has found something to show, rather than to every page. - **host access (all sites)** — required because harmful content can appear on any site; used only to run the local filters. No browsing data is collected. diff --git a/background/heads-up.js b/background/heads-up.js new file mode 100644 index 0000000..827c84c --- /dev/null +++ b/background/heads-up.js @@ -0,0 +1,154 @@ +// background/heads-up.js +// Sieve — the heads-up before someone's hardest hours: a notification at a +// time this device already worked out, and nothing else. +// +// Sieve Pro (pro/coach.js) reads when the block page has tended to stop +// someone and, once they switch the heads-up on, writes to proHeadsUp the +// moments to give it and the words to say. This file is the open-source half: +// it keeps one alarm set for the next of those moments, shows the notification +// when it comes, and sets the next. Without Pro nothing writes proHeadsUp, so +// nothing here ever fires; and it only ever shows the words stored there. +// +// Notifications need a permission Sieve does not ask for when it is installed. +// It is an optional one, asked for in Settings only when someone switches the +// heads-up on. Until it is given, chrome.notifications does not exist here and +// nothing is shown. +// +// A heads-up that comes late, because the computer was asleep through it, is +// dropped rather than shown at the wrong time: it is a warning for a moment +// that has already passed. + +const KEY = "proHeadsUp"; +const LICENCE_KEY = "proLicence"; +const ALARM = "sieve-heads-up"; +const NOTIFICATION = "sieve-heads-up"; +const LATE_MS = 30 * 60 * 1000; +const TITLE_MAX = 80; +const BODY_MAX = 400; + +// The stored schedule, read defensively: { enabled, at: [{ day, minute }], +// title, body }. day is Date#getDay's (0 is Sunday), minute of the day local. +export function normalize(raw) { + const src = raw && typeof raw === "object" ? raw : {}; + const at = (Array.isArray(src.at) ? src.at : []).filter( + (s) => + s && + Number.isInteger(s.day) && + s.day >= 0 && + s.day < 7 && + Number.isInteger(s.minute) && + s.minute >= 0 && + s.minute < 1440, + ); + return { + enabled: src.enabled === true, + at: at.map((s) => ({ day: s.day, minute: s.minute })), + title: typeof src.title === "string" ? src.title.slice(0, TITLE_MAX) : "", + body: typeof src.body === "string" ? src.body.slice(0, BODY_MAX) : "", + }; +} + +// The first of those moments after `now`, in local time, or null. Built from +// the date parts, so a daylight-saving change cannot move it by an hour. +export function nextAt(at, now) { + const base = new Date(now); + let best = null; + for (const slot of at) { + for (let add = 0; add <= 7; add++) { + const d = new Date( + base.getFullYear(), + base.getMonth(), + base.getDate() + add, + Math.floor(slot.minute / 60), + slot.minute % 60, + ); + if (d.getDay() !== slot.day || d.getTime() <= now) continue; + if (best === null || d.getTime() < best) best = d.getTime(); + break; + } + } + return best; +} + +// Is Pro on? The same test as common/pro.js isProState, which is written for +// pages and cannot load in a service worker: a stored key Polar granted, not +// past its expiry. A key that lapses stops the heads-up with it. +export function licensed(raw, now) { + if (!raw || typeof raw !== "object") return false; + if (typeof raw.key !== "string" || !raw.key.trim() || raw.status !== "granted") return false; + return !Number.isFinite(raw.expiresAt) || now < raw.expiresAt; +} + +// Keeps the one alarm on the next heads-up, or clears it when there is none. +export async function arm(now = Date.now()) { + const stored = await chrome.storage.local.get([KEY, LICENCE_KEY]); + const headsUp = normalize(stored[KEY]); + const when = headsUp.enabled && licensed(stored[LICENCE_KEY], now) ? nextAt(headsUp.at, now) : null; + if (when === null) { + await chrome.alarms.clear(ALARM); + return null; + } + const set = await chrome.alarms.get(ALARM); + if (!set || set.scheduledTime !== when) await chrome.alarms.create(ALARM, { when }); + return when; +} + +// The alarm went off: show the heads-up if it is still wanted, still allowed +// and on time, then set the next one. Returns whether it was shown. +export async function fire(alarm, now = Date.now()) { + if (!alarm || alarm.name !== ALARM) return false; + const stored = await chrome.storage.local.get([KEY, LICENCE_KEY]); + const headsUp = normalize(stored[KEY]); + let shown = false; + if ( + headsUp.enabled && + headsUp.title && + headsUp.body && + licensed(stored[LICENCE_KEY], now) && + now - alarm.scheduledTime < LATE_MS && + chrome.notifications + ) { + try { + await chrome.notifications.create(NOTIFICATION, { + type: "basic", + iconUrl: chrome.runtime.getURL("icons/icon-128.png"), + title: headsUp.title, + message: headsUp.body, + priority: 1, + }); + shown = true; + } catch (err) { + console.warn("[Sieve] could not show the heads-up:", err); + } + } + // The next one, never this one again. + await arm(Math.max(now, alarm.scheduledTime) + 1000); + return shown; +} + +// Tapping it opens Your progress at the plans. Registered once the permission +// exists, which may be after this worker started. +let clicksHeard = false; +function listenForClicks() { + if (clicksHeard || !chrome.notifications || !chrome.notifications.onClicked) return; + chrome.notifications.onClicked.addListener((id) => { + if (id !== NOTIFICATION) return; + chrome.notifications.clear(id); + chrome.tabs.create({ url: chrome.runtime.getURL("pages/progress.html#plans") }); + }); + clicksHeard = true; +} + +chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name !== ALARM) return; + fire(alarm).catch((err) => console.warn("[Sieve] heads-up:", err)); +}); + +chrome.storage.onChanged.addListener((changes, area) => { + if (area !== "local" || (!changes[KEY] && !changes[LICENCE_KEY])) return; + arm().catch((err) => console.warn("[Sieve] heads-up:", err)); +}); + +if (chrome.permissions && chrome.permissions.onAdded) chrome.permissions.onAdded.addListener(listenForClicks); +listenForClicks(); +arm().catch((err) => console.warn("[Sieve] heads-up:", err)); diff --git a/background/service-worker.js b/background/service-worker.js index c42be9a..002cbc3 100644 --- a/background/service-worker.js +++ b/background/service-worker.js @@ -24,6 +24,7 @@ import "./google-web-only.js"; // Site Cleanup — sends Google searches to the import "./search-filter-subscriptions.js"; // Search Result Filter — subscribed lists, fetched and refreshed import "./tells.js"; // Dark Pattern Blocker — the Claim Ledger's storage, and the toolbar badge import "./trial-reminders.js"; // Dark Pattern Blocker — the free-trial reminders you ask for +import "./heads-up.js"; // Sieve Pro — the heads-up before the hardest hours (shows only what Pro stored) // A plain script, not an ES module: importing it for its side effect is what // puts KeywordPattern on `self`, which is where the blocked-sites entry parser // lives. The settings page and the content script load the same file, so all diff --git a/common/changelog.js b/common/changelog.js index 459d7c2..0bf068e 100644 --- a/common/changelog.js +++ b/common/changelog.js @@ -27,6 +27,10 @@ const SIEVE_CHANGELOG = [ "Record a message for yourself in Settings, or choose a song or a voice note from someone you love. The urge screen plays it with a tap, or by itself if you ask. It stays on your device; the microphone is on only while you record.", "Streaks count the days since you last tried to open a gambling site, a dating site, or any other kind you track, and what it would have cost: “23 days · about $1,140 kept”. Give the money a goal, such as a trip or a debt paid off, and see how close it is. They show in the toolbar popup and in settings, with your best run and the next milestone.", "Your progress, a page of its own: when it tends to get hard, by weekday and hour; the dial of every urge you have waited out; a letter after every month, with clear days, money kept and the month before beside it, ready to print for a counsellor or sponsor; and your year on one calendar. The toolbar popup says when a new month's letter is waiting.", + "Plans for the hard moments: decide while it's calm, in your own words. “If it's late and I'm in bed scrolling, then I put my phone on the kitchen charger.” Give a plan a kind of site and a time, such as your hardest hours or around 11 pm, and the urge screen shows it before anything else when that moment comes.", + "After “I'm OK now”, if there was no plan for that moment, the urge screen asks two questions while it's fresh: what was going on, and what you could do first next time. Your answers become a plan for that kind of site and that hour. “Not now” skips it, and Settings can turn the questions off.", + "A heads-up before your hardest hours, if you turn it on: a notification fifteen minutes before they usually start, on the days they have come, with your plan for them. Sieve asks your browser for permission to show notifications only when you switch this on. It is worked out on your device, and a heads-up the computer slept through is dropped rather than shown late.", + "What works for you: while you wait on the urge screen, pick one of your own things to try instead, such as a walk or a call. Sieve keeps which one you picked and how long until a blocked site stopped you again, and once you have tried something twice it says so: “After a walk, you usually stayed away about 3 hours.” Your progress lists them all. A pattern from your own days, never a promise.", "To make that possible, the block page now keeps when it stopped you, as well as how many times, for the kinds of site you block for yourself (never threats such as scam sites, and never the site's address). It is kept on your device for a year, for everyone, so Pro can show the months before you bought it.", "Sieve Pro is sold by Polar, who send the licence key with your receipt. One key works in up to three browsers at once, and “Remove from this browser” frees a place for another. Entering it sends that key and a plain name for the browser to Polar to check it, and again about once a week when you open the settings. Firefox asks your permission first. The privacy policy explains exactly what is sent.", "A fix for the Protection Dashboard: blocks from the gambling list built into Sieve were not being counted, only those from the downloaded list.", diff --git a/manifest.firefox.json b/manifest.firefox.json index 490f79b..b41f4b5 100644 --- a/manifest.firefox.json +++ b/manifest.firefox.json @@ -20,6 +20,9 @@ "webNavigation", "tabs" ], + "optional_permissions": [ + "notifications" + ], "host_permissions": [ "" ], diff --git a/manifest.json b/manifest.json index 510f77f..ec27ae4 100644 --- a/manifest.json +++ b/manifest.json @@ -22,6 +22,9 @@ "tabs", "offscreen" ], + "optional_permissions": [ + "notifications" + ], "host_permissions": [ "" ], diff --git a/options/options.css b/options/options.css index dcfbd28..b0bc180 100644 --- a/options/options.css +++ b/options/options.css @@ -2742,8 +2742,121 @@ html.preload .loading-veil { color: var(--ink-2); } +/* Things to try instead (pro/coach.js): a plain list, each with its Remove. */ +.instead-list { + list-style: none; + margin-top: 6px; +} + +.instead-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--s-2); + padding: 6px 0; + border-bottom: 1px solid var(--rule); +} + +.instead-text { + min-width: 0; + font-size: 14px; + color: var(--ink); + overflow-wrap: anywhere; +} + +.instead-add { + display: flex; + gap: var(--s-2); + margin-top: 10px; + max-width: 28rem; +} + +.instead-add .input { + flex: 1; + min-width: 0; +} + +/* Plans for the hard moments: each in the person's own words, If and Then + apart, as on the urge screen. */ +.plan-list { + list-style: none; +} + +.plan-item { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: start; + gap: 4px var(--s-2); + padding: 12px 0; + border-bottom: 1px solid var(--rule); +} + +.plan-item:first-child { + padding-top: 4px; +} + +.plan-text { + display: grid; + grid-template-columns: auto 1fr; + gap: 4px 12px; + margin: 0; +} + +.plan-text dt { + padding-top: 4px; + font-family: var(--font-mono); + font-size: 10.5px; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--ink-3); +} + +.plan-text dd { + margin: 0; + font-family: var(--font-serif); + font-size: 17px; + line-height: 1.4; + color: var(--ink); + overflow-wrap: anywhere; +} + +.plan-item > .meta { + grid-column: 1; + margin: 2px 0 0; +} + +.plan-item > .btn { + grid-column: 2; + grid-row: 1; +} + +.plan-form { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 0 var(--s-2); + max-width: 36rem; + margin-top: 14px; +} + +.plan-cell-wide, +.plan-form > .actions, +.plan-form > .error { + grid-column: 1 / -1; +} + +.plan-cell .sub-label { + margin: 12px 0 6px; +} + +.plan-form > .actions { + margin-top: 14px; +} + @container (max-width: 560px) { .urge-contact-row { grid-template-columns: minmax(0, 1fr); } + .plan-form { + grid-template-columns: minmax(0, 1fr); + } } diff --git a/options/options.html b/options/options.html index b1419cb..a9ac3fe 100644 --- a/options/options.html +++ b/options/options.html @@ -1912,6 +1912,27 @@

At the centre

+ +
+ + + +
+
+

Plans for the hard moments

+

+ Decide now, while it’s calm: “If it’s late and I’m in bed + scrolling, then I put my phone on the kitchen charger.” The urge screen shows + the plan that fits the kind of site and the hour, before anything else. Sieve can also + give you a heads-up shortly before your hardest hours start. +

+ +
+
+ +
+
@@ -1936,8 +1957,9 @@

Streaks

Your progress

When it tends to get hard, by weekday and hour. Proof that your urges pass, from - the ones you’ve waited out. And a letter after every month, with your year on - one calendar. Read from what Sieve already keeps on this device. + the ones you’ve waited out. What tends to help you, and your plans. And a + letter after every month, with your year on one calendar. Read from what Sieve + already keeps on this device.

@@ -2016,10 +2038,13 @@

Why I made Sieve

+ + + diff --git a/options/options.js b/options/options.js index e2a9a5b..71aac67 100644 --- a/options/options.js +++ b/options/options.js @@ -603,6 +603,10 @@ function optionsDefaults() { proHabits: {}, habitAttempts: {}, proVoice: null, + // Plans, things to do instead, and the heads-up (pro/coach.js). + proPlans: null, + proInstead: null, + proHeadsUp: null, }; for (const t of DARK_PATTERN_TYPES) { d[t.key] = t.default !== undefined ? t.default : true; diff --git a/pages/blocked.html b/pages/blocked.html index 70bfdbf..6618406 100644 --- a/pages/blocked.html +++ b/pages/blocked.html @@ -953,6 +953,108 @@ color: var(--ink-2); } + /* Plans, things to do instead, and the questions after it passes + (pro/coach.js). The plan is written in the person's own words, so it + gets the reason's serif; the rest stays in the page's sans. */ + .urge-plan { + margin: 24px 0 0; + padding: 14px 0; + border-top: 1px solid var(--rule); + border-bottom: 1px solid var(--rule); + } + + .urge-plan-text { + display: grid; + grid-template-columns: auto 1fr; + gap: 6px 14px; + margin: 6px 0 0; + } + + .urge-plan-text dt { + padding-top: 5px; + font-family: var(--font-mono); + font-size: 10.5px; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--ink-3); + } + + .urge-plan-text dd { + margin: 0; + font-family: var(--font-serif); + font-size: 18px; + line-height: 1.45; + overflow-wrap: anywhere; + } + + .urge-instead, + .urge-debrief { + margin: 28px 0 0; + } + + .urge-tries { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + } + + .urge-try { + min-height: 36px; + padding: 0 14px; + } + + .urge-try[aria-pressed="true"] { + border-color: var(--ink); + background: var(--wash); + box-shadow: inset 0 0 0 1px var(--ink); + } + + .urge-works, + .urge-debrief-lede, + .urge-debrief-done { + margin: 12px 0 0; + max-width: 54ch; + font-size: 14px; + line-height: 1.5; + color: var(--ink-2); + } + + .urge-field { + display: block; + margin-top: 14px; + max-width: 54ch; + } + + .urge-field-label { + display: block; + margin-bottom: 6px; + font-size: 13px; + color: var(--ink-2); + } + + .urge-input { + box-sizing: border-box; + width: 100%; + min-height: 40px; + padding: 8px 12px; + font-family: var(--font-sans); + font-size: 15px; + color: var(--ink); + background: transparent; + border: 1px solid var(--rule-strong); + border-radius: 3px; + } + + .urge-input:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 1px; + } + + .urge-debrief .actions { + margin-top: 16px; + } + /* With the urge screen leading, its own buttons are the primary ones; Go back below steps down to an outline, and the settings note goes. */ html[data-urge="on"] #back-btn { @@ -1085,6 +1187,18 @@

This will pass.

+ + + @@ -1099,6 +1213,38 @@

This will pass.

1:30

+ + + + + + +