Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95144d8d18 | ||
|
|
31078cb4e0 | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 | ||
|
|
3bdaa6e100 | ||
|
|
b7b00bfb9d | ||
|
|
ae2b523503 | ||
|
|
75b3b3c48a | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 |
No files matched your search
@@ -8,6 +8,13 @@
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
# returns a different RP ID or when multiple domains must be entitled.
|
||||
# T3CODE_APPLE_TEAM_ID=ABC1234567
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
test:
|
||||
name: Test
|
||||
@@ -60,52 +61,6 @@ jobs:
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
test_browser:
|
||||
name: Test Browser
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: vp run --filter @t3tools/web test:browser:install
|
||||
|
||||
- name: Browser test / Chat view
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
|
||||
|
||||
- name: Browser test / Chat markdown
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
|
||||
|
||||
- name: Browser test / Components
|
||||
working-directory: apps/web
|
||||
run: |
|
||||
vp test run --mode browser --browser=chromium \
|
||||
src/components/GitActionsControl.browser.tsx \
|
||||
src/components/KeybindingsToast.browser.tsx \
|
||||
src/components/ThreadTerminalDrawer.browser.tsx \
|
||||
src/components/chat/MessagesTimeline.browser.tsx \
|
||||
src/components/chat/ProviderModelPicker.browser.tsx \
|
||||
src/components/chat/CompactComposerControlsMenu.browser.tsx \
|
||||
src/components/settings/SettingsPanels.browser.tsx
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -180,12 +180,46 @@ jobs:
|
||||
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
relay_url: ${{ steps.public_config.outputs.relay_url }}
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- id: relay_state
|
||||
name: Read production relay tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
vp run --filter t3code-relay deploy \
|
||||
--stage prod \
|
||||
--read-state \
|
||||
--github-output \
|
||||
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
|
||||
|
||||
- name: Upload relay client tracing config
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing.env
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- id: public_config
|
||||
name: Resolve production relay public config
|
||||
shell: bash
|
||||
@@ -272,6 +306,20 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -377,6 +425,9 @@ jobs:
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
|
||||
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
|
||||
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
@@ -404,9 +455,21 @@ jobs:
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
|
||||
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
|
||||
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
|
||||
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
|
||||
security cms -D -i "$profile_path" >/dev/null
|
||||
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
|
||||
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
|
||||
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
@@ -508,6 +571,20 @@ jobs:
|
||||
- --filter=@t3tools/web...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -670,6 +747,20 @@ jobs:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -716,6 +807,9 @@ jobs:
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/electron": "catalog:",
|
||||
"@clerk/electron-passkeys": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
@@ -20,6 +22,7 @@
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
@@ -33,6 +34,8 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -57,7 +60,7 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -65,7 +68,7 @@ function killChildTreeByPid(pid, signal) {
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -194,7 +197,7 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
@@ -30,17 +31,11 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 10;
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
|
||||
function resolveDevelopmentProtocolCallbackPort() {
|
||||
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
|
||||
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
|
||||
return configuredPort + 1;
|
||||
}
|
||||
return 13774;
|
||||
}
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
@@ -97,7 +92,6 @@ function shellSingleQuote(value) {
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
|
||||
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
@@ -106,23 +100,12 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
|
||||
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
'for arg in "$@"; do',
|
||||
' case "$arg" in',
|
||||
" t3code-dev://auth/callback*)",
|
||||
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
|
||||
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
|
||||
" fi",
|
||||
" ;;",
|
||||
" esac",
|
||||
"done",
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
@@ -295,7 +278,11 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
@@ -308,7 +295,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (process.platform !== "linux") {
|
||||
if (hostPlatform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -338,7 +325,7 @@ export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
@@ -354,7 +341,7 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (process.platform !== "darwin" || !isDevelopment) {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { arch, platform, tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (process.platform) {
|
||||
switch (hostPlatform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -17,12 +21,12 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (process.platform !== "win32") {
|
||||
if (hostPlatform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +43,7 @@ function repairPathFile(electronDir, platformPath) {
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
@@ -58,7 +62,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -76,7 +80,7 @@ function missingRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -111,16 +115,16 @@ function runChecked(command, args) {
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
@@ -163,6 +163,16 @@ const bootstrap = Effect.gen(function* () {
|
||||
}
|
||||
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
|
||||
const backendConfig = yield* serverExposure.backendConfig;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const rendererTarget = environment.isDevelopment
|
||||
? Option.getOrThrow(environment.devServerUrl)
|
||||
: backendConfig.httpBaseUrl;
|
||||
yield* electronProtocol.registerDesktopProtocol({
|
||||
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
|
||||
targetOrigin: rendererTarget,
|
||||
backendOrigin: backendConfig.httpBaseUrl,
|
||||
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
|
||||
});
|
||||
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
|
||||
baseUrl: backendConfig.httpBaseUrl.href,
|
||||
});
|
||||
@@ -189,9 +199,8 @@ const startup = Effect.gen(function* () {
|
||||
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
@@ -209,7 +218,7 @@ const startup = Effect.gen(function* () {
|
||||
|
||||
yield* appIdentity.configure;
|
||||
yield* lifecycle.register;
|
||||
yield* cloudAuth.configure;
|
||||
yield* clerk.configure;
|
||||
|
||||
yield* electronApp.whenReady.pipe(
|
||||
Effect.withSpan("desktop.electron.whenReady"),
|
||||
@@ -218,7 +227,6 @@ const startup = Effect.gen(function* () {
|
||||
yield* logStartupInfo("app ready");
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* electronProtocol.registerDesktopFileProtocol;
|
||||
yield* updates.configure;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
@@ -49,7 +49,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
storageAdapter: {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
storageMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron", () => ({
|
||||
createClerkBridge: createClerkBridgeMock,
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import {
|
||||
createDesktopClerkBridge,
|
||||
resolveDesktopClerkFrontendApiHostname,
|
||||
} from "./DesktopClerk.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
describe("DesktopClerk", () => {
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname(publishableKey), "clerk.t3.codes");
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment: true,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(
|
||||
Layer.build(
|
||||
DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme: "t3code-dev", host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
|
||||
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() };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createClerkBridge } from "@clerk/electron";
|
||||
import { storage } from "@clerk/electron/storage";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export interface DesktopClerkShape {
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<DesktopClerk, DesktopClerkShape>()(
|
||||
"@t3tools/desktop/app/DesktopClerk",
|
||||
) {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
if (!normalizedKey) return undefined;
|
||||
|
||||
try {
|
||||
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
|
||||
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? undefined
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
renderer: {
|
||||
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
|
||||
host: ElectronProtocol.DESKTOP_HOST,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
|
||||
(bridge) => Effect.sync(() => bridge.cleanup()),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
yield* electronApp.on("second-instance", () => {
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.clerk.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClerk, make);
|
||||
@@ -1,302 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthHarness {
|
||||
readonly app: ElectronApp.ElectronAppShape;
|
||||
readonly window: ElectronWindow.ElectronWindowShape;
|
||||
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
|
||||
readonly protocolRegistrations: {
|
||||
readonly protocol: string;
|
||||
readonly path?: string;
|
||||
readonly args?: readonly string[];
|
||||
}[];
|
||||
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
|
||||
readonly reveals: unknown[];
|
||||
readonly layer: Layer.Layer<
|
||||
| DesktopCloudAuth.DesktopCloudAuth
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronWindow.ElectronWindow
|
||||
>;
|
||||
}
|
||||
|
||||
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
|
||||
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
|
||||
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
|
||||
const sends: CloudAuthHarness["sends"] = [];
|
||||
const reveals: unknown[] = [];
|
||||
const mainWindow = { id: "main-window" };
|
||||
|
||||
const app = ElectronApp.ElectronApp.of({
|
||||
metadata: Effect.succeed({
|
||||
appVersion: "0.0.0-test",
|
||||
appPath: "/tmp/t3-code-test",
|
||||
isPackaged: !input.isDevelopment,
|
||||
resourcesPath: "/tmp/t3-code-test/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
protocolRegistrations.push({
|
||||
protocol,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(args === undefined ? {} : { args }),
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
const erasedListener = listener as (...args: readonly unknown[]) => void;
|
||||
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
|
||||
}),
|
||||
});
|
||||
|
||||
const window = ElectronWindow.ElectronWindow.of({
|
||||
create: () => Effect.die("not used"),
|
||||
main: Effect.succeed(Option.some(mainWindow as never)),
|
||||
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: (target) =>
|
||||
Effect.sync(() => {
|
||||
reveals.push(target);
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
sends.push({ channel, args });
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
});
|
||||
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
isDevelopment: input.isDevelopment,
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
|
||||
|
||||
return {
|
||||
app,
|
||||
window,
|
||||
listeners,
|
||||
protocolRegistrations,
|
||||
sends,
|
||||
reveals,
|
||||
layer: Layer.mergeAll(
|
||||
DesktopCloudAuth.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
Layer.succeed(ElectronApp.ElectronApp, app),
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, window),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function emitAppEvent(
|
||||
harness: CloudAuthHarness,
|
||||
eventName: string,
|
||||
...args: readonly unknown[]
|
||||
): void {
|
||||
for (const listener of harness.listeners.get(eventName) ?? []) {
|
||||
listener(...args);
|
||||
}
|
||||
}
|
||||
|
||||
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
|
||||
|
||||
describe("DesktopCloudAuth", () => {
|
||||
it("uses separate callback schemes for packaged and development builds", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
|
||||
"t3code",
|
||||
);
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
|
||||
"t3code-dev",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only the expected scheme, host, path, and state", () => {
|
||||
assert.isNotNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native development callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code-dev",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code-dev://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
let prevented = false;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => (prevented = true) },
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.isTrue(prevented);
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.isString(harness.protocolRegistrations[0]?.path);
|
||||
assert.isArray(harness.protocolRegistrations[0]?.args);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.lengthOf(harness.reveals, 1);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
|
||||
const harness = makeHarness({ isDevelopment: false });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const validCallback = new URL(redirectUrl);
|
||||
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
const invalidCallback = new URL(validCallback);
|
||||
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
invalidCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
assert.deepEqual(harness.sends, []);
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code"],
|
||||
);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [validCallback.toString()],
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"routes second-instance callbacks and reveals the window for non-callback launches",
|
||||
() => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
const revealCountAfterCallback = harness.reveals.length;
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.equal(revealCountAfterCallback, 1);
|
||||
assert.equal(harness.reveals.length, 2);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,330 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
|
||||
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
|
||||
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
|
||||
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
|
||||
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
|
||||
|
||||
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
|
||||
"DesktopCloudAuthCallbackServerError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to start the desktop cloud auth callback server.";
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingCloudAuthRequest {
|
||||
readonly state: string;
|
||||
readonly redirectUrl: string;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthShape {
|
||||
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
|
||||
"@t3tools/desktop/app/DesktopCloudAuth",
|
||||
) {}
|
||||
|
||||
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
|
||||
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
|
||||
}
|
||||
|
||||
export function buildCloudAuthCallbackUrl(input: {
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): string {
|
||||
const url = new URL(
|
||||
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
|
||||
);
|
||||
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function parseCloudAuthCallbackUrl(input: {
|
||||
readonly rawUrl: unknown;
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
if (typeof input.rawUrl !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(input.rawUrl);
|
||||
if (url.protocol !== `${input.scheme}:`) return null;
|
||||
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
|
||||
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
|
||||
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function findCloudAuthCallbackUrl(input: {
|
||||
readonly values: readonly unknown[];
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
for (const value of input.values) {
|
||||
const url = parseCloudAuthCallbackUrl({
|
||||
rawUrl: value,
|
||||
scheme: input.scheme,
|
||||
state: input.state,
|
||||
});
|
||||
if (url) return url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveProtocolClientLaunchArgs(input: {
|
||||
readonly argv: readonly string[];
|
||||
}): readonly string[] {
|
||||
return input.argv.slice(1);
|
||||
}
|
||||
|
||||
function resolveConfiguredProtocolClient(): {
|
||||
readonly path: string;
|
||||
readonly args: readonly string[];
|
||||
} | null {
|
||||
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
|
||||
if (!path) return null;
|
||||
|
||||
return {
|
||||
path,
|
||||
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
|
||||
.split("\n")
|
||||
.map((arg) => arg.trim())
|
||||
.filter((arg) => arg.length > 0),
|
||||
};
|
||||
}
|
||||
|
||||
function isProtocolRegistrationManagedExternally(): boolean {
|
||||
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
|
||||
}
|
||||
|
||||
function resolveProtocolCallbackForwardUrl(): URL | null {
|
||||
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
|
||||
if (!rawUrl) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "http:") return null;
|
||||
if (url.hostname !== "127.0.0.1") return null;
|
||||
if (url.pathname !== "/auth/callback") return null;
|
||||
if (!url.port) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
|
||||
request?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
|
||||
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function ignoreCloudAuthCallback(_rawUrl: string) {}
|
||||
|
||||
function startProtocolCallbackForwardServer(
|
||||
callbackUrl: URL,
|
||||
dispatch: (rawUrl: string) => void,
|
||||
): Effect.Effect<void, never, Scope.Scope> {
|
||||
const port = Number.parseInt(callbackUrl.port, 10);
|
||||
const routesLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/auth/callback",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const rawUrl = yield* request.text;
|
||||
yield* Effect.sync(() => {
|
||||
dispatch(rawUrl);
|
||||
});
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const NodeHttp = yield* Effect.promise(() => import("node:http"));
|
||||
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: callbackUrl.hostname,
|
||||
port,
|
||||
});
|
||||
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
|
||||
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
|
||||
const makeCloudAuthRequestState = Effect.gen(function* () {
|
||||
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
|
||||
return `${left}${right}`.replaceAll("-", "");
|
||||
});
|
||||
|
||||
return DesktopCloudAuth.of({
|
||||
createRequest: Effect.gen(function* () {
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
const state = yield* makeCloudAuthRequestState.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
|
||||
);
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
|
||||
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
|
||||
const timeout = createCloudAuthRequestTimeout(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
});
|
||||
pendingAuthRequest = {
|
||||
state,
|
||||
redirectUrl,
|
||||
close: () => clearTimeout(timeout),
|
||||
};
|
||||
return redirectUrl;
|
||||
}),
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const scope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
}),
|
||||
);
|
||||
|
||||
if (isProtocolRegistrationManagedExternally()) {
|
||||
// Development macOS launchers set the default URL handler before the stock Electron
|
||||
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
|
||||
} else if (environment.isDevelopment) {
|
||||
const configuredClient = resolveConfiguredProtocolClient();
|
||||
if (configuredClient) {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
configuredClient.path,
|
||||
configuredClient.args,
|
||||
);
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
process.execPath,
|
||||
resolveProtocolClientLaunchArgs({ argv: process.argv }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(scheme);
|
||||
}
|
||||
|
||||
dispatchCloudAuthCallback = (rawUrl: string) => {
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
|
||||
: null;
|
||||
if (!callbackUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* electronWindow.sendAll(
|
||||
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
|
||||
if (environment.isDevelopment && protocolCallbackForwardUrl) {
|
||||
yield* startProtocolCallbackForwardServer(
|
||||
protocolCallbackForwardUrl,
|
||||
dispatchCloudAuthCallback,
|
||||
);
|
||||
}
|
||||
|
||||
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
|
||||
if (!hasInstanceLock) {
|
||||
return yield* electronApp.quit;
|
||||
}
|
||||
|
||||
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
|
||||
event.preventDefault?.();
|
||||
dispatchCloudAuthCallback(rawUrl);
|
||||
});
|
||||
|
||||
yield* electronApp.on<[Electron.Event, readonly string[]]>(
|
||||
"second-instance",
|
||||
(_event, argv) => {
|
||||
const values = resolveProtocolClientLaunchArgs({ argv });
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
|
||||
: null;
|
||||
if (callbackUrl) {
|
||||
dispatchCloudAuthCallback(callbackUrl.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopCloudAuth, make);
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
function makeSafeStorageLayer(input: { readonly available: boolean }) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(input.available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
|
||||
decryptString: (value) => {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
return Effect.fail(
|
||||
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted token"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopCloudAuthTokenStore.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
const withTokenStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
|
||||
input?: { readonly encryptionAvailable?: boolean },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-cloud-auth-token-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopCloudAuthTokenStore", () => {
|
||||
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
|
||||
|
||||
yield* tokenStore.clear;
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
{ encryptionAvailable: false },
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthTokenDocument {
|
||||
readonly version: number;
|
||||
readonly encryptedClientJwt: string;
|
||||
}
|
||||
|
||||
const CloudAuthTokenDocumentSchema = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
encryptedClientJwt: Schema.String,
|
||||
});
|
||||
|
||||
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
|
||||
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
|
||||
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
|
||||
|
||||
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop cloud auth token.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthTokenStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopCloudAuthTokenStoreDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
token: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopCloudAuthTokenStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStore extends Context.Service<
|
||||
DesktopCloudAuthTokenStore,
|
||||
DesktopCloudAuthTokenStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
tokenPath: string,
|
||||
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
|
||||
fileSystem.readFileString(tokenPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
|
||||
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly tokenPath: string;
|
||||
readonly document: CloudAuthTokenDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.tokenPath);
|
||||
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.tokenPath);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopCloudAuthTokenStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
|
||||
|
||||
return DesktopCloudAuthTokenStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, tokenPath);
|
||||
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
|
||||
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
tokenPath,
|
||||
document: { version: 1, encryptedClientJwt },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,297 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
|
||||
decryptString: (value) => {
|
||||
return Effect.gen(function* () {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (
|
||||
!decoded.startsWith("encrypted:") ||
|
||||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
|
||||
) {
|
||||
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted catalog"),
|
||||
});
|
||||
}
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
baseDir: string,
|
||||
encryptionAvailable = true,
|
||||
failDecrypt: Ref.Ref<boolean> | null = null,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
);
|
||||
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
|
||||
return DesktopConnectionCatalogStore.layer.pipe(
|
||||
Layer.provideMerge(savedEnvironmentsLayer),
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
}
|
||||
|
||||
const withStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
|
||||
encryptionAvailable = true,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalog = '{"schemaVersion":1,"targets":[]}';
|
||||
|
||||
assert.isTrue(yield* store.set(catalog));
|
||||
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
|
||||
|
||||
yield* store.clear;
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist when secure storage is unavailable", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
assert.isFalse(yield* store.set("{}"));
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const records: readonly PersistedSavedEnvironmentRecord[] = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
httpBaseUrl: "https://relay.example.com/",
|
||||
wsBaseUrl: "wss://relay.example.com/",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
relayManaged: { relayUrl: "https://relay-control.example.com/" },
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
httpBaseUrl: "http://127.0.0.1:41773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:41773/",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
createdAt: "2026-06-03T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
];
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
assert.isTrue(
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
secret: "legacy-token",
|
||||
}),
|
||||
);
|
||||
|
||||
const migrated = yield* store.get;
|
||||
assert.isTrue(Option.isSome(migrated));
|
||||
if (Option.isNone(migrated)) {
|
||||
return;
|
||||
}
|
||||
const catalog = yield* decodeConnectionCatalog(migrated.value);
|
||||
|
||||
assert.deepInclude(catalog.targets[0], {
|
||||
_tag: "RelayConnectionTarget",
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[1], {
|
||||
_tag: "SshConnectionTarget",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[2], {
|
||||
_tag: "BearerConnectionTarget",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[0], {
|
||||
_tag: "SshConnectionProfile",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[1], {
|
||||
_tag: "BearerConnectionProfile",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
});
|
||||
assert.equal(catalog.credentials.length, 1);
|
||||
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
|
||||
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
|
||||
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
|
||||
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
|
||||
}
|
||||
|
||||
yield* savedEnvironments.setRegistry([]);
|
||||
assert.deepEqual(yield* store.get, migrated);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces malformed catalog documents without deleting them", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.cause, permissionError);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const failDecrypt = yield* Ref.make(false);
|
||||
const layer = makeLayer(baseDir, true, failDecrypt);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,328 @@
|
||||
import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionTarget,
|
||||
RelayConnectionTarget,
|
||||
SshConnectionProfile,
|
||||
SshConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
|
||||
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const EncryptedConnectionCatalogDocument = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
encryptedCatalog: Schema.String,
|
||||
});
|
||||
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
|
||||
|
||||
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
|
||||
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
|
||||
RuntimeConnectionCatalogDocument,
|
||||
);
|
||||
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode the desktop connection catalog.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop connection catalog: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to migrate legacy desktop saved environments.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopConnectionCatalogStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopConnectionCatalogStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
DesktopConnectionCatalogStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not remove a temporary connection catalog file.", {
|
||||
tempPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
|
||||
return `${prefix}:${environmentId}`;
|
||||
}
|
||||
|
||||
const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (record.relayManaged !== undefined) {
|
||||
targets.push(
|
||||
new RelayConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (record.desktopSsh !== undefined) {
|
||||
const id = connectionId("ssh", record.environmentId);
|
||||
targets.push(
|
||||
new SshConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new SshConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
target: record.desktopSsh,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = connectionId("bearer", record.environmentId);
|
||||
targets.push(
|
||||
new BearerConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
credential: new BearerConnectionCredential({ token: token.value }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
targets,
|
||||
profiles,
|
||||
credentials,
|
||||
remoteDpopTokens: [],
|
||||
};
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopConnectionCatalogStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry;
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
|
||||
yield* writeCatalog(encoded);
|
||||
return Option.some(encoded);
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,82 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: {},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3773,
|
||||
t3Home: "/tmp/t3",
|
||||
host: "127.0.0.1",
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
};
|
||||
|
||||
describe("DesktopLocalEnvironmentAuth", () => {
|
||||
it.effect("exchanges the desktop bootstrap credential only once", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestCount = yield* Ref.make(0);
|
||||
const httpClientLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Ref.update(requestCount, (count) => count + 1).pipe(
|
||||
Effect.as(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
access_token: "desktop-bearer-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
scope: "orchestration:read",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
assert.strictEqual(first, "desktop-bearer-token");
|
||||
assert.strictEqual(second, "desktop-bearer-token");
|
||||
assert.strictEqual(yield* Ref.get(requestCount), 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export interface DesktopLocalEnvironmentAuthShape {
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
|
||||
"DesktopLocalEnvironmentAuthError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
DesktopLocalEnvironmentAuthShape
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopLocalEnvironmentAuth,
|
||||
Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthError({
|
||||
message: "Local backend is not configured.",
|
||||
});
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthError({
|
||||
message: "Failed to create the local desktop bearer session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
}),
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export interface ElectronMenuPosition {
|
||||
readonly x: number;
|
||||
@@ -79,109 +80,114 @@ const normalizePosition = (
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const layer = Layer.sync(ElectronMenu, () => {
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
export const layer = Layer.effect(
|
||||
ElectronMenu,
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
});
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,105 +1,132 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
|
||||
vi.hoisted(() => ({
|
||||
registerFileProtocolMock: vi.fn(),
|
||||
registerSchemesAsPrivilegedMock: vi.fn(),
|
||||
unregisterProtocolMock: vi.fn(),
|
||||
}));
|
||||
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
netFetchMock: vi.fn(),
|
||||
unhandleMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
protocol: {
|
||||
registerFileProtocol: registerFileProtocolMock,
|
||||
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
|
||||
unregisterProtocol: unregisterProtocolMock,
|
||||
},
|
||||
net: { fetch: netFetchMock },
|
||||
protocol: { handle: handleMock, unhandle: unhandleMock },
|
||||
}));
|
||||
|
||||
import * as ElectronProtocol from "./ElectronProtocol.ts";
|
||||
|
||||
describe("ElectronProtocol", () => {
|
||||
beforeEach(() => {
|
||||
registerFileProtocolMock.mockReset();
|
||||
registerSchemesAsPrivilegedMock.mockReset();
|
||||
unregisterProtocolMock.mockReset();
|
||||
handleMock.mockReset();
|
||||
netFetchMock.mockReset();
|
||||
unhandleMock.mockReset();
|
||||
});
|
||||
|
||||
it("normalizes safe desktop protocol pathnames", () => {
|
||||
assert.equal(
|
||||
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
|
||||
"settings/general",
|
||||
);
|
||||
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
|
||||
});
|
||||
it.effect("proxies the stable renderer origin to the current app server", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock.mockResolvedValue(new Response("ok"));
|
||||
|
||||
it.effect("registers desktop scheme privileges through a layer", () =>
|
||||
Effect.scoped(
|
||||
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
|
||||
[
|
||||
[
|
||||
{
|
||||
scheme: "t3",
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"img-src 'self' t3code-dev: blob: data: http: https:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"font-src 'self' t3code-dev: data:",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
handleMock.mock.calls.map((call) => call[0]),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes registered file protocols", () =>
|
||||
it.effect("rejects custom protocol requests for another host", () =>
|
||||
Effect.gen(function* () {
|
||||
let capturedHandler:
|
||||
| ((
|
||||
request: Electron.ProtocolRequest,
|
||||
callback: (response: Electron.ProtocolResponse) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
|
||||
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
|
||||
capturedHandler = handler;
|
||||
return true;
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* electronProtocol.registerFileProtocol({
|
||||
scheme: "t3",
|
||||
handler: () => Effect.succeed({ path: "/app/index.html" }),
|
||||
});
|
||||
|
||||
assert.isDefined(capturedHandler);
|
||||
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
|
||||
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
|
||||
resume(Effect.succeed(response)),
|
||||
);
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(response, { path: "/app/index.html" });
|
||||
assert.deepEqual(
|
||||
registerFileProtocolMock.mock.calls.map((call) => call[0]),
|
||||
["t3"],
|
||||
);
|
||||
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
|
||||
assert.equal(response.status, 404);
|
||||
assert.equal(netFetchMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
const directives = Object.fromEntries(
|
||||
policy.split("; ").map((directive) => {
|
||||
const [name, ...sources] = directive.split(" ");
|
||||
return [name, sources];
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
|
||||
assert.deepEqual(directives["img-src"], [
|
||||
"'self'",
|
||||
"t3code:",
|
||||
"blob:",
|
||||
"data:",
|
||||
"http:",
|
||||
"https:",
|
||||
]);
|
||||
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,27 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
|
||||
export const DESKTOP_HOST = "app";
|
||||
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
|
||||
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
|
||||
|
||||
export const DESKTOP_SCHEME = "t3";
|
||||
export function getDesktopScheme(isDevelopment: boolean): string {
|
||||
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
|
||||
}
|
||||
|
||||
export function getDesktopOrigin(isDevelopment: boolean): string {
|
||||
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
|
||||
}
|
||||
|
||||
export function getDesktopUrl(isDevelopment: boolean): string {
|
||||
return `${getDesktopOrigin(isDevelopment)}/`;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
"ElectronProtocolRegistrationError",
|
||||
@@ -21,252 +30,117 @@ export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: file protocol.`;
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
|
||||
"ElectronProtocolStaticBundleMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
|
||||
}
|
||||
export interface DesktopProtocolRegistrationInput {
|
||||
readonly scheme: string;
|
||||
readonly targetOrigin: URL;
|
||||
readonly backendOrigin: URL;
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
export interface ElectronProtocolShape {
|
||||
readonly registerFileProtocol: <E, R>(input: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
|
||||
readonly registerDesktopFileProtocol: Effect.Effect<
|
||||
void,
|
||||
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
|
||||
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
|
||||
>;
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
|
||||
const segments: string[] = [];
|
||||
for (const segment of rawPath.split("/")) {
|
||||
if (segment.length === 0 || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
return Option.none();
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return Option.some(segments.join("/"));
|
||||
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
|
||||
const clerkOrigin = input.clerkFrontendApiHostname
|
||||
? `https://${input.clerkFrontendApiHostname}`
|
||||
: undefined;
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
// The renderer connects directly to user-configured environments in addition to
|
||||
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
|
||||
// origins are not known when this response policy is created, so restrict
|
||||
// connections by the network schemes the client supports instead of by host.
|
||||
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
|
||||
|
||||
return [
|
||||
"default-src 'self'",
|
||||
`script-src ${scriptSources.join(" ")}`,
|
||||
`connect-src ${connectSources.join(" ")}`,
|
||||
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`font-src 'self' ${input.scheme}: data:`,
|
||||
"worker-src 'self' blob:",
|
||||
"frame-src 'self' https://challenges.cloudflare.com",
|
||||
"form-action 'self'",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(() => {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
|
||||
function withContentSecurityPolicy(response: Response, policy: string): Response {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Content-Security-Policy", policy);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
const resolveDesktopStaticDir: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidates = [
|
||||
environment.path.join(environment.appRoot, "apps/server/dist/client"),
|
||||
environment.path.join(environment.appRoot, "apps/web/dist"),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const hasIndex = yield* fileSystem
|
||||
.exists(environment.path.join(candidate, "index.html"))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (hasIndex) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
contentSecurityPolicy: string,
|
||||
): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (requestUrl.host !== DESKTOP_HOST) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
|
||||
function* (
|
||||
staticRoot: string,
|
||||
requestUrl: string,
|
||||
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
|
||||
if (Option.isNone(normalizedPath)) {
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
|
||||
const resolvedPath = environment.path.join(staticRoot, requestedPath);
|
||||
|
||||
if (environment.path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = environment.path.join(resolvedPath, "index.html");
|
||||
const nestedIndexExists = yield* fileSystem
|
||||
.exists(nestedIndex)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (nestedIndexExists) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
},
|
||||
);
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return environment.path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
|
||||
function* <E, R>({
|
||||
scheme,
|
||||
handler,
|
||||
onFailure,
|
||||
}: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
|
||||
yield* Effect.annotateCurrentSpan({ scheme });
|
||||
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
|
||||
Effect.map((protocols) => protocols.has(scheme)),
|
||||
);
|
||||
if (alreadyRegistered) {
|
||||
return;
|
||||
}
|
||||
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
function* (input: DesktopProtocolRegistrationInput) {
|
||||
if (yield* Ref.get(registered)) return;
|
||||
|
||||
const context = yield* Effect.context<R>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const registered = Electron.protocol.registerFileProtocol(
|
||||
scheme,
|
||||
(request, callback) => {
|
||||
const response = handler(request).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
|
||||
),
|
||||
);
|
||||
|
||||
void runPromise(response).then(callback, () => callback({ error: -2 }));
|
||||
},
|
||||
Electron.protocol.handle(input.scheme, (request) =>
|
||||
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
|
||||
);
|
||||
if (!registered) {
|
||||
throw new ElectronProtocolRegistrationError({
|
||||
scheme,
|
||||
cause: "registerFileProtocol returned false",
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof ElectronProtocolRegistrationError
|
||||
? cause
|
||||
: new ElectronProtocolRegistrationError({ scheme, cause }),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unregisterProtocol(scheme);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => {
|
||||
const next = new Set(protocols);
|
||||
next.delete(scheme);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
),
|
||||
Electron.protocol.unhandle(input.scheme);
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const registerDesktopFileProtocol = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment;
|
||||
if (environment.isDevelopment) return;
|
||||
|
||||
const staticRoot = yield* resolveDesktopStaticDir;
|
||||
if (Option.isNone(staticRoot)) {
|
||||
return yield* new ElectronProtocolStaticBundleMissingError();
|
||||
}
|
||||
|
||||
const staticRootResolved = environment.path.resolve(staticRoot.value);
|
||||
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
|
||||
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
|
||||
|
||||
yield* registerFileProtocol({
|
||||
scheme: DESKTOP_SCHEME,
|
||||
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = environment.path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url, environment);
|
||||
const exists = yield* fileSystem
|
||||
.exists(resolvedCandidate)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
if (!isInRoot || !exists) {
|
||||
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
|
||||
}
|
||||
|
||||
return { path: resolvedCandidate } as const;
|
||||
}),
|
||||
onFailure: () => ({ path: fallbackIndex }),
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
|
||||
|
||||
return ElectronProtocol.of({
|
||||
registerFileProtocol,
|
||||
registerDesktopFileProtocol,
|
||||
});
|
||||
return ElectronProtocol.of({ registerDesktopProtocol });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronProtocol, make);
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -37,6 +38,7 @@ export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWind
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
@@ -98,7 +100,7 @@ const make = Effect.gen(function* () {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
import {
|
||||
clearCloudAuthToken,
|
||||
createCloudAuthRequest,
|
||||
fetchCloudAuth,
|
||||
getCloudAuthToken,
|
||||
setCloudAuthToken,
|
||||
} from "./methods/cloudAuth.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import {
|
||||
getSavedEnvironmentRegistry,
|
||||
getSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
setSavedEnvironmentRegistry,
|
||||
setSavedEnvironmentSecret,
|
||||
} from "./methods/savedEnvironments.ts";
|
||||
clearConnectionCatalog,
|
||||
getConnectionCatalog,
|
||||
setConnectionCatalog,
|
||||
} from "./methods/connectionCatalog.ts";
|
||||
import {
|
||||
getAdvertisedEndpoints,
|
||||
getServerExposureState,
|
||||
@@ -42,6 +33,7 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
@@ -56,14 +48,13 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
yield* ipc.handle(setClientSettings);
|
||||
yield* ipc.handle(getSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(setSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(getSavedEnvironmentSecret);
|
||||
yield* ipc.handle(setSavedEnvironmentSecret);
|
||||
yield* ipc.handle(removeSavedEnvironmentSecret);
|
||||
yield* ipc.handle(getConnectionCatalog);
|
||||
yield* ipc.handle(setConnectionCatalog);
|
||||
yield* ipc.handle(clearConnectionCatalog);
|
||||
|
||||
yield* ipc.handle(discoverSshHosts);
|
||||
yield* ipc.handle(ensureSshEnvironment);
|
||||
@@ -84,11 +75,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
yield* ipc.handle(createCloudAuthRequest);
|
||||
yield* ipc.handle(getCloudAuthToken);
|
||||
yield* ipc.handle(setCloudAuthToken);
|
||||
yield* ipc.handle(clearCloudAuthToken);
|
||||
yield* ipc.handle(fetchCloudAuth);
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
|
||||
@@ -3,12 +3,6 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
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 CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
|
||||
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
|
||||
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
|
||||
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
|
||||
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
|
||||
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
@@ -18,13 +12,13 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
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 ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
|
||||
|
||||
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
|
||||
const calls: Array<FetchCall> = [];
|
||||
let responseIndex = 0;
|
||||
const fetchFn = ((input, init) => {
|
||||
calls.push([input, init ?? {}]);
|
||||
const response = responses[responseIndex++];
|
||||
if (!response) {
|
||||
return Promise.reject(new Error("Unexpected fetch call"));
|
||||
}
|
||||
return Promise.resolve(response);
|
||||
}) satisfies typeof fetch;
|
||||
|
||||
return { fetchFn, calls };
|
||||
};
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-mobile": "1",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
const [url, init] = forwardedRequest;
|
||||
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
|
||||
assert.equal(init.method, "POST");
|
||||
assert.equal(
|
||||
new Headers(init.headers).get("content-type"),
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://clerk.t3.codes/v1/client",
|
||||
method: "GET",
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
assert.throws(
|
||||
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
|
||||
/restricted to Clerk Frontend API HTTPS hosts/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,177 +0,0 @@
|
||||
import {
|
||||
DesktopCloudAuthFetchInputSchema,
|
||||
DesktopCloudAuthFetchResultSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
clerkFrontendApiHostnameFromPublishableKey,
|
||||
isAllowedClerkFrontendApiHostname,
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
|
||||
readonly reason: string;
|
||||
readonly cause?: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
function configuredClerkFrontendApiHostname(): string | null {
|
||||
const publishableKey =
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
|
||||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? ""
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
|
||||
if (!publishableKey) return null;
|
||||
|
||||
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
|
||||
}
|
||||
|
||||
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
|
||||
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
|
||||
|
||||
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
|
||||
throw new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
|
||||
});
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
|
||||
return Effect.gen(function* () {
|
||||
const method = (input.method ?? "GET") as "GET" | "POST";
|
||||
const headers = new Headers(input.headers);
|
||||
const response = yield* HttpClientRequest.make(method)(url).pipe(
|
||||
HttpClientRequest.setHeaders(headers),
|
||||
input.body === undefined
|
||||
? identity
|
||||
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
|
||||
HttpClient.execute,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed to execute.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const electronNetFetchLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const electronFetch = yield* Effect.promise(async () => {
|
||||
const electron = (await import("electron")) as {
|
||||
readonly net?: { readonly fetch?: typeof globalThis.fetch };
|
||||
};
|
||||
return typeof electron.net?.fetch === "function"
|
||||
? electron.net.fetch.bind(electron.net)
|
||||
: null;
|
||||
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
|
||||
|
||||
if (!electronFetch) {
|
||||
yield* Effect.logWarning(
|
||||
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
|
||||
);
|
||||
}
|
||||
|
||||
return FetchHttpClient.layer.pipe(
|
||||
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const createCloudAuthRequest = makeIpcMethod({
|
||||
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
return yield* cloudAuth.createRequest;
|
||||
}),
|
||||
});
|
||||
|
||||
export const getCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return Option.getOrNull(yield* tokenStore.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return yield* tokenStore.set(token);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
yield* tokenStore.clear;
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchCloudAuth = makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
|
||||
payload: DesktopCloudAuthFetchInputSchema,
|
||||
result: DesktopCloudAuthFetchResultSchema,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
|
||||
const url = yield* Effect.try({
|
||||
try: () => validateClerkFrontendApiUrl(input.url),
|
||||
catch: (cause) =>
|
||||
cause instanceof DesktopCloudAuthFetchError
|
||||
? cause
|
||||
: new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch received an invalid URL.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return Option.getOrNull(yield* store.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return yield* store.set(catalog);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* store.clear;
|
||||
}),
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
|
||||
const NonBlankString = Schema.String.check(
|
||||
Schema.makeFilter((value) =>
|
||||
value.trim().length > 0 ? undefined : "Expected a non-empty string",
|
||||
),
|
||||
);
|
||||
|
||||
const SetSavedEnvironmentSecretInput = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
secret: NonBlankString,
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: SavedEnvironmentRegistryPayload,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.getRegistry;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: SavedEnvironmentRegistryPayload,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
}),
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: SetSavedEnvironmentSecretInput,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
|
||||
environmentId,
|
||||
secret,
|
||||
}) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.setSecret({
|
||||
environmentId,
|
||||
secret,
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export const removeSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.removeSecret(environmentId);
|
||||
}),
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime";
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
EnvironmentAuthInvalidError,
|
||||
DesktopDiscoveredSshHostSchema,
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
@@ -64,6 +65,16 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBearerToken = makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
|
||||
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* localAuth.getBearerToken;
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickFolder = makeIpcMethod({
|
||||
channel: IpcChannels.PICK_FOLDER_CHANNEL,
|
||||
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
@@ -26,12 +27,13 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "./electron/ElectronWindow.ts";
|
||||
import * as DesktopApp from "./app/DesktopApp.ts";
|
||||
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
@@ -53,11 +55,13 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
|
||||
Effect.flatMap((app) => app.metadata),
|
||||
);
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const processArch = yield* HostProcessArchitecture;
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: __dirname,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
platform,
|
||||
processArch,
|
||||
...metadata,
|
||||
});
|
||||
}),
|
||||
@@ -114,8 +118,7 @@ const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layerShutdown,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopSavedEnvironments.layer,
|
||||
DesktopCloudAuthTokenStore.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
DesktopAssets.layer,
|
||||
DesktopObservability.layer,
|
||||
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
|
||||
@@ -145,17 +148,30 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopCloudAuth.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
|
||||
Layer.flatMap(() =>
|
||||
const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(desktopEnvironmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
|
||||
@@ -4,10 +4,13 @@ import type {
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
@@ -39,19 +42,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getLocalEnvironmentBearerToken: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
|
||||
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
|
||||
setClientSettings: (settings) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
|
||||
getSavedEnvironmentRegistry: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
|
||||
setSavedEnvironmentRegistry: (records) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
|
||||
getSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
setSavedEnvironmentSecret: (environmentId, secret) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
|
||||
setConnectionCatalog: (catalog) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
|
||||
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
@@ -101,23 +100,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
...(position === undefined ? {} : { position }),
|
||||
}),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
|
||||
createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL),
|
||||
getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL),
|
||||
setCloudAuthToken: (token: string) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
|
||||
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
|
||||
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
|
||||
onCloudAuthCallback: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
|
||||
if (typeof rawUrl !== "string") return;
|
||||
listener(rawUrl);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
|
||||
@@ -128,6 +128,58 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const loadURL = vi.fn(async () => undefined);
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "about:blank",
|
||||
getTitle: () => "",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.navigate("tab_pending", "localhost:3200");
|
||||
|
||||
expect(yield* manager.automationStatus("tab_pending")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_pending",
|
||||
url: "http://localhost:3200/",
|
||||
title: "",
|
||||
loading: true,
|
||||
});
|
||||
|
||||
yield* manager.registerWebview("tab_pending", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(loadURL).toHaveBeenCalledOnce();
|
||||
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -189,6 +241,55 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps element picking active during subframe navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isFocused: () => true,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
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;
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
|
||||
yield* Effect.yieldNow;
|
||||
expect(pick.pollUnsafe()).toBeUndefined();
|
||||
|
||||
listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
|
||||
expect(yield* Fiber.join(pick)).toBeNull();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1195,26 +1195,103 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
yield* update(tabId, {
|
||||
webContentsId,
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor: tab.zoomFactor,
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) {
|
||||
return [
|
||||
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
|
||||
tabs,
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const next: PreviewTabState = {
|
||||
...current,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
Option.some({
|
||||
state: next,
|
||||
pendingUrl,
|
||||
}),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isNone(registration)) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt("registerWebview.restoreZoom", () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt("registerWebview.sendTheme", () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
|
||||
if (
|
||||
pendingUrl &&
|
||||
latestNavStatus?.kind === "Loading" &&
|
||||
latestNavStatus.url === pendingUrl &&
|
||||
wc.getURL() !== pendingUrl
|
||||
) {
|
||||
runFork(
|
||||
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
|
||||
Effect.ignore,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
|
||||
const updatedAt = yield* currentIso;
|
||||
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
const next: PreviewTabState = {
|
||||
tabId,
|
||||
webContentsId: current?.webContentsId ?? null,
|
||||
navStatus: {
|
||||
kind: "Loading",
|
||||
url,
|
||||
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
|
||||
},
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
next,
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
yield* attempt("navigate.reload", () => wc.reload());
|
||||
return;
|
||||
@@ -1344,7 +1421,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
};
|
||||
const onDestroyed = () => settle(null);
|
||||
const onNavigated = () => settle(null);
|
||||
const onNavigated = (
|
||||
_event: Electron.Event,
|
||||
_url: string,
|
||||
_isInPlace: boolean,
|
||||
isMainFrame: boolean,
|
||||
) => {
|
||||
if (isMainFrame) settle(null);
|
||||
};
|
||||
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
|
||||
yield* attempt("pickElement.register", () => {
|
||||
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
|
||||
|
||||
@@ -15,6 +15,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
defaultRuntimeMode: "full-access",
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
|
||||
@@ -272,6 +272,26 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
});
|
||||
|
||||
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
|
||||
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats empty saved environment documents as empty", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
@@ -289,7 +309,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats malformed saved environment documents as empty", () =>
|
||||
it.effect("surfaces malformed saved environment documents", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -298,10 +318,15 @@ describe("DesktopSavedEnvironments", () => {
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
registryError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
|
||||
);
|
||||
const secretError = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -82,6 +82,16 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop saved environments: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentSecretDecodeError",
|
||||
)<{
|
||||
@@ -93,6 +103,7 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
@@ -103,10 +114,16 @@ export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
|
||||
|
||||
export interface DesktopSavedEnvironmentsShape {
|
||||
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadError
|
||||
>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
@@ -176,18 +193,20 @@ function normalizeSavedEnvironmentRegistryDocument(
|
||||
function readRegistryDocument(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
registryPath: string,
|
||||
): Effect.Effect<SavedEnvironmentRegistryDocument> {
|
||||
): Effect.Effect<
|
||||
SavedEnvironmentRegistryDocument,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> {
|
||||
return fileSystem.readFileString(registryPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed({ version: 1, records: [] }),
|
||||
onSome: (raw) =>
|
||||
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed({ version: 1, records: [] })
|
||||
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.map(normalizeSavedEnvironmentRegistryDocument),
|
||||
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -267,21 +286,39 @@ export const layer = Layer.effect(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
@@ -299,7 +336,7 @@ export const layer = Layer.effect(
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
@@ -331,7 +368,7 @@ export const layer = Layer.effect(
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
@@ -368,6 +405,18 @@ export const layerTest = (input?: {
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: Ref.get(recordsRef),
|
||||
setRegistry: (records) => Ref.set(recordsRef, records),
|
||||
removeEnvironment: (environmentId) =>
|
||||
Ref.update(recordsRef, (records) =>
|
||||
records.filter((record) => record.environmentId !== environmentId),
|
||||
).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(secretsRef, (secrets) => {
|
||||
const nextSecrets = new Map(secrets);
|
||||
nextSecrets.delete(environmentId);
|
||||
return nextSecrets;
|
||||
}),
|
||||
),
|
||||
),
|
||||
getSecret: (environmentId) =>
|
||||
Ref.get(secretsRef).pipe(
|
||||
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
|
||||
|
||||
@@ -68,6 +68,7 @@ function makeFakeBrowserWindow() {
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
setTitle: vi.fn(),
|
||||
setTitleBarOverlay: vi.fn(),
|
||||
show: vi.fn(),
|
||||
@@ -78,6 +79,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
}
|
||||
@@ -134,10 +136,17 @@ function makeTestLayer(input: {
|
||||
readonly window: Electron.BrowserWindow;
|
||||
readonly createCount: Ref.Ref<number>;
|
||||
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
|
||||
readonly openedExternalUrls?: unknown[];
|
||||
}) {
|
||||
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
|
||||
create: (options) =>
|
||||
Effect.sync(() => {
|
||||
input.createdWindowOptions?.push(options);
|
||||
}).pipe(
|
||||
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
|
||||
Effect.as(input.window),
|
||||
),
|
||||
main: Ref.get(input.mainWindow),
|
||||
currentMainOrFirst: Ref.get(input.mainWindow),
|
||||
focusedMainOrFirst: Ref.get(input.mainWindow),
|
||||
@@ -182,19 +191,19 @@ describe("DesktopWindow", () => {
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
navigationUrl: "http://127.0.0.1:3773/settings/connections",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "t3code://app/settings/connections",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "https://accounts.microsoft.com/oauth",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
applicationUrl: "t3code://app/",
|
||||
navigationUrl: "not a url",
|
||||
}),
|
||||
);
|
||||
@@ -205,10 +214,12 @@ describe("DesktopWindow", () => {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
createdWindowOptions,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -218,7 +229,9 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
|
||||
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -16,8 +15,8 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -32,7 +31,6 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopState.DesktopState
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
@@ -40,16 +38,7 @@ type DesktopWindowRuntimeServices =
|
||||
| ElectronWindow.ElectronWindow
|
||||
| PreviewManager.PreviewManager;
|
||||
|
||||
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
"DesktopWindowDevServerUrlMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "VITE_DEV_SERVER_URL is required in desktop development.";
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopWindowError =
|
||||
| DesktopWindowDevServerUrlMissingError
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
@@ -71,20 +60,12 @@ export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowS
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-window");
|
||||
|
||||
function resolveDesktopDevServerUrl(
|
||||
environment: DesktopEnvironment.DesktopEnvironmentShape,
|
||||
): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
|
||||
return Option.match(environment.devServerUrl, {
|
||||
onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
|
||||
onSome: (url) => Effect.succeed(url.href),
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
platform: NodeJS.Platform,
|
||||
): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = platform === "win32" ? "ico" : "png";
|
||||
return Option.match(iconPaths[ext], {
|
||||
onNone: () => ({}),
|
||||
onSome: (icon) => ({ icon }),
|
||||
@@ -106,8 +87,11 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): WindowTitleBarOptions {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
@@ -127,6 +111,7 @@ function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarO
|
||||
function syncWindowAppearance(
|
||||
window: Electron.BrowserWindow,
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
@@ -134,7 +119,7 @@ function syncWindowAppearance(
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
@@ -166,20 +151,18 @@ const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
|
||||
backendHttpUrl: URL,
|
||||
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
Electron.BrowserWindow,
|
||||
DesktopWindowError
|
||||
> {
|
||||
yield* previewManager.getBrowserSession();
|
||||
const applicationUrl = environment.isDevelopment
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
const applicationUrl = getDesktopUrl(environment.isDevelopment);
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths);
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const window = yield* electronWindow.create({
|
||||
width: 1100,
|
||||
@@ -188,10 +171,11 @@ const make = Effect.gen(function* () {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
...iconOption,
|
||||
title: environment.displayName,
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors),
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
|
||||
webPreferences: {
|
||||
preload: environment.preloadPath,
|
||||
contextIsolation: true,
|
||||
@@ -201,6 +185,10 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
window.setAutoHideCursor(false);
|
||||
}
|
||||
|
||||
yield* previewManager.setMainWindow(window);
|
||||
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
if (
|
||||
@@ -318,7 +306,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (process.platform === "linux") {
|
||||
if (environment.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
@@ -340,8 +328,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const createMain = Effect.gen(function* () {
|
||||
const backendConfig = yield* serverExposure.backendConfig;
|
||||
const window = yield* createWindow(backendConfig.httpBaseUrl);
|
||||
const window = yield* createWindow();
|
||||
yield* electronWindow.setMain(window);
|
||||
yield* logWindowInfo("main window created");
|
||||
return window;
|
||||
@@ -408,7 +395,7 @@ const make = Effect.gen(function* () {
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
yield* electronWindow.syncAllAppearance((window) =>
|
||||
syncWindowAppearance(window, shouldUseDarkColors),
|
||||
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
|
||||
});
|
||||
|
||||
@@ -56,6 +56,12 @@ export default defineConfig({
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
define: publicConfigDefine,
|
||||
entry: ["src/preload.ts"],
|
||||
deps: {
|
||||
// Sandboxed Electron preloads cannot reliably resolve package imports
|
||||
// from inside the packaged ASAR. Bundle Clerk's preload bridge into the
|
||||
// preload artifact instead of leaving a runtime require() behind.
|
||||
alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),
|
||||
},
|
||||
},
|
||||
{
|
||||
format: "cjs",
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
---
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
@@ -36,17 +38,17 @@ const {
|
||||
</a>
|
||||
<div class="nav-right">
|
||||
<a
|
||||
class="nav-gh"
|
||||
href="https://github.com/pingdotgg/t3code"
|
||||
class="nav-stars"
|
||||
href={GITHUB_REPOSITORY_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
|
||||
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
|
||||
</svg>
|
||||
<span>GitHub</span>
|
||||
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
|
||||
</a>
|
||||
<a class="btn btn-primary" href="/#download">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -62,7 +64,7 @@ const {
|
||||
<span>© {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
|
||||
</div>
|
||||
<div class="footer-links">
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
</div>
|
||||
@@ -329,23 +331,36 @@ const {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.nav-gh {
|
||||
.nav-stars {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
gap: 7px;
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
|
||||
font-size: 13px;
|
||||
letter-spacing: -0.01em;
|
||||
white-space: nowrap;
|
||||
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
|
||||
}
|
||||
|
||||
.nav-gh:hover {
|
||||
.nav-stars:hover {
|
||||
color: var(--fg);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border-color: var(--border-strong);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.nav-stars strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.nav-stars svg {
|
||||
color: var(--warn);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.main {
|
||||
@@ -407,4 +422,17 @@ const {
|
||||
padding-right: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.nav-inner {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.nav-stars {
|
||||
height: 34px;
|
||||
gap: 6px;
|
||||
padding: 0 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,6 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "12k+",
|
||||
users: "100,000",
|
||||
} as const;
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import { tweets } from "../lib/tweets";
|
||||
|
||||
const desktopEndorsementRows = [
|
||||
@@ -55,11 +56,12 @@ const mobileEndorsementRows = [
|
||||
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
|
||||
<span id="download-label">Download for macOS</span>
|
||||
</a>
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<a class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
|
||||
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
|
||||
</svg>
|
||||
Star on GitHub
|
||||
<span>Steal our code (legally)</span>
|
||||
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -82,8 +84,8 @@ const mobileEndorsementRows = [
|
||||
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
|
||||
<div class="container">
|
||||
<div class="endorsements-head">
|
||||
<h2 id="endorsements-title">Developers love T3 Code</h2>
|
||||
<p>Real reactions from people building with T3 Code today.</p>
|
||||
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
|
||||
<p>Some of them even tweeted about it.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -282,10 +284,6 @@ const mobileEndorsementRows = [
|
||||
<div class="section-head open-head">
|
||||
<div class="eyebrow">Open source</div>
|
||||
<h2>If you don't like something, fork it.</h2>
|
||||
<p>
|
||||
T3 Code is as open as they come. We built this app to be modifiable,
|
||||
customizable, and forkable. Go nuts - that's the whole point.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="open-grid">
|
||||
@@ -305,43 +303,44 @@ const mobileEndorsementRows = [
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="open-stats">
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">MIT</div>
|
||||
<div class="open-stat-lbl">License · commercial-friendly</div>
|
||||
<div class="tile open-pitch">
|
||||
<div class="open-pitch-copy">
|
||||
<ul class="open-pitch-list">
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
|
||||
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">TypeScript</div>
|
||||
<div class="open-stat-lbl">End-to-end, strictly typed</div>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">1 monorepo</div>
|
||||
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
|
||||
</div>
|
||||
<div class="tile open-stat">
|
||||
<div class="open-stat-val">No telemetry</div>
|
||||
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
|
||||
|
||||
<div class="open-pitch-footer">
|
||||
<div class="open-pitch-meta">
|
||||
<span>MIT licensed</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{MARKETING_STATS.githubStars} stars</span>
|
||||
</div>
|
||||
|
||||
<div class="open-pitch-actions">
|
||||
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
|
||||
Fork on GitHub
|
||||
</a>
|
||||
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
|
||||
Browse source
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="open-ctas">
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
|
||||
Star on GitHub
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
|
||||
Fork the repo
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
|
||||
Read CONTRIBUTING.md
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -515,7 +514,7 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-title {
|
||||
font-size: clamp(38px, 5.6vw, 76px);
|
||||
margin: 28px auto 22px;
|
||||
margin: 48px auto 22px;
|
||||
max-width: 20ch;
|
||||
text-wrap: balance;
|
||||
}
|
||||
@@ -531,12 +530,42 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 56px;
|
||||
}
|
||||
|
||||
.hero-source-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--fg-muted);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
transition: color 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-source-link:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.hero-source-mark {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.hero-source-arrow {
|
||||
flex-shrink: 0;
|
||||
opacity: 0.6;
|
||||
transition: transform 0.18s ease, opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-source-link:hover .hero-source-arrow {
|
||||
transform: translate(2px, -2px);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Download button icons (platform-aware) */
|
||||
.dl-icon {
|
||||
display: none;
|
||||
@@ -656,6 +685,30 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-opencode,
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 580px;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-cursor {
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode img,
|
||||
.hero-float-mark.hf-cursor img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero-preview {
|
||||
max-width: 1180px;
|
||||
margin: 0 auto;
|
||||
@@ -759,6 +812,11 @@ const mobileEndorsementRows = [
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.endorsements-count {
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.endorsements-head p {
|
||||
color: var(--fg-muted);
|
||||
font-size: 18px;
|
||||
@@ -962,12 +1020,11 @@ const mobileEndorsementRows = [
|
||||
text-align: center;
|
||||
margin: 0 auto 56px;
|
||||
}
|
||||
.open-head p { margin: 0 auto; }
|
||||
|
||||
.open-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.25fr 1fr;
|
||||
gap: 20px; margin-bottom: 32px;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.open-term { padding: 0; overflow: hidden; }
|
||||
@@ -1009,27 +1066,85 @@ const mobileEndorsementRows = [
|
||||
animation: blink 1s steps(2) infinite;
|
||||
}
|
||||
|
||||
.open-stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.open-stat {
|
||||
padding: 22px;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
}
|
||||
.open-stat-val {
|
||||
font-size: 22px; font-weight: 500;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
.open-stat-lbl {
|
||||
font-family: var(--font-mono); font-size: 10.5px;
|
||||
color: var(--fg-dim); letter-spacing: 0.04em;
|
||||
.open-pitch {
|
||||
padding: 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 32px;
|
||||
background:
|
||||
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
|
||||
}
|
||||
|
||||
.open-ctas {
|
||||
display: flex; gap: 10px;
|
||||
justify-content: center; flex-wrap: wrap;
|
||||
.open-pitch-list {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.open-pitch-list li {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.open-pitch-list strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.open-pitch-mark {
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin-top: 1px;
|
||||
border-radius: 7px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-dim);
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
|
||||
}
|
||||
|
||||
.open-pitch-footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.open-pitch-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.open-pitch-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.open-source-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--fg-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: color 0.18s ease;
|
||||
}
|
||||
|
||||
.open-source-link:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Final CTA ────────────────────────────────────────── */
|
||||
|
||||
@@ -131,6 +131,11 @@ const config: ExpoConfig = {
|
||||
{
|
||||
ios: {
|
||||
deploymentTarget: "18.0",
|
||||
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
|
||||
extraPods: [
|
||||
{ name: "GoogleUtilities", modular_headers: true },
|
||||
{ name: "RecaptchaInterop", modular_headers: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"neutral": "#F5F5F5",
|
||||
"border": "#E5E5EA",
|
||||
"ring": "#A3A3A3",
|
||||
"muted": "#F5F5F5",
|
||||
"muted": "#F2F2F7",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"darkColors": {
|
||||
@@ -30,7 +30,7 @@
|
||||
"neutral": "#1C1C1C",
|
||||
"border": "#2A2A2A",
|
||||
"ring": "#525252",
|
||||
"muted": "#1C1C1C",
|
||||
"muted": "#0E0E0E",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"design": {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"cli": {
|
||||
"version": ">= 18.4.0",
|
||||
"appVersionSource": "remote"
|
||||
"appVersionSource": "remote",
|
||||
"promptToConfigurePushNotifications": false
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
--color-foreground: #262626;
|
||||
--color-foreground-secondary: #525252;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #a3a3a3;
|
||||
--color-foreground-tertiary: #8e8e93;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(0, 0, 0, 0.08);
|
||||
@@ -28,6 +28,9 @@
|
||||
/* Subtle backgrounds (badges, pills, overlays) */
|
||||
--color-subtle: rgba(0, 0, 0, 0.04);
|
||||
--color-subtle-strong: rgba(0, 0, 0, 0.08);
|
||||
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
|
||||
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
|
||||
--color-inline-skill-foreground: #a21caf;
|
||||
|
||||
/* Primary action */
|
||||
--color-primary: #262626;
|
||||
@@ -58,6 +61,8 @@
|
||||
/* Header / glass chrome */
|
||||
--color-header: rgba(255, 255, 255, 0.97);
|
||||
--color-header-border: rgba(0, 0, 0, 0.06);
|
||||
--color-glass-surface: rgba(255, 255, 255, 0.72);
|
||||
--color-glass-tint: rgba(255, 255, 255, 0.18);
|
||||
|
||||
/* StatusBar */
|
||||
--color-status-bar: #f2f2f7;
|
||||
@@ -105,8 +110,8 @@
|
||||
/* Text */
|
||||
--color-foreground: #f5f5f5;
|
||||
--color-foreground-secondary: #a3a3a3;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #525252;
|
||||
--color-foreground-muted: #8e8e93;
|
||||
--color-foreground-tertiary: #636366;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(255, 255, 255, 0.06);
|
||||
@@ -116,6 +121,9 @@
|
||||
/* Subtle backgrounds (badges, pills, overlays) */
|
||||
--color-subtle: rgba(255, 255, 255, 0.04);
|
||||
--color-subtle-strong: rgba(255, 255, 255, 0.08);
|
||||
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
|
||||
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
|
||||
--color-inline-skill-foreground: #f0abfc;
|
||||
|
||||
/* Primary action */
|
||||
--color-primary: #f5f5f5;
|
||||
@@ -136,16 +144,18 @@
|
||||
/* Inputs */
|
||||
--color-input: #141414;
|
||||
--color-input-border: rgba(255, 255, 255, 0.08);
|
||||
--color-placeholder: #737373;
|
||||
--color-placeholder: #8e8e93;
|
||||
|
||||
/* Icons */
|
||||
--color-icon: #f5f5f5;
|
||||
--color-icon-muted: #a3a3a3;
|
||||
--color-icon-subtle: #737373;
|
||||
--color-icon-subtle: #8e8e93;
|
||||
|
||||
/* Header / glass chrome */
|
||||
--color-header: rgba(10, 10, 10, 0.97);
|
||||
--color-header-border: rgba(255, 255, 255, 0.06);
|
||||
--color-glass-surface: rgba(23, 23, 23, 0.78);
|
||||
--color-glass-tint: rgba(23, 23, 23, 0.24);
|
||||
|
||||
/* StatusBar */
|
||||
--color-status-bar: #0a0a0a;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ComposerEditorModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3ComposerEditor'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'Native attributed composer editor for T3 Code mobile.'
|
||||
s.description = 'UIKit-backed rich text composer with atomic skill and file tokens.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '16.4',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
# Swift/Objective-C compatibility
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
|
||||
end
|
||||
@@ -0,0 +1,71 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public class T3ComposerEditorModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3ComposerEditor")
|
||||
|
||||
View(T3ComposerEditorView.self) {
|
||||
Prop("value") { (view: T3ComposerEditorView, value: String) in
|
||||
view.setValue(value)
|
||||
}
|
||||
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
|
||||
view.setSelectionJson(selectionJson)
|
||||
}
|
||||
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
|
||||
view.setThemeJson(themeJson)
|
||||
}
|
||||
Prop("placeholder") { (view: T3ComposerEditorView, placeholder: String) in
|
||||
view.setPlaceholder(placeholder)
|
||||
}
|
||||
Prop("fontFamily") { (view: T3ComposerEditorView, fontFamily: String) in
|
||||
view.setFontFamily(fontFamily)
|
||||
}
|
||||
Prop("fontSize") { (view: T3ComposerEditorView, fontSize: Double) in
|
||||
view.setFontSize(CGFloat(fontSize))
|
||||
}
|
||||
Prop("lineHeight") { (view: T3ComposerEditorView, lineHeight: Double) in
|
||||
view.setLineHeight(CGFloat(lineHeight))
|
||||
}
|
||||
Prop("contentInsetVertical") { (view: T3ComposerEditorView, contentInsetVertical: Double) in
|
||||
view.setContentInsetVertical(CGFloat(contentInsetVertical))
|
||||
}
|
||||
Prop("editable") { (view: T3ComposerEditorView, editable: Bool) in
|
||||
view.setEditable(editable)
|
||||
}
|
||||
Prop("scrollEnabled") { (view: T3ComposerEditorView, scrollEnabled: Bool) in
|
||||
view.setScrollEnabled(scrollEnabled)
|
||||
}
|
||||
Prop("autoFocus") { (view: T3ComposerEditorView, autoFocus: Bool) in
|
||||
view.setAutoFocus(autoFocus)
|
||||
}
|
||||
Prop("autoCorrect") { (view: T3ComposerEditorView, autoCorrect: Bool) in
|
||||
view.setAutoCorrect(autoCorrect)
|
||||
}
|
||||
Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in
|
||||
view.setSpellCheck(spellCheck)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onComposerChange",
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange"
|
||||
)
|
||||
|
||||
AsyncFunction("focus") { (view: T3ComposerEditorView) in
|
||||
view.focusEditor()
|
||||
}
|
||||
AsyncFunction("blur") { (view: T3ComposerEditorView) in
|
||||
view.blurEditor()
|
||||
}
|
||||
AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
|
||||
view.setSelection(start: start, end: end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,819 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
private struct ComposerTokenPayload: Decodable {
|
||||
let type: String
|
||||
let source: String
|
||||
let label: String
|
||||
let iconUri: String?
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerSelectionPayload: Decodable {
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerThemePayload: Decodable {
|
||||
let text: String
|
||||
let placeholder: String
|
||||
let chipBackground: String
|
||||
let chipBorder: String
|
||||
let chipText: String
|
||||
let skillBackground: String
|
||||
let skillBorder: String
|
||||
let skillText: String
|
||||
let fileTint: String
|
||||
}
|
||||
|
||||
private struct ComposerChipStyle {
|
||||
let tint: UIColor
|
||||
let backgroundColor: UIColor
|
||||
let borderColor: UIColor
|
||||
let textColor: UIColor
|
||||
}
|
||||
|
||||
private final class ComposerTextAttachment: NSTextAttachment {
|
||||
let source: String
|
||||
|
||||
init(source: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
|
||||
self.source = source
|
||||
super.init(data: nil, ofType: nil)
|
||||
self.image = image
|
||||
bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
private final class ComposerTextView: UITextView {
|
||||
private static let pastedImageDirectoryName = "t3-composer-paste"
|
||||
private static let stalePastedImageAge: TimeInterval = 60 * 60
|
||||
|
||||
var onPasteImages: (([String]) -> Void)?
|
||||
var onAttributedMutation: (() -> Void)?
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
if action == #selector(paste(_:)) {
|
||||
let pasteboard = UIPasteboard.general
|
||||
if pasteboard.hasImages ||
|
||||
pasteboard.itemProviders.contains(where: {
|
||||
$0.canLoadObject(ofClass: UIImage.self)
|
||||
}) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.canPerformAction(action, withSender: sender)
|
||||
}
|
||||
|
||||
override func paste(_ sender: Any?) {
|
||||
let pasteboard = UIPasteboard.general
|
||||
let imageProviders = pasteboard.itemProviders.filter {
|
||||
$0.canLoadObject(ofClass: UIImage.self)
|
||||
}
|
||||
if !imageProviders.isEmpty {
|
||||
loadImages(from: imageProviders)
|
||||
return
|
||||
}
|
||||
|
||||
let images = pasteboard.images ?? []
|
||||
if !images.isEmpty {
|
||||
let urls = images.compactMap(Self.writeTemporaryImage)
|
||||
if !urls.isEmpty {
|
||||
onPasteImages?(urls)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.paste(sender)
|
||||
}
|
||||
|
||||
override func deleteBackward() {
|
||||
guard selectedRange.length == 0, selectedRange.location > 0 else {
|
||||
super.deleteBackward()
|
||||
return
|
||||
}
|
||||
|
||||
let previousOffset = selectedRange.location - 1
|
||||
if textStorage.attribute(.attachment, at: previousOffset, effectiveRange: nil)
|
||||
is ComposerTextAttachment {
|
||||
replaceDisplayRange(NSRange(location: previousOffset, length: 1))
|
||||
return
|
||||
}
|
||||
|
||||
super.deleteBackward()
|
||||
}
|
||||
|
||||
private func replaceDisplayRange(_ range: NSRange) {
|
||||
guard let start = position(from: beginningOfDocument, offset: range.location),
|
||||
let end = position(from: start, offset: range.length),
|
||||
let textRange = textRange(from: start, to: end) else {
|
||||
return
|
||||
}
|
||||
replace(textRange, withText: "")
|
||||
}
|
||||
|
||||
private func loadImages(from providers: [NSItemProvider]) {
|
||||
let group = DispatchGroup()
|
||||
let lock = NSLock()
|
||||
var images = [UIImage?](repeating: nil, count: providers.count)
|
||||
|
||||
for (index, provider) in providers.enumerated() {
|
||||
group.enter()
|
||||
provider.loadObject(ofClass: UIImage.self) { object, _ in
|
||||
defer { group.leave() }
|
||||
guard let image = object as? UIImage else {
|
||||
return
|
||||
}
|
||||
lock.lock()
|
||||
images[index] = image
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
group.notify(queue: .main) { [weak self] in
|
||||
let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
|
||||
if !urls.isEmpty {
|
||||
self?.onPasteImages?(urls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func copy(_ sender: Any?) {
|
||||
guard selectedRange.length > 0 else {
|
||||
return super.copy(sender)
|
||||
}
|
||||
UIPasteboard.general.string = serializedText(in: selectedRange)
|
||||
}
|
||||
|
||||
override func cut(_ sender: Any?) {
|
||||
guard isEditable, selectedRange.length > 0 else {
|
||||
return super.cut(sender)
|
||||
}
|
||||
copy(sender)
|
||||
textStorage.replaceCharacters(in: selectedRange, with: "")
|
||||
selectedRange = NSRange(location: selectedRange.location, length: 0)
|
||||
onAttributedMutation?()
|
||||
}
|
||||
|
||||
func serializedText() -> String {
|
||||
serializedText(in: NSRange(location: 0, length: attributedText.length))
|
||||
}
|
||||
|
||||
func serializedText(in range: NSRange) -> String {
|
||||
guard range.length > 0 else {
|
||||
return ""
|
||||
}
|
||||
|
||||
let source = NSMutableString()
|
||||
let nsString = attributedText.string as NSString
|
||||
var cursor = range.location
|
||||
let end = NSMaxRange(range)
|
||||
attributedText.enumerateAttribute(.attachment, in: range) { value, attachmentRange, _ in
|
||||
if attachmentRange.location > cursor {
|
||||
source.append(
|
||||
nsString.substring(
|
||||
with: NSRange(location: cursor, length: attachmentRange.location - cursor)
|
||||
)
|
||||
)
|
||||
}
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
source.append(attachment.source)
|
||||
} else {
|
||||
source.append(nsString.substring(with: attachmentRange))
|
||||
}
|
||||
cursor = NSMaxRange(attachmentRange)
|
||||
}
|
||||
if cursor < end {
|
||||
source.append(nsString.substring(with: NSRange(location: cursor, length: end - cursor)))
|
||||
}
|
||||
return source as String
|
||||
}
|
||||
|
||||
func sourceOffset(forDisplayOffset displayOffset: Int) -> Int {
|
||||
let boundedOffset = max(0, min(attributedText.length, displayOffset))
|
||||
if boundedOffset == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
var sourceOffset = 0
|
||||
let range = NSRange(location: 0, length: boundedOffset)
|
||||
attributedText.enumerateAttribute(.attachment, in: range) { value, attributeRange, _ in
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
sourceOffset += (attachment.source as NSString).length
|
||||
} else {
|
||||
sourceOffset += attributeRange.length
|
||||
}
|
||||
}
|
||||
return sourceOffset
|
||||
}
|
||||
|
||||
private static func writeTemporaryImage(_ image: UIImage) -> String? {
|
||||
guard let data = image.pngData() else {
|
||||
return nil
|
||||
}
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
removeStaleTemporaryImages(in: directory)
|
||||
let url = directory.appendingPathComponent("\(UUID().uuidString).png")
|
||||
try data.write(to: url, options: .atomic)
|
||||
return url.absoluteString
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func removeStaleTemporaryImages(in directory: URL) {
|
||||
let cutoff = Date().addingTimeInterval(-stalePastedImageAge)
|
||||
guard let urls = try? FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],
|
||||
options: [.skipsHiddenFiles]
|
||||
) else {
|
||||
return
|
||||
}
|
||||
|
||||
for url in urls {
|
||||
guard
|
||||
let values = try? url.resourceValues(
|
||||
forKeys: [.contentModificationDateKey, .isRegularFileKey]
|
||||
),
|
||||
values.isRegularFile == true,
|
||||
let modifiedAt = values.contentModificationDate,
|
||||
modifiedAt < cutoff
|
||||
else {
|
||||
continue
|
||||
}
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
private let textView = ComposerTextView()
|
||||
private let placeholderLabel = UILabel()
|
||||
private var value = ""
|
||||
private var tokensJson = "[]"
|
||||
private var tokens: [ComposerTokenPayload] = []
|
||||
private var requestedSelection: ComposerSelectionPayload?
|
||||
private var theme = ComposerThemePayload(
|
||||
text: "#262626",
|
||||
placeholder: "#8e8e93",
|
||||
chipBackground: "#f2f2f7",
|
||||
chipBorder: "#dedee3",
|
||||
chipText: "#262626",
|
||||
skillBackground: "#f9e8fb",
|
||||
skillBorder: "#e5a6eb",
|
||||
skillText: "#a21caf",
|
||||
fileTint: "#737373"
|
||||
)
|
||||
private var fontFamily = "DMSans_400Regular"
|
||||
private var fontSize: CGFloat = 15
|
||||
private var lineHeight: CGFloat = 22
|
||||
private var contentInsetVertical: CGFloat = 0
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
private var isApplyingControlledValue = false
|
||||
private var lastContentSize = CGSize.zero
|
||||
private var iconImages: [String: UIImage] = [:]
|
||||
private var pendingIconUris = Set<String>()
|
||||
private var tokensNeedRebuild = false
|
||||
|
||||
let onComposerChange = EventDispatcher()
|
||||
let onComposerSelectionChange = EventDispatcher()
|
||||
let onComposerFocus = EventDispatcher()
|
||||
let onComposerBlur = EventDispatcher()
|
||||
let onComposerPasteImages = EventDispatcher()
|
||||
let onComposerContentSizeChange = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
clipsToBounds = false
|
||||
textView.delegate = self
|
||||
textView.backgroundColor = .clear
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
textView.keyboardDismissMode = .interactive
|
||||
textView.alwaysBounceVertical = false
|
||||
textView.showsVerticalScrollIndicator = true
|
||||
textView.adjustsFontForContentSizeCategory = true
|
||||
textView.onPasteImages = { [weak self] urls in
|
||||
self?.onComposerPasteImages(["uris": urls])
|
||||
}
|
||||
textView.onAttributedMutation = { [weak self] in
|
||||
self?.emitTextChange()
|
||||
}
|
||||
addSubview(textView)
|
||||
|
||||
placeholderLabel.numberOfLines = 0
|
||||
placeholderLabel.adjustsFontForContentSizeCategory = true
|
||||
addSubview(placeholderLabel)
|
||||
applyTypography()
|
||||
applyTheme()
|
||||
}
|
||||
|
||||
public override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
textView.frame = bounds
|
||||
let placeholderX = textView.textContainerInset.left + textView.textContainer.lineFragmentPadding
|
||||
let placeholderY = textView.textContainerInset.top
|
||||
let placeholderWidth = max(
|
||||
0,
|
||||
bounds.width - placeholderX - textView.textContainerInset.right -
|
||||
textView.textContainer.lineFragmentPadding
|
||||
)
|
||||
placeholderLabel.frame = CGRect(
|
||||
x: placeholderX,
|
||||
y: placeholderY,
|
||||
width: placeholderWidth,
|
||||
height: max(lineHeight, placeholderLabel.font.lineHeight)
|
||||
)
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
guard window != nil, shouldAutoFocus, !didAutoFocus else {
|
||||
return
|
||||
}
|
||||
didAutoFocus = true
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.textView.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
func setValue(_ value: String) {
|
||||
self.value = value
|
||||
applyControlledDocument(force: tokensNeedRebuild)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard self.tokensJson != tokensJson else {
|
||||
return
|
||||
}
|
||||
self.tokensJson = tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
applyControlledDocument(force: true)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setSelectionJson(_ selectionJson: String) {
|
||||
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
func setThemeJson(_ themeJson: String) {
|
||||
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
|
||||
return
|
||||
}
|
||||
theme = nextTheme
|
||||
applyTheme()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setPlaceholder(_ placeholder: String) {
|
||||
placeholderLabel.text = placeholder
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
func setFontFamily(_ fontFamily: String) {
|
||||
self.fontFamily = fontFamily
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setFontSize(_ fontSize: CGFloat) {
|
||||
self.fontSize = fontSize
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setLineHeight(_ lineHeight: CGFloat) {
|
||||
self.lineHeight = lineHeight
|
||||
applyTypography()
|
||||
applyControlledDocument(force: true)
|
||||
}
|
||||
|
||||
func setContentInsetVertical(_ contentInsetVertical: CGFloat) {
|
||||
self.contentInsetVertical = contentInsetVertical
|
||||
textView.textContainerInset = UIEdgeInsets(
|
||||
top: contentInsetVertical,
|
||||
left: 0,
|
||||
bottom: contentInsetVertical,
|
||||
right: 0
|
||||
)
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
func setEditable(_ editable: Bool) {
|
||||
textView.isEditable = editable
|
||||
}
|
||||
|
||||
func setScrollEnabled(_ scrollEnabled: Bool) {
|
||||
textView.isScrollEnabled = scrollEnabled
|
||||
}
|
||||
|
||||
func setAutoFocus(_ autoFocus: Bool) {
|
||||
shouldAutoFocus = autoFocus
|
||||
}
|
||||
|
||||
func setAutoCorrect(_ autoCorrect: Bool) {
|
||||
textView.autocorrectionType = autoCorrect ? .yes : .no
|
||||
}
|
||||
|
||||
func setSpellCheck(_ spellCheck: Bool) {
|
||||
textView.spellCheckingType = spellCheck ? .yes : .no
|
||||
}
|
||||
|
||||
func focusEditor() {
|
||||
textView.becomeFirstResponder()
|
||||
}
|
||||
|
||||
func blurEditor() {
|
||||
textView.resignFirstResponder()
|
||||
}
|
||||
|
||||
func setSelection(start: Int, end: Int) {
|
||||
requestedSelection = ComposerSelectionPayload(start: start, end: end)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
public func textViewDidChange(_ textView: UITextView) {
|
||||
emitTextChange()
|
||||
}
|
||||
|
||||
public func textViewDidChangeSelection(_ textView: UITextView) {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
public func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
onComposerFocus()
|
||||
}
|
||||
|
||||
public func textViewDidEndEditing(_ textView: UITextView) {
|
||||
onComposerBlur()
|
||||
}
|
||||
|
||||
private func applyControlledDocument(force: Bool = false) {
|
||||
let currentSource = textView.serializedText()
|
||||
guard force || currentSource != value || !documentMatchesExpectedTokens() else {
|
||||
updatePlaceholderVisibility()
|
||||
return
|
||||
}
|
||||
|
||||
let previousSelection = sourceSelection()
|
||||
isApplyingControlledValue = true
|
||||
textView.attributedText = makeAttributedDocument()
|
||||
let targetSelection = requestedSelection ?? previousSelection
|
||||
requestedSelection = nil
|
||||
textView.selectedRange = displayRange(for: targetSelection)
|
||||
isApplyingControlledValue = false
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func makeAttributedDocument() -> NSAttributedString {
|
||||
let result = NSMutableAttributedString()
|
||||
let source = value as NSString
|
||||
var cursor = 0
|
||||
let validTokens = tokens.filter {
|
||||
$0.start >= cursor &&
|
||||
$0.end > $0.start &&
|
||||
$0.end <= source.length &&
|
||||
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
|
||||
}
|
||||
|
||||
for token in validTokens {
|
||||
if token.start < cursor {
|
||||
continue
|
||||
}
|
||||
if token.start > cursor {
|
||||
appendPlainText(
|
||||
source.substring(with: NSRange(location: cursor, length: token.start - cursor)),
|
||||
to: result
|
||||
)
|
||||
}
|
||||
result.append(makeAttachmentString(token))
|
||||
cursor = token.end
|
||||
}
|
||||
if cursor < source.length {
|
||||
appendPlainText(
|
||||
source.substring(with: NSRange(location: cursor, length: source.length - cursor)),
|
||||
to: result
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private func appendPlainText(_ text: String, to result: NSMutableAttributedString) {
|
||||
result.append(NSAttributedString(string: text, attributes: baseAttributes()))
|
||||
}
|
||||
|
||||
private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
|
||||
let isSkill = token.type == "skill"
|
||||
let tint = UIColor(composerHex: isSkill ? theme.skillText : theme.fileTint) ?? .secondaryLabel
|
||||
let iconName = isSkill ? "cube" : "doc"
|
||||
let iconImage = token.iconUri.flatMap(iconImage(for:))
|
||||
let style = ComposerChipStyle(
|
||||
tint: tint,
|
||||
backgroundColor: UIColor(
|
||||
composerHex: isSkill ? theme.skillBackground : theme.chipBackground
|
||||
) ?? .secondarySystemFill,
|
||||
borderColor: UIColor(
|
||||
composerHex: isSkill ? theme.skillBorder : theme.chipBorder
|
||||
) ?? .separator,
|
||||
textColor: UIColor(composerHex: isSkill ? theme.skillText : theme.chipText) ?? .label
|
||||
)
|
||||
let image = renderChip(
|
||||
label: token.label,
|
||||
iconName: iconName,
|
||||
iconImage: iconImage,
|
||||
style: style
|
||||
)
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
let baselineOffset = floor((font.capHeight - image.size.height) / 2)
|
||||
let attachment = ComposerTextAttachment(
|
||||
source: token.source,
|
||||
image: image,
|
||||
size: image.size,
|
||||
baselineOffset: baselineOffset
|
||||
)
|
||||
return NSAttributedString(attachment: attachment)
|
||||
}
|
||||
|
||||
private func renderChip(
|
||||
label: String,
|
||||
iconName: String,
|
||||
iconImage: UIImage?,
|
||||
style: ComposerChipStyle
|
||||
) -> UIImage {
|
||||
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
|
||||
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
|
||||
let fallbackIcon = UIImage(
|
||||
systemName: iconName,
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .medium)
|
||||
)
|
||||
let icon = iconImage ?? fallbackIcon
|
||||
let textSize = (label as NSString).size(withAttributes: [.font: font])
|
||||
let iconWidth = icon == nil ? 0 : 14
|
||||
let iconGap = icon == nil ? 0 : 5
|
||||
let height: CGFloat = 24
|
||||
let width = ceil(9 + CGFloat(iconWidth + iconGap) + textSize.width + 9)
|
||||
let format = UIGraphicsImageRendererFormat.preferred()
|
||||
format.opaque = false
|
||||
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
|
||||
return renderer.image { context in
|
||||
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
|
||||
let path = UIBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), cornerRadius: 7)
|
||||
style.backgroundColor.setFill()
|
||||
path.fill()
|
||||
style.borderColor.setStroke()
|
||||
path.lineWidth = 1
|
||||
path.stroke()
|
||||
|
||||
var x: CGFloat = 9
|
||||
if let icon {
|
||||
let renderedIcon = iconImage == nil
|
||||
? icon.withTintColor(style.tint, renderingMode: .alwaysOriginal)
|
||||
: icon
|
||||
renderedIcon.draw(
|
||||
in: CGRect(x: x, y: 5, width: 14, height: 14)
|
||||
)
|
||||
x += 19
|
||||
}
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.alignment = .left
|
||||
(label as NSString).draw(
|
||||
in: CGRect(x: x, y: 3, width: textSize.width + 1, height: 18),
|
||||
withAttributes: [
|
||||
.font: font,
|
||||
.foregroundColor: style.textColor,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
)
|
||||
context.cgContext.setAllowsAntialiasing(true)
|
||||
}
|
||||
}
|
||||
|
||||
private func iconImage(for uri: String) -> UIImage? {
|
||||
if let image = iconImages[uri] {
|
||||
return image
|
||||
}
|
||||
guard !pendingIconUris.contains(uri), let url = URL(string: uri) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {
|
||||
iconImages[uri] = image
|
||||
return image
|
||||
}
|
||||
|
||||
pendingIconUris.insert(uri)
|
||||
URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
|
||||
guard let self, let data, let image = UIImage(data: data) else {
|
||||
DispatchQueue.main.async {
|
||||
self?.pendingIconUris.remove(uri)
|
||||
}
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
self.pendingIconUris.remove(uri)
|
||||
self.iconImages[uri] = image
|
||||
self.applyControlledDocument(force: true)
|
||||
}
|
||||
}.resume()
|
||||
return nil
|
||||
}
|
||||
|
||||
private func baseAttributes() -> [NSAttributedString.Key: Any] {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.minimumLineHeight = lineHeight
|
||||
paragraph.maximumLineHeight = lineHeight
|
||||
return [
|
||||
.font: font,
|
||||
.foregroundColor: UIColor(composerHex: theme.text) ?? .label,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
}
|
||||
|
||||
private func applyTypography() {
|
||||
let font = UIFont(name: fontFamily, size: fontSize)
|
||||
?? UIFont.systemFont(ofSize: fontSize)
|
||||
textView.font = font
|
||||
textView.typingAttributes = baseAttributes()
|
||||
placeholderLabel.font = font
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func applyTheme() {
|
||||
textView.textColor = UIColor(composerHex: theme.text) ?? .label
|
||||
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
|
||||
tintColor = UIColor.systemBlue
|
||||
}
|
||||
|
||||
private func emitTextChange() {
|
||||
guard !isApplyingControlledValue else {
|
||||
return
|
||||
}
|
||||
value = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
onComposerChange([
|
||||
"value": value,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
])
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
let selection = sourceSelection()
|
||||
onComposerSelectionChange([
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
])
|
||||
}
|
||||
|
||||
private func sourceSelection() -> ComposerSelectionPayload {
|
||||
ComposerSelectionPayload(
|
||||
start: textView.sourceOffset(forDisplayOffset: textView.selectedRange.location),
|
||||
end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))
|
||||
)
|
||||
}
|
||||
|
||||
private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {
|
||||
let start = displayOffset(forSourceOffset: selection.start)
|
||||
let end = displayOffset(forSourceOffset: selection.end)
|
||||
return NSRange(location: start, length: max(0, end - start))
|
||||
}
|
||||
|
||||
private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
|
||||
let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
|
||||
var collapsedLength = 0
|
||||
for token in tokens where token.end <= boundedOffset {
|
||||
collapsedLength += max(0, token.end - token.start - 1)
|
||||
}
|
||||
if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
|
||||
return token.start - collapsedLength + 1
|
||||
}
|
||||
return boundedOffset - collapsedLength
|
||||
}
|
||||
|
||||
private func applyRequestedSelection() {
|
||||
guard let requestedSelection else {
|
||||
return
|
||||
}
|
||||
let nextRange = displayRange(for: requestedSelection)
|
||||
guard nextRange.location <= textView.attributedText.length,
|
||||
NSMaxRange(nextRange) <= textView.attributedText.length else {
|
||||
return
|
||||
}
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
placeholderLabel.isHidden = !value.isEmpty
|
||||
}
|
||||
|
||||
private func emitContentSizeIfNeeded() {
|
||||
let nextSize = textView.contentSize
|
||||
guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
|
||||
abs(nextSize.height - lastContentSize.height) > 0.5 else {
|
||||
return
|
||||
}
|
||||
lastContentSize = nextSize
|
||||
onComposerContentSizeChange(["width": nextSize.width, "height": nextSize.height])
|
||||
}
|
||||
|
||||
private func decode<T: Decodable>(_ type: T.Type, from json: String) -> T? {
|
||||
guard let data = json.data(using: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
return try? JSONDecoder().decode(type, from: data)
|
||||
}
|
||||
|
||||
private func tokensMatchCurrentValue() -> Bool {
|
||||
let source = value as NSString
|
||||
return tokens.allSatisfy {
|
||||
$0.start >= 0 &&
|
||||
$0.end > $0.start &&
|
||||
$0.end <= source.length &&
|
||||
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
|
||||
}
|
||||
}
|
||||
|
||||
private func documentMatchesExpectedTokens() -> Bool {
|
||||
let source = value as NSString
|
||||
let expectedSources = tokens.compactMap { token -> String? in
|
||||
guard token.start >= 0,
|
||||
token.end > token.start,
|
||||
token.end <= source.length,
|
||||
source.substring(
|
||||
with: NSRange(location: token.start, length: token.end - token.start)
|
||||
) == token.source else {
|
||||
return nil
|
||||
}
|
||||
return token.source
|
||||
}
|
||||
var renderedSources: [String] = []
|
||||
textView.attributedText.enumerateAttribute(
|
||||
.attachment,
|
||||
in: NSRange(location: 0, length: textView.attributedText.length)
|
||||
) { value, _, _ in
|
||||
if let attachment = value as? ComposerTextAttachment {
|
||||
renderedSources.append(attachment.source)
|
||||
}
|
||||
}
|
||||
return renderedSources == expectedSources
|
||||
}
|
||||
}
|
||||
|
||||
private extension UIColor {
|
||||
convenience init?(composerHex hex: String?) {
|
||||
guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
if value.hasPrefix("#") {
|
||||
value.removeFirst()
|
||||
}
|
||||
guard value.count == 6 || value.count == 8,
|
||||
let raw = UInt64(value, radix: 16) else {
|
||||
return nil
|
||||
}
|
||||
if value.count == 8 {
|
||||
self.init(
|
||||
red: CGFloat((raw >> 24) & 0xff) / 255,
|
||||
green: CGFloat((raw >> 16) & 0xff) / 255,
|
||||
blue: CGFloat((raw >> 8) & 0xff) / 255,
|
||||
alpha: CGFloat(raw & 0xff) / 255
|
||||
)
|
||||
} else {
|
||||
self.init(
|
||||
red: CGFloat((raw >> 16) & 0xff) / 255,
|
||||
green: CGFloat((raw >> 8) & 0xff) / 255,
|
||||
blue: CGFloat(raw & 0xff) / 255,
|
||||
alpha: 1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024-25 Bluesky PBC
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,25 @@
|
||||
require "json"
|
||||
|
||||
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
|
||||
new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
|
||||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "T3MarkdownText"
|
||||
s.version = package["version"]
|
||||
s.summary = "Native selectable markdown renderer for T3 Code mobile."
|
||||
s.description = "Fabric-backed attributed text and markdown rendering primitives owned by T3 Code."
|
||||
s.homepage = "https://t3tools.com"
|
||||
s.license = { :type => "MIT", :file => "LICENSE" }
|
||||
s.author = { "T3 Tools" => "[email protected]" }
|
||||
s.platforms = { :ios => min_ios_version_supported }
|
||||
s.source = { :path => "." }
|
||||
s.source_files = "ios/**/*.{h,m,mm,cpp}"
|
||||
|
||||
install_modules_dependencies(s)
|
||||
|
||||
if ENV["USE_FRAMEWORKS"] != nil && new_arch_enabled
|
||||
add_dependency(s, "React-FabricComponents", :additional_framework_paths => [
|
||||
"react/renderer/textlayoutmanager/platform/ios",
|
||||
])
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,12 @@
|
||||
# Upstream Attribution
|
||||
|
||||
The Fabric attributed-text component in this module originated from
|
||||
[`bluesky-social/react-native-uitextview`](https://github.com/bluesky-social/react-native-uitextview),
|
||||
version `2.2.0`, commit `addc08fea303608f070fe1eeba4bc075f181c4af`.
|
||||
|
||||
The upstream project is Copyright (c) 2024-25 Bluesky PBC and licensed under
|
||||
the MIT License included in this directory.
|
||||
|
||||
T3 Code has substantially modified and renamed the implementation, integrated
|
||||
its markdown renderer, and owns the resulting module going forward. This is not
|
||||
an upstream package dependency or a compatibility fork.
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 870 B |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 534 B |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 472 B |
|
After Width: | Height: | Size: 620 B |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 497 B |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 3.1 KiB |