create-disposabl-app 0.13.4 → 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.
Files changed (26) hide show
  1. package/dist/disposabl.js +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/templates/default/.github/workflows/pipeline.yml +16 -3
  4. package/dist/templates/default/apps/desktop/README.md +8 -0
  5. package/dist/templates/default/apps/desktop/forge.config.mts +12 -1
  6. package/dist/templates/default/apps/desktop/src/main.ts +88 -9
  7. package/dist/templates/default/apps/desktop/src/navigation.ts +74 -0
  8. package/dist/templates/default/apps/desktop/src/preload.ts +4 -3
  9. package/dist/templates/default/packages/backend/convex/billing.ts +1 -0
  10. package/dist/templates/default/packages/backend/package.json +1 -1
  11. package/dist/templates/default/packages/disposabl-kit/PAYMENTS.md +25 -5
  12. package/dist/templates/default/packages/disposabl-kit/client/components/google-sign-in.tsx +22 -1
  13. package/dist/templates/default/packages/disposabl-kit/lib/desktop-auth.ts +73 -0
  14. package/dist/templates/default/packages/disposabl-kit/payments/config.ts +1 -1
  15. package/dist/templates/default/packages/disposabl-kit/server/billing-functions.ts +12 -1
  16. package/dist/templates/default/packages/disposabl-kit/server/billing-setup.ts +125 -0
  17. package/dist/templates/default/packages/disposabl-kit/server/billing.ts +2 -0
  18. package/dist/templates/default/packages/disposabl-kit/server/http.ts +16 -0
  19. package/dist/templates/default/packages/tests/README.md +2 -0
  20. package/dist/templates/default/packages/tests/android-failure-workflow.test.ts +42 -0
  21. package/dist/templates/default/packages/tests/billing-setup-hooks.test.ts +91 -0
  22. package/dist/templates/default/packages/tests/billing-setup.test.ts +292 -0
  23. package/dist/templates/default/packages/tests/components/desktop-navigation.cjs +219 -0
  24. package/dist/templates/default/packages/tests/desktop-auth.test.ts +88 -0
  25. package/dist/templates/default/packages/tests/flows/desktop-navigation.e2e.ts +125 -0
  26. package/package.json +1 -1
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.13.4",
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.13.4";
11
+ var version = "0.14.1";
12
12
 
13
13
  // ../disposabl-kit/platforms.ts
