@mastra/factory 0.2.2-alpha.1 → 0.2.2-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/auth.js +401 -334
- package/dist/auth.js.map +1 -1
- package/dist/capabilities/connection.js +1 -1
- package/dist/capabilities/intake.js +1 -1
- package/dist/capabilities/version-control.js +1 -1
- package/dist/factory.js +441 -39622
- package/dist/factory.js.map +1 -1
- package/dist/index.js +2 -39633
- package/dist/integrations/base.js +1 -1
- package/dist/integrations/github/config.js +36 -22
- package/dist/integrations/github/config.js.map +1 -1
- package/dist/integrations/github/factory-session.js +33 -37
- package/dist/integrations/github/factory-session.js.map +1 -1
- package/dist/integrations/github/integration.js +1037 -3672
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/issue-triage.js +71 -71
- package/dist/integrations/github/issue-triage.js.map +1 -1
- package/dist/integrations/github/pat.js +47 -36
- package/dist/integrations/github/pat.js.map +1 -1
- package/dist/integrations/github/provenance.js +72 -101
- package/dist/integrations/github/provenance.js.map +1 -1
- package/dist/integrations/github/routes.js +1272 -1881
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.js +203 -471
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.js +400 -345
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +165 -223
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/subscriptions.js +43 -51
- package/dist/integrations/github/subscriptions.js.map +1 -1
- package/dist/integrations/github/token-refresh.js +15 -18
- package/dist/integrations/github/token-refresh.js.map +1 -1
- package/dist/integrations/github/webhook.js +359 -343
- package/dist/integrations/github/webhook.js.map +1 -1
- package/dist/integrations/linear/agent-tools.js +77 -100
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/integration.js +611 -1309
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/routes.js +227 -230
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.js +126 -346
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/linear/storage.js +1 -1
- package/dist/integrations/platform/api-client.js +131 -135
- package/dist/integrations/platform/api-client.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +275 -573
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.js +845 -4022
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/linear/integration.js +457 -1309
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/workos/integration.js +80 -85
- package/dist/integrations/workos/integration.js.map +1 -1
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +933 -912
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/custom-provider-source.js +110 -93
- package/dist/routes/custom-provider-source.js.map +1 -1
- package/dist/routes/fs.js +401 -349
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake.js +165 -165
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/oauth.js +447 -25166
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.js +437 -376
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.js +76 -58
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/route.js +12 -8
- package/dist/routes/route.js.map +1 -1
- package/dist/routes/skills.js +160 -173
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/surface.js +250 -28615
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.js +141 -166
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-items.js +654 -862
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.js +23 -35
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/defaults.js +200 -309
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/dispatcher.js +438 -683
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/index.js +5 -599
- package/dist/rules/processor.js +344 -596
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/resolve.js +21 -18
- package/dist/rules/resolve.js.map +1 -1
- package/dist/rules/start-coordinator.js +168 -157
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +50 -85
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.js +183 -454
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.js +33 -29
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.js +266 -281
- package/dist/rules/validation.js.map +1 -1
- package/dist/sandbox/fleet.js +272 -250
- package/dist/sandbox/fleet.js.map +1 -1
- package/dist/sandbox/reattach.js +13 -6
- package/dist/sandbox/reattach.js.map +1 -1
- package/dist/server-error.js +12 -16
- package/dist/server-error.js.map +1 -1
- package/dist/skills/service.js +30 -35
- package/dist/skills/service.js.map +1 -1
- package/dist/spa-static.js +91 -65
- package/dist/spa-static.js.map +1 -1
- package/dist/state-signing.js +73 -44
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/audit/agent-audit.js +60 -59
- package/dist/storage/domains/audit/agent-audit.js.map +1 -1
- package/dist/storage/domains/audit/base.js +169 -112
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/audit/domain.js +155 -153
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/credentials/base.js +259 -243
- package/dist/storage/domains/credentials/base.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.js +138 -143
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/intake/base.js +75 -57
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.js +310 -245
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/memory-settings/base.js +117 -102
- package/dist/storage/domains/memory-settings/base.js.map +1 -1
- package/dist/storage/domains/model-packs/base.js +89 -88
- package/dist/storage/domains/model-packs/base.js.map +1 -1
- package/dist/storage/domains/projects/base.js +97 -92
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/queue-health/base.js +111 -76
- package/dist/storage/domains/queue-health/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.js +777 -706
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +322 -348
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.js +1266 -1148
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.js +202 -184
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/timing.js +29 -22
- package/dist/timing.js.map +1 -1
- package/dist/workspace.js +236 -477
- package/dist/workspace.js.map +1 -1
- package/package.json +8 -8
- package/dist/capabilities/connection.js.map +0 -1
- package/dist/capabilities/intake.js.map +0 -1
- package/dist/capabilities/version-control.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/integrations/base.js.map +0 -1
- package/dist/integrations/linear/storage.js.map +0 -1
- package/dist/rules/index.js.map +0 -1
|
@@ -1,1918 +1,1309 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
1
|
+
import { clearGithubPat, getGithubPat, getGithubPatStatus, setGithubPat } from "./pat.js";
|
|
2
|
+
import { listPullRequestSubscriptionsForThread, subscribeToPullRequest } from "./subscriptions.js";
|
|
3
|
+
import { SandboxBudgetError } from "../../sandbox/fleet.js";
|
|
4
|
+
import { getGithubFeatureDiagnostics, isGithubFeatureEnabled } from "./config.js";
|
|
5
|
+
import { MaterializeError, WorktreeError, commitAll, computeWorktreePath, ensureProjectSandbox, isValidGitRef as isValidGitRef$1, materializeRepo, pushBranch, teardownProjectSandbox } from "./sandbox.js";
|
|
6
|
+
import { handleGithubWebhook } from "./webhook.js";
|
|
3
7
|
import { registerApiRoute } from "@mastra/core/server";
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
4
9
|
import { streamSSE } from "hono/streaming";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
// src/integrations/github/config.ts
|
|
28
|
-
var GITHUB_APP_ENV_VARS = [
|
|
29
|
-
"GITHUB_APP_ID",
|
|
30
|
-
"GITHUB_APP_PRIVATE_KEY",
|
|
31
|
-
"GITHUB_APP_CLIENT_ID",
|
|
32
|
-
"GITHUB_APP_CLIENT_SECRET",
|
|
33
|
-
"GITHUB_APP_SLUG"
|
|
34
|
-
];
|
|
35
|
-
function isGithubFeatureEnabled(options) {
|
|
36
|
-
return options.github !== void 0 && options.auth.enabled();
|
|
37
|
-
}
|
|
38
|
-
function getGithubFeatureDiagnostics(options) {
|
|
39
|
-
const { github, auth, appDbConfigured, stateSigner, fleet } = options;
|
|
40
|
-
return {
|
|
41
|
-
githubAppConfigured: github !== void 0,
|
|
42
|
-
factoryAuthEnabled: auth.enabled(),
|
|
43
|
-
appDbConfigured,
|
|
44
|
-
stateSecretConfigured: stateSigner?.stable ?? false,
|
|
45
|
-
sandboxEnabled: fleet?.enabled ?? false,
|
|
46
|
-
sandboxProvider: fleet?.provider ?? "none",
|
|
47
|
-
missingGithubAppEnvVars: github ? [] : [...GITHUB_APP_ENV_VARS]
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// src/integrations/github/pat.ts
|
|
52
|
-
var PAT_SETTINGS_USER_ID = "__github_org_settings__";
|
|
53
|
-
var FIELD_FOR_KIND = {
|
|
54
|
-
default: "pat",
|
|
55
|
-
reviewer: "reviewerPat"
|
|
56
|
-
};
|
|
57
|
-
function asToken(value) {
|
|
58
|
-
return typeof value === "string" && value.length > 0 ? value : null;
|
|
59
|
-
}
|
|
60
|
-
async function getGithubPat(getStorage, orgId, kind = "default") {
|
|
61
|
-
try {
|
|
62
|
-
const settings = await getStorage().settings.get(orgId, PAT_SETTINGS_USER_ID);
|
|
63
|
-
if (!settings) return null;
|
|
64
|
-
if (kind === "reviewer") return asToken(settings.reviewerPat) ?? asToken(settings.pat);
|
|
65
|
-
return asToken(settings.pat);
|
|
66
|
-
} catch {
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
async function getGithubPatStatus(getStorage, orgId) {
|
|
71
|
-
try {
|
|
72
|
-
const settings = await getStorage().settings.get(orgId, PAT_SETTINGS_USER_ID);
|
|
73
|
-
return {
|
|
74
|
-
configured: asToken(settings?.pat) !== null,
|
|
75
|
-
reviewerConfigured: asToken(settings?.reviewerPat) !== null
|
|
76
|
-
};
|
|
77
|
-
} catch {
|
|
78
|
-
return { configured: false, reviewerConfigured: false };
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
async function setGithubPat(storage, orgId, pat, kind = "default") {
|
|
82
|
-
const existing = await storage.settings.get(orgId, PAT_SETTINGS_USER_ID) ?? {};
|
|
83
|
-
await storage.settings.save(orgId, PAT_SETTINGS_USER_ID, { ...existing, [FIELD_FOR_KIND[kind]]: pat });
|
|
84
|
-
}
|
|
85
|
-
async function clearGithubPat(storage, orgId, kind = "default") {
|
|
86
|
-
const existing = await storage.settings.get(orgId, PAT_SETTINGS_USER_ID);
|
|
87
|
-
const field = FIELD_FOR_KIND[kind];
|
|
88
|
-
if (!existing?.[field]) return;
|
|
89
|
-
const { [field]: _removed, ...rest } = existing;
|
|
90
|
-
await storage.settings.save(orgId, PAT_SETTINGS_USER_ID, rest);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// src/integrations/github/sandbox.ts
|
|
94
|
-
import { createHash } from "crypto";
|
|
95
|
-
function bindingStore(row, storage) {
|
|
96
|
-
return {
|
|
97
|
-
sandboxId: row.sandboxId,
|
|
98
|
-
setSandboxId: (id) => id === null ? storage.clearBinding({ id: row.id }) : storage.setSandboxId({ id: row.id, sandboxId: id }),
|
|
99
|
-
clear: () => storage.clearBinding({ id: row.id })
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
async function ensureProjectSandbox(options) {
|
|
103
|
-
const { fleet, row, storage, token, onProgress } = options;
|
|
104
|
-
return fleet.ensureSandbox(bindingStore(row, storage), { GH_TOKEN: token }, onProgress);
|
|
105
|
-
}
|
|
106
|
-
async function teardownProjectSandbox(options) {
|
|
107
|
-
const { fleet, row, storage, sandbox } = options;
|
|
108
|
-
return fleet.teardownSandbox(bindingStore(row, storage), sandbox);
|
|
109
|
-
}
|
|
110
|
-
function shellQuote(value) {
|
|
111
|
-
return `'` + value.split(`'`).join(`'\\''`) + `'`;
|
|
112
|
-
}
|
|
113
|
-
var DEFAULT_COMMAND_TIMEOUT_MS = 15 * 6e4;
|
|
114
|
-
var CHECKOUT_COMMAND_TIMEOUT_MS = 5 * 6e4;
|
|
115
|
-
async function sh(sandbox, script, options = {}) {
|
|
116
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
|
|
117
|
-
let timer;
|
|
118
|
-
const hangGuard = new Promise((_, reject) => {
|
|
119
|
-
timer = setTimeout(() => {
|
|
120
|
-
const phase = options.phase ? ` during ${options.phase}` : "";
|
|
121
|
-
reject(new Error(`Sandbox command timed out after ${Math.round(timeoutMs / 1e3)}s${phase}.`));
|
|
122
|
-
}, timeoutMs);
|
|
123
|
-
timer.unref?.();
|
|
124
|
-
});
|
|
125
|
-
try {
|
|
126
|
-
return await Promise.race([sandbox.executeCommand("sh", ["-c", script], { timeout: timeoutMs }), hangGuard]);
|
|
127
|
-
} finally {
|
|
128
|
-
clearTimeout(timer);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
var MaterializeError = class extends Error {
|
|
132
|
-
constructor(message, code) {
|
|
133
|
-
super(message);
|
|
134
|
-
this.code = code;
|
|
135
|
-
this.name = "MaterializeError";
|
|
136
|
-
}
|
|
137
|
-
code;
|
|
138
|
-
};
|
|
139
|
-
function tokenUrl(repoFullName, token) {
|
|
140
|
-
return `https://x-access-token:${token}@github.com/${repoFullName}.git`;
|
|
141
|
-
}
|
|
142
|
-
function cleanUrl(repoFullName) {
|
|
143
|
-
return `https://github.com/${repoFullName}.git`;
|
|
144
|
-
}
|
|
145
|
-
async function materializeRepo(options) {
|
|
146
|
-
const { row: sandboxRow, repoInfo, sandbox, token, storage, onProgress } = options;
|
|
147
|
-
const workdir = sandboxRow.sandboxWorkdir;
|
|
148
|
-
const repo = repoInfo.repoFullName;
|
|
149
|
-
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) {
|
|
150
|
-
throw new MaterializeError(`Refusing to materialize: invalid repo full name '${repo}'.`, "clone-failed");
|
|
151
|
-
}
|
|
152
|
-
if (!/^[A-Za-z0-9_./-]+$/.test(repoInfo.defaultBranch)) {
|
|
153
|
-
throw new MaterializeError(
|
|
154
|
-
`Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,
|
|
155
|
-
"clone-failed"
|
|
156
|
-
);
|
|
157
|
-
}
|
|
158
|
-
const gitVersion = await sh(sandbox, "git --version");
|
|
159
|
-
if (gitVersion.exitCode !== 0) {
|
|
160
|
-
throw new MaterializeError(
|
|
161
|
-
"git is not installed in the sandbox. The sandbox template must include git.",
|
|
162
|
-
"git-missing"
|
|
163
|
-
);
|
|
164
|
-
}
|
|
165
|
-
const authUrl = tokenUrl(repo, token);
|
|
166
|
-
const alreadyMaterialized = await hasExistingCheckout(sandbox, workdir, repo);
|
|
167
|
-
let succeeded = false;
|
|
168
|
-
try {
|
|
169
|
-
if (!alreadyMaterialized) {
|
|
170
|
-
reportProgress(onProgress, {
|
|
171
|
-
phase: "cloning",
|
|
172
|
-
message: `Cloning ${repo} (first open can take a minute)\u2026`
|
|
173
|
-
});
|
|
174
|
-
const clone = await sh(
|
|
175
|
-
sandbox,
|
|
176
|
-
`git clone --depth=1 --single-branch --branch ${shellQuote(repoInfo.defaultBranch)} ${shellQuote(authUrl)} ${shellQuote(workdir)}`,
|
|
177
|
-
{ phase: "repository clone" }
|
|
178
|
-
);
|
|
179
|
-
if (clone.exitCode !== 0) {
|
|
180
|
-
throw classifyGitFailure(clone, "clone-failed");
|
|
181
|
-
}
|
|
182
|
-
} else {
|
|
183
|
-
reportProgress(onProgress, { phase: "pulling", message: `Updating ${repo} to the latest changes\u2026` });
|
|
184
|
-
const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
|
|
185
|
-
if (setUrl.exitCode !== 0) {
|
|
186
|
-
throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr}`, "pull-failed");
|
|
187
|
-
}
|
|
188
|
-
const pull = await sh(sandbox, `git -C ${shellQuote(workdir)} pull --ff-only`, { phase: "repository pull" });
|
|
189
|
-
if (pull.exitCode !== 0) {
|
|
190
|
-
throw classifyGitFailure(pull, "pull-failed");
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
succeeded = true;
|
|
194
|
-
} finally {
|
|
195
|
-
await scrubRemote(sandbox, workdir, repo, succeeded);
|
|
196
|
-
}
|
|
197
|
-
reportProgress(onProgress, { phase: "finalizing", message: "Finalizing workspace\u2026" });
|
|
198
|
-
await storage.markMaterialized({ id: sandboxRow.id });
|
|
199
|
-
}
|
|
200
|
-
async function hasExistingCheckout(sandbox, workdir, repoFullName) {
|
|
201
|
-
const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote get-url origin`);
|
|
202
|
-
if (result.exitCode !== 0) return false;
|
|
203
|
-
const url = result.stdout.trim().toLowerCase();
|
|
204
|
-
const suffix = `github.com/${repoFullName.toLowerCase()}`;
|
|
205
|
-
return url.endsWith(`${suffix}.git`) || url.endsWith(suffix);
|
|
206
|
-
}
|
|
207
|
-
async function scrubRemote(sandbox, workdir, repoFullName, expectGitDir) {
|
|
208
|
-
const result = await sh(
|
|
209
|
-
sandbox,
|
|
210
|
-
`git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`
|
|
211
|
-
);
|
|
212
|
-
if (result.exitCode !== 0 && expectGitDir) {
|
|
213
|
-
throw new MaterializeError(
|
|
214
|
-
`Failed to scrub installation token from git remote: ${result.stderr.trim() || result.stdout.trim()}`,
|
|
215
|
-
"pull-failed"
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function classifyGitFailure(result, fallback) {
|
|
220
|
-
const stderr = result.stderr || "";
|
|
221
|
-
if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {
|
|
222
|
-
return new MaterializeError(
|
|
223
|
-
"The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.",
|
|
224
|
-
"egress-blocked"
|
|
225
|
-
);
|
|
226
|
-
}
|
|
227
|
-
const verb = fallback === "clone-failed" ? "clone" : fallback === "pull-failed" ? "pull" : "push";
|
|
228
|
-
return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);
|
|
229
|
-
}
|
|
230
|
-
function isValidGitRef(value) {
|
|
231
|
-
return typeof value === "string" && value.length > 0 && value.length <= 255 && // Reject leading-dash refs (e.g. `--mirror`) so the value can never be
|
|
232
|
-
// parsed as a git option when interpolated into a command.
|
|
233
|
-
!value.startsWith("-") && /^[A-Za-z0-9_./-]+$/.test(value);
|
|
234
|
-
}
|
|
235
|
-
function resolveGitIdentity(identity) {
|
|
236
|
-
const login = (identity.login || "").trim();
|
|
237
|
-
const name = (identity.name || "").trim() || login || "Mastra Code";
|
|
238
|
-
const email = (identity.email || "").trim() || (login ? `${login}@users.noreply.github.com` : "mastra-code@users.noreply.github.com");
|
|
239
|
-
return { name, email };
|
|
240
|
-
}
|
|
241
|
-
async function configureGitIdentity(sandbox, workdir, identity) {
|
|
242
|
-
const { name, email } = resolveGitIdentity(identity);
|
|
243
|
-
const setName = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.name ${shellQuote(name)}`);
|
|
244
|
-
if (setName.exitCode !== 0) {
|
|
245
|
-
throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, "commit-failed");
|
|
246
|
-
}
|
|
247
|
-
const setEmail = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.email ${shellQuote(email)}`);
|
|
248
|
-
if (setEmail.exitCode !== 0) {
|
|
249
|
-
throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
async function withInstallToken(sandbox, workdir, repoFullName, token, fn) {
|
|
253
|
-
if (!/^[\w.-]+\/[\w.-]+$/.test(repoFullName)) {
|
|
254
|
-
throw new MaterializeError(`Refusing to push: invalid repo full name '${repoFullName}'.`, "push-failed");
|
|
255
|
-
}
|
|
256
|
-
const setUrl = await sh(
|
|
257
|
-
sandbox,
|
|
258
|
-
`git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(tokenUrl(repoFullName, token))}`
|
|
259
|
-
);
|
|
260
|
-
if (setUrl.exitCode !== 0) {
|
|
261
|
-
await scrubRemote(sandbox, workdir, repoFullName, false);
|
|
262
|
-
throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr.trim()}`, "push-failed");
|
|
263
|
-
}
|
|
264
|
-
try {
|
|
265
|
-
return await fn();
|
|
266
|
-
} finally {
|
|
267
|
-
await scrubRemote(sandbox, workdir, repoFullName, true);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
async function pushBranch(sandbox, workdir, branch, token, repoFullName) {
|
|
271
|
-
if (!isValidGitRef(branch)) {
|
|
272
|
-
throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, "push-failed");
|
|
273
|
-
}
|
|
274
|
-
await withInstallToken(sandbox, workdir, repoFullName, token, async () => {
|
|
275
|
-
const push = await sh(sandbox, `git -C ${shellQuote(workdir)} push -u origin ${shellQuote(branch)}`);
|
|
276
|
-
if (push.exitCode !== 0) {
|
|
277
|
-
throw classifyGitFailure(push, "push-failed");
|
|
278
|
-
}
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
async function commitAll(sandbox, workdir, message, identity) {
|
|
282
|
-
await configureGitIdentity(sandbox, workdir, identity);
|
|
283
|
-
const add = await sh(sandbox, `git -C ${shellQuote(workdir)} add -A`);
|
|
284
|
-
if (add.exitCode !== 0) {
|
|
285
|
-
throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, "commit-failed");
|
|
286
|
-
}
|
|
287
|
-
const staged = await sh(sandbox, `git -C ${shellQuote(workdir)} diff --cached --quiet`);
|
|
288
|
-
if (staged.exitCode === 0) {
|
|
289
|
-
return { committed: false };
|
|
290
|
-
}
|
|
291
|
-
const commit = await sh(sandbox, `git -C ${shellQuote(workdir)} commit -m ${shellQuote(message)}`);
|
|
292
|
-
if (commit.exitCode !== 0) {
|
|
293
|
-
throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, "commit-failed");
|
|
294
|
-
}
|
|
295
|
-
return { committed: true };
|
|
296
|
-
}
|
|
297
|
-
var WorktreeError = class extends Error {
|
|
298
|
-
constructor(message, code) {
|
|
299
|
-
super(message);
|
|
300
|
-
this.code = code;
|
|
301
|
-
this.name = "WorktreeError";
|
|
302
|
-
}
|
|
303
|
-
code;
|
|
304
|
-
};
|
|
305
|
-
function safeBranchDir(branch) {
|
|
306
|
-
const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/\/+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 100) || "work";
|
|
307
|
-
if (sanitized === branch) return sanitized;
|
|
308
|
-
const hash = createHash("sha256").update(branch).digest("hex").slice(0, 8);
|
|
309
|
-
return `${sanitized}-${hash}`;
|
|
310
|
-
}
|
|
311
|
-
function computeWorktreePath(repoWorkdir, branch) {
|
|
312
|
-
const parent = repoWorkdir.replace(/\/+$/, "").split("/").slice(0, -1).join("/") || "";
|
|
313
|
-
return `${parent}/worktrees/${safeBranchDir(branch)}`;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// src/integrations/github/subscriptions.ts
|
|
317
|
-
function changeRequestTargetKey(input) {
|
|
318
|
-
return `change-request:${input.installationExternalId}:${input.repositoryExternalId}:${input.changeRequestId}`;
|
|
319
|
-
}
|
|
320
|
-
function sameSession(row, input) {
|
|
321
|
-
return row.orgId === input.orgId && row.sessionId === input.sessionId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "");
|
|
322
|
-
}
|
|
323
|
-
async function subscribeToPullRequest(input, storage) {
|
|
324
|
-
const targetKey = changeRequestTargetKey(input);
|
|
325
|
-
const existing = (await storage.subscriptions.listByTarget(targetKey)).find((row) => sameSession(row, input));
|
|
326
|
-
if (existing) {
|
|
327
|
-
if (existing.status !== "open") await storage.subscriptions.updateStatus(existing.id, "open");
|
|
328
|
-
return { ...existing, status: "open" };
|
|
329
|
-
}
|
|
330
|
-
return storage.subscriptions.create({
|
|
331
|
-
orgId: input.orgId,
|
|
332
|
-
targetKey,
|
|
333
|
-
sessionId: input.sessionId,
|
|
334
|
-
resourceId: input.resourceId,
|
|
335
|
-
threadId: input.threadId,
|
|
336
|
-
sessionScope: input.sessionScope ?? "",
|
|
337
|
-
status: "open",
|
|
338
|
-
data: {
|
|
339
|
-
installationExternalId: input.installationExternalId,
|
|
340
|
-
projectRepositoryId: input.projectRepositoryId,
|
|
341
|
-
repositoryExternalId: input.repositoryExternalId,
|
|
342
|
-
repositorySlug: input.repositorySlug,
|
|
343
|
-
changeRequestId: input.changeRequestId,
|
|
344
|
-
ownerId: input.ownerId,
|
|
345
|
-
source: input.source,
|
|
346
|
-
subscribedByUserId: input.subscribedByUserId ?? null
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
async function listPullRequestSubscriptionsForThread(input, storage) {
|
|
351
|
-
const rows = await storage.subscriptions.listByThread(input.resourceId, input.threadId);
|
|
352
|
-
return rows.filter(
|
|
353
|
-
(row) => row.orgId === input.orgId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "")
|
|
354
|
-
);
|
|
355
|
-
}
|
|
356
|
-
async function listPullRequestSubscriptionsForWebhook(input, options, storage) {
|
|
357
|
-
const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
|
|
358
|
-
return options?.includeTerminal ? rows : rows.filter((row) => row.status === "open");
|
|
359
|
-
}
|
|
360
|
-
function retirePullRequestSubscription(id, status, storage) {
|
|
361
|
-
return storage.subscriptions.updateStatus(id, status);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// src/integrations/github/webhook.ts
|
|
365
|
-
import { createHmac, timingSafeEqual } from "crypto";
|
|
366
|
-
var SUPPORTED_GITHUB_WEBHOOK_EVENTS = /* @__PURE__ */ new Set([
|
|
367
|
-
"issues",
|
|
368
|
-
"issue_comment",
|
|
369
|
-
"pull_request",
|
|
370
|
-
"pull_request_review",
|
|
371
|
-
"pull_request_review_comment"
|
|
372
|
-
]);
|
|
373
|
-
function normalizeHeader(value) {
|
|
374
|
-
if (!value) return null;
|
|
375
|
-
const trimmed = value.trim();
|
|
376
|
-
return trimmed.length > 0 ? trimmed : null;
|
|
377
|
-
}
|
|
378
|
-
function verifySignature(rawBody, signature, secret) {
|
|
379
|
-
if (!signature.startsWith("sha256=")) return false;
|
|
380
|
-
const signatureHex = signature.slice("sha256=".length);
|
|
381
|
-
if (!/^[a-fA-F0-9]{64}$/.test(signatureHex)) return false;
|
|
382
|
-
const expectedHex = createHmac("sha256", secret).update(rawBody).digest("hex");
|
|
383
|
-
const received = Buffer.from(signatureHex, "hex");
|
|
384
|
-
const expected = Buffer.from(expectedHex, "hex");
|
|
385
|
-
return received.length === expected.length && timingSafeEqual(received, expected);
|
|
386
|
-
}
|
|
387
|
-
async function parseGithubWebhook(c, secret) {
|
|
388
|
-
if (!secret) {
|
|
389
|
-
return { status: 401, body: { error: "unauthorized", message: "GitHub webhook secret is not configured" } };
|
|
390
|
-
}
|
|
391
|
-
const event = normalizeHeader(c.req.header("x-github-event"));
|
|
392
|
-
const deliveryId = normalizeHeader(c.req.header("x-github-delivery"));
|
|
393
|
-
const signature = normalizeHeader(c.req.header("x-hub-signature-256"));
|
|
394
|
-
if (!event) return { status: 400, body: { error: "bad_request", message: "Missing x-github-event header" } };
|
|
395
|
-
if (!deliveryId) return { status: 400, body: { error: "bad_request", message: "Missing x-github-delivery header" } };
|
|
396
|
-
if (!signature)
|
|
397
|
-
return { status: 401, body: { error: "unauthorized", message: "Missing x-hub-signature-256 header" } };
|
|
398
|
-
const rawBody = await c.req.text();
|
|
399
|
-
if (!verifySignature(rawBody, signature, secret)) {
|
|
400
|
-
return { status: 401, body: { error: "unauthorized", message: "Invalid GitHub webhook signature" } };
|
|
401
|
-
}
|
|
402
|
-
let payload;
|
|
403
|
-
try {
|
|
404
|
-
payload = JSON.parse(rawBody);
|
|
405
|
-
} catch {
|
|
406
|
-
return { status: 400, body: { error: "bad_request", message: "Malformed JSON payload" } };
|
|
407
|
-
}
|
|
408
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
409
|
-
return { status: 400, body: { error: "bad_request", message: "Payload must be a JSON object" } };
|
|
410
|
-
}
|
|
411
|
-
return { event, deliveryId, payload };
|
|
412
|
-
}
|
|
413
|
-
function getObject(value) {
|
|
414
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
415
|
-
}
|
|
416
|
-
function getString(value) {
|
|
417
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
418
|
-
}
|
|
419
|
-
function getNumber(value) {
|
|
420
|
-
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
421
|
-
}
|
|
422
|
-
function getBoolean(value) {
|
|
423
|
-
return typeof value === "boolean" ? value : void 0;
|
|
424
|
-
}
|
|
425
|
-
function getLabels(value) {
|
|
426
|
-
if (!Array.isArray(value)) return [];
|
|
427
|
-
return value.map((label) => typeof label === "string" ? label : getString(getObject(label)?.name)).filter((label) => Boolean(label));
|
|
428
|
-
}
|
|
429
|
-
function getIssueTriageRunInput(parsed) {
|
|
430
|
-
if (parsed.event !== "issues" || getString(parsed.payload.action) !== "opened") return null;
|
|
431
|
-
const repository = getString(getObject(parsed.payload.repository)?.full_name);
|
|
432
|
-
const issue = getObject(parsed.payload.issue);
|
|
433
|
-
const sender = getString(getObject(parsed.payload.sender)?.login);
|
|
434
|
-
const installationId = getNumber(getObject(parsed.payload.installation)?.id);
|
|
435
|
-
const issueNumber = getNumber(issue?.number);
|
|
436
|
-
const issueTitle = getString(issue?.title);
|
|
437
|
-
const issueUrl = getString(issue?.html_url);
|
|
438
|
-
if (!repository || !installationId || !issueNumber || !issueTitle || !issueUrl) return null;
|
|
439
|
-
return {
|
|
440
|
-
repository,
|
|
441
|
-
issueNumber,
|
|
442
|
-
issueTitle,
|
|
443
|
-
issueUrl,
|
|
444
|
-
labels: getLabels(issue?.labels),
|
|
445
|
-
sender,
|
|
446
|
-
installationId
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
function normalizeGithubWebhookMetadata(parsed) {
|
|
450
|
-
const { event, deliveryId, payload } = parsed;
|
|
451
|
-
const repository = getObject(payload.repository);
|
|
452
|
-
const issue = getObject(payload.issue);
|
|
453
|
-
const pullRequest = getObject(payload.pull_request);
|
|
454
|
-
const sender = getObject(payload.sender);
|
|
455
|
-
const installation = getObject(payload.installation);
|
|
456
|
-
const issuePullRequest = getObject(issue?.pull_request);
|
|
457
|
-
return {
|
|
458
|
-
event,
|
|
459
|
-
action: getString(payload.action),
|
|
460
|
-
deliveryId,
|
|
461
|
-
repository: getString(repository?.full_name),
|
|
462
|
-
repositoryId: getNumber(repository?.id),
|
|
463
|
-
issueNumber: getNumber(issue?.number),
|
|
464
|
-
pullRequestNumber: getNumber(pullRequest?.number) ?? (event === "issue_comment" && issuePullRequest ? getNumber(issue?.number) : void 0),
|
|
465
|
-
sender: getString(sender?.login),
|
|
466
|
-
senderType: getString(sender?.type),
|
|
467
|
-
installationId: getNumber(installation?.id)
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
function notificationSummary(metadata, label) {
|
|
471
|
-
const actor = metadata.sender ? `${metadata.sender} ` : "";
|
|
472
|
-
return `${actor}${label} on ${metadata.repository}#${metadata.pullRequestNumber}`;
|
|
473
|
-
}
|
|
474
|
-
function notificationTargetUrl(event, payload) {
|
|
475
|
-
if (event === "issue_comment" || event === "pull_request_review_comment") {
|
|
476
|
-
return getString(getObject(payload.comment)?.html_url);
|
|
477
|
-
}
|
|
478
|
-
if (event === "pull_request_review") {
|
|
479
|
-
return getString(getObject(payload.review)?.html_url);
|
|
480
|
-
}
|
|
481
|
-
return getString(getObject(payload.pull_request)?.html_url);
|
|
482
|
-
}
|
|
483
|
-
function classifyGithubWebhook(parsed) {
|
|
484
|
-
const metadata = normalizeGithubWebhookMetadata(parsed);
|
|
485
|
-
const { event, payload } = parsed;
|
|
486
|
-
const action = metadata.action;
|
|
487
|
-
if (!action || !metadata.repositoryId || !metadata.installationId || !metadata.pullRequestNumber || !metadata.repository) {
|
|
488
|
-
return void 0;
|
|
489
|
-
}
|
|
490
|
-
let priority;
|
|
491
|
-
let kind;
|
|
492
|
-
let label;
|
|
493
|
-
let terminal = false;
|
|
494
|
-
if (event === "pull_request_review" && action === "submitted") {
|
|
495
|
-
const state = getString(getObject(payload.review)?.state)?.toLowerCase().replaceAll("_", "-");
|
|
496
|
-
priority = state === "approved" || state === "changes-requested" ? "urgent" : "high";
|
|
497
|
-
kind = state === "approved" ? "review-approved" : state === "changes-requested" ? "review-changes-requested" : "review-submitted";
|
|
498
|
-
label = state === "approved" ? "approved the pull request" : state === "changes-requested" ? "requested changes" : "submitted a review";
|
|
499
|
-
} else if (event === "pull_request" && action === "closed") {
|
|
500
|
-
const merged = getBoolean(getObject(payload.pull_request)?.merged) === true;
|
|
501
|
-
priority = "urgent";
|
|
502
|
-
kind = merged ? "pull-request-merged" : "pull-request-closed";
|
|
503
|
-
label = merged ? "merged the pull request" : "closed the pull request";
|
|
504
|
-
terminal = true;
|
|
505
|
-
} else if (event === "issue_comment" && action === "created") {
|
|
506
|
-
priority = "high";
|
|
507
|
-
kind = "issue-comment-created";
|
|
508
|
-
label = "commented";
|
|
509
|
-
} else if (event === "pull_request_review_comment" && action === "created") {
|
|
510
|
-
priority = "high";
|
|
511
|
-
kind = "review-comment-created";
|
|
512
|
-
label = "left a review comment";
|
|
513
|
-
} else if (event === "pull_request" && action === "reopened") {
|
|
514
|
-
priority = "high";
|
|
515
|
-
kind = "pull-request-reopened";
|
|
516
|
-
label = "reopened the pull request";
|
|
517
|
-
} else if (event === "pull_request_review" && action === "dismissed") {
|
|
518
|
-
priority = "high";
|
|
519
|
-
kind = "review-dismissed";
|
|
520
|
-
label = "dismissed a review";
|
|
521
|
-
} else if (event === "pull_request" && [
|
|
522
|
-
"synchronize",
|
|
523
|
-
"ready_for_review",
|
|
524
|
-
"converted_to_draft",
|
|
525
|
-
"assigned",
|
|
526
|
-
"unassigned",
|
|
527
|
-
"review_requested",
|
|
528
|
-
"review_request_removed"
|
|
529
|
-
].includes(action)) {
|
|
530
|
-
priority = "medium";
|
|
531
|
-
kind = `pull-request-${action.replaceAll("_", "-")}`;
|
|
532
|
-
label = action.replaceAll("_", " ");
|
|
533
|
-
} else if (event === "pull_request" && ["edited", "labeled", "unlabeled", "milestoned", "demilestoned"].includes(action)) {
|
|
534
|
-
priority = "low";
|
|
535
|
-
kind = `pull-request-${action.replaceAll("_", "-")}`;
|
|
536
|
-
label = action.replaceAll("_", " ");
|
|
537
|
-
} else {
|
|
538
|
-
return void 0;
|
|
539
|
-
}
|
|
540
|
-
return {
|
|
541
|
-
action,
|
|
542
|
-
kind,
|
|
543
|
-
priority,
|
|
544
|
-
summary: notificationSummary(metadata, label),
|
|
545
|
-
terminal,
|
|
546
|
-
metadata: {
|
|
547
|
-
...metadata,
|
|
548
|
-
pullRequestNumber: metadata.pullRequestNumber,
|
|
549
|
-
repositoryId: metadata.repositoryId,
|
|
550
|
-
installationId: metadata.installationId
|
|
551
|
-
},
|
|
552
|
-
payload
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
async function resolveSubscriptionSession(controller, subscription) {
|
|
556
|
-
const { sessionId, resourceId, threadId } = subscription;
|
|
557
|
-
if (!sessionId || !resourceId || !threadId) {
|
|
558
|
-
throw new Error(`GitHub subscription ${subscription.id} is missing its session binding.`);
|
|
559
|
-
}
|
|
560
|
-
const scope = subscription.sessionScope || void 0;
|
|
561
|
-
let session = await controller.getSessionByResource(resourceId, scope);
|
|
562
|
-
if (!session) {
|
|
563
|
-
const tags = {
|
|
564
|
-
factoryProjectId: resourceId,
|
|
565
|
-
projectRepositoryId: subscription.data.projectRepositoryId,
|
|
566
|
-
...scope ? { worktreePath: scope } : {}
|
|
567
|
-
};
|
|
568
|
-
session = await controller.createSession({
|
|
569
|
-
id: sessionId,
|
|
570
|
-
ownerId: subscription.data.ownerId,
|
|
571
|
-
resourceId,
|
|
572
|
-
scope,
|
|
573
|
-
tags
|
|
574
|
-
});
|
|
575
|
-
}
|
|
576
|
-
if (session.thread.getId() !== threadId) {
|
|
577
|
-
await session.thread.switch({ threadId, emitEvent: false });
|
|
578
|
-
}
|
|
579
|
-
if (session.thread.getId() !== threadId) {
|
|
580
|
-
throw new Error(`Session ${sessionId} did not bind thread ${threadId}.`);
|
|
581
|
-
}
|
|
582
|
-
return session;
|
|
583
|
-
}
|
|
584
|
-
var AUTHORIZED_BOTS = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
|
|
585
|
-
var AUTHORIZED_PERMISSIONS = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
|
|
586
|
-
var PERMISSION_CHECK_TIMEOUT_MS = 5e3;
|
|
587
|
-
var AUTHOR_GATED_KINDS = /* @__PURE__ */ new Set([
|
|
588
|
-
"issue-comment-created",
|
|
589
|
-
"review-comment-created",
|
|
590
|
-
"review-submitted",
|
|
591
|
-
"review-approved",
|
|
592
|
-
"review-changes-requested",
|
|
593
|
-
"review-dismissed"
|
|
594
|
-
]);
|
|
595
|
-
async function isAuthorizedGithubSender(notification, github) {
|
|
596
|
-
if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;
|
|
597
|
-
const sender = notification.metadata.sender;
|
|
598
|
-
const repository = notification.metadata.repository;
|
|
599
|
-
if (!sender || !repository) return false;
|
|
600
|
-
const normalizedSender = sender.toLowerCase();
|
|
601
|
-
if (notification.metadata.senderType?.toLowerCase() === "bot" || normalizedSender.endsWith("[bot]")) {
|
|
602
|
-
return AUTHORIZED_BOTS.has(normalizedSender);
|
|
603
|
-
}
|
|
604
|
-
if (!github) return false;
|
|
605
|
-
const abortController = new AbortController();
|
|
606
|
-
let timeout;
|
|
607
|
-
try {
|
|
608
|
-
const permission = await Promise.race([
|
|
609
|
-
github.getRepositoryCollaboratorPermission(
|
|
610
|
-
notification.metadata.installationId,
|
|
611
|
-
repository,
|
|
612
|
-
sender,
|
|
613
|
-
abortController.signal
|
|
614
|
-
),
|
|
615
|
-
new Promise((resolve) => {
|
|
616
|
-
timeout = setTimeout(() => {
|
|
617
|
-
abortController.abort();
|
|
618
|
-
resolve(void 0);
|
|
619
|
-
}, PERMISSION_CHECK_TIMEOUT_MS);
|
|
620
|
-
})
|
|
621
|
-
]);
|
|
622
|
-
return permission !== void 0 && AUTHORIZED_PERMISSIONS.has(permission);
|
|
623
|
-
} catch {
|
|
624
|
-
return false;
|
|
625
|
-
} finally {
|
|
626
|
-
if (timeout) clearTimeout(timeout);
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
async function dispatchGithubWebhook(parsed, dependencies) {
|
|
630
|
-
const notification = classifyGithubWebhook(parsed);
|
|
631
|
-
if (!notification) return { delivered: 0, failed: 0, ignored: true };
|
|
632
|
-
const isAuthorizedSender = dependencies.isAuthorizedSender ?? ((n) => isAuthorizedGithubSender(n, dependencies.github));
|
|
633
|
-
if (!await isAuthorizedSender(notification)) {
|
|
634
|
-
return { delivered: 0, failed: 0, ignored: true };
|
|
635
|
-
}
|
|
636
|
-
const target = {
|
|
637
|
-
installationExternalId: notification.metadata.installationId.toString(),
|
|
638
|
-
repositoryExternalId: notification.metadata.repositoryId.toString(),
|
|
639
|
-
changeRequestId: notification.metadata.pullRequestNumber.toString()
|
|
640
|
-
};
|
|
641
|
-
const listSubscriptions = dependencies.listSubscriptions ?? ((subscriptionTarget, options) => {
|
|
642
|
-
if (!dependencies.github) throw new Error("GitHub integration is required to load webhook subscriptions.");
|
|
643
|
-
return listPullRequestSubscriptionsForWebhook(
|
|
644
|
-
subscriptionTarget,
|
|
645
|
-
options,
|
|
646
|
-
dependencies.github.integrationStorage
|
|
647
|
-
);
|
|
648
|
-
});
|
|
649
|
-
const retireSubscription = dependencies.retireSubscription ?? ((id, status) => {
|
|
650
|
-
if (!dependencies.github) throw new Error("GitHub integration is required to retire webhook subscriptions.");
|
|
651
|
-
return retirePullRequestSubscription(id, status, dependencies.github.integrationStorage);
|
|
652
|
-
});
|
|
653
|
-
const subscriptions = await listSubscriptions(target, { includeTerminal: notification.action === "reopened" });
|
|
654
|
-
let delivered = 0;
|
|
655
|
-
let failed = 0;
|
|
656
|
-
for (const subscription of subscriptions) {
|
|
657
|
-
try {
|
|
658
|
-
const session = await resolveSubscriptionSession(dependencies.controller, subscription);
|
|
659
|
-
const result = await session.sendNotificationSignal({
|
|
660
|
-
source: "github",
|
|
661
|
-
kind: notification.kind,
|
|
662
|
-
summary: notification.summary,
|
|
663
|
-
priority: notification.priority,
|
|
664
|
-
payload: notification.payload,
|
|
665
|
-
sourceId: parsed.deliveryId,
|
|
666
|
-
dedupeKey: `${parsed.deliveryId}:${subscription.sessionId}:${subscription.threadId}`,
|
|
667
|
-
coalesceKey: `github:${subscription.data.repositoryExternalId}:pull-request:${subscription.data.changeRequestId}`,
|
|
668
|
-
metadata: {
|
|
669
|
-
event: notification.metadata.event,
|
|
670
|
-
action: notification.action,
|
|
671
|
-
repository: notification.metadata.repository,
|
|
672
|
-
issueNumber: notification.metadata.issueNumber,
|
|
673
|
-
pullRequestNumber: notification.metadata.pullRequestNumber,
|
|
674
|
-
targetUrl: notificationTargetUrl(parsed.event, parsed.payload),
|
|
675
|
-
deliveryId: parsed.deliveryId
|
|
676
|
-
}
|
|
677
|
-
});
|
|
678
|
-
await Promise.all([result.persisted, result.accepted].filter(Boolean));
|
|
679
|
-
if (notification.terminal) {
|
|
680
|
-
await retireSubscription(subscription.id, notification.kind === "pull-request-merged" ? "merged" : "closed");
|
|
681
|
-
} else if (notification.action === "reopened") {
|
|
682
|
-
await retireSubscription(subscription.id, "open");
|
|
683
|
-
}
|
|
684
|
-
delivered += 1;
|
|
685
|
-
} catch (error) {
|
|
686
|
-
failed += 1;
|
|
687
|
-
dependencies.onTargetError?.(subscription, error);
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
return { delivered, failed, ignored: false };
|
|
691
|
-
}
|
|
692
|
-
async function handleGithubWebhook(c, options) {
|
|
693
|
-
const parsed = await parseGithubWebhook(c, options.github.webhookSecret);
|
|
694
|
-
if ("status" in parsed) return parsed;
|
|
695
|
-
if (!SUPPORTED_GITHUB_WEBHOOK_EVENTS.has(parsed.event)) {
|
|
696
|
-
return { status: 202, body: { ok: true, ignored: true } };
|
|
697
|
-
}
|
|
698
|
-
const metadata = normalizeGithubWebhookMetadata(parsed);
|
|
699
|
-
console.info("[GitHub Webhook]", metadata);
|
|
700
|
-
if (options.ingestFactoryEvent) {
|
|
701
|
-
await options.ingestFactoryEvent(parsed);
|
|
702
|
-
} else {
|
|
703
|
-
const issueTriageRun = getIssueTriageRunInput(parsed);
|
|
704
|
-
if (issueTriageRun && options.runIssueTriage) {
|
|
705
|
-
void options.runIssueTriage(issueTriageRun).catch((error) => {
|
|
706
|
-
console.error("[GitHub Webhook] Failed to run issue triage", {
|
|
707
|
-
deliveryId: metadata.deliveryId,
|
|
708
|
-
repository: metadata.repository,
|
|
709
|
-
issueNumber: metadata.issueNumber,
|
|
710
|
-
error: error instanceof Error ? error.message : String(error)
|
|
711
|
-
});
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
if (!options.controller) {
|
|
716
|
-
return { status: 202, body: { ok: true } };
|
|
717
|
-
}
|
|
718
|
-
const result = await dispatchGithubWebhook(parsed, options);
|
|
719
|
-
if (result.failed > 0) {
|
|
720
|
-
console.warn(`[GitHub Webhook] ${result.failed} subscribed target(s) failed for delivery ${parsed.deliveryId}.`);
|
|
721
|
-
}
|
|
722
|
-
return { status: 202, body: { ok: true, ...result.ignored ? { ignored: true } : {} } };
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
// src/integrations/github/routes.ts
|
|
726
|
-
var sessionOperationLocks = /* @__PURE__ */ new Map();
|
|
10
|
+
//#region src/integrations/github/routes.ts
|
|
11
|
+
/**
|
|
12
|
+
* Mastra `apiRoutes` for the GitHub App project feature.
|
|
13
|
+
*
|
|
14
|
+
* Registered alongside the other `/web/*` routes, behind the host auth gate.
|
|
15
|
+
* Every route additionally re-checks the authenticated user via the injected
|
|
16
|
+
* `RouteAuth` seam and scopes all rows by that user's stable id, so a user can
|
|
17
|
+
* only ever see and operate on their own installations and projects.
|
|
18
|
+
*
|
|
19
|
+
* When the feature is disabled (`isGithubFeatureEnabled()` false), `buildGithubRoutes`
|
|
20
|
+
* returns only `GET /web/github/status`, which reports `enabled:false`
|
|
21
|
+
* so the SPA can cleanly hide all GitHub UI.
|
|
22
|
+
*/
|
|
23
|
+
const sessionOperationLocks = /* @__PURE__ */ new Map();
|
|
24
|
+
/**
|
|
25
|
+
* Serialize same-session mutations within one Factory process. Factory sessions
|
|
26
|
+
* normally issue these operations sequentially, so this lock is probably not
|
|
27
|
+
* necessary; keep the cheap local guard until that invariant is enforced by
|
|
28
|
+
* the request protocol. It intentionally does not consume a database connection.
|
|
29
|
+
*/
|
|
727
30
|
function withSessionOperationLock(sessionId, fn) {
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
});
|
|
738
|
-
return next;
|
|
739
|
-
}
|
|
31
|
+
const next = (sessionOperationLocks.get(sessionId) ?? Promise.resolve()).then(fn, fn);
|
|
32
|
+
const tail = next.then(() => void 0, () => void 0);
|
|
33
|
+
sessionOperationLocks.set(sessionId, tail);
|
|
34
|
+
tail.then(() => {
|
|
35
|
+
if (sessionOperationLocks.get(sessionId) === tail) sessionOperationLocks.delete(sessionId);
|
|
36
|
+
});
|
|
37
|
+
return next;
|
|
38
|
+
}
|
|
39
|
+
/** Erase a route handler's path-parameterized context to a plain `Context`. */
|
|
740
40
|
function loose(c) {
|
|
741
|
-
|
|
41
|
+
return c;
|
|
742
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the Factory project's default model for a triage run. Best-effort:
|
|
45
|
+
* a missing project or an uninitialized storage domain simply means "no
|
|
46
|
+
* default", never a failed run.
|
|
47
|
+
*/
|
|
743
48
|
async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
}
|
|
49
|
+
if (!projects || !factoryProjectId) return void 0;
|
|
50
|
+
try {
|
|
51
|
+
return (await projects.getById({ id: factoryProjectId }))?.defaultModelId ?? void 0;
|
|
52
|
+
} catch {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
751
55
|
}
|
|
752
56
|
function pullRequestNumberFromUrl(value, expectedRepo) {
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
return void 0;
|
|
763
|
-
}
|
|
57
|
+
try {
|
|
58
|
+
const url = new URL(value);
|
|
59
|
+
const match = url.pathname.match(/^\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/);
|
|
60
|
+
if (url.protocol !== "https:" || url.hostname !== "github.com" || match?.[1]?.toLowerCase() !== expectedRepo.toLowerCase()) return;
|
|
61
|
+
const number = Number(match[2]);
|
|
62
|
+
return Number.isInteger(number) && number > 0 ? number : void 0;
|
|
63
|
+
} catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
764
66
|
}
|
|
765
67
|
function isCanonicalGithubIssueUrl(value, repoFullName, issueNumber) {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
68
|
+
try {
|
|
69
|
+
const url = new URL(value);
|
|
70
|
+
const [owner, repo] = repoFullName.split("/");
|
|
71
|
+
return url.protocol === "https:" && url.hostname === "github.com" && url.pathname === `/${owner}/${repo}/issues/${issueNumber}` && url.search === "" && url.hash === "";
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Validate a git branch/ref name against a strict whitelist. The value is later
|
|
78
|
+
* interpolated into a shell `git clone --branch` command, so it must never
|
|
79
|
+
* contain shell metacharacters. We accept only git-ref-safe characters and
|
|
80
|
+
* reject anything else rather than relying on shell quoting alone.
|
|
81
|
+
*/
|
|
82
|
+
function isValidGitRef(value) {
|
|
83
|
+
return typeof value === "string" && value.length > 0 && value.length <= 255 && /^[A-Za-z0-9_./-]+$/.test(value);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolve the org-scoped tenant for a GitHub request. GitHub project features
|
|
87
|
+
* are org-owned, so they require both a signed-in user and a WorkOS
|
|
88
|
+
* organization. Returns the `(orgId, userId)` tenant (with `orgId` narrowed to a
|
|
89
|
+
* non-null string) or a ready-to-return error response: 401 when unauthenticated,
|
|
90
|
+
* 403 when the user has no organization (personal account).
|
|
91
|
+
*
|
|
92
|
+
* Resolves the session from the request cookie itself (via `auth.ensureUser`)
|
|
93
|
+
* instead of relying on the auth gate's context stash: on platform deploys
|
|
94
|
+
* custom `apiRoutes` run on an isolated sub-app context where the gate's
|
|
95
|
+
* `c.set(...)` is invisible. When the gate stash IS visible (local Hono
|
|
96
|
+
* server), `auth.ensureUser` returns the cached user and this is a no-op.
|
|
97
|
+
*/
|
|
777
98
|
async function resolveOrgTenant(c, auth) {
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
99
|
+
await auth.ensureUser(c);
|
|
100
|
+
const tenant = auth.tenant(c);
|
|
101
|
+
if (!tenant) return { response: c.json({ error: "unauthorized" }, 401) };
|
|
102
|
+
if (!tenant.orgId) return { response: c.json({
|
|
103
|
+
error: "organization_required",
|
|
104
|
+
message: "GitHub projects require a WorkOS organization. Personal accounts cannot connect repositories."
|
|
105
|
+
}, 403) };
|
|
106
|
+
return { tenant: {
|
|
107
|
+
orgId: tenant.orgId,
|
|
108
|
+
userId: tenant.userId
|
|
109
|
+
} };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Parse a 1-based `page` query param. Missing means page 1; anything that is
|
|
113
|
+
* not a small positive integer is rejected (`null`).
|
|
114
|
+
*/
|
|
794
115
|
function parseListPage(raw) {
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
116
|
+
if (raw === void 0) return 1;
|
|
117
|
+
if (!/^\d{1,5}$/.test(raw)) return null;
|
|
118
|
+
const page = Number(raw);
|
|
119
|
+
return page >= 1 ? page : null;
|
|
799
120
|
}
|
|
800
|
-
|
|
121
|
+
const VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set(["auto-triaged", "needs-approval"]);
|
|
801
122
|
function parseIssueLabelFilter(raw) {
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
123
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
124
|
+
if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
|
|
125
|
+
return null;
|
|
805
126
|
}
|
|
806
127
|
function parseIssueNumberParam(raw) {
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
128
|
+
if (!raw || !/^\d{1,10}$/.test(raw)) return null;
|
|
129
|
+
const issueNumber = Number(raw);
|
|
130
|
+
return Number.isSafeInteger(issueNumber) && issueNumber > 0 ? issueNumber : null;
|
|
810
131
|
}
|
|
811
132
|
function parseStringList(value) {
|
|
812
|
-
|
|
813
|
-
|
|
133
|
+
if (!Array.isArray(value)) return [];
|
|
134
|
+
return value.filter((item) => typeof item === "string" && item.length > 0);
|
|
814
135
|
}
|
|
815
136
|
async function resolveProjectRepository(args) {
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
137
|
+
const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
|
|
138
|
+
orgId: args.orgId,
|
|
139
|
+
id: args.projectRepositoryId
|
|
140
|
+
});
|
|
141
|
+
if (!projectRepository) return null;
|
|
142
|
+
const connection = await args.github.sourceControlStorage.connections.get({
|
|
143
|
+
orgId: args.orgId,
|
|
144
|
+
id: projectRepository.connectionId
|
|
145
|
+
});
|
|
146
|
+
if (!connection) return null;
|
|
147
|
+
const repository = await args.github.sourceControlStorage.repositories.get({
|
|
148
|
+
orgId: args.orgId,
|
|
149
|
+
id: projectRepository.repositoryId
|
|
150
|
+
});
|
|
151
|
+
if (!repository) return null;
|
|
152
|
+
const installation = await args.github.sourceControlStorage.installations.get({
|
|
153
|
+
orgId: args.orgId,
|
|
154
|
+
id: connection.installationId
|
|
155
|
+
});
|
|
156
|
+
if (!installation) return null;
|
|
157
|
+
return {
|
|
158
|
+
...projectRepository,
|
|
159
|
+
connection,
|
|
160
|
+
installation,
|
|
161
|
+
repository,
|
|
162
|
+
factoryProjectId: connection.factoryProjectId,
|
|
163
|
+
defaultBranch: projectRepository.branch ?? repository.defaultBranch
|
|
164
|
+
};
|
|
844
165
|
}
|
|
845
166
|
function polledIssueEvent(project, issue) {
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
167
|
+
const repositoryId = Number(project.repository.externalId);
|
|
168
|
+
return {
|
|
169
|
+
event: "issues",
|
|
170
|
+
deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
|
|
171
|
+
payload: {
|
|
172
|
+
action: "opened",
|
|
173
|
+
installation: { id: Number(project.installation.externalId) },
|
|
174
|
+
repository: {
|
|
175
|
+
id: repositoryId,
|
|
176
|
+
full_name: project.repository.slug
|
|
177
|
+
},
|
|
178
|
+
sender: { login: issue.author ?? "__unknown__" },
|
|
179
|
+
issue: {
|
|
180
|
+
number: issue.number,
|
|
181
|
+
title: issue.title,
|
|
182
|
+
html_url: issue.url,
|
|
183
|
+
created_at: issue.createdAt,
|
|
184
|
+
labels: issue.labels.map((name) => ({ name }))
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
864
188
|
}
|
|
865
189
|
function polledPullRequestEvent(project, pullRequest) {
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
190
|
+
const repositoryId = Number(project.repository.externalId);
|
|
191
|
+
return {
|
|
192
|
+
event: "pull_request",
|
|
193
|
+
deliveryId: `poll:${repositoryId}:pull-request:${pullRequest.number}:${pullRequest.createdAt}`,
|
|
194
|
+
payload: {
|
|
195
|
+
action: "opened",
|
|
196
|
+
installation: { id: Number(project.installation.externalId) },
|
|
197
|
+
repository: {
|
|
198
|
+
id: repositoryId,
|
|
199
|
+
full_name: project.repository.slug
|
|
200
|
+
},
|
|
201
|
+
sender: { login: pullRequest.author ?? "__unknown__" },
|
|
202
|
+
pull_request: {
|
|
203
|
+
number: pullRequest.number,
|
|
204
|
+
title: pullRequest.title,
|
|
205
|
+
html_url: pullRequest.url,
|
|
206
|
+
created_at: pullRequest.createdAt,
|
|
207
|
+
state: "open",
|
|
208
|
+
merged: false,
|
|
209
|
+
head: { ref: pullRequest.headBranch },
|
|
210
|
+
base: { ref: pullRequest.baseBranch }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
887
214
|
}
|
|
888
215
|
async function ingestPolledEvents(events, ingestFactoryEvent) {
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
216
|
+
if (!ingestFactoryEvent) return;
|
|
217
|
+
const rejected = (await Promise.allSettled(events.map((event) => ingestFactoryEvent(event)))).find((result) => result.status === "rejected");
|
|
218
|
+
if (rejected) throw rejected.reason;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Build the GitHub routes as Mastra `apiRoutes`. When the feature is disabled,
|
|
222
|
+
* returns only the `status` route so the SPA can detect the disabled state.
|
|
223
|
+
*/
|
|
894
224
|
function buildGithubRoutes(options) {
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
return routes;
|
|
1439
|
-
}
|
|
225
|
+
const routes = [];
|
|
226
|
+
const { auth, fleet, storage, github, stateSigner, emitAudit } = options;
|
|
227
|
+
const diagnostics = () => getGithubFeatureDiagnostics({
|
|
228
|
+
github,
|
|
229
|
+
auth,
|
|
230
|
+
appDbConfigured: storage !== void 0,
|
|
231
|
+
stateSigner,
|
|
232
|
+
fleet
|
|
233
|
+
});
|
|
234
|
+
routes.push(registerApiRoute("/web/github/status", {
|
|
235
|
+
method: "GET",
|
|
236
|
+
requiresAuth: false,
|
|
237
|
+
handler: async (c) => {
|
|
238
|
+
if (!isGithubFeatureEnabled({
|
|
239
|
+
github,
|
|
240
|
+
auth
|
|
241
|
+
}) || !github || !stateSigner) return c.json({
|
|
242
|
+
enabled: false,
|
|
243
|
+
connected: false,
|
|
244
|
+
installations: [],
|
|
245
|
+
reason: "missing_config",
|
|
246
|
+
diagnostics: diagnostics()
|
|
247
|
+
});
|
|
248
|
+
await auth.ensureUser(loose(c));
|
|
249
|
+
const tenant = auth.tenant(loose(c));
|
|
250
|
+
if (!tenant) return c.json({
|
|
251
|
+
error: "unauthorized",
|
|
252
|
+
reason: "auth_required"
|
|
253
|
+
}, 401);
|
|
254
|
+
if (!tenant.orgId) return c.json({
|
|
255
|
+
enabled: true,
|
|
256
|
+
sandboxEnabled: fleet.enabled,
|
|
257
|
+
organizationRequired: true,
|
|
258
|
+
connected: false,
|
|
259
|
+
installations: [],
|
|
260
|
+
reason: "organization_required",
|
|
261
|
+
diagnostics: diagnostics()
|
|
262
|
+
});
|
|
263
|
+
const rows = options.github ? await options.github.sourceControlStorage.installations.list({ orgId: tenant.orgId }) : [];
|
|
264
|
+
const connected = rows.length > 0;
|
|
265
|
+
return c.json({
|
|
266
|
+
enabled: true,
|
|
267
|
+
sandboxEnabled: fleet.enabled,
|
|
268
|
+
connected,
|
|
269
|
+
installations: rows.map((r) => ({
|
|
270
|
+
installationId: Number(r.externalId),
|
|
271
|
+
accountLogin: r.accountName,
|
|
272
|
+
accountType: r.accountType
|
|
273
|
+
})),
|
|
274
|
+
reason: connected ? "ready" : "not_connected",
|
|
275
|
+
diagnostics: diagnostics()
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}));
|
|
279
|
+
if (!isGithubFeatureEnabled({
|
|
280
|
+
github,
|
|
281
|
+
auth
|
|
282
|
+
}) || !github || !stateSigner) return routes;
|
|
283
|
+
const signState = (orgId, userId) => stateSigner.sign(orgId, userId);
|
|
284
|
+
const verifyState = (state) => stateSigner.verify(state);
|
|
285
|
+
const { runIssueTriage } = options;
|
|
286
|
+
const runBoardIssueTriage = runIssueTriage ? async (input) => {
|
|
287
|
+
if (!input.resourceId || !input.projectPath) throw new Error("GitHub issue triage requires an explicit Factory project repository");
|
|
288
|
+
await github.addIssueLabels(input.installationId, input.repository, input.issueNumber, ["auto-triaged"]);
|
|
289
|
+
return runIssueTriage({
|
|
290
|
+
...input,
|
|
291
|
+
defaultModelId: input.defaultModelId ?? await resolveFactoryDefaultModelId(options.projects, input.resourceId),
|
|
292
|
+
labels: input.labels.includes("auto-triaged") ? input.labels : [...input.labels, "auto-triaged"]
|
|
293
|
+
});
|
|
294
|
+
} : void 0;
|
|
295
|
+
routes.push(registerApiRoute("/web/github/subscriptions", {
|
|
296
|
+
method: "GET",
|
|
297
|
+
handler: async (c) => {
|
|
298
|
+
await auth.ensureUser(loose(c));
|
|
299
|
+
const tenant = auth.tenant(loose(c));
|
|
300
|
+
if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
|
|
301
|
+
const resourceId = c.req.query("resourceId");
|
|
302
|
+
const threadId = c.req.query("threadId");
|
|
303
|
+
const sessionScope = c.req.query("scope");
|
|
304
|
+
if (!resourceId || !threadId) return c.json({ error: "resourceId and threadId are required" }, 400);
|
|
305
|
+
const subscriptions = await listPullRequestSubscriptionsForThread({
|
|
306
|
+
orgId: tenant.orgId,
|
|
307
|
+
resourceId,
|
|
308
|
+
threadId,
|
|
309
|
+
sessionScope
|
|
310
|
+
}, github.integrationStorage);
|
|
311
|
+
return c.json({ subscriptions: subscriptions.map((subscription) => ({
|
|
312
|
+
id: subscription.id,
|
|
313
|
+
repoFullName: subscription.data.repositorySlug,
|
|
314
|
+
pullRequestNumber: Number(subscription.data.changeRequestId),
|
|
315
|
+
status: subscription.status,
|
|
316
|
+
url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
|
|
317
|
+
})) });
|
|
318
|
+
}
|
|
319
|
+
}), registerApiRoute("/web/github/webhook", {
|
|
320
|
+
method: "POST",
|
|
321
|
+
requiresAuth: false,
|
|
322
|
+
handler: async (c) => {
|
|
323
|
+
const result = await handleGithubWebhook(loose(c), {
|
|
324
|
+
github,
|
|
325
|
+
runIssueTriage: runBoardIssueTriage,
|
|
326
|
+
ingestFactoryEvent: options.ingestFactoryEvent,
|
|
327
|
+
...options.controller ? {
|
|
328
|
+
controller: options.controller,
|
|
329
|
+
onTargetError: (subscription, error) => {
|
|
330
|
+
console.warn(`[GitHub Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`, error);
|
|
331
|
+
}
|
|
332
|
+
} : {}
|
|
333
|
+
});
|
|
334
|
+
return c.json(result.body, result.status);
|
|
335
|
+
}
|
|
336
|
+
}));
|
|
337
|
+
const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? "").replace(/\/$/, "")}/auth/github/callback`;
|
|
338
|
+
routes.push(registerApiRoute("/auth/github/connect", {
|
|
339
|
+
method: "GET",
|
|
340
|
+
requiresAuth: false,
|
|
341
|
+
handler: async (c) => {
|
|
342
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
343
|
+
if ("response" in resolved) return resolved.response;
|
|
344
|
+
const state = signState(resolved.tenant.orgId, resolved.tenant.userId);
|
|
345
|
+
if (c.req.query("manage")) return c.redirect(github.buildInstallUrl(state));
|
|
346
|
+
return c.redirect(github.buildOAuthIdentifyUrl(state, redirectUri));
|
|
347
|
+
}
|
|
348
|
+
}));
|
|
349
|
+
routes.push(registerApiRoute("/auth/github/callback", {
|
|
350
|
+
method: "GET",
|
|
351
|
+
requiresAuth: false,
|
|
352
|
+
handler: async (c) => {
|
|
353
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
354
|
+
if ("response" in resolved) return resolved.response;
|
|
355
|
+
const { orgId, userId } = resolved.tenant;
|
|
356
|
+
const state = c.req.query("state");
|
|
357
|
+
if (!state) return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
|
|
358
|
+
const stateTenant = verifyState(state);
|
|
359
|
+
if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {
|
|
360
|
+
console.warn("[GitHub] Install callback rejected: state/tenant mismatch.", JSON.stringify({
|
|
361
|
+
stateValid: Boolean(stateTenant),
|
|
362
|
+
stateOrgId: stateTenant?.orgId,
|
|
363
|
+
stateUserId: stateTenant?.userId,
|
|
364
|
+
sessionOrgId: orgId,
|
|
365
|
+
sessionUserId: userId
|
|
366
|
+
}));
|
|
367
|
+
return c.redirect("/?github=error");
|
|
368
|
+
}
|
|
369
|
+
const code = c.req.query("code");
|
|
370
|
+
if (!code) return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
|
|
371
|
+
try {
|
|
372
|
+
const userToken = await github.exchangeOAuthCode(code, redirectUri);
|
|
373
|
+
const installations = await github.listUserInstallations(userToken);
|
|
374
|
+
if (installations.length === 0) return c.redirect(github.buildInstallUrl(signState(orgId, userId)));
|
|
375
|
+
for (const inst of installations) await github.sourceControlStorage.installations.upsert({
|
|
376
|
+
orgId,
|
|
377
|
+
connectedByUserId: userId,
|
|
378
|
+
externalId: inst.installationId.toString(),
|
|
379
|
+
accountName: inst.accountLogin,
|
|
380
|
+
accountType: inst.accountType
|
|
381
|
+
});
|
|
382
|
+
} catch (error) {
|
|
383
|
+
console.warn(`[GitHub] Install callback failed to persist installations for org ${orgId} / user ${userId}.`, error);
|
|
384
|
+
return c.redirect("/?github=error");
|
|
385
|
+
}
|
|
386
|
+
return c.redirect("/?github=connected");
|
|
387
|
+
}
|
|
388
|
+
}));
|
|
389
|
+
routes.push(registerApiRoute("/web/github/repos", {
|
|
390
|
+
method: "GET",
|
|
391
|
+
requiresAuth: false,
|
|
392
|
+
handler: async (c) => {
|
|
393
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
394
|
+
if ("response" in resolved) return resolved.response;
|
|
395
|
+
const orgId = resolved.tenant.orgId;
|
|
396
|
+
const installs = await github.sourceControlStorage.installations.list({ orgId });
|
|
397
|
+
const query = (c.req.query("q") ?? "").toLowerCase();
|
|
398
|
+
const listed = await Promise.all(installs.map(async (inst) => {
|
|
399
|
+
try {
|
|
400
|
+
return {
|
|
401
|
+
inst,
|
|
402
|
+
list: await github.listInstallationRepos(Number(inst.externalId))
|
|
403
|
+
};
|
|
404
|
+
} catch (err) {
|
|
405
|
+
if (err.status !== 404) throw err;
|
|
406
|
+
console.error(`[Mastra Factory] pruning stale GitHub installation ${inst.externalId} (404 from GitHub)`);
|
|
407
|
+
await github.sourceControlStorage.installations.delete({
|
|
408
|
+
orgId,
|
|
409
|
+
id: inst.id
|
|
410
|
+
});
|
|
411
|
+
return {
|
|
412
|
+
inst,
|
|
413
|
+
list: []
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
}));
|
|
417
|
+
const matches = [];
|
|
418
|
+
const seenRepositoryIds = /* @__PURE__ */ new Set();
|
|
419
|
+
for (const { inst, list } of listed) for (const repo of list) {
|
|
420
|
+
if (query && !repo.fullName.toLowerCase().includes(query)) continue;
|
|
421
|
+
if (seenRepositoryIds.has(repo.id)) continue;
|
|
422
|
+
seenRepositoryIds.add(repo.id);
|
|
423
|
+
matches.push({
|
|
424
|
+
inst,
|
|
425
|
+
repo
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
const repos = new Array(matches.length);
|
|
429
|
+
const upsertConcurrency = 10;
|
|
430
|
+
for (let start = 0; start < matches.length; start += upsertConcurrency) await Promise.all(matches.slice(start, start + upsertConcurrency).map(async ({ inst, repo }, offset) => {
|
|
431
|
+
const repository = await github.sourceControlStorage.repositories.upsert({
|
|
432
|
+
orgId,
|
|
433
|
+
input: {
|
|
434
|
+
installationId: inst.id,
|
|
435
|
+
externalId: repo.id.toString(),
|
|
436
|
+
slug: repo.fullName,
|
|
437
|
+
defaultBranch: isValidGitRef(repo.defaultBranch) ? repo.defaultBranch : "main",
|
|
438
|
+
providerMetadata: {
|
|
439
|
+
private: repo.private,
|
|
440
|
+
owner: repo.owner
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
repos[start + offset] = {
|
|
445
|
+
...repo,
|
|
446
|
+
installationStorageId: inst.id,
|
|
447
|
+
repositoryStorageId: repository.id,
|
|
448
|
+
sandboxProvider: fleet.provider,
|
|
449
|
+
sandboxWorkdir: fleet.computeWorkdir(repo.fullName)
|
|
450
|
+
};
|
|
451
|
+
}));
|
|
452
|
+
return c.json({ repos });
|
|
453
|
+
}
|
|
454
|
+
}));
|
|
455
|
+
routes.push(registerApiRoute("/web/github/projects/:id/ensure", {
|
|
456
|
+
method: "POST",
|
|
457
|
+
requiresAuth: false,
|
|
458
|
+
handler: async (c) => {
|
|
459
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
460
|
+
if ("response" in resolved) return resolved.response;
|
|
461
|
+
const { orgId, userId } = resolved.tenant;
|
|
462
|
+
if (!fleet.enabled) return c.json({
|
|
463
|
+
error: "sandbox_not_configured",
|
|
464
|
+
message: "No sandbox provider is configured."
|
|
465
|
+
}, 503);
|
|
466
|
+
const projectRepositoryId = c.req.param("id");
|
|
467
|
+
if (!projectRepositoryId) return c.json({ error: "Project repository not found" }, 404);
|
|
468
|
+
const project = await resolveProjectRepository({
|
|
469
|
+
github,
|
|
470
|
+
orgId,
|
|
471
|
+
projectRepositoryId
|
|
472
|
+
});
|
|
473
|
+
if (!project) return c.json({ error: "Project repository not found" }, 404);
|
|
474
|
+
if ((c.req.header("accept") ?? "").includes("text/event-stream")) return streamSSE(loose(c), async (stream) => {
|
|
475
|
+
try {
|
|
476
|
+
const result = await prepareProject({
|
|
477
|
+
github,
|
|
478
|
+
fleet,
|
|
479
|
+
project,
|
|
480
|
+
userId,
|
|
481
|
+
onProgress: (ev) => void stream.writeSSE({
|
|
482
|
+
event: "progress",
|
|
483
|
+
data: JSON.stringify(ev)
|
|
484
|
+
})
|
|
485
|
+
});
|
|
486
|
+
await stream.writeSSE({
|
|
487
|
+
event: "done",
|
|
488
|
+
data: JSON.stringify(result)
|
|
489
|
+
});
|
|
490
|
+
} catch (err) {
|
|
491
|
+
await stream.writeSSE({
|
|
492
|
+
event: "error",
|
|
493
|
+
data: JSON.stringify(ensureErrorPayload(err).body)
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
try {
|
|
498
|
+
const result = await prepareProject({
|
|
499
|
+
github,
|
|
500
|
+
fleet,
|
|
501
|
+
project,
|
|
502
|
+
userId
|
|
503
|
+
});
|
|
504
|
+
return c.json(result);
|
|
505
|
+
} catch (err) {
|
|
506
|
+
const { status, body } = ensureErrorPayload(err);
|
|
507
|
+
return c.json(body, status);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}));
|
|
511
|
+
routes.push(registerApiRoute("/web/github/projects/:id/issues", {
|
|
512
|
+
method: "GET",
|
|
513
|
+
requiresAuth: false,
|
|
514
|
+
handler: async (c) => {
|
|
515
|
+
const loaded = await loadOrgProject({
|
|
516
|
+
github,
|
|
517
|
+
auth,
|
|
518
|
+
c: loose(c)
|
|
519
|
+
});
|
|
520
|
+
if ("response" in loaded) return loaded.response;
|
|
521
|
+
const page = parseListPage(c.req.query("page"));
|
|
522
|
+
if (page === null) return c.json({ error: "invalid_page" }, 400);
|
|
523
|
+
const label = parseIssueLabelFilter(c.req.query("label"));
|
|
524
|
+
if (label === null) return c.json({ error: "invalid_label" }, 400);
|
|
525
|
+
try {
|
|
526
|
+
const { issues, nextCursor } = await github.intake.listIssues({
|
|
527
|
+
connection: {
|
|
528
|
+
type: "app-installation",
|
|
529
|
+
installationId: Number(loaded.project.installation.externalId)
|
|
530
|
+
},
|
|
531
|
+
sourceIds: [loaded.project.repository.slug],
|
|
532
|
+
labels: label ? [label] : void 0,
|
|
533
|
+
cursor: String(page)
|
|
534
|
+
});
|
|
535
|
+
const responseIssues = issues.map((issue) => ({
|
|
536
|
+
number: Number(issue.id),
|
|
537
|
+
title: issue.title,
|
|
538
|
+
url: issue.url,
|
|
539
|
+
author: issue.author,
|
|
540
|
+
labels: issue.labels,
|
|
541
|
+
comments: issue.commentCount ?? 0,
|
|
542
|
+
createdAt: issue.createdAt,
|
|
543
|
+
updatedAt: issue.updatedAt
|
|
544
|
+
}));
|
|
545
|
+
await ingestPolledEvents(responseIssues.map((issue) => polledIssueEvent(loaded.project, issue)), options.ingestFactoryEvent);
|
|
546
|
+
return c.json({
|
|
547
|
+
issues: responseIssues,
|
|
548
|
+
nextPage: nextCursor === null ? null : Number(nextCursor)
|
|
549
|
+
});
|
|
550
|
+
} catch (err) {
|
|
551
|
+
return c.json({
|
|
552
|
+
error: "github_fetch_failed",
|
|
553
|
+
message: err instanceof Error ? err.message : String(err)
|
|
554
|
+
}, 502);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}));
|
|
558
|
+
routes.push(registerApiRoute("/web/github/projects/:id/issues/:number/triage", {
|
|
559
|
+
method: "POST",
|
|
560
|
+
requiresAuth: false,
|
|
561
|
+
handler: async (c) => {
|
|
562
|
+
const owned = await loadOwnedProject({
|
|
563
|
+
github,
|
|
564
|
+
auth,
|
|
565
|
+
fleet,
|
|
566
|
+
c: loose(c)
|
|
567
|
+
});
|
|
568
|
+
if ("response" in owned) return owned.response;
|
|
569
|
+
const { project, sandboxRow } = owned;
|
|
570
|
+
const issueNumber = parseIssueNumberParam(c.req.param("number"));
|
|
571
|
+
if (issueNumber === null) return c.json({ error: "invalid_issue_number" }, 400);
|
|
572
|
+
let body;
|
|
573
|
+
try {
|
|
574
|
+
body = await c.req.json();
|
|
575
|
+
} catch {
|
|
576
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
577
|
+
}
|
|
578
|
+
if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 5e3) return c.json({ error: "invalid_title" }, 400);
|
|
579
|
+
if (typeof body.url !== "string" || body.url.trim().length === 0 || body.url.length > 2048 || !isCanonicalGithubIssueUrl(body.url, project.repository.slug, issueNumber)) return c.json({ error: "invalid_url" }, 400);
|
|
580
|
+
if (!runIssueTriage) return c.json({ error: "triage_unavailable" }, 503);
|
|
581
|
+
const branch = `factory/issue-${issueNumber}`;
|
|
582
|
+
const projectPath = computeWorktreePath(sandboxRow.sandboxWorkdir, branch);
|
|
583
|
+
await github.addIssueLabels(Number(project.installation.externalId), project.repository.slug, issueNumber, ["auto-triaged"]);
|
|
584
|
+
const result = await runIssueTriage({
|
|
585
|
+
repository: project.repository.slug,
|
|
586
|
+
issueNumber,
|
|
587
|
+
issueTitle: body.title,
|
|
588
|
+
issueUrl: body.url,
|
|
589
|
+
labels: parseStringList(body.labels),
|
|
590
|
+
installationId: Number(project.installation.externalId),
|
|
591
|
+
resourceId: project.factoryProjectId,
|
|
592
|
+
projectPath,
|
|
593
|
+
branch,
|
|
594
|
+
defaultModelId: await resolveFactoryDefaultModelId(options.projects, project.factoryProjectId)
|
|
595
|
+
});
|
|
596
|
+
await emitAudit?.({
|
|
597
|
+
context: loose(c),
|
|
598
|
+
input: {
|
|
599
|
+
action: "factory.triage.started",
|
|
600
|
+
factoryProjectId: project.factoryProjectId,
|
|
601
|
+
projectRepositoryId: project.id,
|
|
602
|
+
targets: [{
|
|
603
|
+
type: "issue",
|
|
604
|
+
id: String(issueNumber),
|
|
605
|
+
name: body.title
|
|
606
|
+
}],
|
|
607
|
+
metadata: {
|
|
608
|
+
issueNumber,
|
|
609
|
+
branch,
|
|
610
|
+
threadId: result.threadId
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
return c.json({
|
|
615
|
+
ok: true,
|
|
616
|
+
threadId: result.threadId,
|
|
617
|
+
projectPath: result.projectPath ?? projectPath,
|
|
618
|
+
branch: result.branch ?? branch
|
|
619
|
+
}, 202);
|
|
620
|
+
}
|
|
621
|
+
}));
|
|
622
|
+
routes.push(registerApiRoute("/web/github/projects/:id/prs", {
|
|
623
|
+
method: "GET",
|
|
624
|
+
requiresAuth: false,
|
|
625
|
+
handler: async (c) => {
|
|
626
|
+
const loaded = await loadOrgProject({
|
|
627
|
+
github,
|
|
628
|
+
auth,
|
|
629
|
+
c: loose(c)
|
|
630
|
+
});
|
|
631
|
+
if ("response" in loaded) return loaded.response;
|
|
632
|
+
const page = parseListPage(c.req.query("page"));
|
|
633
|
+
if (page === null) return c.json({ error: "invalid_page" }, 400);
|
|
634
|
+
try {
|
|
635
|
+
const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
|
|
636
|
+
connection: {
|
|
637
|
+
type: "app-installation",
|
|
638
|
+
installationId: Number(loaded.project.installation.externalId)
|
|
639
|
+
},
|
|
640
|
+
sourceId: loaded.project.repository.slug,
|
|
641
|
+
includeDrafts: false,
|
|
642
|
+
cursor: String(page)
|
|
643
|
+
});
|
|
644
|
+
const responsePullRequests = pullRequests.map((pr) => ({
|
|
645
|
+
number: Number(pr.id),
|
|
646
|
+
title: pr.title,
|
|
647
|
+
url: pr.url,
|
|
648
|
+
author: pr.author,
|
|
649
|
+
baseBranch: pr.baseBranch,
|
|
650
|
+
headBranch: pr.headBranch,
|
|
651
|
+
createdAt: pr.createdAt,
|
|
652
|
+
updatedAt: pr.updatedAt
|
|
653
|
+
}));
|
|
654
|
+
await ingestPolledEvents(responsePullRequests.map((pullRequest) => polledPullRequestEvent(loaded.project, pullRequest)), options.ingestFactoryEvent);
|
|
655
|
+
return c.json({
|
|
656
|
+
pullRequests: responsePullRequests,
|
|
657
|
+
nextPage: nextCursor === null ? null : Number(nextCursor)
|
|
658
|
+
});
|
|
659
|
+
} catch (err) {
|
|
660
|
+
return c.json({
|
|
661
|
+
error: "github_fetch_failed",
|
|
662
|
+
message: err instanceof Error ? err.message : String(err)
|
|
663
|
+
}, 502);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}));
|
|
667
|
+
routes.push(registerApiRoute("/web/github/projects/:id/settings", {
|
|
668
|
+
method: "GET",
|
|
669
|
+
requiresAuth: false,
|
|
670
|
+
handler: async (c) => {
|
|
671
|
+
const loaded = await loadOrgProject({
|
|
672
|
+
github,
|
|
673
|
+
auth,
|
|
674
|
+
c: loose(c)
|
|
675
|
+
});
|
|
676
|
+
if ("response" in loaded) return loaded.response;
|
|
677
|
+
return c.json({ setupCommand: loaded.project.setupCommand });
|
|
678
|
+
}
|
|
679
|
+
}));
|
|
680
|
+
routes.push(registerApiRoute("/web/github/projects/:id/settings", {
|
|
681
|
+
method: "POST",
|
|
682
|
+
requiresAuth: false,
|
|
683
|
+
handler: async (c) => {
|
|
684
|
+
const loaded = await loadOrgProject({
|
|
685
|
+
github,
|
|
686
|
+
auth,
|
|
687
|
+
c: loose(c)
|
|
688
|
+
});
|
|
689
|
+
if ("response" in loaded) return loaded.response;
|
|
690
|
+
let body;
|
|
691
|
+
try {
|
|
692
|
+
body = await c.req.json();
|
|
693
|
+
} catch {
|
|
694
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
695
|
+
}
|
|
696
|
+
if (body.setupCommand !== null && typeof body.setupCommand !== "string") return c.json({ error: "Invalid setupCommand" }, 400);
|
|
697
|
+
if (typeof body.setupCommand === "string" && body.setupCommand.length > 2e3) return c.json({ error: "setupCommand too long (max 2000 characters)" }, 400);
|
|
698
|
+
if (typeof body.setupCommand === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.setupCommand)) return c.json({ error: "setupCommand contains control characters" }, 400);
|
|
699
|
+
const setupCommand = typeof body.setupCommand === "string" && body.setupCommand.trim().length > 0 ? body.setupCommand.trim() : null;
|
|
700
|
+
await github.sourceControlStorage.projectRepositories.update({
|
|
701
|
+
orgId: loaded.project.installation.orgId,
|
|
702
|
+
id: loaded.project.id,
|
|
703
|
+
input: { setupCommand }
|
|
704
|
+
});
|
|
705
|
+
return c.json({ setupCommand });
|
|
706
|
+
}
|
|
707
|
+
}));
|
|
708
|
+
const parsePatKind = (value) => {
|
|
709
|
+
if (value === void 0 || value === null || value === "default") return "default";
|
|
710
|
+
if (value === "reviewer") return "reviewer";
|
|
711
|
+
return null;
|
|
712
|
+
};
|
|
713
|
+
routes.push(registerApiRoute("/web/github/pat", {
|
|
714
|
+
method: "GET",
|
|
715
|
+
requiresAuth: false,
|
|
716
|
+
handler: async (c) => {
|
|
717
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
718
|
+
if ("response" in resolved) return resolved.response;
|
|
719
|
+
return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
|
|
720
|
+
}
|
|
721
|
+
}), registerApiRoute("/web/github/pat", {
|
|
722
|
+
method: "POST",
|
|
723
|
+
requiresAuth: false,
|
|
724
|
+
handler: async (c) => {
|
|
725
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
726
|
+
if ("response" in resolved) return resolved.response;
|
|
727
|
+
let body;
|
|
728
|
+
try {
|
|
729
|
+
body = await c.req.json();
|
|
730
|
+
} catch {
|
|
731
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
732
|
+
}
|
|
733
|
+
const kind = parsePatKind(body.kind);
|
|
734
|
+
if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
|
|
735
|
+
const token = typeof body.token === "string" ? body.token.trim() : "";
|
|
736
|
+
if (!token) return c.json({ error: "A token is required" }, 400);
|
|
737
|
+
if (token.length > 500) return c.json({ error: "Token too long (max 500 characters)" }, 400);
|
|
738
|
+
if (/\s/.test(token)) return c.json({ error: "Token must not contain whitespace" }, 400);
|
|
739
|
+
await setGithubPat(github.integrationStorage, resolved.tenant.orgId, token, kind);
|
|
740
|
+
return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
|
|
741
|
+
}
|
|
742
|
+
}), registerApiRoute("/web/github/pat", {
|
|
743
|
+
method: "DELETE",
|
|
744
|
+
requiresAuth: false,
|
|
745
|
+
handler: async (c) => {
|
|
746
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
747
|
+
if ("response" in resolved) return resolved.response;
|
|
748
|
+
const kind = parsePatKind(c.req.query("kind"));
|
|
749
|
+
if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
|
|
750
|
+
await clearGithubPat(github.integrationStorage, resolved.tenant.orgId, kind);
|
|
751
|
+
return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
|
|
752
|
+
}
|
|
753
|
+
}));
|
|
754
|
+
routes.push(...buildProjectGitRoutes({
|
|
755
|
+
github,
|
|
756
|
+
auth,
|
|
757
|
+
fleet,
|
|
758
|
+
emitAudit
|
|
759
|
+
}));
|
|
760
|
+
return routes;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Load the org-owned project for a read-only GitHub API route. Unlike
|
|
764
|
+
* `loadOwnedProject`, this never touches sandbox state — the issues/PR list
|
|
765
|
+
* routes only need the repo + installation, so they work before a sandbox is
|
|
766
|
+
* ever provisioned.
|
|
767
|
+
*/
|
|
1440
768
|
async function loadOrgProject(options) {
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
769
|
+
const { github, auth, c } = options;
|
|
770
|
+
const resolved = await resolveOrgTenant(c, auth);
|
|
771
|
+
if ("response" in resolved) return { response: resolved.response };
|
|
772
|
+
const { orgId, userId } = resolved.tenant;
|
|
773
|
+
const projectRepositoryId = c.req.param("id");
|
|
774
|
+
if (!projectRepositoryId) return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
775
|
+
const project = await resolveProjectRepository({
|
|
776
|
+
github,
|
|
777
|
+
orgId,
|
|
778
|
+
projectRepositoryId
|
|
779
|
+
});
|
|
780
|
+
if (!project) return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
781
|
+
return {
|
|
782
|
+
project,
|
|
783
|
+
userId
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/** Derive a commit/author identity from the authenticated host user. */
|
|
1455
787
|
function identityFromUser(user) {
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
788
|
+
const u = user;
|
|
789
|
+
return {
|
|
790
|
+
name: u?.name ?? null,
|
|
791
|
+
email: u?.email ?? null
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Resolve a live, started sandbox for the caller's per-user sandbox binding. The
|
|
796
|
+
* sandbox must already have been provisioned (`sandboxId` set) — the git write
|
|
797
|
+
* routes never clone, they operate on the existing checkout.
|
|
798
|
+
*/
|
|
1459
799
|
async function resolveProjectSandbox(options) {
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
800
|
+
const { fleet, sandboxRow } = options;
|
|
801
|
+
if (!sandboxRow.sandboxId) throw new MaterializeError("Project sandbox is not provisioned. Open the project first.", "clone-failed");
|
|
802
|
+
return fleet.reattachSandbox(sandboxRow.sandboxId);
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Load (or create) the caller's per-(project,user) sandbox binding row. The
|
|
806
|
+
* binding inherits its workdir from the org-owned project, but `sandboxId` /
|
|
807
|
+
* `materializedAt` stay null until the user first opens the project.
|
|
808
|
+
*/
|
|
1466
809
|
async function loadOrCreateSandboxRow(github, project, userId) {
|
|
1467
|
-
|
|
1468
|
-
|
|
810
|
+
return github.sourceControlStorage.sandboxes.getOrCreate({
|
|
811
|
+
projectRepository: project,
|
|
812
|
+
userId
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Provision/reattach the caller's sandbox and materialize the repo into it,
|
|
817
|
+
* emitting coarse progress events as each server step happens. Shared by both
|
|
818
|
+
* the JSON and SSE variants of the `/ensure` route. Throws on failure so the
|
|
819
|
+
* caller can shape the response (HTTP status vs SSE `error` event).
|
|
820
|
+
*/
|
|
1469
821
|
async function prepareProject(options) {
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
}
|
|
822
|
+
const { github, fleet, userId, onProgress } = options;
|
|
823
|
+
let project = options.project;
|
|
824
|
+
if (project.sandboxProvider !== fleet.provider) {
|
|
825
|
+
const sandboxWorkdir = fleet.computeWorkdir(project.repository.slug);
|
|
826
|
+
await github.sourceControlStorage.projectRepositories.update({
|
|
827
|
+
orgId: project.installation.orgId,
|
|
828
|
+
id: project.id,
|
|
829
|
+
input: {
|
|
830
|
+
sandboxProvider: fleet.provider,
|
|
831
|
+
sandboxWorkdir
|
|
832
|
+
}
|
|
833
|
+
});
|
|
834
|
+
project = {
|
|
835
|
+
...project,
|
|
836
|
+
sandboxProvider: fleet.provider,
|
|
837
|
+
sandboxWorkdir
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
let sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
|
|
841
|
+
if (sandboxRow.sandboxWorkdir !== project.sandboxWorkdir) {
|
|
842
|
+
await github.sourceControlStorage.sandboxes.setWorkdir({
|
|
843
|
+
id: sandboxRow.id,
|
|
844
|
+
sandboxWorkdir: project.sandboxWorkdir
|
|
845
|
+
});
|
|
846
|
+
sandboxRow = {
|
|
847
|
+
...sandboxRow,
|
|
848
|
+
sandboxWorkdir: project.sandboxWorkdir,
|
|
849
|
+
materializedAt: null
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
const access = await github.versionControl.getRepositoryAccess({
|
|
853
|
+
orgId: project.installation.orgId,
|
|
854
|
+
repositoryId: project.repository.id
|
|
855
|
+
});
|
|
856
|
+
if (!access.authorization) throw new MaterializeError("Repository access did not include a bearer token.", "clone-failed");
|
|
857
|
+
const ghCliToken = await getGithubPat(() => github.integrationStorage, project.installation.orgId) ?? access.authorization.token;
|
|
858
|
+
const sandbox = await ensureProjectSandbox({
|
|
859
|
+
fleet,
|
|
860
|
+
row: sandboxRow,
|
|
861
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
862
|
+
token: ghCliToken,
|
|
863
|
+
onProgress
|
|
864
|
+
});
|
|
865
|
+
const finalRow = await github.sourceControlStorage.sandboxes.getById({ id: sandboxRow.id }) ?? sandboxRow;
|
|
866
|
+
await materializeRepo({
|
|
867
|
+
row: finalRow,
|
|
868
|
+
repoInfo: {
|
|
869
|
+
repoFullName: project.repository.slug,
|
|
870
|
+
defaultBranch: project.defaultBranch
|
|
871
|
+
},
|
|
872
|
+
sandbox,
|
|
873
|
+
token: access.authorization.token,
|
|
874
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
875
|
+
onProgress
|
|
876
|
+
});
|
|
877
|
+
const result = {
|
|
878
|
+
resourceId: project.factoryProjectId,
|
|
879
|
+
factoryProjectId: project.factoryProjectId,
|
|
880
|
+
projectRepositoryId: project.id,
|
|
881
|
+
sandboxId: finalRow.sandboxId,
|
|
882
|
+
sandboxWorkdir: finalRow.sandboxWorkdir
|
|
883
|
+
};
|
|
884
|
+
onProgress?.({
|
|
885
|
+
phase: "done",
|
|
886
|
+
message: "Workspace ready."
|
|
887
|
+
});
|
|
888
|
+
return result;
|
|
889
|
+
}
|
|
890
|
+
/** Shape an /ensure failure into an HTTP status + JSON body (also used as the SSE error payload). */
|
|
1525
891
|
function ensureErrorPayload(err) {
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
892
|
+
if (err instanceof SandboxBudgetError) return {
|
|
893
|
+
status: 429,
|
|
894
|
+
body: {
|
|
895
|
+
error: err.code,
|
|
896
|
+
message: err.message
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
if (err instanceof MaterializeError) return {
|
|
900
|
+
status: 502,
|
|
901
|
+
body: {
|
|
902
|
+
error: err.code,
|
|
903
|
+
message: err.message
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
return {
|
|
907
|
+
status: 500,
|
|
908
|
+
body: {
|
|
909
|
+
error: "materialize_failed",
|
|
910
|
+
message: err instanceof Error ? err.message : String(err)
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
/** Map a sandbox/worktree error to an actionable HTTP response. */
|
|
1537
915
|
function gitErrorResponse(c, err) {
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
}
|
|
916
|
+
if (err instanceof WorktreeError) return c.json({
|
|
917
|
+
error: err.code,
|
|
918
|
+
message: err.message
|
|
919
|
+
}, err.code === "invalid-branch" ? 400 : 502);
|
|
920
|
+
if (err instanceof MaterializeError) return c.json({
|
|
921
|
+
error: err.code,
|
|
922
|
+
message: err.message
|
|
923
|
+
}, 502);
|
|
924
|
+
return c.json({
|
|
925
|
+
error: "git_failed",
|
|
926
|
+
message: err instanceof Error ? err.message : String(err)
|
|
927
|
+
}, 500);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Load the org-owned project and the caller's per-user sandbox binding for a git
|
|
931
|
+
* route. Centralizes the auth + org/ownership checks every git route shares:
|
|
932
|
+
* the project is scoped by `(id, orgId)`, the sandbox binding by
|
|
933
|
+
* `(projectRepositoryId, userId)`. Returns the tenant, project, and sandbox row, or
|
|
934
|
+
* a ready-to-return error response.
|
|
935
|
+
*/
|
|
1546
936
|
async function loadOwnedProject(options) {
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
}
|
|
937
|
+
const { github, auth, fleet, c } = options;
|
|
938
|
+
const resolved = await resolveOrgTenant(c, auth);
|
|
939
|
+
if ("response" in resolved) return { response: resolved.response };
|
|
940
|
+
const { orgId, userId } = resolved.tenant;
|
|
941
|
+
if (!fleet.enabled) return { response: c.json({
|
|
942
|
+
error: "sandbox_not_configured",
|
|
943
|
+
message: "No sandbox provider is configured."
|
|
944
|
+
}, 503) };
|
|
945
|
+
const projectRepositoryId = c.req.param("id");
|
|
946
|
+
if (!projectRepositoryId) return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
947
|
+
const project = await resolveProjectRepository({
|
|
948
|
+
github,
|
|
949
|
+
orgId,
|
|
950
|
+
projectRepositoryId
|
|
951
|
+
});
|
|
952
|
+
if (!project) return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
953
|
+
return {
|
|
954
|
+
orgId,
|
|
955
|
+
userId,
|
|
956
|
+
project,
|
|
957
|
+
sandboxRow: await loadOrCreateSandboxRow(github, project, userId)
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
function buildProjectGitRoutes({ github, auth, fleet, emitAudit }) {
|
|
961
|
+
return [
|
|
962
|
+
registerApiRoute("/web/github/projects/:id/sessions", {
|
|
963
|
+
method: "GET",
|
|
964
|
+
requiresAuth: false,
|
|
965
|
+
handler: async (c) => {
|
|
966
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
967
|
+
if ("response" in resolved) return resolved.response;
|
|
968
|
+
const { orgId, userId } = resolved.tenant;
|
|
969
|
+
const projectRepositoryId = c.req.param("id");
|
|
970
|
+
const project = projectRepositoryId ? await resolveProjectRepository({
|
|
971
|
+
github,
|
|
972
|
+
orgId,
|
|
973
|
+
projectRepositoryId
|
|
974
|
+
}) : null;
|
|
975
|
+
if (!project) return c.json({ error: "Project repository not found" }, 404);
|
|
976
|
+
const sessions = await github.sourceControlStorage.sessions.list({
|
|
977
|
+
projectRepositoryId: project.id,
|
|
978
|
+
userId
|
|
979
|
+
});
|
|
980
|
+
return c.json({ sessions });
|
|
981
|
+
}
|
|
982
|
+
}),
|
|
983
|
+
registerApiRoute("/web/github/projects/:id/sessions", {
|
|
984
|
+
method: "POST",
|
|
985
|
+
requiresAuth: false,
|
|
986
|
+
handler: async (c) => {
|
|
987
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
988
|
+
if ("response" in resolved) return resolved.response;
|
|
989
|
+
const { orgId, userId } = resolved.tenant;
|
|
990
|
+
const projectRepositoryId = c.req.param("id");
|
|
991
|
+
const project = projectRepositoryId ? await resolveProjectRepository({
|
|
992
|
+
github,
|
|
993
|
+
orgId,
|
|
994
|
+
projectRepositoryId
|
|
995
|
+
}) : null;
|
|
996
|
+
if (!project) return c.json({ error: "Project repository not found" }, 404);
|
|
997
|
+
let body;
|
|
998
|
+
try {
|
|
999
|
+
body = await c.req.json();
|
|
1000
|
+
} catch {
|
|
1001
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1002
|
+
}
|
|
1003
|
+
if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
|
|
1004
|
+
const baseBranch = body.baseBranch === void 0 ? project.defaultBranch : body.baseBranch;
|
|
1005
|
+
if (!isValidGitRef$1(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
|
|
1006
|
+
const session = await github.sourceControlStorage.sessions.create({
|
|
1007
|
+
sessionId: randomUUID(),
|
|
1008
|
+
projectRepositoryId: project.id,
|
|
1009
|
+
orgId,
|
|
1010
|
+
userId,
|
|
1011
|
+
branch: body.branch,
|
|
1012
|
+
baseBranch
|
|
1013
|
+
});
|
|
1014
|
+
return c.json({ session });
|
|
1015
|
+
}
|
|
1016
|
+
}),
|
|
1017
|
+
registerApiRoute("/web/user-sessions/:sessionId", {
|
|
1018
|
+
method: "GET",
|
|
1019
|
+
requiresAuth: false,
|
|
1020
|
+
handler: async (c) => {
|
|
1021
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1022
|
+
if ("response" in resolved) return resolved.response;
|
|
1023
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
|
|
1024
|
+
if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
|
|
1025
|
+
return c.json({ session });
|
|
1026
|
+
}
|
|
1027
|
+
}),
|
|
1028
|
+
registerApiRoute("/web/user-sessions/:sessionId", {
|
|
1029
|
+
method: "DELETE",
|
|
1030
|
+
requiresAuth: false,
|
|
1031
|
+
handler: async (c) => {
|
|
1032
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1033
|
+
if ("response" in resolved) return resolved.response;
|
|
1034
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
|
|
1035
|
+
if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
|
|
1036
|
+
let sandbox;
|
|
1037
|
+
if (session.sandboxId) {
|
|
1038
|
+
try {
|
|
1039
|
+
sandbox = await fleet.reattachSandbox(session.sandboxId);
|
|
1040
|
+
} catch {}
|
|
1041
|
+
await fleet.teardownSandbox({
|
|
1042
|
+
sandboxId: session.sandboxId,
|
|
1043
|
+
setSandboxId: async () => {},
|
|
1044
|
+
clear: async () => {
|
|
1045
|
+
await github.sourceControlStorage.sessions.setSandbox({
|
|
1046
|
+
id: session.id,
|
|
1047
|
+
sandboxId: null,
|
|
1048
|
+
sandboxWorkdir: session.sandboxWorkdir ?? ""
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
}, sandbox);
|
|
1052
|
+
}
|
|
1053
|
+
await github.sourceControlStorage.sessions.delete(session.id);
|
|
1054
|
+
return c.json({ removed: true });
|
|
1055
|
+
}
|
|
1056
|
+
}),
|
|
1057
|
+
registerApiRoute("/web/github/projects/:id/commit", {
|
|
1058
|
+
method: "POST",
|
|
1059
|
+
requiresAuth: false,
|
|
1060
|
+
handler: async (c) => {
|
|
1061
|
+
const owned = await loadOwnedProject({
|
|
1062
|
+
github,
|
|
1063
|
+
auth,
|
|
1064
|
+
fleet,
|
|
1065
|
+
c: loose(c)
|
|
1066
|
+
});
|
|
1067
|
+
if ("response" in owned) return owned.response;
|
|
1068
|
+
const { userId, project } = owned;
|
|
1069
|
+
let body;
|
|
1070
|
+
try {
|
|
1071
|
+
body = await c.req.json();
|
|
1072
|
+
} catch {
|
|
1073
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1074
|
+
}
|
|
1075
|
+
if (typeof body.message !== "string" || body.message.trim().length === 0 || body.message.length > 5e3) return c.json({ error: "Invalid message" }, 400);
|
|
1076
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1077
|
+
if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
|
|
1078
|
+
const { workdir, sandboxBinding } = sessionWorkspace;
|
|
1079
|
+
try {
|
|
1080
|
+
return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
|
|
1081
|
+
const result = await commitAll(await resolveProjectSandbox({
|
|
1082
|
+
fleet,
|
|
1083
|
+
sandboxRow: sandboxBinding
|
|
1084
|
+
}), workdir, body.message, identityFromUser(await auth.ensureUser(loose(c))));
|
|
1085
|
+
if (result.committed) await emitAudit?.({
|
|
1086
|
+
context: loose(c),
|
|
1087
|
+
input: {
|
|
1088
|
+
action: "factory.git.commit",
|
|
1089
|
+
factoryProjectId: project.factoryProjectId,
|
|
1090
|
+
projectRepositoryId: project.id,
|
|
1091
|
+
targets: [{
|
|
1092
|
+
type: "session",
|
|
1093
|
+
id: sessionWorkspace.session.sessionId
|
|
1094
|
+
}],
|
|
1095
|
+
metadata: { sessionId: sessionWorkspace.session.sessionId }
|
|
1096
|
+
}
|
|
1097
|
+
});
|
|
1098
|
+
return c.json({ committed: result.committed });
|
|
1099
|
+
});
|
|
1100
|
+
} catch (err) {
|
|
1101
|
+
return gitErrorResponse(loose(c), err);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
}),
|
|
1105
|
+
registerApiRoute("/web/github/projects/:id/push", {
|
|
1106
|
+
method: "POST",
|
|
1107
|
+
requiresAuth: false,
|
|
1108
|
+
handler: async (c) => {
|
|
1109
|
+
const owned = await loadOwnedProject({
|
|
1110
|
+
github,
|
|
1111
|
+
auth,
|
|
1112
|
+
fleet,
|
|
1113
|
+
c: loose(c)
|
|
1114
|
+
});
|
|
1115
|
+
if ("response" in owned) return owned.response;
|
|
1116
|
+
const { orgId, userId, project } = owned;
|
|
1117
|
+
let body;
|
|
1118
|
+
try {
|
|
1119
|
+
body = await c.req.json();
|
|
1120
|
+
} catch {
|
|
1121
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1122
|
+
}
|
|
1123
|
+
if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
|
|
1124
|
+
const branch = body.branch;
|
|
1125
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1126
|
+
if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
|
|
1127
|
+
const { workdir, sandboxBinding } = sessionWorkspace;
|
|
1128
|
+
try {
|
|
1129
|
+
return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
|
|
1130
|
+
const sandbox = await resolveProjectSandbox({
|
|
1131
|
+
fleet,
|
|
1132
|
+
sandboxRow: sandboxBinding
|
|
1133
|
+
});
|
|
1134
|
+
const access = await github.versionControl.getRepositoryAccess({
|
|
1135
|
+
orgId,
|
|
1136
|
+
repositoryId: project.repository.id
|
|
1137
|
+
});
|
|
1138
|
+
if (!access.authorization) throw new Error("Repository access did not include a bearer token.");
|
|
1139
|
+
await pushBranch(sandbox, workdir, branch, access.authorization.token, project.repository.slug);
|
|
1140
|
+
await emitAudit?.({
|
|
1141
|
+
context: loose(c),
|
|
1142
|
+
input: {
|
|
1143
|
+
action: "factory.git.push",
|
|
1144
|
+
factoryProjectId: project.factoryProjectId,
|
|
1145
|
+
projectRepositoryId: project.id,
|
|
1146
|
+
targets: [{
|
|
1147
|
+
type: "branch",
|
|
1148
|
+
id: branch
|
|
1149
|
+
}],
|
|
1150
|
+
metadata: {
|
|
1151
|
+
branch,
|
|
1152
|
+
sessionId: sessionWorkspace.session.sessionId
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
return c.json({
|
|
1157
|
+
pushed: true,
|
|
1158
|
+
branch
|
|
1159
|
+
});
|
|
1160
|
+
});
|
|
1161
|
+
} catch (err) {
|
|
1162
|
+
return gitErrorResponse(loose(c), err);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
}),
|
|
1166
|
+
registerApiRoute("/web/github/projects/:id/pr", {
|
|
1167
|
+
method: "POST",
|
|
1168
|
+
requiresAuth: false,
|
|
1169
|
+
handler: async (c) => {
|
|
1170
|
+
const owned = await loadOwnedProject({
|
|
1171
|
+
github,
|
|
1172
|
+
auth,
|
|
1173
|
+
fleet,
|
|
1174
|
+
c: loose(c)
|
|
1175
|
+
});
|
|
1176
|
+
if ("response" in owned) return owned.response;
|
|
1177
|
+
const { orgId, userId, project } = owned;
|
|
1178
|
+
let body;
|
|
1179
|
+
try {
|
|
1180
|
+
body = await c.req.json();
|
|
1181
|
+
} catch {
|
|
1182
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1183
|
+
}
|
|
1184
|
+
if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
|
|
1185
|
+
const base = body.base === void 0 ? project.defaultBranch : body.base;
|
|
1186
|
+
if (!isValidGitRef$1(base)) return c.json({ error: "Invalid base" }, 400);
|
|
1187
|
+
if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 256) return c.json({ error: "Invalid title" }, 400);
|
|
1188
|
+
if (body.body !== void 0 && (typeof body.body !== "string" || body.body.length > 65536)) return c.json({ error: "Invalid body" }, 400);
|
|
1189
|
+
const head = body.branch;
|
|
1190
|
+
const title = body.title;
|
|
1191
|
+
const prBody = body.body;
|
|
1192
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1193
|
+
if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
|
|
1194
|
+
try {
|
|
1195
|
+
return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
|
|
1196
|
+
const result = await github.versionControl.createPullRequest({
|
|
1197
|
+
connection: {
|
|
1198
|
+
type: "app-installation",
|
|
1199
|
+
installationId: Number(project.installation.externalId)
|
|
1200
|
+
},
|
|
1201
|
+
sourceId: project.repository.slug,
|
|
1202
|
+
baseBranch: base,
|
|
1203
|
+
headBranch: head,
|
|
1204
|
+
title,
|
|
1205
|
+
body: prBody,
|
|
1206
|
+
actingUserId: userId
|
|
1207
|
+
});
|
|
1208
|
+
await emitAudit?.({
|
|
1209
|
+
context: loose(c),
|
|
1210
|
+
input: {
|
|
1211
|
+
action: "factory.git.pr_opened",
|
|
1212
|
+
factoryProjectId: project.factoryProjectId,
|
|
1213
|
+
projectRepositoryId: project.id,
|
|
1214
|
+
targets: [{
|
|
1215
|
+
type: "pull_request",
|
|
1216
|
+
id: result.url,
|
|
1217
|
+
name: title
|
|
1218
|
+
}],
|
|
1219
|
+
metadata: {
|
|
1220
|
+
branch: head,
|
|
1221
|
+
base,
|
|
1222
|
+
url: result.url
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
});
|
|
1226
|
+
const pullRequestNumber = pullRequestNumberFromUrl(result.url, project.repository.slug);
|
|
1227
|
+
if (pullRequestNumber) {
|
|
1228
|
+
const sessionId = sessionWorkspace.session.sessionId;
|
|
1229
|
+
await subscribeToPullRequest({
|
|
1230
|
+
orgId,
|
|
1231
|
+
installationExternalId: project.installation.externalId,
|
|
1232
|
+
projectRepositoryId: project.id,
|
|
1233
|
+
repositoryExternalId: project.repository.externalId,
|
|
1234
|
+
repositorySlug: project.repository.slug,
|
|
1235
|
+
changeRequestId: pullRequestNumber.toString(),
|
|
1236
|
+
sessionId,
|
|
1237
|
+
ownerId: userId,
|
|
1238
|
+
resourceId: sessionId,
|
|
1239
|
+
threadId: sessionId,
|
|
1240
|
+
source: "factory-pr-create",
|
|
1241
|
+
subscribedByUserId: userId
|
|
1242
|
+
}, github.integrationStorage).catch((error) => {
|
|
1243
|
+
console.warn(`[GitHub] Pull request ${result.url} was created but automatic subscription failed.`, error);
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
return c.json({ url: result.url });
|
|
1247
|
+
});
|
|
1248
|
+
} catch (err) {
|
|
1249
|
+
return c.json({
|
|
1250
|
+
error: "github_pr_create_failed",
|
|
1251
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1252
|
+
}, 502);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
}),
|
|
1256
|
+
registerApiRoute("/web/github/projects/:id/sandbox", {
|
|
1257
|
+
method: "DELETE",
|
|
1258
|
+
requiresAuth: false,
|
|
1259
|
+
handler: async (c) => {
|
|
1260
|
+
const owned = await loadOwnedProject({
|
|
1261
|
+
github,
|
|
1262
|
+
auth,
|
|
1263
|
+
fleet,
|
|
1264
|
+
c: loose(c)
|
|
1265
|
+
});
|
|
1266
|
+
if ("response" in owned) return owned.response;
|
|
1267
|
+
const { sandboxRow } = owned;
|
|
1268
|
+
if (!sandboxRow.sandboxId) return c.json({ tornDown: false });
|
|
1269
|
+
try {
|
|
1270
|
+
return await withSessionOperationLock(`sandbox:${sandboxRow.id}`, async () => {
|
|
1271
|
+
const sandbox = await fleet.reattachSandbox(sandboxRow.sandboxId);
|
|
1272
|
+
await teardownProjectSandbox({
|
|
1273
|
+
fleet,
|
|
1274
|
+
row: sandboxRow,
|
|
1275
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
1276
|
+
sandbox
|
|
1277
|
+
});
|
|
1278
|
+
return c.json({ tornDown: true });
|
|
1279
|
+
});
|
|
1280
|
+
} catch (err) {
|
|
1281
|
+
return gitErrorResponse(loose(c), err);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
})
|
|
1285
|
+
];
|
|
1286
|
+
}
|
|
1287
|
+
/** Resolve the materialized workspace owned by a Factory session. */
|
|
1893
1288
|
async function resolveSessionWorkspace(github, projectId, userId, sessionId) {
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
}
|
|
1915
|
-
export {
|
|
1916
|
-
buildGithubRoutes
|
|
1917
|
-
};
|
|
1289
|
+
if (typeof sessionId !== "string") return;
|
|
1290
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
|
|
1291
|
+
if (session?.projectRepositoryId !== projectId || session.userId !== userId || !session.sandboxId || !session.sandboxWorkdir) return;
|
|
1292
|
+
return {
|
|
1293
|
+
session,
|
|
1294
|
+
workdir: session.sandboxWorkdir,
|
|
1295
|
+
sandboxBinding: {
|
|
1296
|
+
id: session.id,
|
|
1297
|
+
projectRepositoryId: session.projectRepositoryId,
|
|
1298
|
+
userId: session.userId,
|
|
1299
|
+
sandboxId: session.sandboxId,
|
|
1300
|
+
sandboxWorkdir: session.sandboxWorkdir,
|
|
1301
|
+
materializedAt: session.materializedAt,
|
|
1302
|
+
createdAt: session.createdAt
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
//#endregion
|
|
1307
|
+
export { buildGithubRoutes };
|
|
1308
|
+
|
|
1918
1309
|
//# sourceMappingURL=routes.js.map
|