create-disposabl-app 0.8.9 → 0.8.11

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 (69) hide show
  1. package/README.md +8 -1
  2. package/dist/disposabl.js +42 -42
  3. package/dist/index.js +1 -1
  4. package/dist/templates/default/bun.lock +1 -7
  5. package/dist/templates/default/packages/backend/README.md +4 -8
  6. package/dist/templates/default/packages/backend/convex/_generated/api.d.ts +0 -67
  7. package/dist/templates/default/packages/backend/convex/_generated/server.d.ts +0 -9
  8. package/dist/templates/default/packages/backend/convex/convex.config.ts +0 -11
  9. package/dist/templates/default/packages/backend/convex/http.ts +1 -9
  10. package/dist/templates/default/packages/backend/convex/schema.ts +1 -69
  11. package/dist/templates/default/packages/backend/generated/openapi.json +1 -1262
  12. package/dist/templates/default/packages/backend/generated/pages.json +0 -4
  13. package/dist/templates/default/packages/backend/generated/platforms.ts +2 -20
  14. package/dist/templates/default/packages/backend/package.json +1 -7
  15. package/dist/templates/default/packages/cli/README.md +5 -1
  16. package/dist/templates/default/packages/cli/commands.ts +15 -8
  17. package/dist/templates/default/packages/cli/delete.ts +40 -31
  18. package/dist/templates/default/packages/skill/SKILL.md +13 -5
  19. package/dist/templates/default/packages/skill/references/delivery.md +1 -1
  20. package/package.json +1 -1
  21. package/dist/templates/default/packages/backend/convex/apps/actions/cleanup.ts +0 -296
  22. package/dist/templates/default/packages/backend/convex/apps/actions/create.ts +0 -30
  23. package/dist/templates/default/packages/backend/convex/apps/actions/delete.ts +0 -15
  24. package/dist/templates/default/packages/backend/convex/apps/actions/expo.ts +0 -174
  25. package/dist/templates/default/packages/backend/convex/apps/actions/setup.ts +0 -48
  26. package/dist/templates/default/packages/backend/convex/apps/internal.ts +0 -211
  27. package/dist/templates/default/packages/backend/convex/apps/operations/internal.ts +0 -213
  28. package/dist/templates/default/packages/backend/convex/apps/validator.ts +0 -23
  29. package/dist/templates/default/packages/backend/convex/connections/actions/credentials.ts +0 -56
  30. package/dist/templates/default/packages/backend/convex/connections/actions/expo.ts +0 -79
  31. package/dist/templates/default/packages/backend/convex/connections/actions/github.ts +0 -119
  32. package/dist/templates/default/packages/backend/convex/connections/actions/oauth.ts +0 -128
  33. package/dist/templates/default/packages/backend/convex/connections/index.ts +0 -80
  34. package/dist/templates/default/packages/backend/convex/connections/internal.ts +0 -147
  35. package/dist/templates/default/packages/backend/convex/connections/validator.ts +0 -35
  36. package/dist/templates/default/packages/backend/convex/downloads/action.ts +0 -136
  37. package/dist/templates/default/packages/backend/convex/downloads/http.ts +0 -32
  38. package/dist/templates/default/packages/backend/convex/downloads/internal.ts +0 -58
  39. package/dist/templates/default/packages/backend/convex/github/actions/http.ts +0 -69
  40. package/dist/templates/default/packages/backend/convex/github/actions/internal.ts +0 -196
  41. package/dist/templates/default/packages/backend/convex/github/actions/oidc.ts +0 -75
  42. package/dist/templates/default/packages/backend/convex/github/actions/provision.ts +0 -76
  43. package/dist/templates/default/packages/backend/convex/github/actions/secrets.ts +0 -180
  44. package/dist/templates/default/packages/backend/convex/github/actions/signing.ts +0 -41
  45. package/dist/templates/default/packages/backend/convex/github/actions/tokens.ts +0 -145
  46. package/dist/templates/default/packages/backend/convex/github/identityCache.ts +0 -54
  47. package/dist/templates/default/packages/backend/convex/github/internal.ts +0 -33
  48. package/dist/templates/default/packages/backend/convex/previews/internal.ts +0 -257
  49. package/dist/templates/default/packages/backend/convex/previews/token/actions/create.ts +0 -83
  50. package/dist/templates/default/packages/backend/convex/previews/token/actions/management.ts +0 -182
  51. package/dist/templates/default/packages/backend/convex/previews/token/internal.ts +0 -32
  52. package/dist/templates/default/packages/backend/convex/releases/internal.ts +0 -28
  53. package/dist/templates/default/packages/backend/convex/validator.ts +0 -87
  54. package/dist/templates/default/packages/sdk/src/generated/client/client.gen.ts +0 -300
  55. package/dist/templates/default/packages/sdk/src/generated/client/index.ts +0 -27
  56. package/dist/templates/default/packages/sdk/src/generated/client/types.gen.ts +0 -238
  57. package/dist/templates/default/packages/sdk/src/generated/client/utils.gen.ts +0 -337
  58. package/dist/templates/default/packages/sdk/src/generated/client.gen.ts +0 -28
  59. package/dist/templates/default/packages/sdk/src/generated/core/auth.gen.ts +0 -49
  60. package/dist/templates/default/packages/sdk/src/generated/core/bodySerializer.gen.ts +0 -96
  61. package/dist/templates/default/packages/sdk/src/generated/core/params.gen.ts +0 -188
  62. package/dist/templates/default/packages/sdk/src/generated/core/pathSerializer.gen.ts +0 -186
  63. package/dist/templates/default/packages/sdk/src/generated/core/queryKeySerializer.gen.ts +0 -134
  64. package/dist/templates/default/packages/sdk/src/generated/core/serverSentEvents.gen.ts +0 -265
  65. package/dist/templates/default/packages/sdk/src/generated/core/types.gen.ts +0 -126
  66. package/dist/templates/default/packages/sdk/src/generated/core/utils.gen.ts +0 -146
  67. package/dist/templates/default/packages/sdk/src/generated/index.ts +0 -63
  68. package/dist/templates/default/packages/sdk/src/generated/sdk.gen.ts +0 -234
  69. package/dist/templates/default/packages/sdk/src/generated/types.gen.ts +0 -660
