create-disposabl-app 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/disposabl.js CHANGED
@@ -5,7 +5,7 @@ import { lock } from "proper-lockfile";
5
5
  // ../cli/package.json
6
6
  var package_default = {
7
7
  name: "@disposabl/cli",
8
- version: "0.14.0",
8
+ version: "0.14.1",
9
9
  type: "module",
10
10
  description: "Command-line access to your Disposabl app",
11
11
  license: "MIT",
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
8
8
  import { Command, CommanderError } from "commander";
9
9
  import * as p2 from "@clack/prompts";
10
10
  // package.json
11
- var version = "0.14.0";
11
+ var version = "0.14.1";
12
12
 
13
13
  // ../disposabl-kit/platforms.ts
14
14
  var platforms = [
@@ -49,6 +49,14 @@ Windows and Linux installers are unsigned. macOS uses ad hoc signing and provide
49
49
 
50
50
  The desktop window uses `http://localhost:3000` during development and the deployed `CONVEX_SITE_URL` in packaged builds. It shares the website and authentication flow; if the site is unavailable, it shows the bundled starter page.
51
51
 
52
+ ## Browser and sign-in handoff
53
+
54
+ External HTTPS links open in the system browser. Connection flows can create a temporary blank window while requesting their provider URL; it closes after opening that URL in the browser. Other native protocols and credential-bearing URLs are rejected. App pages remain sandboxed, with context isolation enabled and Node integration disabled.
55
+
56
+ Google sign-in returns through `/oauth/desktop` to the installed app's unique `disposabl-desktop-<desktopId>` protocol. The return contains only Convex's one-time ticket. The initiating app retains the flow state and redeems the ticket through the existing auth client. Keep `desktopId` unchanged between builds. macOS packaging declares the protocol; Windows registers it when the installed app starts, and Linux packages declare its MIME handler. Development builds do not register an OS protocol. Use an installed build for real browser-return verification. Other external provider pages may require their own browser session.
57
+
58
+ Run `E2E_DESKTOP_NAVIGATION=1 bun run e2e run desktop-navigation.e2e.ts --target backend --retries 0` on a machine with Electron installed and a graphical session. It compiles the actual main/preload, checks navigation and callback delivery using local fixture pages, and intercepts system-browser launches. It makes no provider requests and does not prove a Google transaction, OS protocol association, or native binary update. Test those separately on each supported OS.
59
+
52
60
  ## Native updates
53
61
 
54
62
  The website is loaded from `CONVEX_SITE_URL`; refreshing it receives deployed web changes independently of a native update. The app menu's **Check for updates** checks the installed native binary on macOS and Windows, downloads an available update, and asks before restarting. A downloaded update may also install at the next launch. Development builds and builds without a feed report that updates are not configured. Linux uses the system package manager; the menu explains this and does not claim to check for an update. The existing DEB/RPM artifacts do not configure an apt or RPM repository, so operators must provide one for package-manager updates.
@@ -9,14 +9,20 @@ import { MakerRpm } from '@electron-forge/maker-rpm';
9
9
  import { VitePlugin } from '@electron-forge/plugin-vite';
10
10
  import { FusesPlugin } from '@electron-forge/plugin-fuses';
11
11
  import { FuseV1Options, FuseVersion } from '@electron/fuses';
12
+ import { desktopAuthScheme } from '../../packages/disposabl-kit/lib/desktop-auth';
12
13
 
13
14
  const executableName = manifest.name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
15
+ const authScheme = desktopAuthScheme(
16
+ 'disposablDesktopId' in manifest ? manifest.disposablDesktopId : null,
17
+ );
18
+ const mimeType = authScheme ? [`x-scheme-handler/${authScheme}`] : [];
14
19
 
15
20
  // specTemplate is supported by electron-installer-redhat but absent from Forge's types.
16
21
  const rpmOptions = {
17
22
  name: executableName,
18
23
  bin: executableName,
19
24
  specTemplate: resolve('rpm.spec.ejs'),
25
+ mimeType,
20
26
  };
21
27
 
22
28
  const signedRelease =
@@ -33,6 +39,9 @@ const config: ForgeConfig = {
33
39
  packagerConfig: {
34
40
  asar: true,
35
41
  executableName,
42
+ ...(authScheme
43
+ ? { protocols: [{ name: manifest.productName, schemes: [authScheme] }] }
44
+ : {}),
36
45
  icon: 'src/assets/icon',
37
46
  appBundleId:
38
47
  process.env.MACOS_BUNDLE_ID ||
@@ -85,7 +94,9 @@ const config: ForgeConfig = {
85
94
  new MakerZIP({}, ['darwin']),
86
95
  new MakerDMG({ format: 'ULFO' }),
87
96
  new MakerRpm({ options: rpmOptions }),
88
- new MakerDeb({ options: { name: executableName, bin: executableName } }),
97
+ new MakerDeb({
98
+ options: { name: executableName, bin: executableName, mimeType },
99
+ }),
89
100
  ],
90
101
  plugins: [
91
102
  new VitePlugin({
@@ -1,5 +1,10 @@
1
- import { app, autoUpdater, BrowserWindow, dialog, Menu } from 'electron';
1
+ import { app, autoUpdater, BrowserWindow, dialog, Menu, shell } from 'electron';
2
2
  import { createUpdateController, feedUrl, type UpdateState } from './updates';
3
+ import { protectNavigation } from './navigation';
4
+ import {
5
+ desktopAuthCallback,
6
+ desktopAuthScheme,
7
+ } from '../../../packages/disposabl-kit/lib/desktop-auth';
3
8
  import path from 'node:path';
4
9
  import started from 'electron-squirrel-startup';
5
10
 
@@ -11,30 +16,104 @@ if (DISPOSABL_DESKTOP_ID)
11
16
 
12
17
  if (started) app.quit();
13
18
 
19
+ const website =
20
+ DISPOSABL_WEB_URL || (app.isPackaged ? '' : 'http://localhost:3000');
21
+ const authScheme = desktopAuthScheme(DISPOSABL_DESKTOP_ID);
22
+ let mainWindow: BrowserWindow | undefined;
23
+ let pendingAuth: string | undefined;
24
+ function receiveAuth(url: string) {
25
+ if (!desktopAuthCallback(url, DISPOSABL_DESKTOP_ID, website)) return;
26
+ pendingAuth = url;
27
+ if (app.isReady() && (!mainWindow || mainWindow.isDestroyed())) {
28
+ void createWindow();
29
+ return;
30
+ }
31
+ finishAuth();
32
+ }
33
+ function finishAuth() {
34
+ if (
35
+ !pendingAuth ||
36
+ !mainWindow ||
37
+ mainWindow.isDestroyed() ||
38
+ mainWindow.webContents.isLoading()
39
+ )
40
+ return;
41
+ const current = mainWindow.webContents.getURL();
42
+ const destination =
43
+ current && new URL(current).origin === new URL(website).origin
44
+ ? current
45
+ : website;
46
+ const target = desktopAuthCallback(
47
+ pendingAuth,
48
+ DISPOSABL_DESKTOP_ID,
49
+ destination,
50
+ );
51
+ pendingAuth = undefined;
52
+ if (!target) return;
53
+ mainWindow.show();
54
+ mainWindow.focus();
55
+ void mainWindow.loadURL(target).catch(() => {
56
+ void dialog.showMessageBox({
57
+ type: 'error',
58
+ message: 'Could not return to sign-in. Please try again.',
59
+ });
60
+ });
61
+ }
62
+ if (authScheme) {
63
+ if (!app.requestSingleInstanceLock()) app.exit(0);
64
+ // Packaged protocol metadata and Windows registration use this app's unique identity.
65
+ if (app.isPackaged) app.setAsDefaultProtocolClient(authScheme);
66
+ app.on('open-url', (event, url) => {
67
+ event.preventDefault();
68
+ receiveAuth(url);
69
+ });
70
+ app.on('second-instance', (_event, args) => {
71
+ for (const arg of args)
72
+ if (arg.startsWith(`${authScheme}://`)) receiveAuth(arg);
73
+ if (mainWindow && !mainWindow.isDestroyed()) {
74
+ mainWindow.show();
75
+ mainWindow.focus();
76
+ }
77
+ });
78
+ for (const arg of process.argv)
79
+ if (arg.startsWith(`${authScheme}://`)) receiveAuth(arg);
80
+ }
81
+
14
82
  async function createWindow() {
15
83
  const window = new BrowserWindow({
16
- title: 'Disposabl',
84
+ title: app.name,
17
85
  width: 1000,
18
86
  height: 720,
19
87
  webPreferences: {
20
88
  sandbox: true,
21
89
  contextIsolation: true,
22
90
  nodeIntegration: false,
91
+ preload: path.join(__dirname, 'preload.cjs'),
92
+ additionalArguments: authScheme ? ['--disposabl-desktop-auth'] : [],
23
93
  },
24
94
  });
95
+ mainWindow = window;
96
+ window.webContents.on('did-stop-loading', finishAuth);
25
97
  window.webContents.session.setPermissionRequestHandler(
26
98
  (_contents, _permission, callback) => callback(false),
27
99
  );
28
- window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
29
100
  // Reuse the website's home, authentication and feature selection in the desktop app.
30
- const website = app.isPackaged ? DISPOSABL_WEB_URL : 'http://localhost:3000';
31
101
  if (website) {
32
102
  const origin = new URL(website).origin;
33
103
  if (app.isPackaged && !website.startsWith('https://'))
34
104
  throw new Error('Desktop requires an HTTPS website.');
35
- window.webContents.on('will-navigate', (event, url) => {
36
- if (new URL(url).origin !== origin) event.preventDefault();
37
- });
105
+ protectNavigation(
106
+ window.webContents,
107
+ origin,
108
+ (url) => shell.openExternal(url),
109
+ () => {
110
+ if (window.isDestroyed()) return;
111
+ void dialog.showMessageBox(window, {
112
+ type: 'error',
113
+ message: 'Could not open your browser. Please try again.',
114
+ });
115
+ },
116
+ );
38
117
  try {
39
118
  await window.loadURL(website);
40
119
  return;
@@ -129,9 +208,9 @@ app.whenReady().then(() => {
129
208
  autoUpdater.on('error', updates.error);
130
209
  }
131
210
  renderMenu();
132
- void createWindow();
211
+ if (!mainWindow || mainWindow.isDestroyed()) void createWindow();
133
212
  app.on('activate', () => {
134
- if (BrowserWindow.getAllWindows().length === 0) void createWindow();
213
+ if (!mainWindow || mainWindow.isDestroyed()) void createWindow();
135
214
  });
136
215
  });
137
216
  app.on('window-all-closed', () => {
@@ -0,0 +1,74 @@
1
+ import type { WebContents } from 'electron';
2
+
3
+ export function externalUrl(input: string) {
4
+ try {
5
+ const url = new URL(input);
6
+ return url.protocol === 'https:' && !url.username && !url.password
7
+ ? url.href
8
+ : null;
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ /** Keep remote content outside the app's privileged window and preload. */
15
+ export function protectNavigation(
16
+ contents: WebContents,
17
+ origin: string,
18
+ openExternal: (url: string) => Promise<void>,
19
+ onError: () => void,
20
+ closePopup?: () => void,
21
+ ) {
22
+ const sameOrigin = (input: string) => {
23
+ try {
24
+ return new URL(input).origin === origin;
25
+ } catch {
26
+ return false;
27
+ }
28
+ };
29
+ const open = (input: string) => {
30
+ const url = externalUrl(input);
31
+ if (!url) return;
32
+ void openExternal(url).then(
33
+ () => closePopup?.(),
34
+ () => {
35
+ closePopup?.();
36
+ onError();
37
+ },
38
+ );
39
+ };
40
+ const navigate = (event: { preventDefault(): void }, url: string) => {
41
+ if (sameOrigin(url)) return;
42
+ event.preventDefault();
43
+ open(url);
44
+ };
45
+ contents.on('will-navigate', navigate);
46
+ contents.on('will-redirect', (event) => {
47
+ if (event.isMainFrame) navigate(event, event.url);
48
+ });
49
+ contents.setWindowOpenHandler(({ url }) => {
50
+ if (url === 'about:blank' || sameOrigin(url))
51
+ return {
52
+ action: 'allow',
53
+ overrideBrowserWindowOptions: {
54
+ show: url !== 'about:blank',
55
+ webPreferences: {
56
+ sandbox: true,
57
+ contextIsolation: true,
58
+ nodeIntegration: false,
59
+ },
60
+ },
61
+ };
62
+ open(url);
63
+ return { action: 'deny' };
64
+ });
65
+ contents.on('did-create-window', (child) => {
66
+ child.webContents.session.setPermissionRequestHandler(
67
+ (_contents, _permission, callback) => callback(false),
68
+ );
69
+ protectNavigation(child.webContents, origin, openExternal, onError, () =>
70
+ child.close(),
71
+ );
72
+ });
73
+ contents.on('will-attach-webview', (event) => event.preventDefault());
74
+ }
@@ -1,3 +1,4 @@
1
- // oxlint-disable eslint-plugin-unicorn/no-empty-file
2
- // See the Electron documentation for details on how to use preload scripts:
3
- // https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts
1
+ import { contextBridge } from 'electron';
2
+
3
+ if (process.argv.includes('--disposabl-desktop-auth'))
4
+ contextBridge.exposeInMainWorld('disposablDesktop', { authentication: true });
@@ -7,6 +7,13 @@ import {
7
7
  import { api } from "../../../backend/convex/_generated/api";
8
8
  import { Button } from "./ui/button";
9
9
  import googleLogo from "../../lib/google-logo.png";
10
+ import { desktopAuthPath } from "../../lib/desktop-auth";
11
+
12
+ declare global {
13
+ interface Window {
14
+ disposablDesktop?: { authentication: boolean };
15
+ }
16
+ }
10
17
 
11
18
  export function GoogleSignIn() {
12
19
  const providers = useQuery(api.auth.providers);
@@ -47,7 +54,11 @@ export function GoogleSignIn() {
47
54
  onClick={async () => {
48
55
  setStartError(null);
49
56
  setPending(true);
50
- const result = await signIn({ redirectTo: window.location.href });
57
+ const redirectTo = window.disposablDesktop?.authentication
58
+ ? new URL(desktopAuthPath, import.meta.env.VITE_CONVEX_SITE_URL)
59
+ .href
60
+ : window.location.href;
61
+ const result = await signIn({ redirectTo });
51
62
  if (result.status === "error") {
52
63
  setPending(false);
53
64
  setStartError("Couldn't start Google sign-in. Please try again.");
@@ -61,6 +72,16 @@ export function GoogleSignIn() {
61
72
  />
62
73
  {pending ? "Opening Google…" : "Sign in with Google"}
63
74
  </Button>
75
+ {pending && window.disposablDesktop?.authentication && (
76
+ <Button
77
+ type="button"
78
+ variant="ghost"
79
+ className="w-full"
80
+ onClick={() => window.location.reload()}
81
+ >
82
+ Back to sign-in
83
+ </Button>
84
+ )}
64
85
  {error && (
65
86
  <p role="alert" className="text-sm text-destructive">
66
87
  {error}
@@ -0,0 +1,73 @@
1
+ export const desktopAuthPath = "/oauth/desktop";
2
+
3
+ export function desktopAuthScheme(id: unknown) {
4
+ return typeof id === "string" && /^[a-f0-9]{32}$/.test(id)
5
+ ? `disposabl-desktop-${id}`
6
+ : null;
7
+ }
8
+
9
+ function ticket(url: URL) {
10
+ const code = url.searchParams.getAll("convexAuthCode");
11
+ const error = url.searchParams.getAll("convexAuthError");
12
+ if (code.length === 1 && !error.length && code[0] && code[0].length <= 4096)
13
+ return { name: "convexAuthCode", value: code[0] };
14
+ if (error.length === 1 && !code.length && error[0])
15
+ return {
16
+ name: "convexAuthError",
17
+ value: error[0] === "access_denied" ? "access_denied" : "oauth_error",
18
+ };
19
+ return null;
20
+ }
21
+
22
+ /** The browser forwards only a one-time ticket. The initiating app retains flow state. */
23
+ export function desktopAuthRedirect(request: Request, id: unknown) {
24
+ const scheme = desktopAuthScheme(id);
25
+ const result = ticket(new URL(request.url));
26
+ const headers = {
27
+ "Cache-Control": "no-store",
28
+ "Referrer-Policy": "no-referrer",
29
+ };
30
+ if (!scheme || !result)
31
+ return new Response("Invalid desktop sign-in response.", {
32
+ status: 400,
33
+ headers,
34
+ });
35
+ const target = new URL(`${scheme}://login`);
36
+ target.searchParams.set(result.name, result.value);
37
+ return new Response(null, {
38
+ status: 302,
39
+ headers: { ...headers, Location: target.href },
40
+ });
41
+ }
42
+
43
+ export function desktopAuthCallback(
44
+ input: string,
45
+ id: unknown,
46
+ destination: string,
47
+ ) {
48
+ try {
49
+ const scheme = desktopAuthScheme(id);
50
+ const url = new URL(input);
51
+ const target = new URL(destination);
52
+ if (
53
+ !scheme ||
54
+ url.protocol !== `${scheme}:` ||
55
+ url.hostname !== "login" ||
56
+ url.pathname ||
57
+ url.username ||
58
+ url.password ||
59
+ url.port ||
60
+ url.hash ||
61
+ !["https:", "http:"].includes(target.protocol)
62
+ )
63
+ return null;
64
+ const result = ticket(url);
65
+ if (!result) return null;
66
+ target.searchParams.delete("convexAuthCode");
67
+ target.searchParams.delete("convexAuthError");
68
+ target.searchParams.set(result.name, result.value);
69
+ return target.href;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
@@ -20,6 +20,7 @@ import { registerPageRoutes } from "./lib/static";
20
20
  import { resend } from "../../backend/convex/emails";
21
21
  import { googleRelay } from "./google";
22
22
  import { mobileAuthPath, mobileAuthRedirect } from "../lib/mobile-auth";
23
+ import { desktopAuthPath, desktopAuthRedirect } from "../lib/desktop-auth";
23
24
 
24
25
  export { tool } from "@convex-dev/mcp";
25
26
  export type { McpServerOptions, McpUser, ToolCtx } from "@convex-dev/mcp";
@@ -65,6 +66,21 @@ export const {
65
66
  export default function createHttpRouter(apiPolicy?: ApiPolicy) {
66
67
  const http = httpRouter();
67
68
  if (authenticationEnabled) {
69
+ if (
70
+ enabled.some((platform) =>
71
+ ["macos", "windows", "linux"].includes(platform),
72
+ )
73
+ )
74
+ http.route({
75
+ path: desktopAuthPath,
76
+ method: "GET",
77
+ handler: httpActionGeneric(async (_ctx, request) =>
78
+ desktopAuthRedirect(
79
+ request,
80
+ "desktopId" in config ? config.desktopId : null,
81
+ ),
82
+ ),
83
+ });
68
84
  if (
69
85
  enabled.some((platform) => platform === "ios" || platform === "android")
70
86
  )
@@ -52,6 +52,8 @@ When supplying an isolated backend through Metro's shell environment, also set `
52
52
 
53
53
  ## CI
54
54
 
55
+ Desktop navigation can be checked locally with `E2E_DESKTOP_NAVIGATION=1 bun run e2e run desktop-navigation.e2e.ts --target backend --retries 0`. This opt-in flow requires the desktop workspace, installed Electron binary, and a graphical session. It launches an isolated Electron instance against local fixture pages, intercepts browser launches, and checks the application's navigation and OAuth callback handling. No backend or provider calls are made. This is separate from real Google sign-in, installed protocol registration, and two-version native update verification.
56
+
55
57
  The same commands work in CI without model credentials. On Linux, install Chromium's system dependencies with `bun run --cwd packages/tests setup:browser`. Provision an isolated backend and deploy the current functions before testing. Set its URLs, then run `bun run test --target web,backend` and include `,api` when `disposabl.json` enables it.
56
58
 
57
59
  Run Android separately on a runner with an emulator and iOS on macOS with Xcode and a simulator. Build/install the test artifact before its E2E run. Gate publication on the required target results; native E2E cannot run before an app exists to install. This setup does not replace or automatically gate the repository's existing deployment workflows.
@@ -0,0 +1,219 @@
1
+ // Runs inside Electron against the compiled application main and preload.
2
+ const { app, BrowserWindow, shell, dialog } = require("electron");
3
+ const assert = require("node:assert/strict");
4
+ const { once, EventEmitter } = require("node:events");
5
+ const path = require("node:path");
6
+ const [build, origin, id] = process.argv.slice(2);
7
+ const cold = process.argv.includes(
8
+ `disposabl-desktop-${id}://login?convexAuthCode=cold-ticket`,
9
+ );
10
+ app.setPath("appData", build);
11
+ app.setPath("userData", path.join(build, "user-data"));
12
+ const events = new EventEmitter();
13
+ const opened = [];
14
+ const dialogs = [];
15
+ shell.openExternal = async (url) => {
16
+ opened.push(url);
17
+ if (url === "https://broken.example.test/")
18
+ throw new Error("No browser handler");
19
+ events.emit("external", url);
20
+ };
21
+ dialog.showMessageBox = async (...args) => {
22
+ dialogs.push(args.at(-1).message);
23
+ events.emit("dialog");
24
+ return { response: 0 };
25
+ };
26
+ const firstWindow = new Promise((resolve) => {
27
+ app.once("browser-window-created", (_event, window) => {
28
+ window.hide();
29
+ window.webContents.on("console-message", (event) =>
30
+ console.error("renderer:", event.message),
31
+ );
32
+ window.webContents.on("preload-error", (_event, path, error) =>
33
+ console.error("preload:", path, error),
34
+ );
35
+ window.webContents.on("did-finish-load", () => {
36
+ if (
37
+ !cold ||
38
+ new URL(window.webContents.getURL()).searchParams.get(
39
+ "convexAuthCode",
40
+ ) === "cold-ticket"
41
+ )
42
+ resolve(window);
43
+ });
44
+ });
45
+ });
46
+ const timeout = setTimeout(() => {
47
+ console.error("Desktop fixture timed out");
48
+ app.exit(1);
49
+ }, 25000);
50
+ require(path.join(build, "main.cjs"));
51
+ (async () => {
52
+ const window = await firstWindow;
53
+ const contents = window.webContents;
54
+ console.log("stage: loaded", contents.getURL());
55
+ const prefs = contents.getLastWebPreferences();
56
+ assert.equal(prefs.sandbox, true);
57
+ assert.equal(prefs.contextIsolation, true);
58
+ assert.equal(prefs.nodeIntegration, false);
59
+ assert.equal(
60
+ await contents.executeJavaScript("window.disposablDesktop.authentication"),
61
+ true,
62
+ );
63
+ await contents.executeJavaScript(
64
+ "localStorage.setItem('flow-fixture', 'private-initiator-state')",
65
+ );
66
+
67
+ const redirected = once(contents, "will-redirect");
68
+ await contents.executeJavaScript(
69
+ "window.frame = document.createElement('iframe'); window.frame.src='/frame-redirect'; document.body.append(window.frame)",
70
+ );
71
+ const [frameRedirect] = await redirected;
72
+ assert.equal(frameRedirect.isMainFrame, false);
73
+ assert.equal(frameRedirect.defaultPrevented, false);
74
+ assert.equal(opened.length, 0);
75
+ await contents.executeJavaScript("window.frame.remove()");
76
+
77
+ console.log("stage: popup");
78
+ let external = once(events, "external");
79
+ assert.equal(
80
+ await contents.executeJavaScript(
81
+ `
82
+ window.connection = window.open('about:blank', '_blank');
83
+ if (window.connection) {
84
+ window.connection.opener = null;
85
+ window.connection.document.body.textContent = 'Opening connection setup';
86
+ window.connection.location.replace('https://provider.example.test/authorize');
87
+ }
88
+ Boolean(window.connection);
89
+ `,
90
+ true,
91
+ ),
92
+ true,
93
+ );
94
+ assert.deepEqual(await external, ["https://provider.example.test/authorize"]);
95
+ await new Promise(setImmediate);
96
+ assert.equal(BrowserWindow.getAllWindows().length, 1);
97
+
98
+ external = once(events, "external");
99
+ await contents.executeJavaScript(
100
+ "window.location.assign('https://billing.example.test/checkout')",
101
+ true,
102
+ );
103
+ assert.deepEqual(await external, ["https://billing.example.test/checkout"]);
104
+ assert.equal(new URL(contents.getURL()).origin, origin);
105
+
106
+ const blocked = once(contents, "will-navigate");
107
+ await contents.executeJavaScript(
108
+ "window.location.assign('http://untrusted.example.test/')",
109
+ true,
110
+ );
111
+ assert.equal((await blocked)[0].defaultPrevented, true);
112
+ assert.equal(opened.length, 2);
113
+ assert.equal(
114
+ await contents.executeJavaScript(
115
+ "window.open('file:///tmp/not-allowed')===null",
116
+ true,
117
+ ),
118
+ true,
119
+ );
120
+
121
+ const failed = once(events, "dialog");
122
+ const closed = new Promise((resolve) =>
123
+ app.once("browser-window-created", (_event, popup) =>
124
+ popup.once("closed", resolve),
125
+ ),
126
+ );
127
+ await contents.executeJavaScript(
128
+ "window.failed = window.open('about:blank'); window.failed.location.replace('https://broken.example.test/')",
129
+ true,
130
+ );
131
+ await Promise.all([failed, closed]);
132
+ assert.equal(BrowserWindow.getAllWindows().length, 1);
133
+ assert.deepEqual(dialogs, ["Could not open your browser. Please try again."]);
134
+
135
+ console.log("stage: same-origin");
136
+ let loaded = once(contents, "did-finish-load");
137
+ void contents
138
+ .executeJavaScript(
139
+ `window.location.assign(${JSON.stringify(origin + "/login?returnTo=%2Fdashboard")})`,
140
+ true,
141
+ )
142
+ .catch(() => {});
143
+ await loaded;
144
+ console.log("stage: callback");
145
+ loaded = once(contents, "did-finish-load");
146
+ app.emit(
147
+ "open-url",
148
+ { preventDefault() {} },
149
+ `disposabl-desktop-${id}://login?convexAuthCode=one-time-ticket`,
150
+ );
151
+ await loaded;
152
+ const returned = new URL(contents.getURL());
153
+ assert.equal(returned.origin, origin);
154
+ assert.equal(returned.pathname, "/login");
155
+ assert.equal(returned.searchParams.get("returnTo"), "/dashboard");
156
+ assert.equal(returned.searchParams.get("convexAuthCode"), "one-time-ticket");
157
+ assert.equal(
158
+ await contents.executeJavaScript("localStorage.getItem('flow-fixture')"),
159
+ "private-initiator-state",
160
+ );
161
+ const before = contents.getURL();
162
+ app.emit(
163
+ "open-url",
164
+ { preventDefault() {} },
165
+ "disposabl-desktop-other://login?convexAuthCode=wrong-app",
166
+ );
167
+ assert.equal(contents.getURL(), before);
168
+
169
+ loaded = once(contents, "did-finish-load");
170
+ app.emit("second-instance", {}, [
171
+ "app",
172
+ `disposabl-desktop-${id}://login?convexAuthCode=second-instance-ticket`,
173
+ ]);
174
+ await loaded;
175
+ assert.equal(
176
+ new URL(contents.getURL()).searchParams.get("convexAuthCode"),
177
+ "second-instance-ticket",
178
+ );
179
+
180
+ if (process.platform === "darwin") {
181
+ const closedMain = once(window, "closed");
182
+ window.close();
183
+ await closedMain;
184
+ assert.equal(BrowserWindow.getAllWindows().length, 0);
185
+ const reopened = new Promise((resolve) =>
186
+ app.once("browser-window-created", (_event, replacement) => {
187
+ replacement.hide();
188
+ replacement.webContents.on("did-finish-load", () => {
189
+ if (
190
+ new URL(replacement.webContents.getURL()).searchParams.get(
191
+ "convexAuthCode",
192
+ ) === "reopened-ticket"
193
+ )
194
+ resolve(replacement);
195
+ });
196
+ }),
197
+ );
198
+ app.emit(
199
+ "open-url",
200
+ { preventDefault() {} },
201
+ `disposabl-desktop-${id}://login?convexAuthCode=reopened-ticket`,
202
+ );
203
+ const replacement = await reopened;
204
+ assert.equal(BrowserWindow.getAllWindows().length, 1);
205
+ assert.equal(
206
+ await replacement.webContents.executeJavaScript(
207
+ "localStorage.getItem('flow-fixture')",
208
+ ),
209
+ "private-initiator-state",
210
+ );
211
+ }
212
+ assert.equal(dialogs.length, 1);
213
+ console.log("DESKTOP_NAVIGATION_PASSED");
214
+ clearTimeout(timeout);
215
+ app.exit(0);
216
+ })().catch((error) => {
217
+ console.error(error);
218
+ app.exit(1);
219
+ });
@@ -0,0 +1,88 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {
4
+ desktopAuthCallback,
5
+ desktopAuthRedirect,
6
+ desktopAuthScheme,
7
+ } from "../disposabl-kit/lib/desktop-auth";
8
+ import { externalUrl } from "../../apps/desktop/src/navigation";
9
+
10
+ const id = "a".repeat(32);
11
+ const scheme = desktopAuthScheme(id)!;
12
+ test("desktop OAuth returns a ticket only to the app identity", () => {
13
+ const response = desktopAuthRedirect(
14
+ new Request(
15
+ "https://app.test/oauth/desktop?convexAuthCode=ticket&redirectTo=https://evil.test",
16
+ ),
17
+ id,
18
+ );
19
+ assert.equal(response.status, 302);
20
+ assert.equal(response.headers.get("cache-control"), "no-store");
21
+ assert.equal(response.headers.get("referrer-policy"), "no-referrer");
22
+ assert.equal(
23
+ response.headers.get("location"),
24
+ `${scheme}://login?convexAuthCode=ticket`,
25
+ );
26
+ assert.equal(
27
+ desktopAuthCallback(
28
+ response.headers.get("location")!,
29
+ id,
30
+ "https://app.test/login?returnTo=%2Fdashboard",
31
+ ),
32
+ "https://app.test/login?returnTo=%2Fdashboard&convexAuthCode=ticket",
33
+ );
34
+ for (const query of [
35
+ "",
36
+ "convexAuthCode=",
37
+ "convexAuthCode=a&convexAuthCode=b",
38
+ "convexAuthCode=a&convexAuthError=x",
39
+ `convexAuthCode=${"x".repeat(4097)}`,
40
+ ]) {
41
+ assert.equal(
42
+ desktopAuthRedirect(
43
+ new Request(`https://app.test/oauth/desktop?${query}`),
44
+ id,
45
+ ).status,
46
+ 400,
47
+ );
48
+ assert.equal(
49
+ desktopAuthCallback(`${scheme}://login?${query}`, id, "https://app.test"),
50
+ null,
51
+ );
52
+ }
53
+ for (const input of [
54
+ "https://evil.test/?convexAuthCode=t",
55
+ `${scheme}://other?convexAuthCode=t`,
56
+ `${scheme}://login/path?convexAuthCode=t`,
57
+ `${scheme}://user@login?convexAuthCode=t`,
58
+ `${scheme}://login?convexAuthCode=t#extra`,
59
+ `${desktopAuthScheme("b".repeat(32))}://login?convexAuthCode=t`,
60
+ ])
61
+ assert.equal(desktopAuthCallback(input, id, "https://app.test"), null);
62
+ assert.equal(desktopAuthScheme("../other"), null);
63
+ assert.equal(
64
+ desktopAuthCallback(
65
+ `${scheme}://login?convexAuthError=unknown`,
66
+ id,
67
+ "https://app.test",
68
+ ),
69
+ "https://app.test/?convexAuthError=oauth_error",
70
+ );
71
+ });
72
+
73
+ test("desktop external links allow HTTPS but never credentials or native protocols", () => {
74
+ assert.equal(
75
+ externalUrl("https://example.test/a?q=b#c"),
76
+ "https://example.test/a?q=b#c",
77
+ );
78
+ for (const url of [
79
+ "file:///tmp/example",
80
+ "javascript:alert(1)",
81
+ "data:text/html,test",
82
+ "http://example.test",
83
+ "https://user:secret@example.test",
84
+ "ms-settings:privacy",
85
+ "not a URL",
86
+ ])
87
+ assert.equal(externalUrl(url), null);
88
+ });
@@ -0,0 +1,125 @@
1
+ import { test, expect } from "e2e";
2
+ import { createServer } from "node:http";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { existsSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { spawn, execFileSync } from "node:child_process";
8
+ import { root } from "../project";
9
+
10
+ test(
11
+ "desktop preserves its window and OAuth state across browser handoffs",
12
+ { platforms: ["backend"] },
13
+ async () => {
14
+ test.skip(
15
+ process.env.E2E_DESKTOP_NAVIGATION !== "1",
16
+ "Explicit local Electron verification only",
17
+ );
18
+ if (!existsSync(join(root, "apps/desktop/src/main.ts")))
19
+ throw new Error("Desktop is not selected");
20
+ const build = await mkdtemp(
21
+ join(tmpdir(), "disposabl-desktop-navigation-"),
22
+ );
23
+ const server = createServer((request, response) => {
24
+ if (request.url === "/frame-redirect") {
25
+ const address = server.address();
26
+ if (!address || typeof address === "string")
27
+ throw new Error("Missing fixture port");
28
+ response.writeHead(302, {
29
+ Location: `http://localhost:${address.port}/frame-arrived`,
30
+ });
31
+ response.end();
32
+ return;
33
+ }
34
+ response.setHeader("Content-Type", "text/html");
35
+ response.setHeader(
36
+ "Content-Security-Policy",
37
+ "default-src 'self'; script-src 'none'; frame-src 'self' http://localhost:*",
38
+ );
39
+ response.end(
40
+ "<!doctype html><title>Desktop navigation fixture</title><main>Local fixture</main>",
41
+ );
42
+ });
43
+ await new Promise<void>((resolve) =>
44
+ server.listen(0, "127.0.0.1", resolve),
45
+ );
46
+ try {
47
+ const address = server.address();
48
+ if (!address || typeof address === "string")
49
+ throw new Error("Fixture failed to listen");
50
+ const origin = `http://127.0.0.1:${address.port}`;
51
+ const id = "c".repeat(32);
52
+ const define = {
53
+ __dirname: build,
54
+ DISPOSABL_WEB_URL: origin,
55
+ DISPOSABL_DESKTOP_ID: id,
56
+ DISPOSABL_UPDATE_URL: "",
57
+ DISPOSABL_UPDATE_CHANNEL: "test",
58
+ MAIN_WINDOW_VITE_DEV_SERVER_URL: "",
59
+ MAIN_WINDOW_VITE_NAME: "main_window",
60
+ };
61
+ execFileSync(
62
+ "bun",
63
+ [
64
+ "build",
65
+ "apps/desktop/src/main.ts",
66
+ "apps/desktop/src/preload.ts",
67
+ "--target=node",
68
+ "--format=cjs",
69
+ `--outdir=${build}`,
70
+ "--entry-naming=[name].cjs",
71
+ "--external=electron",
72
+ ...Object.entries(define).map(
73
+ ([key, value]) => `--define=${key}=${JSON.stringify(value)}`,
74
+ ),
75
+ ],
76
+ { cwd: root },
77
+ );
78
+ const electron = execFileSync(
79
+ process.execPath,
80
+ ["-e", 'console.log(require("electron"))'],
81
+ { cwd: root, encoding: "utf8" },
82
+ ).trim();
83
+ const env = { ...process.env };
84
+ delete env.ELECTRON_RUN_AS_NODE;
85
+ for (const extra of [
86
+ [],
87
+ [`disposabl-desktop-${id}://login?convexAuthCode=cold-ticket`],
88
+ ]) {
89
+ const child = spawn(
90
+ electron,
91
+ [
92
+ join(root, "packages/tests/components/desktop-navigation.cjs"),
93
+ build,
94
+ origin,
95
+ id,
96
+ ...extra,
97
+ ],
98
+ {
99
+ cwd: root,
100
+ env,
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ timeout: 30_000,
103
+ },
104
+ );
105
+ let output = "";
106
+ child.stdout.on("data", (chunk) => {
107
+ output += chunk;
108
+ });
109
+ child.stderr.on("data", (chunk) => {
110
+ output += chunk;
111
+ });
112
+ const code = await new Promise<number | null>((resolve, reject) => {
113
+ child.once("error", reject);
114
+ child.once("exit", resolve);
115
+ });
116
+ if (code !== 0) throw new Error(output);
117
+ expect(output.includes("DESKTOP_NAVIGATION_PASSED")).toBe(true);
118
+ }
119
+ } finally {
120
+ server.closeAllConnections();
121
+ await new Promise<void>((resolve) => server.close(() => resolve()));
122
+ await rm(build, { recursive: true, force: true });
123
+ }
124
+ },
125
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-disposabl-app",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Create a Disposabl app",
5
5
  "type": "module",
6
6
  "license": "MIT",