Merge remote-tracking branch 'origin/main' into pr-server-only
* origin/main: (675 commits) fix(web): tolerate servers that predate git identity in project import (#10547) chore(mobile): bump app version to 1.1.0 fix(mobile): wait for native thread scroll before reveal (#10486) fix(mobile): match Working status color to desktop fix(web): remove inserted citations on cancel (#10518) feat(web): group onboarding project import by repository (#10493) fix(mobile): preserve chat rows when toggling commands (#10492) fix(mobile): restore assistant message bottom padding (#10491) fix(mobile): animate thread lifecycle transitions consistently (#10487) fix(mobile): release initial scroll target after dragging (#10483) fix(mobile): smooth composer status pill resizing (#10484) fix(mobile): prevent chat from disappearing when scrolling (#10479) fix(web): resize the floating preview from any edge (#10467) fix(web): keep composer toolbar controls anchored during transitions (#10478) fix(mobile): improve font-size slider performance and prevent maximum update depth errors (#7138) feat(mobile): start a new thread on an existing branch (#10359) fix(ios): scroll short source files from blank space (#10178) fix(mobile): hide changed-files navigator and restore refresh in raw diff fallback (#9828) fix(projects): prevent invalid script IDs from crashing threads (#10019) fix(devcontainer): make repository setup work (#7875) ... # Conflicts: # apps/server/src/provider/builtInDrivers.ts # docs/README.md # docs/user/install.md # packages/contracts/src/settings.test.ts # packages/contracts/src/settings.ts
This commit is contained in:
1802 files changed
+186443
-43978
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
reviews:
|
||||
review_status: false
|
||||
auto_review:
|
||||
enabled: false
|
||||
enabled: true
|
||||
@@ -1,29 +1,73 @@
|
||||
// Dev container for T3 Code. Mirrors CI (ubuntu-24.04, Node 24, Rust stable)
|
||||
// and the canonical setup in docs/operations/development.md: global `vp`, `vp i`.
|
||||
// Contributor doc: docs/internals/devcontainer.md
|
||||
{
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"name": "T3 Code",
|
||||
"image": "mcr.microsoft.com/devcontainers/base:ubuntu-24.04",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
// nodeGypDependencies (default true) brings python3/make/g++, which Linux
|
||||
// needs for node-pty's node-gyp fallback (its prebuilds are mac/win only).
|
||||
"ghcr.io/devcontainers/features/node:2": {
|
||||
"version": "24"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24.13.1"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
}
|
||||
// native/resource-monitor (edition 2024, needs stable >= 1.85). The server
|
||||
// degrades gracefully without the binary, but CI checks cargo fmt + test.
|
||||
"ghcr.io/devcontainers/features/rust:1": {},
|
||||
"ghcr.io/devcontainers/features/github-cli:1": {}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
"hostRequirements": {
|
||||
"cpus": 4,
|
||||
"memory": "8gb",
|
||||
"storage": "32gb"
|
||||
},
|
||||
"containerEnv": {
|
||||
// Keep all runtime state inside the (gitignored) workspace .t3, matching
|
||||
// the worktree default. An explicit --home-dir still wins.
|
||||
"T3CODE_HOME": "${containerWorkspaceFolder}/.t3"
|
||||
},
|
||||
"mounts": [
|
||||
// vp keeps the pnpm content-addressable store and metadata cache under
|
||||
// ~/.cache/pnpm (verified: the v11 store dir lives there); mounting a
|
||||
// volume there lets installs survive container rebuilds.
|
||||
"source=t3code-pnpm-store,target=/home/vscode/.cache/pnpm,type=volume",
|
||||
// Root node_modules holds the whole pnpm virtual store (.pnpm), so one
|
||||
// volume keeps the heavy tree off the slow macOS/Windows bind mount.
|
||||
// Scoped by devcontainerId so parallel checkouts do not share it.
|
||||
// Codespaces note: prebuild snapshots exclude volumes; drop these mounts
|
||||
// if prebuilt codespaces become the primary workflow.
|
||||
"source=t3code-node-modules-${devcontainerId},target=${containerWorkspaceFolder}/node_modules,type=volume"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
"onCreateCommand": "bash .devcontainer/on-create.sh",
|
||||
"updateContentCommand": "bash .devcontainer/update-content.sh",
|
||||
"forwardPorts": [5733, 13773],
|
||||
"portsAttributes": {
|
||||
"5733": {
|
||||
"label": "t3 web (open via the pairing URL, not the bare origin)",
|
||||
"onAutoForward": "notify"
|
||||
},
|
||||
"13773": {
|
||||
"label": "t3 server",
|
||||
"onAutoForward": "silent"
|
||||
}
|
||||
},
|
||||
"customizations": {
|
||||
"codespaces": {
|
||||
"openFiles": ["docs/internals/devcontainer.md"]
|
||||
},
|
||||
"vscode": {
|
||||
"extensions": ["oxc.oxc-vscode"]
|
||||
"extensions": ["oxc.oxc-vscode", "rust-lang.rust-analyzer"],
|
||||
"settings": {
|
||||
// .repos is a large vendored read-only reference tree; watching it
|
||||
// burns CPU and file handles.
|
||||
"files.watcherExclude": {
|
||||
"**/.repos/**": true,
|
||||
"**/.t3/**": true
|
||||
},
|
||||
"search.exclude": {
|
||||
"**/.repos": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"remoteUser": "vscode"
|
||||
}
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-time container setup, baked into prebuilds. Content-dependent work
|
||||
# (dependency install, Chromium) lives in update-content.sh.
|
||||
set -euo pipefail
|
||||
|
||||
# The Vite+ CLI is the repo task runner (vp i, vp run dev, vp test run).
|
||||
# Download to a file first: a curl failure inside $( ) would yield an empty
|
||||
# script and a false success. VP_NODE_MANAGER=no skips the installer's node
|
||||
# shims; Node comes from the devcontainer feature. The VP_*_DIR group (set
|
||||
# together, absolute) pins the install location instead of the installer's
|
||||
# XDG platform defaults, which moved the binary from ~/.vite-plus/bin to
|
||||
# ~/.local/share/vite-plus/bin between releases and would break the check
|
||||
# below either way.
|
||||
export VP_BIN_DIR="$HOME/.local/share/vite-plus/bin"
|
||||
export VP_DATA_DIR="$HOME/.local/share/vite-plus"
|
||||
export VP_CACHE_DIR="$HOME/.cache/vite-plus"
|
||||
installer=$(mktemp)
|
||||
curl -fsSL https://vite.plus -o "$installer"
|
||||
VP_NODE_MANAGER=no bash "$installer"
|
||||
rm -f "$installer"
|
||||
|
||||
# Non-login lifecycle shells never source the profile the installer edits,
|
||||
# so expose vp on the default PATH. test -x keeps a bad install loud.
|
||||
test -x "$VP_BIN_DIR/vp"
|
||||
sudo ln -sf "$VP_BIN_DIR/vp" /usr/local/bin/vp
|
||||
|
||||
# First-run terminal notice, rendered by the devcontainers base image.
|
||||
sudo mkdir -p /usr/local/etc/vscode-dev-containers
|
||||
sudo tee /usr/local/etc/vscode-dev-containers/first-run-notice.txt >/dev/null <<'EOF'
|
||||
T3 Code devcontainer
|
||||
|
||||
vp run dev start server + web, then open the pairing URL it
|
||||
prints (the bare forwarded port will not authenticate)
|
||||
cp .env.example .env optional: enable T3 Connect cloud features
|
||||
(public identifiers, not secrets)
|
||||
|
||||
Details: docs/internals/devcontainer.md
|
||||
EOF
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs at creation and on every prebuild content refresh, so codespaces start
|
||||
# with deps installed and caches warm. Everything here is idempotent.
|
||||
set -euo pipefail
|
||||
|
||||
# Volume mounts (pnpm store, node_modules) and the directories docker creates
|
||||
# for them arrive root-owned; hand them to the dev user before installing.
|
||||
for dir in "$HOME/.cache" "$HOME/.cache/pnpm" node_modules; do
|
||||
if [ -d "$dir" ] && [ "$(stat -c %U "$dir")" != "$(id -un)" ]; then
|
||||
sudo chown "$(id -un):$(id -gn)" "$dir"
|
||||
fi
|
||||
done
|
||||
|
||||
CI=true vp i
|
||||
# Repairs electron's path.txt and exec bits after install, same as CI.
|
||||
vp run --filter @t3tools/desktop ensure:electron
|
||||
# Pre-warms Vite's dep optimizer (cache is keyed on the absolute path, which
|
||||
# is stable inside the container).
|
||||
node apps/web/scripts/warm-dep-cache.ts
|
||||
@@ -1,2 +1,5 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
# Batch files need CRLF for cmd.exe to parse them reliably.
|
||||
*.cmd text eol=crlf
|
||||
*.bat text eol=crlf
|
||||
@@ -0,0 +1,8 @@
|
||||
# Security policy
|
||||
|
||||
Report security vulnerabilities affecting T3 Code or T3 Tools-operated infrastructure to
|
||||
[[email protected]](mailto:[email protected]). Please do not disclose them publicly until we have had
|
||||
a reasonable opportunity to investigate and remediate them.
|
||||
|
||||
See the [full security policy](https://t3.codes/security-policy) for reporting details, scope,
|
||||
and safe harbor terms for good-faith research.
|
||||
@@ -12,22 +12,28 @@
|
||||
github:0x4bs3nt
|
||||
github:Adamulek123
|
||||
github:adityavardhansharma
|
||||
github:aoright
|
||||
github:arhxam
|
||||
github:bil0000
|
||||
github:binbandit
|
||||
github:Brechard
|
||||
github:btsouth
|
||||
github:chrisdeeming
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:D3OXY
|
||||
github:dbalders
|
||||
github:eggfriedrice24
|
||||
github:extoci
|
||||
github:flamboh
|
||||
github:FllipEis
|
||||
github:gbarros-dev
|
||||
github:gfsaaser24
|
||||
github:github-actions[bot]
|
||||
github:gsimone
|
||||
github:GuilhermeVieiraDev
|
||||
github:hwanseoc
|
||||
github:inayayousfi
|
||||
github:ipanasenko
|
||||
github:jakeleventhal
|
||||
github:jamesx0416
|
||||
@@ -36,13 +42,18 @@ github:jasonLaster
|
||||
github:JoeEverest
|
||||
github:justsomelegs
|
||||
github:kridaydave
|
||||
github:lgwacker
|
||||
github:lnieuwenhuis
|
||||
github:Lucenx9
|
||||
github:mackinleysmith
|
||||
github:maria-rcks
|
||||
github:MatthewFeroz
|
||||
github:maxwellyoung
|
||||
github:mwolson
|
||||
github:myacoub91
|
||||
github:naMqe-h
|
||||
github:nateEc
|
||||
github:naveed949
|
||||
github:nmggithub
|
||||
github:Noojuno
|
||||
github:notkainoa
|
||||
@@ -64,6 +75,7 @@ github:tarik02
|
||||
github:tris203
|
||||
github:tsouth89
|
||||
github:UtkarshUsername
|
||||
github:vitalyiegorov
|
||||
github:Yash-Singh1
|
||||
github:yashranaway
|
||||
github:Ymit24
|
||||
@@ -0,0 +1,22 @@
|
||||
name: Setup APT mirrors
|
||||
description: Configure Ubuntu package downloads with automatic mirror failover.
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- shell: bash
|
||||
run: |
|
||||
# Replace the existing Blacksmith mirror list as well as direct sources.
|
||||
printf '%s\tpriority:%s\n' \
|
||||
https://archive.ubuntu.com/ubuntu 1 \
|
||||
https://mirrors.edge.kernel.org/ubuntu 2 \
|
||||
https://mirror.math.princeton.edu/pub/ubuntu 3 \
|
||||
| sudo tee /etc/apt/blacksmith-ubuntu-mirrors.txt > /dev/null
|
||||
|
||||
# APT's mirror transport retries each file against the next server.
|
||||
sudo find /etc/apt -maxdepth 2 -type f \( -name '*.list' -o -name '*.sources' \) \
|
||||
-exec sed -i -E \
|
||||
's#https?://(([^/]+\.)?archive|security)\.ubuntu\.com/ubuntu/?#mirror+file:/etc/apt/blacksmith-ubuntu-mirrors.txt#g' {} +
|
||||
|
||||
# Move on to a fallback before an unreachable server exhausts the job.
|
||||
printf '%s\n' 'Acquire::http::Timeout "15";' 'Acquire::https::Timeout "15";' \
|
||||
| sudo tee /etc/apt/apt.conf.d/80-mirror-timeouts > /dev/null
|
||||
@@ -0,0 +1,67 @@
|
||||
const MINIMUM_RELEASE_GAP_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
const isNightlyTag = (tag) => /^v.*-nightly\./.test(tag) || tag.startsWith("nightly-v");
|
||||
|
||||
// Newest published nightly by publication time, or undefined when none exists.
|
||||
async function findLatestNightly({ github, context }) {
|
||||
const releases = await github.paginate(github.rest.repos.listReleases, {
|
||||
...context.repo,
|
||||
per_page: 100,
|
||||
});
|
||||
return releases
|
||||
.filter((release) => !release.draft && release.published_at && isNightlyTag(release.tag_name))
|
||||
.sort((a, b) => Date.parse(b.published_at) - Date.parse(a.published_at))[0];
|
||||
}
|
||||
|
||||
// Runs after the workflow acquires the nightly concurrency lock.
|
||||
async function shouldReleaseNightly({ github, context, core, now = Date.now() }) {
|
||||
const lastNightly = await findLatestNightly({ github, context });
|
||||
|
||||
if (!lastNightly) {
|
||||
core.info("No published nightly found. Proceeding with release.");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (now - Date.parse(lastNightly.published_at) < MINIMUM_RELEASE_GAP_MS) {
|
||||
core.info(`Nightly ${lastNightly.tag_name} was published less than six hours ago. Skipping.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({
|
||||
...context.repo,
|
||||
basehead: `${lastNightly.tag_name}...${context.sha}`,
|
||||
per_page: 1,
|
||||
});
|
||||
if (comparison.status !== "ahead") {
|
||||
core.info(
|
||||
`Candidate commit is ${comparison.status} relative to ${lastNightly.tag_name}. Skipping.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
core.info(`New commits since ${lastNightly.tag_name}, and the six-hour gap has passed.`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stable releases build the commit the latest nightly shipped, so the stable
|
||||
// build is one nightly users already ran. Returns the nightly tag, its commit,
|
||||
// and the stable version that nightly was a preview of.
|
||||
async function resolveLatestNightlyCommit({ github, context, core }) {
|
||||
const lastNightly = await findLatestNightly({ github, context });
|
||||
if (!lastNightly) {
|
||||
throw new Error("No published nightly found. Stable releases build the latest nightly commit.");
|
||||
}
|
||||
|
||||
const tag = lastNightly.tag_name;
|
||||
// repos.getCommit dereferences annotated tags, so this is the commit either way.
|
||||
const { data: commit } = await github.rest.repos.getCommit({ ...context.repo, ref: tag });
|
||||
const version = /^(?:nightly-)?v(\d+\.\d+\.\d+)-nightly\./.exec(tag)?.[1];
|
||||
if (!version) {
|
||||
throw new Error(`Cannot derive a stable version from nightly tag ${tag}.`);
|
||||
}
|
||||
|
||||
core.info(`Latest nightly ${tag} shipped ${commit.sha} as a preview of ${version}.`);
|
||||
return { tag, sha: commit.sha, version };
|
||||
}
|
||||
|
||||
module.exports = { shouldReleaseNightly, resolveLatestNightlyCommit };
|
||||
@@ -0,0 +1,143 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const { shouldReleaseNightly } = require("./check-nightly-release.cjs");
|
||||
|
||||
const now = Date.parse("2026-09-05T12:00:00Z");
|
||||
const hour = 60 * 60 * 1000;
|
||||
const nightly = (hoursAgo, overrides = {}) => ({
|
||||
tag_name: "v1.0.1-nightly.20260905.123",
|
||||
draft: false,
|
||||
published_at: new Date(now - hoursAgo * hour).toISOString(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function fixture({ releases = [nightly(7)], comparisonStatus = "ahead" } = {}) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
options: {
|
||||
now,
|
||||
context: { repo: { owner: "example", repo: "app" }, sha: "new" },
|
||||
core: { info() {} },
|
||||
github: {
|
||||
rest: {
|
||||
repos: {
|
||||
listReleases() {},
|
||||
async compareCommitsWithBasehead(params) {
|
||||
calls.push(params);
|
||||
return { data: { status: comparisonStatus } };
|
||||
},
|
||||
},
|
||||
},
|
||||
async paginate() {
|
||||
return releases;
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("releases the first nightly when no nightly is published", async () => {
|
||||
const { options } = fixture({
|
||||
releases: [nightly(0, { tag_name: "v1.0.0" }), nightly(0, { draft: true })],
|
||||
});
|
||||
assert.equal(await shouldReleaseNightly(options), true);
|
||||
});
|
||||
|
||||
test("waits six hours after publication, including manual nightlies", async () => {
|
||||
for (const age of [0, 3, 6 - 1 / 3600]) {
|
||||
const { options, calls } = fixture({ releases: [nightly(age)] });
|
||||
assert.equal(await shouldReleaseNightly(options), false);
|
||||
assert.equal(calls.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("releases new commits at six hours and after an idle period", async () => {
|
||||
for (const age of [6, 7, 24]) {
|
||||
const { options } = fixture({ releases: [nightly(age)] });
|
||||
assert.equal(await shouldReleaseNightly(options), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("skips unchanged commits after the gap", async () => {
|
||||
const { options } = fixture({ comparisonStatus: "identical" });
|
||||
assert.equal(await shouldReleaseNightly(options), false);
|
||||
});
|
||||
|
||||
test("uses publication time, not release order or the tagged commit date", async () => {
|
||||
const { options } = fixture({
|
||||
releases: [nightly(10), nightly(1), nightly(20, { tag_name: "nightly-v0.9.0" })],
|
||||
});
|
||||
assert.equal(await shouldReleaseNightly(options), false);
|
||||
});
|
||||
|
||||
test("ignores stable releases and drafts when checking the gap", async () => {
|
||||
const { options } = fixture({
|
||||
releases: [nightly(0, { tag_name: "v1.0.0" }), nightly(0, { draft: true }), nightly(7)],
|
||||
});
|
||||
assert.equal(await shouldReleaseNightly(options), true);
|
||||
});
|
||||
|
||||
test("compares against the published tag, including legacy nightly tags", async () => {
|
||||
const tag = "nightly-v0.9.0";
|
||||
const { options, calls } = fixture({ releases: [nightly(7, { tag_name: tag })] });
|
||||
assert.equal(await shouldReleaseNightly(options), true);
|
||||
assert.equal(calls[0].basehead, `${tag}...new`);
|
||||
});
|
||||
|
||||
test("fails instead of releasing when GitHub cannot supply release state", async () => {
|
||||
const { options } = fixture();
|
||||
options.github.paginate = async () => {
|
||||
throw new Error("GitHub unavailable");
|
||||
};
|
||||
await assert.rejects(shouldReleaseNightly(options), /GitHub unavailable/);
|
||||
});
|
||||
|
||||
for (const status of ["behind", "diverged"]) {
|
||||
test(`skips a candidate commit that is ${status} relative to the last nightly`, async () => {
|
||||
const { options } = fixture({ comparisonStatus: status });
|
||||
assert.equal(await shouldReleaseNightly(options), false);
|
||||
});
|
||||
}
|
||||
|
||||
const { resolveLatestNightlyCommit } = require("./check-nightly-release.cjs");
|
||||
|
||||
function nightlyCommitFixture({ releases, commitSha = "abc123" }) {
|
||||
const refs = [];
|
||||
const { options } = fixture({ releases });
|
||||
options.github.rest.repos.getCommit = async ({ ref }) => {
|
||||
refs.push(ref);
|
||||
return { data: { sha: commitSha } };
|
||||
};
|
||||
return { options, refs };
|
||||
}
|
||||
|
||||
test("stable releases resolve the commit of the newest published nightly", async () => {
|
||||
const { options, refs } = nightlyCommitFixture({
|
||||
releases: [
|
||||
nightly(10, { tag_name: "v1.0.1-nightly.20260905.100" }),
|
||||
nightly(1, { tag_name: "v1.0.1-nightly.20260905.123" }),
|
||||
nightly(0, { tag_name: "v1.0.0" }),
|
||||
nightly(0, { draft: true, tag_name: "v1.0.1-nightly.20260905.999" }),
|
||||
],
|
||||
commitSha: "deadbeef",
|
||||
});
|
||||
assert.deepEqual(await resolveLatestNightlyCommit(options), {
|
||||
tag: "v1.0.1-nightly.20260905.123",
|
||||
sha: "deadbeef",
|
||||
version: "1.0.1",
|
||||
});
|
||||
assert.deepEqual(refs, ["v1.0.1-nightly.20260905.123"]);
|
||||
});
|
||||
|
||||
test("stable releases derive the version from legacy nightly tags", async () => {
|
||||
const { options } = nightlyCommitFixture({
|
||||
releases: [nightly(1, { tag_name: "nightly-v0.9.0-nightly.20260905.5" })],
|
||||
});
|
||||
assert.equal((await resolveLatestNightlyCommit(options)).version, "0.9.0");
|
||||
});
|
||||
|
||||
test("stable releases fail without a published nightly", async () => {
|
||||
const { options } = nightlyCommitFixture({ releases: [nightly(0, { tag_name: "v1.0.0" })] });
|
||||
await assert.rejects(resolveLatestNightlyCommit(options), /No published nightly/);
|
||||
});
|
||||
@@ -45,12 +45,23 @@ jobs:
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
# Files/dependencies are repo-wide; export checks cover clean workspaces only.
|
||||
- name: Check unused code
|
||||
run: vp run knip:check
|
||||
|
||||
- name: Check
|
||||
run: vp check
|
||||
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- uses: ./.github/actions/setup-apt-mirrors
|
||||
|
||||
- name: Install browser secret helper build libraries
|
||||
run: |
|
||||
sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
|
||||
sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -85,6 +96,16 @@ jobs:
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- uses: ./.github/actions/setup-apt-mirrors
|
||||
|
||||
- name: Install browser secret helper build libraries
|
||||
run: |
|
||||
sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
|
||||
sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
|
||||
- name: Test nightly release checks
|
||||
run: node --test .github/scripts/check-nightly-release.test.cjs
|
||||
|
||||
- name: Test
|
||||
run: vp run --parallel --concurrency-limit 4 --filter '!t3' --filter '!@t3tools/monorepo' test
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Forward to Cursor hygiene
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, reopened, ready_for_review]
|
||||
issues:
|
||||
types: [opened, closed, reopened]
|
||||
discussion:
|
||||
types: [created, closed, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
forward:
|
||||
name: POST to Cursor
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: POST to Cursor
|
||||
env:
|
||||
URL: ${{ secrets.CURSOR_T3CODE_WEBHOOK_URL }}
|
||||
AUTH: ${{ secrets.CURSOR_T3CODE_WEBHOOK_AUTH }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${URL:-}" ] || [ -z "${AUTH:-}" ]; then
|
||||
echo "Missing CURSOR_T3CODE_WEBHOOK_URL or CURSOR_T3CODE_WEBHOOK_AUTH — skipping."
|
||||
exit 0
|
||||
fi
|
||||
curl -fsS --max-time 60 -X POST "$URL" \
|
||||
-H "Authorization: $AUTH" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-GitHub-Event: ${{ github.event_name }}" \
|
||||
-H "X-GitHub-Delivery: ${{ github.run_id }}-${{ github.run_attempt }}" \
|
||||
--data-binary @"${{ github.event_path }}"
|
||||
+146
-85
@@ -6,8 +6,8 @@ on:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
# Off minute zero: GitHub delays scheduled runs most at the top of the hour.
|
||||
- cron: "38 */3 * * *"
|
||||
# Avoid minute zero, when GitHub scheduled jobs are busiest.
|
||||
- cron: "8,38 * * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
@@ -19,7 +19,7 @@ on:
|
||||
- stable
|
||||
- nightly
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
description: "Stable version override (for example 1.2.3). Defaults to the version the latest nightly previewed."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
@@ -28,7 +28,7 @@ on:
|
||||
# own group so a nightly never blocks them. Running publishers are never
|
||||
# canceled, and queue: max keeps every pending run instead of the default
|
||||
# newest-wins single slot, so a queued stable tag can never be silently
|
||||
# dropped. Queued nightlies with no new commits skip via check_changes.
|
||||
# dropped. Automatic nightlies recheck the release gap after leaving the queue.
|
||||
concurrency:
|
||||
group: release-${{ (github.event_name == 'schedule' || inputs.channel == 'nightly') && 'nightly' || 'stable' }}
|
||||
cancel-in-progress: false
|
||||
@@ -39,49 +39,54 @@ permissions:
|
||||
id-token: none
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
# Picks the commit every later job builds. Nightlies and tag pushes build the
|
||||
# triggering commit. Manual stable releases build the commit of the latest
|
||||
# published nightly, so stable only ever ships a build that nightly users
|
||||
# have already run. Scheduled runs also decide here whether a nightly is due.
|
||||
resolve_commit:
|
||||
name: Resolve release commit
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
ref: ${{ steps.resolve.outputs.ref }}
|
||||
nightly_version: ${{ steps.resolve.outputs.nightly_version }}
|
||||
has_changes: ${{ steps.resolve.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
- id: resolve
|
||||
name: Resolve release commit
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DISPATCH_CHANNEL: ${{ inputs.channel }}
|
||||
with:
|
||||
script: |
|
||||
const {
|
||||
shouldReleaseNightly,
|
||||
resolveLatestNightlyCommit,
|
||||
} = require('./.github/scripts/check-nightly-release.cjs');
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
if (context.eventName === 'schedule') {
|
||||
core.setOutput('has_changes', await shouldReleaseNightly({ github, context, core }));
|
||||
core.setOutput('ref', context.sha);
|
||||
} else if (context.eventName === 'workflow_dispatch' && process.env.DISPATCH_CHANNEL !== 'nightly') {
|
||||
const { tag, sha, version } = await resolveLatestNightlyCommit({ github, context, core });
|
||||
core.notice(`Stable release builds ${sha}, the commit shipped by ${tag}.`);
|
||||
core.setOutput('ref', sha);
|
||||
core.setOutput('nightly_version', version);
|
||||
} else {
|
||||
core.setOutput('ref', context.sha);
|
||||
}
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
needs: [check_changes]
|
||||
needs: [resolve_commit]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
needs.resolve_commit.result == 'success' &&
|
||||
(github.event_name != 'schedule' || needs.resolve_commit.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
@@ -94,11 +99,12 @@ jobs:
|
||||
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ needs.resolve_commit.outputs.ref }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.resolve_commit.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
@@ -111,6 +117,8 @@ jobs:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
env:
|
||||
pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -118,8 +126,9 @@ jobs:
|
||||
env:
|
||||
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
|
||||
DISPATCH_VERSION: ${{ github.event.inputs.version }}
|
||||
NIGHTLY_VERSION: ${{ needs.resolve_commit.outputs.nightly_version }}
|
||||
NIGHTLY_DATE: ${{ github.run_started_at }}
|
||||
NIGHTLY_SHA: ${{ github.sha }}
|
||||
NIGHTLY_SHA: ${{ needs.resolve_commit.outputs.ref }}
|
||||
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
|
||||
@@ -137,9 +146,9 @@ jobs:
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${DISPATCH_VERSION}"
|
||||
raw="${DISPATCH_VERSION:-$NIGHTLY_VERSION}"
|
||||
if [[ -z "$raw" ]]; then
|
||||
echo "workflow_dispatch stable releases require the version input." >&2
|
||||
echo "workflow_dispatch stable releases need a version input or a published nightly." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
@@ -174,6 +183,14 @@ jobs:
|
||||
--current-tag "${{ steps.release_meta.outputs.tag }}" \
|
||||
--github-output
|
||||
|
||||
# Share only the verification results, not the large registry metadata cache.
|
||||
- name: Upload dependency verification
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-dependency-verification
|
||||
path: ${{ runner.temp }}/pnpm-metadata/lockfile-verified.jsonl
|
||||
|
||||
quality:
|
||||
name: Release quality checks
|
||||
needs: [preflight]
|
||||
@@ -206,19 +223,22 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vp run typecheck
|
||||
|
||||
- uses: ./.github/actions/setup-apt-mirrors
|
||||
|
||||
- name: Install browser secret helper build libraries
|
||||
run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
relay_public_config:
|
||||
name: Resolve T3 Connect public config
|
||||
# Consumes only the commit SHA, not preflight's resolved version, so it runs
|
||||
# alongside preflight instead of after it. The condition mirrors preflight's:
|
||||
# check_changes is skipped on non-schedule events (skipped is neither failure
|
||||
# nor success, so success() would be wrong here).
|
||||
needs: [check_changes]
|
||||
# Consumes only the release commit, not preflight's resolved version, so it
|
||||
# runs alongside preflight instead of after it. The condition mirrors preflight's.
|
||||
needs: [resolve_commit]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
needs.resolve_commit.result == 'success' &&
|
||||
(github.event_name != 'schedule' || needs.resolve_commit.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
environment:
|
||||
@@ -240,7 +260,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ needs.resolve_commit.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
@@ -313,19 +333,19 @@ jobs:
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
# Same gating as relay_public_config: only the commit SHA is needed, so this
|
||||
# runs alongside preflight. See the condition comment there.
|
||||
needs: [check_changes]
|
||||
# Same gating as relay_public_config: only the release commit is needed, so
|
||||
# this runs alongside preflight. See the condition comment there.
|
||||
needs: [resolve_commit]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
needs.resolve_commit.result == 'success' &&
|
||||
(github.event_name != 'schedule' || needs.resolve_commit.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ needs.resolve_commit.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
@@ -446,7 +466,18 @@ jobs:
|
||||
path: ${{ steps.package_cache_path.outputs.path }}
|
||||
key: windows-release-packages-v1-${{ matrix.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
# pnpm checks the lockfile and policy before reusing this result. A missing
|
||||
# artifact leaves the cache empty, so installation runs the checks again.
|
||||
- name: Download dependency verification
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: release-dependency-verification
|
||||
path: ${{ runner.temp }}/pnpm-metadata
|
||||
|
||||
- name: Install desktop dependencies
|
||||
env:
|
||||
pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata
|
||||
run: vp install --filter=@t3tools/desktop... --filter=t3... --filter=@t3tools/scripts...
|
||||
|
||||
- name: Cache resource monitor
|
||||
@@ -495,7 +526,7 @@ jobs:
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
"Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
@@ -503,12 +534,16 @@ jobs:
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Install ImageMagick
|
||||
- uses: ./.github/actions/setup-apt-mirrors
|
||||
if: matrix.platform == 'linux'
|
||||
|
||||
- name: Install Linux desktop build libraries
|
||||
if: matrix.platform == 'linux'
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
if ! command -v magick >/dev/null 2>&1 && ! command -v convert >/dev/null 2>&1; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y imagemagick
|
||||
fi
|
||||
|
||||
@@ -583,6 +618,7 @@ jobs:
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata
|
||||
T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: ${{ steps.resource_monitor_cache.outputs.cache-hit == 'true' }}
|
||||
CSC_LINK: ${{ secrets.CSC_LINK }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||
@@ -851,35 +887,6 @@ jobs:
|
||||
fi
|
||||
done
|
||||
|
||||
# - name: Merge Windows updater manifests
|
||||
# run: |
|
||||
# shopt -s nullglob
|
||||
# found_windows_manifest=false
|
||||
# for x64_manifest in release-assets/*-win-x64.yml; do
|
||||
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
|
||||
# continue
|
||||
# fi
|
||||
|
||||
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
|
||||
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
|
||||
# if [[ ! -f "$arm64_manifest" ]]; then
|
||||
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# found_windows_manifest=true
|
||||
# node scripts/merge-update-manifests.ts --platform win \
|
||||
# "$arm64_manifest" \
|
||||
# "$x64_manifest" \
|
||||
# "$output_manifest"
|
||||
# rm -f "$arm64_manifest" "$x64_manifest"
|
||||
# done
|
||||
|
||||
# if [[ "$found_windows_manifest" != true ]]; then
|
||||
# echo "No Windows updater manifests found to merge." >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v3
|
||||
@@ -1050,6 +1057,60 @@ jobs:
|
||||
"${vercel_scope_args[@]}"
|
||||
fi
|
||||
|
||||
deploy_marketing:
|
||||
name: Deploy marketing site
|
||||
needs: [preflight, release]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'nightly' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/marketing...
|
||||
|
||||
- name: Deploy marketing site to Vercel
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" ]]; then
|
||||
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERCEL_PROJECT_ID="$(
|
||||
curl --fail --silent --show-error \
|
||||
--header "Authorization: Bearer $VERCEL_TOKEN" \
|
||||
"https://api.vercel.com/v9/projects/t3code-marketing?teamId=$VERCEL_ORG_ID" \
|
||||
| jq --exit-status --raw-output '.id'
|
||||
)"
|
||||
export VERCEL_PROJECT_ID
|
||||
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--prod \
|
||||
--yes \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
--scope "${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# On-demand Windows test lane. Manual only: nothing in the suite passes on
|
||||
# Windows yet, so this exists to give contributors (and agents) a cloud Windows
|
||||
# box to iterate against. Once the suite is green here, fold it into ci.yml.
|
||||
#
|
||||
# gh workflow run windows-tests.yml --ref <branch> -f package=packages/shared
|
||||
# gh workflow run windows-tests.yml --ref <branch> -f package=apps/server \
|
||||
# -f files="src/process/externalLauncher.test.ts src/cli/theme.test.ts"
|
||||
# gh run watch && gh run view --log-failed
|
||||
name: Windows Tests
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
package:
|
||||
description: "Workspace directory to test, e.g. apps/server or packages/shared. Empty runs every package except apps/server."
|
||||
type: string
|
||||
default: ""
|
||||
files:
|
||||
description: "Space-separated test files relative to the package directory. Empty runs the package's whole suite. Requires package."
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test (${{ inputs.package || 'all non-server' }})
|
||||
runs-on: blacksmith-8vcpu-windows-2025
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# setup-vp's own cache restores a Linux-shaped store on Windows, which is
|
||||
# slower than no cache (see #7975). Cache pnpm's Windows store directly.
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: false
|
||||
run-install: false
|
||||
|
||||
- name: Resolve package cache path
|
||||
id: package_cache_path
|
||||
shell: pwsh
|
||||
run: '"path=$(vp pm cache dir)" >> $env:GITHUB_OUTPUT'
|
||||
|
||||
- name: Cache packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ steps.package_cache_path.outputs.path }}
|
||||
key: windows-tests-packages-v1-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Install
|
||||
run: vp install
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
if: inputs.package == '' || inputs.package == 'apps/desktop'
|
||||
run: vp run --filter "@t3tools/desktop" ensure:electron
|
||||
|
||||
# `vp run ... test -- <files>` does not forward positional args to vitest,
|
||||
# so file-scoped runs call `vp test run` inside the package instead.
|
||||
- name: Test
|
||||
shell: pwsh
|
||||
run: |
|
||||
$package = '${{ inputs.package }}'
|
||||
$files = '${{ inputs.files }}'
|
||||
if ($package -eq '') {
|
||||
vp run --parallel --concurrency-limit 4 --filter '!t3' --filter '!@t3tools/monorepo' test
|
||||
} elseif ($files -eq '') {
|
||||
vp run --filter "./$package" test
|
||||
} else {
|
||||
Set-Location $package
|
||||
vp test run $files.Split(' ')
|
||||
}
|
||||
@@ -1,94 +1,73 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
model: gpt-5-6-sol
|
||||
effort: medium
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
exclude:
|
||||
- "**/*.test.ts"
|
||||
labels:
|
||||
- vouch:trusted
|
||||
requires:
|
||||
- Check
|
||||
maxBudgetPerRun: 5
|
||||
maxBudgetPerPR: 25
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
Review changed TypeScript for the conventions below. They apply when a pull request creates, moves, refactors, or consumes an Effect service. Review only the lines the PR changed; older code in the same file that predates these conventions is not a finding. Do not demand repository-wide cleanup.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
- Import Effect modules from their subpaths as namespaces: `import * as Effect from "effect/Effect"`, `import * as Layer from "effect/Layer"`. Flag named imports from the bare `"effect"` package.
|
||||
- At a service boundary, import the local service module as a namespace and use its public shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the namespace.
|
||||
- Named imports stay correct for whole packages such as `@t3tools/contracts` and for modules used only for a pure helper, error, schema, config value, or type. Do not request `import type * as Contracts`.
|
||||
- When a barrel exposes a whole service module, prefer `export * as TokenStore from "./tokenStore.ts"` over individually renamed `make` and `layer` exports.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
- One canonical module per service in this order: imports, error and schema declarations, the `Context.Service` tag with its interface inline, `make`, then `layer`.
|
||||
- Define the interface inline in `Context.Service`. Do not add a standalone `FooShape` interface; refer to the inferred type as `Foo["Service"]`.
|
||||
- Export a real `make` when the module owns construction. Do not write `make = Effect.succeed(...)` only to force `Layer.effect`; use `Layer.succeed`, `Layer.scoped`, or whichever constructor matches.
|
||||
- Use plain `make` and `layer` in a module named for its implementation (`BunPtyAdapter.ts`). Keep implementation-specific names when one abstract port module holds several implementations (`makeCloudflaredRelayClient`, `layerCloudflared` in `RelayClient.ts`). `infra/relay/src/db.ts` may keep its inline `Layer.succeed(RelayDb, db)`.
|
||||
- When a service moves, delete the old files and update every consumer, including orchestration, MCP, tests, and integration harnesses. Do not leave compatibility re-export shims.
|
||||
|
||||
## Dependency acquisition and runtime boundaries
|
||||
|
||||
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
|
||||
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
|
||||
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
|
||||
- Production service construction acquires its Effect dependencies from the environment with `yield* Foo.Foo`, and `make`/`layer` types expose those requirements. Flag a factory that takes `Foo["Service"]` (or an object of Effect-returning methods) as a parameter when that value is a service dependency. Passing service instances explicitly in tests is fine; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or a `Layer.succeed` whose implementation calls runtime-backed or imperative APIs.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at application or framework boundaries: React, native callbacks, CLI, HTTP adapters. Flag them in domain services, repositories, persistence, and service constructors. A named imperative adapter may bridge an Effect service into a Promise API but must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to hand the same owned resource to several consumers. Compose the resource once in an application-owned layer and provide its context to integration runtimes.
|
||||
- When acquisition can fail and callers need fallback behavior, keep the failure typed in Effect (an error in the service operation or an explicit optional-service layer) rather than bypassing the layer through an imperative runtime.
|
||||
|
||||
## Errors and predicates
|
||||
## Errors
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- For startup reconciliation that repairs multiple independent entities, preserve interruption rather than reducing it to a warning. Retry a transient per-entity repair before readiness, then isolate a persistent failure so one bad entity cannot abort global startup or prevent later entities from being repaired. Require tests for both the retry-success path and persistent-failure continuation.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes: operation or stage, resource path or entity identifier, normalized category or status. Derive `message` from those attributes only. Never derive it from `cause`, `cause.message`, or a stringified defect, and do not add a `detail` field that copies `cause.message`.
|
||||
- When wrapping a real failure, keep the immediate underlying error as `cause` so the chain and stack survive. Make `cause` required if every construction wraps a failure. Pure validation or domain errors created without an underlying failure need no cause.
|
||||
- Keep attributes and log annotations safe and bounded: no raw wire payloads, command arguments or output, signed URLs, credentials, query strings, or arbitrary defect text. Preserve the exact value only as `cause`; expose normalized categories, lengths, counts, and safe URL protocol or hostname where useful.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the target error channel; wrap only unknown or lower-level failures. Map failures where the context is known instead of wrapping a whole multi-step pipeline in one generic error.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Split into separate error classes when a discriminator drives caller control flow or the user-facing message; a discriminator used only for diagnostics may stay a field. Caller-visible messages exposed through HTTP, RPC, persisted state, or UI are behavior and must survive a structural refactor.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`. Construct the error at the failure boundary. Keep a mapper only when it performs real normalization, passes through domain errors, or adds reusable context; when such a mapper belongs to the target error type, prefer a static factory on that class.
|
||||
- Export predicates directly as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a function with the same signature.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including for a single tag; do not use `catchTag` or `catchIf` with a schema predicate for that. `Effect.catch` is fine when the whole error channel is handled; `catchIf` is fine for structural predicates such as a platform error code.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Require every new or broadened directive that disables or suppresses a lint, type-checker, LSP, or other static-analysis diagnostic to have an adjacent comment explaining why that diagnostic must be disabled there. The directive itself is not an explanation. Report a missing explanation as a concrete violation.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
- Every new or broadened directive that disables a lint, type-checker, LSP, or static-analysis diagnostic needs an adjacent comment explaining why. The directive itself is not an explanation; a missing one is a concrete violation.
|
||||
- If backend behavior changes, require focused tests that use test layers for external services only, never mocks of core business logic. Do not require new tests for mechanical refactors or import-only changes.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, or separate error classes for diagnostic-only fields.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
Report only violations introduced by changed lines. Post each as a precise inline comment on the smallest relevant range and state the expected fix. A clear convention violation may fail the check; optional style preferences and untouched legacy code may not.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
When there are no findings, make the entire final response exactly `All clear` on one line with nothing else.
|
||||
@@ -1,92 +1,61 @@
|
||||
---
|
||||
title: UI Consistency
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
model: gpt-5-6-terra
|
||||
effort: medium
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/web/src/**/*.ts"
|
||||
- "apps/web/src/**/*.tsx"
|
||||
- "apps/web/src/**/*.css"
|
||||
exclude:
|
||||
- "apps/web/src/**/*.test.tsx"
|
||||
labels:
|
||||
- vouch:trusted
|
||||
requires:
|
||||
- Check
|
||||
maxBudgetPerRun: 2
|
||||
maxBudgetPerPR: 10
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# UI consistency review
|
||||
|
||||
Review changed web UI code and directly affected call sites for consistency with the shared component system, Tailwind ownership, and the behavioral constraints below. Apply these rules when a pull request creates, moves, or modifies controls or styling. Do not demand unrelated repository-wide cleanup.
|
||||
This is a styling guard for `apps/web`, not a general review. Review only the changed lines in the diff and answer three questions. Do not build the project, inspect emitted CSS, trace selector consumers across the codebase, or ask for screenshots. If the diff does not make a violation obvious, there is no finding.
|
||||
|
||||
The goal is not to minimize CSS or class counts at any cost. The goal is to put each behavior in the smallest correct owner while preserving interaction, theming, accessibility, layout, and browser behavior.
|
||||
## 1. Shared primitives over custom controls
|
||||
|
||||
## Shared controls and variants
|
||||
Product UI must use the primitives in `apps/web/src/components/ui` (`Button`, `Input`, `InputGroup`, `Select`, `Toggle`, `Menu`, `Dialog`, `Tooltip`, `ScrollArea`, and the rest of that directory) instead of rebuilding them.
|
||||
|
||||
- Prefer the core UI primitives in `apps/web/src/components/ui` over native controls or locally reconstructed primitives. In ordinary product UI, a raw `<button>` that recreates `Button`, a raw input that recreates `Input` or `InputGroup`, or a local trigger that recreates `Select`, `Toggle`, or `Menu` is a concrete finding.
|
||||
- Do not flag raw elements that intentionally implement a semantic row, tab, resize handle, swatch, image target, editor surface, or another interaction whose behavior or geometry differs from the core primitive.
|
||||
- When multiple call sites repeat the same durable geometry or treatment, prefer a named primitive size or variant. Examples include compact controls, micro icon actions, muted ghost actions, and glass actions. Keep contextual layout, width, and color at the call site.
|
||||
- Flag large call-site class strings that override a primitive's core height, radius, padding, focus ring, cursor, hit target, or base state colors. Prefer extending the primitive contract when the same pattern is genuinely shared.
|
||||
- Preserve accessibility and interaction semantics during migrations: focus-visible rings, disabled behavior, loading state, keyboard behavior, pointer cursor, `aria-*`, Base UI or Radix render/close props, and coarse-pointer hit targets.
|
||||
- Do not require tests for a tiny visual-only class migration. Require focused tests when primitive composition changes behavior, prop forwarding, state transitions, keyboard handling, or width/defaulting logic.
|
||||
- Flag a raw `<button>`, `<input>`, `<select>`, or `<textarea>` styled to look like a control when the matching primitive exists.
|
||||
- Flag a call site that overrides a primitive's height, radius, padding, focus ring, or base colors with its own class string. If the same look is needed in several places, the fix is a new size or variant on the primitive.
|
||||
- Do not flag raw elements that are intentionally not a primitive: semantic rows, tabs, resize handles, swatches, editor surfaces, or anything whose behavior or geometry is different by design.
|
||||
|
||||
## CSS and Tailwind ownership
|
||||
## 2. Tailwind in the owning component, not global CSS
|
||||
|
||||
- Ordinary one-owner presentation belongs in the owning TS or TSX module as static Tailwind classes or owner-level CSS variables. Examples include local geometry, spacing, typography, backgrounds, borders, simple vendor pseudo-elements, and component-only positioning.
|
||||
- Keep global CSS when it is genuinely reusable or behaviorally complex: generated markdown or imperative DOM, custom elements and shadow roots, masks, shared or complex pseudo-elements, animations, glass composition, runtime theme variables, safe-area calculations, scrollbar-lane preservation, Electron drag regions, and browser/vendor integration. Simple owner-local pseudo-elements may still belong in the owning module.
|
||||
- Before calling a selector dead, trace literal, dynamic, generated, imperative, test, custom-element, and shadow-root consumers. Search both the emitted class string and any class-valued field names through their final DOM sink. A helper returning a class is not proof that it is rendered, and a missed downstream property read can make a deletion unsafe.
|
||||
- Flag duplicate declarations only after comparing cascade layer, selector specificity, inheritance, runtime theme scope, media/variant scope, and the final owning element. Textually identical declarations are not necessarily behaviorally redundant.
|
||||
- When moving CSS into Tailwind, preserve selector scope and cascade ownership. A utility at the owner is preferable to a fragile global override that depends on stylesheet order.
|
||||
- Do not request moving complex global behavior into arbitrary Tailwind merely to reduce `index.css`. Do not preserve ordinary one-owner CSS merely because it already exists globally.
|
||||
Styling lives as Tailwind classes in the component that renders the element.
|
||||
|
||||
## Themes and generated CSS
|
||||
- Flag new rules added to `apps/web/src/index.css` or any other `.css` file when the same styling could be Tailwind classes on the owning component. New global CSS is acceptable only for things Tailwind cannot express at the owner: generated markdown or imperative DOM, custom elements and shadow roots, animations, runtime theme variables, and browser or Electron integration.
|
||||
- Flag new `style={{ ... }}` objects or inline `<style>` blocks that carry static values a Tailwind class already covers. Dynamic values computed at runtime are fine.
|
||||
- Flag theme-only declarations that use raw `.dark` selectors instead of `@variant dark` / `@variant light`.
|
||||
|
||||
- Use the project variants for theme-only declarations:
|
||||
- dark-only declarations use `@variant dark`;
|
||||
- light-only declarations use `@variant light`;
|
||||
- raw `.dark` should remain only in the `dark` and `light` custom-variant definitions.
|
||||
- Preserve custom themes and runtime token bridges. Removing a variable or selector is safe only when all runtime, inspector, generated, and theme-palette consumers are accounted for.
|
||||
- Contrast and accessibility settings that target app chrome must derive from semantic color tokens. Do not apply `filter` to `html`, `body`, or the app root: it also changes user media, previews, terminals, glass backdrop ownership, and view-transition snapshots.
|
||||
- Preserve alpha and surface ownership when deriving contrast tokens. Soften translucent borders and inputs toward transparent rather than an opaque canvas, use a modest semantic-foreground mix for stronger borders, and adjust card, popover, accent, secondary, and message foregrounds against their own surfaces when the base foreground changes.
|
||||
- Runtime-adjusted roles must be ordinary custom properties shared by the Tailwind bridge, global CSS, imperative style strings, and bridge snapshots sent to other renderers. Audit literal `var(--foreground)`, `var(--border)`, and related role reads so headings, markdown chrome, menus, previews, and utilities do not split into adjusted and unadjusted colors.
|
||||
- Inspect emitted production CSS after unusual variants, arbitrary selectors, nested pseudo-elements, or attribute matching. Source syntax that looks valid is insufficient.
|
||||
- Flag malformed or empty emitted selectors such as empty `:is()` or `:not(:is())`, selector branches that can never match their own class attribute, and transformations that silently drop the intended rule.
|
||||
- Prefer source-level logic over clever selectors when behavior depends on consumer-provided class strings. Preserve `MenuPopup`'s current defaulting contract: a string `className` containing a `w-*`, `min-w-*`, or `max-w-*` utility after variant prefixes are stripped suppresses `min-w-32`; a string without one and a functional/non-string `className` keep the default. Arbitrary width values count as width utilities, and the consumer class must be merged last so it retains control. Do not replace this with a raw class-attribute substring selector.
|
||||
- Do not fail solely because a valid emitted selector is verbose or because a source rule uses an intentional custom property.
|
||||
## 3. Composable components
|
||||
|
||||
## Scroll and virtualized lists
|
||||
The reference for how this codebase wants UI built is the composer banner system in `apps/web/src/components/chat/`:
|
||||
|
||||
- `ScrollArea` owns and masks its Base UI viewport. A virtualized list usually owns a native scrolling element and cannot automatically reuse viewport-specific `ScrollArea` behavior.
|
||||
- Repeated native or virtualized overflow fades should use the shared virtualized-scroll-fade contract rather than component-named mask selectors.
|
||||
- Preserve runtime top and bottom overflow state. Do not replace dynamic fades with an always-on static mask.
|
||||
- Preserve fade geometry and keep the native scrollbar lane opaque so the track and thumb stay visible and usable. A visually similar mask that fades the scrollbar is a regression.
|
||||
- Verify actual scroll behavior when changing virtualizers, masks, overflow ownership, or scrollbar selectors. Source-level class comparison is not enough.
|
||||
- `ComposerBanner.tsx` exports one object of small slot components (`Root`, `Row`, `Icon`, `Content`, `Actions`, `Dismiss`, `Children`, and so on). Each slot owns its own Tailwind classes, exposes a `data-slot` attribute, takes `className` and spreads the rest of its props, and uses `cn` so callers can adjust without overriding. Variants and density are props on `Root`, not ad hoc class strings at call sites. Where a slot needs a real control it renders `Button` from `ui/` rather than a styled `<button>`.
|
||||
- `ComposerBannerStack.tsx` composes those slots into the ordered stack and owns only stack behavior (priority, expand and collapse, dismiss transitions).
|
||||
- Consumers such as `ComposerActivityStatus.tsx`, `ComposerStashBadge.tsx`, and `ComposerPlanFollowUpBanner.tsx` are a few lines of `<ComposerBanner.Row><ComposerBanner.Icon/><ComposerBanner.Content>…` with no styling of their own.
|
||||
|
||||
## Visual and layout preservation
|
||||
Hold new and changed UI to that shape:
|
||||
|
||||
- Preserve responsive geometry, titlebar insets, panel and inline-preview modes, desktop Electron layout, light and dark contrast, clipping, radius, and composable shadows.
|
||||
- For meaningful visual changes, prefer available real-app evidence using the actual component and state. A mock recreation does not validate the real component. Light and dark evidence is useful when theme-sensitive styles change, but missing or inaccessible evidence alone is not a finding; report only a concrete regression supported by the diff, code, or available artifacts.
|
||||
- Do not treat a screenshot as proof of keyboard, overflow, scrollbar, responsive, or runtime-theme behavior. Pair visual evidence with source, computed-style, emitted-CSS, or interaction checks as appropriate.
|
||||
- Be alert to shared primitive color indirection. When a primitive routes icon color through a CSS variable, ensure migrated contextual icons retain their intended tone, including pressed and disabled states.
|
||||
|
||||
## Environment routing in shared renderers
|
||||
|
||||
- A shared renderer that performs an environment-scoped action — a server RPC such as opening or revealing a file, an environment-gated capability check, or an OS-derived label — must resolve its target environment from explicit scope: the bound thread's `environmentId`, or an `environmentId` prop threaded from the owning surface. Never let it silently fall back to the globally active environment. Multi-environment surfaces (pull request panels, review annotations, cross-environment listings) can render content from environment B while environment A is active; a silent fallback sends B's paths to A's server and presents A's platform wording.
|
||||
- When a call site cannot supply an explicit environment scope, suppress the environment-scoped actions at that call site rather than guessing. A hidden menu item is correct; an item that targets the wrong server is a concrete finding.
|
||||
- Capability gating, action dispatch, and user-facing labels must all read from the same environment's server config that the action will execute against. Flag a renderer whose label derives from one environment while its RPC targets another.
|
||||
- Flag new call sites of shared markdown, chip, or menu renderers that trigger environment actions without passing explicit scope, and flag new environment-action props whose default reintroduces an active-environment fallback.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Review the pull request's changed scope and directly affected consumers. Do not turn a focused PR into a demand for unrelated legacy cleanup.
|
||||
- Prefer the smallest durable contract over a component-specific workaround or a broad abstraction with one consumer.
|
||||
- Preserve intentional exceptions and comments that explain browser, virtualizer, theme, or Electron constraints.
|
||||
- If a proposed cleanup cannot prove ownership or semantic equivalence, ask for evidence or leave it unchanged rather than guessing.
|
||||
- Select verification gates according to the changed behavior: typecheck or focused tests for typing and interaction contracts, production build and emitted-CSS inspection for Tailwind or selector transformations, and real-app evidence for meaningful visual behavior when available. These gates are complementary when applicable, but do not require every gate for tiny visual-only migrations or fail solely because an artifact the configured tools cannot produce is absent.
|
||||
- Flag a new component that copies a chunk of an existing primitive's markup and classes instead of composing or extending it.
|
||||
- Flag a large one-off class string on a shared component when it is clearly the same treatment another call site already uses. The fix is a variant or a new slot on the shared component.
|
||||
- Flag a new composer banner or notice that bypasses `ComposerBanner` slots and hand-builds its row, icon column, or actions.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced by changed lines or behavior, plus pre-existing behavior that the patch directly makes relevant or worsens. Touching a large file does not make unrelated retained issues reportable. Prefer precise inline comments on the smallest relevant line range. Explain the broken behavior or ownership rule, not merely the preferred syntax, and state the smallest expected fix. A clear consistency or regression risk may fail the check. Do not fail for optional aesthetic preferences, harmless class ordering, or unrelated legacy code.
|
||||
Report only violations introduced by changed lines. Post each as a brief inline comment on the relevant line: name the rule, name the primitive or location the code should use instead, and stop. Do not comment on class ordering, aesthetic preference, or untouched legacy code, and do not demand cleanup outside the PR's scope.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
When there are no findings, make the entire final response exactly `All clear` on one line with nothing else.
|
||||
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs (Codex, Claude Code, Cursor, Grok, OpenCode) and serves web, desktop, and mobile clients.
|
||||
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity) and serves web, desktop, and mobile clients.
|
||||
|
||||
You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor.
|
||||
|
||||
@@ -68,11 +68,11 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
|
||||
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
|
||||
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
|
||||
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
|
||||
- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, and Antigravity each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
|
||||
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
|
||||
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
|
||||
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
|
||||
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
|
||||
- **Docs.** Check whether the change makes existing guidance inaccurate. Apply the [documentation rules](#documentation) before adding anything.
|
||||
|
||||
## Dev servers
|
||||
|
||||
@@ -120,11 +120,22 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- One concern per PR. If the description says "also", split it.
|
||||
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
|
||||
|
||||
## Documentation
|
||||
|
||||
Most code changes do not need an internal documentation change. Agents can read the code.
|
||||
|
||||
- `docs/internals/` is for architectural decisions and their reasons, constraints that span components, and implementation traps that are hard to discover from the source. Before adding a paragraph, ask what a maintainer would get wrong without it. If reading the relevant code answers the question, leave it out.
|
||||
- Do not document every feature, enumerate fields or methods, narrate control flow, maintain file catalogs, or append PR summaries. Types, tests, and code already record the implementation. The glossary defines shared vocabulary; it is not a feature index.
|
||||
- Keep a local implementation explanation in a nearby code comment. Use an internal doc when the reasoning crosses boundaries or needs context the code cannot carry well. Link to the relevant source instead of copying it.
|
||||
- When a documented decision or constraint changes, rewrite or remove the affected text. Do not append another account of the new behavior. A new internal page needs a distinct, durable reason to exist.
|
||||
- `docs/user/` helps users accomplish tasks. Give each major feature a concise section explaining what it does, how to start, and anything unintuitive. A settings path is useful; descriptions of visible buttons, icons, layouts, animations, or every UI state are not. Before adding text, ask what task or decision it helps the user with.
|
||||
- Keep user docs in the shipped product's voice, without implementation details or contributor tooling. Update the relevant feature section when how to use it changes. A UI tweak does not need a documentation entry, and a new control does not need its own page.
|
||||
- `docs/operations/` holds maintainer setup, release, and debugging procedures. Keep instructions for operating an installed T3 Code server in the user guides.
|
||||
|
||||
## Plans and work artifacts
|
||||
|
||||
- Do not commit implementation plans, research notes, or agent scratch files. Keep temporary working material outside the worktree. `.plans/` is gitignored only as a safety net for legacy tooling.
|
||||
- Track active maintainer work in the GitHub issue or project item that owns it. External proposals follow `CONTRIBUTING.md` and belong in Ideas discussions.
|
||||
- Put durable architecture, constraints, and decisions in `docs/internals/`. Update those docs when the product changes so agents find current facts instead of abandoned intentions.
|
||||
- A merged PR is the implementation record. Close or update its tracking item when the work lands; do not preserve a second checklist in the repository.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Contributing
|
||||
|
||||
## Developer Setup
|
||||
|
||||
See the [development runbook](docs/operations/development.md#first-checkout) for the initial checkout,
|
||||
development commands, tests, and platform-specific desktop packaging prerequisites.
|
||||
|
||||
## Read This First
|
||||
|
||||
We are not actively accepting contributions right now.
|
||||
@@ -44,6 +49,10 @@ Explain exactly what changed.
|
||||
|
||||
Explain exactly why the change should exist.
|
||||
|
||||
Follow the [documentation rules](AGENTS.md#documentation). Keep internal docs for decisions and
|
||||
hard-to-discover constraints. Update user guides when how to use a feature changes; skip descriptions
|
||||
of obvious controls and cosmetic changes.
|
||||
|
||||
Do not mix unrelated fixes together.
|
||||
|
||||
If the PR makes anything resembling a UI change, include clear before/after images.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
|
||||
|
||||
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
|
||||
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, OpenCode, and Google Antigravity. If they're set up on your computer, T3 Code can control them.
|
||||
|
||||
## "Wait, what are you selling me?"
|
||||
|
||||
@@ -13,13 +13,14 @@ We wanted something performant, remote-ready, and truly open. If we ever go the
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, Cursor, Grok Build and OpenCode. Install and authenticate at least one provider before use:
|
||||
> T3 Code currently supports Codex, Claude, Cursor, Grok Build, OpenCode, and Antigravity. Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login`
|
||||
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
> - Antigravity: enable it in Settings, then use **Install Antigravity** and **Sign in with Google**. No CLI is required.
|
||||
|
||||
### Try it out (install-free)
|
||||
|
||||
@@ -78,12 +79,12 @@ Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
- [Install and first run](./docs/user/install.md)
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Project settings](./docs/user/project-settings.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
|
||||
- Linux: [run T3 Code as a background service](./docs/user/background-service.md)
|
||||
- [Run T3 Code as a background service](./docs/user/background-service.md)
|
||||
|
||||
Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md).
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.38",
|
||||
"version": "0.0.39",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -15,6 +15,7 @@
|
||||
"@clerk/electron": "catalog:",
|
||||
"@clerk/electron-passkeys": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@napi-rs/keyring": "^1.3.0",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- The native compiler targets the actual host; this script has no Effect runtime.
|
||||
const hostArch = process.arch;
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Native compilation only runs on the actual Linux host.
|
||||
const hostPlatform = process.platform;
|
||||
|
||||
describe.skipIf(hostPlatform !== "linux")("bundled libsecret helper", () => {
|
||||
let directory;
|
||||
let executable;
|
||||
beforeAll(() => {
|
||||
directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-browser-secret-test-"));
|
||||
executable = NodePath.join(directory, "t3-browser-secret");
|
||||
const root = NodeURL.fileURLToPath(new URL("../../../native/browser-secret/", import.meta.url));
|
||||
const flags = NodeChildProcess.execFileSync(
|
||||
"pkg-config",
|
||||
["--cflags", "--libs", "libsecret-1"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
)
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
NodeChildProcess.execFileSync(
|
||||
process.env.CC || "cc",
|
||||
[
|
||||
"-std=c11",
|
||||
"-Wall",
|
||||
"-Wextra",
|
||||
"-Werror",
|
||||
NodePath.join(root, "main.c"),
|
||||
NodePath.join(root, "test.c"),
|
||||
"-Wl,--wrap=secret_service_search_sync",
|
||||
"-Wl,--wrap=secret_item_get_locked",
|
||||
"-Wl,--wrap=secret_item_get_secret",
|
||||
"-o",
|
||||
executable,
|
||||
...flags,
|
||||
],
|
||||
{ stdio: "pipe" },
|
||||
);
|
||||
});
|
||||
afterAll(() => {
|
||||
if (directory) NodeFS.rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const run = (args) =>
|
||||
NodeChildProcess.spawnSync(executable, args, {
|
||||
env: { ...process.env, DBUS_SESSION_BUS_ADDRESS: "unix:path=/unused-test-bus" },
|
||||
});
|
||||
|
||||
it("builds an executable for the requested architecture into a staged resource directory", () => {
|
||||
const output = NodePath.join(directory, "resources", "browser-secret", "t3-browser-secret");
|
||||
NodeChildProcess.execFileSync(process.execPath, [
|
||||
NodeURL.fileURLToPath(new URL("./build-browser-secret.mjs", import.meta.url)),
|
||||
"--arch",
|
||||
hostArch,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
const header = NodeFS.readFileSync(output).subarray(0, 20);
|
||||
expect(header.toString("hex", 0, 6)).toBe("7f454c460201");
|
||||
expect(header.readUInt16LE(18)).toBe({ x64: 62, arm64: 183 }[hostArch]);
|
||||
expect(NodeFS.statSync(output).mode & 0o111).not.toBe(0);
|
||||
// Invalid arguments exit before the real executable could contact a keyring.
|
||||
expect(NodeChildProcess.spawnSync(output, []).status).toBe(64);
|
||||
});
|
||||
|
||||
it("preserves the exact secret bytes with no added or removed delimiter", () => {
|
||||
const result = run(["success"]);
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toEqual(Buffer.from("secret\0with whitespace \t\r\n"));
|
||||
expect(result.stderr.length).toBe(0);
|
||||
});
|
||||
|
||||
for (const [scenario, code] of [
|
||||
["missing", 2],
|
||||
["empty", 2],
|
||||
["locked", 3],
|
||||
["cancelled", 3],
|
||||
["denied", 3],
|
||||
["unavailable", 4],
|
||||
["unloaded", 4],
|
||||
]) {
|
||||
it(`reports ${scenario} without emitting a secret`, () => {
|
||||
const result = run([scenario]);
|
||||
expect(result.status).toBe(code);
|
||||
expect(result.stdout.length).toBe(0);
|
||||
});
|
||||
}
|
||||
it("rejects invalid arguments before accessing the keyring", () => {
|
||||
for (const args of [[], [""], ["chrome", "extra"]]) {
|
||||
const result = run(args);
|
||||
expect(result.status).toBe(64);
|
||||
expect(result.stdout.length).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import * as NodeUtil from "node:util";
|
||||
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- The native compiler targets the actual host; this script has no Effect runtime.
|
||||
const hostArch = process.arch;
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Native compilation only runs on the actual Linux host.
|
||||
const hostPlatform = process.platform;
|
||||
|
||||
const { values } = NodeUtil.parseArgs({
|
||||
options: { output: { type: "string" }, arch: { type: "string", default: hostArch } },
|
||||
});
|
||||
|
||||
if (hostPlatform === "linux") {
|
||||
const machine = { x64: 62, arm64: 183 }[values.arch];
|
||||
if (machine === undefined) throw new Error(`Unsupported Linux architecture: ${values.arch}`);
|
||||
const root = NodeURL.fileURLToPath(new URL("../../../native/browser-secret/", import.meta.url));
|
||||
const source = NodePath.resolve(root, "main.c");
|
||||
const output = values.output ?? NodePath.resolve(root, "build", values.arch, "t3-browser-secret");
|
||||
const matchesArchitecture = (file) => {
|
||||
const header = NodeFS.readFileSync(file).subarray(0, 20);
|
||||
return header.toString("hex", 0, 6) === "7f454c460201" && header.readUInt16LE(18) === machine;
|
||||
};
|
||||
let current = false;
|
||||
try {
|
||||
current =
|
||||
NodeFS.statSync(output).mtimeMs >=
|
||||
Math.max(
|
||||
NodeFS.statSync(source).mtimeMs,
|
||||
NodeFS.statSync(NodeURL.fileURLToPath(import.meta.url)).mtimeMs,
|
||||
) && matchesArchitecture(output);
|
||||
} catch {
|
||||
/* The first build has no output yet. */
|
||||
}
|
||||
if (!current) {
|
||||
let flags;
|
||||
try {
|
||||
flags = NodeChildProcess.execFileSync("pkg-config", ["--cflags", "--libs", "libsecret-1"], {
|
||||
encoding: "utf8",
|
||||
})
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
} catch (cause) {
|
||||
throw new Error(
|
||||
"Building the Linux browser import helper requires pkg-config and libsecret development headers (Ubuntu/Debian: libsecret-1-dev).",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
NodeFS.mkdirSync(NodePath.dirname(output), { recursive: true });
|
||||
const temporary = `${output}.${process.pid}.tmp`;
|
||||
try {
|
||||
NodeChildProcess.execFileSync(
|
||||
process.env.CC || "cc",
|
||||
["-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", source, "-o", temporary, ...flags],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
if (!matchesArchitecture(temporary))
|
||||
throw new Error(`C compiler did not produce a Linux ${values.arch} executable.`);
|
||||
NodeFS.renameSync(temporary, output);
|
||||
} finally {
|
||||
NodeFS.rmSync(temporary, { force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,12 @@ const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.tr
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
NodeChildProcess.execFileSync(
|
||||
process.execPath,
|
||||
[NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
|
||||
@@ -165,10 +165,14 @@ function registerMacLauncherBundle(appBundlePath) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bundle-internal paths are macOS paths whatever host builds them.
|
||||
export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
|
||||
return {
|
||||
sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
|
||||
generatedIconPath: NodePath.join(runtimeDir, development ? "icon-dev.icns" : "icon-prod.icns"),
|
||||
generatedIconPath: NodePath.posix.join(
|
||||
runtimeDir,
|
||||
development ? "icon-dev.icns" : "icon-prod.icns",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -280,12 +284,12 @@ function readJson(path) {
|
||||
}
|
||||
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const executableDir = NodePath.posix.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
launcherBinaryPath: NodePath.posix.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.posix.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -84,9 +84,10 @@ describe("electron development launcher", () => {
|
||||
const development = resolveMacLauncherIconPaths("/runtime", true);
|
||||
const production = resolveMacLauncherIconPaths("/runtime", false);
|
||||
|
||||
assert.match(development.sourceIconPath, /assets\/dev\/blueprint-macos-1024\.png$/);
|
||||
// The source icons are real repo paths, joined for the host.
|
||||
assert.match(development.sourceIconPath, /assets[\\/]dev[\\/]blueprint-macos-1024\.png$/);
|
||||
assert.equal(development.generatedIconPath, "/runtime/icon-dev.icns");
|
||||
assert.match(production.sourceIconPath, /assets\/prod\/black-macos-1024\.png$/);
|
||||
assert.match(production.sourceIconPath, /assets[\\/]prod[\\/]black-macos-1024\.png$/);
|
||||
assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns");
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import * as NodeFS from "node:fs";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
@@ -176,7 +177,8 @@ export function ensureElectronRuntime() {
|
||||
return electronPath;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
// `file://${argv[1]}` never matches on Windows (drive letters need `file:///C:/`).
|
||||
if (process.argv[1] && NodeURL.pathToFileURL(process.argv[1]).href === import.meta.url) {
|
||||
const electronPath = ensureElectronRuntime();
|
||||
process.stdout.write(`${electronPath}\n`);
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
NodeChildProcess.execFileSync(
|
||||
process.execPath,
|
||||
[NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
|
||||
@@ -194,7 +194,10 @@ const bootstrap = Effect.gen(function* () {
|
||||
yield* logBootstrapInfo("bootstrap enabled network access", {
|
||||
endpointUrl: serverExposureState.endpointUrl,
|
||||
});
|
||||
} else if (settings.serverExposureMode === "network-accessible") {
|
||||
} else if (
|
||||
settings.serverExposureMode === "network-accessible" &&
|
||||
serverExposureState.mode === "local-only"
|
||||
) {
|
||||
yield* logBootstrapWarning(
|
||||
"bootstrap fell back to local-only because no advertised network host was available",
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -88,6 +89,7 @@ const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
NodePath.layerPosix,
|
||||
DesktopConfig.layerTest({
|
||||
...env,
|
||||
}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -20,7 +21,11 @@ const environmentLayer = DesktopEnvironment.layer({
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest({})),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopAssets", () => {
|
||||
it.effect("uses canonical source-tree icons for unpackaged development", () =>
|
||||
@@ -39,6 +44,7 @@ describe("DesktopAssets", () => {
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
NodePath.layerPosix,
|
||||
DesktopConfig.layerTest({ VITE_DEV_SERVER_URL: "http://localhost:5733" }),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -63,17 +63,6 @@ describe("DesktopClerk", () => {
|
||||
storageMock.mockReset();
|
||||
});
|
||||
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(
|
||||
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
|
||||
"clerk.t3.codes",
|
||||
);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
const events: string[] = [];
|
||||
@@ -208,27 +197,4 @@ describe("DesktopClerk", () => {
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme, host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
@@ -53,7 +53,7 @@ export class DesktopClerk extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopClerk") {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
@@ -72,7 +72,7 @@ export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHos
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
@@ -226,10 +227,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("surfaces malformed catalog documents without deleting them", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, "{not-json");
|
||||
|
||||
@@ -247,6 +249,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
|
||||
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
@@ -255,7 +258,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
pathOrDescriptor: path.join(baseDir, "userdata", "connection-catalog.json"),
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -272,11 +275,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, path.join(baseDir, "userdata", "connection-catalog.json"));
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Failed to read the desktop connection catalog at ${path.join(baseDir, "userdata", "connection-catalog.json")}.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -285,6 +288,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("reports the failed catalog write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
@@ -292,7 +296,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: path.join(baseDir, "userdata"),
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -310,11 +314,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, path.join(baseDir, "userdata"));
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop connection catalog write failed during create-directory at ${path.join(baseDir, "userdata")}.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -323,6 +327,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("reports the legacy migration stage", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
@@ -335,7 +340,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
|
||||
);
|
||||
assert.equal(error.operation, "read-legacy-registry");
|
||||
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, path.join(environment.stateDir, "connection-catalog.json"));
|
||||
assert.instanceOf(
|
||||
error.cause,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
@@ -345,7 +350,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
assert.exists(registryError.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${path.join(environment.stateDir, "connection-catalog.json")}.`,
|
||||
);
|
||||
assert.notEqual(error.message, registryError.message);
|
||||
}),
|
||||
@@ -355,10 +360,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("reports invalid encrypted catalog data without exposing it", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
|
||||
|
||||
@@ -381,6 +387,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
@@ -399,14 +406,14 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, path.join(baseDir, "userdata", "connection-catalog.json"));
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${path.join(baseDir, "userdata", "connection-catalog.json")}.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -26,7 +27,11 @@ const makeEnvironmentLayer = (
|
||||
DesktopEnvironment.layer({
|
||||
...defaultInput,
|
||||
...overrides,
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest(env))));
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest(env)),
|
||||
),
|
||||
);
|
||||
|
||||
const makeEnvironment = (
|
||||
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
|
||||
|
||||
@@ -37,45 +37,22 @@ describe("DesktopPreReadyPlatform", () => {
|
||||
registerSchemesMock.mockReset();
|
||||
});
|
||||
|
||||
it("reads an explicit Electron command-line switch value", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: (switchName) => switchName === "password-store",
|
||||
getSwitchValue: (switchName) => {
|
||||
assert.equal(switchName, "password-store");
|
||||
return "basic";
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
it.effect("preserves an explicit Linux password-store switch", () => {
|
||||
hasSwitchMock.mockImplementation((switchName) => switchName === "password-store");
|
||||
getSwitchValueMock.mockReturnValue(" basic ");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const options = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
|
||||
|
||||
assert.equal(options.linuxPasswordStoreCommandLine, "basic");
|
||||
assert.isFalse(appendSwitchMock.mock.calls.some(([name]) => name === "password-store"));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopPreReadyPlatform.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(value, "basic");
|
||||
});
|
||||
|
||||
it("treats valueless Electron command-line switches as absent", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => true,
|
||||
getSwitchValue: () => "",
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it("returns null for missing Electron command-line switches", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => false,
|
||||
getSwitchValue: () => {
|
||||
throw new Error("Unexpected switch value read.");
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface DesktopPreReadyCommandLineReader {
|
||||
readonly getSwitchValue: (switchName: string) => string;
|
||||
}
|
||||
|
||||
export function readCommandLineSwitchValue(
|
||||
function readCommandLineSwitchValue(
|
||||
commandLine: DesktopPreReadyCommandLineReader,
|
||||
switchName: string,
|
||||
): string | null {
|
||||
|
||||
@@ -218,14 +218,6 @@ const withPackagedWslHarness = <A, E, R>(
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
|
||||
|
||||
describe("DesktopBackendConfiguration", () => {
|
||||
it("accepts only normalized SHA-256 archive identities", () => {
|
||||
assert.equal(
|
||||
DesktopBackendConfiguration.parseWslRuntimeArchiveHash(` ${"A".repeat(64)}\n`),
|
||||
"a".repeat(64),
|
||||
);
|
||||
assert.isNull(DesktopBackendConfiguration.parseWslRuntimeArchiveHash("abc123"));
|
||||
});
|
||||
|
||||
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -243,7 +243,7 @@ const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
|
||||
const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
|
||||
const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
|
||||
|
||||
export const parseWslRuntimeArchiveHash = (value: string): string | null => {
|
||||
const parseWslRuntimeArchiveHash = (value: string): string | null => {
|
||||
const trimmed = value.trim();
|
||||
return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
|
||||
};
|
||||
|
||||
@@ -663,15 +663,13 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
Ref.update(state, withActiveRun(runId, f));
|
||||
|
||||
const snapshot = Ref.get(state).pipe(
|
||||
Effect.map(
|
||||
(current): DesktopBackendSnapshot => ({
|
||||
desiredRunning: current.desiredRunning,
|
||||
ready: current.ready,
|
||||
activePid: activePid(current.active),
|
||||
restartAttempt: current.restartAttempt,
|
||||
restartScheduled: Option.isSome(current.restartFiber),
|
||||
}),
|
||||
),
|
||||
Effect.map((current): DesktopBackendSnapshot => ({
|
||||
desiredRunning: current.desiredRunning,
|
||||
ready: current.ready,
|
||||
activePid: activePid(current.active),
|
||||
restartAttempt: current.restartAttempt,
|
||||
restartScheduled: Option.isSome(current.restartFiber),
|
||||
})),
|
||||
);
|
||||
const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
|
||||
|
||||
|
||||
@@ -272,8 +272,6 @@ describe("DesktopServerExposure", () => {
|
||||
modeError,
|
||||
DesktopServerExposure.DesktopServerExposureModePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
|
||||
assert.equal(modeError.mode, "network-accessible");
|
||||
assert.strictEqual(modeError.cause, settingsFailure);
|
||||
assert.strictEqual(modeError.cause.cause, diskFailure);
|
||||
@@ -290,7 +288,6 @@ describe("DesktopServerExposure", () => {
|
||||
tailscaleError,
|
||||
DesktopServerExposure.DesktopTailscaleServePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
|
||||
assert.equal(tailscaleError.enabled, true);
|
||||
assert.equal(tailscaleError.port, 8443);
|
||||
assert.strictEqual(tailscaleError.cause, settingsFailure);
|
||||
@@ -307,9 +304,9 @@ describe("DesktopServerExposure", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
|
||||
it.effect("keeps LAN and Tailscale endpoints distinct when Tailscale is enumerated first", () =>
|
||||
withHarness(
|
||||
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
|
||||
{ ...tailnetNetworkInterfaces, ...lanNetworkInterfaces },
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
@@ -324,6 +321,32 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps Tailscale-only hosts network-accessible", () =>
|
||||
withHarness(
|
||||
tailnetNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* settings.setServerExposureMode("network-accessible");
|
||||
|
||||
const state = yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
assert.equal(state.mode, "network-accessible");
|
||||
assert.equal(state.advertisedHost, null);
|
||||
assert.equal(state.endpointUrl, null);
|
||||
assert.equal((yield* serverExposure.backendConfig).bindHost, "0.0.0.0");
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => [endpoint.reachability, endpoint.httpBaseUrl]),
|
||||
[
|
||||
["loopback", "http://127.0.0.1:4173/"],
|
||||
["private-network", "http://100.90.1.2:4173/"],
|
||||
],
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
@@ -345,7 +368,7 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses ConfigProvider desktop exposure overrides", () =>
|
||||
it.effect("preserves explicit Tailscale exposure overrides", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
@@ -353,17 +376,17 @@ describe("DesktopServerExposure", () => {
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
const change = yield* serverExposure.setMode("network-accessible");
|
||||
|
||||
assert.equal(change.state.advertisedHost, "10.0.0.7");
|
||||
assert.equal(change.state.endpointUrl, "http://10.0.0.7:4173");
|
||||
assert.equal(change.state.advertisedHost, "100.90.1.2");
|
||||
assert.equal(change.state.endpointUrl, "http://100.90.1.2:4173");
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["http://127.0.0.1:4173/", "http://10.0.0.7:4173/", "https://public.example.test/"],
|
||||
["http://127.0.0.1:4173/", "http://100.90.1.2:4173/", "https://public.example.test/"],
|
||||
);
|
||||
}),
|
||||
{
|
||||
T3CODE_DESKTOP_LAN_HOST: "10.0.0.7",
|
||||
T3CODE_DESKTOP_LAN_HOST: "100.90.1.2",
|
||||
T3CODE_DESKTOP_HTTPS_ENDPOINTS: "https://public.example.test",
|
||||
},
|
||||
),
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type DesktopServerExposureMode,
|
||||
type DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import { isTailscaleIpv4Address, readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -65,7 +65,9 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
|
||||
};
|
||||
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||
!address.startsWith("127.") &&
|
||||
!address.startsWith("169.254.") &&
|
||||
!isTailscaleIpv4Address(address);
|
||||
|
||||
const isHttpsEndpointUrl = (value: string): boolean => {
|
||||
try {
|
||||
@@ -244,7 +246,6 @@ export const DesktopServerExposureSetModeError = Schema.Union([
|
||||
DesktopServerExposureModePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
|
||||
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
|
||||
|
||||
export const DesktopServerExposureError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
@@ -252,7 +253,6 @@ export const DesktopServerExposureError = Schema.Union([
|
||||
DesktopTailscaleServePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
|
||||
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
|
||||
|
||||
export interface DesktopServerExposureBackendConfig {
|
||||
readonly port: number;
|
||||
@@ -378,7 +378,14 @@ function resolveRuntimeState(input: {
|
||||
...(advertisedHostOverride ? { advertisedHostOverride } : {}),
|
||||
});
|
||||
const unavailable =
|
||||
input.requestedMode === "network-accessible" && requestedExposure.endpointUrl === null;
|
||||
input.requestedMode === "network-accessible" &&
|
||||
requestedExposure.endpointUrl === null &&
|
||||
!Object.values(input.networkInterfaces).some((addresses) =>
|
||||
addresses?.some(
|
||||
(address) =>
|
||||
!address.internal && address.family === "IPv4" && isTailscaleIpv4Address(address.address),
|
||||
),
|
||||
);
|
||||
const exposure = unavailable
|
||||
? resolveDesktopServerExposure({
|
||||
mode: "local-only",
|
||||
|
||||
@@ -43,7 +43,6 @@ describe("ElectronDialog", () => {
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
|
||||
assert.isTrue(ElectronDialog.isElectronDialogError(error));
|
||||
assert.strictEqual(error.ownerWindowId, 7);
|
||||
assert.strictEqual(error.defaultPath, "/workspace");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
|
||||
@@ -73,7 +73,6 @@ export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
export type ElectronDialogError = typeof ElectronDialogError.Type;
|
||||
export const isElectronDialogError = Schema.is(ElectronDialogError);
|
||||
|
||||
export interface ElectronDialogPickFolderInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
|
||||
@@ -36,6 +36,20 @@ describe("ElectronShell", () => {
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens the Full Disk Access settings anchor", () =>
|
||||
Effect.gen(function* () {
|
||||
openExternalMock.mockResolvedValue(undefined);
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const result = yield* electronShell.openSystemSettings("full-disk-access");
|
||||
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(openExternalMock.mock.calls, [
|
||||
["x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles"],
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens remote SSH editor URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
openExternalMock.mockResolvedValue(undefined);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
|
||||
import {
|
||||
REMOTE_CAPABLE_EDITOR_IDS,
|
||||
remoteSchemeForEditor,
|
||||
type SystemSettingsPane,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -6,6 +10,20 @@ import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
/**
|
||||
* Deep links to individual System Settings panes. These are app-fixed, not
|
||||
* renderer-supplied, so they skip `parseSafeExternalUrl` — which exists to keep
|
||||
* arbitrary link schemes from reaching the OS handler — and open through their
|
||||
* own path below. The pane rather than the URL crosses the IPC boundary, so a
|
||||
* renderer can only ask for one of these known destinations.
|
||||
*
|
||||
* Full Disk Access uses the post-Ventura `PrivacySecurity.extension` anchor.
|
||||
*/
|
||||
const SYSTEM_SETTINGS_URLS: Record<SystemSettingsPane, string> = {
|
||||
"full-disk-access":
|
||||
"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
|
||||
};
|
||||
|
||||
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
|
||||
// must reach the OS handler; every other non-web scheme stays blocked.
|
||||
const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]);
|
||||
@@ -43,6 +61,8 @@ export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
/** Opens a known System Settings pane by identifier, not by URL. */
|
||||
readonly openSystemSettings: (pane: SystemSettingsPane) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
@@ -59,6 +79,13 @@ export const make = ElectronShell.of({
|
||||
),
|
||||
),
|
||||
}),
|
||||
openSystemSettings: (pane) =>
|
||||
Effect.promise(() =>
|
||||
Electron.shell.openExternal(SYSTEM_SETTINGS_URLS[pane]).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
),
|
||||
copyText: (text) =>
|
||||
Effect.sync(() => {
|
||||
Electron.clipboard.writeText(text);
|
||||
|
||||
@@ -64,7 +64,6 @@ describe("ElectronTheme", () => {
|
||||
const error = yield* Effect.flip(electronTheme.setSource("dark"));
|
||||
|
||||
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
|
||||
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
|
||||
assert.strictEqual(error.source, "dark");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "dark");
|
||||
|
||||
@@ -19,8 +19,6 @@ export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<Electro
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
|
||||
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
|
||||
@@ -71,7 +71,6 @@ describe("ElectronUpdater", () => {
|
||||
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "beta");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
|
||||
@@ -89,7 +88,6 @@ describe("ElectronUpdater", () => {
|
||||
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
@@ -126,7 +124,6 @@ describe("ElectronUpdater", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "alpha");
|
||||
assert.equal(error.isSilent, true);
|
||||
assert.equal(error.isForceRunAfter, false);
|
||||
|
||||
@@ -54,7 +54,6 @@ export const ElectronUpdaterError = Schema.Union([
|
||||
ElectronUpdaterQuitAndInstallError,
|
||||
]);
|
||||
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
|
||||
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
|
||||
|
||||
export class ElectronUpdater extends Context.Service<
|
||||
ElectronUpdater,
|
||||
|
||||
@@ -79,7 +79,6 @@ describe("ElectronWindow", () => {
|
||||
const error = yield* electronWindow.create(options).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
|
||||
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
|
||||
assert.deepEqual(error.options, {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
|
||||
@@ -58,8 +58,6 @@ export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronW
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
|
||||
@@ -41,7 +41,6 @@ describe("DesktopIpc", () => {
|
||||
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
|
||||
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "invoke");
|
||||
assert.strictEqual(error.channel, invokeMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
@@ -69,7 +68,6 @@ describe("DesktopIpc", () => {
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
|
||||
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
|
||||
assert.strictEqual(error.handlerKind, "sync");
|
||||
assert.strictEqual(error.channel, syncMethod.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
|
||||
@@ -55,7 +55,6 @@ export const DesktopIpcError = Schema.Union([
|
||||
DesktopIpcUnregistrationError,
|
||||
]);
|
||||
export type DesktopIpcError = typeof DesktopIpcError.Type;
|
||||
export const isDesktopIpcError = Schema.is(DesktopIpcError);
|
||||
|
||||
export interface DesktopIpcMethod<E, R> {
|
||||
readonly channel: string;
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
fetchSshEnvironmentDescriptor,
|
||||
fetchSshSessionState,
|
||||
issueSshWebSocketTicket,
|
||||
resolveSshHost,
|
||||
resolveSshPasswordPrompt,
|
||||
} from "./methods/sshEnvironment.ts";
|
||||
import {
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
getSystemLocale,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
openSystemSettings,
|
||||
probeRemoteEditors,
|
||||
pickFolder,
|
||||
pickProjectFavicon,
|
||||
@@ -68,6 +70,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(clearConnectionCatalog);
|
||||
|
||||
yield* ipc.handle(discoverSshHosts);
|
||||
yield* ipc.handle(resolveSshHost);
|
||||
yield* ipc.handle(ensureSshEnvironment);
|
||||
yield* ipc.handle(disconnectSshEnvironment);
|
||||
yield* ipc.handle(fetchSshEnvironmentDescriptor);
|
||||
@@ -92,6 +95,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
yield* ipc.handle(openSystemSettings);
|
||||
yield* ipc.handle(probeRemoteEditors);
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
@@ -101,4 +105,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
for (const previewMethod of PreviewIpc.methods) {
|
||||
yield* ipc.handle(previewMethod);
|
||||
}
|
||||
yield* ipc.handle(PreviewIpc.listBrowserImportSources);
|
||||
yield* ipc.handle(PreviewIpc.importBrowserCookies);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings";
|
||||
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
|
||||
@@ -29,6 +30,7 @@ export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
|
||||
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
|
||||
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
export const RESOLVE_SSH_HOST_CHANNEL = "desktop:resolve-ssh-host";
|
||||
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
export const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
||||
@@ -63,6 +65,8 @@ export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
|
||||
export const PREVIEW_IMPORT_SOURCES_CHANNEL = "desktop:preview-import-sources";
|
||||
export const PREVIEW_IMPORT_COOKIES_CHANNEL = "desktop:preview-import-cookies";
|
||||
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
|
||||
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
|
||||
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { PreviewAutomationStatus } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_ID,
|
||||
INCOGNITO_BROWSER_PROFILE_ID,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -8,6 +12,7 @@ import * as Schema from "effect/Schema";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
|
||||
import * as PreviewIpc from "./preview.ts";
|
||||
|
||||
const { fromPartition } = vi.hoisted(() => ({
|
||||
@@ -38,6 +43,76 @@ describe("preview IPC methods", () => {
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("derives distinct partition scopes when identifiers contain the delimiter", () => {
|
||||
const first = PreviewIpc.resolvePartitionScope("a", "b::c");
|
||||
const second = PreviewIpc.resolvePartitionScope("a::b", "c");
|
||||
|
||||
expect(first).toEqual({ scope: '["a","b::c"]', persistent: true, namespace: "profile" });
|
||||
expect(second).toEqual({ scope: '["a::b","c"]', persistent: true, namespace: "profile" });
|
||||
expect(first.scope).not.toBe(second.scope);
|
||||
});
|
||||
|
||||
it("preserves lone surrogates without collapsing them to replacement characters", () => {
|
||||
const highSurrogate = PreviewIpc.resolvePartitionScope("environment", "profile-\ud800");
|
||||
const lowSurrogate = PreviewIpc.resolvePartitionScope("environment", "profile-\udc00");
|
||||
const replacement = PreviewIpc.resolvePartitionScope("environment", "profile-�");
|
||||
|
||||
expect(highSurrogate.scope).toBe('["environment","profile-\\ud800"]');
|
||||
expect(lowSurrogate.scope).toBe('["environment","profile-\\udc00"]');
|
||||
expect(highSurrogate.scope).not.toBe(lowSurrogate.scope);
|
||||
expect(highSurrogate.scope).not.toBe(replacement.scope);
|
||||
expect(lowSurrogate.scope).not.toBe(replacement.scope);
|
||||
});
|
||||
|
||||
it("keeps the legacy default partition scope and incognito persistence", () => {
|
||||
expect(PreviewIpc.resolvePartitionScope("environment::legacy", undefined)).toEqual({
|
||||
scope: "environment::legacy",
|
||||
persistent: true,
|
||||
});
|
||||
expect(
|
||||
PreviewIpc.resolvePartitionScope("environment::legacy", DEFAULT_BROWSER_PROFILE_ID),
|
||||
).toEqual({ scope: "environment::legacy", persistent: true });
|
||||
expect(
|
||||
PreviewIpc.resolvePartitionScope("environment::legacy", INCOGNITO_BROWSER_PROFILE_ID),
|
||||
).toEqual({
|
||||
scope: '["environment::legacy","incognito"]',
|
||||
persistent: false,
|
||||
namespace: "profile",
|
||||
});
|
||||
});
|
||||
|
||||
effectIt.effect("targets imports at the same partition tuple as the renderer", () => {
|
||||
const received: Array<Parameters<BrowserImport.BrowserImport["Service"]["importCookies"]>[0]> =
|
||||
[];
|
||||
const browserImport = BrowserImport.BrowserImport.of({
|
||||
listSources: Effect.succeed([]),
|
||||
importCookies: (input) =>
|
||||
Effect.sync(() => {
|
||||
received.push(input);
|
||||
return { imported: 0, skipped: 0, skippedDomains: [] };
|
||||
}),
|
||||
});
|
||||
const request = (environmentId: string, targetProfileId: string) =>
|
||||
PreviewIpc.importBrowserCookies.handler({
|
||||
environmentId,
|
||||
sourceId: "helium",
|
||||
sourceProfileDirectory: "Default",
|
||||
targetProfileId,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* request("a", "b");
|
||||
yield* request("a::b", DEFAULT_BROWSER_PROFILE_ID);
|
||||
|
||||
expect(received[0]).toMatchObject(PreviewIpc.resolvePartitionScope("a", "b"));
|
||||
expect(received[1]).toMatchObject(
|
||||
PreviewIpc.resolvePartitionScope("a::b", DEFAULT_BROWSER_PROFILE_ID),
|
||||
);
|
||||
expect(received[0]?.namespace).toBe("profile");
|
||||
expect(received[1]?.namespace).toBeUndefined();
|
||||
}).pipe(Effect.provideService(BrowserImport.BrowserImport, browserImport));
|
||||
});
|
||||
|
||||
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
|
||||
Effect.map(
|
||||
PreviewIpc.registerWebview
|
||||
|
||||
@@ -16,17 +16,24 @@ import {
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetAudioMutedInputSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
BrowserImportResult,
|
||||
BrowserImportSource,
|
||||
DesktopPreviewClearDataInputSchema,
|
||||
DesktopPreviewImportCookiesInputSchema,
|
||||
DesktopPreviewCreateTabInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
DEFAULT_BROWSER_PROFILE_ID,
|
||||
INCOGNITO_BROWSER_PROFILE_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
@@ -196,39 +203,130 @@ export const closePictureInPicture = tabMethod(
|
||||
|
||||
export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
payload: DesktopPreviewClearDataInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* ({ environmentId, profileId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCookies();
|
||||
yield* manager.clearCookies(yield* resolveClearPartitions(manager, environmentId, profileId));
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
payload: DesktopPreviewClearDataInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* ({ environmentId, profileId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCache();
|
||||
yield* manager.clearCache(yield* resolveClearPartitions(manager, environmentId, profileId));
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Partition scope for an (environment, profile) pair.
|
||||
*
|
||||
* The default profile keeps the bare environment id it used before profiles
|
||||
* existed, so upgrading does not strand anyone's existing logins in an
|
||||
* orphaned partition. Incognito derives a non-persistent partition.
|
||||
*/
|
||||
export function resolvePartitionScope(
|
||||
environmentId: string,
|
||||
profileId: string | undefined,
|
||||
): {
|
||||
readonly scope: string;
|
||||
readonly persistent: boolean;
|
||||
readonly namespace?: "profile";
|
||||
} {
|
||||
if (profileId === undefined || profileId === DEFAULT_BROWSER_PROFILE_ID) {
|
||||
return { scope: environmentId, persistent: true };
|
||||
}
|
||||
// JSON's tuple framing is injective for strings, including lone UTF-16
|
||||
// surrogates (which it escapes). URI encoding throws on those supported ids,
|
||||
// while replacing them with U+FFFD would collapse distinct identities.
|
||||
return {
|
||||
scope: JSON.stringify([environmentId, profileId]),
|
||||
persistent: profileId !== INCOGNITO_BROWSER_PROFILE_ID,
|
||||
namespace: "profile" as const,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clearing without a profile keeps the historical "everything" behaviour for
|
||||
* an explicit all-profiles action; naming a profile confines it to that
|
||||
* profile's partition so one profile's sign-out cannot reach the others.
|
||||
*/
|
||||
const resolveClearPartitions = Effect.fn("desktop.ipc.preview.resolveClearPartitions")(function* (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
environmentId: string,
|
||||
profileId: string | undefined,
|
||||
) {
|
||||
if (profileId === undefined) return undefined;
|
||||
const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId);
|
||||
// Loading the session is what puts the partition in the map the clear walks.
|
||||
// Deriving the partition string alone leaves nothing to match, so clearing a
|
||||
// profile with no tab open this run — after a restart, or when deleting a
|
||||
// profile — would report success and delete nothing.
|
||||
yield* manager.getBrowserSession(scope, persistent, namespace);
|
||||
return [yield* manager.getBrowserPartition(scope, persistent, namespace)];
|
||||
});
|
||||
|
||||
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId, profileId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.getBrowserSession(environmentId);
|
||||
const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId);
|
||||
// Creating the session first is what installs the UA rewrite and permission
|
||||
// handlers; a guest that attached to an untouched partition would run with
|
||||
// Electron's default UA and Chromium's default permission behaviour.
|
||||
yield* manager.getBrowserSession(scope, persistent, namespace);
|
||||
return {
|
||||
partition: yield* manager.getBrowserPartition(environmentId),
|
||||
partition: yield* manager.getBrowserPartition(scope, persistent, namespace),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Registered separately from `methods`: these carry `BrowserImport` in their
|
||||
* context and their own failure type, so they do not unify with the
|
||||
* manager-backed handlers the shared loop iterates.
|
||||
*/
|
||||
export const listBrowserImportSources = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Array(BrowserImportSource),
|
||||
handler: Effect.fn("desktop.ipc.preview.listBrowserImportSources")(function* () {
|
||||
const browserImport = yield* BrowserImport.BrowserImport;
|
||||
return yield* browserImport.listSources;
|
||||
}),
|
||||
});
|
||||
|
||||
export const importBrowserCookies = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_IMPORT_COOKIES_CHANNEL,
|
||||
payload: DesktopPreviewImportCookiesInputSchema,
|
||||
result: BrowserImportResult,
|
||||
handler: Effect.fn("desktop.ipc.preview.importBrowserCookies")(function* ({
|
||||
environmentId,
|
||||
...importInput
|
||||
}) {
|
||||
const browserImport = yield* BrowserImport.BrowserImport;
|
||||
// Derived in main from the same helper the webview config uses, so cookies
|
||||
// land in exactly the partition the profile's tabs attach to.
|
||||
const { scope, persistent, namespace } = resolvePartitionScope(
|
||||
environmentId,
|
||||
importInput.targetProfileId,
|
||||
);
|
||||
return yield* browserImport.importCookies({
|
||||
input: importInput,
|
||||
scope,
|
||||
persistent,
|
||||
...(namespace === undefined ? {} : { namespace }),
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
|
||||
@@ -117,6 +117,16 @@ export const discoverSshHosts = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const resolveSshHost = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.RESOLVE_SSH_HOST_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: DesktopSshEnvironmentTargetSchema,
|
||||
handler: Effect.fn("desktop.ipc.sshEnvironment.resolveHost")(function* (alias) {
|
||||
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
|
||||
return yield* sshEnvironment.resolveHost(alias);
|
||||
}),
|
||||
});
|
||||
|
||||
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
|
||||
payload: DesktopSshEnvironmentEnsureInputSchema,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
REMOTE_CAPABLE_EDITOR_IDS,
|
||||
SystemSettingsPaneSchema,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type PickedThemeFile,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -298,6 +299,16 @@ export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const openSystemSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
|
||||
payload: SystemSettingsPaneSchema,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
|
||||
const shell = yield* ElectronShell.ElectronShell;
|
||||
return yield* shell.openSystemSettings(pane);
|
||||
}),
|
||||
});
|
||||
|
||||
export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
resolveLinuxSecretStorageUnavailableMessage,
|
||||
} from "./linuxSecretStorage.ts";
|
||||
|
||||
const autoSwitch = (env: NodeJS.ProcessEnv) =>
|
||||
@@ -124,80 +123,4 @@ describe("linuxSecretStorage", () => {
|
||||
}),
|
||||
).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "gnome-libsecret",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet6",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet",
|
||||
selectedBackend: "gnome-libsecret",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
});
|
||||
|
||||
it("uses KWallet remediation wording for KDE-looking sessions", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "kwallet6",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { DESKTOP_SESSION: "plasmawayland" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
// A desktop name outranks a bare KDE marker when choosing the wording.
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
});
|
||||
@@ -25,9 +25,6 @@ const ELECTRON_KDE_DESKTOP = "KDE";
|
||||
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
|
||||
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
|
||||
|
||||
const KDE_NAME_PREFIXES = ["kde", "plasma"];
|
||||
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
export function normalizeLinuxPasswordStorePreference(
|
||||
value: unknown,
|
||||
): LinuxPasswordStorePreference {
|
||||
@@ -77,102 +74,6 @@ function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveLinuxSecretStorageUnavailableMessage(input: {
|
||||
readonly configuredPreference: LinuxPasswordStorePreference;
|
||||
readonly selectedBackend: string | null;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): string {
|
||||
if (input.configuredPreference === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
input.configuredPreference === "kwallet" ||
|
||||
input.configuredPreference === "kwallet5" ||
|
||||
input.configuredPreference === "kwallet6"
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
|
||||
if (backend === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
backend === "kwallet" ||
|
||||
backend === "kwallet5" ||
|
||||
backend === "kwallet6" ||
|
||||
looksLikeKdeSession(input.env)
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
function getGnomeKeyringRemediationMessage(): string {
|
||||
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
|
||||
}
|
||||
|
||||
function getKWalletRemediationMessage(): string {
|
||||
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
|
||||
}
|
||||
|
||||
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
|
||||
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
|
||||
// rather than an unprotected credential store.
|
||||
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
|
||||
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
|
||||
if (currentDesktopNames.length > 0) {
|
||||
return currentDesktopNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
const legacyNames = legacyDesktopNames(env);
|
||||
if (legacyNames.length > 0) {
|
||||
return legacyNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
|
||||
}
|
||||
|
||||
function isKdeDesktopName(name: string): boolean {
|
||||
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
|
||||
}
|
||||
|
||||
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
|
||||
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonEmptyDesktopNames(value: string | undefined): string[] {
|
||||
return splitDesktopNameList(value).flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function isSet(value: string | undefined): boolean {
|
||||
return Boolean(value?.trim());
|
||||
}
|
||||
|
||||
function isAffirmativeFlag(value: string | undefined): boolean {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
|
||||
}
|
||||
|
||||
function splitDesktopNameList(value: string | undefined): string[] {
|
||||
return value?.split(":") ?? [];
|
||||
}
|
||||
|
||||
function normalizeDesktopName(value: string | undefined): string | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedStorageBackend(value: string | null): string | null {
|
||||
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
@@ -58,6 +58,8 @@ import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
|
||||
import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
@@ -149,6 +151,9 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
);
|
||||
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
// Merged rather than provided so the IPC handlers can reach the import
|
||||
// service alongside the manager; both sit on the same BrowserSession.
|
||||
Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
|
||||
Layer.provideMerge(BrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
@@ -60,6 +60,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
|
||||
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
resolveSshHost: (alias) => ipcRenderer.invoke(IpcChannels.RESOLVE_SSH_HOST_CHANNEL, alias),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
await ipcRenderer.invoke(IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL, {
|
||||
@@ -115,6 +116,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
...(position === undefined ? {} : { position }),
|
||||
}),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
|
||||
openSystemSettings: (pane: string) =>
|
||||
ipcRenderer.invoke(IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL, pane),
|
||||
probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
@@ -222,10 +225,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
|
||||
getPreviewConfig: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
|
||||
listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL),
|
||||
importBrowserCookies: (input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_COOKIES_CHANNEL, input),
|
||||
clearCookies: (environmentId, profileId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, { environmentId, profileId }),
|
||||
clearCache: (environmentId, profileId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, { environmentId, profileId }),
|
||||
getPreviewConfig: (environmentId, profileId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId, profileId }),
|
||||
setAnnotationTheme: (theme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
|
||||
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// @effect-diagnostics globalDate:off - This isolated Electron preload does not run inside an Effect runtime.
|
||||
import type { DesktopPreviewRecordingFrame } from "@t3tools/contracts";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
|
||||
export const previewAnnotationStyles =
|
||||
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
|
||||
'/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', \'Noto Sans\', Arial, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring:where(:not(iframe)) {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: 0px;\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\Line truncated
|
||||
@@ -0,0 +1,212 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as BrowserSession from "../BrowserSession.ts";
|
||||
import * as BrowserImport from "./BrowserImport.ts";
|
||||
import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts";
|
||||
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
|
||||
|
||||
const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
|
||||
|
||||
const cookie = {
|
||||
url: "https://rejected.example/path",
|
||||
name: "session",
|
||||
value: "value",
|
||||
domain: undefined,
|
||||
path: "/",
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
expirationDate: undefined,
|
||||
sameSite: "lax" as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Dies if the import reaches session work: every case here covers a request
|
||||
* that must be rejected before a cookie is read or written.
|
||||
*/
|
||||
const rejectedBeforeSession = Layer.succeed(
|
||||
BrowserSession.BrowserSession,
|
||||
BrowserSession.BrowserSession.of({
|
||||
getPartition: () => Effect.die("getPartition must not be reached"),
|
||||
isPartition: () => false,
|
||||
getSession: () => Effect.die("getSession must not be reached"),
|
||||
clearCookies: () => Effect.die("clearCookies must not be reached"),
|
||||
clearCache: () => Effect.die("clearCache must not be reached"),
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* Builds the service against a scratch home containing an installed, closed
|
||||
* copy of the source browser.
|
||||
*/
|
||||
const withImporter = Effect.fnUntraced(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-import-" });
|
||||
const environment = Layer.succeed(HostProcessEnvironment, { HOME: home });
|
||||
const context = yield* sourcePathContext.pipe(
|
||||
Effect.provideService(HostProcessEnvironment, { HOME: home }),
|
||||
Effect.provideService(HostProcessPlatform, "darwin"),
|
||||
);
|
||||
const root = helium.userDataDirectory(context);
|
||||
if (root === undefined) throw new Error("Helium has no macOS user-data directory");
|
||||
yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
|
||||
// The cookie database is what marks a source as installed, so a fixture
|
||||
// without one is reported as absent before any other check runs.
|
||||
yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
|
||||
|
||||
const importer = yield* BrowserImport.BrowserImport.pipe(
|
||||
Effect.provide(
|
||||
BrowserImport.layer.pipe(
|
||||
Layer.provide(rejectedBeforeSession),
|
||||
Layer.provide(environment),
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
|
||||
Layer.provide(Layer.succeed(HostProcessExecutablePath, "/Applications/T3 Code.app")),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { importer, home, root };
|
||||
});
|
||||
|
||||
describe("BrowserImport.importCookies", () => {
|
||||
it.effect("rejects a source profile the browser never reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { importer, home } = yield* withImporter();
|
||||
|
||||
// A cookie database reachable on disk but outside the browser's
|
||||
// user-data directory — the payoff a traversal would be after.
|
||||
yield* fileSystem.makeDirectory(`${home}/secrets`, { recursive: true });
|
||||
yield* fileSystem.writeFileString(`${home}/secrets/Cookies`, "not-a-db");
|
||||
|
||||
const error = yield* importer
|
||||
.importCookies({
|
||||
input: {
|
||||
sourceId: "helium",
|
||||
sourceProfileDirectory: "../../../../secrets",
|
||||
targetProfileId: "default",
|
||||
},
|
||||
scope: "persist:t3code-preview-test",
|
||||
persistent: true,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
|
||||
assert.equal(error.reason, "unknownSourceProfile");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect.skipIf(!symlinksSupported)(
|
||||
"refuses to import while the source browser holds its profile",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { importer, root } = yield* withImporter();
|
||||
// The lock Chromium leaves while it is running, dangling target and
|
||||
// all. This must stop the import before it ever asks the keychain.
|
||||
yield* fileSystem.symlink("host-that-does-not-exist-1234", `${root}/SingletonLock`);
|
||||
|
||||
const error = yield* importer
|
||||
.importCookies({
|
||||
input: {
|
||||
sourceId: "helium",
|
||||
sourceProfileDirectory: "Default",
|
||||
targetProfileId: "default",
|
||||
},
|
||||
scope: "persist:t3code-preview-test",
|
||||
persistent: true,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.reason, "browserRunning");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
|
||||
describe("BrowserImport.writeCookies", () => {
|
||||
it.effect("counts a rejected cookie and its domain as skipped", () =>
|
||||
Effect.gen(function* () {
|
||||
let flushes = 0;
|
||||
const result = yield* BrowserImport.writeCookies(
|
||||
{
|
||||
cookies: {
|
||||
set: () => Promise.reject(new Error("fixture rejection")),
|
||||
flushStore: () => {
|
||||
flushes += 1;
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
{ cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
|
||||
);
|
||||
|
||||
assert.deepEqual(result, {
|
||||
imported: 0,
|
||||
skipped: 1,
|
||||
skippedDomains: ["rejected.example"],
|
||||
});
|
||||
// Nothing landed, so there is nothing to persist.
|
||||
assert.equal(flushes, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("flushes the store after writing, and reports success if the flush fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const events: Array<string> = [];
|
||||
const result = yield* BrowserImport.writeCookies(
|
||||
{
|
||||
cookies: {
|
||||
set: () => {
|
||||
events.push("set");
|
||||
return Promise.resolve();
|
||||
},
|
||||
flushStore: () => {
|
||||
events.push("flush");
|
||||
return Promise.reject(new Error("fixture flush failure"));
|
||||
},
|
||||
},
|
||||
},
|
||||
{ cookies: [cookie, cookie], undecryptable: 0, undecryptableHosts: [] },
|
||||
);
|
||||
|
||||
// One flush after every write, not one per cookie; the cookies are in
|
||||
// the session either way, so a failed flush is not a failed import.
|
||||
assert.deepEqual(events, ["set", "set", "flush"]);
|
||||
assert.deepEqual(result, { imported: 2, skipped: 0, skippedDomains: [] });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates interruption while writing a cookie", () =>
|
||||
Effect.gen(function* () {
|
||||
const write = BrowserImport.writeCookies(
|
||||
{
|
||||
cookies: {
|
||||
set: () => new Promise<void>(() => {}),
|
||||
flushStore: () => Promise.resolve(),
|
||||
},
|
||||
},
|
||||
{ cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
|
||||
);
|
||||
|
||||
const interrupted = yield* Ref.make(false);
|
||||
const fiber = yield* write.pipe(
|
||||
Effect.onInterrupt(() => Ref.set(interrupted, true)),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Fiber.interrupt(fiber);
|
||||
|
||||
assert.isTrue(yield* Ref.get(interrupted));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
/**
|
||||
* Browser import service - lists importable sources and writes their cookies
|
||||
* into a T3 Code browser profile's Electron partition.
|
||||
*
|
||||
* @module BrowserImport
|
||||
*/
|
||||
import type {
|
||||
BrowserImportInput,
|
||||
BrowserImportResult,
|
||||
BrowserImportSource,
|
||||
BrowserImportUnavailableReason,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserImportFailureReason } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type { Session } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as BrowserSession from "../BrowserSession.ts";
|
||||
import { ChromiumCookieReadError, readChromiumCookies } from "./ChromiumCookies.ts";
|
||||
import type { CookieReadResult } from "./CookieDatabase.ts";
|
||||
import { FirefoxCookieReadError, readFirefoxCookies } from "./FirefoxCookies.ts";
|
||||
import { readSafariCookies, safariAccessDenied, SafariCookieReadError } from "./SafariCookies.ts";
|
||||
import {
|
||||
BROWSER_IMPORT_SOURCES,
|
||||
resolveCookieDatabase,
|
||||
isSourceInstalled,
|
||||
isSourceRunning,
|
||||
listSourceProfiles,
|
||||
sourcePathContext,
|
||||
type BrowserImportPathContext,
|
||||
type BrowserImportSourceDefinition,
|
||||
} from "./Sources.ts";
|
||||
|
||||
export class BrowserImportFailedError extends Schema.TaggedErrorClass<BrowserImportFailedError>()(
|
||||
"BrowserImportFailedError",
|
||||
{
|
||||
sourceId: Schema.String,
|
||||
reason: BrowserImportFailureReason,
|
||||
/** Kept for the log; the user only ever sees the reason's copy. */
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
// The reason token is part of the message on purpose: IPC flattens the error
|
||||
// to its message, and the renderer maps that token back to user-facing copy.
|
||||
override get message(): string {
|
||||
return `Importing cookies from ${this.sourceId} failed: ${this.reason}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserCookieWriteError extends Schema.TaggedErrorClass<BrowserCookieWriteError>()(
|
||||
"BrowserCookieWriteError",
|
||||
{
|
||||
url: Schema.String,
|
||||
name: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not write imported cookie ${this.name} for ${this.url}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserImport extends Context.Service<
|
||||
BrowserImport,
|
||||
{
|
||||
readonly listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>>;
|
||||
readonly importCookies: (input: {
|
||||
readonly input: BrowserImportInput;
|
||||
/** Partition scope of the target profile, derived by the caller in main. */
|
||||
readonly scope: string;
|
||||
readonly persistent: boolean;
|
||||
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
|
||||
}) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
|
||||
|
||||
const unavailableReason = Effect.fn("BrowserImport.unavailableReason")(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
): Effect.fn.Return<
|
||||
BrowserImportUnavailableReason | undefined,
|
||||
never,
|
||||
FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
if (!definition.platforms.includes(context.platform)) return "unsupportedPlatform";
|
||||
if (!(yield* isSourceInstalled(definition, context))) return "notInstalled";
|
||||
if (yield* isSourceRunning(definition, context)) return "browserRunning";
|
||||
// Safari's jar is found by `stat`, which TCC permits without Full Disk
|
||||
// Access — so a Safari that lists as ready may still refuse the read. Probe
|
||||
// the grant here, so the wizard can open on the permission step and a
|
||||
// post-grant recheck can tell granted from still-denied, rather than only
|
||||
// discovering it by attempting the import.
|
||||
if (definition.engine === "safari") {
|
||||
const jar = yield* resolveCookieDatabase(definition, context, ".");
|
||||
if (jar !== undefined && (yield* safariAccessDenied(jar))) return "needsFullDiskAccess";
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
/** The host a constructed cookie URL points at, for naming what was skipped. */
|
||||
const cookieHost = (url: string): string => {
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
|
||||
session: { readonly cookies: Pick<Session["cookies"], "set" | "flushStore"> },
|
||||
read: CookieReadResult,
|
||||
) {
|
||||
let imported = 0;
|
||||
let skipped = read.undecryptable;
|
||||
const skippedDomains = new Set(read.undecryptableHosts);
|
||||
for (const cookie of read.cookies) {
|
||||
const written = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
session.cookies.set({
|
||||
url: cookie.url,
|
||||
name: cookie.name,
|
||||
value: cookie.value,
|
||||
// Omitted for host-only cookies: Electron reads any `domain` as a
|
||||
// domain cookie and re-adds the leading dot, widening its scope.
|
||||
...(cookie.domain === undefined ? {} : { domain: cookie.domain }),
|
||||
path: cookie.path,
|
||||
secure: cookie.secure,
|
||||
httpOnly: cookie.httpOnly,
|
||||
sameSite: cookie.sameSite,
|
||||
...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
|
||||
}),
|
||||
catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }),
|
||||
}).pipe(
|
||||
Effect.as(true),
|
||||
Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
|
||||
Effect.catchTags({ BrowserCookieWriteError: () => Effect.succeed(false) }),
|
||||
);
|
||||
if (written) {
|
||||
imported += 1;
|
||||
} else {
|
||||
skipped += 1;
|
||||
skippedDomains.add(cookieHost(cookie.url));
|
||||
}
|
||||
}
|
||||
// `set` resolves once the cookie is in memory; Chromium writes the store to
|
||||
// disk on its own schedule. Flush before reporting "Done", so a crash right
|
||||
// after does not lose what the user was just told was imported. A failed
|
||||
// flush is logged rather than surfaced: the cookies are still in the
|
||||
// session and land on disk at the next scheduled write.
|
||||
if (imported > 0) {
|
||||
yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) };
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* BrowserImportMake() {
|
||||
const browserSession = yield* BrowserSession.BrowserSession;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const executablePath = yield* HostProcessExecutablePath;
|
||||
// Captured here so the service's methods stay free of a requirements
|
||||
// channel: the layer is built where NodeServices is already in scope.
|
||||
const platformServices = yield* Effect.context<
|
||||
FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
|
||||
>();
|
||||
const pathContext = yield* sourcePathContext;
|
||||
|
||||
const listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>> = Effect.forEach(
|
||||
BROWSER_IMPORT_SOURCES,
|
||||
Effect.fnUntraced(function* (definition) {
|
||||
const unavailable = yield* unavailableReason(definition, pathContext);
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
// Listing profiles touches the source's own files, so skip it when the
|
||||
// source is unusable anyway.
|
||||
profiles:
|
||||
unavailable === undefined ? yield* listSourceProfiles(definition, pathContext) : [],
|
||||
...(unavailable === undefined ? {} : { unavailable }),
|
||||
} satisfies BrowserImportSource;
|
||||
}),
|
||||
).pipe(Effect.provide(platformServices));
|
||||
|
||||
const importCookies = Effect.fn("BrowserImport.importCookies")(function* (input: {
|
||||
readonly input: BrowserImportInput;
|
||||
readonly scope: string;
|
||||
readonly persistent: boolean;
|
||||
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
|
||||
}) {
|
||||
const definition = BROWSER_IMPORT_SOURCES.find(
|
||||
(candidate) => candidate.id === input.input.sourceId,
|
||||
);
|
||||
if (!definition) {
|
||||
return yield* new BrowserImportFailedError({
|
||||
sourceId: input.input.sourceId,
|
||||
reason: "unknownSource",
|
||||
});
|
||||
}
|
||||
|
||||
const blocked = yield* unavailableReason(definition, pathContext).pipe(
|
||||
Effect.provide(platformServices),
|
||||
);
|
||||
if (blocked !== undefined) {
|
||||
return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: blocked });
|
||||
}
|
||||
|
||||
if (platform === "darwin" && definition.engine === "chromium") {
|
||||
// macOS attributes the Keychain prompt and the resulting ACL grant to the
|
||||
// executable that asks, so record which one that was — in a packaged build
|
||||
// it is the signed app, in dev whatever binary hosts the main process.
|
||||
yield* Effect.logInfo("Reading browser cookie key from the keychain", {
|
||||
sourceId: definition.id,
|
||||
executablePath,
|
||||
});
|
||||
}
|
||||
|
||||
// The profile directory arrives over IPC, so it is only honoured when the
|
||||
// source itself reported it. Forwarding it unchecked would let `..`
|
||||
// segments walk out of the browser's user-data directory and read any
|
||||
// cookie database reachable on disk.
|
||||
const sourceProfiles = yield* listSourceProfiles(definition, pathContext).pipe(
|
||||
Effect.provide(platformServices),
|
||||
);
|
||||
const requestedProfile = sourceProfiles.find(
|
||||
(profile) => profile.directory === input.input.sourceProfileDirectory,
|
||||
);
|
||||
if (requestedProfile === undefined) {
|
||||
return yield* new BrowserImportFailedError({
|
||||
sourceId: definition.id,
|
||||
reason: "unknownSourceProfile",
|
||||
});
|
||||
}
|
||||
|
||||
// The profile was listed against a database moments ago; resolve it again
|
||||
// rather than assume a path, since a Chromium jar may sit under `Network/`.
|
||||
const databasePath = yield* resolveCookieDatabase(
|
||||
definition,
|
||||
pathContext,
|
||||
requestedProfile.directory,
|
||||
).pipe(Effect.provide(platformServices));
|
||||
if (databasePath === undefined) {
|
||||
// A profile we listed moments ago can lose its database before the
|
||||
// import runs (browser data cleanup, a profile reset). That is a read
|
||||
// failure, not a platform problem.
|
||||
return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed" });
|
||||
}
|
||||
|
||||
// Both branches fail with a tagged error, so the union stays structurally
|
||||
// identifiable and each tag is handled on its own below. The success side
|
||||
// is normalized to one shape too, so the skipped tally survives either
|
||||
// engine — Firefox stores plaintext, so nothing there is ever unreadable.
|
||||
const userDataDirectory = definition.userDataDirectory(pathContext);
|
||||
const read: Effect.Effect<
|
||||
CookieReadResult,
|
||||
ChromiumCookieReadError | FirefoxCookieReadError | SafariCookieReadError,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
|
||||
> =
|
||||
definition.engine === "safari"
|
||||
? readSafariCookies(databasePath).pipe(
|
||||
Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
|
||||
)
|
||||
: definition.engine === "firefox"
|
||||
? readFirefoxCookies(databasePath).pipe(
|
||||
Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
|
||||
)
|
||||
: readChromiumCookies({
|
||||
cookieDatabasePath: databasePath,
|
||||
keychainService: definition.keychainService,
|
||||
keychainAccount: definition.keychainAccount,
|
||||
linuxSecretApplication: definition.linuxSecretApplication,
|
||||
...(platform === "win32" && userDataDirectory !== undefined
|
||||
? {
|
||||
windowsLocalStatePath: pathContext.path.join(userDataDirectory, "Local State"),
|
||||
}
|
||||
: {}),
|
||||
platform,
|
||||
});
|
||||
|
||||
const result = yield* read.pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(platformServices),
|
||||
Effect.catchTags({
|
||||
ChromiumCookieReadError: (cause) =>
|
||||
Effect.fail(
|
||||
new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
|
||||
),
|
||||
// Firefox has one failure mode — its plaintext database would not open
|
||||
// — so its error carries no reason of its own and the user-facing one
|
||||
// is supplied here.
|
||||
FirefoxCookieReadError: (cause) =>
|
||||
Effect.fail(
|
||||
new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed", cause }),
|
||||
),
|
||||
// Safari's reasons are already user-facing: a TCC refusal is the Full
|
||||
// Disk Access prompt, anything else is a read failure.
|
||||
SafariCookieReadError: (cause) =>
|
||||
Effect.fail(
|
||||
new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const session = yield* browserSession
|
||||
.getSession(input.scope, input.persistent, input.namespace)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserImportFailedError({
|
||||
sourceId: definition.id,
|
||||
reason: "sessionUnavailable",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Written one at a time rather than in parallel: Chromium's cookie store
|
||||
// serialises writes anyway, and a rejected cookie should only cost itself.
|
||||
return yield* writeCookies(session, result);
|
||||
});
|
||||
|
||||
return BrowserImport.of({ listSources, importCookies });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BrowserImport, make);
|
||||
@@ -0,0 +1,493 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Encrypts fixtures with the same
|
||||
// OSCrypt primitives the module under test decrypts.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import {
|
||||
decryptChromiumValue,
|
||||
readChromiumCookieDatabase,
|
||||
readChromiumCookies,
|
||||
} from "./ChromiumCookies.ts";
|
||||
import { ChromiumKeyError } from "./ChromiumKeys.ts";
|
||||
import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
|
||||
import { cookieScope } from "./CookieDatabase.ts";
|
||||
|
||||
const encryptChromium = (
|
||||
prefix: "v10" | "v11",
|
||||
value: string | Buffer,
|
||||
key: Buffer,
|
||||
): Uint8Array => {
|
||||
const cipher = NodeCrypto.createCipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
|
||||
return Buffer.concat([Buffer.from(prefix), cipher.update(value), cipher.final()]);
|
||||
};
|
||||
|
||||
const encryptV10 = (value: string | Buffer, key: Buffer): Uint8Array =>
|
||||
encryptChromium("v10", value, key);
|
||||
|
||||
const encryptWindowsV10 = (value: string | Buffer, key: Buffer): Uint8Array => {
|
||||
const nonce = Buffer.from("0123456789ab");
|
||||
const cipher = NodeCrypto.createCipheriv("aes-256-gcm", key, nonce);
|
||||
const encrypted = Buffer.concat([cipher.update(value), cipher.final()]);
|
||||
return Buffer.concat([Buffer.from("v10"), nonce, encrypted, cipher.getAuthTag()]);
|
||||
};
|
||||
|
||||
describe("cookieScope", () => {
|
||||
it("keeps a host-only cookie host-only", () => {
|
||||
// Chromium stores a host-only cookie without a leading dot. Passing any
|
||||
// `domain` to Electron makes it a domain cookie and re-adds the dot, which
|
||||
// would expose the cookie to every subdomain it was never scoped to.
|
||||
expect(cookieScope("example.test", "/", true)).toEqual({
|
||||
url: "https://example.test/",
|
||||
domain: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a domain cookie's leading dot", () => {
|
||||
expect(cookieScope(".example.test", "/app", true)).toEqual({
|
||||
url: "https://example.test/app",
|
||||
domain: ".example.test",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches the scheme to the secure flag", () => {
|
||||
expect(cookieScope("example.test", "/", false).url).toBe("http://example.test/");
|
||||
});
|
||||
|
||||
it("brackets bare IPv6 hosts without duplicating existing brackets", () => {
|
||||
expect(cookieScope("::1", "/", false)).toEqual({
|
||||
url: "http://[::1]/",
|
||||
domain: undefined,
|
||||
});
|
||||
expect(cookieScope("[::1]", "/app", true)).toEqual({
|
||||
url: "https://[::1]/app",
|
||||
domain: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("readChromiumCookieDatabase", () => {
|
||||
it("decrypts Windows v10 AES-GCM records and rejects app-bound v20 records", () => {
|
||||
const key = Buffer.from("0123456789abcdef0123456789abcdef");
|
||||
const host = ".example.test";
|
||||
const bound = Buffer.concat([
|
||||
NodeCrypto.createHash("sha256").update(host).digest(),
|
||||
Buffer.from("windows value"),
|
||||
]);
|
||||
|
||||
expect(
|
||||
decryptChromiumValue(encryptWindowsV10(bound, key), { gcmV10: key }, host, 24, "win32"),
|
||||
).toBe("windows value");
|
||||
expect(
|
||||
decryptChromiumValue(Buffer.from("v20app-bound"), { gcmV10: key }, host, 24, "win32"),
|
||||
).toBeNull();
|
||||
expect(
|
||||
decryptChromiumValue(
|
||||
encryptWindowsV10(bound, Buffer.alloc(32, 1)),
|
||||
{ gcmV10: key },
|
||||
host,
|
||||
24,
|
||||
"win32",
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"reports the missing key when no cookies can be read, while preserving partial imports",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-missing-key-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', 23)`;
|
||||
yield* sql`create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)`;
|
||||
yield* sql`insert into cookies values ('v11.example', 'session', '', ${encryptChromium("v11", "secret", key)}, '/', 0, 1, 1, 1, '')`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const error = yield* readChromiumCookies({
|
||||
cookieDatabasePath: filename,
|
||||
platform: "linux",
|
||||
linuxSecretApplication: "chromium",
|
||||
keychainService: undefined,
|
||||
keychainAccount: undefined,
|
||||
}).pipe(Effect.provideService(LinuxBrowserSecretPath, undefined), Effect.flip);
|
||||
expect(error.reason).toBe("keychainUnavailable");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`insert into cookies values ('v10.example', 'readable', '', ${encryptV10("kept", key)}, '/', 0, 1, 1, 1, '')`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
const keys = {
|
||||
cbcV10: key,
|
||||
cbcV11Error: new ChromiumKeyError({ reason: "keychainUnavailable" }),
|
||||
};
|
||||
const partial = yield* readChromiumCookieDatabase(filename, keys, "linux");
|
||||
expect(partial.cookies.map((cookie) => cookie.value)).toEqual(["kept"]);
|
||||
expect(partial.undecryptable).toBe(1);
|
||||
|
||||
// A partitioned-only jar does not need its key: it is skipped separately.
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`delete from cookies where name = 'readable'`;
|
||||
yield* sql`update cookies set top_frame_site_key = 'https://top.example'`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
const partitioned = yield* readChromiumCookieDatabase(filename, keys, "linux");
|
||||
expect(partitioned.cookies).toEqual([]);
|
||||
expect(partitioned.undecryptable).toBe(1);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', 23)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null,
|
||||
name text not null,
|
||||
value text not null,
|
||||
encrypted_value blob not null,
|
||||
path text not null,
|
||||
expires_utc integer not null,
|
||||
is_secure integer not null,
|
||||
is_httponly integer not null,
|
||||
samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('plain.example', 'plain', 'stored plaintext', ${new Uint8Array()}, '/', 0, 0, 0, -1)
|
||||
`;
|
||||
yield* sql`
|
||||
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('secure.example', 'encrypted', '', ${encryptV10("stored encrypted", key)}, '/', 0, 1, 1, 2)
|
||||
`;
|
||||
yield* sql`
|
||||
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)
|
||||
`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
|
||||
|
||||
expect(result.undecryptable).toBe(0);
|
||||
expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "plain", value: "stored plaintext" },
|
||||
{ name: "encrypted", value: "stored encrypted" },
|
||||
{ name: "empty", value: "" },
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("enforces domain binding only for schema 24 and newer", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
const boundValue = (host: string, value: string) =>
|
||||
Buffer.concat([NodeCrypto.createHash("sha256").update(host).digest(), Buffer.from(value)]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', 24)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('bound.example', 'valid', '', ${encryptV10(boundValue("bound.example", "kept"), key)}, '/', 0, 1, 0, 0)`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('wrong.example', 'mismatch', '', ${encryptV10(boundValue("another.example", "drop"), key)}, '/', 0, 1, 0, 0)`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('short.example', 'short', '', ${encryptV10("short value", key)}, '/', 0, 1, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
|
||||
|
||||
expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "valid", value: "kept" },
|
||||
]);
|
||||
expect(result.undecryptable).toBe(2);
|
||||
expect(result.undecryptableHosts).toEqual(["wrong.example", "short.example"]);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("decrypts mixed v10 and v11 cookies with their respective keys", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const cbcV10 = Buffer.from("0123456789abcdef");
|
||||
const cbcV11 = Buffer.from("fedcba9876543210");
|
||||
const boundValue = (host: string, value: string) =>
|
||||
Buffer.concat([NodeCrypto.createHash("sha256").update(host).digest(), Buffer.from(value)]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', '24')`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('v10.example', 'v10-cookie', '', ${encryptChromium("v10", boundValue("v10.example", "v10 value"), cbcV10)}, '/', 0, 1, 0, 0)`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('v11.example', 'v11-cookie', '', ${encryptChromium("v11", boundValue("v11.example", "v11 value"), cbcV11)}, '/', 0, 1, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const complete = yield* readChromiumCookieDatabase(filename, { cbcV10, cbcV11 }, "linux");
|
||||
expect(complete.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "v10-cookie", value: "v10 value" },
|
||||
{ name: "v11-cookie", value: "v11 value" },
|
||||
]);
|
||||
expect(complete.undecryptable).toBe(0);
|
||||
|
||||
const v10Only = yield* readChromiumCookieDatabase(filename, { cbcV10 }, "linux");
|
||||
expect(v10Only.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "v10-cookie", value: "v10 value" },
|
||||
]);
|
||||
expect(v10Only.undecryptable).toBe(1);
|
||||
expect(v10Only.undecryptableHosts).toEqual(["v11.example"]);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("recovers records written with the empty-passphrase key", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const cbcV10 = Buffer.from("0123456789abcdef");
|
||||
const cbcV11 = Buffer.from("fedcba9876543210");
|
||||
// The key some Linux clients actually encrypted with (crbug.com/1195256):
|
||||
// OSCrypt's derivation over an empty passphrase.
|
||||
const cbcEmpty = NodeCrypto.pbkdf2Sync("", "saltysalt", 1, 16, "sha1");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', '23')`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('ev10.example', 'empty-v10', '', ${encryptChromium("v10", "empty v10 value", cbcEmpty)}, '/', 0, 1, 0, 0)`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('ev11.example', 'empty-v11', '', ${encryptChromium("v11", "empty v11 value", cbcEmpty)}, '/', 0, 1, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
// The records' own keys fail, and the empty key recovers both — the
|
||||
// retry Chromium itself performs.
|
||||
const recovered = yield* readChromiumCookieDatabase(
|
||||
filename,
|
||||
{ cbcV10, cbcV11, cbcEmpty },
|
||||
"linux",
|
||||
);
|
||||
expect(recovered.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "empty-v10", value: "empty v10 value" },
|
||||
{ name: "empty-v11", value: "empty v11 value" },
|
||||
]);
|
||||
expect(recovered.undecryptable).toBe(0);
|
||||
|
||||
// Matching Chromium: a record whose own key is missing entirely is not
|
||||
// retried with the empty key.
|
||||
const noV11 = yield* readChromiumCookieDatabase(filename, { cbcV10, cbcEmpty }, "linux");
|
||||
expect(noV11.cookies.map(({ name }) => name)).toEqual(["empty-v10"]);
|
||||
expect(noV11.undecryptableHosts).toEqual(["ev11.example"]);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("preserves arbitrary long encrypted values from pre-24 schemas", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
const value = "x".repeat(32) + " legacy value";
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', 23)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('legacy.example', 'legacy', '', ${encryptV10(value, key)}, '/', 0, 0, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
|
||||
expect(result.cookies[0]?.value).toBe(value);
|
||||
expect(result.undecryptable).toBe(0);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("rejects a malformed text schema version", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value text not null)`;
|
||||
yield* sql`insert into meta values ('version', 'not-a-version')`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
const error = yield* readChromiumCookieDatabase(
|
||||
filename,
|
||||
{ cbcV10: Buffer.from("0123456789abcdef") },
|
||||
"darwin",
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("SchemaError");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("treats unversioned encrypted values as legacy plaintext on macOS and Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const filename = `${directory}/Cookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value integer not null)`;
|
||||
yield* sql`insert into meta values ('version', 23)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null default ''
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
|
||||
('legacy.example', 'legacy', '', ${Buffer.from("legacy cleartext")}, '/', 0, 0, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
|
||||
|
||||
// Chromium's OSCrypt returns unprefixed data as-is on both platforms
|
||||
// (os_crypt_mac.mm and os_crypt_linux.cc: "old data saved as clear
|
||||
// text"), so neither counts it as undecryptable.
|
||||
const mac = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
|
||||
const linux = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "linux");
|
||||
|
||||
expect(mac.cookies[0]?.value).toBe("legacy cleartext");
|
||||
expect(mac.undecryptable).toBe(0);
|
||||
expect(linux.cookies[0]?.value).toBe("legacy cleartext");
|
||||
expect(linux.undecryptable).toBe(0);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-chromium-cookies-",
|
||||
});
|
||||
const legacyFilename = `${directory}/LegacyCookies`;
|
||||
const chipsFilename = `${directory}/ChipsCookies`;
|
||||
const key = Buffer.from("0123456789abcdef");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value integer not null)`;
|
||||
yield* sql`insert into meta values ('version', 14)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies values
|
||||
('legacy.example', 'legacy', 'kept', ${new Uint8Array()}, '/', 0, 0, 0, 0)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacyFilename })));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`create table meta (key text primary key, value integer not null)`;
|
||||
yield* sql`insert into meta values ('version', 23)`;
|
||||
yield* sql`
|
||||
create table cookies (
|
||||
host_key text not null, name text not null, value text not null,
|
||||
encrypted_value blob not null, path text not null, expires_utc integer not null,
|
||||
is_secure integer not null, is_httponly integer not null, samesite integer not null,
|
||||
top_frame_site_key text not null
|
||||
)
|
||||
`;
|
||||
yield* sql`insert into cookies values
|
||||
('plain.example', 'plain', 'kept', ${new Uint8Array()}, '/', 0, 0, 0, 0, '')`;
|
||||
yield* sql`insert into cookies values
|
||||
('partitioned.example', 'partitioned', 'must skip', ${new Uint8Array()}, '/', 0, 1, 0, 0, 'https://top.example')`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: chipsFilename })));
|
||||
|
||||
const legacy = yield* readChromiumCookieDatabase(legacyFilename, { cbcV10: key }, "darwin");
|
||||
const chips = yield* readChromiumCookieDatabase(chipsFilename, { cbcV10: key }, "darwin");
|
||||
|
||||
expect(legacy.cookies.map(({ name }) => name)).toEqual(["legacy"]);
|
||||
expect(legacy.undecryptable).toBe(0);
|
||||
expect(chips.cookies.map(({ name }) => name)).toEqual(["plain"]);
|
||||
expect(chips.undecryptable).toBe(1);
|
||||
expect(chips.undecryptableHosts).toEqual(["partitioned.example"]);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
|
||||
// OSCrypt primitives Chromium uses; Effect has no equivalent.
|
||||
/**
|
||||
* Chromium cookie extraction.
|
||||
*
|
||||
* Reads a Chromium-family browser's cookie database and decrypts each record
|
||||
* with the key its prefix calls for. Key acquisition — and the consent it
|
||||
* needs — lives in `ChromiumKeys`.
|
||||
*
|
||||
* Records whose scheme we hold no key for are skipped rather than failing the
|
||||
* whole import: a Linux database can mix `v10` and `v11`. A partial result
|
||||
* reported honestly is more useful than an all-or-nothing error.
|
||||
*
|
||||
* @module ChromiumCookies
|
||||
*/
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
ChromiumKeyError,
|
||||
ChromiumKeyFailure,
|
||||
readWindowsKey,
|
||||
resolveChromiumKeys,
|
||||
type ChromiumKeyMaterial,
|
||||
} from "./ChromiumKeys.ts";
|
||||
import {
|
||||
bareHost,
|
||||
cookieScope,
|
||||
snapshotCookieDatabase,
|
||||
type CookieReadResult,
|
||||
type ImportedCookie,
|
||||
} from "./CookieDatabase.ts";
|
||||
|
||||
/** OSCrypt's CBC mode uses a fixed IV of 16 spaces rather than a per-record one. */
|
||||
const AES_CBC_IV = Buffer.alloc(16, 0x20);
|
||||
const AES_GCM_NONCE_LENGTH = 12;
|
||||
const AES_GCM_TAG_LENGTH = 16;
|
||||
const isChromiumKeyError = Schema.is(ChromiumKeyError);
|
||||
|
||||
/**
|
||||
* Every way the read can fail: the key failures, plus the ones this module
|
||||
* raises itself.
|
||||
*/
|
||||
export const ChromiumCookieReadReason = Schema.Literals([
|
||||
// `readFailed` already comes from the key failures, so it is not repeated.
|
||||
...ChromiumKeyFailure.literals,
|
||||
"browserRunning",
|
||||
]);
|
||||
export type ChromiumCookieReadReason = typeof ChromiumCookieReadReason.Type;
|
||||
|
||||
export class ChromiumCookieReadError extends Schema.TaggedErrorClass<ChromiumCookieReadError>()(
|
||||
"ChromiumCookieReadError",
|
||||
{
|
||||
reason: ChromiumCookieReadReason,
|
||||
/**
|
||||
* Which database the read was for. Without it every `readFailed` and
|
||||
* keychain failure logs identically, and a user with several browsers
|
||||
* installed has no way to tell which one refused.
|
||||
*/
|
||||
cookieDatabasePath: Schema.String,
|
||||
/** Kept for the log; never surfaced to the user. */
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not read Chromium cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Row shape of the cookie table, decoded rather than cast. */
|
||||
const CookieRow = Schema.Struct({
|
||||
host_key: Schema.String,
|
||||
name: Schema.String,
|
||||
value: Schema.String,
|
||||
encrypted_value: Schema.Uint8Array,
|
||||
path: Schema.String,
|
||||
expires_seconds: Schema.Number,
|
||||
is_secure: Schema.Number,
|
||||
is_httponly: Schema.Number,
|
||||
samesite: Schema.Number,
|
||||
top_frame_site_key: Schema.String,
|
||||
});
|
||||
const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow));
|
||||
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
|
||||
const SchemaVersion = Schema.Union([
|
||||
NonNegativeInt,
|
||||
Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
|
||||
]);
|
||||
const decodeSchemaVersion = Schema.decodeUnknownEffect(
|
||||
Schema.Tuple([Schema.Struct({ value: SchemaVersion })]),
|
||||
);
|
||||
|
||||
/**
|
||||
* Chromium stores `SameSite` as an int: -1 = unspecified, 0 = none, 1 = lax,
|
||||
* 2 = strict. Unspecified is imported as Electron's own `unspecified` rather
|
||||
* than pinned to Lax, so the target browser applies its default just as the
|
||||
* source did; anything unrecognised lands there too, since guessing "none"
|
||||
* would widen a cookie's scope on import.
|
||||
*/
|
||||
const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => {
|
||||
if (value === 0) return "no_restriction";
|
||||
if (value === 1) return "lax";
|
||||
if (value === 2) return "strict";
|
||||
return "unspecified";
|
||||
};
|
||||
|
||||
/**
|
||||
* Chromium timestamps count microseconds from 1601-01-01; Electron wants
|
||||
* seconds from the UNIX epoch. The microsecond value overflows JavaScript's
|
||||
* safe integer range and `node:sqlite` refuses to narrow it, so the division
|
||||
* happens in SQL and this only ever sees seconds.
|
||||
*/
|
||||
const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600;
|
||||
const toUnixSeconds = (webkitSeconds: number): number | undefined => {
|
||||
if (webkitSeconds <= 0) return undefined;
|
||||
return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS;
|
||||
};
|
||||
|
||||
/**
|
||||
* Chromium >= 127 prefixes the plaintext with SHA-256 of the host key, binding
|
||||
* a cookie to its domain. Strip it when present.
|
||||
*/
|
||||
const stripDomainBinding = (
|
||||
plaintext: Buffer,
|
||||
domain: string,
|
||||
schemaVersion: number,
|
||||
): Buffer | null => {
|
||||
if (schemaVersion < 24) return plaintext;
|
||||
const domainHash = NodeCrypto.createHash("sha256").update(domain).digest();
|
||||
return plaintext.length >= 32 && plaintext.subarray(0, 32).equals(domainHash)
|
||||
? plaintext.subarray(32)
|
||||
: null;
|
||||
};
|
||||
|
||||
const decryptCbc = (
|
||||
payload: Buffer,
|
||||
key: Buffer,
|
||||
domain: string,
|
||||
schemaVersion: number,
|
||||
): string | null => {
|
||||
try {
|
||||
const decipher = NodeCrypto.createDecipheriv("aes-128-cbc", key, AES_CBC_IV);
|
||||
decipher.setAutoPadding(true);
|
||||
const plaintext = Buffer.concat([decipher.update(payload), decipher.final()]);
|
||||
return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const decryptGcm = (
|
||||
payload: Buffer,
|
||||
key: Buffer,
|
||||
domain: string,
|
||||
schemaVersion: number,
|
||||
): string | null => {
|
||||
if (payload.length < AES_GCM_NONCE_LENGTH + AES_GCM_TAG_LENGTH) return null;
|
||||
try {
|
||||
const nonce = payload.subarray(0, AES_GCM_NONCE_LENGTH);
|
||||
const ciphertext = payload.subarray(AES_GCM_NONCE_LENGTH, -AES_GCM_TAG_LENGTH);
|
||||
const tag = payload.subarray(-AES_GCM_TAG_LENGTH);
|
||||
const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", key, nonce);
|
||||
decipher.setAuthTag(tag);
|
||||
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrypts one stored value, choosing the scheme from its prefix. Returns null
|
||||
* when no key covers that scheme — including Windows' app-bound `v20`, which
|
||||
* this build has no key for at all.
|
||||
*/
|
||||
export function decryptChromiumValue(
|
||||
encrypted: Uint8Array,
|
||||
keys: ChromiumKeyMaterial,
|
||||
domain: string,
|
||||
schemaVersion = 23,
|
||||
platform: NodeJS.Platform = "linux",
|
||||
): string | null {
|
||||
const buffer = Buffer.from(encrypted);
|
||||
if (buffer.length === 0) return "";
|
||||
const prefix = buffer.subarray(0, 3).toString("latin1");
|
||||
const payload = buffer.subarray(3);
|
||||
|
||||
// Windows' legacy v10 format is AES-256-GCM. App-bound records use v20 and
|
||||
// intentionally have no key here, so they fall through as undecryptable.
|
||||
if (platform === "win32") {
|
||||
return prefix === "v10" && keys.gcmV10
|
||||
? decryptGcm(payload, keys.gcmV10, domain, schemaVersion)
|
||||
: null;
|
||||
}
|
||||
|
||||
// Chromium retries a failed record with a key derived from an empty
|
||||
// passphrase, because some Linux clients wrote data that way
|
||||
// (crbug.com/1195256). A record whose own key is missing entirely stays
|
||||
// skipped, matching Chromium.
|
||||
if (prefix === "v10") {
|
||||
if (!keys.cbcV10) return null;
|
||||
return (
|
||||
decryptCbc(payload, keys.cbcV10, domain, schemaVersion) ??
|
||||
(keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
|
||||
);
|
||||
}
|
||||
if (prefix === "v11") {
|
||||
if (!keys.cbcV11) return null;
|
||||
return (
|
||||
decryptCbc(payload, keys.cbcV11, domain, schemaVersion) ??
|
||||
(keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
|
||||
);
|
||||
}
|
||||
// No recognised prefix: Chromium on macOS and Linux both treat this as
|
||||
// legacy data stored in the clear and return it as-is, so it is a readable
|
||||
// cookie rather than an undecryptable one. Windows is the exception — its
|
||||
// app-bound `v20` blobs also lack these prefixes and must not be read as
|
||||
// plaintext — but Windows Chromium is not importable here at all.
|
||||
if (platform === "darwin" || platform === "linux") {
|
||||
return stripDomainBinding(buffer, domain, schemaVersion)?.toString("utf8") ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Reads and decodes one snapshotted Chromium cookie database. */
|
||||
export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiumCookieDatabase")(
|
||||
function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) {
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
|
||||
Effect.flatMap(decodeSchemaVersion),
|
||||
Effect.map(([row]) => row.value),
|
||||
);
|
||||
const raw =
|
||||
schemaVersion >= 15
|
||||
? yield* sql`select host_key, name, value, encrypted_value, path,
|
||||
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
|
||||
samesite, top_frame_site_key from cookies`
|
||||
: yield* sql`select host_key, name, value, encrypted_value, path,
|
||||
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
|
||||
samesite, '' as top_frame_site_key from cookies`;
|
||||
return { rows: yield* decodeCookieRows(raw), schemaVersion };
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })));
|
||||
|
||||
const cookies: ImportedCookie[] = [];
|
||||
let undecryptable = 0;
|
||||
const undecryptableHosts = new Set<string>();
|
||||
for (const row of result.rows) {
|
||||
if (row.top_frame_site_key !== "") {
|
||||
undecryptable += 1;
|
||||
undecryptableHosts.add(bareHost(row.host_key));
|
||||
continue;
|
||||
}
|
||||
const value =
|
||||
row.encrypted_value.length === 0
|
||||
? row.value
|
||||
: decryptChromiumValue(
|
||||
row.encrypted_value,
|
||||
keys,
|
||||
row.host_key,
|
||||
result.schemaVersion,
|
||||
platform,
|
||||
);
|
||||
if (value === null) {
|
||||
undecryptable += 1;
|
||||
undecryptableHosts.add(bareHost(row.host_key));
|
||||
continue;
|
||||
}
|
||||
const secure = row.is_secure === 1;
|
||||
const scope = cookieScope(row.host_key, row.path, secure);
|
||||
cookies.push({
|
||||
url: scope.url,
|
||||
name: row.name,
|
||||
value,
|
||||
domain: scope.domain,
|
||||
path: row.path,
|
||||
secure,
|
||||
httpOnly: row.is_httponly === 1,
|
||||
expirationDate: toUnixSeconds(row.expires_seconds),
|
||||
sameSite: sameSiteFromColumn(row.samesite),
|
||||
});
|
||||
}
|
||||
// Keep partial imports, but do not call a missing key a successful import
|
||||
// when it prevented every otherwise importable cookie from being read.
|
||||
if (
|
||||
cookies.length === 0 &&
|
||||
keys.cbcV11Error !== undefined &&
|
||||
result.rows.some(
|
||||
(row) =>
|
||||
row.top_frame_site_key === "" &&
|
||||
Buffer.from(row.encrypted_value.subarray(0, 3)).toString("latin1") === "v11",
|
||||
)
|
||||
) {
|
||||
return yield* keys.cbcV11Error;
|
||||
}
|
||||
return {
|
||||
cookies,
|
||||
undecryptable,
|
||||
undecryptableHosts: [...undecryptableHosts],
|
||||
} satisfies CookieReadResult;
|
||||
},
|
||||
);
|
||||
|
||||
export interface ChromiumCookieSource {
|
||||
readonly cookieDatabasePath: string;
|
||||
readonly keychainService: string | undefined;
|
||||
readonly keychainAccount: string | undefined;
|
||||
readonly linuxSecretApplication: string | undefined;
|
||||
readonly windowsLocalStatePath?: string;
|
||||
/** Supplied by the caller from `HostProcessPlatform` rather than read here. */
|
||||
readonly platform: NodeJS.Platform;
|
||||
}
|
||||
|
||||
export const readChromiumCookies = Effect.fn("ChromiumCookies.readChromiumCookies")(function* (
|
||||
source: ChromiumCookieSource,
|
||||
): Effect.fn.Return<
|
||||
CookieReadResult,
|
||||
ChromiumCookieReadError,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const keys = yield* (
|
||||
source.platform === "win32" && source.windowsLocalStatePath
|
||||
? readWindowsKey(source.windowsLocalStatePath).pipe(Effect.map((gcmV10) => ({ gcmV10 })))
|
||||
: resolveChromiumKeys({
|
||||
platform: source.platform,
|
||||
keychainService: source.keychainService,
|
||||
keychainAccount: source.keychainAccount,
|
||||
linuxSecretApplication: source.linuxSecretApplication,
|
||||
})
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause: ChromiumKeyError) =>
|
||||
new ChromiumCookieReadError({
|
||||
reason: cause.reason,
|
||||
cookieDatabasePath: source.cookieDatabasePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const snapshotPath = yield* snapshotCookieDatabase(source.cookieDatabasePath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ChromiumCookieReadError({
|
||||
reason: "readFailed",
|
||||
cookieDatabasePath: source.cookieDatabasePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* readChromiumCookieDatabase(snapshotPath, keys, source.platform).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ChromiumCookieReadError({
|
||||
reason: isChromiumKeyError(cause) ? cause.reason : "readFailed",
|
||||
cookieDatabasePath: source.cookieDatabasePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
ChromiumKeyError,
|
||||
decodeWindowsWrappedKey,
|
||||
readLinuxSecret,
|
||||
resolveChromiumKeys,
|
||||
unwrapWindowsDpapiKey,
|
||||
} from "./ChromiumKeys.ts";
|
||||
import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
|
||||
|
||||
type CapturedCommand = {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: Readonly<Record<string, string | undefined>>;
|
||||
};
|
||||
};
|
||||
|
||||
const helperLayer = (input: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly stdoutStream?: Stream.Stream<Uint8Array>;
|
||||
readonly stderrStream?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: number;
|
||||
readonly spawnError?: PlatformError.PlatformError;
|
||||
readonly capture?: (command: CapturedCommand) => void;
|
||||
}) =>
|
||||
Layer.merge(
|
||||
Layer.succeed(LinuxBrowserSecretPath, "/bundled/browser-secret/t3-browser-secret"),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
input.spawnError
|
||||
? Effect.fail(input.spawnError)
|
||||
: Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: input.stdoutStream ?? Stream.encodeText(Stream.make(input.stdout ?? "")),
|
||||
stderr: input.stderrStream ?? Stream.encodeText(Stream.make(input.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => input.capture?.(command as CapturedCommand))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("Linux Chromium secrets", () => {
|
||||
it.effect("retains a missing helper failure alongside the keyring-free fallback", () =>
|
||||
Effect.gen(function* () {
|
||||
const keys = yield* resolveChromiumKeys({
|
||||
platform: "linux",
|
||||
keychainService: undefined,
|
||||
keychainAccount: undefined,
|
||||
linuxSecretApplication: "chromium",
|
||||
});
|
||||
expect(keys.cbcV10).toHaveLength(16);
|
||||
expect(keys.cbcV11).toBeUndefined();
|
||||
expect(keys.cbcV11Error?.reason).toBe("keychainUnavailable");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({
|
||||
spawnError: PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports an unconfigured helper without searching PATH", () =>
|
||||
readLinuxSecret("chromium").pipe(
|
||||
Effect.flip,
|
||||
Effect.tap((error) => Effect.sync(() => expect(error.reason).toBe("keychainUnavailable"))),
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("must not spawn")),
|
||||
),
|
||||
Effect.provideService(LinuxBrowserSecretPath, undefined),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("looks up the browser's libsecret application attribute", () => {
|
||||
let captured: CapturedCommand | undefined;
|
||||
return Effect.gen(function* () {
|
||||
const keys = yield* resolveChromiumKeys({
|
||||
platform: "linux",
|
||||
keychainService: "ignored macOS service",
|
||||
keychainAccount: "ignored macOS account",
|
||||
linuxSecretApplication: "msedge",
|
||||
});
|
||||
|
||||
expect(captured?.command).toBe("/bundled/browser-secret/t3-browser-secret");
|
||||
expect(captured?.args).toEqual(["msedge"]);
|
||||
expect(captured?.options.stdin).toBe("ignore");
|
||||
expect(keys.cbcV10).toHaveLength(16);
|
||||
expect(keys.cbcV11).toHaveLength(16);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({ stdout: "linux-secret", capture: (value) => (captured = value) }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports an unavailable Secret Service backend as a read failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* readLinuxSecret("chrome").pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(ChromiumKeyError);
|
||||
expect(error.reason).toBe("keychainUnavailable");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({ stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY", exitCode: 1 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves trailing whitespace in the stored secret", () =>
|
||||
Effect.gen(function* () {
|
||||
const secret = yield* readLinuxSecret("chrome");
|
||||
expect(secret).toBe("linux-secret \t\n");
|
||||
}).pipe(Effect.provide(helperLayer({ stdout: "linux-secret \t\n" }))),
|
||||
);
|
||||
|
||||
it.effect("drains stdout and stderr concurrently", () =>
|
||||
Effect.gen(function* () {
|
||||
const stderrDrainStarted = yield* Deferred.make<void>();
|
||||
const stdout = Stream.fromEffect(Deferred.await(stderrDrainStarted)).pipe(
|
||||
Stream.flatMap(() => Stream.encodeText(Stream.make("linux-secret"))),
|
||||
);
|
||||
const stderr = Stream.fromEffect(Deferred.succeed(stderrDrainStarted, undefined)).pipe(
|
||||
Stream.drain,
|
||||
);
|
||||
|
||||
const secret = yield* readLinuxSecret("chrome").pipe(
|
||||
Effect.provide(helperLayer({ stdoutStream: stdout, stderrStream: stderr })),
|
||||
);
|
||||
|
||||
expect(secret).toBe("linux-secret");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"preserves the desktop environment and identifies denial without parsing stderr",
|
||||
() => {
|
||||
let captured: CapturedCommand | undefined;
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* readLinuxSecret("brave").pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(ChromiumKeyError);
|
||||
expect(error.reason).toBe("needsKeychainApproval");
|
||||
expect(captured?.options.env?.LC_ALL).toBe("localized");
|
||||
expect(captured?.options.env?.PATH).toBe("/synthetic/bin");
|
||||
expect(captured?.options.env?.SESSION_MARKER).toBe("kept");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({
|
||||
stderr: "Zugriff verweigert",
|
||||
exitCode: 3,
|
||||
capture: (value) => (captured = value),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
PATH: "/synthetic/bin",
|
||||
SESSION_MARKER: "kept",
|
||||
LC_ALL: "localized",
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("does not discard a denied unlock prompt while resolving keys", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* resolveChromiumKeys({
|
||||
platform: "linux",
|
||||
keychainService: undefined,
|
||||
keychainAccount: undefined,
|
||||
linuxSecretApplication: "brave",
|
||||
}).pipe(Effect.flip);
|
||||
expect(error.reason).toBe("needsKeychainApproval");
|
||||
}).pipe(Effect.provide(helperLayer({ stderr: "Keyring is locked", exitCode: 3 }))),
|
||||
);
|
||||
|
||||
it.effect("keeps the v10 fallback when the Secret Service backend is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const keys = yield* resolveChromiumKeys({
|
||||
platform: "linux",
|
||||
keychainService: undefined,
|
||||
keychainAccount: undefined,
|
||||
linuxSecretApplication: "chrome",
|
||||
});
|
||||
expect(keys.cbcV10).toHaveLength(16);
|
||||
expect(keys.cbcV11).toBeUndefined();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({
|
||||
stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY",
|
||||
exitCode: 1,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps the v10 fallback when no matching v11 secret exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const keys = yield* resolveChromiumKeys({
|
||||
platform: "linux",
|
||||
keychainService: undefined,
|
||||
keychainAccount: undefined,
|
||||
linuxSecretApplication: "vivaldi",
|
||||
});
|
||||
expect(keys.cbcV10).toHaveLength(16);
|
||||
expect(keys.cbcV11).toBeUndefined();
|
||||
}).pipe(Effect.provide(helperLayer({ exitCode: 2 }))),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Windows Chromium secrets", () => {
|
||||
it.effect("accepts only DPAPI-wrapped non-app-bound keys", () =>
|
||||
Effect.gen(function* () {
|
||||
const wrapped = Buffer.from("wrapped-key");
|
||||
const encoded = Buffer.concat([Buffer.from("DPAPI"), wrapped]).toString("base64");
|
||||
const localState = `{"os_crypt":{"encrypted_key":"${encoded}"}}`;
|
||||
expect(yield* decodeWindowsWrappedKey(localState)).toEqual(wrapped);
|
||||
|
||||
const appBound = yield* decodeWindowsWrappedKey(
|
||||
`{"os_crypt":{"encrypted_key":"${encoded}","app_bound_encrypted_key":"present"}}`,
|
||||
).pipe(Effect.flip);
|
||||
expect(appBound.reason).toBe("unsupportedPlatform");
|
||||
|
||||
const malformed = yield* decodeWindowsWrappedKey(
|
||||
`{"os_crypt":{"encrypted_key":"${wrapped.toString("base64")}"}}`,
|
||||
).pipe(Effect.flip);
|
||||
expect(malformed.reason).toBe("readFailed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unwraps the binary key through PowerShell without placing it in argv", () => {
|
||||
let captured: CapturedCommand | undefined;
|
||||
const wrapped = Buffer.from("wrapped-key");
|
||||
const key = Buffer.from("0123456789abcdef0123456789abcdef");
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* unwrapWindowsDpapiKey(wrapped)).toEqual(key);
|
||||
expect(captured?.command).toBe(
|
||||
"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
|
||||
);
|
||||
expect(captured?.args).toContain("-NonInteractive");
|
||||
expect(captured?.args.join(" ")).not.toContain(wrapped.toString("base64"));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
helperLayer({ stdout: key.toString("base64"), capture: (value) => (captured = value) }),
|
||||
),
|
||||
Effect.provideService(HostProcessEnvironment, { SystemRoot: "C:\\Windows" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
|
||||
// OSCrypt key derivation Chromium uses; Effect has no equivalent.
|
||||
/**
|
||||
* Chromium cookie-encryption keys, per platform.
|
||||
*
|
||||
* Chromium calls this OSCrypt, and it works differently on each OS:
|
||||
*
|
||||
* - **macOS** keeps one key in the login keychain. Reading it prompts the
|
||||
* user, which is the consent this feature is built around.
|
||||
* - **Linux** may keep a key in libsecret/kwallet (`v11` records), or use a
|
||||
* hardcoded `peanuts` passphrase when no keyring is available (`v10`). Both
|
||||
* can appear in the same database, so both are derived up front and chosen
|
||||
* per record.
|
||||
*
|
||||
* - **Windows** legacy Chromium stores protect a random AES key with DPAPI.
|
||||
* App-Bound Encryption remains deliberately unsupported.
|
||||
*
|
||||
* @module ChromiumKeys
|
||||
*/
|
||||
import * as Keyring from "@napi-rs/keyring";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
|
||||
|
||||
const KEY_SALT = "saltysalt";
|
||||
const KEY_LENGTH = 16;
|
||||
/** macOS stretches the keychain secret; Linux uses a single iteration. */
|
||||
const MAC_KEY_ITERATIONS = 1003;
|
||||
const LINUX_KEY_ITERATIONS = 1;
|
||||
/** Chromium's documented fallback passphrase when no Linux keyring is present. */
|
||||
const LINUX_FALLBACK_PASSPHRASE = "peanuts";
|
||||
|
||||
export const ChromiumKeyFailure = Schema.Literals([
|
||||
"needsKeychainApproval",
|
||||
"keychainItemMissing",
|
||||
"keychainUnavailable",
|
||||
"unsupportedPlatform",
|
||||
/** The key store itself could not be read, as opposed to holding no key. */
|
||||
"readFailed",
|
||||
]);
|
||||
export type ChromiumKeyFailure = typeof ChromiumKeyFailure.Type;
|
||||
|
||||
export class ChromiumKeyError extends Schema.TaggedErrorClass<ChromiumKeyError>()(
|
||||
"ChromiumKeyError",
|
||||
{
|
||||
reason: ChromiumKeyFailure,
|
||||
/** Kept for the log; never surfaced to the user. */
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not obtain the Chromium cookie key: ${this.reason}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys to try, indexed by the record prefix they decrypt. A database can hold
|
||||
* records written under more than one scheme, so a missing entry means those
|
||||
* records are skipped rather than the whole import failing.
|
||||
*/
|
||||
export interface ChromiumKeyMaterial {
|
||||
/** AES-128-CBC on macOS, and the keyring-free Linux fallback. */
|
||||
readonly cbcV10?: Buffer;
|
||||
/** AES-128-CBC, Linux keyring-derived. */
|
||||
readonly cbcV11?: Buffer;
|
||||
/** Retained so an import that needs this key can report why it is missing. */
|
||||
readonly cbcV11Error?: ChromiumKeyError;
|
||||
/**
|
||||
* AES-128-CBC from an empty passphrase. Some Linux clients wrote records
|
||||
* with it (crbug.com/1195256), so Chromium — and this import — retry with it
|
||||
* after a record's own key fails.
|
||||
*/
|
||||
readonly cbcEmpty?: Buffer;
|
||||
/** AES-256-GCM key used by pre-App-Bound Chromium on Windows. */
|
||||
readonly gcmV10?: Buffer;
|
||||
}
|
||||
|
||||
const derive = (passphrase: string, iterations: number) =>
|
||||
NodeCrypto.pbkdf2Sync(passphrase, KEY_SALT, iterations, KEY_LENGTH, "sha1");
|
||||
|
||||
/**
|
||||
* Reads the macOS OSCrypt secret from the login keychain.
|
||||
*
|
||||
* Uses the in-process Keychain API rather than shelling out to
|
||||
* `/usr/bin/security`, because macOS attributes both the consent prompt and the
|
||||
* resulting ACL entry to the binary that asks. Via the CLI the prompt says
|
||||
* "security" and "Always Allow" grants trust to a tool every process on the
|
||||
* machine can invoke; in-process it names this app and the grant belongs to it.
|
||||
* (In an unsigned dev build the name is the dev binary, not the shipped app
|
||||
* identity.)
|
||||
*
|
||||
* Deliberately untimed: macOS answers this with a modal, and a timeout racing
|
||||
* the user means the prompt can be approved while nothing is left listening,
|
||||
* which reads as "approving did nothing".
|
||||
*/
|
||||
const readKeychainSecret = Effect.fn("ChromiumKeys.readKeychainSecret")(function* (
|
||||
service: string,
|
||||
account: string,
|
||||
) {
|
||||
const secret = yield* Effect.try({
|
||||
try: () => new Keyring.Entry(service, account).getPassword(),
|
||||
catch: (cause) => {
|
||||
const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
|
||||
// Distinguish the causes rather than reporting "approve the prompt" for
|
||||
// a failure approving cannot fix.
|
||||
const missing = /no (matching )?entry|not found/i.test(message);
|
||||
return new ChromiumKeyError({
|
||||
reason: missing ? "keychainItemMissing" : "needsKeychainApproval",
|
||||
cause,
|
||||
});
|
||||
},
|
||||
});
|
||||
if (secret === null || secret === "") {
|
||||
return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
|
||||
}
|
||||
return secret;
|
||||
});
|
||||
|
||||
/**
|
||||
* The bundled helper searches Chromium's libsecret schema and application
|
||||
* attribute, retaining the desktop's normal unlock prompt. Its exit codes
|
||||
* distinguish a missing key, denied access, and an unavailable keyring without
|
||||
* parsing localized error messages. Stdout is the unmodified secret.
|
||||
*/
|
||||
export const readLinuxSecret = Effect.fn("ChromiumKeys.readLinuxSecret")(function* (
|
||||
application: string,
|
||||
) {
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
const helper = yield* LinuxBrowserSecretPath;
|
||||
if (helper === undefined) {
|
||||
return yield* new ChromiumKeyError({ reason: "keychainUnavailable" });
|
||||
}
|
||||
const handle = yield* spawner
|
||||
.spawn(ChildProcess.make(helper, [application], { stdin: "ignore", env: environment }))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
|
||||
),
|
||||
);
|
||||
const [secret, , exitCode] = yield* Effect.all(
|
||||
[
|
||||
handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
|
||||
handle.stderr.pipe(Stream.runDrain),
|
||||
handle.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.mapError((cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause })),
|
||||
);
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* new ChromiumKeyError({
|
||||
reason:
|
||||
Number(exitCode) === 2
|
||||
? "keychainItemMissing"
|
||||
: Number(exitCode) === 3
|
||||
? "needsKeychainApproval"
|
||||
: "keychainUnavailable",
|
||||
});
|
||||
}
|
||||
if (secret === "") {
|
||||
return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
|
||||
}
|
||||
return secret;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const WindowsLocalState = Schema.Struct({
|
||||
os_crypt: Schema.Struct({
|
||||
encrypted_key: Schema.String,
|
||||
app_bound_encrypted_key: Schema.optional(Schema.String),
|
||||
}),
|
||||
});
|
||||
const decodeWindowsLocalState = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(WindowsLocalState),
|
||||
);
|
||||
const DPAPI_PREFIX = Buffer.from("DPAPI");
|
||||
const WINDOWS_KEY_LENGTH = 32;
|
||||
const WINDOWS_DPAPI_SCRIPT =
|
||||
"Add-Type -AssemblyName System.Security;" +
|
||||
"$value=[Console]::In.ReadToEnd();" +
|
||||
"$encrypted=[Convert]::FromBase64String($value);" +
|
||||
"$plain=[Security.Cryptography.ProtectedData]::Unprotect($encrypted,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);" +
|
||||
"[Console]::Out.Write([Convert]::ToBase64String($plain))";
|
||||
|
||||
export const decodeWindowsWrappedKey = Effect.fn("ChromiumKeys.decodeWindowsWrappedKey")(function* (
|
||||
contents: string,
|
||||
) {
|
||||
const state = yield* decodeWindowsLocalState(contents).pipe(
|
||||
Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
|
||||
);
|
||||
if (state.os_crypt.app_bound_encrypted_key !== undefined) {
|
||||
return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
|
||||
}
|
||||
const wrapped = yield* Effect.fromResult(
|
||||
Encoding.decodeBase64(state.os_crypt.encrypted_key),
|
||||
).pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
|
||||
const wrappedBuffer = Buffer.from(wrapped);
|
||||
if (!wrappedBuffer.subarray(0, DPAPI_PREFIX.length).equals(DPAPI_PREFIX)) {
|
||||
return yield* new ChromiumKeyError({ reason: "readFailed" });
|
||||
}
|
||||
return wrappedBuffer.subarray(DPAPI_PREFIX.length);
|
||||
});
|
||||
|
||||
/** Unwraps a key with the current Windows user's DPAPI identity. */
|
||||
export const unwrapWindowsDpapiKey = Effect.fn("ChromiumKeys.unwrapWindowsDpapiKey")(function* (
|
||||
wrapped: Buffer,
|
||||
) {
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const windowsRoot = environment.SystemRoot ?? environment.WINDIR;
|
||||
const powershell = windowsRoot
|
||||
? `${windowsRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
|
||||
: "powershell.exe";
|
||||
const handle = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(
|
||||
powershell,
|
||||
[
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-WindowStyle",
|
||||
"Hidden",
|
||||
"-Command",
|
||||
WINDOWS_DPAPI_SCRIPT,
|
||||
],
|
||||
{
|
||||
env: environment,
|
||||
stdin: Stream.encodeText(Stream.make(wrapped.toString("base64"))),
|
||||
},
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
|
||||
),
|
||||
);
|
||||
const [plainEncoded, , exitCode] = yield* Effect.all(
|
||||
[
|
||||
handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
|
||||
handle.stderr.pipe(Stream.runDrain),
|
||||
handle.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* new ChromiumKeyError({ reason: "readFailed" });
|
||||
}
|
||||
const plain = yield* Effect.fromResult(Encoding.decodeBase64(plainEncoded)).pipe(
|
||||
Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
|
||||
);
|
||||
if (plain.length !== WINDOWS_KEY_LENGTH) {
|
||||
return yield* new ChromiumKeyError({ reason: "readFailed" });
|
||||
}
|
||||
return Buffer.from(plain);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
/** Reads and unwraps a legacy Windows Chromium key without exposing it in argv. */
|
||||
export const readWindowsKey = Effect.fn("ChromiumKeys.readWindowsKey")(function* (
|
||||
localStatePath: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const contents = yield* fileSystem
|
||||
.readFileString(localStatePath)
|
||||
.pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
|
||||
return yield* unwrapWindowsDpapiKey(yield* decodeWindowsWrappedKey(contents));
|
||||
});
|
||||
|
||||
export interface ChromiumKeyRequest {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly keychainService: string | undefined;
|
||||
readonly keychainAccount: string | undefined;
|
||||
readonly linuxSecretApplication: string | undefined;
|
||||
}
|
||||
|
||||
export const resolveChromiumKeys = Effect.fn("ChromiumKeys.resolveChromiumKeys")(function* (
|
||||
request: ChromiumKeyRequest,
|
||||
): Effect.fn.Return<
|
||||
ChromiumKeyMaterial,
|
||||
ChromiumKeyError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
if (request.platform === "darwin") {
|
||||
if (!request.keychainService || !request.keychainAccount) {
|
||||
return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
|
||||
}
|
||||
const secret = yield* readKeychainSecret(request.keychainService, request.keychainAccount);
|
||||
return { cbcV10: derive(secret, MAC_KEY_ITERATIONS) };
|
||||
}
|
||||
|
||||
if (request.platform === "linux") {
|
||||
// The fallback passphrase always applies to `v10` records; a keyring
|
||||
// secret, when one is reachable, additionally unlocks `v11`. Preserve its
|
||||
// failure until the reader knows whether any cookies needed that key.
|
||||
const keyringSecret = request.linuxSecretApplication
|
||||
? yield* readLinuxSecret(request.linuxSecretApplication).pipe(
|
||||
// v10 remains importable when Secret Service is absent or does not
|
||||
// contain a key. An explicit denial/lock/cancel remains a consent
|
||||
// failure rather than being silently downgraded.
|
||||
Effect.catch((error) =>
|
||||
error.reason === "needsKeychainApproval" ? Effect.fail(error) : Effect.succeed(error),
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
return {
|
||||
cbcV10: derive(LINUX_FALLBACK_PASSPHRASE, LINUX_KEY_ITERATIONS),
|
||||
...(typeof keyringSecret === "string"
|
||||
? { cbcV11: derive(keyringSecret, LINUX_KEY_ITERATIONS) }
|
||||
: keyringSecret
|
||||
? { cbcV11Error: keyringSecret }
|
||||
: {}),
|
||||
cbcEmpty: derive("", LINUX_KEY_ITERATIONS),
|
||||
};
|
||||
}
|
||||
|
||||
return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { snapshotCookieDatabase } from "./CookieDatabase.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>,
|
||||
) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("snapshotCookieDatabase", () => {
|
||||
it.effect("includes committed WAL data in one consistent database", () =>
|
||||
runNode(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-cookie-source-",
|
||||
});
|
||||
const source = path.join(sourceDirectory, "Cookies");
|
||||
const snapshot = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`PRAGMA journal_mode = WAL`;
|
||||
yield* sql`PRAGMA wal_autocheckpoint = 0`;
|
||||
yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`;
|
||||
yield* sql`INSERT INTO cookies(name) VALUES (${"committed-in-wal"})`;
|
||||
expect(yield* fileSystem.exists(`${source}-wal`)).toBe(true);
|
||||
return yield* snapshotCookieDatabase(source);
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source })));
|
||||
const rows = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
return yield* sql<{ readonly name: string }>`SELECT name FROM cookies`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshot, readonly: true })));
|
||||
expect(rows).toEqual([{ name: "committed-in-wal" }]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("propagates snapshot failures and removes its temporary directory", () =>
|
||||
runNode(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-cookie-invalid-source-",
|
||||
});
|
||||
const source = path.join(sourceDirectory, "Cookies");
|
||||
yield* fileSystem.writeFileString(source, "not a sqlite database");
|
||||
const prefix = `t3code-cookie-failed-${process.pid}-`;
|
||||
const error = yield* snapshotCookieDatabase(source, prefix).pipe(
|
||||
Effect.scoped,
|
||||
Effect.flip,
|
||||
);
|
||||
expect(error._tag).toBe("SqlError");
|
||||
const temporaryEntries = yield* fileSystem.readDirectory(path.dirname(sourceDirectory));
|
||||
expect(temporaryEntries.some((entry) => entry.startsWith(prefix))).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes a successful snapshot when its scope closes", () =>
|
||||
runNode(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-cookie-cleanup-source-",
|
||||
});
|
||||
const source = path.join(sourceDirectory, "Cookies");
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source })));
|
||||
const snapshot = yield* snapshotCookieDatabase(source).pipe(Effect.scoped);
|
||||
expect(yield* fileSystem.exists(snapshot)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Shared pieces of cookie extraction: the shape both engines produce, and the
|
||||
* snapshot every reader takes before touching a live database.
|
||||
*
|
||||
* @module CookieDatabase
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
|
||||
/** A cookie in the shape Electron's `session.cookies.set` accepts. */
|
||||
export interface ImportedCookie {
|
||||
readonly url: string;
|
||||
readonly name: string;
|
||||
readonly value: string;
|
||||
/**
|
||||
* Set only for domain cookies, which the sources mark with a leading dot.
|
||||
* A host-only cookie leaves this undefined: Electron treats any `domain` it
|
||||
* is given as marking a domain cookie and re-adds the dot, which would widen
|
||||
* the cookie to every subdomain of the host it was scoped to, and rejects
|
||||
* `__Host-` cookies, which require it to be absent.
|
||||
*/
|
||||
readonly domain: string | undefined;
|
||||
readonly path: string;
|
||||
readonly secure: boolean;
|
||||
readonly httpOnly: boolean;
|
||||
/** Seconds since the UNIX epoch, or undefined for a session cookie. */
|
||||
readonly expirationDate: number | undefined;
|
||||
readonly sameSite: "unspecified" | "no_restriction" | "lax" | "strict";
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookies recovered from one database and rows that could not be decrypted.
|
||||
* The skipped count reaches the user instead of disappearing from a partial
|
||||
* import result.
|
||||
*/
|
||||
export interface CookieReadResult {
|
||||
readonly cookies: ReadonlyArray<ImportedCookie>;
|
||||
readonly undecryptable: number;
|
||||
/** Distinct hosts of the rows that could not be decrypted. */
|
||||
readonly undecryptableHosts: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL and domain Electron should register a stored row under.
|
||||
*
|
||||
* Both engines mark a domain cookie with a leading dot on the host. Electron
|
||||
* matches on a URL, so the dot comes off for that; `domain` is passed through
|
||||
* only for domain cookies, because supplying it at all makes Electron treat
|
||||
* the cookie as one and re-add the dot — widening a host-only cookie to every
|
||||
* subdomain of the host it was scoped to, and rejecting `__Host-` cookies,
|
||||
* which require it to be absent.
|
||||
*/
|
||||
export const cookieScope = (
|
||||
host: string,
|
||||
path: string,
|
||||
secure: boolean,
|
||||
): { readonly url: string; readonly domain: string | undefined } => {
|
||||
const isDomainCookie = host.startsWith(".");
|
||||
const unwrappedHost = bareHost(host);
|
||||
const authority =
|
||||
unwrappedHost.includes(":") && !(unwrappedHost.startsWith("[") && unwrappedHost.endsWith("]"))
|
||||
? `[${unwrappedHost}]`
|
||||
: unwrappedHost;
|
||||
return {
|
||||
url: `${secure ? "https" : "http"}://${authority}${path}`,
|
||||
domain: isDomainCookie ? host : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
/** A host without the leading dot both engines put on a domain cookie, for display. */
|
||||
export const bareHost = (host: string): string => (host.startsWith(".") ? host.slice(1) : host);
|
||||
|
||||
/**
|
||||
* Creates a transactionally consistent snapshot of a cookie database in a
|
||||
* temporary directory and returns the snapshot's path.
|
||||
*
|
||||
* Both engines keep the file open with WAL while the browser runs, so reading
|
||||
* in place can observe a torn write. Copying also guarantees we never open the
|
||||
* browser's own file for writing.
|
||||
*
|
||||
* Scoped: the temporary directory goes away when the caller's scope closes.
|
||||
*/
|
||||
export const snapshotCookieDatabase = Effect.fn("CookieDatabase.snapshotCookieDatabase")(function* (
|
||||
cookiePath: string,
|
||||
tempPrefix = "t3code-cookie-import-",
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: tempPrefix });
|
||||
const target = path.join(directory, path.basename(cookiePath));
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`VACUUM INTO ${target}`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: cookiePath, readonly: true })));
|
||||
return target;
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Builds a Firefox-shaped
|
||||
// `cookies.sqlite` fixture with the same native bindings Firefox itself uses.
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as NodeSqlite from "node:sqlite";
|
||||
|
||||
import { readFirefoxCookies } from "./FirefoxCookies.ts";
|
||||
import { parseFirefoxProfiles } from "./Sources.ts";
|
||||
|
||||
const parsePosixFirefoxProfiles = (ini: string, root = "/home/user/.mozilla/firefox") =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return parseFirefoxProfiles(ini, path, root);
|
||||
}).pipe(Effect.provide(NodePath.layerPosix));
|
||||
|
||||
const parseWindowsFirefoxProfiles = (ini: string, root = "C:\\Users\\user\\Firefox") =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return parseFirefoxProfiles(ini, path, root);
|
||||
}).pipe(Effect.provide(NodePath.layerWin32));
|
||||
|
||||
/** Builds a `cookies.sqlite` with Firefox's real `moz_cookies` shape. */
|
||||
const writeFirefoxCookieDatabase = Effect.fnUntraced(function* (
|
||||
rows: ReadonlyArray<{
|
||||
host: string;
|
||||
name: string;
|
||||
value: string;
|
||||
path: string;
|
||||
expiry: number;
|
||||
isSecure: number;
|
||||
isHttpOnly: number;
|
||||
sameSite: number | null;
|
||||
rawSameSite?: number;
|
||||
originAttributes?: string;
|
||||
}>,
|
||||
// Firefox stamps `PRAGMA user_version`; schema 16+ stores `expiry` in
|
||||
// milliseconds, earlier ones in seconds.
|
||||
schemaVersion = 15,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-test-" });
|
||||
const file = `${directory}/cookies.sqlite`;
|
||||
const database = new NodeSqlite.DatabaseSync(file);
|
||||
database.exec(`pragma user_version = ${schemaVersion}`);
|
||||
// Only schemas 10–14 have `rawSameSite`; the schema-15 migration dropped it.
|
||||
const hasRawSameSite = schemaVersion >= 10 && schemaVersion <= 14;
|
||||
database.exec(
|
||||
`create table moz_cookies (
|
||||
id integer primary key, host text, name text, value text, path text,
|
||||
expiry integer, isSecure integer, isHttpOnly integer, sameSite integer,
|
||||
${hasRawSameSite ? "rawSameSite integer," : ""}
|
||||
originAttributes text not null default ''
|
||||
)`,
|
||||
);
|
||||
const insert = database.prepare(
|
||||
`insert into moz_cookies
|
||||
(host, name, value, path, expiry, isSecure, isHttpOnly, sameSite,
|
||||
${hasRawSameSite ? "rawSameSite," : ""} originAttributes)
|
||||
values (?, ?, ?, ?, ?, ?, ?, ?, ${hasRawSameSite ? "?," : ""} ?)`,
|
||||
);
|
||||
for (const row of rows) {
|
||||
insert.run(
|
||||
row.host,
|
||||
row.name,
|
||||
row.value,
|
||||
row.path,
|
||||
row.expiry,
|
||||
row.isSecure,
|
||||
row.isHttpOnly,
|
||||
row.sameSite,
|
||||
...(hasRawSameSite ? [row.rawSameSite ?? row.sameSite] : []),
|
||||
row.originAttributes ?? "",
|
||||
);
|
||||
}
|
||||
database.close();
|
||||
return file;
|
||||
});
|
||||
|
||||
const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>) =>
|
||||
effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("readFirefoxCookies", () => {
|
||||
it.effect("converts millisecond expiries from schema 16 and newer", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
// Firefox 129 (schema 16) migrated `expiry` to milliseconds; older
|
||||
// profiles still hold seconds. Both must land as seconds for Electron.
|
||||
const row = {
|
||||
host: "example.test",
|
||||
name: "c",
|
||||
value: "v",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000_000,
|
||||
isSecure: 0,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 0,
|
||||
};
|
||||
const modern = yield* readFirefoxCookies(yield* writeFirefoxCookieDatabase([row], 16));
|
||||
expect(modern[0]?.expirationDate).toBe(1_800_000_000);
|
||||
|
||||
const legacy = yield* readFirefoxCookies(
|
||||
yield* writeFirefoxCookieDatabase([{ ...row, expiry: 1_800_000_000 }], 15),
|
||||
);
|
||||
expect(legacy[0]?.expirationDate).toBe(1_800_000_000);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("maps moz_cookies onto the shape Electron accepts", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* writeFirefoxCookieDatabase([
|
||||
{
|
||||
host: ".github.com",
|
||||
name: "session",
|
||||
value: "abc",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000,
|
||||
isSecure: 1,
|
||||
isHttpOnly: 1,
|
||||
sameSite: 1,
|
||||
},
|
||||
{
|
||||
host: "example.test",
|
||||
name: "plain",
|
||||
value: "v",
|
||||
path: "/app",
|
||||
// Firefox writes 0 for a session cookie.
|
||||
expiry: 0,
|
||||
isSecure: 0,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
const cookies = yield* readFirefoxCookies(file);
|
||||
|
||||
expect(cookies).toEqual([
|
||||
{
|
||||
// The leading dot stays on the domain but not in the URL, which is
|
||||
// what Electron matches against.
|
||||
url: "https://github.com/",
|
||||
name: "session",
|
||||
value: "abc",
|
||||
domain: ".github.com",
|
||||
path: "/",
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
expirationDate: 1_800_000_000,
|
||||
sameSite: "lax",
|
||||
},
|
||||
{
|
||||
url: "http://example.test/app",
|
||||
name: "plain",
|
||||
value: "v",
|
||||
// Host-only in Firefox, so no `domain`: supplying one would make
|
||||
// Electron widen it to every subdomain of example.test.
|
||||
domain: undefined,
|
||||
path: "/app",
|
||||
secure: false,
|
||||
httpOnly: false,
|
||||
// Session cookies carry no expiry rather than one at the epoch.
|
||||
expirationDate: undefined,
|
||||
sameSite: "no_restriction",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps an unset SameSite unspecified instead of widening it to none", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
// nsICookie::SAMESITE_UNSET is 256, a cookie that carried no SameSite
|
||||
// attribute. It is not SAMESITE_NONE (0), which is an explicit opt-in
|
||||
// to cross-site use; importing it as "none" would widen its scope.
|
||||
const row = {
|
||||
host: "example.test",
|
||||
name: "c",
|
||||
value: "v",
|
||||
path: "/",
|
||||
expiry: 0,
|
||||
isSecure: 0,
|
||||
isHttpOnly: 0,
|
||||
};
|
||||
const cookies = yield* readFirefoxCookies(
|
||||
yield* writeFirefoxCookieDatabase([
|
||||
{ ...row, name: "unset", sameSite: 256 },
|
||||
{ ...row, name: "none", sameSite: 0 },
|
||||
]),
|
||||
);
|
||||
expect(cookies.map(({ name, sameSite }) => ({ name, sameSite }))).toEqual([
|
||||
{ name: "unset", sameSite: "unspecified" },
|
||||
{ name: "none", sameSite: "no_restriction" },
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("imports rows whose SameSite was never written", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
// Schema 9 added `sameSite` without a default, so rows from before the
|
||||
// upgrade hold NULL. One such row must not fail the whole import.
|
||||
const row = {
|
||||
host: "example.test",
|
||||
name: "c",
|
||||
value: "v",
|
||||
path: "/",
|
||||
expiry: 0,
|
||||
isSecure: 0,
|
||||
isHttpOnly: 0,
|
||||
};
|
||||
const cookies = yield* readFirefoxCookies(
|
||||
yield* writeFirefoxCookieDatabase(
|
||||
[
|
||||
{ ...row, name: "legacy", sameSite: null },
|
||||
{ ...row, name: "strict", sameSite: 2 },
|
||||
],
|
||||
9,
|
||||
),
|
||||
);
|
||||
expect(cookies.map(({ name, sameSite }) => ({ name, sameSite }))).toEqual([
|
||||
{ name: "legacy", sameSite: "unspecified" },
|
||||
{ name: "strict", sameSite: "strict" },
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("applies the schema-15 rawSameSite rule to older databases", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
// Schemas 10–14 defaulted `sameSite` to Lax and kept the declared value
|
||||
// in `rawSameSite`. Firefox's own migration to 15 turns "Lax by
|
||||
// default, None declared" into Unset; an unmigrated database has to be
|
||||
// read the same way or an undeclared cookie becomes an explicit Lax.
|
||||
const row = {
|
||||
host: "example.test",
|
||||
name: "c",
|
||||
value: "v",
|
||||
path: "/",
|
||||
expiry: 0,
|
||||
isSecure: 0,
|
||||
isHttpOnly: 0,
|
||||
};
|
||||
const cookies = yield* readFirefoxCookies(
|
||||
yield* writeFirefoxCookieDatabase(
|
||||
[
|
||||
{ ...row, name: "defaulted", sameSite: 1, rawSameSite: 0 },
|
||||
{ ...row, name: "declared", sameSite: 1, rawSameSite: 1 },
|
||||
{ ...row, name: "none", sameSite: 0, rawSameSite: 0 },
|
||||
],
|
||||
14,
|
||||
),
|
||||
);
|
||||
expect(cookies.map(({ name, sameSite }) => ({ name, sameSite }))).toEqual([
|
||||
{ name: "defaulted", sameSite: "unspecified" },
|
||||
{ name: "declared", sameSite: "lax" },
|
||||
{ name: "none", sameSite: "no_restriction" },
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("imports only the default container", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* writeFirefoxCookieDatabase([
|
||||
{
|
||||
host: "mail.test",
|
||||
name: "session",
|
||||
value: "default-container",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000,
|
||||
isSecure: 1,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 1,
|
||||
},
|
||||
{
|
||||
// Same host, name and path as above: Firefox keeps these apart by
|
||||
// container, Electron cannot, so importing both would hand the
|
||||
// profile whichever one happened to be written last.
|
||||
host: "mail.test",
|
||||
name: "session",
|
||||
value: "work-container",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000,
|
||||
isSecure: 1,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 1,
|
||||
originAttributes: "^userContextId=2",
|
||||
},
|
||||
{
|
||||
host: "mail.test",
|
||||
name: "private",
|
||||
value: "private-window",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000,
|
||||
isSecure: 1,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 1,
|
||||
originAttributes: "^privateBrowsingId=1",
|
||||
},
|
||||
]);
|
||||
|
||||
const cookies = yield* readFirefoxCookies(file);
|
||||
|
||||
expect(cookies.map((cookie) => cookie.value)).toEqual(["default-container"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads without mutating the source database", () =>
|
||||
run(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const file = yield* writeFirefoxCookieDatabase([
|
||||
{
|
||||
host: "a.test",
|
||||
name: "n",
|
||||
value: "v",
|
||||
path: "/",
|
||||
expiry: 1_800_000_000,
|
||||
isSecure: 1,
|
||||
isHttpOnly: 0,
|
||||
sameSite: 2,
|
||||
},
|
||||
]);
|
||||
const before = yield* fileSystem.stat(file);
|
||||
|
||||
yield* readFirefoxCookies(file);
|
||||
|
||||
// The browser's own file is snapshotted, never opened for writing.
|
||||
const after = yield* fileSystem.stat(file);
|
||||
expect(after.mtime).toEqual(before.mtime);
|
||||
expect(after.size).toBe(before.size);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("parseFirefoxProfiles", () => {
|
||||
it.effect("reads named profiles and ignores Install sections", () =>
|
||||
Effect.gen(function* () {
|
||||
// `Install*` sections name a default profile but do not describe one, so
|
||||
// counting them would invent a profile whose directory does not exist.
|
||||
const parsed = yield* parsePosixFirefoxProfiles(
|
||||
[
|
||||
"[Install4F96D1932A9F858E]",
|
||||
"Default=Profiles/abcd1234.default-release",
|
||||
"Locked=1",
|
||||
"",
|
||||
"[Profile0]",
|
||||
"Name=default-release",
|
||||
"IsRelative=1",
|
||||
"Path=Profiles/abcd1234.default-release",
|
||||
"",
|
||||
"[Profile1]",
|
||||
"Name=Work",
|
||||
"IsRelative=0",
|
||||
"Path=/Volumes/External/firefox-work",
|
||||
"",
|
||||
"[General]",
|
||||
"StartWithLastProfile=1",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(parsed).toEqual([
|
||||
{ directory: "Profiles/abcd1234.default-release", name: "default-release" },
|
||||
{ directory: "/Volumes/External/firefox-work", name: "Work" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the path when a profile has no name", () =>
|
||||
Effect.gen(function* () {
|
||||
expect(
|
||||
yield* parsePosixFirefoxProfiles(["[Profile0]", "Path=Profiles/x.default"].join("\n")),
|
||||
).toEqual([{ directory: "Profiles/x.default", name: "Profiles/x.default" }]);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const [platform, root] of [
|
||||
["Linux", "/home/user/.mozilla/firefox"],
|
||||
["macOS", "/Users/user/Library/Application Support/Firefox"],
|
||||
] as const) {
|
||||
it.effect(`validates relative and absolute ${platform} profile paths`, () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* parsePosixFirefoxProfiles(
|
||||
[
|
||||
"[Profile0]",
|
||||
"Name=Relative",
|
||||
"IsRelative=1",
|
||||
"Path=Profiles/relative.default",
|
||||
"[Profile1]",
|
||||
"Name=Custom",
|
||||
"IsRelative=0",
|
||||
"Path=/mnt/custom/firefox-profile",
|
||||
"[Profile2]",
|
||||
"IsRelative=1",
|
||||
"Path=../../escape",
|
||||
"[Profile3]",
|
||||
"IsRelative=1",
|
||||
"Path=/absolute-marked-relative",
|
||||
"[Profile4]",
|
||||
"IsRelative=0",
|
||||
"Path=relative-marked-absolute",
|
||||
"[Profile5]",
|
||||
"IsRelative=1",
|
||||
"Path=Profiles/nul\u0000escape",
|
||||
].join("\n"),
|
||||
root,
|
||||
);
|
||||
|
||||
expect(parsed).toEqual([
|
||||
{ directory: "Profiles/relative.default", name: "Relative" },
|
||||
{ directory: "/mnt/custom/firefox-profile", name: "Custom" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("uses Windows path rules for relative and absolute profiles", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* parseWindowsFirefoxProfiles(
|
||||
[
|
||||
"[Profile0]",
|
||||
"Name=Relative",
|
||||
"IsRelative=1",
|
||||
"Path=Profiles\\relative.default",
|
||||
"[Profile1]",
|
||||
"Name=Custom",
|
||||
"IsRelative=0",
|
||||
"Path=D:\\Firefox Profiles\\Work",
|
||||
"[Profile2]",
|
||||
"IsRelative=1",
|
||||
"Path=..\\..\\escape",
|
||||
"[Profile3]",
|
||||
"IsRelative=1",
|
||||
"Path=D:\\absolute-marked-relative",
|
||||
"[Profile4]",
|
||||
"IsRelative=0",
|
||||
"Path=relative-marked-absolute",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(parsed).toEqual([
|
||||
{ directory: "Profiles\\relative.default", name: "Relative" },
|
||||
{ directory: "D:\\Firefox Profiles\\Work", name: "Custom" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* Firefox cookie extraction.
|
||||
*
|
||||
* Firefox stores cookies unencrypted in `cookies.sqlite`, so there is no key
|
||||
* to fetch and no consent prompt — the file is readable by anything running as
|
||||
* the user. That is Mozilla's design choice, not a control being circumvented,
|
||||
* which is why this path works identically on macOS, Windows, and Linux while
|
||||
* the Chromium one needs a per-platform credential store.
|
||||
*
|
||||
* @module FirefoxCookies
|
||||
*/
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { cookieScope, snapshotCookieDatabase, type ImportedCookie } from "./CookieDatabase.ts";
|
||||
|
||||
/**
|
||||
* Mirrors `ChromiumCookieReadError` so both engines fail with a tagged error
|
||||
* the service can tell apart, rather than one of them widening the channel to
|
||||
* an anonymous shape.
|
||||
*
|
||||
* No `reason` field: unlike Chromium there is only one way this fails — the
|
||||
* plaintext database would not open — and the tag already says which engine it
|
||||
* was. `BrowserImport` supplies the user-facing reason when it maps the union.
|
||||
*/
|
||||
export class FirefoxCookieReadError extends Schema.TaggedErrorClass<FirefoxCookieReadError>()(
|
||||
"FirefoxCookieReadError",
|
||||
{
|
||||
/**
|
||||
* Which database the read was for. Firefox keeps one per profile, so
|
||||
* without it a failure cannot be traced back to the profile that caused
|
||||
* it.
|
||||
*/
|
||||
cookieDatabasePath: Schema.String,
|
||||
/** Always present: every construction site wraps a real failure. */
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not read Firefox cookies at ${this.cookieDatabasePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `moz_cookies.sameSite` holds nsICookie's constants: 0 = None, 1 = Lax,
|
||||
* 2 = Strict, and 256 = Unset for a cookie that carried no SameSite attribute
|
||||
* at all. Unset is not the same thing as None — None is an explicit opt-in to
|
||||
* cross-site use — so it is imported as Electron's `unspecified`, which lets
|
||||
* the target browser apply its own default exactly as Firefox did. Anything
|
||||
* unrecognised also lands there rather than on `no_restriction`, since
|
||||
* guessing "none" would widen a cookie's scope on import.
|
||||
*/
|
||||
const SAMESITE_NONE = 0;
|
||||
const SAMESITE_LAX = 1;
|
||||
const SAMESITE_STRICT = 2;
|
||||
|
||||
/**
|
||||
* Schemas 10–14 carried a second column, `rawSameSite`: the value the cookie
|
||||
* actually declared, beside a `sameSite` that Firefox had already defaulted to
|
||||
* Lax. The schema-15 migration folded them back together with
|
||||
* `sameSite = UNSET where sameSite = LAX and rawSameSite = NONE`, i.e. a row
|
||||
* that "is Lax" only because nothing was declared. Reading such a database
|
||||
* before Firefox has migrated it must apply the same rule, or an undeclared
|
||||
* cookie is imported as an explicit Lax.
|
||||
*/
|
||||
const FIREFOX_RAW_SAMESITE_FIRST_SCHEMA = 10;
|
||||
const FIREFOX_RAW_SAMESITE_LAST_SCHEMA = 14;
|
||||
|
||||
const sameSiteFromColumn = (
|
||||
value: number | null,
|
||||
rawValue: number | null,
|
||||
): ImportedCookie["sameSite"] => {
|
||||
// Schema 9 added the column with no default, so older rows carry NULL.
|
||||
if (value === null) return "unspecified";
|
||||
if (value === SAMESITE_LAX && rawValue === SAMESITE_NONE) return "unspecified";
|
||||
if (value === SAMESITE_NONE) return "no_restriction";
|
||||
if (value === SAMESITE_LAX) return "lax";
|
||||
if (value === SAMESITE_STRICT) return "strict";
|
||||
return "unspecified";
|
||||
};
|
||||
|
||||
const CookieRow = Schema.Struct({
|
||||
host: Schema.String,
|
||||
name: Schema.String,
|
||||
value: Schema.String,
|
||||
path: Schema.String,
|
||||
// UNIX-epoch based, unlike Chromium's 1601-based microseconds — but the
|
||||
// unit depends on the schema version; see `expiryToSeconds`.
|
||||
expiry: Schema.Number,
|
||||
isSecure: Schema.Number,
|
||||
isHttpOnly: Schema.Number,
|
||||
sameSite: Schema.NullOr(Schema.Number),
|
||||
// Present only for schemas 10–14; selected as NULL elsewhere.
|
||||
rawSameSite: Schema.NullOr(Schema.Number),
|
||||
});
|
||||
const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow));
|
||||
|
||||
/**
|
||||
* Firefox schema 16 (Firefox 129) moved `expiry` from seconds to milliseconds
|
||||
* — the migration is `UPDATE moz_cookies SET expiry = expiry * 1000`. Electron
|
||||
* wants seconds, so the unit is decided by `PRAGMA user_version` rather than
|
||||
* assumed: importing a pre-16 profile as milliseconds would expire every cookie
|
||||
* at once, and a post-16 one as seconds would keep them for ~1000× too long.
|
||||
*/
|
||||
const FIREFOX_EXPIRY_MILLISECONDS_SCHEMA = 16;
|
||||
|
||||
const UserVersionRow = Schema.Struct({ user_version: Schema.Number });
|
||||
const decodeUserVersion = Schema.decodeUnknownEffect(Schema.Array(UserVersionRow));
|
||||
|
||||
const expiryToSeconds = (expiry: number, schemaVersion: number): number | undefined => {
|
||||
if (expiry <= 0) return undefined;
|
||||
return schemaVersion >= FIREFOX_EXPIRY_MILLISECONDS_SCHEMA ? Math.floor(expiry / 1000) : expiry;
|
||||
};
|
||||
|
||||
export const readFirefoxCookies = Effect.fn("FirefoxCookies.readFirefoxCookies")(function* (
|
||||
cookieDatabasePath: string,
|
||||
) {
|
||||
const snapshotPath = yield* snapshotCookieDatabase(cookieDatabasePath).pipe(
|
||||
Effect.mapError((cause) => new FirefoxCookieReadError({ cookieDatabasePath, cause })),
|
||||
);
|
||||
|
||||
const { rows, schemaVersion } = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const [versionRow] = yield* decodeUserVersion(yield* sql`pragma user_version`);
|
||||
const schemaVersion = versionRow?.user_version ?? 0;
|
||||
const hasRawSameSite =
|
||||
schemaVersion >= FIREFOX_RAW_SAMESITE_FIRST_SCHEMA &&
|
||||
schemaVersion <= FIREFOX_RAW_SAMESITE_LAST_SCHEMA;
|
||||
// Only the default container. Firefox isolates cookies per container and
|
||||
// per private window via `originAttributes` (`^userContextId=2`,
|
||||
// `^privateBrowsingId=1`); Electron has no equivalent, so importing them
|
||||
// all would collapse several identities onto one host/name/path and hand
|
||||
// the profile an arbitrary container's session.
|
||||
const raw = hasRawSameSite
|
||||
? yield* sql`
|
||||
select host, name, value, path, expiry, isSecure, isHttpOnly, sameSite, rawSameSite
|
||||
from moz_cookies
|
||||
where originAttributes = ''
|
||||
`
|
||||
: yield* sql`
|
||||
select host, name, value, path, expiry, isSecure, isHttpOnly, sameSite,
|
||||
null as rawSameSite
|
||||
from moz_cookies
|
||||
where originAttributes = ''
|
||||
`;
|
||||
return { rows: yield* decodeCookieRows(raw), schemaVersion };
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })),
|
||||
Effect.mapError((cause) => new FirefoxCookieReadError({ cookieDatabasePath, cause })),
|
||||
);
|
||||
|
||||
return rows.map((row) => {
|
||||
const secure = row.isSecure === 1;
|
||||
const scope = cookieScope(row.host, row.path, secure);
|
||||
return {
|
||||
url: scope.url,
|
||||
name: row.name,
|
||||
value: row.value,
|
||||
domain: scope.domain,
|
||||
path: row.path,
|
||||
secure,
|
||||
httpOnly: row.isHttpOnly === 1,
|
||||
expirationDate: expiryToSeconds(row.expiry, schemaVersion),
|
||||
sameSite: sameSiteFromColumn(row.sameSite, row.rawSameSite),
|
||||
} satisfies ImportedCookie;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopConfig from "../../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as LinuxBrowserSecret from "./LinuxBrowserSecret.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("Linux browser secret path", (it) => {
|
||||
it.effect("finds development and packaged helpers without falling back outside the install", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-browser-secret-path-" });
|
||||
const resourcesPath = path.join(root, "install", "resources");
|
||||
const native = path.join(
|
||||
root,
|
||||
"native",
|
||||
"browser-secret",
|
||||
"build",
|
||||
"x64",
|
||||
"t3-browser-secret",
|
||||
);
|
||||
const staged = path.join(
|
||||
root,
|
||||
"apps",
|
||||
"desktop",
|
||||
"prod-resources",
|
||||
"browser-secret",
|
||||
"t3-browser-secret",
|
||||
);
|
||||
const packaged = path.join(resourcesPath, "browser-secret", "t3-browser-secret");
|
||||
for (const filename of [native, staged, packaged]) {
|
||||
yield* fileSystem.makeDirectory(path.dirname(filename), { recursive: true });
|
||||
yield* fileSystem.writeFileString(filename, "helper");
|
||||
}
|
||||
const resolve = (isPackaged: boolean, platform: NodeJS.Platform = "linux") => {
|
||||
const environment = DesktopEnvironment.layer({
|
||||
dirname: path.join(root, "apps", "desktop", "dist-electron"),
|
||||
homeDirectory: root,
|
||||
platform,
|
||||
processArch: "x64",
|
||||
appVersion: "0.0.1",
|
||||
appPath: path.join(resourcesPath, "app.asar"),
|
||||
isPackaged,
|
||||
resourcesPath,
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(DesktopConfig.layerTest({})));
|
||||
return LinuxBrowserSecret.LinuxBrowserSecretPath.pipe(
|
||||
Effect.provide(LinuxBrowserSecret.layer.pipe(Layer.provide(environment))),
|
||||
);
|
||||
};
|
||||
|
||||
assert.equal(yield* resolve(false), native);
|
||||
assert.equal(yield* resolve(true), packaged);
|
||||
yield* fileSystem.remove(native);
|
||||
assert.equal(yield* resolve(false), staged);
|
||||
yield* fileSystem.remove(packaged);
|
||||
assert.isUndefined(yield* resolve(true));
|
||||
assert.isUndefined(yield* resolve(false, "darwin"));
|
||||
assert.isUndefined(yield* resolve(false, "win32"));
|
||||
yield* fileSystem.remove(staged);
|
||||
assert.isUndefined(yield* resolve(false));
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { DesktopEnvironment } from "../../app/DesktopEnvironment.ts";
|
||||
|
||||
/** Absolute path to the helper shipped with this desktop instance. */
|
||||
export const LinuxBrowserSecretPath = Context.Reference<string | undefined>(
|
||||
"@t3tools/desktop/preview/BrowserImport/LinuxBrowserSecretPath",
|
||||
{ defaultValue: () => undefined },
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(
|
||||
LinuxBrowserSecretPath,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment;
|
||||
if (environment.platform !== "linux") return undefined;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const relative = environment.path.join("browser-secret", "t3-browser-secret");
|
||||
const candidates = environment.isPackaged
|
||||
? [environment.path.join(environment.resourcesPath, relative)]
|
||||
: [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native",
|
||||
"browser-secret",
|
||||
"build",
|
||||
environment.processArch,
|
||||
"t3-browser-secret",
|
||||
),
|
||||
...environment.resolveResourcePathCandidates(relative),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false)))
|
||||
return candidate;
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,443 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Hand-builds Safari's binary jar
|
||||
// format byte by byte.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import {
|
||||
isPermissionDenied,
|
||||
parseBinaryCookies,
|
||||
readSafariCookies,
|
||||
safariAccessDenied,
|
||||
SafariCookieReadError,
|
||||
} from "./SafariCookies.ts";
|
||||
|
||||
const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200;
|
||||
|
||||
interface FixtureCookie {
|
||||
readonly domain: string;
|
||||
readonly name: string;
|
||||
readonly path: string;
|
||||
readonly value: string;
|
||||
readonly flags: number;
|
||||
/** Seconds since 2001-01-01, as Safari stores them. */
|
||||
readonly expiry: number;
|
||||
}
|
||||
|
||||
/** Encodes one cookie exactly as Safari lays it out. */
|
||||
function encodeCookie(cookie: FixtureCookie): Buffer {
|
||||
const strings = [cookie.domain, cookie.name, cookie.path, cookie.value];
|
||||
const headerSize = 56;
|
||||
const offsets: number[] = [];
|
||||
let cursor = headerSize;
|
||||
for (const value of strings) {
|
||||
offsets.push(cursor);
|
||||
cursor += Buffer.byteLength(value) + 1;
|
||||
}
|
||||
const size = cursor;
|
||||
|
||||
const buffer = Buffer.alloc(size);
|
||||
buffer.writeUInt32LE(size, 0);
|
||||
buffer.writeUInt32LE(0, 4);
|
||||
buffer.writeUInt32LE(cookie.flags, 8);
|
||||
buffer.writeUInt32LE(0, 12);
|
||||
buffer.writeUInt32LE(offsets[0]!, 16);
|
||||
buffer.writeUInt32LE(offsets[1]!, 20);
|
||||
buffer.writeUInt32LE(offsets[2]!, 24);
|
||||
buffer.writeUInt32LE(offsets[3]!, 28);
|
||||
buffer.writeUInt32LE(0, 32);
|
||||
buffer.writeUInt32LE(0, 36);
|
||||
buffer.writeDoubleLE(cookie.expiry, 40);
|
||||
buffer.writeDoubleLE(0, 48);
|
||||
strings.forEach((value, index) => {
|
||||
buffer.write(value, offsets[index]!, "utf8");
|
||||
});
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/** Builds a single-page `Cookies.binarycookies` file. */
|
||||
function encodeBinaryCookies(cookies: ReadonlyArray<FixtureCookie>): Buffer {
|
||||
const encoded = cookies.map(encodeCookie);
|
||||
const headerSize = 12 + encoded.length * 4;
|
||||
const offsets: number[] = [];
|
||||
let cursor = headerSize;
|
||||
for (const cookie of encoded) {
|
||||
offsets.push(cursor);
|
||||
cursor += cookie.length;
|
||||
}
|
||||
|
||||
const page = Buffer.alloc(cursor);
|
||||
page.writeUInt32BE(0x0000_0100, 0);
|
||||
page.writeUInt32LE(encoded.length, 4);
|
||||
offsets.forEach((offset, index) => page.writeUInt32LE(offset, 8 + index * 4));
|
||||
encoded.forEach((cookie, index) => cookie.copy(page, offsets[index]!));
|
||||
|
||||
const header = Buffer.alloc(8 + 4);
|
||||
header.write("cook", 0, "latin1");
|
||||
header.writeUInt32BE(1, 4);
|
||||
header.writeUInt32BE(page.length, 8);
|
||||
return Buffer.concat([header, page]);
|
||||
}
|
||||
|
||||
describe("parseBinaryCookies", () => {
|
||||
it("reads Safari's format and rebases its 2001 epoch", () => {
|
||||
const file = encodeBinaryCookies([
|
||||
{
|
||||
domain: ".apple.com",
|
||||
name: "session",
|
||||
path: "/",
|
||||
value: "abc",
|
||||
// secure | httpOnly
|
||||
flags: 0x1 | 0x4,
|
||||
expiry: 800_000_000,
|
||||
},
|
||||
{
|
||||
domain: "example.test",
|
||||
name: "plain",
|
||||
path: "/app",
|
||||
value: "v",
|
||||
flags: 0,
|
||||
expiry: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(parseBinaryCookies(file)).toEqual([
|
||||
{
|
||||
url: "https://apple.com/",
|
||||
name: "session",
|
||||
value: "abc",
|
||||
domain: ".apple.com",
|
||||
path: "/",
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
// Safari counts from 2001-01-01, Electron from 1970.
|
||||
expirationDate: 800_000_000 + APPLE_EPOCH_OFFSET_SECONDS,
|
||||
// The format predates SameSite; Lax is the safe modern default.
|
||||
sameSite: "lax",
|
||||
},
|
||||
{
|
||||
url: "http://example.test/app",
|
||||
name: "plain",
|
||||
value: "v",
|
||||
// Host-only: no leading dot in the jar, so no `domain` for Electron,
|
||||
// which would otherwise re-add the dot and widen it to subdomains.
|
||||
domain: undefined,
|
||||
path: "/app",
|
||||
secure: false,
|
||||
httpOnly: false,
|
||||
expirationDate: undefined,
|
||||
sameSite: "lax",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps __Host- cookies host-only so Electron accepts them", () => {
|
||||
const file = encodeBinaryCookies([
|
||||
{ domain: "example.test", name: "__Host-id", path: "/", value: "v", flags: 0x1, expiry: 0 },
|
||||
]);
|
||||
|
||||
expect(parseBinaryCookies(file)[0]).toMatchObject({
|
||||
url: "https://example.test/",
|
||||
name: "__Host-id",
|
||||
domain: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("brackets IPv6 hosts in the cookie URL", () => {
|
||||
const file = encodeBinaryCookies([
|
||||
{ domain: "::1", name: "local", path: "/", value: "v", flags: 0, expiry: 0 },
|
||||
]);
|
||||
|
||||
expect(parseBinaryCookies(file)[0]).toMatchObject({
|
||||
url: "http://[::1]/",
|
||||
domain: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads cookies spread across multiple pages", () => {
|
||||
// Safari pages its cookie file, and a single-page reader would silently
|
||||
// return only the first slice.
|
||||
const first = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 },
|
||||
]);
|
||||
const second = encodeBinaryCookies([
|
||||
{ domain: "b.test", name: "two", path: "/", value: "2", flags: 0, expiry: 1 },
|
||||
]);
|
||||
// Splice the two single-page files into one two-page file.
|
||||
const firstPage = first.subarray(12);
|
||||
const secondPage = second.subarray(12);
|
||||
const header = Buffer.alloc(16);
|
||||
header.write("cook", 0, "latin1");
|
||||
header.writeUInt32BE(2, 4);
|
||||
header.writeUInt32BE(firstPage.length, 8);
|
||||
header.writeUInt32BE(secondPage.length, 12);
|
||||
|
||||
const parsed = parseBinaryCookies(Buffer.concat([header, firstPage, secondPage]));
|
||||
|
||||
expect(parsed.map((cookie) => cookie.name)).toEqual(["one", "two"]);
|
||||
});
|
||||
|
||||
it("rejects a page that runs past the end of the file", () => {
|
||||
// `Buffer.subarray` clamps rather than throwing, so an overlong first page
|
||||
// swallows the second one's bytes and advances the cursor past the end.
|
||||
// Every cookie after the boundary then vanishes from a "successful" import.
|
||||
const first = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 },
|
||||
]);
|
||||
const second = encodeBinaryCookies([
|
||||
{ domain: "b.test", name: "two", path: "/", value: "2", flags: 0, expiry: 1 },
|
||||
]);
|
||||
const firstPage = first.subarray(12);
|
||||
const secondPage = second.subarray(12);
|
||||
const header = Buffer.alloc(16);
|
||||
header.write("cook", 0, "latin1");
|
||||
header.writeUInt32BE(2, 4);
|
||||
// Declares more bytes for page one than the file holds in total.
|
||||
header.writeUInt32BE(firstPage.length + secondPage.length + 32, 8);
|
||||
header.writeUInt32BE(secondPage.length, 12);
|
||||
|
||||
expect(() => parseBinaryCookies(Buffer.concat([header, firstPage, secondPage]))).toThrow(
|
||||
SafariCookieReadError,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a record whose declared size runs past its page", () => {
|
||||
const valid = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
|
||||
]);
|
||||
// The record's own length is what bounds its string offsets; an inflated
|
||||
// one lets them read the following record's bytes as this cookie's value.
|
||||
const pageStart = 8 + 4;
|
||||
const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
|
||||
const corrupt = Buffer.from(valid);
|
||||
corrupt.writeUInt32LE(0xffff, recordStart);
|
||||
|
||||
expect(() => parseBinaryCookies(corrupt)).toThrow(SafariCookieReadError);
|
||||
});
|
||||
|
||||
it("rejects records truncated inside the 56-byte header", () => {
|
||||
const valid = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
|
||||
]);
|
||||
const pageStart = 8 + 4;
|
||||
const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
|
||||
|
||||
for (let size = 48; size < 56; size += 1) {
|
||||
const corrupt = Buffer.from(valid);
|
||||
corrupt.writeUInt32LE(size, recordStart);
|
||||
expect(() => parseBinaryCookies(corrupt), `record size ${size}`).toThrow(
|
||||
SafariCookieReadError,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects record offsets that point into the page header or an earlier record", () => {
|
||||
const valid = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
|
||||
{ domain: "b.test", name: "m", path: "/", value: "w", expiry: 1_000, flags: 0 },
|
||||
]);
|
||||
const pageStart = 8 + 4;
|
||||
const firstRecord = valid.readUInt32LE(pageStart + 8);
|
||||
|
||||
// Pointing the second offset at the page's offset table would let those
|
||||
// table bytes parse as a fabricated record.
|
||||
const intoTable = Buffer.from(valid);
|
||||
intoTable.writeUInt32LE(4, pageStart + 12);
|
||||
expect(() => parseBinaryCookies(intoTable)).toThrow(SafariCookieReadError);
|
||||
|
||||
// Pointing it back at the first record makes the same bytes count twice.
|
||||
const overlapping = Buffer.from(valid);
|
||||
overlapping.writeUInt32LE(firstRecord, pageStart + 12);
|
||||
expect(() => parseBinaryCookies(overlapping)).toThrow(SafariCookieReadError);
|
||||
|
||||
// And a well-formed two-record page still parses.
|
||||
expect(parseBinaryCookies(valid)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects string offsets that point into the record header", () => {
|
||||
const valid = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
|
||||
]);
|
||||
const pageStart = 8 + 4;
|
||||
const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
|
||||
|
||||
for (const offsetField of [16, 20, 24, 28]) {
|
||||
const corrupt = Buffer.from(valid);
|
||||
corrupt.writeUInt32LE(55, recordStart + offsetField);
|
||||
expect(() => parseBinaryCookies(corrupt), `offset field ${offsetField}`).toThrow(
|
||||
SafariCookieReadError,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the checksum and property-list trailer Safari writes", () => {
|
||||
const file = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 },
|
||||
]);
|
||||
const checksum = Buffer.alloc(8);
|
||||
const plist = Buffer.from("bplist00 stub");
|
||||
const plistLength = Buffer.alloc(4);
|
||||
plistLength.writeUInt32BE(plist.length, 0);
|
||||
|
||||
expect(parseBinaryCookies(Buffer.concat([file, checksum]))).toHaveLength(1);
|
||||
expect(parseBinaryCookies(Buffer.concat([file, checksum, plistLength, plist]))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a jar whose page table stops short of its contents", () => {
|
||||
// A second, undeclared page after the first would be silently dropped —
|
||||
// the cookies it holds vanish from the import with no error — so a file
|
||||
// the header does not fully describe is refused instead.
|
||||
const first = encodeBinaryCookies([
|
||||
{ domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 },
|
||||
]);
|
||||
const extraPage = encodeBinaryCookies([
|
||||
{ domain: "b.test", name: "d", path: "/", value: "w", flags: 0, expiry: 0 },
|
||||
]).subarray(12);
|
||||
|
||||
expect(() => parseBinaryCookies(Buffer.concat([first, extraPage]))).toThrow(
|
||||
SafariCookieReadError,
|
||||
);
|
||||
// A trailer that claims a property list it doesn't contain is refused too.
|
||||
const badLength = Buffer.alloc(4);
|
||||
badLength.writeUInt32BE(99, 0);
|
||||
expect(() =>
|
||||
parseBinaryCookies(Buffer.concat([first, Buffer.alloc(8), badLength, Buffer.from("x")])),
|
||||
).toThrow(SafariCookieReadError);
|
||||
});
|
||||
|
||||
it("rejects a file that is not binarycookies", () => {
|
||||
expect(() => parseBinaryCookies(Buffer.from("not a cookie jar"))).toThrow(
|
||||
SafariCookieReadError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readSafariCookies", () => {
|
||||
it.effect("adds the cookie path and parser cause to malformed jar failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
|
||||
const jar = `${directory}/Cookies.binarycookies`;
|
||||
yield* fileSystem.writeFileString(jar, "not a cookie jar");
|
||||
|
||||
const error = yield* readSafariCookies(jar).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.reason, "readFailed");
|
||||
assert.equal(error.cookieDatabasePath, jar);
|
||||
assert.instanceOf(error.cause, SafariCookieReadError);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports a TCC denial as a permission the user can grant", () =>
|
||||
Effect.gen(function* () {
|
||||
// What Full Disk Access actually looks like: the file is there, the read
|
||||
// is refused with EPERM. Effect tags that `Unknown`, not
|
||||
// `PermissionDenied`, so the reader has to look at the errno. Reporting
|
||||
// it as a generic failure would send the user looking for a missing
|
||||
// browser instead of a checkbox.
|
||||
const denied = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: "/protected/Cookies.binarycookies",
|
||||
cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
|
||||
});
|
||||
|
||||
const error = yield* readSafariCookies("/protected/Cookies.binarycookies").pipe(
|
||||
Effect.flip,
|
||||
Effect.provide(FileSystem.layerNoop({ readFile: () => Effect.fail(denied) })),
|
||||
);
|
||||
|
||||
assert.equal(error.reason, "needsFullDiskAccess");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an ordinary permission failure as a plain read failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
|
||||
const jar = `${directory}/Cookies.binarycookies`;
|
||||
yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b]));
|
||||
// A mode-bits refusal is EACCES: granting Full Disk Access cannot fix
|
||||
// it, so it must not be routed to that grant.
|
||||
yield* fileSystem.chmod(jar, 0o000);
|
||||
|
||||
const error = yield* readSafariCookies(jar).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.reason, "readFailed");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports a missing jar as a plain read failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
|
||||
|
||||
const error = yield* readSafariCookies(`${directory}/absent.binarycookies`).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.reason, "readFailed");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
|
||||
describe("safariAccessDenied", () => {
|
||||
const eperm = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "FileSystem",
|
||||
method: "open",
|
||||
pathOrDescriptor: "/protected/Cookies.binarycookies",
|
||||
cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
|
||||
});
|
||||
const denied = (error: PlatformError.PlatformError) =>
|
||||
FileSystem.layerNoop({ open: () => Effect.fail(error) });
|
||||
|
||||
it.effect("reports TCC's EPERM as a missing Full Disk Access grant", () =>
|
||||
Effect.gen(function* () {
|
||||
// `stat` finds the jar without the grant, so only an open tells the
|
||||
// listing whether the import would actually be allowed.
|
||||
assert.isTrue(
|
||||
yield* safariAccessDenied("/protected/Cookies.binarycookies").pipe(
|
||||
Effect.provide(denied(eperm)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not read a readable jar, or any other failure, as denied", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
|
||||
const jar = `${directory}/Cookies.binarycookies`;
|
||||
yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b]));
|
||||
assert.isFalse(yield* safariAccessDenied(jar));
|
||||
// Missing entirely is "not installed", not "denied".
|
||||
assert.isFalse(yield* safariAccessDenied(`${directory}/absent.binarycookies`));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
|
||||
describe("isPermissionDenied", () => {
|
||||
// Shapes taken from a real `FileSystem.readFile` failure on macOS — verified
|
||||
// against Safari's TCC-protected jar, whose denial is EPERM, tagged
|
||||
// `Unknown` rather than `PermissionDenied`.
|
||||
const platformError = (reasonTag: string, code: string): PlatformError.PlatformError =>
|
||||
({ _tag: "PlatformError", reason: { _tag: reasonTag, cause: { code } } }) as never;
|
||||
|
||||
it("treats a TCC EPERM denial as permission denied", () => {
|
||||
// The regression: EPERM is tagged `Unknown`, so checking the tag alone
|
||||
// reported Safari's Full Disk Access refusal as a generic read failure.
|
||||
expect(isPermissionDenied(platformError("Unknown", "EPERM"))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not send an ordinary EACCES failure to the Full Disk Access grant", () => {
|
||||
// A POSIX permission or ACL refusal cannot be fixed by granting Full Disk
|
||||
// Access, so it stays a plain read failure; only TCC's EPERM routes there.
|
||||
expect(isPermissionDenied(platformError("PermissionDenied", "EACCES"))).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat an unrelated failure as permission denied", () => {
|
||||
expect(isPermissionDenied(platformError("Unknown", "EIO"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Safari cookie extraction.
|
||||
*
|
||||
* Safari does not encrypt its cookies; it stores them in a proprietary
|
||||
* `Cookies.binarycookies` file inside its app container. The protection is
|
||||
* TCC, not cryptography — the file lives under a path only apps with Full Disk
|
||||
* Access may read, so the gate is a permission the user grants in System
|
||||
* Settings rather than a key to obtain.
|
||||
*
|
||||
* The format, big-endian throughout except the page bodies:
|
||||
*
|
||||
* magic "cook", u32 pageCount, u32 pageSize[pageCount], then each page:
|
||||
* u32 0x00000100, u32le cookieCount, u32le cookieOffset[cookieCount],
|
||||
* then each cookie:
|
||||
* u32le size, u32le unknown, u32le flags, u32le unknown,
|
||||
* u32le urlOffset, nameOffset, pathOffset, valueOffset,
|
||||
* u64 end-of-header, f64 expiry, f64 creation, then NUL-terminated
|
||||
* strings at the offsets above (relative to the cookie start).
|
||||
*
|
||||
* @module SafariCookies
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { cookieScope, type ImportedCookie } from "./CookieDatabase.ts";
|
||||
|
||||
/** Safari's timestamps count seconds from 2001-01-01, not the UNIX epoch. */
|
||||
const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200;
|
||||
|
||||
/** `u32 0x00000100`, `u32le cookieCount`, then one `u32le` offset per cookie. */
|
||||
const COOKIE_PAGE_HEADER_SIZE = 12;
|
||||
/** Through the `f64 creation` field; string bytes follow. */
|
||||
const COOKIE_RECORD_HEADER_SIZE = 56;
|
||||
|
||||
const FLAG_SECURE = 0x1;
|
||||
const FLAG_HTTP_ONLY = 0x4;
|
||||
|
||||
export const SafariCookieReadFailure = Schema.Literals(["needsFullDiskAccess", "readFailed"]);
|
||||
export type SafariCookieReadFailure = typeof SafariCookieReadFailure.Type;
|
||||
|
||||
export class SafariCookieReadError extends Schema.TaggedErrorClass<SafariCookieReadError>()(
|
||||
"SafariCookieReadError",
|
||||
{
|
||||
reason: SafariCookieReadFailure,
|
||||
/**
|
||||
* Which jar the read was for. The parser raises this before a path is in
|
||||
* hand, so it is optional rather than required.
|
||||
*/
|
||||
cookieDatabasePath: Schema.optional(Schema.String),
|
||||
/** Kept for the log; never surfaced to the user. */
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.cookieDatabasePath === undefined
|
||||
? `Could not read Safari cookies: ${this.reason}.`
|
||||
: `Could not read Safari cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isSafariCookieReadError = Schema.is(SafariCookieReadError);
|
||||
|
||||
/** Reads a NUL-terminated ASCII string at an offset. */
|
||||
function readCString(buffer: Buffer, start: number): string {
|
||||
const end = buffer.indexOf(0, start);
|
||||
return buffer.toString("utf8", start, end === -1 ? buffer.length : end);
|
||||
}
|
||||
|
||||
export function parseBinaryCookies(buffer: Buffer): ReadonlyArray<ImportedCookie> {
|
||||
if (buffer.length < 8 || buffer.toString("latin1", 0, 4) !== "cook") {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
|
||||
const pageCount = buffer.readUInt32BE(4);
|
||||
// Every declared structure is bounds-checked against what the file actually
|
||||
// contains, and a mismatch fails the read. `Buffer.subarray` clamps silently,
|
||||
// so accepting a short page or an overlong record would return a cookie set
|
||||
// that is quietly missing entries or carrying fields read out of the next
|
||||
// record — a partial import the user has no way to notice.
|
||||
if (8 + pageCount * 4 > buffer.length) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
const pageSizes: number[] = [];
|
||||
for (let index = 0; index < pageCount; index += 1) {
|
||||
pageSizes.push(buffer.readUInt32BE(8 + index * 4));
|
||||
}
|
||||
|
||||
const cookies: ImportedCookie[] = [];
|
||||
let pageStart = 8 + pageCount * 4;
|
||||
|
||||
for (const pageSize of pageSizes) {
|
||||
if (pageSize < COOKIE_PAGE_HEADER_SIZE || pageStart + pageSize > buffer.length) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
const page = buffer.subarray(pageStart, pageStart + pageSize);
|
||||
pageStart += pageSize;
|
||||
|
||||
// Page bodies switch to little-endian after the big-endian header.
|
||||
const cookieCount = page.readUInt32LE(4);
|
||||
const offsetTableEnd = COOKIE_PAGE_HEADER_SIZE + cookieCount * 4;
|
||||
if (offsetTableEnd > page.length) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
// Every record accepted so far, so a later offset cannot point back into
|
||||
// one of them: the page header, the offset table, and earlier records are
|
||||
// all bytes that would otherwise parse as a fabricated cookie.
|
||||
const accepted: Array<readonly [start: number, end: number]> = [];
|
||||
for (let index = 0; index < cookieCount; index += 1) {
|
||||
const cookieStart = page.readUInt32LE(8 + index * 4);
|
||||
if (cookieStart < offsetTableEnd || cookieStart + COOKIE_RECORD_HEADER_SIZE > page.length) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
// Bounded by the record's own length so a string offset cannot run past
|
||||
// it into the following record's bytes.
|
||||
const recordSize = page.readUInt32LE(cookieStart);
|
||||
const cookieEnd = cookieStart + recordSize;
|
||||
if (
|
||||
recordSize < COOKIE_RECORD_HEADER_SIZE ||
|
||||
cookieEnd > page.length ||
|
||||
accepted.some(([start, end]) => cookieStart < end && cookieEnd > start)
|
||||
) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
accepted.push([cookieStart, cookieEnd]);
|
||||
const cookie = page.subarray(cookieStart, cookieEnd);
|
||||
|
||||
const flags = cookie.readUInt32LE(8);
|
||||
const urlOffset = cookie.readUInt32LE(16);
|
||||
const nameOffset = cookie.readUInt32LE(20);
|
||||
const pathOffset = cookie.readUInt32LE(24);
|
||||
const valueOffset = cookie.readUInt32LE(28);
|
||||
const expiry = cookie.readDoubleLE(40);
|
||||
|
||||
// Offsets are relative to the record; one pointing outside it would
|
||||
// otherwise read a neighbouring cookie's bytes as this one's value.
|
||||
if (
|
||||
[urlOffset, nameOffset, pathOffset, valueOffset].some(
|
||||
(offset) => offset < COOKIE_RECORD_HEADER_SIZE || offset >= cookie.length,
|
||||
)
|
||||
) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
const domain = readCString(cookie, urlOffset);
|
||||
const name = readCString(cookie, nameOffset);
|
||||
const path = readCString(cookie, pathOffset);
|
||||
const value = readCString(cookie, valueOffset);
|
||||
if (domain === "" || name === "") continue;
|
||||
|
||||
const secure = (flags & FLAG_SECURE) !== 0;
|
||||
const expirationDate =
|
||||
expiry > 0 ? Math.floor(expiry) + APPLE_EPOCH_OFFSET_SECONDS : undefined;
|
||||
|
||||
cookies.push({
|
||||
// Safari marks domain cookies with a leading dot like the other
|
||||
// engines, so the shared scope rule applies: host-only cookies keep
|
||||
// `domain` undefined, or Electron widens them to every subdomain.
|
||||
...cookieScope(domain, path || "/", secure),
|
||||
name,
|
||||
value,
|
||||
path: path || "/",
|
||||
secure,
|
||||
httpOnly: (flags & FLAG_HTTP_ONLY) !== 0,
|
||||
expirationDate,
|
||||
// Bits 3–5 of the flags carry something SameSite-shaped, but no public
|
||||
// description of them agrees and real jars do not match any of them
|
||||
// cleanly. Lax is the modern browser default; claiming "none" would
|
||||
// widen every imported cookie's scope.
|
||||
sameSite: "lax",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Safari writes an 8-byte checksum after the pages, then an optional
|
||||
// length-prefixed property list. Anything else past the declared pages —
|
||||
// in particular whole extra pages — means the page table does not describe
|
||||
// the file, and a jar the header lies about is refused rather than
|
||||
// imported with cookies silently missing.
|
||||
const trailer = buffer.length - pageStart;
|
||||
// Legal shapes: nothing, the 8-byte checksum alone, or checksum + u32
|
||||
// length + exactly that many property-list bytes.
|
||||
const validTrailer =
|
||||
trailer === 0 ||
|
||||
trailer === 8 ||
|
||||
(trailer >= 12 && trailer === 8 + 4 + buffer.readUInt32BE(pageStart + 8));
|
||||
if (!validTrailer) {
|
||||
throw new SafariCookieReadError({ reason: "readFailed" });
|
||||
}
|
||||
|
||||
return cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a filesystem error is the OS refusing access.
|
||||
*
|
||||
* A TCC denial arrives as EPERM, which Effect tags `Unknown` rather than
|
||||
* `PermissionDenied` (reserved for EACCES), so the underlying errno is checked
|
||||
* too — otherwise a Full Disk Access refusal is reported as a generic read
|
||||
* failure and the user is never told what to grant.
|
||||
*/
|
||||
export const isPermissionDenied = (error: PlatformError.PlatformError): boolean => {
|
||||
// TCC denies with EPERM, which Effect tags `Unknown` rather than
|
||||
// `PermissionDenied` — so the errno is what identifies it. EACCES (and the
|
||||
// `PermissionDenied` tag it maps to) is an ordinary POSIX permission or
|
||||
// ACL failure that granting Full Disk Access cannot fix, so it stays a plain
|
||||
// read failure rather than sending the user to a grant that won't help.
|
||||
const code = (error.reason as { cause?: { code?: unknown } }).cause?.code;
|
||||
return code === "EPERM";
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether reading the jar is refused by TCC. `stat` succeeds on the jar
|
||||
* inside Safari's container even without Full Disk Access — that is what lets
|
||||
* the listing find it — so presence alone cannot tell granted from denied.
|
||||
* Opening it for read is what TCC gates: EPERM means the grant is missing.
|
||||
* Anything else (including a missing jar) is not a permission answer.
|
||||
*/
|
||||
export const safariAccessDenied = Effect.fnUntraced(function* (cookiePath: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
|
||||
Effect.as(false),
|
||||
Effect.catch((cause) => Effect.succeed(isPermissionDenied(cause))),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
|
||||
export const readSafariCookies = Effect.fn("SafariCookies.readSafariCookies")(function* (
|
||||
cookiePath: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const contents = yield* fileSystem.readFile(cookiePath).pipe(
|
||||
Effect.mapError((cause) => {
|
||||
// TCC denies the read even though the file exists — a permission the user
|
||||
// grants in System Settings rather than a missing browser. macOS never
|
||||
// prompts for Full Disk Access, so there is no dialog to wait on; the
|
||||
// read just fails, and it fails with EPERM, which Effect surfaces as an
|
||||
// `Unknown` system error rather than `PermissionDenied` (that is EACCES).
|
||||
return new SafariCookieReadError({
|
||||
reason: isPermissionDenied(cause) ? "needsFullDiskAccess" : "readFailed",
|
||||
cookieDatabasePath: cookiePath,
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
);
|
||||
// The parser throws on a malformed jar; catch it here so callers see a typed
|
||||
// failure rather than a defect.
|
||||
return yield* Effect.try({
|
||||
try: () => parseBinaryCookies(Buffer.from(contents)),
|
||||
catch: (cause) =>
|
||||
isSafariCookieReadError(cause)
|
||||
? new SafariCookieReadError({
|
||||
reason: cause.reason,
|
||||
cookieDatabasePath: cookiePath,
|
||||
cause,
|
||||
})
|
||||
: new SafariCookieReadError({
|
||||
reason: "readFailed",
|
||||
cookieDatabasePath: cookiePath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,922 @@
|
||||
/**
|
||||
* Importable browser sources.
|
||||
*
|
||||
* Chromium-family browsers keep cookies in an
|
||||
* encrypted SQLite database whose key lives in an OS credential store; Firefox
|
||||
* keeps them in plain SQLite with no key at all, so it needs no keychain and
|
||||
* works the same on every platform. Safari uses binary cookie files, with
|
||||
* separate WebKit data stores for named profiles.
|
||||
*
|
||||
* Each entry pins its own paths and credential-store coordinates rather than
|
||||
* deriving them, because the forks do not agree. macOS uses service/account
|
||||
* pairs, while Linux Chromium uses a custom libsecret schema keyed by an
|
||||
* `application` attribute. The user-data directory also differs per fork and
|
||||
* per platform.
|
||||
*
|
||||
* @module BrowserImportSources
|
||||
*/
|
||||
import type { BrowserImportSourceId, BrowserImportSourceProfile } from "@t3tools/contracts";
|
||||
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
|
||||
import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessAddresses,
|
||||
HostProcessHostname,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export type BrowserImportEngine = "chromium" | "firefox" | "safari";
|
||||
|
||||
/**
|
||||
* Directory roots a definition builds its paths from. Passed in rather than
|
||||
* read from `process`, so source resolution stays testable for platforms the
|
||||
* host is not currently running.
|
||||
*/
|
||||
export interface BrowserImportPathContext {
|
||||
readonly path: Path.Path;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly home: string;
|
||||
/** `%APPDATA%` on Windows; unused elsewhere. */
|
||||
readonly appData: string | undefined;
|
||||
/** `%LOCALAPPDATA%` on Windows; unused elsewhere. */
|
||||
readonly localAppData: string | undefined;
|
||||
}
|
||||
|
||||
export interface BrowserImportSourceDefinition {
|
||||
readonly id: BrowserImportSourceId;
|
||||
readonly name: string;
|
||||
readonly engine: BrowserImportEngine;
|
||||
/** Platforms the definition has paths for. */
|
||||
readonly platforms: ReadonlyArray<NodeJS.Platform>;
|
||||
readonly userDataDirectory: (context: BrowserImportPathContext) => string | undefined;
|
||||
/** Chromium on macOS only: where the OSCrypt key lives in the keychain. */
|
||||
readonly keychainService?: string;
|
||||
readonly keychainAccount?: string;
|
||||
/** Chromium's `application` attribute in the Linux libsecret schema. */
|
||||
readonly linuxSecretApplication?: string;
|
||||
}
|
||||
|
||||
const macApplicationSupport = (
|
||||
context: BrowserImportPathContext,
|
||||
...segments: ReadonlyArray<string>
|
||||
) => context.path.join(context.home, "Library", "Application Support", ...segments);
|
||||
|
||||
/**
|
||||
* One Chromium fork. The leaves differ per fork; omitting a platform's
|
||||
* segments marks the fork as unavailable there. Most Windows Chromium builds
|
||||
* use App-Bound Encryption, but forks can retain the older DPAPI-backed store.
|
||||
*/
|
||||
const chromiumSource = (input: {
|
||||
readonly id: BrowserImportSourceId;
|
||||
readonly name: string;
|
||||
readonly keychainService: string;
|
||||
readonly keychainAccount: string;
|
||||
readonly macSegments: ReadonlyArray<string>;
|
||||
readonly linuxSegments?: ReadonlyArray<string>;
|
||||
readonly linuxSecretApplication?: string;
|
||||
readonly windowsSegments?: ReadonlyArray<string>;
|
||||
}): BrowserImportSourceDefinition => ({
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
engine: "chromium",
|
||||
platforms: [
|
||||
"darwin" as NodeJS.Platform,
|
||||
...(input.linuxSegments ? ["linux" as NodeJS.Platform] : []),
|
||||
...(input.windowsSegments ? ["win32" as NodeJS.Platform] : []),
|
||||
],
|
||||
keychainService: input.keychainService,
|
||||
keychainAccount: input.keychainAccount,
|
||||
...(input.linuxSecretApplication === undefined
|
||||
? {}
|
||||
: { linuxSecretApplication: input.linuxSecretApplication }),
|
||||
userDataDirectory: (context) => {
|
||||
if (context.platform === "darwin") return macApplicationSupport(context, ...input.macSegments);
|
||||
if (context.platform === "win32") {
|
||||
return input.windowsSegments && context.localAppData
|
||||
? context.path.join(context.localAppData, ...input.windowsSegments)
|
||||
: undefined;
|
||||
}
|
||||
return input.linuxSegments
|
||||
? context.path.join(context.home, ".config", ...input.linuxSegments)
|
||||
: undefined;
|
||||
},
|
||||
});
|
||||
|
||||
export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition> = [
|
||||
// No Chromium fork is importable on Windows: since Chrome 127 their cookies
|
||||
// are encrypted to the browser's own identity (App-Bound Encryption), so no
|
||||
// other process can read them. macOS and Linux keep working, so only the
|
||||
// Windows segments are omitted.
|
||||
chromiumSource({
|
||||
id: "chrome",
|
||||
name: "Chrome",
|
||||
keychainService: "Chrome Safe Storage",
|
||||
keychainAccount: "Chrome",
|
||||
macSegments: ["Google", "Chrome"],
|
||||
linuxSegments: ["google-chrome"],
|
||||
linuxSecretApplication: "chrome",
|
||||
}),
|
||||
chromiumSource({
|
||||
id: "edge",
|
||||
name: "Microsoft Edge",
|
||||
keychainService: "Microsoft Edge Safe Storage",
|
||||
keychainAccount: "Microsoft Edge",
|
||||
macSegments: ["Microsoft Edge"],
|
||||
linuxSegments: ["microsoft-edge"],
|
||||
linuxSecretApplication: "msedge",
|
||||
}),
|
||||
chromiumSource({
|
||||
id: "brave",
|
||||
name: "Brave",
|
||||
keychainService: "Brave Safe Storage",
|
||||
keychainAccount: "Brave",
|
||||
macSegments: ["BraveSoftware", "Brave-Browser"],
|
||||
linuxSegments: ["BraveSoftware", "Brave-Browser"],
|
||||
linuxSecretApplication: "brave",
|
||||
}),
|
||||
chromiumSource({
|
||||
id: "vivaldi",
|
||||
name: "Vivaldi",
|
||||
keychainService: "Vivaldi Safe Storage",
|
||||
keychainAccount: "Vivaldi",
|
||||
macSegments: ["Vivaldi"],
|
||||
linuxSegments: ["vivaldi"],
|
||||
linuxSecretApplication: "vivaldi",
|
||||
}),
|
||||
chromiumSource({
|
||||
id: "opera",
|
||||
name: "Opera",
|
||||
keychainService: "Opera Safe Storage",
|
||||
keychainAccount: "Opera",
|
||||
macSegments: ["com.operasoftware.Opera"],
|
||||
linuxSegments: ["opera"],
|
||||
linuxSecretApplication: "opera",
|
||||
}),
|
||||
// Arc has no Linux build.
|
||||
chromiumSource({
|
||||
id: "arc",
|
||||
name: "Arc",
|
||||
keychainService: "Arc Safe Storage",
|
||||
keychainAccount: "Arc",
|
||||
macSegments: ["Arc", "User Data"],
|
||||
}),
|
||||
chromiumSource({
|
||||
id: "helium",
|
||||
name: "Helium",
|
||||
keychainService: "Helium Storage Key",
|
||||
keychainAccount: "Helium",
|
||||
macSegments: ["net.imput.helium"],
|
||||
linuxSegments: ["net.imput.helium"],
|
||||
windowsSegments: ["imput", "Helium", "User Data"],
|
||||
// Helium retains Chromium's libsecret application name on Linux.
|
||||
linuxSecretApplication: "chromium",
|
||||
}),
|
||||
{
|
||||
// The default jar lives here; named profiles use WebKit data stores
|
||||
// alongside this directory inside the same app container.
|
||||
id: "safari",
|
||||
name: "Safari",
|
||||
engine: "safari",
|
||||
platforms: ["darwin"],
|
||||
userDataDirectory: (context) =>
|
||||
context.platform === "darwin"
|
||||
? context.path.join(
|
||||
context.home,
|
||||
"Library",
|
||||
"Containers",
|
||||
"com.apple.Safari",
|
||||
"Data",
|
||||
"Library",
|
||||
"Cookies",
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
{
|
||||
id: "firefox",
|
||||
name: "Firefox",
|
||||
engine: "firefox",
|
||||
platforms: ["darwin", "win32", "linux"],
|
||||
userDataDirectory: (context) => {
|
||||
if (context.platform === "darwin") return macApplicationSupport(context, "Firefox");
|
||||
if (context.platform === "win32") {
|
||||
return context.appData
|
||||
? context.path.join(context.appData, "Mozilla", "Firefox")
|
||||
: undefined;
|
||||
}
|
||||
return context.path.join(context.home, ".mozilla", "firefox");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Where a profile's cookie database may live, most current first. Chromium 96
|
||||
* moved the live jar to `Network/Cookies`; a root-level `Cookies` is either a
|
||||
* pre-96 install or a leftover from before the move. Importing the leftover
|
||||
* while sessions live in `Network/` would snapshot a stale or empty database,
|
||||
* and a fresh install with only `Network/Cookies` would read as not installed.
|
||||
* Firefox uses `cookies.sqlite`, and its profile paths from `profiles.ini`
|
||||
* may already be absolute.
|
||||
*
|
||||
* Chrome 96+ moved network-related files (including Cookies) into a `Network`
|
||||
* subdirectory for sandboxing. The candidate list includes both locations so
|
||||
* callers tolerate fresh and legacy installs alike.
|
||||
*/
|
||||
export const cookieDatabaseCandidatePaths = (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
profileDirectory: string,
|
||||
): ReadonlyArray<string> => {
|
||||
const root = definition.userDataDirectory(context);
|
||||
if (root === undefined) return [];
|
||||
const profilePath = context.path.isAbsolute(profileDirectory)
|
||||
? profileDirectory
|
||||
: context.path.join(root, profileDirectory);
|
||||
if (definition.engine === "firefox") {
|
||||
return [context.path.join(profilePath, "cookies.sqlite")];
|
||||
}
|
||||
if (definition.engine === "safari") {
|
||||
return [context.path.join(profilePath, "Cookies.binarycookies")];
|
||||
}
|
||||
// Chromium: pre-96 uses `Cookies`, 96+ use `Network/Cookies`. An upgrade
|
||||
// leaves the legacy file behind, so prefer the current one and fall back.
|
||||
return [
|
||||
context.path.join(profilePath, "Network", "Cookies"),
|
||||
context.path.join(profilePath, "Cookies"),
|
||||
];
|
||||
};
|
||||
|
||||
/** The first candidate that is a regular file, or undefined when none is. */
|
||||
export const resolveCookieDatabase = Effect.fnUntraced(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
profileDirectory: string,
|
||||
) {
|
||||
for (const candidate of cookieDatabaseCandidatePaths(definition, context, profileDirectory)) {
|
||||
if (yield* databaseFileExists(candidate)) return candidate;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
/**
|
||||
* Firefox records its profiles in `profiles.ini`. `Install*` sections point at
|
||||
* a default profile but do not describe one, so only `[ProfileN]` blocks
|
||||
* count.
|
||||
*/
|
||||
export function parseFirefoxProfiles(
|
||||
ini: string,
|
||||
path: Path.Path,
|
||||
root: string,
|
||||
): ReadonlyArray<BrowserImportSourceProfile> {
|
||||
const profiles: BrowserImportSourceProfile[] = [];
|
||||
let current: { name?: string; path?: string; isRelative?: string } | null = null;
|
||||
|
||||
const flush = () => {
|
||||
if (current?.path) {
|
||||
const candidate = current.path;
|
||||
const isRelative = current.isRelative === undefined || current.isRelative === "1";
|
||||
const validIsRelative = current.isRelative === undefined || /^[01]$/.test(current.isRelative);
|
||||
if (!validIsRelative || candidate.includes("\u0000")) {
|
||||
current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
let directory: string | undefined;
|
||||
if (isRelative) {
|
||||
if (!path.isAbsolute(candidate)) {
|
||||
const resolved = path.resolve(root, candidate);
|
||||
const relative = path.relative(root, resolved);
|
||||
const escapesRoot =
|
||||
relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
|
||||
if (!escapesRoot) directory = path.normalize(candidate);
|
||||
}
|
||||
} else if (path.isAbsolute(candidate)) {
|
||||
// Firefox supports profiles on arbitrary custom roots when
|
||||
// IsRelative=0. Do not constrain them to the standard Firefox root.
|
||||
directory = path.normalize(candidate);
|
||||
}
|
||||
|
||||
if (directory !== undefined) {
|
||||
profiles.push({ directory, name: current.name?.trim() || directory });
|
||||
}
|
||||
}
|
||||
current = null;
|
||||
};
|
||||
|
||||
for (const rawLine of ini.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (line.startsWith("[")) {
|
||||
flush();
|
||||
current = /^\[Profile\d+\]$/i.test(line) ? {} : null;
|
||||
continue;
|
||||
}
|
||||
if (!current) continue;
|
||||
const separator = line.indexOf("=");
|
||||
if (separator === -1) continue;
|
||||
const key = line.slice(0, separator).trim().toLowerCase();
|
||||
const value = line.slice(separator + 1).trim();
|
||||
if (key === "name") current.name = value;
|
||||
if (key === "path") current.path = value;
|
||||
if (key === "isrelative") current.isRelative = value;
|
||||
}
|
||||
flush();
|
||||
return profiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the roots the registry builds its paths from, from the ambient
|
||||
* process. Tests build a context directly instead.
|
||||
*/
|
||||
export const sourcePathContext = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
return {
|
||||
path,
|
||||
platform,
|
||||
home: environment.HOME ?? environment.USERPROFILE ?? "",
|
||||
appData: environment.APPDATA,
|
||||
localAppData: environment.LOCALAPPDATA,
|
||||
} satisfies BrowserImportPathContext;
|
||||
});
|
||||
|
||||
/** Shape of the slice of Chromium's `Local State` that names its profiles. */
|
||||
const LocalState = Schema.Struct({
|
||||
profile: Schema.optional(
|
||||
Schema.Struct({
|
||||
info_cache: Schema.optional(
|
||||
Schema.Record(Schema.String, Schema.Struct({ name: Schema.optional(Schema.String) })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const decodeLocalState = Schema.decodeUnknownEffect(Schema.fromJsonString(LocalState));
|
||||
|
||||
/** A single plain path segment: no separators, no `.`/`..`, not empty. */
|
||||
const isSafeProfileDirectory = (directory: string): boolean =>
|
||||
directory.length > 0 &&
|
||||
directory !== "." &&
|
||||
directory !== ".." &&
|
||||
!/[\\/]/.test(directory) &&
|
||||
!directory.includes("\u0000");
|
||||
|
||||
const CookieCountRow = Schema.Struct({ count: Schema.Number });
|
||||
const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow));
|
||||
|
||||
/**
|
||||
* How many importable cookies a profile holds, counted without decrypting
|
||||
* anything. Firefox containers use identities Electron cannot represent, so
|
||||
* its count uses the same default-container predicate as the reader. Best
|
||||
* effort: a locked, missing or unexpected database yields `undefined` rather
|
||||
* than failing the listing.
|
||||
*/
|
||||
const countProfileCookies = Effect.fnUntraced(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
directory: string,
|
||||
): Effect.fn.Return<number | undefined, never, FileSystem.FileSystem> {
|
||||
const database = yield* resolveCookieDatabase(definition, context, directory);
|
||||
if (database === undefined) return undefined;
|
||||
return yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows =
|
||||
definition.engine === "firefox"
|
||||
? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
|
||||
: yield* sql`select count(*) as count from cookies`;
|
||||
const [row] = yield* decodeCookieCount(rows);
|
||||
return row?.count;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
});
|
||||
|
||||
const withCookieCounts = (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
profiles: ReadonlyArray<BrowserImportSourceProfile>,
|
||||
) =>
|
||||
Effect.forEach(profiles, (profile) =>
|
||||
countProfileCookies(definition, context, profile.directory).pipe(
|
||||
Effect.map((cookieCount) =>
|
||||
cookieCount === undefined ? profile : { ...profile, cookieCount },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const SafariProfileRows = Schema.Array(
|
||||
Schema.Struct({ title: Schema.NullOr(Schema.String), external_uuid: Schema.String }),
|
||||
);
|
||||
const decodeSafariProfiles = Schema.decodeUnknownEffect(SafariProfileRows);
|
||||
const isSafariProfileUuid = (value: string) =>
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
||||
|
||||
const listSafariProfiles = Effect.fnUntraced(function* (
|
||||
context: BrowserImportPathContext,
|
||||
root: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const library = context.path.dirname(root);
|
||||
const metadata = context.path.join(library, "Safari", "SafariTabs.db");
|
||||
const declared = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
return yield* decodeSafariProfiles(
|
||||
yield* sql`
|
||||
select title, external_uuid from bookmarks
|
||||
where parent = 0 and type = 1 and subtype = 2 and deleted = 0
|
||||
order by order_index
|
||||
`,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: metadata, readonly: true })),
|
||||
Effect.orElseSucceed(() => []),
|
||||
);
|
||||
const defaultProfile = declared.find((profile) => profile.external_uuid === "DefaultProfile");
|
||||
const profiles: Array<BrowserImportSourceProfile> = [
|
||||
{
|
||||
directory: ".",
|
||||
name: defaultProfile ? defaultProfile.title?.trim() || "Personal" : "Safari",
|
||||
},
|
||||
];
|
||||
const stores = context.path.join(library, "WebKit", "WebsiteDataStore");
|
||||
const profileDirectory = (uuid: string) =>
|
||||
context.path.join(stores, uuid.toLowerCase(), "Cookies");
|
||||
for (const profile of declared) {
|
||||
if (!isSafariProfileUuid(profile.external_uuid)) continue;
|
||||
profiles.push({
|
||||
directory: profileDirectory(profile.external_uuid),
|
||||
name: profile.title?.trim() || profile.external_uuid,
|
||||
});
|
||||
}
|
||||
// If Safari's metadata is unavailable, recover stores that have cookies.
|
||||
// With readable metadata, avoid resurrecting deleted profiles left on disk.
|
||||
if (declared.length === 0) {
|
||||
const entries = yield* fileSystem.readDirectory(stores).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries.filter(isSafariProfileUuid).sort()) {
|
||||
const directory = context.path.join(stores, entry, "Cookies");
|
||||
if (yield* databaseFileExists(context.path.join(directory, "Cookies.binarycookies"))) {
|
||||
profiles.push({ directory, name: entry });
|
||||
}
|
||||
}
|
||||
}
|
||||
return profiles;
|
||||
});
|
||||
|
||||
/**
|
||||
* Profiles the source browser knows about.
|
||||
*
|
||||
* Firefox declares them in `profiles.ini`; Chromium in `Local State`. When
|
||||
* that metadata is missing, unreadable or malformed, the directories that
|
||||
* actually hold a cookie database are scanned instead. Assuming a single
|
||||
* `Default` would report a browser whose cookies live in `Profile 1` as having
|
||||
* nothing to import — and it is then left out of the menu entirely.
|
||||
*/
|
||||
const listSourceProfilesInDirectory = Effect.fnUntraced(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const root = definition.userDataDirectory(context);
|
||||
if (root === undefined) return [];
|
||||
|
||||
if (definition.engine === "safari") {
|
||||
return yield* listSafariProfiles(context, root);
|
||||
}
|
||||
|
||||
if (definition.engine === "firefox") {
|
||||
const declared = yield* fileSystem.readFileString(context.path.join(root, "profiles.ini")).pipe(
|
||||
Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
|
||||
);
|
||||
// `profiles.ini` also lists profiles the installer created but the user
|
||||
// never launched, which hold no cookie database and nothing to import.
|
||||
// Only keep the ones a database proves exist, like the directory scans
|
||||
// below do. When none of the declared profiles has one, fall through to
|
||||
// the scan rather than returning empty: `profiles.ini` can list stale or
|
||||
// never-launched profiles while the cookies live in one it does not
|
||||
// mention, and an empty answer here hides the browser entirely.
|
||||
if (declared.length > 0) {
|
||||
const found = yield* Effect.forEach(declared, (profile) =>
|
||||
Effect.forEach(
|
||||
cookieDatabaseCandidatePaths(definition, context, profile.directory),
|
||||
(candidate) => databaseFileExists(candidate),
|
||||
).pipe(Effect.map((results) => (results.some(Boolean) ? profile : undefined))),
|
||||
);
|
||||
const withDatabase = found.filter((profile) => profile !== undefined);
|
||||
if (withDatabase.length > 0) {
|
||||
return yield* withCookieCounts(definition, context, withDatabase);
|
||||
}
|
||||
}
|
||||
|
||||
// No usable `profiles.ini`, so fall back to scanning the directory the
|
||||
// profiles actually live in, keeping only the ones a cookie database
|
||||
// proves were launched.
|
||||
const fallbackDirectory =
|
||||
context.platform === "linux" ? root : context.path.join(root, "Profiles");
|
||||
const scanned = yield* fileSystem
|
||||
.readDirectory(fallbackDirectory)
|
||||
.pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
|
||||
const found = yield* Effect.forEach(scanned, (entry) => {
|
||||
const directory = context.platform === "linux" ? entry : context.path.join("Profiles", entry);
|
||||
return resolveCookieDatabase(definition, context, directory).pipe(
|
||||
Effect.map((database) => (database === undefined ? undefined : { directory, name: entry })),
|
||||
);
|
||||
});
|
||||
return yield* withCookieCounts(
|
||||
definition,
|
||||
context,
|
||||
found.filter((profile) => profile !== undefined),
|
||||
);
|
||||
}
|
||||
|
||||
const declared = yield* fileSystem.readFileString(context.path.join(root, "Local State")).pipe(
|
||||
Effect.flatMap(decodeLocalState),
|
||||
Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})),
|
||||
// The keys are directory names from the browser's own metadata file, which
|
||||
// anything running as the user can write. Anything but a single plain
|
||||
// segment is dropped: `..` or a path separator would otherwise be handed
|
||||
// to `cookieDatabasePath` and read a database outside the user-data
|
||||
// directory.
|
||||
Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))),
|
||||
Effect.map((entries) =>
|
||||
entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
|
||||
);
|
||||
if (declared.length > 0) return yield* withCookieCounts(definition, context, declared);
|
||||
|
||||
// `Local State` is missing, unreadable or malformed. Scanning for directories
|
||||
// that hold a cookie database finds the profiles anyway.
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(root)
|
||||
.pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
|
||||
const found = yield* Effect.forEach(entries.filter(isSafeProfileDirectory), (directory) =>
|
||||
resolveCookieDatabase(definition, context, directory).pipe(
|
||||
Effect.map((database) =>
|
||||
database === undefined ? undefined : { directory, name: directory },
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* withCookieCounts(
|
||||
definition,
|
||||
context,
|
||||
found.filter((profile) => profile !== undefined),
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Include Firefox's Snap home alongside its native home. Snap profiles use
|
||||
* absolute directories so cookie reads and lock checks keep pointing at the
|
||||
* installation they came from, even when both installs use the same name.
|
||||
*/
|
||||
export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
|
||||
if (definition.engine !== "firefox" || context.platform !== "linux") {
|
||||
return yield* listSourceProfilesInDirectory(definition, context);
|
||||
}
|
||||
|
||||
const root = definition.userDataDirectory(context);
|
||||
if (root === undefined) return [];
|
||||
const roots = [
|
||||
root,
|
||||
context.path.join(context.home, "snap", "firefox", "common", ".mozilla", "firefox"),
|
||||
];
|
||||
const profiles = new Map<string, BrowserImportSourceProfile>();
|
||||
for (const directory of roots) {
|
||||
const found = yield* listSourceProfilesInDirectory(
|
||||
{ ...definition, userDataDirectory: () => directory },
|
||||
context,
|
||||
);
|
||||
for (const profile of found) {
|
||||
const absolute = context.path.resolve(directory, profile.directory);
|
||||
if (!profiles.has(absolute)) {
|
||||
profiles.set(absolute, directory === root ? profile : { ...profile, directory: absolute });
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...profiles.values()];
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether a cookie database candidate is a regular file. Presence alone is
|
||||
* not enough: a directory at the path would list as an importable profile and
|
||||
* then fail the SQLite open, so anything but a file is treated as absent.
|
||||
*/
|
||||
const databaseFileExists = Effect.fnUntraced(function* (path: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.stat(path).pipe(
|
||||
Effect.map((info) => info.type === "File"),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
});
|
||||
|
||||
type ProcessLivenessProbe = (pid: number) => Effect.Effect<boolean>;
|
||||
|
||||
export const chromiumProcessIsAlive = (
|
||||
pid: number,
|
||||
signalProcess: (pid: number, signal: 0) => unknown = process.kill.bind(process),
|
||||
) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
// Signal 0 performs a read-only existence/permission check.
|
||||
signalProcess(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
// Only ESRCH positively proves the process is gone. Permission errors
|
||||
// and unknown failures stay conservative so an active browser is never
|
||||
// mistaken for a stale lock.
|
||||
return !(
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const processIsAlive: ProcessLivenessProbe = (pid) => chromiumProcessIsAlive(pid);
|
||||
|
||||
/** Whether a Chromium `<host>-<pid>` lock target may still name its owner. */
|
||||
export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* (
|
||||
target: string,
|
||||
currentHost: string,
|
||||
isProcessAlive: ProcessLivenessProbe,
|
||||
) {
|
||||
const separator = target.lastIndexOf("-");
|
||||
if (separator <= 0) return true;
|
||||
const host = target.slice(0, separator);
|
||||
const pidText = target.slice(separator + 1);
|
||||
if (!/^\d+$/.test(pidText)) return true;
|
||||
const pid = Number(pidText);
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
|
||||
// A PID is meaningful only on this host. A foreign hostname can come from a
|
||||
// shared home directory, and cannot safely be declared stale from here.
|
||||
if (host !== currentHost) return true;
|
||||
return yield* isProcessAlive(pid);
|
||||
});
|
||||
|
||||
/** Windows sharing and lock violations are translated by libuv to `Busy`. */
|
||||
export const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean =>
|
||||
error.reason._tag === "Busy";
|
||||
|
||||
/**
|
||||
* Whether a Windows `parent.lock` is actually held by a running process. It
|
||||
* is opened with no sharing, so it persists on disk after the process exits
|
||||
* and `stat` always succeeds; only trying to open it for write reveals an
|
||||
* active holder, which surfaces as `Busy`.
|
||||
*/
|
||||
const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) {
|
||||
// Permission failures are distinct: they do not prove a browser owns the
|
||||
// lock, so they must not hide the source as running.
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.open(lockPath, { flag: "r+" }).pipe(
|
||||
Effect.as(false),
|
||||
Effect.catchIf(isWindowsLockHeldError, () => Effect.succeed(true)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
|
||||
type WindowsLockProbe = (path: string) => Effect.Effect<boolean, never, FileSystem.FileSystem>;
|
||||
|
||||
/**
|
||||
* Chromium does not create its POSIX `SingletonLock` symlink on Windows. The
|
||||
* live cookie database is opened without sharing instead, so probing each
|
||||
* profile's current jar is the reliable running signal there.
|
||||
*/
|
||||
export const windowsChromiumCookiesAreHeld = Effect.fnUntraced(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
lockIsHeld: WindowsLockProbe = windowsLockIsHeld,
|
||||
) {
|
||||
const profiles = yield* listSourceProfiles(definition, context);
|
||||
const held = yield* Effect.forEach(profiles, (profile) =>
|
||||
resolveCookieDatabase(definition, context, profile.directory).pipe(
|
||||
Effect.flatMap((database) =>
|
||||
database === undefined ? Effect.succeed(false) : lockIsHeld(database),
|
||||
),
|
||||
),
|
||||
);
|
||||
return held.some(Boolean);
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether a Firefox `lock` symlink's `<ip>:[+]<pid>` target still names a
|
||||
* live owner. Firefox writes this symlink beside the profile while it runs and
|
||||
* unlinks it on a clean exit, so a dangling one is either live or a crash.
|
||||
*/
|
||||
export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* (
|
||||
target: string,
|
||||
localAddresses: ReadonlySet<string>,
|
||||
isProcessAlive: ProcessLivenessProbe,
|
||||
) {
|
||||
const separator = target.lastIndexOf(":");
|
||||
if (separator < 0) return true;
|
||||
// The owner half is whatever Firefox's resolver returned for the machine's
|
||||
// hostname — 127.0.0.1 when the lookup fails, but often 127.0.1.1 or a LAN
|
||||
// address — so a pid is only meaningful when that address is one of ours.
|
||||
// A shared (NFS) profile locked from another machine names a foreign
|
||||
// address whose pid cannot be probed here, nor could a reused local pid
|
||||
// vouch for it, so it stays conservatively held.
|
||||
const owner = target.slice(0, separator);
|
||||
if (!localAddresses.has(owner)) return true;
|
||||
// A `+` marks an fcntl-holding owner; the pid follows either way.
|
||||
const pidText = target.slice(separator + 1).replace(/^\+/, "");
|
||||
if (!/^\d+$/.test(pidText)) return true;
|
||||
const pid = Number(pidText);
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
|
||||
return yield* isProcessAlive(pid);
|
||||
});
|
||||
|
||||
/**
|
||||
* Interpreters that can run the fcntl probe, tried in order. `/usr/bin/python3`
|
||||
* is named absolutely first so a Dock-launched app with launchd's bare `PATH`
|
||||
* still finds it without depending on the login-shell PATH merge; Linux
|
||||
* distributions carry python3 on the default path.
|
||||
*/
|
||||
const FCNTL_PROBE_INTERPRETERS = ["/usr/bin/python3", "python3"] as const;
|
||||
|
||||
/**
|
||||
* The probe prints exactly one of these. Anything else means the script never
|
||||
* ran — most importantly Apple's `/usr/bin/python3` shim, which on a Mac
|
||||
* without the Command Line Tools exits non-zero after printing an install
|
||||
* prompt, without ever reaching our code.
|
||||
*/
|
||||
const FCNTL_PROBE_SCRIPT =
|
||||
"import fcntl,os,sys\n" +
|
||||
"fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
|
||||
"try:\n" +
|
||||
" fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
|
||||
"except BlockingIOError:\n" +
|
||||
" print('held')\n" +
|
||||
"else:\n" +
|
||||
" print('free')";
|
||||
|
||||
/**
|
||||
* Whether another process holds an fcntl write lock on `path`.
|
||||
*
|
||||
* Firefox's `.parentlock` is an empty file whose only signal is the kernel
|
||||
* lock, and Node exposes no fcntl, so a throwaway interpreter tries a
|
||||
* non-blocking `F_SETLK` and reports `EWOULDBLOCK`. The lock is never
|
||||
* acquired for real: on success the child exits and the kernel drops it.
|
||||
*
|
||||
* The answer is trusted only when the script itself spoke. A verdict of
|
||||
* `held` or `free` on stdout is the probe's own, and stands. Anything else —
|
||||
* no interpreter on any candidate path, or one that refused to run the script
|
||||
* (Apple's shim without the developer tools) — is the probe being unavailable,
|
||||
* not evidence about the lock. That case falls back to "not held" rather than
|
||||
* "held": reporting every profile as locked forever would block Firefox import
|
||||
* outright on such machines, and the SQLite snapshot already copes with a
|
||||
* live database's WAL, as it does for every other engine.
|
||||
*/
|
||||
export const posixLockIsHeld = Effect.fnUntraced(function* (
|
||||
path: string,
|
||||
interpreters: ReadonlyArray<string> = FCNTL_PROBE_INTERPRETERS,
|
||||
) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
for (const interpreter of interpreters) {
|
||||
const verdict = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* spawner.spawn(
|
||||
ChildProcess.make(interpreter, ["-c", FCNTL_PROBE_SCRIPT, path], {
|
||||
stdin: "ignore",
|
||||
env: environment,
|
||||
}),
|
||||
);
|
||||
const [stdout] = yield* Effect.all(
|
||||
[handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return stdout.trim();
|
||||
}),
|
||||
).pipe(Effect.orElseSucceed(() => ""));
|
||||
if (verdict === "held") return true;
|
||||
if (verdict === "free") return false;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether Firefox holds a profile.
|
||||
*
|
||||
* Firefox leaves two kinds of lock behind, and they mean different things.
|
||||
* On Linux the `lock` symlink (target `<ip>:+<pid>`) is removed on a clean
|
||||
* exit, so its presence is evidence — provided the pid it names is alive. But
|
||||
* `.parentlock` (macOS/Linux) and `parent.lock` (Windows) are regular files
|
||||
* held with fcntl or a Windows handle and are *deliberately left on disk*
|
||||
* after exit, as a last-used marker; treating them as proof of a running
|
||||
* browser blocks every import after Firefox has been used once. On POSIX the
|
||||
* fcntl lock itself is the truth, and macOS in particular writes nothing else
|
||||
* (no symlink, no pid), so `.parentlock` is probed for the kernel lock. On
|
||||
* Windows the held handle denies our open, which `windowsLockIsHeld` reads as `Busy`.
|
||||
*/
|
||||
const firefoxProfileIsHeld = Effect.fnUntraced(function* (
|
||||
directory: string,
|
||||
context: BrowserImportPathContext,
|
||||
// Resolved once by the caller: it involves a DNS lookup of the hostname and
|
||||
// is the same for every profile.
|
||||
localAddresses: ReadonlySet<string>,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
if (context.platform === "win32") {
|
||||
return yield* windowsLockIsHeld(context.path.join(directory, "parent.lock"));
|
||||
}
|
||||
// Linux additionally writes the `lock` symlink; a live pid there settles it
|
||||
// without spawning anything.
|
||||
const symlinkHeld = yield* fileSystem.readLink(context.path.join(directory, "lock")).pipe(
|
||||
Effect.flatMap((target) => firefoxSymlinkLockIsHeld(target, localAddresses, processIsAlive)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (symlinkHeld) return true;
|
||||
const parentLock = context.path.join(directory, ".parentlock");
|
||||
const present = yield* fileSystem.stat(parentLock).pipe(
|
||||
Effect.map((info) => info.type === "File"),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (!present) return false;
|
||||
return yield* posixLockIsHeld(parentLock);
|
||||
});
|
||||
|
||||
/** Whether the browser is running, which leaves its cookie DB mid-write. */
|
||||
export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
): Effect.fn.Return<
|
||||
boolean,
|
||||
never,
|
||||
FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const root = definition.userDataDirectory(context);
|
||||
if (root === undefined) return false;
|
||||
// Probe the source's own lock state rather than scanning the process table.
|
||||
// Safari keeps no lock and writes its jar atomically, so a running instance
|
||||
// is not a hazard there.
|
||||
//
|
||||
// Chromium exposes its lock through the cookie jar on Windows and through a
|
||||
// user-data SingletonLock on POSIX. Firefox keeps its locks inside each
|
||||
// profile under three names across platforms (`lock` on macOS and Linux,
|
||||
// `.parentlock` beside it, `parent.lock` on Windows). Looking for Firefox's
|
||||
// at the root finds nothing and reports a running browser as importable.
|
||||
if (definition.engine === "safari") return false;
|
||||
if (definition.engine !== "firefox") {
|
||||
if (context.platform === "win32") {
|
||||
return yield* windowsChromiumCookiesAreHeld(definition, context);
|
||||
}
|
||||
const currentHost = yield* HostProcessHostname;
|
||||
const lock = context.path.join(root, "SingletonLock");
|
||||
return yield* fileSystem.readLink(lock).pipe(
|
||||
Effect.flatMap((target) => chromiumSingletonLockIsHeld(target, currentHost, processIsAlive)),
|
||||
Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
|
||||
);
|
||||
}
|
||||
|
||||
const profiles = yield* listSourceProfiles(definition, context);
|
||||
// Only the Linux `lock` symlink names an address, so Windows skips the lookup.
|
||||
const localAddresses: ReadonlySet<string> =
|
||||
context.platform === "win32" ? new Set() : yield* yield* HostProcessAddresses;
|
||||
const found = yield* Effect.forEach(profiles, (profile) => {
|
||||
const directory = context.path.isAbsolute(profile.directory)
|
||||
? profile.directory
|
||||
: context.path.join(root, profile.directory);
|
||||
return firefoxProfileIsHeld(directory, context, localAddresses);
|
||||
});
|
||||
return found.some(Boolean);
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether the source has cookies to import.
|
||||
*
|
||||
* Keyed off the cookie database rather than the user-data directory, because
|
||||
* that directory is not evidence the browser exists: installers for native
|
||||
* messaging hosts create an empty one for every Chromium fork they know about,
|
||||
* so a machine with only Chrome reports Edge, Brave, Vivaldi, Opera and Arc as
|
||||
* present. The database is the thing an import actually needs, so its absence
|
||||
* is the honest answer either way.
|
||||
*
|
||||
* Existence is checked without opening the file, which matters for Safari: TCC
|
||||
* permits `stat` on the jar inside its container but refuses a read, so this
|
||||
* still sees it and the user gets the Full Disk Access prompt rather than
|
||||
* having Safari disappear.
|
||||
*/
|
||||
export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* (
|
||||
definition: BrowserImportSourceDefinition,
|
||||
context: BrowserImportPathContext,
|
||||
): Effect.fn.Return<boolean, never, FileSystem.FileSystem> {
|
||||
const profiles = yield* listSourceProfiles(definition, context);
|
||||
const found = yield* Effect.forEach(profiles, (profile) =>
|
||||
resolveCookieDatabase(definition, context, profile.directory).pipe(
|
||||
Effect.map((database) => database !== undefined),
|
||||
),
|
||||
);
|
||||
return found.some(Boolean);
|
||||
});
|
||||
@@ -63,6 +63,45 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps scopes that differ only by a lone surrogate in separate partitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
|
||||
// TextEncoder folds a lone surrogate to U+FFFD, so without escaping these
|
||||
// two supported ids would hash to one partition and share every cookie.
|
||||
const loneSurrogate = yield* browserSessions.getPartition("p\ud800");
|
||||
const replacementChar = yield* browserSessions.getPartition("p\ufffd");
|
||||
assert.notStrictEqual(loneSurrogate, replacementChar);
|
||||
|
||||
// The escape can't be forged with a literal backslash either.
|
||||
const literal = yield* browserSessions.getPartition("p\\ud800");
|
||||
assert.notStrictEqual(literal, loneSurrogate);
|
||||
|
||||
// And a well-formed scope still lands on its historical partition.
|
||||
assert.strictEqual(
|
||||
yield* browserSessions.getPartition("scope-a"),
|
||||
"persist:t3code-preview-f051bb2c68cb7b2fe969",
|
||||
);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps legacy defaults disjoint from nondefault profile partitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
|
||||
// These share the same scope string: default environment `a::b`, and
|
||||
// environment `a` with nondefault profile `b`.
|
||||
const legacyDefault = yield* browserSessions.getPartition("a::b");
|
||||
const nondefaultProfile = yield* browserSessions.getPartition("a::b", true, "profile");
|
||||
|
||||
assert.strictEqual(legacyDefault, "persist:t3code-preview-78f0be89237d77f7a70e");
|
||||
assert.strictEqual(nondefaultProfile, "persist:t3code-preview-profile-78f0be89237d77f7a70e");
|
||||
assert.notStrictEqual(nondefaultProfile, legacyDefault);
|
||||
assert.isTrue(browserSessions.isPartition(legacyDefault));
|
||||
assert.isTrue(browserSessions.isPartition(nondefaultProfile));
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -133,8 +172,6 @@ describe("BrowserSession", () => {
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
@@ -157,8 +194,6 @@ describe("BrowserSession", () => {
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
@@ -192,6 +227,28 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears a partition whose session has not been opened yet", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("scope-untouched");
|
||||
|
||||
// Deriving the partition string does not create the session, and the
|
||||
// clear only walks sessions it already holds. Without loading it first
|
||||
// this reports success and deletes nothing — which is what a user
|
||||
// clearing a profile after a restart would get.
|
||||
assert.isUndefined(sessions.get(partition));
|
||||
yield* browserSessions.clearCookies([partition]);
|
||||
assert.isUndefined(sessions.get(partition));
|
||||
|
||||
yield* browserSessions.getSession("scope-untouched");
|
||||
yield* browserSessions.clearCookies([partition]);
|
||||
|
||||
const created = sessions.get(partition);
|
||||
assert.isDefined(created);
|
||||
assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -209,7 +266,6 @@ describe("BrowserSession", () => {
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
@@ -226,7 +282,6 @@ describe("BrowserSession", () => {
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
|
||||
@@ -10,6 +10,16 @@ import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
/**
|
||||
* Incognito partitions deliberately omit the `persist:` prefix, which is what
|
||||
* makes Chromium keep them in memory and discard them with the process. They
|
||||
* still carry the product prefix so `isPartition` can admit them — the
|
||||
* `will-attach-webview` gate rejects anything it does not recognise.
|
||||
*/
|
||||
const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
|
||||
const PROFILE_PARTITION_MARKER = "profile-";
|
||||
|
||||
export type BrowserSessionPartitionNamespace = "profile";
|
||||
|
||||
// Permissions granted to preview web content. `clipboard-sanitized-write` is the
|
||||
// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
|
||||
@@ -83,7 +93,6 @@ export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
@@ -92,27 +101,74 @@ export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
persistent?: boolean,
|
||||
namespace?: BrowserSessionPartitionNamespace,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
readonly getSession: (
|
||||
scope?: string,
|
||||
persistent?: boolean,
|
||||
namespace?: BrowserSessionPartitionNamespace,
|
||||
) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
/** Omit `partitions` to clear every known partition. */
|
||||
readonly clearCookies: (
|
||||
partitions?: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: (
|
||||
partitions?: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
/**
|
||||
* Restricts a clear to the given partitions. Omitting them keeps the historical
|
||||
* "every partition" behaviour, which callers now only use for an explicit
|
||||
* "all profiles" action — a per-profile clear must never reach across profiles.
|
||||
*/
|
||||
const selectSessions = (
|
||||
sessions: ReadonlyMap<string, Session>,
|
||||
partitions: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<readonly [string, Session]> =>
|
||||
[...sessions.entries()].filter(
|
||||
([partition]) => partitions === undefined || partitions.includes(partition),
|
||||
);
|
||||
|
||||
/**
|
||||
* Scope bytes for the partition digest.
|
||||
*
|
||||
* `TextEncoder` replaces a lone UTF-16 surrogate with U+FFFD, so `"p\ud800"`
|
||||
* and `"p\ufffd"` would hash to the same partition and share cookies. Those
|
||||
* are distinct, supported ids, so lone surrogates are escaped to `\uXXXX`
|
||||
* first — and a literal backslash is doubled so the escape cannot be forged.
|
||||
* Every well-formed scope passes through byte-for-byte unchanged, which keeps
|
||||
* existing partitions (and the logins in them) where they are.
|
||||
*/
|
||||
const encodeScopeForDigest = (scope: string): Uint8Array =>
|
||||
new TextEncoder().encode(
|
||||
scope
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(
|
||||
/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
|
||||
(unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
|
||||
),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
|
||||
scope = "shared",
|
||||
persistent = true,
|
||||
namespace?: BrowserSessionPartitionNamespace,
|
||||
) {
|
||||
const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
@@ -121,11 +177,19 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
|
||||
// Legacy/default partitions are prefix + hex digest. The non-hex profile
|
||||
// marker creates a disjoint namespace while leaving every legacy default
|
||||
// partition byte-for-byte unchanged.
|
||||
return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
|
||||
const partition = yield* getPartition(scope);
|
||||
const getSession = Effect.fn("BrowserSession.getSession")(function* (
|
||||
scope = "shared",
|
||||
persistent = true,
|
||||
namespace?: BrowserSessionPartitionNamespace,
|
||||
) {
|
||||
const partition = yield* getPartition(scope, persistent, namespace);
|
||||
return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
|
||||
const existing = sessions.get(partition);
|
||||
if (existing) return Effect.succeed([existing, sessions] as const);
|
||||
@@ -159,12 +223,14 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
|
||||
return BrowserSession.of({
|
||||
getPartition,
|
||||
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
|
||||
isPartition: (partition) =>
|
||||
partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
|
||||
partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
|
||||
getSession,
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
selectSessions(sessions, partitions).map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
@@ -180,10 +246,10 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}),
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
selectSessions(sessions, partitions).map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) =>
|
||||
|
||||
@@ -272,6 +272,7 @@ const makeTestPreviewWebContents = (
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -382,6 +383,7 @@ const makeFaviconWebContents = (options?: {
|
||||
send: webviewSend,
|
||||
session: { fetch },
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
debugger: {
|
||||
@@ -474,6 +476,67 @@ describe("PreviewManager", () => {
|
||||
webviewSend.mockClear();
|
||||
});
|
||||
|
||||
effectIt.effect("keeps preview shortcuts out of the host window", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
const sendInputEvent = vi.fn();
|
||||
const hostWebContents = { sendInputEvent };
|
||||
Object.assign(preview.webContents, { hostWebContents });
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
yield* manager.setMainWindow({
|
||||
isDestroyed: () => false,
|
||||
once: vi.fn(),
|
||||
webContents: hostWebContents,
|
||||
} as never);
|
||||
yield* manager.createTab("tab_keys");
|
||||
yield* manager.registerWebview("tab_keys", 42);
|
||||
|
||||
expect(
|
||||
(preview.webContents as Electron.WebContents).setIgnoreMenuShortcuts,
|
||||
).toHaveBeenCalledWith(true);
|
||||
const beforeInput = preview.listeners.get("before-input-event")!;
|
||||
for (const control of [false, true]) {
|
||||
for (const key of ["k", ",", "w", "j", "q", "+", "a", "c", "v", "x"]) {
|
||||
for (const type of ["keyDown", "keyUp"]) {
|
||||
const preventDefault = vi.fn();
|
||||
beforeInput(
|
||||
{ preventDefault } as never,
|
||||
{ type, key, meta: !control, control, shift: key === "j", alt: false } as never,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(sendInputEvent).not.toHaveBeenCalled();
|
||||
|
||||
const preventDefault = vi.fn();
|
||||
beforeInput(
|
||||
{ preventDefault } as never,
|
||||
{
|
||||
type: "keyDown",
|
||||
key: "r",
|
||||
meta: true,
|
||||
control: false,
|
||||
shift: false,
|
||||
alt: false,
|
||||
} as never,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(preventDefault).toHaveBeenCalledOnce();
|
||||
expect(preview.reload).toHaveBeenCalledOnce();
|
||||
expect(sendInputEvent).not.toHaveBeenCalled();
|
||||
|
||||
const setIgnoreMenuShortcuts = vi.fn();
|
||||
preview.listeners.get("did-create-window")!({
|
||||
webContents: { setIgnoreMenuShortcuts, setWindowOpenHandler: vi.fn() },
|
||||
} as never);
|
||||
expect(setIgnoreMenuShortcuts).toHaveBeenCalledWith(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -617,6 +680,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -677,6 +741,68 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("detaches through the pinned debugger after the webview is destroyed", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
// Real Electron throws on any `wc.debugger` access once the
|
||||
// WebContents is destroyed, so cleanup must go through the debugger
|
||||
// reference captured at attach time (electron/electron#53376).
|
||||
let destroyed = false;
|
||||
let attached = false;
|
||||
const debuggerOff = vi.fn();
|
||||
const debuggerDetach = vi.fn(() => {
|
||||
attached = false;
|
||||
});
|
||||
const wcDebugger = {
|
||||
isAttached: () => attached,
|
||||
attach: vi.fn(() => {
|
||||
attached = true;
|
||||
}),
|
||||
detach: debuggerDetach,
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: debuggerOff,
|
||||
};
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => destroyed,
|
||||
getType: () => "webview",
|
||||
getURL: () => "http://localhost:3200/",
|
||||
getTitle: () => "Preview",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
setAudioMuted: vi.fn(),
|
||||
isCurrentlyAudible: () => false,
|
||||
reload: vi.fn(),
|
||||
loadURL: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
get debugger() {
|
||||
if (destroyed) throw new Error("Object has been destroyed");
|
||||
return wcDebugger;
|
||||
},
|
||||
} as never);
|
||||
yield* manager.createTab("tab_pinned_debugger");
|
||||
yield* manager.registerWebview("tab_pinned_debugger", 42);
|
||||
yield* manager.setColorScheme("tab_pinned_debugger", "dark");
|
||||
expect(attached).toBe(true);
|
||||
destroyed = true;
|
||||
|
||||
yield* manager.navigate("tab_pinned_debugger", "https://example.com/");
|
||||
|
||||
expect(debuggerOff).toHaveBeenCalledWith("message", expect.any(Function));
|
||||
expect(debuggerDetach).toHaveBeenCalledOnce();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1161,6 +1287,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1225,6 +1352,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1265,6 +1393,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1311,6 +1440,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1366,6 +1496,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1463,6 +1594,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1798,6 +1930,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1890,6 +2023,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -1926,10 +2060,30 @@ describe("PreviewManager", () => {
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
|
||||
// Chromium reports UnknownVizError while a hidden guest warms its
|
||||
// first compositor frame, so transient failures are retried.
|
||||
capturePage.mockClear();
|
||||
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
|
||||
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
|
||||
const retriedFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const retriedExit = yield* Fiber.join(retriedFiber);
|
||||
expect(Exit.isSuccess(retriedExit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(3);
|
||||
|
||||
// A persistent failure still surfaces once the retries are spent.
|
||||
capturePage.mockClear();
|
||||
const captureCause = new Error("capture failed");
|
||||
capturePage.mockRejectedValueOnce(captureCause);
|
||||
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
|
||||
capturePage.mockRejectedValue(captureCause);
|
||||
const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const exit = yield* Fiber.join(failingFiber);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(3);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
@@ -2263,6 +2417,127 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("stops capture retries when the tab swaps during the retry delay", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const capturePage = vi.fn(async () => ({
|
||||
toPNG: () => Buffer.from("png"),
|
||||
toJPEG: () => Buffer.from("jpeg"),
|
||||
getSize: () => ({ width: 100, height: 80 }),
|
||||
}));
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
|
||||
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
// Let the rejection schedule its retry before replacing the guest.
|
||||
yield* TestClock.adjust(60);
|
||||
expect(capturePage).toHaveBeenCalledTimes(1);
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
|
||||
yield* manager.registerWebview("tab_1", 43);
|
||||
yield* TestClock.adjust(1_000);
|
||||
const exit = yield* Fiber.join(fiber);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(1);
|
||||
expect(writeFile).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("discards a screenshot that resolves after its guest is replaced", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const image = {
|
||||
toPNG: () => Buffer.from("stale-png"),
|
||||
toJPEG: () => Buffer.from("stale-jpeg"),
|
||||
getSize: () => ({ width: 100, height: 80 }),
|
||||
};
|
||||
const pending = Promise.withResolvers<typeof image>();
|
||||
const capturePage = vi.fn(() => pending.promise);
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(0);
|
||||
expect(capturePage).toHaveBeenCalledOnce();
|
||||
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
|
||||
yield* manager.registerWebview("tab_1", 43);
|
||||
pending.resolve(image);
|
||||
const exit = yield* Fiber.join(fiber);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledOnce();
|
||||
expect(writeFile).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("releases snapshot control when every capture attempt stalls", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const capturePage = vi.fn(() => new Promise<TestCapturedPreviewImage>(() => {}));
|
||||
const wc = makeTestPreviewWebContents(capturePage);
|
||||
Object.assign(wc, { isDevToolsOpened: () => false });
|
||||
Object.assign(wc.debugger, {
|
||||
sendCommand: vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (method === "Runtime.evaluate") {
|
||||
return {
|
||||
result: {
|
||||
value:
|
||||
params?.["expression"] === "42"
|
||||
? 42
|
||||
: {
|
||||
url: "https://example.com",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return method === "Accessibility.getFullAXTree" ? { nodes: [] } : undefined;
|
||||
}),
|
||||
});
|
||||
fromId.mockReturnValue(wc);
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
const snapshot = yield* Effect.exit(manager.automationSnapshot("tab_1")).pipe(
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* TestClock.adjust(100);
|
||||
expect(capturePage).toHaveBeenCalledOnce();
|
||||
const evaluate = yield* manager
|
||||
.automationEvaluate("tab_1", { expression: "42" })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
expect(evaluate.pollUnsafe()).toBeUndefined();
|
||||
|
||||
yield* TestClock.adjust(4_000);
|
||||
const exit = yield* Fiber.join(snapshot);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(capturePage).toHaveBeenCalledTimes(3);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewOperationError",
|
||||
operation: "automationSnapshot.capturePage",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause: { _tag: "TimeoutError" },
|
||||
});
|
||||
expect(yield* Fiber.join(evaluate)).toBe(42);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("grants each concurrent preview recording its own tab frame", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2307,6 +2582,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -2609,6 +2885,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3112,6 +3389,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3137,6 +3415,166 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("settles the pick when the annotation screenshot never arrives", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isFocused: () => true,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
setAudioMuted: vi.fn(),
|
||||
isCurrentlyAudible: () => false,
|
||||
on: vi.fn(),
|
||||
once: vi.fn(),
|
||||
off: vi.fn(),
|
||||
// A wedged compositor leaves `capturePage` pending forever.
|
||||
capturePage: vi.fn(() => new Promise(() => {})),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof onPicked) => {
|
||||
if (channel === "preview:element-picked") onPicked = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
onPicked?.(
|
||||
{},
|
||||
{
|
||||
id: "annotation_1",
|
||||
pageUrl: "https://example.com",
|
||||
pageTitle: "Example",
|
||||
comment: "Tighten this spacing",
|
||||
elements: [],
|
||||
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
|
||||
strokes: [],
|
||||
styleChanges: [],
|
||||
screenshot: null,
|
||||
createdAt: "2026-06-11T00:00:00.000Z",
|
||||
},
|
||||
null,
|
||||
"send",
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(pick.pollUnsafe()).toBeUndefined();
|
||||
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
// The pick has to give up on the crop rather than strand the renderer,
|
||||
// which would leave the composer stuck on "Capturing…".
|
||||
const result = yield* Fiber.join(pick);
|
||||
expect(result?.annotation.screenshot).toBeNull();
|
||||
expect(result?.screenshotFailed).toBe(true);
|
||||
expect(result?.submission).toBe("send");
|
||||
expect(webviewSend).toHaveBeenCalledWith("preview:annotation-captured");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("a stale capture from a replaced pick never touches the next pick", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isFocused: () => true,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
setAudioMuted: vi.fn(),
|
||||
isCurrentlyAudible: () => false,
|
||||
on: vi.fn(),
|
||||
once: vi.fn(),
|
||||
off: vi.fn(),
|
||||
capturePage: vi.fn(() => new Promise(() => {})),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof onPicked) => {
|
||||
if (channel === "preview:element-picked") onPicked = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const annotation = {
|
||||
id: "annotation_1",
|
||||
pageUrl: "https://example.com",
|
||||
pageTitle: "Example",
|
||||
comment: "Tighten this spacing",
|
||||
elements: [],
|
||||
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
|
||||
strokes: [],
|
||||
styleChanges: [],
|
||||
screenshot: null,
|
||||
createdAt: "2026-06-11T00:00:00.000Z",
|
||||
};
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const firstPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
// The first pick submits and its crop hangs.
|
||||
onPicked?.({}, annotation, null, "send");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// A second pick on the same tab replaces the first, which resumes null.
|
||||
const secondPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
expect(yield* Fiber.join(firstPick)).toBeNull();
|
||||
webviewSend.mockClear();
|
||||
|
||||
// The first pick's crop times out while the second pick is live. It
|
||||
// must not signal the overlay, which would tear down the second pick.
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
expect(webviewSend).not.toHaveBeenCalledWith("preview:annotation-captured");
|
||||
expect(secondPick.pollUnsafe()).toBeUndefined();
|
||||
|
||||
onPicked?.({}, { ...annotation, id: "annotation_2" }, null, "attach");
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
const result = yield* Fiber.join(secondPick);
|
||||
expect(result?.annotation.id).toBe("annotation_2");
|
||||
expect(result?.submission).toBe("attach");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("navigates the guest history when the thumb-button ipc fires", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -3170,6 +3608,7 @@ describe("PreviewManager", () => {
|
||||
goBack,
|
||||
goForward,
|
||||
},
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3299,6 +3738,7 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3399,6 +3839,7 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3554,6 +3995,7 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
@@ -3618,6 +4060,7 @@ describe("PreviewManager", () => {
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setIgnoreMenuShortcuts: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
|
||||
+205
-113
@@ -48,6 +48,7 @@ import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -113,6 +114,13 @@ const MAX_SCREENSHOT_WIDTH = 1280;
|
||||
const RECORDING_ARM_GRACE_MS = 10_000;
|
||||
const PICTURE_IN_PICTURE_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);
|
||||
const PICTURE_IN_PICTURE_JPEG_QUALITY = 80;
|
||||
/**
|
||||
* Cold guests can reject capturePage with UnknownVizError or never settle it.
|
||||
* Bound each attempt so snapshots release control even when Chromium stalls.
|
||||
*/
|
||||
const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
|
||||
const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
|
||||
const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000;
|
||||
const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
|
||||
const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
|
||||
const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
|
||||
@@ -306,13 +314,24 @@ const normalizeCaptureRect = (value: unknown): PreviewAnnotationRect | null => {
|
||||
};
|
||||
};
|
||||
|
||||
/** `capturePage` never settles when the guest's compositor is wedged. */
|
||||
const ANNOTATION_SCREENSHOT_TIMEOUT = "5 seconds";
|
||||
|
||||
/**
|
||||
* Crops the guest for a picked annotation. A stalled `capturePage` resolves to
|
||||
* `null` after the timeout: the annotation is still sendable without its
|
||||
* screenshot, and the pick session must settle either way.
|
||||
*/
|
||||
const captureAnnotationScreenshot = (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
cropRect: PreviewAnnotationRect | null,
|
||||
): Effect.Effect<PreviewAnnotationPayload["screenshot"], PreviewManagerError> =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
// The unused abort signal is what makes this interruptible, and therefore
|
||||
// what lets the timeout below fire. Drop the parameter and a stalled
|
||||
// capture strands the pick session again.
|
||||
try: (_signal) =>
|
||||
wc.capturePage(
|
||||
cropRect
|
||||
? {
|
||||
@@ -331,7 +350,7 @@ const captureAnnotationScreenshot = (
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.map((image) => {
|
||||
Effect.map((image): PreviewAnnotationPayload["screenshot"] => {
|
||||
const size = image.getSize();
|
||||
return {
|
||||
dataUrl: image.toDataURL(),
|
||||
@@ -340,6 +359,15 @@ const captureAnnotationScreenshot = (
|
||||
cropRect: cropRect ?? { x: 0, y: 0, width: size.width, height: size.height },
|
||||
};
|
||||
}),
|
||||
Effect.timeoutOption(ANNOTATION_SCREENSHOT_TIMEOUT),
|
||||
Effect.flatMap((screenshot) =>
|
||||
Option.isSome(screenshot)
|
||||
? Effect.succeed(screenshot.value)
|
||||
: Effect.logWarning("preview annotation screenshot timed out").pipe(
|
||||
Effect.annotateLogs({ tabId, webContentsId: wc.id }),
|
||||
Effect.as(null),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const findZoomStep = (current: number): number => {
|
||||
@@ -417,6 +445,12 @@ interface PickSession {
|
||||
|
||||
interface BrowserControlSession {
|
||||
readonly webContentsId: number;
|
||||
// Pins the WebContents' Debugger wrapper for the session's lifetime.
|
||||
// Electron's Debugger is GC-managed but registered with Chromium as a raw
|
||||
// DevToolsAgentHostClient pointer; collecting it while attached crashes the
|
||||
// browser process (electron/electron#53376). Detach must also go through
|
||||
// this reference: `wc.debugger` throws once the WebContents is destroyed.
|
||||
readonly debugger: Electron.Debugger;
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly onMessage: (
|
||||
@@ -439,22 +473,6 @@ interface ExpectedAgentInput {
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
|
||||
key: string;
|
||||
meta: boolean;
|
||||
shift: boolean;
|
||||
control: boolean;
|
||||
}> = Object.freeze([
|
||||
// mod+shift+J → preview.toggle
|
||||
{ key: "j", meta: true, shift: true, control: false },
|
||||
// mod+K → command palette
|
||||
{ key: "k", meta: true, shift: false, control: false },
|
||||
// mod+, → settings (macOS convention)
|
||||
{ key: ",", meta: true, shift: false, control: false },
|
||||
// mod+W → close tab/panel
|
||||
{ key: "w", meta: true, shift: false, control: false },
|
||||
]);
|
||||
|
||||
/**
|
||||
* Protocols a preview page may open in a real popup window.
|
||||
*
|
||||
@@ -629,6 +647,42 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try: evaluate,
|
||||
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
|
||||
});
|
||||
const capturePageWithRetry = Effect.fn("PreviewManager.capturePageWithRetry")(function* (
|
||||
errorContext: PreviewOperationContext,
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const requireCurrentGuest = Effect.gen(function* () {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
if (wc.isDestroyed() || tabs.get(tabId)?.webContentsId !== wc.id) {
|
||||
return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId: wc.id });
|
||||
}
|
||||
});
|
||||
const capture = Effect.gen(function* () {
|
||||
// Check after the retry delay, and again before accepting its result.
|
||||
yield* requireCurrentGuest;
|
||||
const image = yield* Effect.tryPromise({
|
||||
// An abort-signal parameter makes a stalled promise interruptible.
|
||||
try: (_signal) => wc.capturePage(),
|
||||
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
|
||||
}).pipe(
|
||||
Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
|
||||
Effect.catchTags({
|
||||
TimeoutError: (cause) =>
|
||||
Effect.fail(new PreviewOperationError({ ...errorContext, cause })),
|
||||
}),
|
||||
);
|
||||
yield* requireCurrentGuest;
|
||||
return image;
|
||||
});
|
||||
return yield* capture.pipe(
|
||||
Effect.retry({
|
||||
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
|
||||
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
|
||||
while: isPreviewOperationError,
|
||||
}),
|
||||
);
|
||||
});
|
||||
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
const currentMillis = Clock.currentTimeMillis;
|
||||
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>
|
||||
@@ -1164,6 +1218,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const wcDebugger = wc.debugger;
|
||||
const handleDebuggerMessage = Effect.fnUntraced(function* (
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -1176,7 +1231,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
() => wcDebugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
@@ -1224,8 +1279,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
),
|
||||
attempt({ operation: "detachControlSession", webContentsId: wc.id }, () => {
|
||||
wc.debugger.off("message", onMessage);
|
||||
if (wc.debugger.isAttached()) wc.debugger.detach();
|
||||
wcDebugger.off("message", onMessage);
|
||||
if (wcDebugger.isAttached()) wcDebugger.detach();
|
||||
}).pipe(Effect.ignore),
|
||||
],
|
||||
{ discard: true },
|
||||
@@ -1233,6 +1288,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const control: BrowserControlSession = {
|
||||
webContentsId: wc.id,
|
||||
debugger: wcDebugger,
|
||||
semaphore,
|
||||
scope,
|
||||
onMessage,
|
||||
@@ -1248,15 +1304,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
);
|
||||
yield* attempt({ operation: "attachDebuggerListeners", webContentsId: wc.id }, () => {
|
||||
wc.debugger.on("message", onMessage);
|
||||
wc.debugger.attach("1.3");
|
||||
wcDebugger.on("message", onMessage);
|
||||
wcDebugger.attach("1.3");
|
||||
});
|
||||
yield* Effect.all(
|
||||
["Runtime.enable", "Accessibility.enable", "Network.enable", "Log.enable"].map(
|
||||
(method) =>
|
||||
attemptPromise(
|
||||
{ operation: `initializeDebugger.${method}`, webContentsId: wc.id },
|
||||
() => wc.debugger.sendCommand(method),
|
||||
() => wcDebugger.sendCommand(method),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
@@ -1345,7 +1401,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const result = yield* attemptPromise(
|
||||
{ operation: `${action}.${method}`, tabId, webContentsId: wc.id },
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
() => control.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
const after = (yield* Ref.get(controlEpochRef)).get(tabId) ?? 0;
|
||||
if (after !== epoch) {
|
||||
@@ -1369,7 +1425,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
() => control.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1507,16 +1563,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
});
|
||||
|
||||
const isAppShortcut = (input: Electron.Input): boolean =>
|
||||
input.type === "keyDown" &&
|
||||
APP_FORWARDED_SHORTCUTS.some(
|
||||
(shortcut) =>
|
||||
shortcut.key.toLowerCase() === input.key.toLowerCase() &&
|
||||
shortcut.meta === input.meta &&
|
||||
shortcut.shift === input.shift &&
|
||||
shortcut.control === input.control,
|
||||
);
|
||||
|
||||
const computeNavStatus = (wc: Electron.WebContents): PreviewNavStatus => {
|
||||
const url = wc.getURL();
|
||||
const title = wc.getTitle();
|
||||
@@ -1791,30 +1837,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}).pipe(Effect.ignore),
|
||||
);
|
||||
};
|
||||
const forwardShortcut = Effect.fn("PreviewManager.forwardShortcut")(function* (
|
||||
event: Electron.Event,
|
||||
input: Electron.Input,
|
||||
) {
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
if (!isAppShortcut(input) || Option.isNone(mainWindow) || mainWindow.value.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
mainWindow.value.webContents.sendInputEvent({
|
||||
type: "keyDown",
|
||||
keyCode: input.key,
|
||||
modifiers: [
|
||||
...(input.meta ? (["meta"] as const) : []),
|
||||
...(input.shift ? (["shift"] as const) : []),
|
||||
...(input.control ? (["control"] as const) : []),
|
||||
...(input.alt ? (["alt"] as const) : []),
|
||||
],
|
||||
});
|
||||
});
|
||||
// A popup opens with Electron's default handler, so the page inside it could
|
||||
// otherwise spawn native windows without limit. Nothing in an OAuth flow
|
||||
// opens a second popup, so the chain stops at the first one.
|
||||
const windowCreated = (window: Electron.BrowserWindow): void => {
|
||||
window.webContents.setIgnoreMenuShortcuts(true);
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
};
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
@@ -1827,7 +1854,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
return;
|
||||
}
|
||||
runFork(forwardShortcut(event, input));
|
||||
};
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
@@ -1850,6 +1876,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
// Preview input belongs to the page, including keys injected through CDP.
|
||||
// Never let it invoke the host application's menu accelerators.
|
||||
wc.setIgnoreMenuShortcuts(true);
|
||||
wc.on("did-start-navigation", navigationStarted);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncInPageNavigation);
|
||||
@@ -2370,30 +2399,52 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
|
||||
(resume) => {
|
||||
// Declared first so cleanup can check slot ownership by identity
|
||||
// without a type cycle through the cancel effect it builds.
|
||||
const session: PickSession = { cancel: Effect.suspend(() => cancelPickSession()) };
|
||||
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
|
||||
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
|
||||
wc.ipc.removeListener(ELEMENT_PICKED_CHANNEL, onMessage);
|
||||
wc.off("destroyed", onDestroyed);
|
||||
wc.off("did-start-navigation", onNavigated);
|
||||
}).pipe(Effect.ignore);
|
||||
// Only drop the slot while it is still ours. A newer session may
|
||||
// already have swapped itself in before cancelling this one.
|
||||
yield* Ref.update(pickSessionsRef, (sessions) =>
|
||||
replaceMap(sessions, (copy) => {
|
||||
copy.delete(tabId);
|
||||
}),
|
||||
sessions.get(tabId) === session
|
||||
? replaceMap(sessions, (copy) => {
|
||||
copy.delete(tabId);
|
||||
})
|
||||
: sessions,
|
||||
);
|
||||
});
|
||||
// Every exit from this session runs through `claimSettle`, so the
|
||||
// renderer's `pickElement` promise resolves exactly once. The previous
|
||||
// identity check let a cancelled or replaced session return without
|
||||
// resuming, which left the composer waiting forever.
|
||||
let settled = false;
|
||||
const claimSettle = (): boolean => {
|
||||
if (settled) return false;
|
||||
settled = true;
|
||||
return true;
|
||||
};
|
||||
const finishPick = Effect.fn("PreviewManager.finishPickElement")(function* (
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
});
|
||||
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
|
||||
if (!active || active.cancel !== cancel) return;
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
if (!claimSettle()) return;
|
||||
yield* finishPick(payload);
|
||||
});
|
||||
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
|
||||
runFork(settlePick(payload));
|
||||
};
|
||||
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
|
||||
if (!claimSettle()) return;
|
||||
yield* cleanup();
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
const activeTab = tabs.get(tabId);
|
||||
@@ -2412,7 +2463,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
resume(Effect.succeed(null));
|
||||
});
|
||||
const cancel = cancelPickSession();
|
||||
const onMessage = (_event: Electron.IpcMainEvent, ...args: unknown[]): void => {
|
||||
const payload = args[0];
|
||||
if (!isPreviewAnnotationPayload(payload)) {
|
||||
@@ -2423,19 +2473,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const submission = args[2] === "send" ? "send" : "attach";
|
||||
runFork(
|
||||
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
|
||||
onSuccess: (screenshot) =>
|
||||
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
|
||||
// The renderer cannot tell a dropped crop from a comment-only
|
||||
// pick by the null alone, so a failed or timed-out capture is
|
||||
// flagged on the result.
|
||||
Effect.match({
|
||||
onFailure: (): PreviewAnnotationSubmissionResult => ({
|
||||
annotation: payload,
|
||||
submission,
|
||||
screenshotFailed: true,
|
||||
}),
|
||||
onSuccess: (screenshot): PreviewAnnotationSubmissionResult =>
|
||||
screenshot === null
|
||||
? { annotation: payload, submission, screenshotFailed: true }
|
||||
: { annotation: { ...payload, screenshot }, submission },
|
||||
}),
|
||||
Effect.ensuring(
|
||||
attempt(
|
||||
Effect.flatMap((result) => {
|
||||
// A capture that outlives its session must not touch the
|
||||
// overlay: the preload tears down on the captured signal, and
|
||||
// by now it may be running a newer pick.
|
||||
if (!claimSettle()) return Effect.void;
|
||||
return attempt(
|
||||
{ operation: "pickElement.captureComplete", tabId, webContentsId: wc.id },
|
||||
() => {
|
||||
if (!wc.isDestroyed()) wc.send(ANNOTATION_CAPTURED_CHANNEL);
|
||||
},
|
||||
).pipe(Effect.ignore),
|
||||
),
|
||||
).pipe(Effect.ignore, Effect.andThen(finishPick(result)));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -2449,6 +2512,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
if (isMainFrame) settle(null);
|
||||
};
|
||||
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
|
||||
// Two picks on one tab can overlap. Swap this session in and cancel
|
||||
// the previous holder in one step, so no third pick can slip into an
|
||||
// empty slot in between and the session we push out still resumes
|
||||
// its renderer.
|
||||
const replaced = yield* Ref.modify(pickSessionsRef, (sessions) => [
|
||||
sessions.get(tabId) ?? null,
|
||||
replaceMap(sessions, (copy) => {
|
||||
copy.set(tabId, session);
|
||||
}),
|
||||
]);
|
||||
if (replaced) yield* replaced.cancel;
|
||||
// A newer pick may have cancelled this session while the previous
|
||||
// one was torn down. Cleanup already ran, so attaching listeners now
|
||||
// would leak them and start an overlay nobody is waiting on.
|
||||
if (settled) return;
|
||||
yield* attempt({ operation: "pickElement.register", tabId, webContentsId: wc.id }, () => {
|
||||
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
|
||||
wc.once("destroyed", onDestroyed);
|
||||
@@ -2456,21 +2534,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
if (!wc.isFocused()) wc.focus();
|
||||
wc.send(START_PICK_CHANNEL, annotationTheme);
|
||||
});
|
||||
yield* Ref.update(pickSessionsRef, (sessions) =>
|
||||
replaceMap(sessions, (copy) => {
|
||||
copy.set(tabId, { cancel });
|
||||
}),
|
||||
);
|
||||
});
|
||||
runFork(
|
||||
registerPickElement().pipe(
|
||||
Effect.catch((error: PreviewManagerError) => {
|
||||
if (!claimSettle()) return Effect.void;
|
||||
resume(Effect.fail(error));
|
||||
return cleanup();
|
||||
}),
|
||||
),
|
||||
);
|
||||
return cancel;
|
||||
return session.cancel;
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -2513,9 +2587,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
yield* ensureControlSession(wc);
|
||||
const control = yield* ensureControlSession(wc);
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
control.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
@@ -2535,7 +2609,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
Effect.gen(function* () {
|
||||
const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (beforeAttach?.webContentsId !== wc.id) return;
|
||||
yield* ensureControlSession(wc);
|
||||
const control = yield* ensureControlSession(wc);
|
||||
const afterAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (afterAttach?.webContentsId !== wc.id) {
|
||||
yield* detachControlSession(wc.id);
|
||||
@@ -2543,7 +2617,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
if (afterAttach.colorScheme !== "system") {
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
control.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
@@ -2618,13 +2692,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const [createdAt, millis, image] = yield* Effect.all([
|
||||
currentIso,
|
||||
currentMillis,
|
||||
attemptPromise(
|
||||
capturePageWithRetry(
|
||||
{
|
||||
operation: "captureScreenshot.capturePage",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.capturePage(),
|
||||
tabId,
|
||||
wc,
|
||||
),
|
||||
]);
|
||||
const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}`;
|
||||
@@ -3483,13 +3558,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const [accessibility, sourceImage, diagnostics, timelines] = yield* Effect.all([
|
||||
send("Accessibility.getFullAXTree"),
|
||||
attemptPromise(
|
||||
capturePageWithRetry(
|
||||
{
|
||||
operation: "automationSnapshot.capturePage",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.capturePage(),
|
||||
tabId,
|
||||
wc,
|
||||
),
|
||||
Ref.get(diagnosticsRef),
|
||||
Ref.get(actionTimelineRef),
|
||||
@@ -4409,7 +4485,11 @@ export class PreviewManager extends Context.Service<
|
||||
PreviewManager,
|
||||
{
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly getBrowserSession: (
|
||||
scope?: string,
|
||||
persistent?: boolean,
|
||||
namespace?: BrowserSession.BrowserSessionPartitionNamespace,
|
||||
) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (
|
||||
tabId: string,
|
||||
@@ -4440,9 +4520,17 @@ export class PreviewManager extends Context.Service<
|
||||
audioMuted: boolean,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly clearCookies: (
|
||||
partitions?: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: (
|
||||
partitions?: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (
|
||||
scope?: string,
|
||||
persistent?: boolean,
|
||||
namespace?: BrowserSession.BrowserSessionPartitionNamespace,
|
||||
) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
@@ -4514,15 +4602,17 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
|
||||
return PreviewManager.of({
|
||||
setMainWindow: operations.setMainWindow,
|
||||
getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")(function* (scope) {
|
||||
return yield* browserSession
|
||||
.getSession(scope)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PreviewOperationError({ operation: "getBrowserSession", cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")(
|
||||
function* (scope, persistent, namespace) {
|
||||
return yield* browserSession
|
||||
.getSession(scope, persistent, namespace)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PreviewOperationError({ operation: "getBrowserSession", cause }),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
isBrowserPartition: browserSession.isPartition,
|
||||
createTab: operations.createTab,
|
||||
closeTab: operations.closeTab,
|
||||
@@ -4539,31 +4629,33 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
setColorScheme: operations.setColorScheme,
|
||||
setAudioMuted: operations.setAudioMuted,
|
||||
openDevTools: operations.openDevTools,
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) {
|
||||
yield* browserSession
|
||||
.clearCookies()
|
||||
.clearCookies(partitions)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PreviewOperationError({ operation: "clearCookies", cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
clearCache: Effect.fn("PreviewManager.clearCache")(function* () {
|
||||
clearCache: Effect.fn("PreviewManager.clearCache")(function* (partitions) {
|
||||
yield* browserSession
|
||||
.clearCache()
|
||||
.clearCache(partitions)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new PreviewOperationError({ operation: "clearCache", cause })),
|
||||
);
|
||||
}),
|
||||
getBrowserPartition: Effect.fn("PreviewManager.getBrowserPartition")(function* (scope) {
|
||||
return yield* browserSession
|
||||
.getPartition(scope)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PreviewOperationError({ operation: "getBrowserPartition", cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
getBrowserPartition: Effect.fn("PreviewManager.getBrowserPartition")(
|
||||
function* (scope, persistent, namespace) {
|
||||
return yield* browserSession
|
||||
.getPartition(scope, persistent, namespace)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new PreviewOperationError({ operation: "getBrowserPartition", cause }),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
setAnnotationTheme: operations.setAnnotationTheme,
|
||||
pickElement: operations.pickElement,
|
||||
cancelPickElement: operations.cancelPickElement,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// @effect-diagnostics globalDate:off - This isolated Electron preload does not run inside an Effect runtime.
|
||||
// @effect-diagnostics globalDate:off globalTimers:off - This isolated Electron preload does not run inside an Effect runtime.
|
||||
import { ipcRenderer } from "electron";
|
||||
import { getElementContext } from "react-grab/primitives";
|
||||
import type {
|
||||
@@ -30,6 +30,8 @@ const Z_INDEX_OVERLAY = 2147483646;
|
||||
const PRIMARY = "var(--t3-primary)";
|
||||
const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
|
||||
const MAX_MARQUEE_ELEMENTS = 20;
|
||||
/** Upper bound on one element's React context lookup during submit. */
|
||||
const ELEMENT_CONTEXT_TIMEOUT_MS = 5_000;
|
||||
const CONTENT_LAYER_Z_INDEX = 1;
|
||||
const CHROME_LAYER_Z_INDEX = 10;
|
||||
|
||||
@@ -279,25 +281,67 @@ function toStackFrame(frame: {
|
||||
};
|
||||
}
|
||||
|
||||
async function captureElement(element: Element): Promise<PickedElementPayload | null> {
|
||||
/**
|
||||
* Resolves to `null` instead of hanging when `promise` outlives `millis`.
|
||||
* `getElementContext` walks the inspected page's React internals, and some
|
||||
* pages leave it pending forever. Without a bound, the whole submit chain
|
||||
* stalls and the overlay sits on "Capturing…".
|
||||
*/
|
||||
function withCaptureTimeout<A>(promise: Promise<A>, millis: number): Promise<A | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => resolve(null), millis);
|
||||
}),
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** Truncation for the DOM-only preview used when React context is unavailable. */
|
||||
const HTML_PREVIEW_MAX_CHARS = 500;
|
||||
|
||||
/**
|
||||
* Describes a picked element. The React context lookup can stall or throw on
|
||||
* some pages, so the element is never dropped: without context it still
|
||||
* carries its tag, a short HTML preview, and its rect so the crop stays on the
|
||||
* pick instead of falling back to the whole viewport.
|
||||
*/
|
||||
async function captureElement(element: Element): Promise<PickedElementPayload> {
|
||||
const base = {
|
||||
pageUrl: location.href,
|
||||
pageTitle: document.title?.trim() || null,
|
||||
tagName: element.tagName.toLowerCase(),
|
||||
pickedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
const context = await getElementContext(element);
|
||||
const stack = (context.stack ?? []).map(toStackFrame);
|
||||
return {
|
||||
pageUrl: location.href,
|
||||
pageTitle: document.title?.trim() || null,
|
||||
tagName: element.tagName.toLowerCase(),
|
||||
selector: context.selector,
|
||||
htmlPreview: context.htmlPreview ?? "",
|
||||
componentName: context.componentName,
|
||||
source: stack[0] ?? null,
|
||||
stack,
|
||||
styles: context.styles ?? "",
|
||||
pickedAt: new Date().toISOString(),
|
||||
};
|
||||
const context = await withCaptureTimeout(
|
||||
Promise.resolve(getElementContext(element)),
|
||||
ELEMENT_CONTEXT_TIMEOUT_MS,
|
||||
);
|
||||
if (context) {
|
||||
const stack = (context.stack ?? []).map(toStackFrame);
|
||||
return {
|
||||
...base,
|
||||
selector: context.selector,
|
||||
htmlPreview: context.htmlPreview ?? "",
|
||||
componentName: context.componentName,
|
||||
source: stack[0] ?? null,
|
||||
stack,
|
||||
styles: context.styles ?? "",
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
// Fall through to the DOM-only payload.
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
selector: null,
|
||||
htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS),
|
||||
componentName: null,
|
||||
source: null,
|
||||
stack: [],
|
||||
styles: "",
|
||||
};
|
||||
}
|
||||
|
||||
function createButton(label: string, title: string): HTMLButtonElement {
|
||||
@@ -1225,12 +1269,20 @@ function startAnnotation(): void {
|
||||
pendingCapture = true;
|
||||
submit.disabled = true;
|
||||
submit.textContent = "Capturing…";
|
||||
// Snapshot everything the annotation will carry before the capture runs.
|
||||
// The element context lookup can take up to its timeout, and the user can
|
||||
// keep editing meanwhile; the annotation must describe what they submitted.
|
||||
const submittedComment = comment.value.trim();
|
||||
const submittedRegions = [...regions];
|
||||
const submittedStrokes = [...strokes];
|
||||
const submittedStyleChanges = Array.from(styleChanges.values(), (change) => ({ ...change }));
|
||||
void Promise.all(
|
||||
Array.from(selected.values()).map(async (target) => {
|
||||
const element = await captureElement(target.element);
|
||||
if (!element) return null;
|
||||
for (const change of styleChanges.values()) {
|
||||
if (change.targetId === target.id) change.selector = element.selector;
|
||||
for (const change of submittedStyleChanges) {
|
||||
if (change.targetId === target.id && element.selector !== null) {
|
||||
change.selector = element.selector;
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: target.id,
|
||||
@@ -1238,30 +1290,39 @@ function startAnnotation(): void {
|
||||
rect: rectFromDomRect(target.element.getBoundingClientRect()),
|
||||
};
|
||||
}),
|
||||
).then((captured) => {
|
||||
const elements = captured.filter((target) => target !== null);
|
||||
const annotation: PreviewAnnotationPayload = {
|
||||
id: nextId("annotation"),
|
||||
pageUrl: location.href,
|
||||
pageTitle: document.title?.trim() || null,
|
||||
comment: comment.value.trim(),
|
||||
elements,
|
||||
regions: [...regions],
|
||||
strokes: [...strokes],
|
||||
styleChanges: Array.from(styleChanges.values()),
|
||||
screenshot: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
editor.style.display = "none";
|
||||
toolbar.style.display = "none";
|
||||
hoverOutline.style.display = "none";
|
||||
const screenshotRect = unionRects([
|
||||
...elements.map((target) => target.rect),
|
||||
...regions.map((region) => region.rect),
|
||||
...strokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
});
|
||||
)
|
||||
.then((elements) => {
|
||||
// The overlay may have been cancelled or replaced while the capture
|
||||
// ran. A late submit must not deliver into the next pick's listener.
|
||||
if (finished) return;
|
||||
const annotation: PreviewAnnotationPayload = {
|
||||
id: nextId("annotation"),
|
||||
pageUrl: location.href,
|
||||
pageTitle: document.title?.trim() || null,
|
||||
comment: submittedComment,
|
||||
elements,
|
||||
regions: submittedRegions,
|
||||
strokes: submittedStrokes,
|
||||
styleChanges: submittedStyleChanges,
|
||||
screenshot: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
editor.style.display = "none";
|
||||
toolbar.style.display = "none";
|
||||
hoverOutline.style.display = "none";
|
||||
const screenshotRect = unionRects([
|
||||
...elements.map((target) => target.rect),
|
||||
...submittedRegions.map((region) => region.rect),
|
||||
...submittedStrokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
})
|
||||
.catch(() => {
|
||||
// Last resort. Main is waiting on this message, so hand it an empty
|
||||
// pick rather than leaving the button stuck on "Capturing…" and the
|
||||
// renderer's pick promise pending. teardown is a no-op once finished.
|
||||
teardown(true);
|
||||
});
|
||||
};
|
||||
submit.addEventListener("click", () => submitAnnotation("attach"));
|
||||
root.addEventListener("keydown", (event) => {
|
||||
|
||||
@@ -54,7 +54,7 @@ const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
return {
|
||||
result: yield* settings.get,
|
||||
result: yield* Effect.result(settings.get),
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
records,
|
||||
};
|
||||
@@ -73,12 +73,13 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(FileSystem.layerNoop({}));
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Success") return assert.fail("expected a successful read");
|
||||
assert.isTrue(Option.isNone(result.result.success));
|
||||
assert.deepEqual(result.records, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs non-missing filesystem failures with the settings path", () => {
|
||||
it.effect("reports non-missing filesystem failures and logs the settings path", () => {
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -93,7 +94,12 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Failure") return assert.fail("expected a read failure");
|
||||
assert.instanceOf(
|
||||
result.result.failure,
|
||||
DesktopClientSettings.DesktopClientSettingsReadError,
|
||||
);
|
||||
assert.strictEqual(result.result.failure.cause, permissionError);
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0]?.message, [
|
||||
"Could not read desktop client settings.",
|
||||
@@ -103,7 +109,7 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("logs malformed settings documents with the settings path", () =>
|
||||
it.effect("reports malformed settings documents and logs the settings path", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
@@ -111,7 +117,12 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Failure") return assert.fail("expected a decode failure");
|
||||
assert.instanceOf(
|
||||
result.result.failure,
|
||||
DesktopClientSettings.DesktopClientSettingsReadError,
|
||||
);
|
||||
assert.equal(result.result.failure.operation, "decode-document");
|
||||
assert.equal(result.records.length, 1);
|
||||
const message = result.records[0]?.message;
|
||||
if (!Array.isArray(message)) {
|
||||
|
||||
@@ -18,13 +18,19 @@ const clientSettings: ClientSettings = {
|
||||
browserDefaultZoomFactor: 1.25,
|
||||
browserDefaultAppearance: "dark",
|
||||
browserRecordingFrameRate: 60,
|
||||
browserLinkTarget: "app",
|
||||
browserAutoShowFloatingPreview: false,
|
||||
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
|
||||
browserDefaultProfileId: "work",
|
||||
confirmQuit: "double-click",
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
confirmThreadUnpin: false,
|
||||
contextWindowMeterEnabled: false,
|
||||
composerCollapseOnScroll: true,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffLayout: "stacked",
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
fontFamilyCode: "",
|
||||
@@ -37,7 +43,10 @@ const clientSettings: ClientSettings = {
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
onboardingCompletedAt: null,
|
||||
panelAnimationDurationMs: 0,
|
||||
planModeEnabled: false,
|
||||
proactivePanelsEnabled: true,
|
||||
showSkillsInSlashMenu: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -48,6 +57,8 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
legacySidebarEnabled: false,
|
||||
loadBalancingEnabled: false,
|
||||
loadBalancingWeights: { "environment-1": 75, "environment-2": 0 },
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
@@ -127,6 +138,59 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
for (const failure of [
|
||||
{ label: "permission", reason: "PermissionDenied" },
|
||||
{ label: "I/O", reason: "Unknown" },
|
||||
] as const) {
|
||||
it.effect(`preserves saved preferences across ${failure.label} read failures and retries`, () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const savedSettings = {
|
||||
...clientSettings,
|
||||
onboardingCompletedAt: "2026-09-05T12:00:00.000Z",
|
||||
};
|
||||
yield* settings.set(savedSettings);
|
||||
const savedContents = yield* fileSystem.readFileString(environment.clientSettingsPath);
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: failure.reason,
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: environment.clientSettingsPath,
|
||||
});
|
||||
let failRead = true;
|
||||
const retryableSettings = yield* DesktopClientSettings.make.pipe(
|
||||
Effect.provideService(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.FileSystem.of({
|
||||
...fileSystem,
|
||||
readFileString: (path) =>
|
||||
Effect.suspend(() =>
|
||||
failRead ? Effect.fail(cause) : fileSystem.readFileString(path),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* retryableSettings.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
|
||||
assert.equal(error.operation, "read-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(environment.clientSettingsPath),
|
||||
savedContents,
|
||||
);
|
||||
|
||||
failRead = false;
|
||||
assert.deepEqual(yield* retryableSettings.get, Option.some(savedSettings));
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("reports the failed client settings write operation and path", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -213,17 +277,31 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats malformed client settings documents as absent", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.clientSettingsPath, "{not-json");
|
||||
for (const document of [
|
||||
{ label: "malformed JSON", contents: "{not-json" },
|
||||
{ label: "invalid direct settings", contents: '{"fontSizeCode":"large"}' },
|
||||
{ label: "invalid legacy settings", contents: '{"settings":{"fontSizeCode":"large"}}' },
|
||||
]) {
|
||||
it.effect(`reports ${document.label} without treating the settings file as absent`, () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.clientSettingsPath, document.contents);
|
||||
|
||||
assert.isTrue(Option.isNone(yield* settings.get));
|
||||
}),
|
||||
),
|
||||
);
|
||||
const error = yield* settings.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
|
||||
assert.equal(error.operation, "decode-document");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.instanceOf(error.cause, Schema.SchemaError);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(environment.clientSettingsPath),
|
||||
document.contents,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -12,25 +12,33 @@ import * as Ref from "effect/Ref";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
|
||||
const ClientSettingsDocumentSchema = Schema.Struct({
|
||||
settings: ClientSettingsSchema,
|
||||
});
|
||||
|
||||
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
|
||||
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
|
||||
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
|
||||
LegacyClientSettingsDocumentJson,
|
||||
const decodeClientSettingsDocument = Schema.decodeEffect(
|
||||
fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
);
|
||||
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
|
||||
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
|
||||
decodeLegacyClientSettingsDocumentJson(raw).pipe(
|
||||
Effect.map((document) => document.settings),
|
||||
Effect.catchTags({
|
||||
SchemaError: () => decodeClientSettingsJsonValue(raw),
|
||||
}),
|
||||
const decodeClientSettingsValue = Schema.decodeUnknownEffect(ClientSettingsSchema);
|
||||
const decodeClientSettingsJson = Effect.fnUntraced(function* (raw: string) {
|
||||
const document = yield* decodeClientSettingsDocument(raw);
|
||||
// Select the shape before validation so invalid legacy settings cannot become defaults.
|
||||
return yield* decodeClientSettingsValue(
|
||||
Object.hasOwn(document, "settings") ? document.settings : document,
|
||||
);
|
||||
});
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
export class DesktopClientSettingsReadError extends Schema.TaggedErrorClass<DesktopClientSettingsReadError>()(
|
||||
"DesktopClientSettingsReadError",
|
||||
{
|
||||
operation: Schema.Literals(["read-file", "decode-document"]),
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop client settings read failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
@@ -55,7 +63,7 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
{
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>, DesktopClientSettingsReadError>;
|
||||
readonly set: (
|
||||
settings: ClientSettings,
|
||||
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
@@ -65,7 +73,7 @@ export class DesktopClientSettings extends Context.Service<
|
||||
const readClientSettings = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
): Effect.Effect<Option.Option<ClientSettings>> =>
|
||||
): Effect.Effect<Option.Option<ClientSettings>, DesktopClientSettingsReadError> =>
|
||||
fileSystem.readFileString(settingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
@@ -74,7 +82,15 @@ const readClientSettings = (
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<string>()),
|
||||
Effect.andThen(
|
||||
Effect.fail(
|
||||
new DesktopClientSettingsReadError({
|
||||
operation: "read-file",
|
||||
path: settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Effect.flatMap(
|
||||
@@ -87,7 +103,15 @@ const readClientSettings = (
|
||||
SchemaError: (cause) =>
|
||||
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<ClientSettings>()),
|
||||
Effect.andThen(
|
||||
Effect.fail(
|
||||
new DesktopClientSettingsReadError({
|
||||
operation: "decode-document",
|
||||
path: settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
@@ -400,11 +401,12 @@ describe("DesktopSavedEnvironments", () => {
|
||||
|
||||
it.effect("reports saved environment filesystem reads separately from document decoding", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const registryPath = path.join(baseDir, "userdata", "saved-environments.json");
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -433,6 +435,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
it.effect("reports the failed saved environment write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
@@ -440,7 +443,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: path.join(baseDir, "userdata"),
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -456,11 +459,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, path.join(baseDir, "userdata"));
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop saved-environment write failed during create-directory at ${path.join(baseDir, "userdata")}.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as SshAuth from "@t3tools/ssh/auth";
|
||||
import { resolveSshTarget } from "@t3tools/ssh/command";
|
||||
import { discoverSshHosts } from "@t3tools/ssh/config";
|
||||
import {
|
||||
SshCommandError,
|
||||
@@ -54,6 +55,9 @@ export class DesktopSshEnvironment extends Context.Service<
|
||||
readonly discoverHosts: (input?: {
|
||||
readonly homeDir?: string;
|
||||
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
|
||||
readonly resolveHost: (
|
||||
alias: string,
|
||||
) => Effect.Effect<DesktopSshEnvironmentTarget, SshCommandError | SshInvalidTargetError>;
|
||||
readonly ensureEnvironment: (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
options?: { readonly issuePairingToken?: boolean },
|
||||
@@ -136,6 +140,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.provide(runtimeContext),
|
||||
Effect.withSpan("desktop.ssh.discoverHosts"),
|
||||
),
|
||||
resolveHost: (alias) =>
|
||||
resolveSshTarget(alias.trim()).pipe(
|
||||
Effect.provide(runtimeContext),
|
||||
Effect.withSpan("desktop.ssh.resolveHost"),
|
||||
),
|
||||
ensureEnvironment: (target, ensureOptions) =>
|
||||
manager
|
||||
.ensureEnvironment(target, ensureOptions)
|
||||
|
||||
@@ -794,7 +794,6 @@ describe("DesktopUpdates", () => {
|
||||
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
|
||||
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, settingsFailure);
|
||||
assert.strictEqual(error.cause.cause, diskFailure);
|
||||
|
||||
@@ -155,7 +155,6 @@ export const DesktopUpdateSetChannelError = Schema.Union([
|
||||
DesktopUpdateChannelPersistenceError,
|
||||
]);
|
||||
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
|
||||
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
|
||||
|
||||
export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
|
||||
@@ -105,6 +105,8 @@ function makeFakeBrowserWindow() {
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
setFullScreen: vi.fn(),
|
||||
setOpacity: vi.fn(),
|
||||
setTitle: vi.fn(),
|
||||
setTitleBarOverlay: vi.fn(),
|
||||
show: vi.fn(),
|
||||
@@ -127,6 +129,8 @@ function makeFakeBrowserWindow() {
|
||||
setZoomLevel: webContents.setZoomLevel,
|
||||
setBackgroundThrottling: webContents.setBackgroundThrottling,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
setFullScreen: window.setFullScreen,
|
||||
setOpacity: window.setOpacity,
|
||||
webContentsListeners,
|
||||
windowListeners,
|
||||
};
|
||||
@@ -276,6 +280,7 @@ function makeTestLayer(input: {
|
||||
input.openedExternalUrls?.push(url);
|
||||
return true;
|
||||
}),
|
||||
openSystemSettings: () => Effect.succeed(true),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
@@ -376,6 +381,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
openSystemSettings: () => Effect.succeed(true),
|
||||
copyText: () => Effect.void,
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
electronThemeLayer,
|
||||
@@ -394,6 +400,25 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
});
|
||||
|
||||
describe("DesktopWindow", () => {
|
||||
it("leaves fullscreen before concealing a pending quit", () => {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
|
||||
assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]);
|
||||
|
||||
fakeWindow.setOpacity.mockClear();
|
||||
fakeWindow.isFullScreen.mockReturnValue(true);
|
||||
DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
|
||||
assert.deepEqual(fakeWindow.setFullScreen.mock.calls, [[false]]);
|
||||
assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]);
|
||||
|
||||
fakeWindow.setOpacity.mockClear();
|
||||
fakeWindow.isFullScreen.mockReturnValue(false);
|
||||
fakeWindow.isDestroyed.mockReturnValue(true);
|
||||
DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
|
||||
assert.equal(fakeWindow.setOpacity.mock.calls.length, 0);
|
||||
});
|
||||
|
||||
it("restores bounds only when the window fits within a connected display", () => {
|
||||
const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
|
||||
const displays = [
|
||||
|
||||
@@ -207,6 +207,21 @@ export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function concealPendingQuitWindow(
|
||||
window: Pick<
|
||||
Electron.BrowserWindow,
|
||||
"isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
|
||||
>,
|
||||
): void {
|
||||
if (window.isDestroyed()) return;
|
||||
if (window.isFullScreen()) {
|
||||
window.setFullScreen(false);
|
||||
}
|
||||
// Electron implements window opacity on macOS and Windows. Linux keeps the
|
||||
// release-gated quit behavior but cannot make the pending window disappear.
|
||||
window.setOpacity(0);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -570,6 +585,9 @@ export const make = Effect.gen(function* () {
|
||||
window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
|
||||
}
|
||||
},
|
||||
// Keep the transparent window focused until the physical shortcut is
|
||||
// released so its remaining repeats cannot reach the next app.
|
||||
concealWindow: () => concealPendingQuitWindow(window),
|
||||
quit: () => {
|
||||
void runPromise(electronApp.quit);
|
||||
},
|
||||
|
||||
@@ -32,11 +32,13 @@ function makeHarness(options?: {
|
||||
getMode?: () => Promise<QuitConfirmationMode>;
|
||||
}) {
|
||||
const notifications: Array<QuitShortcutHintEvent> = [];
|
||||
const concealWindow = vi.fn();
|
||||
const quit = vi.fn();
|
||||
const handler = makeQuitShortcutHandler({
|
||||
platform: options?.platform ?? "darwin",
|
||||
getMode: options?.getMode ?? (() => Promise.resolve(options?.mode ?? "hold")),
|
||||
notify: (event) => notifications.push(event),
|
||||
concealWindow,
|
||||
quit,
|
||||
});
|
||||
const preventDefault = vi.fn();
|
||||
@@ -57,7 +59,7 @@ function makeHarness(options?: {
|
||||
await send(makeInput({ isAutoRepeat: true, ...repeatOverrides }));
|
||||
}
|
||||
};
|
||||
return { notifications, quit, preventDefault, send, holdFor };
|
||||
return { notifications, concealWindow, quit, preventDefault, send, holdFor };
|
||||
}
|
||||
|
||||
describe("makeQuitShortcutHandler", () => {
|
||||
@@ -82,10 +84,11 @@ describe("makeQuitShortcutHandler", () => {
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("quits after a completed hold is released", async () => {
|
||||
it("conceals a completed hold, then quits after release", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
|
||||
expect(harness.concealWindow).toHaveBeenCalledTimes(1);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
@@ -94,6 +97,81 @@ describe("makeQuitShortcutHandler", () => {
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("keeps a concealed hold committed when another key is pressed", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS);
|
||||
|
||||
await harness.send(makeInput({ key: "Shift", shift: true }));
|
||||
expect(harness.concealWindow).toHaveBeenCalledTimes(1);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps a concealed hold committed through a fresh Cmd+Q press", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS);
|
||||
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.concealWindow).toHaveBeenCalledTimes(1);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("quits when a completed hold goes quiet without release events", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS * 2);
|
||||
|
||||
// If neither keyUp reaches the handler, continued repeats must keep the
|
||||
// app alive. Once they stop, the quiet period is the release signal.
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("waits for slow repeats to stop before quitting", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
await harness.send(makeInput({ isAutoRepeat: true }));
|
||||
vi.advanceTimersByTime(900);
|
||||
await harness.send(makeInput({ isAutoRepeat: true }));
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
await harness.send(makeInput({ isAutoRepeat: true }));
|
||||
vi.advanceTimersByTime(1_799);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses the initial repeat delay when the first repeat completes the hold", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + 100);
|
||||
await harness.send(makeInput({ isAutoRepeat: true }));
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1_999);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("waits for Q release when Cmd is released first", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
@@ -115,6 +193,7 @@ describe("makeQuitShortcutHandler", () => {
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.concealWindow).not.toHaveBeenCalled();
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -130,6 +209,7 @@ describe("makeQuitShortcutHandler", () => {
|
||||
it("quits without showing a hint in direct mode", async () => {
|
||||
const harness = makeHarness({ mode: "direct" });
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.concealWindow).not.toHaveBeenCalled();
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
@@ -172,24 +252,31 @@ describe("makeQuitShortcutHandler", () => {
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("honors a quick double press when both key releases beat their mode reads", async () => {
|
||||
const resolvers: Array<(mode: QuitConfirmationMode) => void> = [];
|
||||
const harness = makeHarness({
|
||||
getMode: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
it.each(["direct", "hold", "double-click"] as const)(
|
||||
"quits on a quick second press without waiting for a pending %s mode read",
|
||||
async (mode) => {
|
||||
const resolvers: Array<(mode: QuitConfirmationMode) => void> = [];
|
||||
const harness = makeHarness({
|
||||
getMode: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
resolvers[1]?.("double-click");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
|
||||
resolvers[0]?.(mode);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("discards a stale mode resolution from a superseded press", async () => {
|
||||
// Press #1's mode is still pending when the user releases and
|
||||
@@ -223,6 +310,7 @@ describe("makeQuitShortcutHandler", () => {
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.concealWindow).not.toHaveBeenCalled();
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
|
||||
});
|
||||
@@ -287,12 +375,44 @@ describe("makeQuitShortcutHandler", () => {
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP, DOUBLE_CLICK_DOWN]);
|
||||
});
|
||||
|
||||
it("does not treat two quick presses as a quit in hold mode", async () => {
|
||||
it("quits on a quick second press in hold mode", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("quits on a quick second press in hold mode when the first release is unseen", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
expect(harness.concealWindow).not.toHaveBeenCalled();
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("does not count auto-repeat as a second press", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN]);
|
||||
});
|
||||
|
||||
it("does not count a released tap after another shortcut interrupts it", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
await harness.send(makeInput({ key: "c" }));
|
||||
vi.advanceTimersByTime(100);
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP, HOLD_DOWN]);
|
||||
});
|
||||
|
||||
@@ -11,9 +11,13 @@ export const QUIT_DOUBLE_PRESS_MS = 500;
|
||||
// release: macOS suppresses a letter keyUp while the command key is down, so a
|
||||
// tap release can go completely unseen and a release-based timer would quit
|
||||
// anyway. Once held, quitting waits for Q keyUp or a quiet grace period after
|
||||
// modifier keyUp so repeats cannot reach the next app. Keyboards with
|
||||
// auto-repeat disabled fall back to the application menu Quit action.
|
||||
// repeats stop so they cannot reach the next app. Keyboards with
|
||||
// auto-repeat disabled must use a double press or the application menu Quit action.
|
||||
// Supporting holds without repeats requires a native physical key-state check.
|
||||
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
|
||||
// A slow repeat rate can exceed the fixed grace. Waiting for two observed
|
||||
// cadences keeps the timer behind the next repeat without slowing normal rates.
|
||||
const QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER = 2;
|
||||
|
||||
export interface QuitHoldKeyInput {
|
||||
readonly type: string;
|
||||
@@ -29,6 +33,7 @@ export interface QuitShortcutOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly getMode: () => Promise<QuitConfirmationMode>;
|
||||
readonly notify: (event: QuitShortcutHintEvent) => void;
|
||||
readonly concealWindow: () => void;
|
||||
readonly quit: () => void;
|
||||
}
|
||||
|
||||
@@ -45,9 +50,11 @@ export function makeQuitShortcutHandler(
|
||||
let quitOnRelease = false;
|
||||
let heldSince = 0;
|
||||
let lastPressAt = 0;
|
||||
let lastRepeatAt = 0;
|
||||
let repeatCadenceMs = 0;
|
||||
// Incremented when a press is superseded or explicitly cancelled. A plain
|
||||
// key release does not invalidate its pending mode read: direct mode and a
|
||||
// completed second press must still be honored after that read settles.
|
||||
// key release does not invalidate its pending mode read: a direct-mode
|
||||
// press must still quit after that read settles.
|
||||
let generation = 0;
|
||||
|
||||
const clearWatchdog = () => {
|
||||
@@ -58,12 +65,14 @@ export function makeQuitShortcutHandler(
|
||||
};
|
||||
|
||||
const release = (cancelPendingMode = true, keepDoublePressHint = false) => {
|
||||
if (cancelPendingMode) generation += 1;
|
||||
if (!holding && !notified) return;
|
||||
const keepHint = keepDoublePressHint && mode === "double-click" && notified;
|
||||
if (cancelPendingMode) generation += 1;
|
||||
holding = false;
|
||||
armed = false;
|
||||
quitOnRelease = false;
|
||||
lastRepeatAt = 0;
|
||||
repeatCadenceMs = 0;
|
||||
if (keepHint) return;
|
||||
|
||||
mode = undefined;
|
||||
@@ -77,9 +86,19 @@ export function makeQuitShortcutHandler(
|
||||
// Dismisses any overlay first so a cancelled quit cannot leave a stale hint.
|
||||
const quitNow = () => {
|
||||
release();
|
||||
lastPressAt = 0;
|
||||
options.quit();
|
||||
};
|
||||
|
||||
const quitAfterQuietPeriod = () => {
|
||||
clearWatchdog();
|
||||
const quietPeriodMs = Math.max(
|
||||
QUIT_HOLD_RELEASE_GRACE_MS,
|
||||
repeatCadenceMs * QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER,
|
||||
);
|
||||
watchdog = setTimeout(quitNow, quietPeriodMs);
|
||||
};
|
||||
|
||||
return (event, input) => {
|
||||
const key = input.key.toLowerCase();
|
||||
if (input.type === "keyUp") {
|
||||
@@ -91,32 +110,40 @@ export function makeQuitShortcutHandler(
|
||||
if (!quitOnRelease) {
|
||||
release(false, true);
|
||||
} else {
|
||||
watchdog = setTimeout(quitNow, QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
quitAfterQuietPeriod();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (input.type !== "keyDown") return;
|
||||
|
||||
if (quitOnRelease && input.isAutoRepeat && key === "q") {
|
||||
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
|
||||
if (input.isAutoRepeat && modifierDown && key === "q") {
|
||||
const now = Date.now();
|
||||
repeatCadenceMs = now - (lastRepeatAt === 0 ? heldSince : lastRepeatAt);
|
||||
lastRepeatAt = now;
|
||||
}
|
||||
if (quitOnRelease) {
|
||||
event.preventDefault();
|
||||
clearWatchdog();
|
||||
if (key === "q") {
|
||||
if (modifierDown) {
|
||||
quitAfterQuietPeriod();
|
||||
} else {
|
||||
clearWatchdog();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
|
||||
if (!modifierDown || input.alt || input.shift || key !== "q") {
|
||||
// Re-pressing the platform modifier is the first half of a second full
|
||||
// quit shortcut, so it must not cancel an active double-press window.
|
||||
if (key === modifierKey && !input.alt && !input.shift) return;
|
||||
|
||||
// Any other key (or an extra modifier) pressed mid-hold breaks the
|
||||
// gesture; without this the hold timer keeps running through the
|
||||
// interruption and the next qualifying repeat would quit early. The
|
||||
// interrupted press also stops counting toward a double press, but only
|
||||
// here, not in release(), which runs mid-restart on an unseen-release
|
||||
// re-press and must not wipe that press's own tap timestamp.
|
||||
if ((holding || notified) && !input.isAutoRepeat) {
|
||||
// Other keys cancel the hold and the first tap, even after release.
|
||||
// Keep this separate from release(), which also runs when a fresh Q
|
||||
// keydown follows a keyUp that macOS did not deliver.
|
||||
if (!input.isAutoRepeat) {
|
||||
lastPressAt = 0;
|
||||
release();
|
||||
}
|
||||
@@ -129,7 +156,8 @@ export function makeQuitShortcutHandler(
|
||||
if (mode === "hold" && armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
|
||||
armed = false;
|
||||
quitOnRelease = true;
|
||||
clearWatchdog();
|
||||
options.concealWindow();
|
||||
quitAfterQuietPeriod();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -142,6 +170,13 @@ export function makeQuitShortcutHandler(
|
||||
if (holding || notified) release();
|
||||
|
||||
generation += 1;
|
||||
// Every mode accepts two presses. Quit before reading settings so a slow
|
||||
// read cannot delay the second press. Repeats never reach this branch.
|
||||
if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_PRESS_MS) {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
|
||||
const pressGeneration = generation;
|
||||
holding = true;
|
||||
heldSince = now;
|
||||
@@ -152,15 +187,6 @@ export function makeQuitShortcutHandler(
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
resolvedMode === "double-click" &&
|
||||
previousPressAt !== 0 &&
|
||||
now - previousPressAt <= QUIT_DOUBLE_PRESS_MS
|
||||
) {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
|
||||
if (resolvedMode === "double-click") {
|
||||
const remainingMs = QUIT_DOUBLE_PRESS_MS - (Date.now() - now);
|
||||
if (remainingMs <= 0) {
|
||||
|
||||
@@ -12,21 +12,17 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
buildWslNodeEnvPreamble,
|
||||
buildWslRuntimeInstallScript,
|
||||
buildWslRuntimeInvalidateScript,
|
||||
buildWslRuntimePruneScript,
|
||||
DesktopWslDistroListError,
|
||||
formatMissingToolsReason,
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseNodeVersion,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
parseWslRuntimeRoot,
|
||||
probeWslDistros,
|
||||
sanitizeWslRuntimeId,
|
||||
} from "./DesktopWslEnvironment.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
@@ -144,46 +140,19 @@ describe("probeWslDistros", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatNodePtyProbeFailureReason", () => {
|
||||
it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
|
||||
const reason = formatNodePtyProbeFailureReason(4);
|
||||
|
||||
expect(reason).toContain("packaged Linux node-pty binary was not included");
|
||||
expect(reason).toContain("--wsl-prebuild");
|
||||
});
|
||||
|
||||
it("leaves other node-pty load failures to the compatibility diagnostic", () => {
|
||||
expect(formatNodePtyProbeFailureReason(1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWslShellTransportFailureReason", () => {
|
||||
it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
|
||||
expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
|
||||
expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
|
||||
expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
|
||||
expect(formatWslShellTransportFailureReason(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildWslNodeEnvPreamble", () => {
|
||||
it("passes the required Node engine range into the shared resolver", () => {
|
||||
const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
|
||||
|
||||
expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
|
||||
expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
|
||||
preamble.lastIndexOf("ensure_remote_node_path || true"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the shared resolver permissive when no Node engine range is provided", () => {
|
||||
expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
|
||||
});
|
||||
});
|
||||
|
||||
describe("WSL runtime cache", () => {
|
||||
it("sanitizes cache ids before interpolating them into Linux paths", () => {
|
||||
expect(sanitizeWslRuntimeId("1.2.3/x64; touch /tmp/nope")).toBe("1.2.3_x64__touch__tmp_nope");
|
||||
it.each([
|
||||
[
|
||||
"install",
|
||||
(id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)),
|
||||
],
|
||||
["prune", buildWslRuntimePruneScript],
|
||||
["invalidate", buildWslRuntimeInvalidateScript],
|
||||
] as const)("sanitizes cache ids in the %s script", (_, buildScript) => {
|
||||
const runtimeId = "1.2.3/x64; touch /tmp/nope";
|
||||
const script = buildScript(runtimeId);
|
||||
expect(script).toContain("/1.2.3_x64__touch__tmp_nope");
|
||||
expect(script).not.toContain(runtimeId);
|
||||
});
|
||||
|
||||
it("installs through a temporary directory and only reuses valid completed caches", () => {
|
||||
@@ -198,13 +167,10 @@ describe("WSL runtime cache", () => {
|
||||
expect(script).toContain(' [ -f "$runtime_root/apps/server/dist/bin.mjs" ] &&');
|
||||
expect(script).toContain(' [ -f "$runtime_root/node_modules/node-pty/package.json" ] &&');
|
||||
expect(script).toContain(' node_pty_payload_present "$runtime_root"');
|
||||
expect(script).not.toContain("node_modules/effect/package.json");
|
||||
expect(script).toContain("if runtime_is_ready; then");
|
||||
expect(script).toContain("trap 'exit 1' HUP INT TERM");
|
||||
expect(script).toContain('exec 9> "$runtime_lock"');
|
||||
expect(script).toContain("flock -x 9");
|
||||
expect(script).not.toContain("runtime_lock_pid");
|
||||
expect(script).not.toContain("sleep 0.1");
|
||||
expect(script).not.toContain('rm -rf "$runtime_lock"');
|
||||
expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"');
|
||||
expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"');
|
||||
|
||||
@@ -147,7 +147,7 @@ const TIMEOUT_RESULT: ShellResult = {
|
||||
transportFailure: "timeout",
|
||||
};
|
||||
|
||||
export const formatWslShellTransportFailureReason = (
|
||||
const formatWslShellTransportFailureReason = (
|
||||
failure: ShellResult["transportFailure"],
|
||||
): string | null => {
|
||||
switch (failure) {
|
||||
@@ -165,7 +165,7 @@ export const formatWslShellTransportFailureReason = (
|
||||
// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
|
||||
// the same way. Passing the engine range lets the resolver fall through to
|
||||
// version managers like nvm when a system node exists but is too old.
|
||||
export const buildWslNodeEnvPreamble = (
|
||||
const buildWslNodeEnvPreamble = (
|
||||
nodeEngineRange?: string | null,
|
||||
): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
|
||||
ensure_remote_node_path || true
|
||||
@@ -263,8 +263,7 @@ const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";
|
||||
const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";
|
||||
const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;
|
||||
|
||||
export const sanitizeWslRuntimeId = (value: string): string =>
|
||||
value.replace(/[^A-Za-z0-9._-]/g, "_");
|
||||
const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_");
|
||||
|
||||
// `archiveSha256` is the digest the build recorded alongside the archive. The
|
||||
// install verifies the bytes before extracting, so an archive can never be
|
||||
@@ -491,7 +490,7 @@ export const parseWslRuntimeRoot = (stdout: string): string | null => {
|
||||
|
||||
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
|
||||
|
||||
export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
|
||||
const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
|
||||
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
|
||||
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
|
||||
: null;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { describe, it, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DISTRO_NAME_PATTERN,
|
||||
extractDistroFromUncPath,
|
||||
isValidDistroName,
|
||||
parseWslDistroList,
|
||||
resolveWslHomeUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "./wslPathParsing.ts";
|
||||
@@ -116,29 +114,6 @@ describe("wslUncPathToLinuxPath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslHomeUncPath", () => {
|
||||
const distros = [
|
||||
{ name: "Debian", isDefault: true, version: 2 as const },
|
||||
{ name: "Ubuntu", isDefault: false, version: 2 as const },
|
||||
];
|
||||
|
||||
it("uses the configured distro when one is selected", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: "Ubuntu" }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Ubuntu\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the actual default distro when config uses the WSL default", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the default path when no default distro is known", () => {
|
||||
expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslPickFolderDefaultPath", () => {
|
||||
const config = { distro: null };
|
||||
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
|
||||
@@ -184,23 +159,22 @@ describe("resolveWslPickFolderDefaultPath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
|
||||
describe("isValidDistroName", () => {
|
||||
it("accepts common distro names", () => {
|
||||
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
|
||||
expect(isValidDistroName(name)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names with trailing whitespace, hyphen, or dot", () => {
|
||||
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
expect(isValidDistroName(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names containing control or shell-meta characters", () => {
|
||||
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
expect(isValidDistroName(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1802 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user