create-disposabl-app 0.6.8 → 0.7.0

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 (58) hide show
  1. package/dist/disposabl.js +32 -8
  2. package/dist/index.js +16 -6
  3. package/dist/templates/default/.github/scripts/mobile.sh +123 -0
  4. package/dist/templates/default/.github/scripts/release.sh +83 -0
  5. package/dist/templates/default/.github/workflows/pipeline.yml +22 -14
  6. package/dist/templates/default/AGENTS.md +2 -1
  7. package/dist/templates/default/apps/mobile/gitignore +43 -0
  8. package/dist/templates/default/apps/web/src/routeTree.gen.ts +23 -0
  9. package/dist/templates/default/apps/web/src/router/_authenticated/dashboard.connections.tsx +354 -0
  10. package/dist/templates/default/apps/web/src/router/_authenticated/dashboard.tsx +1 -0
  11. package/dist/templates/default/packages/backend/AGENTS.md +2 -1
  12. package/dist/templates/default/packages/backend/README.md +4 -2
  13. package/dist/templates/default/packages/backend/convex/_generated/api.d.ts +14 -0
  14. package/dist/templates/default/packages/backend/convex/_generated/server.d.ts +5 -5
  15. package/dist/templates/default/packages/backend/convex/apps/actions/create.ts +11 -13
  16. package/dist/templates/default/packages/backend/convex/apps/actions/setup.ts +21 -7
  17. package/dist/templates/default/packages/backend/convex/apps/internal.ts +1 -6
  18. package/dist/templates/default/packages/backend/convex/connections/actions/credentials.ts +56 -0
  19. package/dist/templates/default/packages/backend/convex/connections/actions/expo.ts +79 -0
  20. package/dist/templates/default/packages/backend/convex/connections/actions/github.ts +120 -0
  21. package/dist/templates/default/packages/backend/convex/connections/actions/oauth.ts +128 -0
  22. package/dist/templates/default/packages/backend/convex/connections/index.ts +80 -0
  23. package/dist/templates/default/packages/backend/convex/connections/internal.ts +148 -0
  24. package/dist/templates/default/packages/backend/convex/connections/validator.ts +35 -0
  25. package/dist/templates/default/packages/backend/convex/convex.config.ts +5 -5
  26. package/dist/templates/default/packages/backend/convex/github/actions/provision.ts +2 -6
  27. package/dist/templates/default/packages/backend/convex/github/actions/secrets.ts +25 -11
  28. package/dist/templates/default/packages/backend/convex/github/actions/tokens.ts +19 -15
  29. package/dist/templates/default/packages/backend/convex/github/internal.ts +6 -8
  30. package/dist/templates/default/packages/backend/convex/previews/token/actions/create.ts +4 -3
  31. package/dist/templates/default/packages/backend/convex/previews/token/internal.ts +28 -1
  32. package/dist/templates/default/packages/backend/convex/schema.ts +17 -1
  33. package/dist/templates/default/packages/backend/generated/openapi.json +123 -1
  34. package/dist/templates/default/packages/backend/generated/pages.json +4 -0
  35. package/dist/templates/default/packages/backend/generated/platforms.ts +12 -10
  36. package/dist/templates/default/packages/backend/gitignore +16 -0
  37. package/dist/templates/default/packages/cli/auth.ts +15 -17
  38. package/dist/templates/default/packages/cli/commands.ts +31 -1
  39. package/dist/templates/default/packages/disposabl-kit/client/components/logo.tsx +5 -0
  40. package/dist/templates/default/packages/disposabl-kit/client/routes/_auth-pages/login.tsx +118 -84
  41. package/dist/templates/default/packages/disposabl-kit/client/routes/_auth-pages/signUp.tsx +127 -89
  42. package/dist/templates/default/packages/disposabl-kit/client/routes/route.tsx +2 -5
  43. package/dist/templates/default/packages/sdk/src/generated/index.ts +5 -0
  44. package/dist/templates/default/packages/sdk/src/generated/sdk.gen.ts +20 -0
  45. package/dist/templates/default/packages/sdk/src/generated/types.gen.ts +53 -0
  46. package/package.json +1 -1
  47. package/dist/templates/default/.github/scripts/android-build.sh +0 -27
  48. package/dist/templates/default/.github/scripts/expo-channel.sh +0 -10
  49. package/dist/templates/default/.github/scripts/expo-env.sh +0 -37
  50. package/dist/templates/default/.github/scripts/expo-fingerprint.sh +0 -31
  51. package/dist/templates/default/.github/scripts/expo-update.sh +0 -13
  52. package/dist/templates/default/.github/scripts/package-release.sh +0 -23
  53. package/dist/templates/default/.github/scripts/release-publish.sh +0 -28
  54. package/dist/templates/default/.github/scripts/release-source.sh +0 -14
  55. package/dist/templates/default/.github/scripts/verify-artifacts.sh +0 -13
  56. package/dist/templates/default/.github/scripts/web-deploy.sh +0 -10
  57. package/dist/templates/default/apps/mobile/.env.example +0 -2
  58. package/dist/templates/default/apps/web/.env.example +0 -3