14
14
  var platforms = [
@@ -131,6 +131,9 @@ jobs:
131
131
  target=()
132
132
  if [[ "$CHANNEL" != production ]]; then export AUTH_TARGET="--preview-name $CHANNEL"; target=(--preview-name "$CHANNEL"); fi
133
133
  bun x --no-install convex deploy --yes "${target[@]}" --cmd-url-env-var-name CONVEX_URL --cmd 'for name in CONVEX_URL CONVEX_SITE_URL; do value=$(printenv "$name"); test -n "$value" || exit 1; for prefix in "" VITE_ EXPO_PUBLIC_; do export "$prefix$name=$value"; printf "%s=%s\n" "$prefix$name" "$value" | tee -a "$GITHUB_ENV" >> "$GITHUB_OUTPUT"; done; done; bun run --cwd ../.. build --filter=@disposabl/web'
134
+ setup_target=(--prod)
135
+ if [[ "$CHANNEL" != production ]]; then setup_target=("${target[@]}"); fi
136
+ bun x --no-install convex run "${setup_target[@]}" billing:setup '{}'
134
137
  bun x --no-install static-hosting upload $AUTH_TARGET --no-spa --dist ../../apps/web/dist/client
135
138
  - name: Report web result
136
139
  if: always()
@@ -224,9 +227,19 @@ jobs:
224
227
  run: bash "$GITHUB_WORKSPACE/.github/scripts/mobile.sh" android-build
225
228
  - *publish
226
229
  - *artifacts
227
- - name: Report Android failure
228
- if: failure() || cancelled()
229
- run: node .github/scripts/disposabl.mjs report android failed
230
+ android-failure:
231
+ name: Report Android failure
232
+ needs: android
233
+ if: failure() && needs.android.result == 'failure'
234
+ permissions:
235
+ contents: read
236
+ id-token: write
237
+ runs-on: *linux-runner
238
+ timeout-minutes: 5
239
+ steps:
240
+ - *checkout
241
+ - *node
242
+ - run: node .github/scripts/disposabl.mjs report android failed
230
243
  ios-preview:
231
244
  name: iOS simulator preview
232
245
  needs: [changes, web]
@@ -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 });
@@ -1,4 +1,5 @@
1
1
  export {
2
+ setup,
2
3
  snapshot,
3
4
  checkout,
4
5
  portal,
@@ -5,7 +5,7 @@
5
5
  "scripts": {
6
6
  "generate": "bun generate.ts",
7
7
  "generate:watch": "bun generate.ts --watch",
8
- "dev": "convex dev",
8
+ "dev": "convex dev --run billing:setup",
9
9
  "logs": "convex logs",
10
10
  "typecheck": "tsc -p convex",
11
11
  "lint": "eslint . --report-unused-disable-directives --max-warnings 0",
@@ -2,9 +2,27 @@
2
2
 
3
3
  Payments is optional and includes authentication. Select `payments` in `disposabl.json`; the server checks this selection before reading credentials or calling Autumn. With it off, the pricing page blocks purchases and no billing credentials are needed. The authenticated Convex Auth user ID is the Autumn customer ID. Never use a client-supplied customer ID or price.
4
4
 
5
- Set the Autumn environment default currency to match `payments/config.ts` (USD by default) and verify both prices in the provider preview. For a separate Autumn test environment, configure `AUTUMN_SECRET_KEY` and `BILLING_RETURN_URL` on that app's Convex deployment. The latter must be the absolute HTTPS URL of its `/pricing` page (HTTP localhost is allowed for development), without query or fragment. Do not store the secret in the frontend or `disposabl.json`. Set the corresponding live values separately only when ready to launch.
5
+ Before first setup, the **Autumn organization's default currency must match `pricing.currency`** in `payments/config.ts`, USD in the starter. Base price amounts use that organization currency; the create-plan request does not select a currency. Setup neither changes nor verifies the organization currency. Autumn `accounts.get` describes a customer group, not the organization, and cannot verify this prerequisite. Check the organization settings and both prices in Autumn before accepting purchases.
6
6
 
7
- `payments/autumn.config.example` defines the `credits` consumable feature, $5 monthly plan with 500 credits per cycle, and $5 one-off prepaid top-up for 500 credits. The editable defaults live in `payments/config.ts`; checkout quantities, the web pricing page, mobile allowance text, and the Autumn example use this same configuration. Copy both files into a separate configuration project with `atmn@2.0.218` installed, naming the example `autumn.config.ts` and keeping `config.ts` alongside it. After editing prices or credits, apply the matching Autumn and store configuration before deploying the app. Changing the local file alone does not update provider prices. Preview with `atmn push` before applying to a dedicated Autumn environment. Its lists are complete: a push can delete unlisted plans and features. Review the diff and test repeated top-ups, renewals and cancellation in sandbox before taking payment. The one-off prepaid credits are documented to last forever; subscription credits reset each cycle. Autumn's docs do not establish that subscription credits survive cancellation. Do not promise that they do. The provider balance is authoritative; a redirect alone does not grant credits. This foundation does not implement usage charging.
7
+ Configure `AUTUMN_SECRET_KEY` and `BILLING_RETURN_URL` on this app's Convex deployment. The return URL is needed for checkout, not catalog setup; it must be the absolute HTTPS URL of the app's `/pricing` page, without query or fragment. HTTP localhost is allowed for development. Use sandbox credentials for development and preview deployments and configure live credentials separately when ready to launch. Never store the secret in the frontend or `disposabl.json`.
8
+
9
+ ## Catalog initialization
10
+
11
+ `payments/config.ts` is the editable source for plan IDs, prices, credits and currency. The default catalog has a consumable `credits` feature, a $5 monthly plan with 500 included credits resetting each month, and a $5 prepaid top-up with `billing_units: 500` and `interval: "one_off"`. Top-ups have no reset or expiry configuration. Web checkout sends exactly that credit quantity. The web pricing page, mobile allowance text and optional Autumn configuration example use the same source.
12
+
13
+ The internal Convex action `billing:setup` takes `{}` and returns `{ enabled, created, preserved }`. It is re-exported by both the app backend and starter backend. With payments disabled, it returns before reading credentials or calling Autumn. When enabled without `AUTUMN_SECRET_KEY`, it fails with a setup message identifying the missing deployment credential. Customer checkout never initializes the catalog.
14
+
15
+ Setup uses the existing REST helper with API version `2.6.0`. It reads `features.list` and `plans.list` with `include_archived` and `all_versions`, validates both responses, then creates only missing configured IDs through `features.create` and `plans.create`. There are at most two reads and three creates per invocation. It never updates, deletes, archives or reactivates entries. Existing custom prices, credit definitions, archived plans and unrelated entries remain untouched. A preserved entry means its ID already exists, not that its pricing or usability matches the app. Review existing entries manually.
16
+
17
+ Any read error, including unauthorized or 404, stops setup without writes. A failed or uncertain create stops the invocation without an automatic retry. Rerun setup after checking the provider: the next run reads provider state and resumes from entries already created. Concurrent runs may collide and one may fail; rerunning preserves the winning entries. There is no cross-provider transaction, rollback or automatic reconciliation.
18
+
19
+ `bun run dev` starts the backend with `convex dev --run billing:setup`. The installed Convex CLI runs it after the first successful push in each dev process, against that same selected deployment. CI runs setup after `convex deploy` succeeds and before the web upload, using the same preview name or an explicit production target and the existing deploy key. Setup failure prevents that upload but does not undo the backend deploy. No new deployment selection or credentials are introduced.
20
+
21
+ For a manual retry, run from `packages/backend` with an explicit target: `bun x --no-install convex run --preview-name <channel> billing:setup '{}'` for the existing preview, or `bun x --no-install convex run --prod billing:setup '{}'` for production. For development, restart the existing dev process. Verify the target and its Autumn key first.
22
+
23
+ After editing prices, credits or currency for existing IDs, apply matching changes in Autumn and the native stores before deploying the app. Editing the local file does not update existing provider entries. `payments/autumn.config.example` is an optional manual reference, not an initialization step. If used, copy it and `config.ts` into a separate project with `atmn@2.0.218`, renaming it `autumn.config.ts`. Never automate `atmn push`: its complete catalog lists can delete unlisted plans and features.
24
+
25
+ Autumn documents one-off prepaid credits as nonexpiring; subscription credits reset each cycle. Provider transactions, repeated top-ups, renewals, cancellation and refunds still need sandbox verification. Do not promise subscription credits survive cancellation. The provider balance is authoritative; a redirect alone does not grant credits. This foundation does not implement usage charging.
8
26
 
9
27
  The app calls Autumn API 2.6.0 `customers.get_or_create`, `billing.attach`, and `billing.open_customer_portal` server-side. Checkout uses server-owned plan IDs and the top-up quantity from `payments/config.ts`. Return to pricing may precede provider synchronization; use Refresh to read Autumn again. Setup and test Stripe checkout and portal in Autumn before enabling live use.
10
28
 
@@ -24,10 +42,12 @@ Autumn's integration documentation does not confirm repeatable consumable top-up
24
42
 
25
43
  ## Platform connection and starter packaging
26
44
 
27
- Autumn's Platform API is private preview; its documented OAuth connects Stripe to a managed Autumn organization, not an existing Autumn account to Disposabl. Disposabl Connections accepts an encrypted sandbox key and an optional live key. It verifies each through the read-only `plans.list` endpoint. Payments selection requires this connection; other apps remain unblocked. Generator setup installs the sandbox key only on the named development backend, and the live key only on production when supplied. The platform billing key is never copied. Setup initializes `BILLING_RETURN_URL` only when absent, using that deployment's `/pricing` page; change it to your verified custom web origin if needed. Plan catalogs are not changed automatically. Configure and test both plans in each Autumn environment. Disconnecting or omitting a live key does not revoke credentials previously installed on an app; rotate those in Autumn and update each app explicitly.
45
+ Autumn's Platform API is private preview; its documented OAuth connects Stripe to a managed Autumn organization, not an existing Autumn account to Disposabl. Disposabl Connections accepts an encrypted sandbox key and an optional live key. It verifies each through the read-only `plans.list` endpoint. Payments selection requires this connection; other apps remain unblocked. Generator setup installs the sandbox key only on the named development backend, and the live key only on production when supplied. The platform billing key is never copied. Setup initializes `BILLING_RETURN_URL` only when absent, using that deployment's `/pricing` page; change it to your verified custom web origin if needed. Provisioning only installs credentials and the return URL. The deployed app initializes missing catalog entries from its own config through `billing:setup`. Verify both plans in each Autumn environment. Disconnecting or omitting a live key does not revoke credentials previously installed on an app; rotate those in Autumn and update each app explicitly.
46
+
47
+ The parent `reset.ts` replaces backend functions from `starter/backend`; both backends re-export the billing functions, including internal setup. The generated package retains the kit, editable payment config and backend dev hook. Both Convex configs declare the optional billing variables. Regenerate API types after backend functions change. Do not copy any parent credentials.
28
48
 
29
- The parent `reset.ts` removes backend functions before copying `starter/backend`; this patch adds the thin billing wrapper to both places and declares the optional variables in both Convex configs. Preserve the `autumn/` config and kit files when packaging, and regenerate the generated API types after backend functions change. Do not copy any parent credentials.
49
+ Catalog contracts were checked against the official API 2.6.0 docs and `autumn-js` 1.5.64 schemas; no SDK dependency is added. The get endpoints do not specify missing-resource error codes, so initialization uses complete list responses instead.
30
50
 
31
- Provider references: [API attach](https://docs.useautumn.com/api-reference/billing/attach), [customer](https://docs.useautumn.com/api-reference/customers/getOrCreateCustomer), [portal](https://docs.useautumn.com/api-reference/billing/openCustomerPortal), [prepaid top-ups](https://docs.useautumn.com/examples/prepaid), [pricing config](https://docs.useautumn.com/cli/config), [RevenueCat](https://docs.useautumn.com/documentation/external-providers/revenuecat), [Platform API](https://docs.useautumn.com/api-reference/platform/overview).
51
+ Provider references: [create plan](https://docs.useautumn.com/api-reference/plans/createPlan), [get plan](https://docs.useautumn.com/api-reference/plans/getPlan), [list plans](https://docs.useautumn.com/api-reference/plans/listPlans), [create feature](https://docs.useautumn.com/api-reference/features/createFeature), [get feature](https://docs.useautumn.com/api-reference/features/getFeature), [list features](https://docs.useautumn.com/api-reference/features/listFeatures), [API attach](https://docs.useautumn.com/api-reference/billing/attach), [customer](https://docs.useautumn.com/api-reference/customers/getOrCreateCustomer), [portal](https://docs.useautumn.com/api-reference/billing/openCustomerPortal), [prepaid top-ups](https://docs.useautumn.com/examples/prepaid), [pricing config](https://docs.useautumn.com/cli/config), [RevenueCat](https://docs.useautumn.com/documentation/external-providers/revenuecat), [Platform API](https://docs.useautumn.com/api-reference/platform/overview).
32
52
 
33
53
  Native SDK is pinned to `react-native-purchases` 10.16.0 because its required `PurchasesHybridCommon` 19.17.0 is published in CocoaPods. At verification on 2026-11-07, npm 11.0.1 required 20.4.0, which was absent from the CocoaPods specs repository. Upgrade only after both native dependency graphs resolve and installed builds pass.
@@ -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
+ }
@@ -6,7 +6,7 @@ export type Pricing = {
6
6
  topup: { planId: string; price: number };
7
7
  };
8
8
 
9
- /** Editable starter example. Apply matching changes to Autumn before accepting purchases. */
9
+ /** Setup creates missing entries. Apply matching changes to existing Autumn plans manually. */
10
10
  export const pricing: Pricing = {
11
11
  currency: "USD",
12
12
  creditsPerDollar: 100,
@@ -1,8 +1,9 @@
1
1
  import type { Auth } from "convex/server";
2
- import { getSessionUserId } from "./lib/functions";
2
+ import { getSessionUserId, internalAction } from "./lib/functions";
3
3
  import { v } from "convex/values";
4
4
  import { action } from "../../backend/convex/_generated/server";
5
5
  import { paymentsEnabled } from "../features";
6
+ import { setupBilling } from "./billing-setup";
6
7
  import {
7
8
  balanceFromCustomer,
8
9
  monthlyPlanFromCustomer,
@@ -11,6 +12,16 @@ import {
11
12
  purchaseRequest,
12
13
  } from "./billing";
13
14
 
15
+ export const setup = internalAction({
16
+ args: {},
17
+ returns: v.object({
18
+ enabled: v.boolean(),
19
+ created: v.array(v.string()),
20
+ preserved: v.array(v.string()),
21
+ }),
22
+ handler: async () => setupBilling(paymentsEnabled, process.env),
23
+ });
24
+
14
25
  async function context(ctx: { auth: Auth }) {
15
26
  return billingContext(paymentsEnabled, process.env, () =>
16
27
  getSessionUserId(ctx),