Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Security: links, download names, feeds, bombs and the scheme's answers

Yashwanth Kamireddi6918e000598f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7b4e9c3..ff8c129 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -33,7 +33,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 50 # a cold cache (new toolchain, new lockfile) compiles everything; warm runs take ~12
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Build dependencies
run: |
sudo apt-get update
@@ -43,15 +43,15 @@ jobs:
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-libav
# The codecs, not only their headers: a video test reads an .mp4's first frames.
- - uses: dtolnay/rust-toolchain@stable
+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
with:
components: rustfmt, clippy
- - uses: Swatinem/rust-cache@v2
+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
# Only main writes the cache; pull requests read it, so they cannot crowd it out.
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt --all --check
- - uses: actions/setup-node@v4
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
@@ -76,8 +76,8 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
@@ -89,7 +89,7 @@ jobs:
- name: Playwright version
id: pw
run: echo "version=$(node -p 'require("playwright/package.json").version')" >> "$GITHUB_OUTPUT"
- - uses: actions/cache@v4
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ~/.cache/ms-playwright
key: playwright-chromium-${{ steps.pw.outputs.version }}
@@ -134,7 +134,7 @@ jobs:
echo "::error::${#failed[@]} suite(s) failed: ${failed[*]}"
exit 1
fi
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: failure()
with:
name: ui-smoke
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index d1b5452..e619c0d 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -22,14 +22,14 @@ jobs:
image: ghcr.io/flathub-infra/flatpak-github-actions:gnome-51
options: --privileged
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# The manifest's main source is this repository as a git checkout (`path: ../..`);
# a shallow clone of it cannot be cloned again.
fetch-depth: 0
- name: The checkout, trusted inside the container
run: git config --global --add safe.directory '*'
- - uses: flatpak/flatpak-github-actions/flatpak-builder@v6
+ - uses: flatpak/flatpak-github-actions/flatpak-builder@79327416609af08178ad73b352877e51450790b3 # v6.8
with:
manifest-path: packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml
bundle: skykeep.flatpak
diff --git a/.github/workflows/linux-compat.yml b/.github/workflows/linux-compat.yml
index 20915f6..d008b12 100644
--- a/.github/workflows/linux-compat.yml
+++ b/.github/workflows/linux-compat.yml
@@ -27,7 +27,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Build dependencies
run: |
sudo apt-get update
@@ -37,12 +37,12 @@ jobs:
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-libav \
libheif-examples libheif-plugin-x265
- - uses: actions/setup-node@v4
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
- - uses: dtolnay/rust-toolchain@stable
- - uses: Swatinem/rust-cache@v2
+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- run: npm ci
- name: Build the packages
env:
@@ -67,7 +67,7 @@ jobs:
target/release/bundle/appimage/*.AppImage \
target/release/examples/distro_check test.heic packaging/linux-compat/check.sh compat/
ls -l compat
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: linux-compat
path: compat/
@@ -96,7 +96,7 @@ jobs:
container:
image: ${{ matrix.image }}
steps:
- - uses: actions/download-artifact@v4
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: linux-compat
path: /compat
@@ -118,8 +118,8 @@ jobs:
steps:
- name: Build tools
run: pacman -Syu --noconfirm --needed base-devel git rust nodejs npm
- - uses: actions/checkout@v4
- - uses: actions/download-artifact@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: linux-compat
path: /compat
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index e8eddad..101ee0c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Build dependencies
run: |
sudo apt-get update
@@ -35,12 +35,12 @@ jobs:
# The GStreamer plugins are here for two reasons: the AppImage carries the ones
# installed on this machine (bundleMediaFramework), and the launch checks below run
# the program as it will run for someone playing a video.
- - uses: actions/setup-node@v4
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
- - uses: dtolnay/rust-toolchain@stable
- - uses: Swatinem/rust-cache@v2
+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- run: npm ci
- name: Build the packages
# The build machine's paths are never written into the program.
@@ -100,7 +100,7 @@ jobs:
cd target/release/bundle
sha256sum deb/*.deb rpm/*.rpm appimage/*.AppImage | sed 's# [a-z]*/# #' > SHA256SUMS-linux.txt
cat SHA256SUMS-linux.txt
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: skykeep-linux
path: |
@@ -121,7 +121,7 @@ jobs:
permissions:
contents: write
steps:
- - uses: actions/download-artifact@v4
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
path: dist
- name: A draft release with every file
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index b5a47e1..b069e98 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -45,8 +45,8 @@ jobs:
runs-on: windows-latest
timeout-minutes: 75
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
@@ -63,12 +63,12 @@ jobs:
const mm = (v) => v.split(".").slice(0, 2).join(".");
console.log(`@tauri-apps/api ${npm}, tauri crate ${rust}`);
if (mm(npm) !== mm(rust)) { console.error("Tauri npm package and crate differ: align them"); process.exit(1); }'
- - uses: dtolnay/rust-toolchain@stable
- - uses: Swatinem/rust-cache@v2
+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
shared-key: windows-release
# HEIC decoding: libheif with its default codecs (libde265 decodes), linked in statically.
- - uses: actions/cache@v4
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: C:\vcpkg\installed
key: vcpkg-libheif-default-x64-windows-static-md-v1
@@ -98,7 +98,7 @@ jobs:
$files = Get-ChildItem target/release/bundle -Recurse -Include *.msi,*.exe
$files | ForEach-Object { "{0} {1}" -f (Get-FileHash $_ -Algorithm SHA256).Hash.ToLower(), $_.Name } |
Set-Content target/release/bundle/SHA256SUMS-windows.txt
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: skykeep-windows
path: |
@@ -114,8 +114,8 @@ jobs:
runs-on: windows-latest
timeout-minutes: 45
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm
@@ -150,7 +150,7 @@ jobs:
Stop-Process -Id $preview.Id -ErrorAction SilentlyContinue
"$($suites.Count - $failed.Count) of $($suites.Count) suites passed in Edge"
if ($failed.Count) { $failed | Set-Content "$shots\FAILED.txt"; exit 1 }
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: always()
with:
name: skykeep-ui-in-edge
@@ -164,7 +164,7 @@ jobs:
runs-on: windows-latest
timeout-minutes: 20
steps:
- - uses: actions/download-artifact@v4
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: skykeep-windows
path: dist
@@ -303,7 +303,7 @@ jobs:
if ($left) { throw "uninstalled, but the Start menu still has: $($left.Name -join ', ')" }
if (Test-Path $exe.FullName) { throw "uninstalled, but skykeep.exe is still there" }
"uninstalled: no Skykeep entries left in the Start menu"
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: always()
with:
name: skykeep-on-windows
diff --git a/.uiverify/links.test.mjs b/.uiverify/links.test.mjs
new file mode 100644
index 0000000..81b9a39
--- /dev/null
+++ b/.uiverify/links.test.mjs
@@ -0,0 +1,46 @@
+// Which links Skykeep opens: a web page, an email, a call, a place. A shared note's, list's or
+// invitation's link is someone else's choice, and anything else (a file on a share, a search
+// query, a program's own scheme) is never handed to the computer.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { outsideHref, linkedNote } from "../src/lib/links.ts";
+
+test("web pages, email, calls and places are opened", () => {
+ assert.equal(outsideHref("https://example.org/agenda"), "https://example.org/agenda");
+ assert.equal(outsideHref("http://example.org"), "http://example.org/");
+ assert.equal(outsideHref("mailto:[email protected]"), "mailto:[email protected]");
+ assert.equal(outsideHref("tel:+15550100"), "tel:+15550100");
+ assert.equal(outsideHref("geo:0,0?q=Main%20Street"), "geo:0,0?q=Main%20Street");
+ assert.equal(outsideHref(" HTTPS://EXAMPLE.ORG/ "), "https://example.org/");
+});
+
+test("every other kind of link is refused", () => {
+ for (const href of [
+ "file:///home/someone/x.desktop",
+ "file://attacker.example@SSL/DavWWWRoot/a.lnk",
+ "\\\\attacker.example\\share\\a.lnk",
+ "search-ms:query=x&crumb=location:%5C%5Cattacker.example",
+ "search:query=x",
+ "ms-msdt:/id PCWDiagnostic",
+ "smb://attacker.example/share",
+ "javascript:alert(1)",
+ "java\tscript:alert(1)",
+ " javascript:alert(1)",
+ "data:text/html,<h1>Sign in</h1>",
+ "blob:tauri://localhost/0b1c",
+ "quince://photo/ABC",
+ "vbscript:msgbox(1)",
+ "webcal://example.org/a.ics",
+ "applenotes:note/0b1c2d3e-0000-0000-0000-000000000000",
+ "",
+ null,
+ undefined,
+ ]) {
+ assert.equal(outsideHref(href), null, String(href));
+ }
+});
+
+test("a link to another note is the app's own", () => {
+ assert.equal(linkedNote("applenotes:note/0b1c2d3e-aaaa-bbbb-cccc-000000000000?ownerIdentifier=x"), "0B1C2D3E-AAAA-BBBB-CCCC-000000000000");
+ assert.equal(linkedNote("https://example.org/note/0b1c2d3e-aaaa-bbbb-cccc-000000000000"), null);
+});
diff --git a/.uiverify/notes-link-schemes.mjs b/.uiverify/notes-link-schemes.mjs
new file mode 100644
index 0000000..29fcd1f
--- /dev/null
+++ b/.uiverify/notes-link-schemes.mjs
@@ -0,0 +1,75 @@
+// A link in a shared note is whoever wrote the note's to choose. Only a web page, an email, a
+// call or a place is followed; a link to a file on a share, a search query or a page made of
+// data never leaves the window, and says, calmly, that it can't be opened from Skykeep. Every
+// click is taken the one way (lib/follow.ts): the engine never navigates by itself.
+//
+// The note here is invented, shaped as a phone stores one: text with link runs.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+const LINKS = [
+ ["Agenda", "file://attacker.example@SSL/DavWWWRoot/agenda.lnk"],
+ ["Search", "search-ms:query=x&crumb=location:%5C%5Cattacker.example%5Cshare"],
+ ["Sign in", "data:text/html,<h1>Sign in to iCloud</h1>"],
+ ["Run", "javascript:document.title='ran'"],
+ ["Site", "https://example.org/site"],
+];
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+await ctx.addInitScript((links) => {
+ const t = window.__TAURI_INTERNALS__;
+ const inner = t.invoke;
+ const title = "Shared plans";
+ const body = [title, ...links.map(([w]) => w)].join("\n");
+ const note = { guid: "nS", folderGuid: "f1", title, snippet: links[0][0], body, locked: false, editable: true, pinned: false,
+ createdAt: 1789000000, modifiedAt: 1789900000, etag: null };
+ const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
+ const runs = [{ ...plain(title.length + 1), style: 0 }];
+ links.forEach(([w, href], i) => {
+ runs.push({ ...plain(w.length), link: href });
+ if (i < links.length - 1) runs.push(plain(1));
+ });
+ t.invoke = async (cmd, args) => {
+ switch (cmd) {
+ case "notes_in": return [{ ...note, body: null }, ...(await inner(cmd, args))];
+ case "note_body": if (args?.guid === "nS") return body; break;
+ case "note_runs": if (args?.guid === "nS") return runs; break;
+ case "note_row": if (args?.guid === "nS") return { ...note, body: null }; break;
+ }
+ return inner(cmd, args);
+ };
+}, LINKS);
+await ctx.route("https://example.org/**", (r) => r.fulfill({ status: 200, body: "opened" }));
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+const base = process.env.BASE ?? "http://localhost:4173";
+await page.goto(base, { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.locator(".note-row", { hasText: "Shared plans" }).first().click();
+await page.waitForTimeout(700);
+for (const [word] of LINKS.slice(0, 4)) {
+ const link = page.locator(".ProseMirror a", { hasText: word });
+ ok(await link.evaluate((a) => a.classList.contains("nf-link-refused") && !!a.title), `"${word}" is drawn as text, saying why`);
+ const navs = [];
+ const seen = (f) => { if (f === page.mainFrame()) navs.push(f.url()); };
+ page.on("framenavigated", seen);
+ await link.click();
+ await page.waitForTimeout(400);
+ page.off("framenavigated", seen);
+ ok(navs.length === 0 && page.url().startsWith(base), `a click on "${word}" goes nowhere ${JSON.stringify(navs)}`);
+ ok(await page.getByText("This kind of link can't be opened from Skykeep.").first().isVisible(), `and says it can't be opened from Skykeep`);
+}
+ok((await page.title()) !== "ran", "a javascript: link never runs");
+// A web page is still followed, the one way out.
+const [nav] = await Promise.all([
+ page.waitForEvent("framenavigated", { timeout: 3000 }).catch(() => null),
+ page.locator(".ProseMirror a", { hasText: "Site" }).click(),
+]);
+ok(nav?.url() === "https://example.org/site", `a web page is still opened ${nav?.url()}`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/workflows-pinned.test.mjs b/.uiverify/workflows-pinned.test.mjs
new file mode 100644
index 0000000..49ceb6e
--- /dev/null
+++ b/.uiverify/workflows-pinned.test.mjs
@@ -0,0 +1,20 @@
+// Every third-party step a build runs is pinned to one commit, never a tag or a branch that
+// can be moved under it: a moved tag runs someone else's code on the machine that builds the
+// release. A local workflow (`./.github/…`) is this repository's own.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync } from "node:fs";
+
+const dir = new URL("../.github/workflows/", import.meta.url);
+
+test("every action a workflow uses is pinned to a full commit", () => {
+ const loose = [];
+ for (const file of readdirSync(dir).filter((f) => /\.ya?ml$/.test(f))) {
+ for (const [i, line] of readFileSync(new URL(file, dir), "utf8").split("\n").entries()) {
+ const m = /^\s*-?\s*uses:\s*([^\s#]+)\s*(#\s*(\S+))?/.exec(line);
+ if (!m || m[1].startsWith("./")) continue;
+ if (!/@[0-9a-f]{40}$/.test(m[1]) || !m[3]) loose.push(`${file}:${i + 1} ${m[1]}`);
+ }
+ }
+ assert.deepEqual(loose, []);
+});
diff --git a/Cargo.lock b/Cargo.lock
index 7685fd8..383c2fa 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3901,6 +3901,7 @@ dependencies = [
"keyring",
"num-bigint",
"pbkdf2",
+ "quince-auth",
"rand 0.9.5",
"reqwest 0.12.28",
"reqwest_cookie_store",
diff --git a/crates/quince-auth/Cargo.toml b/crates/quince-auth/Cargo.toml
index 0ebbe12..4970e98 100644
--- a/crates/quince-auth/Cargo.toml
+++ b/crates/quince-auth/Cargo.toml
@@ -23,7 +23,13 @@ thiserror = "2"
# Looking up Apple's hosts for the client's own resolver (AppleOnly).
tokio = { workspace = true, features = ["net"] }
+[features]
+# This computer counts as Apple's — for tests, whose mock servers run here. Never in the app.
+loopback = []
+
[dev-dependencies]
+# The crate's own tests (tests/*.rs) reach mock servers on this computer.
+quince-auth = { path = ".", features = ["loopback"] }
tokio = { workspace = true }
wiremock = "0.6"
tempfile = "3"
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index ef12c04..9d6c5f2 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -1119,12 +1119,22 @@ impl Client {
/// lists as what Skykeep talks to, read from here so the list is the lock itself.
pub const APPLE_DOMAINS: [&str; 3] = ["apple.com", "icloud.com", "icloud-content.com"];
+/// Whether this computer counts as Apple's: in this crate's tests, and in a build made with the
+/// `loopback` feature (the other crates' tests, whose mock servers run here) — never in the
+/// app. A shipped client that reached `localhost` could be pointed, by an address in Apple's
+/// data (a contact's photo), at whatever else runs on the person's computer.
+const LOOPBACK: bool = cfg!(any(test, feature = "loopback"));
+
/// Whether `host` is Apple's: under one of [`APPLE_DOMAINS`] — every host Skykeep has any
-/// reason to reach. Loopback too, which is this computer.
+/// reason to reach. Loopback too, which is this computer, only in tests (see `LOOPBACK`).
#[must_use]
pub fn is_apple_host(host: &str) -> bool {
+ apple_host(host, LOOPBACK)
+}
+
+fn apple_host(host: &str, loopback: bool) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
- host == "localhost"
+ (loopback && host == "localhost")
|| APPLE_DOMAINS
.iter()
.any(|d| host == *d || host.ends_with(&format!(".{d}")))
@@ -1199,10 +1209,60 @@ fn normal_host(host: &str) -> String {
.to_ascii_lowercase()
}
-/// Whether a request's URL names one of the listed hosts exactly.
+/// Whether a request's URL names one of the listed hosts exactly — and, where it names an
+/// address, one out on the internet.
fn url_is_listed(url: &reqwest::Url, listed: &[String]) -> bool {
- url.host_str()
- .is_some_and(|h| listed.iter().any(|l| *l == normal_host(h)))
+ url.host_str().is_some_and(|h| {
+ let h = normal_host(h);
+ listed.contains(&h) && h.parse::<std::net::IpAddr>().ok().is_none_or(is_public_ip)
+ })
+}
+
+/// Whether an address is out on the internet: not this computer, not the local network (a
+/// router's page, a printer, `192.168.…`, `10.…`, `fd…`), not link-local (where cloud machines
+/// keep their secrets, `169.254.169.254`), nor any other range no public calendar is on. A
+/// subscription is an address anyone can hand the person — and its name can be pointed at any
+/// address its owner likes — so one that leads inside is never fetched.
+#[must_use]
+pub fn is_public_ip(ip: std::net::IpAddr) -> bool {
+ use std::net::IpAddr;
+ match ip {
+ IpAddr::V4(v4) => {
+ let [a, b, ..] = v4.octets();
+ !(v4.is_private()
+ || v4.is_loopback()
+ || v4.is_link_local()
+ || v4.is_unspecified()
+ || v4.is_broadcast()
+ || v4.is_multicast()
+ || v4.is_documentation()
+ || a == 0
+ || a >= 240
+ // Shared address space (carrier NAT, tailnets) and benchmarking.
+ || (a == 100 && (64..128).contains(&b))
+ || (a == 198 && (18..20).contains(&b))
+ // IETF protocol assignments.
+ || (a == 192 && b == 0 && v4.octets()[2] == 0))
+ }
+ IpAddr::V6(v6) => {
+ if let Some(v4) = v6.to_ipv4_mapped() {
+ return is_public_ip(IpAddr::V4(v4));
+ }
+ let first = v6.segments()[0];
+ // NAT64 (`64:ff9b::/96`) carries an IPv4 address inside.
+ if v6.segments()[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
+ let [.., a, b, c, d] = v6.octets();
+ return is_public_ip(IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d)));
+ }
+ !(v6.is_loopback()
+ || v6.is_unspecified()
+ || v6.is_multicast()
+ || (first & 0xfe00) == 0xfc00
+ || (first & 0xffc0) == 0xfe80
+ || (first & 0xffc0) == 0xfec0
+ || first == 0x2001 && v6.segments()[1] == 0x0db8)
+ }
+ }
}
/// The subscribed-calendar client's resolver: a listed host is looked up as the system looks
@@ -1219,8 +1279,18 @@ impl reqwest::dns::Resolve for ListedOnly {
format!("{host} is not a calendar you subscribed to").into();
return Err(refused);
}
- let found = tokio::net::lookup_host((host.as_str(), 0)).await?;
- let addrs: reqwest::dns::Addrs = Box::new(found.collect::<Vec<_>>().into_iter());
+ // Whatever the name says, only addresses out on the internet are dialled: a feed
+ // whose name leads to this computer or the local network reaches neither.
+ let found: Vec<_> = tokio::net::lookup_host((host.as_str(), 0))
+ .await?
+ .filter(|a| is_public_ip(a.ip()))
+ .collect();
+ if found.is_empty() {
+ let refused: Box<dyn std::error::Error + Send + Sync> =
+ format!("{host} is not on the internet").into();
+ return Err(refused);
+ }
+ let addrs: reqwest::dns::Addrs = Box::new(found.into_iter());
Ok(addrs)
})
}
@@ -1229,8 +1299,12 @@ impl reqwest::dns::Resolve for ListedOnly {
/// Where a request that is not Apple's is pointed: a name the resolver refuses.
const REFUSED: &str = "http://refused.skykeep.invalid";
-/// Whether a request's URL may be sent: an Apple host by name, or this computer.
+/// Whether a request's URL may be sent: an Apple host by name, or this computer in tests.
fn url_is_apples(url: &reqwest::Url) -> bool {
+ url_apples(url, LOOPBACK)
+}
+
+fn url_apples(url: &reqwest::Url, loopback: bool) -> bool {
let Some(host) = url.host_str() else {
return false;
};
@@ -1239,8 +1313,8 @@ fn url_is_apples(url: &reqwest::Url) -> bool {
.trim_end_matches(']')
.parse::<std::net::IpAddr>()
{
- Ok(ip) => ip.is_loopback(),
- Err(_) => is_apple_host(host),
+ Ok(ip) => loopback && ip.is_loopback(),
+ Err(_) => apple_host(host, loopback),
}
}
@@ -1265,6 +1339,35 @@ impl reqwest::dns::Resolve for AppleOnly {
}
}
+#[cfg(test)]
+mod release_tests {
+ use super::*;
+
+ /// What the shipped client allows: Apple's hosts, and never this computer — by name or
+ /// by address.
+ #[test]
+ fn a_release_client_never_reaches_this_computer() {
+ for host in ["localhost", "LOCALHOST.", "127.0.0.1", "[::1]"] {
+ assert!(!apple_host(host, false), "{host}");
+ }
+ for url in [
+ "http://localhost:8080/",
+ "http://127.0.0.1:631/",
+ "http://127.1.2.3/",
+ "http://[::1]:9/",
+ "https://localhost./",
+ ] {
+ let u = reqwest::Url::parse(url).unwrap();
+ assert!(!url_apples(&u, false), "{url}");
+ assert!(url_apples(&u, true), "{url}");
+ }
+ assert!(url_apples(
+ &reqwest::Url::parse("https://p01-contacts.icloud.com/x").unwrap(),
+ false
+ ));
+ }
+}
+
#[cfg(test)]
mod listed_tests {
use super::*;
@@ -1300,6 +1403,53 @@ mod listed_tests {
assert!(!ok("https://example.org/a.ics"));
assert!(!ok("https://calendar.example.org.evil.net/a.ics"));
}
+
+ /// A subscription never reaches this computer or the local network: not by an address in
+ /// it, not by a name that leads there.
+ #[tokio::test]
+ async fn a_subscription_never_reaches_inside() {
+ use std::net::IpAddr;
+ for inside in [
+ "127.0.0.1",
+ "10.0.0.1",
+ "172.16.5.4",
+ "192.168.1.1",
+ "169.254.169.254",
+ "100.100.100.100",
+ "0.0.0.0",
+ "255.255.255.255",
+ "::1",
+ "::",
+ "fe80::1",
+ "fd00::1",
+ "::ffff:127.0.0.1",
+ "::ffff:192.168.0.1",
+ "64:ff9b::a9fe:a9fe",
+ ] {
+ assert!(!is_public_ip(inside.parse::<IpAddr>().unwrap()), "{inside}");
+ }
+ for out in ["93.184.215.14", "1.1.1.1", "2606:4700:4700::1111"] {
+ assert!(is_public_ip(out.parse::<IpAddr>().unwrap()), "{out}");
+ }
+ // Listed, and still refused: an address inside, or a name that leads inside.
+ let by_address = vec![normal_host("192.168.1.1"), normal_host("[::1]")];
+ for u in ["http://192.168.1.1/a.ics", "http://[::1]:8080/a.ics"] {
+ assert!(
+ !url_is_listed(&reqwest::Url::parse(u).unwrap(), &by_address),
+ "{u}"
+ );
+ }
+ let http = listed_only(&["localhost".into()]).build().unwrap();
+ let err = http
+ .get("http://localhost:9/feed.ics")
+ .send()
+ .await
+ .expect_err("a name that leads to this computer");
+ assert!(
+ format!("{err:?}").contains("not on the internet"),
+ "{err:?}"
+ );
+ }
}
#[cfg(test)]
diff --git a/crates/quince-icloud/src/bounded.rs b/crates/quince-icloud/src/bounded.rs
new file mode 100644
index 0000000..1a219d1
--- /dev/null
+++ b/crates/quince-icloud/src/bounded.rs
@@ -0,0 +1,55 @@
+//! Decompressing someone else's bytes, with a ceiling. A shared note's table, a feed or a
+//! document arrives compressed, and ten megabytes of zeros inflate to gigabytes: read whole,
+//! that was enough to take the computer's memory (and on Linux, the whole desktop with it).
+//! Every inflate of remote data reads through here, and anything past its ceiling is refused —
+//! never cut short and read as if whole.
+
+use std::io::Read;
+
+/// The most any one remote payload inflates to: far beyond a real note, table or calendar.
+pub const MOST_INFLATED: u64 = 64 * 1024 * 1024;
+
+/// All of `reader`, or `None` when it fails or holds more than `most` bytes.
+pub fn read_capped(reader: impl Read, most: u64) -> Option<Vec<u8>> {
+ let mut out = Vec::new();
+ reader
+ .take(most.saturating_add(1))
+ .read_to_end(&mut out)
+ .ok()?;
+ (out.len() as u64 <= most).then_some(out)
+}
+
+/// A gzip stream inflated, within `most`.
+pub fn gunzip(data: &[u8], most: u64) -> Option<Vec<u8>> {
+ read_capped(flate2::read::GzDecoder::new(data), most)
+}
+
+/// A zlib stream inflated, within `most`.
+pub fn unzlib(data: &[u8], most: u64) -> Option<Vec<u8>> {
+ read_capped(flate2::read::ZlibDecoder::new(data), most)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+
+ fn gz(bytes: &[u8]) -> Vec<u8> {
+ let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
+ e.write_all(bytes).unwrap();
+ e.finish().unwrap()
+ }
+
+ #[test]
+ fn a_bomb_is_refused_and_a_real_payload_reads_whole() {
+ let bomb = gz(&vec![0u8; 4 * 1024 * 1024]);
+ assert!(bomb.len() < 64 * 1024, "{}", bomb.len());
+ assert_eq!(gunzip(&bomb, 1024 * 1024), None);
+ assert_eq!(
+ gunzip(&bomb, 4 * 1024 * 1024).map(|v| v.len()),
+ Some(4 * 1024 * 1024)
+ );
+ assert_eq!(gunzip(&gz(b"hello"), 5).as_deref(), Some(&b"hello"[..]));
+ assert_eq!(gunzip(b"not gzip", 100), None);
+ }
+}
diff --git a/crates/quince-icloud/src/calendar_feeds.rs b/crates/quince-icloud/src/calendar_feeds.rs
index 3af788e..ef335db 100644
--- a/crates/quince-icloud/src/calendar_feeds.rs
+++ b/crates/quince-icloud/src/calendar_feeds.rs
@@ -139,13 +139,11 @@ pub async fn fetch(http: &reqwest::Client, url: &str) -> Result<String> {
bytes.extend_from_slice(&chunk);
}
let text = if bytes.starts_with(&[0x1f, 0x8b]) {
- use std::io::Read;
- let mut out = String::new();
- flate2::read::GzDecoder::new(&bytes[..])
- .take(MOST_BYTES as u64)
- .read_to_string(&mut out)
- .map_err(|_| Error::Refused("That calendar file couldn’t be opened.".into()))?;
- out
+ // Within the same ceiling as the file itself (crate::bounded): too large is refused,
+ // never read cut short as if whole.
+ let out = crate::bounded::gunzip(&bytes, MOST_BYTES as u64)
+ .ok_or_else(|| Error::Refused("That calendar file couldn’t be opened.".into()))?;
+ String::from_utf8_lossy(&out).into_owned()
} else {
String::from_utf8_lossy(&bytes).into_owned()
};
@@ -397,7 +395,7 @@ fn duration(s: &str) -> Option<i64> {
let n: i64 = number.parse().ok()?;
number.clear();
any = true;
- total += n * match (unit, in_time) {
+ let unit: i64 = match (unit, in_time) {
('W', _) => 7 * 86_400,
('D', _) => 86_400,
('H', true) => 3_600,
@@ -405,6 +403,8 @@ fn duration(s: &str) -> Option<i64> {
('S', true) => 1,
_ => return None,
};
+ // A feed's number can be anything: one too large is no duration, not a crash.
+ total = total.checked_add(n.checked_mul(unit)?)?;
}
}
}
@@ -488,8 +488,12 @@ fn rule_of(p: &Property, here: &TimeZone) -> Option<Rule> {
}
"BYDAY" => {
for d in list() {
+ // The day is the last two letters; anything else there (`é1`) is no day,
+ // and never a cut through the middle of a character.
let split = d.len().saturating_sub(2);
- let (n, code) = d.split_at(split);
+ let (Some(n), Some(code)) = (d.get(..split), d.get(split..)) else {
+ return None;
+ };
let n: i8 = if n.is_empty() || n == "+" {
0
} else {
@@ -726,13 +730,20 @@ fn month_day(year: i16, month: i8, day: i8) -> Option<Date> {
.flatten()
}
-/// The dates one period of a rule holds, in order.
+/// A span of `n` days, months or years, or none where the calendar has no such span: a
+/// feed's `INTERVAL` is anyone's number, and jiff's own `.days()` panics past its range.
+fn days(n: i64) -> Option<Span> {
+ Span::new().try_days(n).ok()
+}
+
+/// The dates one period of a rule holds, in order. None at all past the calendar's range.
fn period_dates(rule: &Rule, first: Date, k: i64) -> Vec<Date> {
- let step = k * rule.interval;
+ let Some(step) = k.checked_mul(rule.interval) else {
+ return Vec::new();
+ };
let mut out: Vec<Date> = match rule.freq {
- Freq::Daily => first
- .checked_add(step.days())
- .ok()
+ Freq::Daily => days(step)
+ .and_then(|span| first.checked_add(span).ok())
.into_iter()
.filter(|d| {
rule.by_day.is_empty() || rule.by_day.iter().any(|(_, w)| *w == d.weekday())
@@ -743,7 +754,12 @@ fn period_dates(rule: &Rule, first: Date, k: i64) -> Vec<Date> {
(first.weekday().to_monday_zero_offset() - rule.week_start.to_monday_zero_offset())
.rem_euclid(7),
);
- let Ok(week) = first.checked_add((step * 7 - back).days()) else {
+ let Some(Ok(week)) = step
+ .checked_mul(7)
+ .and_then(|d| d.checked_sub(back))
+ .and_then(days)
+ .map(|span| first.checked_add(span))
+ else {
return Vec::new();
};
if rule.by_day.is_empty() {
@@ -756,14 +772,21 @@ fn period_dates(rule: &Rule, first: Date, k: i64) -> Vec<Date> {
}
}
Freq::Monthly => {
- let Ok(m) = first.first_of_month().checked_add(step.months()) else {
+ let Some(Ok(m)) = Span::new()
+ .try_months(step)
+ .ok()
+ .map(|span| first.first_of_month().checked_add(span))
+ else {
return Vec::new();
};
month_set(rule, m.year(), m.month(), first.day())
}
Freq::Yearly => {
- let Ok(y) = Date::new(first.year(), 1, 1).and_then(|d| d.checked_add(step.years()))
- else {
+ let Ok(y) = Date::new(first.year(), 1, 1).and_then(|d| {
+ Span::new()
+ .try_years(step)
+ .and_then(|span| d.checked_add(span))
+ }) else {
return Vec::new();
};
let year = y.year();
@@ -965,7 +988,7 @@ fn event_of(item: &Item, w: &When, calendar_guid: &str, key: i64) -> Option<Even
let zone = TimeZone::system();
let start = d.to_zoned(zone.clone()).ok()?;
let end = d
- .checked_add(Span::new().days(item.length.max(1)))
+ .checked_add(days(item.length.max(1))?)
.ok()?
.to_zoned(zone)
.ok()?;
@@ -980,7 +1003,7 @@ fn event_of(item: &Item, w: &When, calendar_guid: &str, key: i64) -> Option<Even
let start = dt.to_zoned(tz.clone()).ok()?.timestamp().as_second();
(
start,
- start + item.length,
+ start.checked_add(item.length)?,
false,
tz.iana_name().map(ToString::to_string),
)
@@ -1226,4 +1249,59 @@ mod tests {
assert_eq!(s.calendar(0).guid, "quince:sub:a");
assert!(!s.calendar(0).writable);
}
+ /// A public feed is anyone's file: no rule, date or length in it stops the calendar. A rule
+ /// that names no real date walks to its end and gives nothing; one too large for the
+ /// calendar stops; a date that does not exist is left out.
+ #[test]
+ fn a_hostile_feed_never_panics() {
+ let rules = [
+ "FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=30",
+ "FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=31;BYDAY=MO",
+ "FREQ=DAILY;INTERVAL=1000000",
+ "FREQ=WEEKLY;INTERVAL=9223372036854775807",
+ "FREQ=MONTHLY;INTERVAL=9223372036854775807",
+ "FREQ=YEARLY;INTERVAL=9223372036854775807",
+ "FREQ=YEARLY;INTERVAL=20000",
+ "FREQ=MONTHLY;INTERVAL=300000",
+ "FREQ=WEEKLY;INTERVAL=3000000;BYDAY=MO,TU",
+ "FREQ=MONTHLY;BYDAY=\u{e9}1",
+ "FREQ=WEEKLY;BYDAY=\u{20ac}",
+ "FREQ=WEEKLY;BYDAY=1",
+ "FREQ=WEEKLY;BYDAY=\u{1F600}MO",
+ "FREQ=MONTHLY;BYDAY=127MO,-128FR",
+ "FREQ=MONTHLY;BYSETPOS=-2147483648,2147483647;BYDAY=MO",
+ "FREQ=YEARLY;BYDAY=-53SU;COUNT=9223372036854775807",
+ "FREQ=DAILY;UNTIL=99999999T999999Z",
+ ];
+ let starts = [
+ "DTSTART;VALUE=DATE:20240229",
+ "DTSTART:99991231T235959Z",
+ "DTSTART;VALUE=DATE:00010101",
+ "DTSTART;TZID=Europe/Berlin:20260329T023000",
+ ];
+ let (from, _) = year(2026);
+ let (_, to) = year(9998);
+ for rule in rules {
+ for start in starts {
+ let text = wrap(&format!(
+ "BEGIN:VEVENT\r\nUID:x\r\nSUMMARY:x\r\n{start}\r\nDURATION:P9999999999999999W\r\nRRULE:{rule}\r\nEND:VEVENT\r\n"
+ ));
+ if let Ok(feed) = parse(&text, &kolkata()) {
+ let _ = events(&feed, "c", from, to);
+ let _ = events(&feed, "c", i64::MIN / 2, i64::MAX / 2);
+ }
+ }
+ }
+ // A date that does not exist is skipped, and the rest of the feed still reads.
+ let text = wrap(
+ "BEGIN:VEVENT\r\nUID:long\r\nSUMMARY:Long\r\nDTSTART;VALUE=DATE:20260301\r\nDTEND;VALUE=DATE:99991231\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:bad\r\nSUMMARY:Bad\r\nDTSTART;VALUE=DATE:20260230\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:ok\r\nSUMMARY:Ok\r\nDTSTART;VALUE=DATE:20260301\r\nEND:VEVENT\r\n",
+ );
+ let feed = parse(&text, &kolkata()).unwrap();
+ let got = events(&feed, "c", from, to);
+ assert!(got.iter().any(|e| e.title == "Ok"));
+ assert!(!got.iter().any(|e| e.title == "Bad"));
+ // A length too large to be one is none, not a wrapped-around number.
+ assert_eq!(duration("P9999999999999999W"), None);
+ assert_eq!(duration("PT1H30M"), Some(5_400));
+ }
}
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index a898f5d..ec29064 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -11,7 +11,6 @@
//! from an attacker-controlled length.
use base64::{engine::general_purpose::STANDARD as B64, Engine};
-use std::io::Read;
/// Where the readable text lives inside the document protobuf.
const TEXT_PATH: &[u64] = &[2, 3, 2];
@@ -111,26 +110,16 @@ fn inflate(compressed: &[u8]) -> Option<Vec<u8>> {
return Some(compressed.to_vec());
}
- let read_all = |mut reader: Box<dyn Read>| -> Option<Vec<u8>> {
- let mut out = Vec::new();
- reader.read_to_end(&mut out).ok()?;
- Some(out)
- };
-
// gzip
if compressed[0] == 0x1f && compressed[1] == 0x8b {
- return read_all(Box::new(
- flate2::read::GzDecoder::new(compressed).take(MAX_DECOMPRESSED),
- ));
+ return crate::bounded::gunzip(compressed, MAX_DECOMPRESSED);
}
// zlib: low nibble of the first byte is the method (8 = deflate), and the two-byte
// header is a multiple of 31.
let header = u16::from(compressed[0]) << 8 | u16::from(compressed[1]);
if compressed[0] & 0x0f == 8 && header % 31 == 0 {
- if let Some(out) = read_all(Box::new(
- flate2::read::ZlibDecoder::new(compressed).take(MAX_DECOMPRESSED),
- )) {
+ if let Some(out) = crate::bounded::unzlib(compressed, MAX_DECOMPRESSED) {
return Some(out);
}
}
diff --git a/crates/quince-icloud/src/courier.rs b/crates/quince-icloud/src/courier.rs
index 8151c26..1bc65c3 100644
--- a/crates/quince-icloud/src/courier.rs
+++ b/crates/quince-icloud/src/courier.rs
@@ -368,6 +368,35 @@ const EXPIRED_PUSH_TOKEN: u64 = 6;
/// How long the server is given to answer the connect, and a JWT request.
const ANSWER: Duration = Duration::from_secs(15);
+/// The socket's address for `server` (a host, as [`SERVER`], or a full `wss://` address), or
+/// `None` when it is not Apple's push service. The host is read as the socket library reads
+/// it — a parsed URL, not the text — so `evil.example?.apple.com` or `evil.example#.apple.com`
+/// is the host it really is. Only `wss://`; a plain `ws://` socket, or this computer, only in
+/// tests (`loopback`).
+fn push_base(server: &str, loopback: bool) -> Option<String> {
+ let full = if server.contains("://") {
+ server.to_string()
+ } else {
+ format!("wss://{server}")
+ };
+ let url = reqwest::Url::parse(&full).ok()?;
+ let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
+ let bare = url.username().is_empty()
+ && url.password().is_none()
+ && url.query().is_none()
+ && url.fragment().is_none()
+ && matches!(url.path(), "" | "/");
+ let apple = url.scheme() == "wss" && host.ends_with(".apple.com");
+ let here = loopback
+ && matches!(url.scheme(), "ws" | "wss")
+ && (host == "localhost"
+ || host
+ .trim_matches(['[', ']'])
+ .parse::<std::net::IpAddr>()
+ .is_ok_and(|ip| ip.is_loopback()));
+ (bare && (apple || here)).then(|| url.as_str().trim_end_matches('/').to_string())
+}
+
impl Courier {
/// Connect to `server` (normally [`SERVER`]), get or keep a token, and filter the socket
/// to the containers' topics. Not yet registered: see [`Courier::register`].
@@ -377,26 +406,16 @@ impl Courier {
containers: &[&str],
) -> std::result::Result<Self, Failure> {
// Only Apple's push server, ever: the socket does not ride the HTTP client's locks.
- let host = server
- .split("://")
- .last()
- .unwrap_or(server)
- .split(['/', ':'])
- .next()
- .unwrap_or_default();
- if !(host.ends_with(".apple.com") || host == "localhost" || host == "127.0.0.1") {
- return Err(Failure::Refused(format!("{host} is not Apple's")));
- }
- let scheme = if server.starts_with("ws://") {
- ""
- } else {
- "wss://"
+ let Some(base) = push_base(server, cfg!(test)) else {
+ return Err(Failure::Refused(format!(
+ "{server} is not Apple's push server"
+ )));
};
let topics: Vec<String> = containers.iter().map(|c| topic_of(c)).collect();
let mut clock: Option<u64> = None;
for _ in 0..3 {
let url = format!(
- "{scheme}{server}/v2/{}",
+ "{base}/v2/{}",
identity.connect_message(clock.unwrap_or_else(now_ms))
);
let mut request = url
@@ -961,6 +980,32 @@ mod tests {
assert!(matches!(got, Err(Failure::Refused(_))));
}
+ /// The host is the one the socket would dial, not text that ends the right way; and a
+ /// release build dials Apple over `wss://` alone, never this computer.
+ #[test]
+ fn the_push_host_is_read_as_a_url() {
+ assert_eq!(
+ push_base(SERVER, false).as_deref(),
+ Some("wss://websocket.push.apple.com")
+ );
+ for bad in [
+ "evil.example?.apple.com",
+ "evil.example#.apple.com",
+ "evil.example/.apple.com",
+ "[email protected]:443/.apple.com",
+ "apple.com.evil.example",
+ "ws://websocket.push.apple.com",
+ "https://websocket.push.apple.com",
+ "wss://evil.example?x=.apple.com",
+ "localhost",
+ "ws://127.0.0.1:9",
+ "ws://localhost:9",
+ ] {
+ assert_eq!(push_base(bad, false), None, "{bad}");
+ }
+ assert!(push_base("ws://127.0.0.1:9", true).is_some());
+ }
+
#[test]
fn a_malformed_message_is_refused_not_panicked_on() {
assert!(pb::fields(&[0x0a, 0x05, 1]).is_none());
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 07a783f..3041e9f 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -249,8 +249,12 @@ pub async fn download_to(
)));
}
- if let Some(parent) = destination.parent() {
- tokio::fs::create_dir_all(parent).await.ok();
+ // Into a folder that is already there, never one made on the way: the caller chose the
+ // folder (Downloads), and a name that reached for others would have them made for it.
+ if !destination.parent().is_some_and(std::path::Path::is_dir) {
+ return Err(Error::Protocol(
+ "the folder to save into is not there".into(),
+ ));
}
// Into a file of its own beside the destination, moved into place only once it is all
// there and only if nothing has taken the name meanwhile. Written straight to the name,
@@ -2029,6 +2033,37 @@ mod write_tests {
std::fs::remove_dir_all(&dir).ok();
}
+ #[tokio::test]
+ async fn a_download_never_makes_folders_on_its_way() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ws/com.apple.CloudDocs/download/by_id"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "data_token": { "url": format!("{}/bytes", server.uri()) }
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/bytes"))
+ .respond_with(ResponseTemplate::new(200).set_body_bytes(b"x".to_vec()))
+ .mount(&server)
+ .await;
+
+ let dir = tempdir();
+ let destination = dir.join("Startup").join("update.bat");
+ let saved = download_to(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &file(),
+ &destination,
+ )
+ .await;
+ assert!(saved.is_err());
+ assert!(!dir.join("Startup").exists());
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
fn tempdir() -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("quince-drive-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 536813b..370cbe8 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -14,6 +14,7 @@ macro_rules! quiet {
};
}
+pub mod bounded;
pub mod calendar;
pub mod calendar_feeds;
pub mod ckdocument;
diff --git a/crates/quince-icloud/src/occasions.rs b/crates/quince-icloud/src/occasions.rs
index a624d32..b90ec0c 100644
--- a/crates/quince-icloud/src/occasions.rs
+++ b/crates/quince-icloud/src/occasions.rs
@@ -371,14 +371,10 @@ pub async fn fetch_feed(http: &reqwest::Client, region: &str, lang: &str) -> Res
}
let bytes = response.bytes().await?;
let text = if bytes.starts_with(&[0x1f, 0x8b]) {
- use std::io::Read;
- let mut out = String::new();
- flate2::read::GzDecoder::new(&bytes[..])
- .read_to_string(&mut out)
- .map_err(|e| {
- Error::Protocol(format!("the holiday calendar would not open: {e}"))
- })?;
- out
+ let out = crate::bounded::gunzip(&bytes, crate::bounded::MOST_INFLATED)
+ .ok_or_else(|| Error::Protocol("the holiday calendar would not open".into()))?;
+ String::from_utf8(out)
+ .map_err(|e| Error::Protocol(format!("the holiday calendar would not open: {e}")))?
} else {
String::from_utf8_lossy(&bytes).into_owned()
};
diff --git a/crates/quince-icloud/src/table.rs b/crates/quince-icloud/src/table.rs
index 3acfe03..ff5ad66 100644
--- a/crates/quince-icloud/src/table.rs
+++ b/crates/quince-icloud/src/table.rs
@@ -120,21 +120,25 @@ fn object_index(id: &[u8]) -> Option<usize> {
usize::try_from(int(&fields(id)?, 6)?).ok()
}
+/// A table's data, inflated — within a ceiling: a shared note's table is whoever shared it's
+/// to write, and a bomb is refused rather than read into memory (crate::bounded).
fn inflate(data: &[u8]) -> Option<Vec<u8>> {
+ use crate::bounded::{gunzip, MOST_INFLATED};
use std::io::Read;
- let mut out = Vec::new();
if data.starts_with(&[0x1f, 0x8b]) {
- flate2::read::GzDecoder::new(data)
- .read_to_end(&mut out)
- .ok()?;
- } else if flate2::read::ZlibDecoder::new(data)
+ return gunzip(data, MOST_INFLATED);
+ }
+ // Zlib, or (when it is not) bare bytes. One that is zlib but too large is refused, not
+ // taken for bare bytes.
+ let mut out = Vec::new();
+ match flate2::read::ZlibDecoder::new(data)
+ .take(MOST_INFLATED + 1)
.read_to_end(&mut out)
- .is_ok()
{
- } else {
- return Some(data.to_vec());
+ Ok(_) if out.len() as u64 > MOST_INFLATED => None,
+ Ok(_) => Some(out),
+ Err(_) => Some(data.to_vec()),
}
- Some(out)
}
struct Doc<'a> {
@@ -1728,6 +1732,24 @@ pub fn cells(document: &[u8]) -> Option<Vec<Vec<String>>> {
mod tests {
use super::*;
+ /// A shared note's table that inflates past the ceiling is refused, never read whole.
+ #[test]
+ fn a_table_bomb_is_refused() {
+ use std::io::Write;
+ let zeros = vec![0u8; 1024 * 1024];
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
+ for _ in 0..=(crate::bounded::MOST_INFLATED / (1024 * 1024)) {
+ gz.write_all(&zeros).unwrap();
+ z.write_all(&zeros).unwrap();
+ }
+ let (gz, z) = (gz.finish().unwrap(), z.finish().unwrap());
+ assert!(gz.len() < 1024 * 1024 && z.len() < 1024 * 1024);
+ assert_eq!(inflate(&gz), None);
+ assert_eq!(inflate(&z), None);
+ assert_eq!(inflate(b"plain"), Some(b"plain".to_vec()));
+ }
+
/// A 2×2 table a phone made and nobody typed in (iOS, 2026-10-21), gzip + base64.
const PHONE_BLANK: &[&str] = &[
"H4sIAAAAAAAC/+NgEJrCx8EgwCDVy8fFxsUCZDJKBWT5cQhIaXEwCKkpqRhAgS4WAgak2DgYhZgMGIE0M5BmBtKs",
diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs
index c76ae36..50383fb 100644
--- a/src-tauri/src/export.rs
+++ b/src-tauri/src/export.rs
@@ -344,6 +344,9 @@ fn copy(from: &Path, to: &Path, cancel: &AtomicBool) -> Done<u64> {
total += n as u64;
}
dst.flush()?;
+ drop(dst);
+ // Every file copied out is iCloud's, much of it other people's (Windows: Mark of the Web).
+ crate::saving::mark_from_internet(to);
Ok(total)
}
@@ -1347,7 +1350,7 @@ fn photos(
};
let found = order
.iter()
- .map(|s| src.photos.join(s).join(&p.id))
+ .map(|s| src.photos.join(s).join(&*crate::photos::cache_name(&p.id)))
.find(|f| f.is_file());
let when = Timestamp::from_second(p.taken_at)
.unwrap_or(Timestamp::UNIX_EPOCH)
@@ -1383,7 +1386,10 @@ fn photos(
copy(&from, &to, t.cancel)?;
date(&to, Some(p.taken_at));
// A Live Photo's moving part, beside it under the same name.
- let live = src.photos.join("live").join(&p.id);
+ let live = src
+ .photos
+ .join("live")
+ .join(&*crate::photos::cache_name(&p.id));
if p.kind == "live" && live.is_file() {
let movie = names.unique(&dir, split_ext(&name).0, "MOV");
copy(&live, &dir.join(&movie), t.cancel)?;
diff --git a/src-tauri/src/links.rs b/src-tauri/src/links.rs
new file mode 100644
index 0000000..5fd5786
--- /dev/null
+++ b/src-tauri/src/links.rs
@@ -0,0 +1,173 @@
+//! Where a navigation in a window may go. Much of what the window shows was written by someone
+//! else — a shared note, a shared list, an invitation, a public calendar — so a link's address
+//! is theirs to choose, and the computer's opener (ShellExecute, xdg-open) runs whatever an
+//! address names: a `file:` link to a share, a `search-ms:` query, a `.desktop` file, a UNC
+//! path that hands over the person's Windows password hash. So only the kinds a person means by
+//! "a link" leave Skykeep; the page keeps the same list (src/lib/links.ts).
+
+use tauri::Url;
+
+/// The kinds of address handed to the computer's opener. Anything else is refused.
+const OUTSIDE: &[&str] = &["http", "https", "mailto", "tel", "geo"];
+
+/// What becomes of a navigation.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Navigation {
+ /// The app's own page: followed in the window.
+ Inside,
+ /// A link Skykeep opens: refused in the window and handed to the computer.
+ Outside,
+ /// Neither: refused, and not opened anywhere. `data:`, `blob:` and `javascript:` would put
+ /// a page of someone else's making in the window (a convincing "sign in again"), and
+ /// `quince:` is the app's own data, which is fetched, never navigated to.
+ Refused,
+}
+
+/// Where `url` may go. `dev` is a development build, whose page comes from the dev server on
+/// localhost; a release counts no other program's localhost as its own.
+pub fn navigation(url: &Url, dev: bool) -> Navigation {
+ let scheme = url.scheme();
+ let host = url.host_str().unwrap_or("");
+ let web = matches!(scheme, "http" | "https");
+ // The app's own page: `tauri://localhost` on Linux and macOS, `http(s)://tauri.localhost`
+ // on Windows; a blank page is nothing at all.
+ if scheme == "tauri" && host == "localhost"
+ || web && host == "tauri.localhost"
+ || web && dev && host == "localhost"
+ || scheme == "about" && url.path() == "blank"
+ {
+ return Navigation::Inside;
+ }
+ if !OUTSIDE.contains(&scheme) {
+ return Navigation::Refused;
+ }
+ // A web address names a host; one that names none (`http:///x`) is not followed.
+ if web && host.is_empty() {
+ return Navigation::Refused;
+ }
+ Navigation::Outside
+}
+
+/// What every `quince://` answer says about itself. The scheme is the app's own, so a page it
+/// served would be trusted with the app's commands; what it serves is pictures, media and files,
+/// some of them someone else's bytes. So: never read as another type than the one given
+/// (`nosniff`), and, were one ever opened as a page, nothing in it may run or load
+/// (`sandbox`, `default-src 'none'`).
+pub const GUARDS: [(&str, &str); 2] = [
+ ("x-content-type-options", "nosniff"),
+ (
+ "content-security-policy",
+ "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox",
+ ),
+];
+
+/// A response with the guards on it, in place of any it set itself.
+pub fn guard<T>(mut response: tauri::http::Response<T>) -> tauri::http::Response<T> {
+ for (name, value) in GUARDS {
+ response.headers_mut().insert(
+ tauri::http::HeaderName::from_static(name),
+ tauri::http::HeaderValue::from_static(value),
+ );
+ }
+ response
+}
+
+/// The scheme's responder, which guards every answer it gives.
+pub struct Guarded(pub tauri::UriSchemeResponder);
+
+impl Guarded {
+ pub fn respond<T: Into<std::borrow::Cow<'static, [u8]>>>(
+ self,
+ response: tauri::http::Response<T>,
+ ) {
+ self.0.respond(guard(response));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn nav(s: &str, dev: bool) -> Navigation {
+ navigation(&Url::parse(s).unwrap(), dev)
+ }
+
+ #[test]
+ fn the_apps_own_page_stays_in_the_window() {
+ assert_eq!(
+ nav("tauri://localhost/index.html", false),
+ Navigation::Inside
+ );
+ assert_eq!(nav("http://tauri.localhost/", false), Navigation::Inside);
+ assert_eq!(
+ nav("https://tauri.localhost/?app=notes", false),
+ Navigation::Inside
+ );
+ assert_eq!(nav("about:blank", false), Navigation::Inside);
+ assert_eq!(nav("http://localhost:1420/", true), Navigation::Inside);
+ }
+
+ #[test]
+ fn web_mail_calls_and_places_go_to_the_computer() {
+ for s in [
+ "https://example.org/agenda",
+ "http://example.org/",
+ "mailto:[email protected]",
+ "tel:+15550100",
+ "geo:0,0?q=Main%20Street",
+ "HTTPS://EXAMPLE.ORG/",
+ ] {
+ assert_eq!(nav(s, false), Navigation::Outside, "{s}");
+ }
+ // Another program's server on this computer is not the app's page in a release.
+ assert_eq!(nav("http://localhost:8080/", false), Navigation::Outside);
+ }
+
+ #[test]
+ fn every_answer_is_guarded_whatever_it_set() {
+ let r = tauri::http::Response::builder()
+ .header("Content-Type", "text/html")
+ .header("X-Content-Type-Options", "sniff-away")
+ .body(Vec::<u8>::new())
+ .unwrap();
+ let r = guard(r);
+ assert_eq!(r.headers()["x-content-type-options"], "nosniff");
+ let csp = r.headers()["content-security-policy"].to_str().unwrap();
+ assert!(
+ csp.contains("default-src 'none'") && csp.contains("sandbox"),
+ "{csp}"
+ );
+ assert!(!csp.contains("script-src"), "{csp}");
+ assert_eq!(
+ r.headers().get_all("x-content-type-options").iter().count(),
+ 1
+ );
+ }
+
+ #[test]
+ fn every_other_kind_is_refused_not_opened() {
+ for s in [
+ "file:///home/someone/x.desktop",
+ "file://attacker.example/DavWWWRoot/a.lnk",
+ "file://server/share/report.url",
+ "search-ms:query=x&crumb=location:%5C%5Cattacker.example%5Cshare",
+ "search:query=x",
+ "ms-msdt:/id PCWDiagnostic",
+ "ms-settings:display",
+ "smb://attacker.example/share",
+ "javascript:alert(1)",
+ "data:text/html,<h1>Sign in to iCloud</h1>",
+ "blob:tauri://localhost/0b1c",
+ "quince://photo/ABC",
+ "quince://localhost/note-file/x",
+ "applenotes:note/0b1c2d3e-0000-0000-0000-000000000000",
+ "vscode://file/x",
+ "about:srcdoc",
+ "tauri://elsewhere/",
+ "ftp://example.org/x",
+ "webcal://example.org/feed.ics",
+ ] {
+ assert_eq!(nav(s, false), Navigation::Refused, "{s}");
+ }
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 5af0cbc..a27e954 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -22,6 +22,7 @@ mod export;
mod grants;
mod intake;
mod library_lock;
+mod links;
mod login;
mod migrate;
mod mount;
@@ -43,6 +44,7 @@ mod poster {
mod push;
mod refresh;
mod reminders_cmds;
+mod saving;
// Skykeep's results in GNOME's and KDE's own search, on the session bus.
#[cfg(target_os = "linux")]
mod search_provider;
@@ -715,6 +717,7 @@ async fn note_attachment_open(
tokio::fs::rename(&partial, &path)
.await
.map_err(|e| e.to_string())?;
+ saving::mark_from_internet(&path);
hand_over_attachment(&app, &path).await
}
@@ -796,17 +799,37 @@ pub(crate) fn attachment_name(given: Option<&str>, id: &str) -> String {
let trimmed = cleaned
.trim_start_matches(['.', ' '])
.trim_end_matches(['.', ' ']);
- // Long enough for any real name, short enough for every file system.
- let mut name: String = trimmed.chars().take(120).collect();
+ // Long enough for any real name, short enough for every file system — and, cut short, it
+ // still ends in neither a dot nor a space, which Windows drops (turning `a.pdf.` into
+ // another file than the one checked).
+ let mut name: String = trimmed
+ .chars()
+ .take(120)
+ .collect::<String>()
+ .trim_end_matches(['.', ' '])
+ .to_string();
+ // Windows reads a device in the stem whatever follows it (`CON.txt`, `CON .txt`), and
+ // counts superscript digits as digits (`COM¹`).
let stem = name
.split('.')
.next()
.unwrap_or_default()
- .to_ascii_uppercase();
- let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
- || (stem.len() == 4
- && (stem.starts_with("COM") || stem.starts_with("LPT"))
- && stem.as_bytes()[3].is_ascii_digit());
+ .trim_end_matches(' ')
+ .to_uppercase();
+ let numbered = |prefix: &str| {
+ stem.strip_prefix(prefix).is_some_and(|n| {
+ let mut n = n.chars();
+ matches!(
+ (n.next(), n.next()),
+ (Some('0'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}'), None)
+ )
+ })
+ };
+ let device = matches!(
+ stem.as_str(),
+ "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" | "CLOCK$"
+ ) || numbered("COM")
+ || numbered("LPT");
if device {
name.insert(0, '_');
}
@@ -894,6 +917,71 @@ pub(crate) fn runs_code(name: &str, bytes: &[u8]) -> bool {
"img",
"vhd",
"vhdx",
+ "appxbundle",
+ "msixbundle",
+ "appinstaller",
+ "search-ms",
+ "searchconnector-ms",
+ "diagcab",
+ "rdp",
+ "website",
+ "wsc",
+ "sct",
+ "msh",
+ "msh1",
+ "msh2",
+ "mshxml",
+ "msh1xml",
+ "msh2xml",
+ "ps1xml",
+ "ps2",
+ "ps2xml",
+ "psc1",
+ "psc2",
+ "vb",
+ "grp",
+ "hlp",
+ "ins",
+ "isp",
+ "theme",
+ "themepack",
+ "deskthemepack",
+ "cab",
+ "xbap",
+ "jsx",
+ // Office documents that carry macros or add-ins, and OneNote's (a favourite carrier)
+ "docm",
+ "dotm",
+ "xlsm",
+ "xltm",
+ "xlam",
+ "xla",
+ "xll",
+ "pptm",
+ "potm",
+ "ppsm",
+ "ppam",
+ "sldm",
+ "one",
+ "onepkg",
+ "onetoc2",
+ "mdb",
+ "mde",
+ "accde",
+ "ade",
+ "adp",
+ "mam",
+ "mda",
+ // Pages a browser runs from the disk, with their scripts
+ "html",
+ "htm",
+ "xhtml",
+ "xht",
+ "shtml",
+ "mht",
+ "mhtml",
+ "svg",
+ "svgz",
// macOS
"app",
"command",
@@ -957,12 +1045,39 @@ fn percent_decode(text: &str) -> String {
/// its owner can open. Made with the system's usual permissions it was readable by every user
/// of the computer, and the cookies are a signed-in iCloud session. Everything inside is covered
/// at once: nothing in a folder can be reached without opening the folder.
+///
+/// What is directly inside is made the owner's alone too — the library and its journal, each
+/// folder of photos, notes' files, faces — so a copy or a restore that loses the outer folder's
+/// mode does not leave them open to everyone. Called again once the library is open, for the
+/// files the database makes as it opens.
fn keep_private(dir: &std::path::Path) {
let _ = std::fs::create_dir_all(dir);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ // Never through a link: its target is not this folder's to change.
+ let Ok(kind) = entry.file_type() else {
+ continue;
+ };
+ let mode = if kind.is_dir() {
+ 0o700
+ } else if kind.is_file() {
+ 0o600
+ } else {
+ continue;
+ };
+ let path = entry.path();
+ if std::fs::symlink_metadata(&path)
+ .is_ok_and(|m| m.permissions().mode() & 0o777 != mode)
+ {
+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode));
+ }
+ }
}
}
@@ -2099,6 +2214,21 @@ async fn network_reach(feeds: State<'_, Feeds>) -> UiResult<Reach> {
})
}
+/// The `https://` form of a plain `http://` feed address, to be tried first; `None` for one
+/// already secure.
+fn secure_feed_url(url: &str) -> Option<String> {
+ let mut u = reqwest::Url::parse(url).ok()?;
+ if u.scheme() != "http" {
+ return None;
+ }
+ // A port written for http is http's; the secure one is the scheme's own.
+ if u.port().is_some() {
+ u.set_port(None).ok()?;
+ }
+ u.set_scheme("https").ok()?;
+ Some(u.to_string())
+}
+
/// Fetch one subscription's file with the client that reaches its host and nothing else.
async fn fetch_subscription(url: &str) -> UiResult<(String, feeds::Feed)> {
let host = feeds::host_of(url).ok_or("That address has no server in it.")?;
@@ -2221,19 +2351,47 @@ async fn calendar_subscribe(
app: tauri::AppHandle,
feeds_state: State<'_, Feeds>,
) -> UiResult<Subscription> {
- let url = feeds::normalise_url(&url)
- .map_err(|e| e.to_string())?
- .to_string();
+ let url = feeds::normalise_url(&url).map_err(|e| e.to_string())?;
+ // A public calendar is out on the internet; an address on this computer or the local
+ // network is refused here, said plainly (the client refuses it besides, and a name that
+ // leads there: quince_auth::listed_only).
+ if let Ok(ip) = url
+ .host_str()
+ .unwrap_or_default()
+ .trim_matches(['[', ']'])
+ .parse::<std::net::IpAddr>()
+ {
+ if !quince_auth::is_public_ip(ip) {
+ return Err(
+ "That address is on this computer or your local network, not a public calendar."
+ .into(),
+ );
+ }
+ }
+ let url = url.to_string();
+ // Over https where the server offers it: a plain http feed can be changed on its way by
+ // anyone on the network, events and their links with it.
+ let secure = secure_feed_url(&url);
if feeds_state
.subs
.lock()
.await
.iter()
- .any(|(s, _)| s.url == url)
+ .any(|(s, _)| s.url == url || secure.as_ref() == Some(&s.url))
{
return Err("You’re already subscribed to that calendar.".into());
}
- let (text, feed) = fetch_subscription(&url).await?;
+ let secured = match &secure {
+ Some(s) => fetch_subscription(s).await.ok().map(|got| (s.clone(), got)),
+ None => None,
+ };
+ let (url, (text, feed)) = match secured {
+ Some(got) => got,
+ None => {
+ let got = fetch_subscription(&url).await?;
+ (url, got)
+ }
+ };
let mut subs = feeds_state.subs.lock().await;
let taken: Vec<String> = subs.iter().map(|(s, _)| s.colour.clone()).collect();
let colour = feed.colour.clone().unwrap_or_else(|| {
@@ -3590,7 +3748,9 @@ fn free_path(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
let (stem, ext) = name.rsplit_once('.').map_or((name, ""), |(s, e)| (s, e));
let mut path = dir.join(name);
let mut suffix = 1;
- while path.exists() {
+ // Anything at all under the name counts as taken — a link too, even one that leads
+ // nowhere: written through, it would put the file wherever the link points.
+ while path.symlink_metadata().is_ok() {
path = dir.join(if ext.is_empty() {
format!("{stem} {suffix}")
} else {
@@ -3624,17 +3784,13 @@ async fn contacts_export(
.path()
.download_dir()
.map_err(|_| "Couldn't find your Downloads folder.".to_string())?;
- // A name fit for a file: no folders smuggled in, never empty.
- let clean: String = file_name
- .chars()
- .filter(|c| !matches!(c, '/' | '\\' | '\0'))
- .collect();
- let clean = if clean.trim().trim_end_matches(".vcf").is_empty() {
- "iCloud vCards.vcf".into()
+ // A name fit for a file: no folders, streams or devices smuggled in, never empty.
+ let clean = if file_name.trim().trim_end_matches(".vcf").is_empty() {
+ "iCloud vCards.vcf"
} else {
- clean
+ file_name.as_str()
};
- let path = free_path(&downloads, &clean);
+ let path = saving::save_path(&downloads, clean, "iCloud vCards.vcf")?;
std::fs::write(&path, vcard).map_err(|e| format!("Couldn't save the vCard: {e}"))?;
Ok(path.to_string_lossy().into_owned())
}
@@ -3864,24 +4020,17 @@ async fn drive_download(
.path()
.download_dir()
.map_err(|_| "Couldn't find your Downloads folder.".to_string())?;
- let name = item.display_name();
- let (stem, ext) = name
- .rsplit_once('.')
- .map_or((name.as_str(), ""), |(s, e)| (s, e));
- let mut destination = downloads.join(&name);
- let mut suffix = 1;
- while destination.exists() {
- destination = downloads.join(if ext.is_empty() {
- format!("{stem} {suffix}")
- } else {
- format!("{stem} {suffix}.{ext}")
- });
- suffix += 1;
- }
+ // The name is whoever shared the folder's to choose (a `..\\` or a `C:` in it would reach
+ // out of Downloads on Windows): saved as one plain name in Downloads, or not at all.
+ tokio::fs::create_dir_all(&downloads)
+ .await
+ .map_err(|e| e.to_string())?;
+ let destination = saving::save_path(&downloads, &item.display_name(), "Download")?;
quince_icloud::drive::download_to(&http, &root, params, &item, &destination)
.await
.map_err(|e| e.to_string())?;
+ saving::mark_from_internet(&destination);
Ok(destination.to_string_lossy().into_owned())
}
@@ -5677,7 +5826,9 @@ fn main() {
// The window shows Quince and nothing else. A link to anywhere outside it — a phone
// number, an address, a web page in a note or an event — goes to the app this
// computer uses for it. Followed in place, a `tel:` link replaced the whole window
- // with "URL can't be shown", and there was no way back.
+ // with "URL can't be shown", and there was no way back. Only the kinds a person means
+ // by "a link" go out (links.rs): a `file:` or `search-ms:` link in a shared note is
+ // someone else's choice, and the opener would run it.
.plugin(
tauri::plugin::Builder::<tauri::Wry, ()>::new("links")
.on_navigation(|webview, url| {
@@ -5685,23 +5836,24 @@ fn main() {
// address on this computer (a server some other program runs on localhost)
// is somewhere else, opened outside; only a development build, whose page
// comes from the dev server, counts localhost as its own.
- let inside =
- matches!(url.scheme(), "tauri" | "quince" | "about" | "data" | "blob")
- || url.host_str().is_some_and(|h| {
- h == "tauri.localhost"
- || (cfg!(debug_assertions) && h == "localhost")
- });
- if !inside {
- use tauri_plugin_opener::OpenerExt;
- if let Err(e) = webview
- .app_handle()
- .opener()
- .open_url(url.as_str(), None::<&str>)
- {
- quiet!("a link could not be opened: {e}");
+ match links::navigation(url, cfg!(debug_assertions)) {
+ links::Navigation::Inside => true,
+ links::Navigation::Outside => {
+ use tauri_plugin_opener::OpenerExt;
+ if let Err(e) = webview
+ .app_handle()
+ .opener()
+ .open_url(url.as_str(), None::<&str>)
+ {
+ quiet!("a link could not be opened: {e}");
+ }
+ false
+ }
+ links::Navigation::Refused => {
+ quiet!("a link of a kind Skykeep does not open: {}", url.scheme());
+ false
}
}
- inside
})
.on_webview_ready(|webview| app_cache(&webview))
.build(),
@@ -5749,6 +5901,9 @@ fn main() {
// webview itself, which is what keeps a scrolling list cheap.
.register_asynchronous_uri_scheme_protocol("quince", |ctx, request, responder| {
let app = ctx.app_handle().clone();
+ // Every answer carries the same guard (links.rs): its bytes are never sniffed into
+ // something active, and never run as a page of their own.
+ let responder = links::Guarded(responder);
// WebKitGTK reads `quince://photo/<id>` with "photo" as the host, while Tauri's
// own helper produces `quince://localhost/photo/<id>`. Accept either, rather than
// depending on which one the caller happened to build.
@@ -5912,6 +6067,7 @@ fn main() {
// The local library. Opened once at startup so every command shares one
// connection and the WAL behaves.
let mut library = Library::open(&dir)?;
+ keep_private(&dir);
timing::mark("library open");
adopt_writer(&mut library);
app.manage(Data(library_lock::LibraryLock::new(
@@ -6258,6 +6414,52 @@ fn main() {
#[cfg(test)]
mod tests {
+ /// Everything directly in the data folder is its owner's alone, whatever it was made with.
+ #[cfg(unix)]
+ #[test]
+ fn the_library_and_its_folders_are_the_owners_alone() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let data = dir.path().join("data");
+ std::fs::create_dir_all(data.join("photos").join("thumb")).unwrap();
+ std::fs::create_dir_all(data.join("note-media")).unwrap();
+ for f in ["library.db", "library.db-wal", "library.db-shm"] {
+ std::fs::write(data.join(f), b"x").unwrap();
+ std::fs::set_permissions(data.join(f), std::fs::Permissions::from_mode(0o644)).unwrap();
+ }
+ std::fs::set_permissions(data.join("photos"), std::fs::Permissions::from_mode(0o755))
+ .unwrap();
+ // A link inside is left alone, and so is what it leads to.
+ let outside = dir.path().join("outside.txt");
+ std::fs::write(&outside, b"y").unwrap();
+ std::fs::set_permissions(&outside, std::fs::Permissions::from_mode(0o644)).unwrap();
+ std::os::unix::fs::symlink(&outside, data.join("link")).unwrap();
+ super::keep_private(&data);
+ let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode(&data), 0o700);
+ for f in ["library.db", "library.db-wal", "library.db-shm"] {
+ assert_eq!(mode(&data.join(f)), 0o600, "{f}");
+ }
+ assert_eq!(mode(&data.join("photos")), 0o700);
+ assert_eq!(mode(&data.join("note-media")), 0o700);
+ assert_eq!(mode(&outside), 0o644);
+ }
+
+ /// A plain http feed is tried over https first; a secure one is left as it is.
+ #[test]
+ fn a_plain_feed_is_tried_secure_first() {
+ use super::secure_feed_url;
+ assert_eq!(
+ secure_feed_url("http://calendar.example.org/team.ics?k=1").as_deref(),
+ Some("https://calendar.example.org/team.ics?k=1")
+ );
+ assert_eq!(
+ secure_feed_url("http://calendar.example.org:8080/a.ics").as_deref(),
+ Some("https://calendar.example.org/a.ics")
+ );
+ assert_eq!(secure_feed_url("https://calendar.example.org/a.ics"), None);
+ }
+
/// The sidebar's services and the account's name are answered while the session is busy —
/// taken up again, or checked at the start of a sync — from what was kept, never a wait.
#[test]
@@ -6364,6 +6566,25 @@ mod tests {
"a.pdf.jar",
"Run.AppImage",
"s.lnk",
+ "invoice.one",
+ "budget.xlsm",
+ "letter.docm",
+ "deck.pptm",
+ "addin.xll",
+ "q.search-ms",
+ "q.searchConnector-ms",
+ "fix.diagcab",
+ "office.rdp",
+ "app.appinstaller",
+ "app.msix",
+ "app.appx",
+ "lib.library-ms",
+ "go.url",
+ "go.website",
+ "s.settingcontent-ms",
+ "page.hta",
+ "page.html",
+ "image.svg",
] {
assert!(runs_code(runs, b"%PDF-"), "{runs}");
}
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 07d353b..b590259 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -196,7 +196,7 @@ pub async fn fitted(app: &AppHandle, id: &str, long: u32) -> Result<Vec<u8>, Str
.join("photos")
.join("fit")
.join(long.to_string())
- .join(id);
+ .join(&*cache_name(id));
let preview = long > crate::photo_cache::THUMB_STEP;
if let Ok(bytes) = tokio::fs::read(&path).await {
// The viewer's sizes are previews, let go of longest unseen first: seen now.
@@ -262,7 +262,26 @@ pub(crate) fn cache_path(app: &AppHandle, id: &str, size: Size) -> PathBuf {
crate::state_dir(app)
.join("photos")
.join(size.name())
- .join(id)
+ .join(&*cache_name(id))
+}
+
+/// A record id as one name in a folder. Ids come from CloudKit and the window, and are checked
+/// where a request comes in (`requested`) — and here too, where one becomes a path, so no other
+/// way in can make one reach elsewhere. A record name is letters, digits, `-` and `_`, kept as
+/// it is; anything else is spelled out in hex behind a `~` no record name has.
+pub(crate) fn cache_name(id: &str) -> std::borrow::Cow<'_, str> {
+ if !id.is_empty()
+ && id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
+ return id.into();
+ }
+ let mut out = String::from("~");
+ for b in id.bytes() {
+ out.push_str(&format!("{b:02x}"));
+ }
+ out.into()
}
/// One picture of a photo: from the disk cache, or fetched from Apple once and kept.
@@ -407,7 +426,10 @@ async fn from_apple(
/// read once from the film and kept (`photos/poster/<id>`). An empty file there says the film
/// is dark all through, so it is not read again. `None` when there is none to be had.
async fn seen_frame(app: &AppHandle, id: &str) -> Option<Vec<u8>> {
- let kept = crate::state_dir(app).join("photos").join("poster").join(id);
+ let kept = crate::state_dir(app)
+ .join("photos")
+ .join("poster")
+ .join(&*cache_name(id));
if let Ok(bytes) = tokio::fs::read(&kept).await {
return (!bytes.is_empty()).then_some(bytes);
}
@@ -491,7 +513,7 @@ pub async fn repair_poster(app: &AppHandle, id: &str) -> bool {
.join("photos")
.join("fit")
.join(step.to_string())
- .join(id),
+ .join(&*cache_name(id)),
)
.await;
}
@@ -733,7 +755,12 @@ pub fn prepare(app: AppHandle) {
.take(600)
.map(|p| (p.id.clone(), steps_of(p, shown).1)),
)
- .filter(|(id, step)| !fit_dir.join(step.to_string()).join(id).exists())
+ .filter(|(id, step)| {
+ !fit_dir
+ .join(step.to_string())
+ .join(&*cache_name(id))
+ .exists()
+ })
.collect()
})
.await
@@ -1801,7 +1828,10 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui
Some(given) => crate::attachment_name(Some(given), &id),
None => format!("{id}.mp4"),
};
- let dir = crate::state_dir(&app).join("photos").join("open").join(&id);
+ let dir = crate::state_dir(&app)
+ .join("photos")
+ .join("open")
+ .join(&*cache_name(&id));
tokio::fs::create_dir_all(&dir)
.await
.map_err(|e| e.to_string())?;
@@ -1827,6 +1857,7 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui
head.truncate(n);
head
};
+ crate::saving::mark_from_internet(&path);
if crate::runs_code(&name, &head) {
return app
.opener()
@@ -2022,12 +2053,12 @@ pub async fn photo_download(
.path()
.download_dir()
.map_err(|_| "There is no Downloads folder to save to.")?;
- let name = if name.contains('/') || name.starts_with('.') {
- format!("Photo {}", &id[..id.len().min(8)])
- } else {
- name
- };
- let path = crate::free_path(&dir, &name);
+ // A shared album's file names are other people's: one plain name in Downloads, or none.
+ tokio::fs::create_dir_all(&dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ let fallback = format!("Photo {}", id.chars().take(8).collect::<String>());
+ let path = crate::saving::save_path(&dir, &name, &fallback)?;
let part = path.with_extension(format!(
"{}.part",
path.extension()
@@ -2040,7 +2071,11 @@ pub async fn photo_download(
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| format!("iCloud did not send the file: {e}"))?;
- let mut out = tokio::fs::File::create(&part)
+ // A file of its own, never one already there (nor a link left in its place).
+ let mut out = tokio::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&part)
.await
.map_err(|e| e.to_string())?;
let mut body = response.bytes_stream();
@@ -2061,6 +2096,7 @@ pub async fn photo_download(
tokio::fs::rename(&part, &path)
.await
.map_err(|e| e.to_string())?;
+ crate::saving::mark_from_internet(&path);
Ok(path.display().to_string())
}
@@ -2723,6 +2759,29 @@ async fn refresh_photos(app: &AppHandle) {
mod tests {
use super::*;
+ /// A record id becomes one name in the cache's folder, whatever it holds.
+ #[test]
+ fn a_record_id_is_one_name_in_its_folder() {
+ assert_eq!(cache_name("AbC-12_x"), "AbC-12_x");
+ let dir = std::path::Path::new("/data/photos/original");
+ for id in [
+ "../../cookies.json",
+ "..",
+ "a/b",
+ "a\\b",
+ "C:x",
+ "",
+ "x\0y",
+ "AW+/=",
+ ] {
+ let name = cache_name(id);
+ assert!(name.starts_with('~'), "{id:?}");
+ assert!(name[1..].chars().all(|c| c.is_ascii_hexdigit()), "{id:?}");
+ assert_eq!(dir.join(&*name).parent(), Some(dir), "{id:?}");
+ }
+ assert_ne!(cache_name("a/b"), cache_name("a\\b"));
+ }
+
#[test]
fn ranges_as_a_player_asks_for_them() {
let len = 10 * 1024 * 1024;
diff --git a/src-tauri/src/saving.rs b/src-tauri/src/saving.rs
new file mode 100644
index 0000000..cbc1da2
--- /dev/null
+++ b/src-tauri/src/saving.rs
@@ -0,0 +1,146 @@
+//! Files from iCloud saved where the person keeps their own: Downloads, or a folder they chose.
+//! A name is whoever shared the file's to choose — a shared folder, a shared album — so it is
+//! made one plain file name before it touches a path, the path is checked to be in that folder
+//! before anything is written, and on Windows the file is marked as come from the internet, so
+//! SmartScreen and Office's Protected View still look at it.
+
+use std::path::{Component, Path, PathBuf};
+
+/// Where `given` is saved in `dir`: a plain name (see [`crate::attachment_name`]), `fallback`
+/// when nothing is left of it, with a number on the end rather than over a file already there.
+/// Refused — never a path elsewhere — when the result would not sit directly in `dir`.
+pub(crate) fn save_path(dir: &Path, given: &str, fallback: &str) -> Result<PathBuf, String> {
+ let name = crate::export::file_name(given, fallback);
+ let path = crate::free_path(dir, &name);
+ if !directly_in(dir, &path) {
+ return Err("That file's name can't be saved here.".into());
+ }
+ Ok(path)
+}
+
+/// Whether `path` is one plain name directly inside `dir`: no folder on the way, no `..`, no
+/// drive or root that would set `dir` aside, no stream (`name:stream`) on Windows.
+pub(crate) fn directly_in(dir: &Path, path: &Path) -> bool {
+ let Ok(rest) = path.strip_prefix(dir) else {
+ return false;
+ };
+ let mut parts = rest.components();
+ let (Some(Component::Normal(name)), None) = (parts.next(), parts.next()) else {
+ return false;
+ };
+ let name = name.to_string_lossy();
+ !name.contains(['/', '\\', ':']) && name != "." && name != ".."
+}
+
+/// The stream Windows reads to know a file came from the internet: zone 3, as a browser writes.
+// Read only where Windows writes it (and in tests).
+#[cfg_attr(not(windows), allow(dead_code))]
+pub(crate) const ZONE_IDENTIFIER: &str = "[ZoneTransfer]\r\nZoneId=3\r\nHostUrl=about:internet\r\n";
+
+/// Mark a file saved from iCloud as come from the internet (Mark of the Web). Without it a
+/// document from a stranger's shared folder opened straight into Office with its macros, and
+/// a program ran without SmartScreen asking. Nothing to do elsewhere: no other system reads it.
+/// Best effort — a drive that keeps no streams (FAT, a network share) simply has none.
+pub(crate) fn mark_from_internet(path: &Path) {
+ #[cfg(windows)]
+ {
+ let mut stream = path.as_os_str().to_owned();
+ stream.push(":Zone.Identifier");
+ let _ = std::fs::write(PathBuf::from(stream), ZONE_IDENTIFIER);
+ }
+ #[cfg(not(windows))]
+ let _ = path;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A shared file's name is saved as a name in Downloads, whatever its sender called it.
+ #[test]
+ fn a_shared_name_stays_in_its_folder() {
+ let dir = std::env::temp_dir().join(format!("skykeep-save-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ for (given, want) in [
+ ("Report.pdf", "Report.pdf"),
+ (
+ "..\\..\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\update.bat",
+ "AppDataRoamingMicrosoftWindowsStart MenuProgramsStartupupdate.bat",
+ ),
+ ("../../.config/autostart/x.desktop", "configautostartx.desktop"),
+ ("/etc/passwd", "etcpasswd"),
+ ("C:\\Windows\\evil.dll", "CWindowsevil.dll"),
+ ("C:evil.txt", "Cevil.txt"),
+ ("report.pdf:evil.exe", "report.pdfevil.exe"),
+ ("CON", "_CON"),
+ ("nul.txt", "_nul.txt"),
+ ("COM1.pdf", "_COM1.pdf"),
+ ("LPT9", "_LPT9"),
+ ("CONIN$", "_CONIN$"),
+ ("conout$.log", "_conout$.log"),
+ ("COM\u{b9}.txt", "_COM\u{b9}.txt"),
+ ("CON .txt", "_CON .txt"),
+ ("trailing. . ", "trailing"),
+ ("..", "Download"),
+ ("", "Download"),
+ ("\u{202E}fdp.exe", "fdp.exe"),
+ ] {
+ let at = save_path(&dir, given, "Download").unwrap();
+ assert_eq!(at.parent(), Some(dir.as_path()), "{given:?}");
+ assert_eq!(at.file_name().unwrap().to_string_lossy(), want, "{given:?}");
+ assert!(directly_in(&dir, &at), "{given:?}");
+ }
+ // A long name cut to length never ends in a dot or a space Windows would drop.
+ let at = save_path(&dir, &format!("{}. x", "a".repeat(119)), "Download").unwrap();
+ let name = at.file_name().unwrap().to_string_lossy().into_owned();
+ assert!(!name.ends_with(['.', ' ']), "{name:?}");
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn only_a_plain_name_directly_inside_counts() {
+ let dir = Path::new("/home/someone/Downloads");
+ assert!(directly_in(dir, &dir.join("a.pdf")));
+ assert!(!directly_in(dir, &dir.join("sub/a.pdf")));
+ assert!(!directly_in(dir, &dir.join("../a.pdf")));
+ assert!(!directly_in(dir, Path::new("/etc/a.pdf")));
+ assert!(!directly_in(dir, dir));
+ assert!(!directly_in(dir, &dir.join("a.pdf:stream")));
+ assert!(!directly_in(dir, &dir.join("a\\b.pdf")));
+ }
+
+ /// A file already there, or a link left in its place, is never written through.
+ #[cfg(unix)]
+ #[test]
+ fn a_link_in_the_way_is_never_followed() {
+ let dir = std::env::temp_dir().join(format!("skykeep-link-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ std::os::unix::fs::symlink("/nonexistent/target", dir.join("a.pdf")).unwrap();
+ let at = save_path(&dir, "a.pdf", "Download").unwrap();
+ assert_eq!(at, dir.join("a 1.pdf"));
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn the_mark_says_internet_zone() {
+ assert!(ZONE_IDENTIFIER.starts_with("[ZoneTransfer]\r\n"));
+ assert!(ZONE_IDENTIFIER.contains("ZoneId=3\r\n"));
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn a_saved_file_carries_the_mark_on_windows() {
+ let dir = std::env::temp_dir().join(format!("skykeep-motw-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("a.docx");
+ std::fs::write(&file, b"PK").unwrap();
+ mark_from_internet(&file);
+ let mut stream = file.as_os_str().to_owned();
+ stream.push(":Zone.Identifier");
+ assert_eq!(
+ std::fs::read_to_string(PathBuf::from(stream)).unwrap(),
+ ZONE_IDENTIFIER
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/src/lib/follow.ts b/src/lib/follow.ts
new file mode 100644
index 0000000..1c44e13
--- /dev/null
+++ b/src/lib/follow.ts
@@ -0,0 +1,41 @@
+import { toast } from "../components/Toast";
+import { OPEN_NOTE_EVENT, REFUSED_LINK, linkedNote, outsideHref } from "./links";
+
+/**
+ * The one way a link is followed, from anywhere in the window. The engine never follows one
+ * itself — every click on a link is taken here first (main.tsx) — so a link's address is
+ * always checked before it goes anywhere:
+ * - a link to another note opens that note, as it does in Notes;
+ * - a web page, an email, a call or a place goes to the app this computer uses for it (as a
+ * navigation, which the window refuses and hands on; main.rs, `links`);
+ * - anything else is not opened, and says so.
+ */
+export function follow(href: string): boolean {
+ const note = linkedNote(href);
+ if (note) {
+ window.dispatchEvent(new CustomEvent<string>(OPEN_NOTE_EVENT, { detail: note }));
+ return true;
+ }
+ const out = outsideHref(href);
+ if (!out) {
+ toast(REFUSED_LINK);
+ return false;
+ }
+ window.location.assign(out);
+ return true;
+}
+
+/**
+ * A click on a link: the engine's own navigation is always prevented, and a plain click (not
+ * one extending a selection) is followed. Taken once — the window's own listener sees every
+ * click first, so a screen's handler that calls this again finds it already done.
+ */
+export function followClick(event: MouseEvent): boolean {
+ const a = (event.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
+ if (!a) return false;
+ if (event.defaultPrevented) return true;
+ event.preventDefault();
+ if (event.button !== 0 || event.shiftKey || event.altKey) return true;
+ follow(a.getAttribute("href") ?? "");
+ return true;
+}
diff --git a/src/lib/links.ts b/src/lib/links.ts
new file mode 100644
index 0000000..6e9284a
--- /dev/null
+++ b/src/lib/links.ts
@@ -0,0 +1,45 @@
+/**
+ * Which links Skykeep opens. Much of what the window shows was written by someone else — a
+ * shared note, a shared list, an invitation, a public calendar — so a link's address is theirs
+ * to choose, and the computer's opener runs whatever an address names: a `file:` link on a
+ * share, a `search-ms:` query, a `.desktop` file. Only the kinds a person means by "a link" go
+ * out: a web page, an email, a call, a place on a map. Anything else stays text.
+ *
+ * The same list is kept in Rust, where the window's navigation is refused (main.rs, `links`),
+ * so a link that slips past this still goes nowhere.
+ */
+
+/** The kinds of address handed to the computer: everything else is refused. */
+export const OUTSIDE_SCHEMES = ["http:", "https:", "mailto:", "tel:", "geo:"] as const;
+
+/** What a refused link says, once, when clicked. */
+export const REFUSED_LINK = "This kind of link can't be opened from Skykeep.";
+
+/** A link to another note asked to be followed: the Notes screen (NotesView) opens it. */
+export const OPEN_NOTE_EVENT = "quince:open-note";
+
+/** The note an Apple Notes link points at, as the library names it: `applenotes:note/<id>?…`
+ * carries the note's record name, lower-cased (measured on his "Link feature of notes"). */
+export function linkedNote(href: string): string | null {
+ const m = /^applenotes:(?:\/\/)?note\/([0-9a-f-]{36})/i.exec(href);
+ return m ? m[1].toUpperCase() : null;
+}
+
+/**
+ * The address to hand to the computer for a link, or null when it is not one Skykeep opens.
+ * Read as the engine reads it (WHATWG URL), so tabs, newlines, case and leading spaces cannot
+ * dress one scheme up as another.
+ */
+export function outsideHref(href: string | null | undefined): string | null {
+ if (!href) return null;
+ let url: URL;
+ try {
+ url = new URL(href.trim());
+ } catch {
+ return null;
+ }
+ if (!(OUTSIDE_SCHEMES as readonly string[]).includes(url.protocol)) return null;
+ // A web address names a host; `http:foo` or `https:///x` is not one.
+ if ((url.protocol === "http:" || url.protocol === "https:") && !url.hostname) return null;
+ return url.href;
+}
diff --git a/src/main.tsx b/src/main.tsx
index c137ac8..115843e 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -13,6 +13,7 @@ import "./styles/a11y.css";
import { applyTheme, followContrast, storedTheme } from "./lib/theme";
import { keepTinted } from "./lib/tint";
import { fadeSheetsIn } from "./lib/fade";
+import { followClick } from "./lib/follow";
// Before the first paint, so the window opens in the appearance chosen.
applyTheme(storedTheme());
@@ -21,17 +22,16 @@ keepTinted();
fadeSheetsIn();
/*
- * Every link goes the one way out: as a navigation, which the window refuses and hands to
- * the app this computer uses for it (see the "links" plugin in main.rs). A link meant for a
- * new window would otherwise slip past that — WebKitGTK asks for a window instead — so it
- * is followed in place, where the refusal catches it.
+ * Every link goes the one way out: through `followClick` (lib/follow.ts), which checks what
+ * kind of address it is before anything happens — the engine never follows a link by itself.
+ * A permitted one leaves as a navigation, which the window refuses and hands to the app this
+ * computer uses for it (see the "links" plugin in main.rs). Capturing, so a link whose own
+ * handler stops the click from spreading is covered too; a middle click, which would ask for
+ * a new window, is refused the same way.
*/
-document.addEventListener("click", (e) => {
- const a = (e.target as HTMLElement | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
- if (!a || e.defaultPrevented || a.target !== "_blank") return;
- e.preventDefault();
- window.location.assign(a.href);
- // Capturing, so a link whose own handler stops the click from spreading is covered too.
+document.addEventListener("click", (e) => void followClick(e), true);
+document.addEventListener("auxclick", (e) => {
+ if ((e.target as Element | null)?.closest?.("a[href]")) e.preventDefault();
}, true);
/*
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index b43616e..eafed3a 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -30,6 +30,7 @@ import { RowMenu, type MenuEntry } from "../components/RowMenu";
import { pickOpen } from "../lib/pick";
import { useReveal } from "../lib/reveal";
import { FIRST_LABEL, OFFERED, labelText, offeredMatch, profileHref } from "../lib/contactLabels";
+import { REFUSED_LINK, outsideHref } from "../lib/links";
import { DateField, dateWords } from "./contacts/DateField";
import { PhotoSheet } from "./contacts/PhotoSheet";
import { DuplicatesBanner, DuplicatesView } from "./contacts/Duplicates";
@@ -1526,7 +1527,7 @@ export function ContactsView() {
) : m.kind === "phone" ? (
<a href={`tel:${m.value.replace(/[^\d+#*,;]/g, "")}`}>{m.value}</a>
) : m.kind === "url" ? (
- <a href={webHref(m.value)}>{m.value}</a>
+ webHref(m.value) ? <a href={webHref(m.value)!}>{m.value}</a> : <span title={REFUSED_LINK}>{m.value}</span>
) : m.kind === "date" ? (
dateWords(m.value)
) : m.kind === "profile" && profileHref(m.label, m.value) ? (
@@ -1693,8 +1694,12 @@ async function copyText(text: string): Promise<boolean> {
}
}
-/** A link a person typed without its scheme still opens: "example.com" is the web. */
-const webHref = (value: string) => (/^[a-z][a-z0-9+.-]*:/i.test(value.trim()) ? value.trim() : `https://${value.trim()}`);
+/** A link a person typed without its scheme still opens: "example.com" is the web. One of a
+ * kind Skykeep does not open (lib/links.ts) is no link: null, and it shows as its text. */
+const webHref = (value: string) => {
+ const href = /^[a-z][a-z0-9+.-]*:/i.test(value.trim()) ? value.trim() : `https://${value.trim()}`;
+ return outsideHref(href) ? href : null;
+};
/** A row in the lists column: All Contacts, or one list, with its count and ⋯. */
function ListRow({
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index 1a2db87..2e9bef1 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -1,4 +1,5 @@
import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { REFUSED_LINK, outsideHref } from "../lib/links";
import { fadeIn, fadeOut } from "../lib/fade";
import { overlayOpen, useActiveRef } from "../lib/screen";
import { useModalFocus } from "../lib/focus";
@@ -2385,8 +2386,8 @@ const ReminderRow = memo(function ReminderRow({
{chips.messaging}
</span>
)}
- {chips.url && (
- <a className="rx-chip rx-chip-link" href={chips.url} target="_blank" rel="noreferrer" tabIndex={-1} title={chips.url}>
+ {chips.url && outsideHref(chips.url) && (
+ <a className="rx-chip rx-chip-link" href={outsideHref(chips.url)!} target="_blank" rel="noreferrer" tabIndex={-1} title={chips.url}>
<Link2 aria-hidden="true" size={12} strokeWidth={2.2} />
{hostOf(chips.url)}
</a>
@@ -2699,12 +2700,18 @@ function DueField({ reminder, onChange }: { reminder: Reminder; onChange: (day:
function UrlField({ reminder, url, onSave }: { reminder: Reminder; url: string | null; onSave: (url: string | null) => void }) {
if (!REMINDER_DETAIL_WRITES) {
if (!url) return null;
+ // A link of a kind Skykeep does not open (lib/links.ts) is shown, never followed.
+ const out = outsideHref(url);
return (
<div className="rx-field">
<span>URL</span>
- <a className="rx-url" href={url} target="_blank" rel="noreferrer" title={url}>
- {url.replace(/^https?:\/\//, "").replace(/\/$/, "")}
- </a>
+ {out ? (
+ <a className="rx-url" href={out} target="_blank" rel="noreferrer" title={url}>
+ {url.replace(/^https?:\/\//, "").replace(/\/$/, "")}
+ </a>
+ ) : (
+ <span className="rx-url" title={REFUSED_LINK}>{url}</span>
+ )}
</div>
);
}
@@ -2730,8 +2737,8 @@ function UrlField({ reminder, url, onSave }: { reminder: Reminder; url: string |
}
}}
/>
- {url && /^(https?:|mailto:)/i.test(url) && (
- <a className="rx-url rx-url-open" href={url} target="_blank" rel="noreferrer" title={url}>
+ {url && /^(https?:|mailto:)/i.test(url) && outsideHref(url) && (
+ <a className="rx-url rx-url-open" href={outsideHref(url)!} target="_blank" rel="noreferrer" title={url}>
Open
</a>
)}
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 04bc7de..08568cf 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -1,4 +1,6 @@
import { toast, dismissToast, useErrorToast } from "../../components/Toast";
+import { REFUSED_LINK, outsideHref } from "../../lib/links";
+import { follow } from "../../lib/follow";
import { ConfirmSheet, useConfirm } from "../../components/Confirm";
import { EmptyState } from "../../components/EmptyState";
import { SearchField } from "../../components/SearchField";
@@ -1657,7 +1659,7 @@ export function CalendarView() {
run: () => { if (c.guid !== e.calendarGuid) void save({ ...draftOf(e), calendarGuid: c.guid }); },
})),
}] : []),
- ...(e.location ? [{ label: "Open in Maps", run: () => { window.location.href = mapsHref(e.location ?? ""); } }] : []),
+ ...(e.location ? [{ label: "Open in Maps", run: () => void follow(mapsHref(e.location ?? "")) }] : []),
...(mine ? [null, { label: "Delete", danger: true, run: () => void deleteAsking(e) }] : []),
]}
/>
@@ -3147,9 +3149,13 @@ function EventPopover({
)}
<p className="cx-info-line">{when}</p>
<p className="cx-info-cal"><span className="cx-info-dot" aria-hidden="true" />{calendar?.title}</p>
- {draft.url && (
- <a className="cx-info-url" href={draft.url} target="_blank" rel="noreferrer">{draft.url}</a>
- )}
+ {/* An invitation's link is the sender's to choose: only a kind Skykeep opens is a link
+ (lib/links.ts); any other is its text. */}
+ {draft.url && (outsideHref(draft.url) ? (
+ <a className="cx-info-url" href={outsideHref(draft.url)!} target="_blank" rel="noreferrer">{draft.url}</a>
+ ) : (
+ <p className="cx-info-url" title={REFUSED_LINK}>{draft.url}</p>
+ ))}
<Guests guid={draft.guid} />
{draft.notes && <p className="cx-info-notes">{draft.notes}</p>}
</form>
@@ -3323,8 +3329,8 @@ function EventPopover({
readOnly={!editable}
onChange={(e) => set({ url: e.target.value || null })}
/>
- {draft.url && /^(https?:\/\/|mailto:)/i.test(draft.url.trim()) && (
- <a className="cx-pop-link is-text" href={draft.url.trim()} target="_blank" rel="noreferrer">Open</a>
+ {draft.url && /^(https?:\/\/|mailto:)/i.test(draft.url.trim()) && outsideHref(draft.url) && (
+ <a className="cx-pop-link is-text" href={outsideHref(draft.url)!} target="_blank" rel="noreferrer">Open</a>
)}
</span>
<Guests guid={draft.guid} />
diff --git a/src/screens/notes/Formatted.tsx b/src/screens/notes/Formatted.tsx
index 8333220..6b8aa9a 100644
--- a/src/screens/notes/Formatted.tsx
+++ b/src/screens/notes/Formatted.tsx
@@ -11,6 +11,7 @@
import { useEffect, useRef } from "react";
import { describe, drawMedia } from "./NoteEditor";
import { addressesIn, openLinkAt } from "./links";
+import { REFUSED_LINK, linkedNote, outsideHref } from "../../lib/links";
export type Run = {
length: number;
style: number | null;
@@ -154,12 +155,16 @@ function Inline({ span }: { span: Span }) {
if (run.underline) node = <u>{node}</u>;
if (run.strike) node = <s>{node}</s>;
if (run.emphasis) node = <span className={`nf-em-${run.emphasis}`}>{node}</span>;
- if (run.link) {
+ if (run.link && (outsideHref(run.link) || linkedNote(run.link))) {
node = (
<a href={run.link} rel="noreferrer" onClick={(e) => { e.stopPropagation(); openLinkAt(e.nativeEvent); }}>
{node}
</a>
);
+ } else if (run.link) {
+ // A link to something Skykeep does not open (a file on a share, a program's own scheme)
+ // is its text, saying why it is not a link.
+ node = <span className="nf-link-refused" title={REFUSED_LINK}>{node}</span>;
}
return <>{node}</>;
}
diff --git a/src/screens/notes/links.ts b/src/screens/notes/links.ts
index 91b83ce..c0d6fd6 100644
--- a/src/screens/notes/links.ts
+++ b/src/screens/notes/links.ts
@@ -6,6 +6,7 @@
import { Plugin } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
import type { Node as PMNode } from "prosemirror-model";
+import { followClick } from "../../lib/follow";
/** An address: with its scheme, or starting www. — ending before closing punctuation, as a
* sentence's full stop or a bracket is not part of it. */
@@ -50,31 +51,10 @@ export const autolink = new Plugin<DecorationSet>({
},
});
-/** A click on a link (its own, or one found) opens it, as a click does in Notes on the Mac.
- * Navigating is enough: the app hands any address outside it to this computer's browser. */
-/** A link to another note asked to be followed: the Notes screen (NotesView) opens it. */
-export const OPEN_NOTE_EVENT = "quince:open-note";
-
-/** The note an Apple Notes link points at, as the library names it: `applenotes:note/<id>?…`
- * carries the note's record name, lower-cased (measured on his "Link feature of notes"). */
-export function linkedNote(href: string): string | null {
- const m = /^applenotes:(?:\/\/)?note\/([0-9a-f-]{36})/i.exec(href);
- return m ? m[1].toUpperCase() : null;
-}
+/** A click on a link (its own, or one found) opens it, as a click does in Notes on the Mac —
+ * through the window's one checked way out (lib/follow.ts). */
+export { OPEN_NOTE_EVENT, linkedNote } from "../../lib/links";
export function openLinkAt(event: MouseEvent): boolean {
- const a = (event.target as HTMLElement | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
- if (!a || event.button !== 0 || event.shiftKey || event.altKey) return false;
- const href = a.getAttribute("href") ?? "";
- // A link to another note opens that note here, as it does in Notes.
- const note = linkedNote(href);
- if (note) {
- event.preventDefault();
- window.dispatchEvent(new CustomEvent<string>(OPEN_NOTE_EVENT, { detail: note }));
- return true;
- }
- if (!/^(https?:|mailto:|tel:)/i.test(href)) return false;
- event.preventDefault();
- window.location.assign(href);
- return true;
+ return followClick(event);
}
diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.ts
index 894395a..7877d5f 100644
--- a/src/screens/notes/rich.ts
+++ b/src/screens/notes/rich.ts
@@ -13,6 +13,7 @@
*/
import { Schema, type DOMOutputSpec, type Node as PMNode, type Mark } from "prosemirror-model";
import type { Run } from "./Formatted";
+import { REFUSED_LINK, linkedNote, outsideHref } from "../../lib/links.ts";
/** Apple's paragraph styles. */
export const STYLE = {
@@ -131,7 +132,12 @@ export const schema = new Schema({
parseDOM: [{ tag: "a[href]", getAttrs: (d) => ({ href: (d as HTMLElement).getAttribute("href") }) }],
// No target: a click is the editor's to follow (notes/links), never a new window — one
// opened by WebKitGTK for a link to a note went to the browser.
- toDOM: (m) => ["a", { href: m.attrs.href, rel: "noreferrer" }, 0],
+ // A link Skykeep will not open keeps its address (the note is left as Apple has it), but
+ // says so where it stands; a click on it is refused (lib/follow.ts).
+ toDOM: (m) =>
+ outsideHref(m.attrs.href) || linkedNote(m.attrs.href)
+ ? ["a", { href: m.attrs.href, rel: "noreferrer" }, 0]
+ : ["a", { href: m.attrs.href, rel: "noreferrer", class: "nf-link-refused", title: REFUSED_LINK }, 0],
},
},
});
diff --git a/src/styles/notes.css b/src/styles/notes.css
index 00740a8..a777fda 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -418,6 +418,8 @@ textarea.note-title::placeholder { color: var(--text-3); }
/* Web addresses found in a note: links, as Notes draws them. */
.nf-autolink, .ProseMirror a[href] { color: var(--accent); text-decoration: underline; text-decoration-thickness: from-font; text-underline-offset: 2px; cursor: pointer; }
+/* A link Skykeep will not open (lib/links.ts): its words, as plain text, with why on hover. */
+.ProseMirror a.nf-link-refused, .nf-link-refused { color: inherit; text-decoration: none; cursor: default; }
/* A note's picture shown large, over the dimmed window. */
.nf-picture-veil { display: grid; place-items: center; padding: 32px; }