@@ -1,56 +0,0 @@
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
- }
@@ -1,79 +0,0 @@
1
- "use node";
2
-
3
- import {
4
- identityFields,
5
- internalAction,
6
- } from "@disposabl/disposabl-kit/server/lib/functions";
7
- import { ConvexError, v } from "convex/values";
8
- import { internal } from "../../_generated/api";
9
- import { account } from "../validator";
10
- import { seal } from "./credentials";
11
-
12
- export async function validateExpo(token: string) {
13
- if (!token || token.length > 4096 || /\s/.test(token))
14
- throw new ConvexError("Enter a valid Expo access token.");
15
- const response = await fetch("https://api.expo.dev/graphql", {
16
- method: "POST",
17
- redirect: "error",
18
- signal: AbortSignal.timeout(30_000),
19
- headers: {
20
- Authorization: `Bearer ${token}`,
21
- "Content-Type": "application/json",
22
- },
23
- body: JSON.stringify({
24
- query:
25
- "query { meActor { id accounts { id name viewerUserPermission2 { effectivePermissions } } } }",
26
- }),
27
- });
28
- const result = (await response.json()) as {
29
- errors?: unknown[];
30
- data?: {
31
- meActor?: {
32
- id: string;
33
- accounts: {
34
- id: string;
35
- name: string;
36
- viewerUserPermission2: { effectivePermissions: string[] };
37
- }[];
38
- };
39
- };
40
- };
41
- if (!response.ok || result.errors?.length || !result.data?.meActor)
42
- throw new ConvexError(
43
- "Expo could not verify this token. Check that it is active and try again.",
44
- );
45
- const accounts = result.data.meActor.accounts
46
- .filter((a) =>
47
- a.viewerUserPermission2.effectivePermissions.includes("PUBLISH"),
48
- )
49
- .map(({ id, name }) => ({ id, name }));
50
- if (!accounts.length)
51
- throw new ConvexError(
52
- "This Expo token needs permission to create projects and publish updates.",
53
- );
54
- return accounts;
55
- }
56
- export const expoAccounts = internalAction({
57
- args: { ...identityFields, token: v.string() },
58
- returns: v.array(account),
59
- handler: async (_ctx, { token }) => validateExpo(token.trim()),
60
- });
61
- export const connectExpo = internalAction({
62
- args: { ...identityFields, token: v.string(), accountId: v.string() },
63
- returns: v.null(),
64
- handler: async (ctx, { userId, token, accountId }) => {
65
- token = token.trim();
66
- const accounts = await validateExpo(token);
67
- const account = accounts.find((a) => a.id === accountId);
68
- if (!account)
69
- throw new ConvexError("Choose an Expo account available to this token.");
70
- await ctx.runMutation(internal.connections.internal.save, {
71
- userId,
72
- provider: "expo",
73
- accountId,
74
- name: account.name,
75
- token: seal(token, `${userId}:expo`),
76
- });
77
- return null;
78
- },
79
- });
@@ -1,119 +0,0 @@
1
- "use node";
2
-
3
- import { getToken } from "@vercel/connect";
4
- import {
5
- identityFields,
6
- internalAction,
7
- } from "@disposabl/disposabl-kit/server/lib/functions";
8
- import { ConvexError, v, type Infer } from "convex/values";
9
- import { internal } from "../../_generated/api";
10
- import { env, type ActionCtx } from "../../_generated/server";
11
- import {
12
- githubRequest,
13
- githubToken,
14
- vercelIdentity,
15
- } from "../../github/actions/tokens";
16
- import { installation } from "../validator";
17
- import { seal, unseal } from "./credentials";
18
-
19
- type Installation = Infer<typeof installation>;
20
- type GitHubInstallation = {
21
- id: number;
22
- app_slug: string;
23
- suspended_at: string | null;
24
- account: { login: string; type: string };
25
- permissions: Record<string, string>;
26
- };
27
- const permissions = [
28
- "administration",
29
- "actions",
30
- "contents",
31
- "workflows",
32
- "secrets",
33
- ];
34
-
35
- export async function userInstallations(ctx: ActionCtx, userId: string) {
36
- const token = await getToken(
37
- env.GITHUB_CONNECTOR!,
38
- {
39
- subject: { type: "user", id: userId },
40
- },
41
- { vercelToken: await vercelIdentity(ctx), forceRefresh: true },
42
- );
43
- const user = await githubRequest<{ login: string }>(token, "/user");
44
- const organizations = new Set<string>();
45
- for (let page = 1; ; page++) {
46
- const memberships = await githubRequest<
47
- Array<{ role: string; organization: { login: string } }>
48
- >(token, `/user/memberships/orgs?state=active&per_page=100&page=${page}`);
49
- for (const membership of memberships)
50
- if (membership.role === "admin")
51
- organizations.add(membership.organization.login.toLowerCase());
52
- if (memberships.length < 100) break;
53
- }
54
- const installations: Installation[] = [];
55
- for (let page = 1; ; page++) {
56
- const result = await githubRequest<{ installations: GitHubInstallation[] }>(
57
- token,
58
- `/user/installations?per_page=100&page=${page}`,
59
- );
60
- for (const item of result.installations) {
61
- if (item.app_slug !== env.GITHUB_APP_SLUG || item.suspended_at) continue;
62
- if (!permissions.every((p) => item.permissions[p] === "write")) continue;
63
- if (item.account.type === "Organization") {
64
- // Only an organization admin can authorize account-wide repository creation.
65
- if (!organizations.has(item.account.login.toLowerCase())) continue;
66
- } else if (item.account.login.toLowerCase() !== user.login.toLowerCase())
67
- continue;
68
- installations.push({
69
- installationId: String(item.id),
70
- owner: item.account.login.toLowerCase(),
71
- });
72
- }
73
- if (result.installations.length < 100) break;
74
- }
75
- return {
76
- installations,
77
- proof: seal(
78
- JSON.stringify({ installations, expiresAt: Date.now() + 10 * 60_000 }),
79
- `github-choice:${userId}`,
80
- ),
81
- };
82
- }
83
- export const selectGithub = internalAction({
84
- args: { ...identityFields, proof: v.string(), installationId: v.string() },
85
- returns: v.null(),
86
- handler: async (ctx, { userId, proof, installationId }) => {
87
- let verified: { installations: Installation[]; expiresAt: number };
88
- try {
89
- verified = JSON.parse(unseal(proof, `github-choice:${userId}`));
90
- } catch {
91
- throw new ConvexError("Connect GitHub again to choose an account.");
92
- }
93
- const chosen = verified.installations.find(
94
- (i) => i.installationId === installationId,
95
- );
96
- if (!chosen || verified.expiresAt < Date.now())
97
- throw new ConvexError("Connect GitHub again to choose an account.");
98
- // Re-check membership and the granted permissions before saving the binding.
99
- const current = await userInstallations(ctx, userId);
100
- if (
101
- !current.installations.some(
102
- (i) => i.installationId === installationId && i.owner === chosen.owner,
103
- )
104
- )
105
- throw new ConvexError(
106
- "GitHub access changed. Install Disposabl with the requested permissions.",
107
- );
108
- await githubToken(
109
- ctx,
110
- installationId,
111
- permissions.map((p) => `${p}:write`),
112
- );
113
- await ctx.runMutation(internal.github.internal.connect, {
114
- userId,
115
- ...chosen,
116
- });
117
- return null;
118
- },
119
- });
@@ -1,128 +0,0 @@
1
- "use node";
2
-
3
- import { createHash, randomBytes } from "node:crypto";
4
- import { startAuthorization } from "@vercel/connect";
5
- import {
6
- identityFields,
7
- internalAction,
8
- } from "@disposabl/disposabl-kit/server/lib/functions";
9
- import { ConvexError, v, type Infer } from "convex/values";
10
- import { internal } from "../../_generated/api";
11
- import { env } from "../../_generated/server";
12
- import { management } from "../../previews/token/actions/management";
13
- import { vercelIdentity } from "../../github/actions/tokens";
14
- import { completion, oauthProvider } from "../validator";
15
- import { connectionsUrl, seal } from "./credentials";
16
- import { userInstallations } from "./github";
17
-
18
- const hash = (value: string) =>
19
- createHash("sha256").update(value).digest("base64url");
20
- export const start = internalAction({
21
- args: { ...identityFields, provider: oauthProvider },
22
- returns: v.string(),
23
- handler: async (ctx, { userId, provider }) => {
24
- const status = await ctx.runQuery(internal.connections.internal.status, {
25
- userId,
26
- });
27
- if (!status.available[provider])
28
- throw new ConvexError(
29
- `${provider === "github" ? "GitHub" : "Convex"} connections are not configured yet.`,
30
- );
31
- const state = randomBytes(32).toString("base64url");
32
- const verifier = randomBytes(32).toString("base64url");
33
- await ctx.runMutation(internal.connections.internal.begin, {
34
- userId,
35
- provider,
36
- hash: hash(state),
37
- verifier,
38
- });
39
- const callback = `${connectionsUrl()}?provider=${provider}`;
40
- if (provider === "github") {
41
- const result = await startAuthorization(
42
- env.GITHUB_CONNECTOR!,
43
- { subject: { type: "user", id: userId } },
44
- {
45
- vercelToken: await vercelIdentity(ctx),
46
- callbackUrl: `${callback}&code=connected&state=${state}`,
47
- expiresInMs: 10 * 60_000,
48
- },
49
- );
50
- return result.url;
51
- }
52
- const url = new URL("https://dashboard.convex.dev/oauth/authorize/team");
53
- url.search = new URLSearchParams({
54
- client_id: env.CONVEX_OAUTH_CLIENT_ID!,
55
- redirect_uri: callback,
56
- response_type: "code",
57
- state,
58
- code_challenge: hash(verifier),
59
- code_challenge_method: "S256",
60
- }).toString();
61
- return url.href;
62
- },
63
- });
64
- export const complete = internalAction({
65
- args: {
66
- ...identityFields,
67
- provider: oauthProvider,
68
- code: v.string(),
69
- state: v.string(),
70
- },
71
- returns: completion,
72
- handler: async (
73
- ctx,
74
- { userId, provider, code, state },
75
- ): Promise<Infer<typeof completion>> => {
76
- if (!code || code.length > 4096 || state.length > 128)
77
- throw new ConvexError("Invalid connection callback.");
78
- const verifier = await ctx.runMutation(
79
- internal.connections.internal.consume,
80
- { userId, provider, hash: hash(state) },
81
- );
82
- if (provider === "github") return userInstallations(ctx, userId);
83
- const response = await fetch("https://api.convex.dev/oauth/token", {
84
- method: "POST",
85
- redirect: "error",
86
- signal: AbortSignal.timeout(30_000),
87
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
88
- body: new URLSearchParams({
89
- client_id: env.CONVEX_OAUTH_CLIENT_ID!,
90
- client_secret: env.CONVEX_OAUTH_CLIENT_SECRET!,
91
- grant_type: "authorization_code",
92
- redirect_uri: `${connectionsUrl()}?provider=convex`,
93
- code,
94
- code_verifier: verifier,
95
- }),
96
- });
97
- if (!response.ok)
98
- throw new ConvexError(
99
- "Convex could not confirm this connection. Please try again.",
100
- );
101
- const result = (await response.json()) as { access_token?: string };
102
- if (!result.access_token)
103
- throw new ConvexError(
104
- "Convex did not return access. Please connect again.",
105
- );
106
- const details = await management<{ type: string; teamId?: number }>(
107
- result.access_token,
108
- "/token_details",
109
- );
110
- if (
111
- details.type !== "teamToken" ||
112
- !Number.isSafeInteger(details.teamId) ||
113
- details.teamId! < 1
114
- )
115
- throw new ConvexError(
116
- "Authorize a Convex team so Disposabl can create your project's backend.",
117
- );
118
- const slug = /^team:([a-z0-9-]+)\|/.exec(result.access_token)?.[1];
119
- await ctx.runMutation(internal.connections.internal.save, {
120
- userId,
121
- provider: "convex",
122
- accountId: String(details.teamId),
123
- name: slug || `Team ${details.teamId}`,
124
- token: seal(result.access_token, `${userId}:convex`),
125
- });
126
- return { installations: [] };
127
- },
128
- });
@@ -1,80 +0,0 @@
1
- import { getAuthUserId } from "@convex-dev/auth/server";
2
- import { ConvexError, v, type Infer } from "convex/values";
3
- import type { ActionCtx, MutationCtx, QueryCtx } from "../_generated/server";
4
- import { action, mutation, query } from "../_generated/server";
5
- import { internal } from "../_generated/api";
6
- import {
7
- account,
8
- completion,
9
- connectionStatus,
10
- oauthProvider,
11
- provider,
12
- } from "./validator";
13
-
14
- async function requireUser(ctx: QueryCtx | MutationCtx | ActionCtx) {
15
- const id = await getAuthUserId(ctx);
16
- if (!id) throw new ConvexError("Sign in to manage your connections.");
17
- return id;
18
- }
19
- export const status = query({
20
- args: {},
21
- returns: connectionStatus,
22
- handler: async (ctx): Promise<Infer<typeof connectionStatus>> =>
23
- ctx.runQuery(internal.connections.internal.status, {
24
- userId: await requireUser(ctx),
25
- }),
26
- });
27
- export const start = action({
28
- args: { provider: oauthProvider },
29
- returns: v.string(),
30
- handler: async (ctx, args): Promise<string> =>
31
- ctx.runAction(internal.connections.actions.oauth.start, {
32
- ...args,
33
- userId: await requireUser(ctx),
34
- }),
35
- });
36
- export const complete = action({
37
- args: { provider: oauthProvider, code: v.string(), state: v.string() },
38
- returns: completion,
39
- handler: async (ctx, args): Promise<Infer<typeof completion>> =>
40
- ctx.runAction(internal.connections.actions.oauth.complete, {
41
- ...args,
42
- userId: await requireUser(ctx),
43
- }),
44
- });
45
- export const selectGithub = action({
46
- args: { proof: v.string(), installationId: v.string() },
47
- returns: v.null(),
48
- handler: async (ctx, args): Promise<null> =>
49
- ctx.runAction(internal.connections.actions.github.selectGithub, {
50
- ...args,
51
- userId: await requireUser(ctx),
52
- }),
53
- });
54
- export const expoAccounts = action({
55
- args: { token: v.string() },
56
- returns: v.array(account),
57
- handler: async (ctx, args): Promise<Infer<typeof account>[]> =>
58
- ctx.runAction(internal.connections.actions.expo.expoAccounts, {
59
- ...args,
60
- userId: await requireUser(ctx),
61
- }),
62
- });
63
- export const connectExpo = action({
64
- args: { token: v.string(), accountId: v.string() },
65
- returns: v.null(),
66
- handler: async (ctx, args): Promise<null> =>
67
- ctx.runAction(internal.connections.actions.expo.connectExpo, {
68
- ...args,
69
- userId: await requireUser(ctx),
70
- }),
71
- });
72
- export const disconnect = mutation({
73
- args: { provider },
74
- returns: v.null(),
75
- handler: async (ctx, args): Promise<null> =>
76
- ctx.runMutation(internal.connections.internal.disconnect, {
77
- ...args,
78
- userId: await requireUser(ctx),
79
- }),
80
- });
@@ -1,147 +0,0 @@
1
- import {
2
- identityFields,
3
- internalMutation,
4
- internalQuery,
5
- } from "@disposabl/disposabl-kit/server/lib/functions";
6
- import { ConvexError, v } from "convex/values";
7
- import type { QueryCtx } from "../_generated/server";
8
- import { env } from "../_generated/server";
9
- import {
10
- connectionStatus,
11
- oauthProvider,
12
- provider,
13
- storedConnection,
14
- tokenProvider,
15
- } from "./validator";
16
-
17
- const connection = (
18
- ctx: Pick<QueryCtx, "db">,
19
- userId: string,
20
- provider: "convex" | "expo",
21
- ) =>
22
- ctx.db
23
- .query("connections")
24
- .withIndex("by_userId_provider", (q) =>
25
- q.eq("userId", userId).eq("provider", provider),
26
- )
27
- .unique();
28
-
29
- export const status = internalQuery({
30
- platforms: true,
31
- args: identityFields,
32
- returns: connectionStatus,
33
- handler: async (ctx, { userId }) => {
34
- const github = await ctx.db
35
- .query("githubConnections")
36
- .withIndex("by_userId", (q) => q.eq("userId", userId))
37
- .order("desc")
38
- .first();
39
- const convex = await connection(ctx, userId, "convex");
40
- const expo = await connection(ctx, userId, "expo");
41
- const encrypted = !!env.CONNECTIONS_ENCRYPTION_KEY;
42
- return {
43
- github: github ? { owner: github.owner } : null,
44
- convex: convex ? { name: convex.name } : null,
45
- expo: expo ? { name: expo.name } : null,
46
- ready: !!github && !!convex,
47
- available: {
48
- github:
49
- encrypted &&
50
- !!env.VERCEL_TOKEN &&
51
- !!env.VERCEL_PROJECT_ID &&
52
- !!env.VERCEL_TEAM_ID &&
53
- !!env.GITHUB_CONNECTOR &&
54
- !!env.GITHUB_APP_SLUG,
55
- convex:
56
- encrypted &&
57
- !!env.CONVEX_OAUTH_CLIENT_ID &&
58
- !!env.CONVEX_OAUTH_CLIENT_SECRET,
59
- expo: encrypted,
60
- },
61
- githubInstallUrl: env.GITHUB_APP_SLUG
62
- ? `https://github.com/apps/${encodeURIComponent(env.GITHUB_APP_SLUG)}/installations/new`
63
- : null,
64
- };
65
- },
66
- });
67
- export const get = internalQuery({
68
- args: { ...identityFields, provider: tokenProvider },
69
- returns: v.union(storedConnection, v.null()),
70
- handler: async (ctx, { userId, provider }) => {
71
- const row = await connection(ctx, userId, provider);
72
- return row
73
- ? { accountId: row.accountId, name: row.name, token: row.token }
74
- : null;
75
- },
76
- });
77
- export const save = internalMutation({
78
- args: {
79
- ...identityFields,
80
- provider: tokenProvider,
81
- ...storedConnection.fields,
82
- },
83
- returns: v.null(),
84
- handler: async (ctx, args) => {
85
- const row = await connection(ctx, args.userId, args.provider);
86
- if (row) await ctx.db.replace("connections", row._id, args);
87
- else await ctx.db.insert("connections", args);
88
- return null;
89
- },
90
- });
91
- export const disconnect = internalMutation({
92
- args: { ...identityFields, provider },
93
- returns: v.null(),
94
- handler: async (ctx, { userId, provider }) => {
95
- if (provider === "github") {
96
- for await (const row of ctx.db
97
- .query("githubConnections")
98
- .withIndex("by_userId", (q) => q.eq("userId", userId)))
99
- await ctx.db.delete("githubConnections", row._id);
100
- } else {
101
- const row = await connection(ctx, userId, provider);
102
- if (row) await ctx.db.delete("connections", row._id);
103
- }
104
- const id = ctx.db.normalizeId("users", userId);
105
- if (id) await ctx.db.patch("users", id, { connectionState: undefined });
106
- return null;
107
- },
108
- });
109
- export const begin = internalMutation({
110
- args: {
111
- ...identityFields,
112
- provider: oauthProvider,
113
- hash: v.string(),
114
- verifier: v.string(),
115
- },
116
- returns: v.null(),
117
- handler: async (ctx, { userId, ...state }) => {
118
- const id = ctx.db.normalizeId("users", userId);
119
- if (!id) throw new ConvexError("Invalid userId.");
120
- await ctx.db.patch("users", id, {
121
- connectionState: { ...state, expiresAt: Date.now() + 10 * 60_000 },
122
- });
123
- return null;
124
- },
125
- });
126
- export const consume = internalMutation({
127
- args: { ...identityFields, provider: oauthProvider, hash: v.string() },
128
- returns: v.string(),
129
- handler: async (ctx, { userId, provider, hash }) => {
130
- const id = ctx.db.normalizeId("users", userId);
131
- const state = id
132
- ? (await ctx.db.get("users", id))?.connectionState
133
- : undefined;
134
- if (
135
- !id ||
136
- !state ||
137
- state.provider !== provider ||
138
- state.hash !== hash ||
139
- state.expiresAt < Date.now()
140
- )
141
- throw new ConvexError(
142
- "This connection link has expired. Please connect again.",
143
- );
144
- await ctx.db.patch("users", id, { connectionState: undefined });
145
- return state.verifier;
146
- },
147
- });
@@ -1,35 +0,0 @@
1
- import { v } from "convex/values";
2
-
3
- export const provider = v.union(
4
- v.literal("github"),
5
- v.literal("convex"),
6
- v.literal("expo"),
7
- );
8
- export const oauthProvider = v.union(v.literal("github"), v.literal("convex"));
9
- export const tokenProvider = v.union(v.literal("convex"), v.literal("expo"));
10
- export const account = v.object({ id: v.string(), name: v.string() });
11
- export const installation = v.object({
12
- installationId: v.string(),
13
- owner: v.string(),
14
- });
15
- export const completion = v.object({
16
- installations: v.array(installation),
17
- proof: v.optional(v.string()),
18
- });
19
- export const connectionStatus = v.object({
20
- github: v.union(v.object({ owner: v.string() }), v.null()),
21
- convex: v.union(v.object({ name: v.string() }), v.null()),
22
- expo: v.union(v.object({ name: v.string() }), v.null()),
23
- ready: v.boolean(),
24
- available: v.object({
25
- github: v.boolean(),
26
- convex: v.boolean(),
27
- expo: v.boolean(),
28
- }),
29
- githubInstallUrl: v.union(v.string(), v.null()),
30
- });
31
- export const storedConnection = v.object({
32
- accountId: v.string(),
33
- name: v.string(),
34
- token: v.string(),
35
- });