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,136 +0,0 @@
1
- "use node";
2
-
3
- import { v } from "convex/values";
4
- import { internalAction } from "@disposabl/disposabl-kit/server/lib/functions";
5
- import { internal } from "../_generated/api";
6
- import { githubRequest, githubToken } from "../github/actions/tokens";
7
-
8
- const suffixes: Partial<Record<string, string[]>> = {
9
- android: [".apk"],
10
- ios: [".ipa"],
11
- macos: [".dmg"],
12
- windows: [".exe"],
13
- linux: [".AppImage", ".deb"],
14
- };
15
- type Candidate = {
16
- owner: string;
17
- repo: string;
18
- installationId: string;
19
- releaseUrl: string;
20
- artifactUrl: string;
21
- runId: number;
22
- attempt: number;
23
- };
24
- type Release = {
25
- html_url: string;
26
- draft: boolean;
27
- prerelease: boolean;
28
- published_at: string | null;
29
- assets: {
30
- id: number;
31
- name: string;
32
- state: string;
33
- browser_download_url: string;
34
- }[];
35
- };
36
-
37
- export const resolve = internalAction({
38
- args: { appId: v.string(), platform: v.string() },
39
- returns: v.union(v.string(), v.null()),
40
- handler: async (ctx, args): Promise<string | null> => {
41
- if (
42
- !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
43
- args.appId,
44
- ) ||
45
- !Object.hasOwn(suffixes, args.platform)
46
- )
47
- return null;
48
- const candidate: Candidate | null = await ctx.runQuery(
49
- internal.downloads.internal.candidate,
50
- args,
51
- );
52
- if (
53
- !candidate ||
54
- !/^[a-zA-Z0-9-]+$/.test(candidate.owner) ||
55
- !/^[a-zA-Z0-9_.-]+$/.test(candidate.repo)
56
- )
57
- return null;
58
- const repository = `${candidate.owner}/${candidate.repo}`;
59
- const prefix = `https://github.com/${repository}/releases/tag/`;
60
- if (!candidate.releaseUrl.startsWith(prefix)) return null;
61
- const encodedTag = candidate.releaseUrl.slice(prefix.length);
62
- if (!encodedTag || /[?#]/.test(encodedTag)) return null;
63
- let tag: string;
64
- try {
65
- tag = decodeURIComponent(encodedTag);
66
- } catch {
67
- return null;
68
- }
69
- if (
70
- tag !==
71
- `app-production-${args.platform}-${candidate.runId}-${candidate.attempt}`
72
- )
73
- return null;
74
- const token = await githubToken(
75
- ctx,
76
- candidate.installationId,
77
- ["contents:read"],
78
- repository,
79
- );
80
- const release = await githubRequest<Release>(
81
- token,
82
- `/repos/${repository}/releases/tags/${encodeURIComponent(tag)}`,
83
- );
84
- if (
85
- release.html_url !== candidate.releaseUrl ||
86
- release.draft !== false ||
87
- release.prerelease !== false ||
88
- !release.published_at ||
89
- !Array.isArray(release.assets)
90
- )
91
- return null;
92
- const asset = release.assets.find(
93
- (a) =>
94
- a.browser_download_url === candidate.artifactUrl &&
95
- a.state === "uploaded" &&
96
- suffixes[args.platform]?.some((s) => a.name.endsWith(s)) &&
97
- Number.isSafeInteger(a.id) &&
98
- a.id > 0,
99
- );
100
- if (!asset) return null;
101
- const response = await fetch(
102
- `https://api.github.com/repos/${repository}/releases/assets/${asset.id}`,
103
- {
104
- headers: {
105
- Authorization: `Bearer ${token}`,
106
- Accept: "application/octet-stream",
107
- "X-GitHub-Api-Version": "2022-11-28",
108
- },
109
- redirect: "manual",
110
- signal: AbortSignal.timeout(30_000),
111
- },
112
- );
113
- if (response.status !== 302) return null;
114
- const location = response.headers.get("location");
115
- if (!location) return null;
116
- const url = new URL(location);
117
- if (
118
- url.protocol !== "https:" ||
119
- url.username ||
120
- url.password ||
121
- url.port ||
122
- ![
123
- "release-assets.githubusercontent.com",
124
- "objects.githubusercontent.com",
125
- ].includes(url.hostname)
126
- )
127
- return null;
128
- const current: Candidate | null = await ctx.runQuery(
129
- internal.downloads.internal.candidate,
130
- args,
131
- );
132
- return JSON.stringify(current) === JSON.stringify(candidate)
133
- ? url.href
134
- : null;
135
- },
136
- });
@@ -1,32 +0,0 @@
1
- import { httpAction } from "../_generated/server";
2
- import { internal } from "../_generated/api";
3
-
4
- export const download = httpAction(async (ctx, request) => {
5
- const headers = {
6
- "Cache-Control": "no-store",
7
- "Referrer-Policy": "no-referrer",
8
- "X-Content-Type-Options": "nosniff",
9
- };
10
- try {
11
- const match = /^\/downloads\/([^/]+)\/([^/]+)$/.exec(
12
- new URL(request.url).pathname,
13
- );
14
- if (match) {
15
- const location = await ctx.runAction(internal.downloads.action.resolve, {
16
- appId: match.at(1) ?? "",
17
- platform: match.at(2) ?? "",
18
- });
19
- if (location)
20
- return new Response(null, {
21
- status: 302,
22
- headers: { ...headers, Location: location },
23
- });
24
- }
25
- } catch {
26
- // Do not disclose repository, connection, or upstream failure details.
27
- }
28
- return Response.json(
29
- { error: "Download not found or not ready." },
30
- { status: 404, headers },
31
- );
32
- });
@@ -1,58 +0,0 @@
1
- import { v } from "convex/values";
2
- import { internalQuery } from "@disposabl/disposabl-kit/server/lib/functions";
3
-
4
- export const candidate = internalQuery({
5
- args: { appId: v.string(), platform: v.string() },
6
- returns: v.union(
7
- v.null(),
8
- v.object({
9
- owner: v.string(),
10
- repo: v.string(),
11
- installationId: v.string(),
12
- releaseUrl: v.string(),
13
- artifactUrl: v.string(),
14
- runId: v.number(),
15
- attempt: v.number(),
16
- }),
17
- ),
18
- handler: async (ctx, { appId, platform }) => {
19
- const app = await ctx.db
20
- .query("apps")
21
- .withIndex("by_appId", (q) => q.eq("appId", appId))
22
- .unique();
23
- if (
24
- !app?.githubOwner ||
25
- !app.githubRepo ||
26
- app.operation?.kind === "delete" ||
27
- !app.platforms.some((p) => p === platform)
28
- )
29
- return null;
30
- const release = await ctx.db
31
- .query("appReleases")
32
- .withIndex("by_appId", (q) => q.eq("appId", appId))
33
- .unique();
34
- const latest = release?.releases[platform];
35
- if (
36
- latest?.status !== "ready" ||
37
- !latest.githubReleaseUrl ||
38
- !latest.artifactUrl
39
- )
40
- return null;
41
- const connection = await ctx.db
42
- .query("githubConnections")
43
- .withIndex("by_userId_owner", (q) =>
44
- q.eq("userId", app.userId).eq("owner", app.githubOwner!),
45
- )
46
- .unique();
47
- if (!connection) return null;
48
- return {
49
- owner: app.githubOwner,
50
- repo: app.githubRepo,
51
- installationId: connection.installationId,
52
- releaseUrl: latest.githubReleaseUrl,
53
- artifactUrl: latest.artifactUrl,
54
- runId: latest.run.id,
55
- attempt: latest.run.attempt,
56
- };
57
- },
58
- });
@@ -1,69 +0,0 @@
1
- import { httpAction } from "../../_generated/server";
2
- import { internal } from "../../_generated/api";
3
- import { ConvexError } from "convex/values";
4
-
5
- function retryResponse(error: unknown) {
6
- const data = error instanceof ConvexError ? error.data : undefined;
7
- if (
8
- data &&
9
- typeof data === "object" &&
10
- "code" in data &&
11
- data.code === "UPSTREAM_RETRY"
12
- ) {
13
- const seconds = "retryAfter" in data ? Number(data.retryAfter) : 5;
14
- return Response.json(
15
- { error: "GitHub connection is temporarily busy. Retry this request." },
16
- {
17
- status: 503,
18
- headers: {
19
- "Retry-After": String(
20
- Math.max(1, Math.min(3600, Number.isFinite(seconds) ? seconds : 5)),
21
- ),
22
- "Cache-Control": "no-store",
23
- },
24
- },
25
- );
26
- }
27
- return null;
28
- }
29
-
30
- export const token = httpAction(async (ctx, request) => {
31
- try {
32
- const body = await request.json();
33
- const token = request.headers.get("Authorization")?.replace(/^Bearer /, "");
34
- if (!token) return new Response("Unauthorized", { status: 401 });
35
- const result = await ctx.runAction(internal.github.actions.internal.token, {
36
- appId: body.appId,
37
- token,
38
- });
39
- return Response.json(result, { headers: { "Cache-Control": "no-store" } });
40
- } catch (error) {
41
- return (
42
- retryResponse(error) ??
43
- Response.json(
44
- { error: "Actions identity or app binding rejected." },
45
- { status: 403 },
46
- )
47
- );
48
- }
49
- });
50
- export const report = httpAction(async (ctx, request) => {
51
- try {
52
- const body = await request.json();
53
- const token = request.headers.get("Authorization")?.replace(/^Bearer /, "");
54
- if (!token) return new Response("Unauthorized", { status: 401 });
55
- await ctx.runAction(internal.github.actions.internal.report, {
56
- ...body,
57
- token,
58
- });
59
- return Response.json(
60
- { ok: true },
61
- { headers: { "Cache-Control": "no-store" } },
62
- );
63
- } catch (error) {
64
- return (
65
- retryResponse(error) ??
66
- Response.json({ error: "Actions report rejected." }, { status: 403 })
67
- );
68
- }
69
- });
@@ -1,196 +0,0 @@
1
- "use node";
2
-
3
- import { internalAction } from "@disposabl/disposabl-kit/server/lib/functions";
4
- import { v } from "convex/values";
5
- import { internal } from "../../_generated/api";
6
- import type { ActionCtx } from "../../_generated/server";
7
- import { platform, releaseDetails } from "../../validator";
8
- import { githubRequest, githubToken } from "./tokens";
9
- import { verifyGitHubToken } from "./oidc";
10
-
11
- type WorkflowRun = {
12
- id: number;
13
- run_attempt: number;
14
- run_number: number;
15
- head_sha: string;
16
- head_branch: string;
17
- event: string;
18
- html_url: string;
19
- path: string;
20
- repository: { id: number };
21
- head_repository: { id: number };
22
- };
23
- async function authorize(ctx: ActionCtx, appId: string, token: string) {
24
- const claims = await verifyGitHubToken(token);
25
- const app = await ctx.runQuery(internal.apps.internal.githubApp, { appId });
26
- if (!app) throw new Error("Repository is not linked to this app.");
27
- const repository = `${app.githubOwner}/${app.githubRepo}`;
28
- const publisher = claims.environment === "publishing";
29
- const workflowPath = ".github/workflows/pipeline.yml";
30
- const workflow = `${repository}/${workflowPath}@${claims.ref}`;
31
- if (
32
- claims.repository !== repository ||
33
- claims.workflow_ref !== workflow ||
34
- (claims.job_workflow_ref && claims.job_workflow_ref !== workflow)
35
- )
36
- throw new Error("Unexpected workflow.");
37
- const productionEvent =
38
- claims.event_name === "push" && claims.ref === "refs/heads/main";
39
- if (claims.event_name !== "pull_request" && !productionEvent)
40
- throw new Error("Unexpected workflow event.");
41
- // PR build code only receives read access. Write tokens go to main or its trusted artifact publisher.
42
- const installationToken = await githubToken(
43
- ctx,
44
- app.installationId,
45
- [
46
- publisher || productionEvent ? "contents:write" : "contents:read",
47
- "actions:read",
48
- "pull_requests:read",
49
- ],
50
- repository,
51
- );
52
- const { id: repositoryId } = await githubRequest<{ id: number }>(
53
- installationToken,
54
- `/repos/${repository}`,
55
- );
56
- if (String(repositoryId) !== claims.repository_id)
57
- throw new Error("Repository does not match Actions identity.");
58
- const workflowRun = await githubRequest<WorkflowRun>(
59
- installationToken,
60
- `/repos/${repository}/actions/runs/${claims.run_id}`,
61
- );
62
- if (
63
- workflowRun.id !== Number(claims.run_id) ||
64
- workflowRun.run_attempt !== Number(claims.run_attempt) ||
65
- workflowRun.repository.id !== repositoryId ||
66
- workflowRun.head_repository.id !== repositoryId ||
67
- workflowRun.event !== claims.event_name ||
68
- workflowRun.path.split("@")[0] !== workflowPath
69
- )
70
- throw new Error("Workflow run does not match Actions identity.");
71
- if (publisher && !productionEvent) {
72
- // PR changes cannot grant themselves a publishing environment or execute different publisher steps.
73
- if (!/^[a-f0-9]{40}$/.test(claims.workflow_sha ?? ""))
74
- throw new Error("Missing workflow source identity.");
75
- const workflowFile = `/repos/${repository}/contents/${workflowPath}`;
76
- const [source, trusted] = await Promise.all([
77
- githubRequest<{ sha: string }>(
78
- installationToken,
79
- `${workflowFile}?ref=${claims.workflow_sha}`,
80
- ),
81
- githubRequest<{ sha: string }>(
82
- installationToken,
83
- `${workflowFile}?ref=main`,
84
- ),
85
- ]);
86
- if (source.sha !== trusted.sha)
87
- throw new Error(
88
- "Merge workflow changes before publishing preview artifacts.",
89
- );
90
- }
91
- const production = workflowRun.event === "push";
92
- if (production && workflowRun.head_branch !== "main")
93
- throw new Error("Production requires main.");
94
- if (
95
- !production &&
96
- claims.head_ref &&
97
- claims.head_ref !== workflowRun.head_branch
98
- )
99
- throw new Error("Unexpected preview branch.");
100
- await ctx.runMutation(internal.apps.operations.internal.workflow, {
101
- userId: app.userId,
102
- appId,
103
- production,
104
- });
105
- return {
106
- app,
107
- repository,
108
- installationToken,
109
- production,
110
- reference: production ? "main" : workflowRun.head_branch,
111
- run: {
112
- id: workflowRun.id,
113
- attempt: workflowRun.run_attempt,
114
- number: workflowRun.run_number,
115
- commitSha: workflowRun.head_sha,
116
- url: workflowRun.html_url,
117
- },
118
- };
119
- }
120
- export const token = internalAction({
121
- args: {
122
- appId: v.string(),
123
- token: v.string(),
124
- },
125
- returns: v.object({ token: v.string() }),
126
- handler: async (ctx, args): Promise<{ token: string }> => ({
127
- token: (await authorize(ctx, args.appId, args.token)).installationToken,
128
- }),
129
- });
130
- export const report = internalAction({
131
- args: {
132
- appId: v.string(),
133
- token: v.string(),
134
- platform,
135
- ...releaseDetails,
136
- },
137
- returns: v.null(),
138
- handler: async (ctx, args) => {
139
- const verified = await authorize(ctx, args.appId, args.token);
140
- for (const field of [
141
- "url",
142
- "githubReleaseUrl",
143
- "artifactUrl",
144
- "updateUrl",
145
- ] as const) {
146
- if (!args[field]) continue;
147
- const url = new URL(args[field]);
148
- if (url.protocol !== "https:" || url.username || url.password)
149
- throw new Error("Release links must use HTTPS.");
150
- if (
151
- field === "githubReleaseUrl" ||
152
- (field === "artifactUrl" && url.hostname === "github.com")
153
- ) {
154
- if (
155
- url.hostname !== "github.com" ||
156
- !url.pathname.startsWith(`/${verified.repository}/releases/`)
157
- )
158
- throw new Error("Release belongs to another repository.");
159
- }
160
- }
161
- if (args.githubReleaseUrl) {
162
- const tag = new URL(args.githubReleaseUrl).pathname.split(
163
- "/releases/tag/",
164
- )[1];
165
- if (!tag) throw new Error("Expected a GitHub release link.");
166
- const release = await githubRequest<{
167
- html_url: string;
168
- draft: boolean;
169
- assets: { browser_download_url: string }[];
170
- }>(
171
- verified.installationToken,
172
- `/repos/${verified.repository}/releases/tags/${encodeURIComponent(decodeURIComponent(tag))}`,
173
- );
174
- if (
175
- release.draft ||
176
- release.html_url !== args.githubReleaseUrl ||
177
- (args.artifactUrl &&
178
- !release.assets.some(
179
- (asset) => asset.browser_download_url === args.artifactUrl,
180
- ))
181
- )
182
- throw new Error("Release or download is not published.");
183
- }
184
- const { token: _token, ...result } = args;
185
- await ctx.runMutation(internal.previews.internal.report, {
186
- ...result,
187
- userId: verified.app.userId,
188
- githubOwner: verified.app.githubOwner,
189
- githubRepo: verified.app.githubRepo,
190
- reference: verified.reference,
191
- production: verified.production,
192
- run: verified.run,
193
- });
194
- return null;
195
- },
196
- });
@@ -1,75 +0,0 @@
1
- "use node";
2
-
3
- const decode = (value: string) =>
4
- Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (char) =>
5
- char.charCodeAt(0),
6
- );
7
- const json = (value: string) =>
8
- JSON.parse(new TextDecoder().decode(decode(value)));
9
-
10
- /** GitHub alone signs the repository, workflow and run identity. */
11
- export async function verifyGitHubToken(token: string) {
12
- if (token.length > 16_000) throw new Error("Invalid Actions token.");
13
- const parts = token.split(".");
14
- if (parts.length !== 3) throw new Error("Invalid Actions token.");
15
- const [headerPart, bodyPart, signature] = parts as [string, string, string];
16
- const header = json(headerPart);
17
- if (header.alg !== "RS256" || typeof header.kid !== "string")
18
- throw new Error("Invalid Actions signature.");
19
- const response = await fetch(
20
- "https://token.actions.githubusercontent.com/.well-known/jwks",
21
- { redirect: "error", signal: AbortSignal.timeout(15_000) },
22
- );
23
- if (!response.ok) throw new Error("Cannot verify Actions identity.");
24
- const { keys } = (await response.json()) as {
25
- keys: (JsonWebKey & { kid: string })[];
26
- };
27
- const key = keys.find((key) => key.kid === header.kid);
28
- if (!key) throw new Error("Invalid Actions signature.");
29
- const publicKey = await crypto.subtle.importKey(
30
- "jwk",
31
- key,
32
- {
33
- name: "RSASSA-PKCS1-v1_5",
34
- hash: "SHA-256",
35
- },
36
- false,
37
- ["verify"],
38
- );
39
- if (
40
- !(await crypto.subtle.verify(
41
- "RSASSA-PKCS1-v1_5",
42
- publicKey,
43
- decode(signature),
44
- new TextEncoder().encode(`${headerPart}.${bodyPart}`),
45
- ))
46
- )
47
- throw new Error("Invalid Actions signature.");
48
- const claims = json(bodyPart) as Record<string, unknown>;
49
- const now = Date.now() / 1000;
50
- if (
51
- claims.iss !== "https://token.actions.githubusercontent.com" ||
52
- claims.aud !== "https://disposabl.dev" ||
53
- typeof claims.exp !== "number" ||
54
- claims.exp <= now ||
55
- typeof claims.nbf !== "number" ||
56
- claims.nbf > now + 30
57
- )
58
- throw new Error("Expired or invalid Actions identity.");
59
- for (const key of ["repository_id", "run_id", "run_attempt"] as const)
60
- if (
61
- typeof claims[key] !== "string" ||
62
- !/^[1-9]\d*$/.test(claims[key]) ||
63
- !Number.isSafeInteger(Number(claims[key]))
64
- )
65
- throw new Error("Invalid Actions run.");
66
- for (const key of [
67
- "repository",
68
- "workflow_ref",
69
- "ref",
70
- "event_name",
71
- ] as const)
72
- if (typeof claims[key] !== "string")
73
- throw new Error("Missing Actions identity.");
74
- return claims as Record<string, string>;
75
- }
@@ -1,76 +0,0 @@
1
- "use node";
2
-
3
- import {
4
- identityFields,
5
- internalAction,
6
- } from "@disposabl/disposabl-kit/server/lib/functions";
7
- import { v } from "convex/values";
8
- import { internal } from "../../_generated/api";
9
- import { githubRequest, githubToken } from "./tokens";
10
-
11
- type Repository = {
12
- id: number;
13
- name: string;
14
- private: boolean;
15
- description: string | null;
16
- owner: { login: string };
17
- };
18
- export const run = internalAction({
19
- args: { ...identityFields, appId: v.string() },
20
- returns: v.null(),
21
- handler: async (ctx, args) => {
22
- const { app, connection } = await ctx.runQuery(
23
- internal.apps.internal.githubSetup,
24
- args,
25
- );
26
- if (app.githubOwner && app.githubRepo) return null;
27
- const owner = connection?.owner;
28
- const installationId = connection?.installationId;
29
- if (!owner || !installationId || !/^[a-zA-Z0-9-]+$/.test(owner))
30
- throw new Error("Configure a verified GitHub installation.");
31
- const token = await githubToken(ctx, installationId, [
32
- "administration:write",
33
- "contents:read",
34
- ]);
35
- const name = `${app.name
36
- .toLowerCase()
37
- .replace(/[^a-z0-9_.-]/g, "-")
38
- .slice(0, 55)}-${app.appId}`;
39
- const description = `Disposabl app ${app.appId}`;
40
- const account = await githubRequest<{ type: string }>(
41
- token,
42
- `/users/${owner}`,
43
- );
44
- let repo: Repository;
45
- try {
46
- repo = await githubRequest<Repository>(
47
- token,
48
- account.type === "Organization"
49
- ? `/orgs/${owner}/repos`
50
- : "/user/repos",
51
- { name, description, private: true, auto_init: false },
52
- );
53
- } catch (error) {
54
- try {
55
- repo = await githubRequest<Repository>(
56
- token,
57
- `/repos/${owner}/${name}`,
58
- );
59
- } catch {
60
- throw error;
61
- }
62
- }
63
- if (
64
- !repo.private ||
65
- repo.owner.login.toLowerCase() !== owner.toLowerCase() ||
66
- repo.description !== description
67
- )
68
- throw new Error("Repository does not match this app.");
69
- await ctx.runMutation(internal.apps.internal.connectGithub, {
70
- ...args,
71
- githubOwner: repo.owner.login,
72
- githubRepo: repo.name,
73
- });
74
- return null;
75
- },
76
- });