@@ -0,0 +1,354 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { createFileRoute, Link } from "@tanstack/react-router";
3
+ import { useAction, useMutation, useQuery } from "convex/react";
4
+ import { ConvexError } from "convex/values";
5
+ import { api } from "../../../../../packages/backend/convex/_generated/api";
6
+ import { Button } from "@disposabl/disposabl-kit/client/components/ui/button";
7
+ import { Input } from "@disposabl/disposabl-kit/client/components/ui/input";
8
+
9
+ export const Route = createFileRoute(
10
+ "/_providers/_authenticated/dashboard/connections",
11
+ )({ component: Connections });
12
+ type Installation = { installationId: string; owner: string };
13
+
14
+ function Connections() {
15
+ const status = useQuery(api.connections.index.status, {});
16
+ const start = useAction(api.connections.index.start);
17
+ const complete = useAction(api.connections.index.complete);
18
+ const selectGithub = useAction(api.connections.index.selectGithub);
19
+ const expoAccounts = useAction(api.connections.index.expoAccounts);
20
+ const connectExpo = useAction(api.connections.index.connectExpo);
21
+ const disconnect = useMutation(api.connections.index.disconnect);
22
+ const [busy, setBusy] = useState(false);
23
+ const [error, setError] = useState<string>();
24
+ const [installations, setInstallations] = useState<Installation[]>([]);
25
+ const [proof, setProof] = useState<string>();
26
+ const [installNeeded, setInstallNeeded] = useState(false);
27
+ const [returnedFromInstall, setReturnedFromInstall] = useState(false);
28
+ const [token, setToken] = useState("");
29
+ const [showExpo, setShowExpo] = useState(false);
30
+ const [accounts, setAccounts] = useState<Array<{ id: string; name: string }>>(
31
+ [],
32
+ );
33
+ const [accountId, setAccountId] = useState("");
34
+ const consumed = useRef(false);
35
+ const fail = (cause: unknown) =>
36
+ setError(
37
+ cause instanceof ConvexError && typeof cause.data === "string"
38
+ ? cause.data
39
+ : cause instanceof Error
40
+ ? cause.message
41
+ : "Something went wrong. Please try again.",
42
+ );
43
+
44
+ useEffect(() => {
45
+ if (consumed.current) return;
46
+ consumed.current = true;
47
+ const url = new URL(window.location.href);
48
+ const provider = url.searchParams.get("provider");
49
+ const code = url.searchParams.get("code");
50
+ const state = url.searchParams.get("state");
51
+ const denial = url.searchParams.get("error");
52
+ if (url.searchParams.has("installation_id")) setReturnedFromInstall(true);
53
+ for (const key of [
54
+ "provider",
55
+ "code",
56
+ "state",
57
+ "error",
58
+ "error_description",
59
+ "installation_id",
60
+ "setup_action",
61
+ ])
62
+ url.searchParams.delete(key);
63
+ window.history.replaceState(window.history.state, "", url.toString());
64
+ if (denial) {
65
+ setError("Authorization was cancelled or denied. Please try again.");
66
+ return;
67
+ }
68
+ if ((provider !== "github" && provider !== "convex") || !code || !state)
69
+ return;
70
+ setBusy(true);
71
+ void complete({ provider, code, state })
72
+ .then((result) => {
73
+ if (provider === "github") {
74
+ setInstallations(result.installations);
75
+ setProof(result.proof);
76
+ setInstallNeeded(result.installations.length === 0);
77
+ }
78
+ })
79
+ .catch(fail)
80
+ .finally(() => setBusy(false));
81
+ }, [complete]);
82
+
83
+ async function run(action: () => Promise<void>) {
84
+ if (busy) return;
85
+ setBusy(true);
86
+ setError(undefined);
87
+ try {
88
+ await action();
89
+ } catch (cause) {
90
+ fail(cause);
91
+ } finally {
92
+ setBusy(false);
93
+ }
94
+ }
95
+ const providers = [
96
+ { id: "github", name: "GitHub", description: "Code and releases" },
97
+ {
98
+ id: "convex",
99
+ name: "Convex",
100
+ description: "Backend and data",
101
+ },
102
+ { id: "expo", name: "Expo", description: "Mobile builds and updates" },
103
+ ] as const;
104
+ return (
105
+ <main className="mx-auto max-w-xl space-y-6 px-5 py-10 sm:py-16">
106
+ <header>
107
+ <h1 className="text-2xl font-semibold tracking-tight">Connections</h1>
108
+ </header>
109
+ {error && (
110
+ <p role="alert" className="text-sm text-destructive">
111
+ {error}
112
+ </p>
113
+ )}
114
+ {!status ? (
115
+ <p role="status">Loading…</p>
116
+ ) : (
117
+ <div className="space-y-3">
118
+ {providers.map(({ id, name, description }) => {
119
+ const connected = status[id];
120
+ return (
121
+ <section key={id} className="space-y-4 rounded-xl border p-4">
122
+ <div className="flex items-center justify-between gap-3">
123
+ <div className="min-w-0 space-y-1">
124
+ <h2 className="font-medium">
125
+ {name}{" "}
126
+ <span className="ml-1 text-xs font-normal text-muted-foreground">
127
+ {id === "expo" ? "Optional" : "Required"}
128
+ </span>
129
+ </h2>
130
+ <p className="text-sm text-muted-foreground">
131
+ {connected
132
+ ? "owner" in connected
133
+ ? connected.owner
134
+ : connected.name
135
+ : description}
136
+ </p>
137
+ </div>
138
+ {connected ? (
139
+ <Button
140
+ variant="outline"
141
+ className="min-h-11 shrink-0"
142
+ disabled={busy}
143
+ onClick={() =>
144
+ void run(async () => {
145
+ await disconnect({ provider: id });
146
+ })
147
+ }
148
+ >
149
+ Disconnect
150
+ </Button>
151
+ ) : (
152
+ <Button
153
+ className="min-h-11 shrink-0"
154
+ disabled={busy || !status.available[id]}
155
+ onClick={() => {
156
+ if (id === "expo") {
157
+ setShowExpo(!showExpo);
158
+ return;
159
+ }
160
+ void run(async () => {
161
+ window.location.assign(await start({ provider: id }));
162
+ });
163
+ }}
164
+ >
165
+ {returnedFromInstall && id === "github"
166
+ ? "Continue"
167
+ : id === "expo" && showExpo
168
+ ? "Cancel"
169
+ : "Connect"}
170
+ </Button>
171
+ )}
172
+ </div>
173
+ {!status.available[id] && !connected && (
174
+ <p className="text-xs text-muted-foreground">
175
+ Temporarily unavailable.
176
+ </p>
177
+ )}
178
+ {id === "expo" && !connected && showExpo && (
179
+ <form
180
+ className="space-y-3"
181
+ onSubmit={(event) => {
182
+ event.preventDefault();
183
+ void run(async () => {
184
+ if (!accounts.length) {
185
+ const result = await expoAccounts({ token });
186
+ setAccounts(result);
187
+ setAccountId(result[0]?.id ?? "");
188
+ } else {
189
+ await connectExpo({ token, accountId });
190
+ setToken("");
191
+ setAccounts([]);
192
+ setAccountId("");
193
+ setShowExpo(false);
194
+ }
195
+ });
196
+ }}
197
+ >
198
+ <label className="block space-y-1 text-sm">
199
+ Access token
200
+ <Input
201
+ type="password"
202
+ autoComplete="off"
203
+ required
204
+ value={token}
205
+ onChange={(event) => {
206
+ setToken(event.target.value);
207
+ setAccounts([]);
208
+ setAccountId("");
209
+ }}
210
+ />
211
+ </label>
212
+ <a
213
+ className="inline-block text-xs underline underline-offset-4"
214
+ href="https://expo.dev/settings/access-tokens"
215
+ target="_blank"
216
+ rel="noreferrer"
217
+ >
218
+ Get an Expo token
219
+ </a>
220
+ {accounts.length > 0 && (
221
+ <label className="block space-y-1 text-sm">
222
+ Account
223
+ <select
224
+ className="block min-h-11 w-full rounded-md border bg-background px-3"
225
+ value={accountId}
226
+ onChange={(event) => setAccountId(event.target.value)}
227
+ >
228
+ {accounts.map((account) => (
229
+ <option key={account.id} value={account.id}>
230
+ {account.name}
231
+ </option>
232
+ ))}
233
+ </select>
234
+ </label>
235
+ )}
236
+ <Button
237
+ type="submit"
238
+ className="min-h-11"
239
+ disabled={busy || !token.trim()}
240
+ >
241
+ {accounts.length ? "Save connection" : "Verify token"}
242
+ </Button>
243
+ </form>
244
+ )}
245
+ {id === "github" && installations.length > 0 && (
246
+ <div className="flex flex-wrap gap-2">
247
+ {installations.map((installation) => (
248
+ <Button
249
+ key={installation.installationId}
250
+ variant="outline"
251
+ disabled={busy || !proof}
252
+ onClick={() =>
253
+ void run(async () => {
254
+ if (!proof) return;
255
+ await selectGithub({
256
+ proof,
257
+ installationId: installation.installationId,
258
+ });
259
+ setInstallations([]);
260
+ setProof(undefined);
261
+ })
262
+ }
263
+ >
264
+ {installation.owner}
265
+ </Button>
266
+ ))}
267
+ </div>
268
+ )}
269
+ {id === "github" && installNeeded && (
270
+ <p className="text-sm">
271
+ Install Disposabl, then connect again.{" "}
272
+ {status.githubInstallUrl && (
273
+ <a className="underline" href={status.githubInstallUrl}>
274
+ Install on GitHub
275
+ </a>
276
+ )}
277
+ </p>
278
+ )}
279
+ </section>
280
+ );
281
+ })}
282
+ </div>
283
+ )}
284
+ {busy && (
285
+ <p role="status" className="text-sm">
286
+ Connecting…
287
+ </p>
288
+ )}
289
+ {status?.ready && (
290
+ <p role="status" className="text-sm">
291
+ You're ready. Continue in your terminal.
292
+ </p>
293
+ )}
294
+ <div className="space-y-3 text-xs text-muted-foreground">
295
+ <p>
296
+ Free to start, with plans for personal projects and early startups.
297
+ </p>
298
+ <details>
299
+ <summary className="cursor-pointer">
300
+ Permissions &amp; security
301
+ </summary>
302
+ <div className="mt-3 space-y-2 leading-relaxed">
303
+ <p>
304
+ GitHub creates repositories and manages builds, releases and CI
305
+ secrets. Convex can create and manage projects in your chosen
306
+ team. Expo tokens are verified before saving.
307
+ </p>
308
+ <p>
309
+ Saved tokens are encrypted. We never ask for your provider
310
+ passwords. Disconnect here to remove saved access; revoke provider
311
+ access and CI tokens in their settings.
312
+ </p>
313
+ <p>
314
+ Free plan limits:{" "}
315
+ <a
316
+ className="underline"
317
+ href="https://github.com/pricing"
318
+ target="_blank"
319
+ rel="noreferrer"
320
+ >
321
+ GitHub
322
+ </a>
323
+ ,{" "}
324
+ <a
325
+ className="underline"
326
+ href="https://www.convex.dev/pricing"
327
+ target="_blank"
328
+ rel="noreferrer"
329
+ >
330
+ Convex
331
+ </a>
332
+ ,{" "}
333
+ <a
334
+ className="underline"
335
+ href="https://expo.dev/pricing"
336
+ target="_blank"
337
+ rel="noreferrer"
338
+ >
339
+ Expo
340
+ </a>
341
+ .
342
+ </p>
343
+ </div>
344
+ </details>
345
+ </div>
346
+ <Link
347
+ to="/dashboard"
348
+ className="inline-block text-sm underline underline-offset-4"
349
+ >
350
+ {status?.ready ? "Go to dashboard" : "Skip for now"}
351
+ </Link>
352
+ </main>
353
+ );
354
+ }
@@ -18,6 +18,7 @@ function Dashboard() {
18
18
  <main className="mx-auto max-w-xl space-y-4 p-6">
19
19
  <h1 className="text-2xl font-semibold">Dashboard</h1>
20
20
  <nav className="flex gap-4">
21
+ <Link to="/dashboard/connections">Connections</Link>
21
22
  {config.platforms.includes("api") && (
22
23
  <Link to="/dashboard/api-keys">API keys</Link>
23
24
  )}
@@ -15,6 +15,7 @@
15
15
 
16
16
  ## Keep it simple
17
17
 
18
- - Keep every source file at 300 lines or fewer; regenerate generated files instead of editing them.
18
+ - Aim for roughly 300 lines per source file, not a hard limit. Keep related logic together rather than splitting files to meet a line count.
19
+ - Regenerate generated files instead of editing them.
19
20
  - Prefer clear, concise code over extra layers, fields, or abstractions.
20
21
  - With each change, review it from a fresh perspective: simplify related code, remove duplication, and address nearby debt without expanding scope.
@@ -2,10 +2,12 @@
2
2
 
3
3
  Run `bun run dev` at the workspace root, or `bun run dev` here for Convex alone.
4
4
 
5
- `apps`, `previews`, `appReleases`, and `githubConnections` hold application data. `users` provides authentication identities. App IDs are UUID v4 values; preview references are branch/worktree names, including `main`. Deletion permanently removes app, preview, and release records.
5
+ `apps`, `previews`, and `appReleases` hold application data. `githubConnections` stores installation bindings; `connections` stores encrypted Convex and Expo credentials. `users` provides authentication identities. App IDs are UUID v4 values; preview references are branch/worktree names, including `main`. Deletion permanently removes app, preview, and release records.
6
6
 
7
7
  `index.ts` resolves the authenticated user for web/mobile. `internal.ts` implements operations; `platforms: true` exposes them through enabled API, MCP, SDK, and CLI platforms. Actions live under `actions/`. Put argument/return validators in `validator.ts`, and table definitions in `schema.ts`.
8
8
 
9
- Managed setup needs `CONVEX_TEAM_ID` and `CONVEX_TEAM_TOKEN` on the service backend. GitHub repository creation uses Vercel Connect installation tokens, with `VERCEL_TOKEN`, `VERCEL_PROJECT_ID`, `VERCEL_TEAM_ID`, and `GITHUB_CONNECTOR`. `GITHUB_OWNER` and `GITHUB_INSTALLATION_ID` provide the default organization when the user has no connection.
9
+ Managed setup uses the user's GitHub and Convex connections; Expo is optional. Connect accounts at `/dashboard/connections`. Login works independently. The CLI saves the app UUID before creating cloud resources so setup can resume after a failure.
10
+
11
+ The Disposabl service needs `CONVEX_OAUTH_CLIENT_ID`, `CONVEX_OAUTH_CLIENT_SECRET`, and a base64-encoded 32-byte `CONNECTIONS_ENCRYPTION_KEY`. GitHub uses Vercel Connect with `VERCEL_TOKEN`, `VERCEL_PROJECT_ID`, `VERCEL_TEAM_ID`, `GITHUB_CONNECTOR`, and `GITHUB_APP_SLUG`. `CONNECTIONS_ORIGIN` defaults to `https://www.disposabl.dev`. Generated apps do not need these service credentials for normal development.
10
12
 
11
13
  Preview token creation reuses a named development deployment and returns a fresh development key. Keys are never stored in application tables. GitHub Actions reports the latest build results through verified OIDC identity. Enabled platforms without a published artifact have no download link.
@@ -12,6 +12,13 @@ import type * as apps_actions_create from "../apps/actions/create.js";
12
12
  import type * as apps_actions_setup from "../apps/actions/setup.js";
13
13
  import type * as apps_internal from "../apps/internal.js";
14
14
  import type * as auth from "../auth.js";
15
+ import type * as connections_actions_credentials from "../connections/actions/credentials.js";
16
+ import type * as connections_actions_expo from "../connections/actions/expo.js";
17
+ import type * as connections_actions_github from "../connections/actions/github.js";
18
+ import type * as connections_actions_oauth from "../connections/actions/oauth.js";
19
+ import type * as connections_index from "../connections/index.js";
20
+ import type * as connections_internal from "../connections/internal.js";
21
+ import type * as connections_validator from "../connections/validator.js";
15
22
  import type * as github_actions_http from "../github/actions/http.js";
16
23
  import type * as github_actions_internal from "../github/actions/internal.js";
17
24
  import type * as github_actions_oidc from "../github/actions/oidc.js";
@@ -41,6 +48,13 @@ declare const fullApi: ApiFromModules<{
41
48
  "apps/actions/setup": typeof apps_actions_setup;
42
49
  "apps/internal": typeof apps_internal;
43
50
  auth: typeof auth;
51
+ "connections/actions/credentials": typeof connections_actions_credentials;
52
+ "connections/actions/expo": typeof connections_actions_expo;
53
+ "connections/actions/github": typeof connections_actions_github;
54
+ "connections/actions/oauth": typeof connections_actions_oauth;
55
+ "connections/index": typeof connections_index;
56
+ "connections/internal": typeof connections_internal;
57
+ "connections/validator": typeof connections_validator;
44
58
  "github/actions/http": typeof github_actions_http;
45
59
  "github/actions/internal": typeof github_actions_internal;
46
60
  "github/actions/oidc": typeof github_actions_oidc;
@@ -32,12 +32,12 @@ type Env = {
32
32
  readonly CONVEX_SITE_URL: string;
33
33
  readonly AUTH_JWKS: string;
34
34
  readonly AUTH_PRIVATE_KEY: string;
35
- readonly CONVEX_TEAM_ID: string | undefined;
36
- readonly CONVEX_TEAM_TOKEN: string | undefined;
37
- readonly EXPO_TOKEN: string | undefined;
35
+ readonly CONNECTIONS_ENCRYPTION_KEY: string | undefined;
36
+ readonly CONNECTIONS_ORIGIN: string | undefined;
37
+ readonly CONVEX_OAUTH_CLIENT_ID: string | undefined;
38
+ readonly CONVEX_OAUTH_CLIENT_SECRET: string | undefined;
39
+ readonly GITHUB_APP_SLUG: string | undefined;
38
40
  readonly GITHUB_CONNECTOR: string | undefined;
39
- readonly GITHUB_INSTALLATION_ID: string | undefined;
40
- readonly GITHUB_OWNER: string | undefined;
41
41
  readonly VERCEL_PROJECT_ID: string | undefined;
42
42
  readonly VERCEL_TEAM_ID: string | undefined;
43
43
  readonly VERCEL_TOKEN: string | undefined;
@@ -4,7 +4,7 @@ import {
4
4
  } from "@disposabl/disposabl-kit/server/lib/functions";
5
5
  import { internal } from "../../_generated/api";
6
6
  import { appArgs, appResult } from "../../validator";
7
- import { env } from "../../_generated/server";
7
+ import { ConvexError } from "convex/values";
8
8
  import type { Infer } from "convex/values";
9
9
  type AppResult = Infer<typeof appResult>;
10
10
 
@@ -13,20 +13,18 @@ export const create = internalAction({
13
13
  args: { ...identityFields, ...appArgs },
14
14
  returns: appResult,
15
15
  handler: async (ctx, args): Promise<AppResult> => {
16
- const app = await ctx.runMutation(internal.apps.internal.insert, {
16
+ const connections = await ctx.runQuery(
17
+ internal.connections.internal.status,
18
+ { userId: args.userId },
19
+ );
20
+ if (!connections.ready)
21
+ throw new ConvexError(
22
+ "Connect GitHub and Convex at https://www.disposabl.dev/dashboard/connections, then retry setup. Your login remains active.",
23
+ );
24
+ // Return the UUID before external setup so the CLI can save it and resume safely.
25
+ return ctx.runMutation(internal.apps.internal.insert, {
17
26
  ...args,
18
27
  appId: crypto.randomUUID(),
19
28
  });
20
- if (env.CONVEX_TEAM_TOKEN) {
21
- await ctx.runAction(internal.apps.actions.setup.setup, {
22
- userId: args.userId,
23
- appId: app.appId,
24
- });
25
- return ctx.runQuery(internal.apps.internal.get, {
26
- userId: args.userId,
27
- appId: app.appId,
28
- });
29
- }
30
- return app;
31
29
  },
32
30
  });
@@ -1,23 +1,37 @@
1
+ "use node";
2
+
1
3
  import {
2
4
  identityFields,
3
5
  internalAction,
4
6
  } from "@disposabl/disposabl-kit/server/lib/functions";
5
7
  import { v } from "convex/values";
6
8
  import { internal } from "../../_generated/api";
7
- import { env } from "../../_generated/server";
8
- import { ensureProject } from "../../previews/token/actions/management";
9
+ import { credential } from "../../connections/actions/credentials";
10
+ import {
11
+ ensureProject,
12
+ management,
13
+ } from "../../previews/token/actions/management";
9
14
 
10
15
  export const setup = internalAction({
11
16
  args: { ...identityFields, appId: v.string() },
12
17
  returns: v.number(),
13
18
  handler: async (ctx, args): Promise<number> => {
14
19
  const saved = await ctx.runQuery(internal.apps.internal.project, args);
15
- const token = env.CONVEX_TEAM_TOKEN;
16
- const teamId = env.CONVEX_TEAM_ID;
17
- if (!token || !teamId || !/^\d+$/.test(teamId))
18
- throw new Error(
19
- "Managed setup requires CONVEX_TEAM_ID and CONVEX_TEAM_TOKEN on the service backend.",
20
+ const { token, accountId: teamId } = await credential(
21
+ ctx,
22
+ args.userId,
23
+ "convex",
24
+ );
25
+ if (saved !== null) {
26
+ const projects = await management<{ items: { id: number }[] }>(
27
+ token,
28
+ `/teams/${teamId}/projects?q=${encodeURIComponent(`disposabl-${args.appId}`)}&limit=100`,
20
29
  );
30
+ if (!projects.items.some((project) => project.id === saved))
31
+ throw new Error(
32
+ "Reconnect the Convex team that owns this app before continuing setup.",
33
+ );
34
+ }
21
35
  const projectId = saved ?? (await ensureProject(token, teamId, args.appId));
22
36
  if (saved === null)
23
37
  await ctx.runMutation(internal.apps.internal.saveProject, {
@@ -10,7 +10,6 @@ import {
10
10
  import { ConvexError, v, type Infer } from "convex/values";
11
11
  import { appArgs, appResult } from "../validator";
12
12
  import { githubConnection } from "../validator";
13
- import { env } from "../_generated/server";
14
13
  import type { Doc } from "../_generated/dataModel";
15
14
  import type { QueryCtx } from "../_generated/server";
16
15
  type AppResult = Infer<typeof appResult>;
@@ -136,11 +135,7 @@ export const githubApp = internalQuery({
136
135
  q.eq("userId", app.userId).eq("owner", app.githubOwner!),
137
136
  )
138
137
  .unique();
139
- const installationId =
140
- connection?.installationId ??
141
- (app.githubOwner === env.GITHUB_OWNER?.toLowerCase()
142
- ? env.GITHUB_INSTALLATION_ID
143
- : undefined);
138
+ const installationId = connection?.installationId;
144
139
  return installationId
145
140
  ? {
146
141
  githubOwner: app.githubOwner,
@@ -0,0 +1,56 @@
1
+ /// <reference types="node" />
2
+ "use node";
3
+
4
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
5
+ import { ConvexError } from "convex/values";
6
+ import { env } from "../../_generated/server";
7
+ import type { ActionCtx } from "../../_generated/server";
8
+ import { internal } from "../../_generated/api";
9
+
10
+ export const connectionsUrl = () =>
11
+ `${env.CONNECTIONS_ORIGIN || "https://www.disposabl.dev"}/dashboard/connections`;
12
+ function encryptionKey() {
13
+ const key = Buffer.from(env.CONNECTIONS_ENCRYPTION_KEY || "", "base64");
14
+ if (key.length !== 32)
15
+ throw new ConvexError("Account connections are not configured yet.");
16
+ return key;
17
+ }
18
+ export function seal(value: string, context: string) {
19
+ const iv = randomBytes(12);
20
+ const cipher = createCipheriv("aes-256-gcm", encryptionKey(), iv);
21
+ cipher.setAAD(Buffer.from(context));
22
+ const data = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
23
+ return Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64url");
24
+ }
25
+ export function unseal(value: string, context: string) {
26
+ const data = Buffer.from(value, "base64url");
27
+ const decipher = createDecipheriv(
28
+ "aes-256-gcm",
29
+ encryptionKey(),
30
+ data.subarray(0, 12),
31
+ );
32
+ decipher.setAAD(Buffer.from(context));
33
+ decipher.setAuthTag(data.subarray(12, 28));
34
+ return Buffer.concat([
35
+ decipher.update(data.subarray(28)),
36
+ decipher.final(),
37
+ ]).toString("utf8");
38
+ }
39
+ export async function credential(
40
+ ctx: ActionCtx,
41
+ userId: string,
42
+ provider: "convex" | "expo",
43
+ ) {
44
+ const connection = await ctx.runQuery(internal.connections.internal.get, {
45
+ userId,
46
+ provider,
47
+ });
48
+ if (!connection)
49
+ throw new ConvexError(
50
+ `Connect ${provider === "convex" ? "Convex" : "Expo"} at ${connectionsUrl()} to continue setup.`,
51
+ );
52
+ return {
53
+ ...connection,
54
+ token: unseal(connection.token, `${userId}:${provider}`),
55
+ };
56
+ }