@sentry/junior 0.316.0 → 0.317.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{admin-QYiDMnsu.js → admin-CAugg87B.js} +1 -1
- package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-AjrEV6Qe.js} +13438 -13149
- package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
- package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-B_YIZcgf.js} +5 -5
- package/dist/api/schema.d.ts +558 -102
- package/dist/api/schema.js +6 -6
- package/dist/api.js +230 -213
- package/dist/{app-BhvzRD__.d.ts → app-MoNAsVV5.d.ts} +34 -14
- package/dist/app.d.ts +1 -1
- package/dist/app.js +167 -122
- package/dist/catalog-runtime-DfSpJZdY.js +6 -0
- package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
- package/dist/{adapter-context-Bref7aPI.js → channel-access-j-YAVYK4.js} +2 -42
- package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-aH85nEHv.js} +4 -3
- package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +5 -4
- package/dist/cli/snapshot-create.js +5 -2
- package/dist/cli/upgrade.js +5 -3
- package/dist/config-CHQ8X251.js +2422 -0
- package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-D-FZ8Fin.js} +2 -3
- package/dist/{conversation-feed-B84pMjHo.js → conversation-feed--9S0_PXL.js} +3 -3
- package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-B1uXn5sf.js} +2 -16
- package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-BUE_7xaN.js} +99 -76
- package/dist/{create-DUJBXr6E.js → create-DoDIYgtZ.js} +12 -9
- package/dist/{credential-sync-JH_K9Adg.js → credential-sync-BJOqGnjV.js} +17 -12
- package/dist/{db-DhzvUY23.js → db-BFmyYZtJ.js} +20265 -27551
- package/dist/{deployment-BhvrhQeh.js → deployment-DXq9ZLU4.js} +17 -15
- package/dist/{engine-context-C9Nal48K.js → engine-context-CgQ7mlHt.js} +264 -47
- package/dist/{html-B_12WjKT.js → html-B3VKTGbJ.js} +6 -2
- package/dist/instrumentation.js +15 -7
- package/dist/{job-runner-DO8nslyY.js → job-runner-A1lCkybD.js} +391 -24
- package/dist/{lineage-D3AZAJVe.js → lineage-Bktb0UcV.js} +1 -1
- package/dist/{list-B0zsb5Cp.js → list-Bxvg5wXf.js} +224 -544
- package/dist/{logging-B8KEJegM.js → logging--smS7XRK.js} +2 -2
- package/dist/{session-stop-DponjDUZ.js → mailbox-turn-uSXhUFc9.js} +4747 -7039
- package/dist/{message-B5fKDYzz.js → message-BNenhsmB.js} +12 -22
- package/dist/{model-input-CuMWy37l.js → model-input-BReSnwHp.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +20 -6
- package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CE4soEIY.js} +2 -2
- package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-C36gX1gH.js} +2 -2
- package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
- package/dist/{list-mkB_GU8R.js → parent-result-Ck1rFYRQ.js} +107 -92
- package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
- package/dist/profile-BQ-iBDsZ.js +4657 -0
- package/dist/{transcript-CCi7323k.js → prompt-Dv7gkpD6.js} +97 -103
- package/dist/proxy-path-BHYoKZdq.js +15 -0
- package/dist/registry-iXMT5Jmh.js +3279 -0
- package/dist/reports-WKHfGTsU.js +195 -0
- package/dist/{resolve-D5JVvv6A.js → resolve-tony4ibz.js} +9 -29
- package/dist/{result-CS_7mo8a.js → result-Bta_dlWa.js} +25 -116
- package/dist/run-conversation-DL6ru7iW.js +336 -0
- package/dist/{runner-BzAES5W3.js → runner-BstDRbD9.js} +7 -7
- package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
- package/dist/{schema-z5-wA6N4.js → schema-DfqrHACA.js} +48 -86
- package/dist/sender-actors-CPglLd5R.js +83 -0
- package/dist/{service-account-D6AsAtc1.js → service-account-CTV_jaNu.js} +3 -1
- package/dist/{skills-DgJ9GBPR.js → skills-BCEU41zM.js} +4 -4
- package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
- package/dist/{spawn-BJWpdwhQ.js → spawn-frczVPIr.js} +11 -8
- package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-CiXy0eNR.js} +88 -69
- package/dist/{task-runner-BJae4JwE.js → task-runner-C9Yc2_ae.js} +20 -46
- package/dist/{thread-context-fiMNylbg.js → thread-context-CqZDKErp.js} +6 -6
- package/dist/topics-SRN7IVX-.js +24 -0
- package/dist/turn-membership-CENFf3kI.js +856 -0
- package/dist/{turn-wake-BjDW7x-5.js → turn-wake-BhloiI2h.js} +4 -5
- package/dist/{media-BebquhET.js → types-C4iC-IMC.js} +801 -771
- package/dist/user-customization-CvfuY9Eo.js +93 -0
- package/dist/users-ByG5RCEJ.js +181 -0
- package/dist/{validation-D5WmmmhX.js → validation-8gjfR91V.js} +1 -1
- package/dist/{version-CBQoanXb.js → version-BeZhWWBE.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-Cyb4kF17.js → worker-BqMQQNRk.js} +5 -4
- package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
- package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
- package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
- package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
- package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
- package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
- package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
- package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
- package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
- package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
- package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
- package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
- package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
- package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
- package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
- package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
- package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
- package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
- package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
- package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
- package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
- package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
- package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
- package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
- package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
- package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
- package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
- package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
- package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
- package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
- package/package.json +5 -5
- package/dist/people-CUtFApfL.js +0 -81
- package/dist/start-conversation-B-LIqqNi.js +0 -162
- package/dist/turn-session-routing-D15orfwy.js +0 -1309
- package/dist/user-customization-B27StpVQ.js +0 -9
- package/dist/web-message-id-C6P83ans.js +0 -10
|
@@ -0,0 +1,4657 @@
|
|
|
1
|
+
import { M as acquireActiveLock, P as withLock, j as MUTATION_LOCK_TTL_MS, n as getChatConfig } from "./config-CHQ8X251.js";
|
|
2
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
|
|
3
|
+
import { Ho as credentialLogContext, Ji as createPluginCache, Js as sleep, Ku as getStateAdapter, Vo as credentialContextSchema, Wo as credentialUserSubjectId, a as getDb, qi as runNonInteractiveCommand, xt as getPlugins } from "./db-BFmyYZtJ.js";
|
|
4
|
+
import { L as mapBounded, d as SANDBOX_WORKSPACE_ROOT, h as createPluginLogger } from "./prompt-Dv7gkpD6.js";
|
|
5
|
+
import { E as withSpan, b as setSpanAttributes, d as logAudit, h as logWarn, p as logException, y as setSentryUser } from "./logging--smS7XRK.js";
|
|
6
|
+
import { A as createEncryptedState, I as resolvePluginCommandEnv, J as CredentialUnavailableError, M as findLegacyWebActorUserId, P as resolveApiHeaderTransforms, Q as workloadIdentityHeader, Y as ServiceAccountUnavailableError, i as mergeHeaderTransforms, j as readEncryptedState, n as HOST_MANAGED_CREDENTIAL_PLACEHOLDER, q as CredentialMintError, r as resolveAuthTokenPlaceholder } from "./registry-iXMT5Jmh.js";
|
|
7
|
+
import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
8
|
+
import { r as continueTrace } from "./sentry-CPbZjomA.js";
|
|
9
|
+
import * as z from "zod";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
|
|
12
|
+
import { EgressAuthRequired, EgressPolicyDenied, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginGrantSchema, pluginProviderAccountSchema, pluginStoredTokensSchema } from "@sentry/junior-plugin-api";
|
|
13
|
+
import fs from "node:fs/promises";
|
|
14
|
+
import http from "node:http";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import dns from "node:dns/promises";
|
|
17
|
+
import net from "node:net";
|
|
18
|
+
import { Duplex, Readable } from "node:stream";
|
|
19
|
+
import tls from "node:tls";
|
|
20
|
+
import { FileSystem, Sandbox } from "@vercel/sandbox";
|
|
21
|
+
import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
|
|
22
|
+
// src/chat/credentials/audit.ts
|
|
23
|
+
/**
|
|
24
|
+
* Facts that credential audit events name about the run and the credential.
|
|
25
|
+
*
|
|
26
|
+
* These values are telemetry only. They grant nothing.
|
|
27
|
+
*/
|
|
28
|
+
const nonBlankStringSchema = z.string().min(1);
|
|
29
|
+
const credentialAuditSourceSchema = z.object({
|
|
30
|
+
kind: nonBlankStringSchema,
|
|
31
|
+
automationId: nonBlankStringSchema.optional(),
|
|
32
|
+
automationRunId: nonBlankStringSchema.optional()
|
|
33
|
+
}).strict();
|
|
34
|
+
/** Project a run Source to the facts that credential audit events name. */
|
|
35
|
+
function credentialAuditSource(source) {
|
|
36
|
+
if (source.kind !== "scheduled_automation" && source.kind !== "event_automation") return { kind: source.kind };
|
|
37
|
+
const result = { kind: source.kind };
|
|
38
|
+
if (source.automationId) result.automationId = source.automationId;
|
|
39
|
+
if (source.automationRunId) result.automationRunId = source.automationRunId;
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
/** Telemetry attributes for the run Source of a credential audit event. */
|
|
43
|
+
function credentialAuditAttributes(source) {
|
|
44
|
+
if (!source) return {};
|
|
45
|
+
const attributes = { "app.source.kind": source.kind };
|
|
46
|
+
if (source.automationId) attributes["app.task.id"] = source.automationId;
|
|
47
|
+
if (source.automationRunId) attributes["app.task.run.id"] = source.automationRunId;
|
|
48
|
+
return attributes;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Name whose credential a lease holds. An OAuth lease issued for a person
|
|
52
|
+
* holds that person's token: the Actor's own, or a delegated credential
|
|
53
|
+
* subject. Any other lease holds a credential that Junior owns, such as a
|
|
54
|
+
* GitHub App installation token or a deployment API key. An OAuth provider
|
|
55
|
+
* with no person falls back to its deployment token.
|
|
56
|
+
*/
|
|
57
|
+
function credentialAccount(lease, credentials) {
|
|
58
|
+
return lease.authorization && credentialUserSubjectId(credentials) ? "actor" : "app";
|
|
59
|
+
}
|
|
60
|
+
// src/chat/egress/git-push.ts
|
|
61
|
+
const OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
|
|
62
|
+
const ZERO_OBJECT_ID = /^0+$/;
|
|
63
|
+
const PKT_LENGTH = /^[0-9a-f]{4}$/i;
|
|
64
|
+
/** Match a Git push request. */
|
|
65
|
+
function isGitReceivePack(method, upstreamUrl) {
|
|
66
|
+
return method.toUpperCase() === "POST" && upstreamUrl.pathname.toLowerCase().endsWith("/git-receive-pack");
|
|
67
|
+
}
|
|
68
|
+
function unreadable$1(reason) {
|
|
69
|
+
return {
|
|
70
|
+
kind: "unreadable",
|
|
71
|
+
reason
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Read the ref update commands from a `git-receive-pack` body.
|
|
76
|
+
*
|
|
77
|
+
* The command list ends at the first flush packet, so push options and pack
|
|
78
|
+
* data after it do not matter. A signed push nests its commands in a
|
|
79
|
+
* certificate, so it is reported as unreadable.
|
|
80
|
+
*/
|
|
81
|
+
function readGitPush(body) {
|
|
82
|
+
const bytes = new Uint8Array(body ?? /* @__PURE__ */ new ArrayBuffer(0));
|
|
83
|
+
if (bytes[0] === 31 && bytes[1] === 139) return unreadable$1("gzip");
|
|
84
|
+
const decoder = new TextDecoder();
|
|
85
|
+
const updates = [];
|
|
86
|
+
let offset = 0;
|
|
87
|
+
while (true) {
|
|
88
|
+
if (offset + 4 > bytes.length) return unreadable$1("unterminated");
|
|
89
|
+
const lengthText = String.fromCharCode(...bytes.subarray(offset, offset + 4));
|
|
90
|
+
if (!PKT_LENGTH.test(lengthText)) return unreadable$1("malformed");
|
|
91
|
+
const length = Number.parseInt(lengthText, 16);
|
|
92
|
+
if (length === 0) return {
|
|
93
|
+
kind: "commands",
|
|
94
|
+
updates
|
|
95
|
+
};
|
|
96
|
+
if (length < 4) return unreadable$1("malformed");
|
|
97
|
+
if (offset + length > bytes.length) return unreadable$1("unterminated");
|
|
98
|
+
const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, "");
|
|
99
|
+
offset += length;
|
|
100
|
+
if (line.startsWith("shallow ")) continue;
|
|
101
|
+
const command = line.split("\0", 1)[0];
|
|
102
|
+
if (command === "push-cert") return unreadable$1("signed");
|
|
103
|
+
const [oldId, newId, ref, ...rest] = command.split(" ");
|
|
104
|
+
if (!oldId || !newId || !ref || rest.length > 0 || !OBJECT_ID.test(oldId) || !OBJECT_ID.test(newId)) return unreadable$1("malformed");
|
|
105
|
+
updates.push({
|
|
106
|
+
deletes: ZERO_OBJECT_ID.test(newId),
|
|
107
|
+
ref
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// src/chat/egress/graphql.ts
|
|
112
|
+
/** Largest GraphQL body that the host reads before it issues credentials. */
|
|
113
|
+
const GRAPHQL_BODY_LIMIT_BYTES = 65536;
|
|
114
|
+
/** Match a GraphQL request whose body names the operation. */
|
|
115
|
+
function isGraphqlPost(method, upstreamUrl) {
|
|
116
|
+
return method.toUpperCase() === "POST" && upstreamUrl.pathname.toLowerCase().endsWith("/graphql");
|
|
117
|
+
}
|
|
118
|
+
function unreadable(reason) {
|
|
119
|
+
return {
|
|
120
|
+
kind: "unreadable",
|
|
121
|
+
reason
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Read the operations of a GraphQL POST body.
|
|
126
|
+
*
|
|
127
|
+
* A JSON array is a batch. One unreadable entry makes the whole batch
|
|
128
|
+
* unreadable.
|
|
129
|
+
*/
|
|
130
|
+
async function readGraphqlRequest(body) {
|
|
131
|
+
const bytes = new Uint8Array(body ?? /* @__PURE__ */ new ArrayBuffer(0));
|
|
132
|
+
if (bytes[0] === 31 && bytes[1] === 139) return unreadable("gzip");
|
|
133
|
+
if (bytes.byteLength > GRAPHQL_BODY_LIMIT_BYTES) return unreadable("too-large");
|
|
134
|
+
let parsed;
|
|
135
|
+
try {
|
|
136
|
+
parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
137
|
+
} catch {
|
|
138
|
+
return unreadable("json");
|
|
139
|
+
}
|
|
140
|
+
if (!Array.isArray(parsed)) {
|
|
141
|
+
const operation = await readOperation(parsed);
|
|
142
|
+
return typeof operation === "string" ? unreadable(operation) : {
|
|
143
|
+
kind: "operation",
|
|
144
|
+
operation
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const operations = [];
|
|
148
|
+
for (const entry of parsed) {
|
|
149
|
+
const operation = await readOperation(entry);
|
|
150
|
+
if (typeof operation === "string") return unreadable(operation);
|
|
151
|
+
operations.push(operation);
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
kind: "batch",
|
|
155
|
+
operations
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
async function readOperation(entry) {
|
|
159
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return "json";
|
|
160
|
+
const { operationName, query } = entry;
|
|
161
|
+
if (typeof query !== "string") return "query";
|
|
162
|
+
if (operationName !== void 0 && operationName !== null && typeof operationName !== "string") return "operation";
|
|
163
|
+
const { parse } = await import("graphql");
|
|
164
|
+
let document;
|
|
165
|
+
try {
|
|
166
|
+
document = parse(query, { noLocation: true });
|
|
167
|
+
} catch {
|
|
168
|
+
return "document";
|
|
169
|
+
}
|
|
170
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
171
|
+
const operations = [];
|
|
172
|
+
for (const definition of document.definitions) if (definition.kind === "OperationDefinition") operations.push(definition);
|
|
173
|
+
else if (definition.kind === "FragmentDefinition") {
|
|
174
|
+
if (fragments.has(definition.name.value)) return "document";
|
|
175
|
+
fragments.set(definition.name.value, definition);
|
|
176
|
+
}
|
|
177
|
+
const operation = operationName ? operations.find((candidate) => candidate.name?.value === operationName) : operations.length === 1 ? operations[0] : void 0;
|
|
178
|
+
if (!operation) return "operation";
|
|
179
|
+
const fields = /* @__PURE__ */ new Map();
|
|
180
|
+
const rootFields = [];
|
|
181
|
+
if (!collectFields(operation.selectionSet, fragments, /* @__PURE__ */ new Set(), fields) || !collectRootFields(operation.selectionSet, fragments, /* @__PURE__ */ new Set(), rootFields)) return "document";
|
|
182
|
+
return {
|
|
183
|
+
fields: [...fields.values()],
|
|
184
|
+
...operation.name ? { name: operation.name.value } : void 0,
|
|
185
|
+
rootFields,
|
|
186
|
+
type: operation.operation
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** Add each distinct field at any depth. Each fragment is read once. */
|
|
190
|
+
function collectFields(selectionSet, fragments, seen, fields) {
|
|
191
|
+
for (const selection of selectionSet.selections) {
|
|
192
|
+
if (selection.kind === "Field") {
|
|
193
|
+
const name = selection.name.value;
|
|
194
|
+
const args = (selection.arguments ?? []).map((arg) => arg.name.value);
|
|
195
|
+
const key = [name, ...args].join("\0");
|
|
196
|
+
if (!fields.has(key)) fields.set(key, {
|
|
197
|
+
arguments: args,
|
|
198
|
+
name
|
|
199
|
+
});
|
|
200
|
+
if (selection.selectionSet && !collectFields(selection.selectionSet, fragments, seen, fields)) return false;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const inner = fragmentSelectionSet(selection, fragments, seen);
|
|
204
|
+
if (inner === false) return false;
|
|
205
|
+
if (inner && !collectFields(inner, fragments, seen, fields)) return false;
|
|
206
|
+
}
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
/** Add the operation root fields, through fragments. */
|
|
210
|
+
function collectRootFields(selectionSet, fragments, seen, rootFields) {
|
|
211
|
+
for (const selection of selectionSet.selections) {
|
|
212
|
+
if (selection.kind === "Field") {
|
|
213
|
+
rootFields.push(selection.name.value);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
const inner = fragmentSelectionSet(selection, fragments, seen);
|
|
217
|
+
if (inner === false) return false;
|
|
218
|
+
if (inner && !collectRootFields(inner, fragments, seen, rootFields)) return false;
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Return the selections of an inline fragment or a fragment spread.
|
|
224
|
+
*
|
|
225
|
+
* Returns undefined for a fragment already read, which also stops cycles, and
|
|
226
|
+
* false for a spread of an undefined fragment.
|
|
227
|
+
*/
|
|
228
|
+
function fragmentSelectionSet(selection, fragments, seen) {
|
|
229
|
+
if (selection.kind === "InlineFragment") return selection.selectionSet;
|
|
230
|
+
const name = selection.name.value;
|
|
231
|
+
if (seen.has(name)) return;
|
|
232
|
+
seen.add(name);
|
|
233
|
+
return fragments.get(name)?.selectionSet ?? false;
|
|
234
|
+
}
|
|
235
|
+
// src/chat/plugins/credential-hooks.ts
|
|
236
|
+
function parseSchema(schema, value, message) {
|
|
237
|
+
const result = schema.safeParse(value);
|
|
238
|
+
if (!result.success) throw new Error(message);
|
|
239
|
+
return result.data;
|
|
240
|
+
}
|
|
241
|
+
function parseAuthorization(value, pluginName) {
|
|
242
|
+
if (value === void 0) return;
|
|
243
|
+
const authorization = parseSchema(pluginAuthorizationSchema, value, `Plugin "${pluginName}" grant authorization is invalid`);
|
|
244
|
+
if (authorization.provider !== pluginName) throw new Error(`Plugin "${pluginName}" grant authorization provider must match the issuing plugin`);
|
|
245
|
+
return authorization;
|
|
246
|
+
}
|
|
247
|
+
function parseGrant(value, pluginName) {
|
|
248
|
+
return parseSchema(pluginGrantSchema, value, `Plugin "${pluginName}" grantForEgress returned an invalid grant`);
|
|
249
|
+
}
|
|
250
|
+
function pluginFor(provider) {
|
|
251
|
+
return getPlugins().find((candidate) => candidate.manifest.name === provider);
|
|
252
|
+
}
|
|
253
|
+
function basePluginContext(plugin) {
|
|
254
|
+
const pluginName = plugin.manifest.name;
|
|
255
|
+
return {
|
|
256
|
+
plugin: { name: pluginName },
|
|
257
|
+
cache: createPluginCache(pluginName),
|
|
258
|
+
log: createPluginLogger(pluginName),
|
|
259
|
+
db: getDb()
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function parseCredentialResult(value, pluginName) {
|
|
263
|
+
const result = parseSchema(pluginCredentialResultSchema, value, `Plugin "${pluginName}" issueCredential result is invalid`);
|
|
264
|
+
if (result.type === "lease") {
|
|
265
|
+
parseAuthorization(result.lease.authorization, pluginName);
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
if (result.type === "unavailable") return result;
|
|
269
|
+
parseAuthorization(result.authorization, pluginName);
|
|
270
|
+
return result;
|
|
271
|
+
}
|
|
272
|
+
/** Ask a plugin which grant an outbound request needs. */
|
|
273
|
+
async function selectPluginGrant(input) {
|
|
274
|
+
const plugin = pluginFor(input.provider);
|
|
275
|
+
const hook = plugin?.hooks?.grantForEgress;
|
|
276
|
+
if (!plugin || !hook) return;
|
|
277
|
+
const result = await hook({
|
|
278
|
+
...basePluginContext(plugin),
|
|
279
|
+
request: {
|
|
280
|
+
...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
|
|
281
|
+
...input.conversationId ? { conversationId: input.conversationId } : void 0,
|
|
282
|
+
...input.gitPush ? { gitPush: input.gitPush } : void 0,
|
|
283
|
+
...input.graphql ? { graphql: input.graphql } : void 0,
|
|
284
|
+
method: input.method,
|
|
285
|
+
...input.operation ? { operation: input.operation } : void 0,
|
|
286
|
+
url: input.upstreamUrl.toString(),
|
|
287
|
+
...input.withoutCredential ? { withoutCredential: true } : void 0
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
return result === void 0 ? void 0 : parseGrant(result, plugin.manifest.name);
|
|
291
|
+
}
|
|
292
|
+
/** Let the owning plugin inspect an upstream response without changing pass-through behavior. */
|
|
293
|
+
async function onPluginEgressResponse(input) {
|
|
294
|
+
const plugin = pluginFor(input.provider);
|
|
295
|
+
const hook = plugin?.hooks?.onEgressResponse;
|
|
296
|
+
if (!plugin || !hook) return {};
|
|
297
|
+
let permissionDenied;
|
|
298
|
+
await hook({
|
|
299
|
+
...basePluginContext(plugin),
|
|
300
|
+
grant: input.grant,
|
|
301
|
+
permissionDenied(message) {
|
|
302
|
+
const trimmed = message.trim();
|
|
303
|
+
if (!trimmed) throw new Error(`Plugin "${plugin.manifest.name}" onEgressResponse permissionDenied message is empty`);
|
|
304
|
+
permissionDenied = { message: trimmed };
|
|
305
|
+
},
|
|
306
|
+
request: {
|
|
307
|
+
...input.conversationId ? { conversationId: input.conversationId } : void 0,
|
|
308
|
+
method: input.method,
|
|
309
|
+
...input.operation ? { operation: input.operation } : void 0,
|
|
310
|
+
url: input.upstreamUrl.toString()
|
|
311
|
+
},
|
|
312
|
+
response: input.response
|
|
313
|
+
});
|
|
314
|
+
return permissionDenied ? { permissionDenied } : {};
|
|
315
|
+
}
|
|
316
|
+
/** Return whether a plugin owns credential issuance for egress. */
|
|
317
|
+
function hasEgressCredentialHooks(provider) {
|
|
318
|
+
const hooks = pluginFor(provider)?.hooks;
|
|
319
|
+
return Boolean(hooks?.grantForEgress || hooks?.issueCredential);
|
|
320
|
+
}
|
|
321
|
+
/** Return providers that can verify an OAuth account for identity storage. */
|
|
322
|
+
function getOAuthAccountProviders() {
|
|
323
|
+
return getPlugins().filter((plugin) => Boolean(plugin.hooks?.resolveOAuthAccount)).map((plugin) => plugin.manifest.name);
|
|
324
|
+
}
|
|
325
|
+
/** Ask a plugin which provider account belongs to an OAuth token. */
|
|
326
|
+
async function resolvePluginOAuthAccount(input) {
|
|
327
|
+
const plugin = pluginFor(input.provider);
|
|
328
|
+
const hook = plugin?.hooks?.resolveOAuthAccount;
|
|
329
|
+
if (!plugin || !hook) return;
|
|
330
|
+
const account = await hook({
|
|
331
|
+
...basePluginContext(plugin),
|
|
332
|
+
tokenResponse: input.tokenResponse,
|
|
333
|
+
tokens: input.tokens
|
|
334
|
+
});
|
|
335
|
+
return account === void 0 ? void 0 : parseSchema(pluginProviderAccountSchema, account, `Plugin "${plugin.manifest.name}" resolveOAuthAccount returned an invalid account`);
|
|
336
|
+
}
|
|
337
|
+
/** Ask a plugin to issue headers or describe why the selected grant is unavailable. */
|
|
338
|
+
async function issuePluginCredential(input) {
|
|
339
|
+
const plugin = pluginFor(input.provider);
|
|
340
|
+
const hook = plugin?.hooks?.issueCredential;
|
|
341
|
+
if (!plugin || !hook) throw new Error(`Plugin "${input.provider}" has no issueCredential hook`);
|
|
342
|
+
const currentUserId = "type" in input.actor ? input.actor.userId : void 0;
|
|
343
|
+
const credentialSubjectUserId = input.credentialSubject?.userId;
|
|
344
|
+
return parseCredentialResult(await hook({
|
|
345
|
+
...basePluginContext(plugin),
|
|
346
|
+
actor: input.actor,
|
|
347
|
+
grant: input.grant,
|
|
348
|
+
...input.credentialSubject ? { credentialSubject: input.credentialSubject } : void 0,
|
|
349
|
+
tokens: {
|
|
350
|
+
...currentUserId ? { currentUser: {
|
|
351
|
+
userId: currentUserId,
|
|
352
|
+
get: async () => await input.userTokenStore.get(currentUserId, plugin.manifest.name),
|
|
353
|
+
set: async (tokens) => {
|
|
354
|
+
await input.userTokenStore.set(currentUserId, plugin.manifest.name, tokens);
|
|
355
|
+
},
|
|
356
|
+
withRefresh: async (callback) => await input.userTokenStore.withRefresh(currentUserId, plugin.manifest.name, callback)
|
|
357
|
+
} } : void 0,
|
|
358
|
+
...credentialSubjectUserId ? { credentialSubject: {
|
|
359
|
+
userId: credentialSubjectUserId,
|
|
360
|
+
get: async () => await input.userTokenStore.get(credentialSubjectUserId, plugin.manifest.name),
|
|
361
|
+
set: async (tokens) => {
|
|
362
|
+
await input.userTokenStore.set(credentialSubjectUserId, plugin.manifest.name, tokens);
|
|
363
|
+
},
|
|
364
|
+
withRefresh: async (callback) => await input.userTokenStore.withRefresh(credentialSubjectUserId, plugin.manifest.name, callback)
|
|
365
|
+
} } : void 0
|
|
366
|
+
}
|
|
367
|
+
}), plugin.manifest.name);
|
|
368
|
+
}
|
|
369
|
+
// src/chat/sandbox/egress/tracing.ts
|
|
370
|
+
function isValidDomainPattern(domain) {
|
|
371
|
+
if (domain.includes("*")) return domain.startsWith("*.") && domain.indexOf("*", 1) === -1;
|
|
372
|
+
return true;
|
|
373
|
+
}
|
|
374
|
+
/** Normalize exact and leading-wildcard sandbox egress trace domains. */
|
|
375
|
+
function normalizeSandboxEgressTracePropagationDomains(domains) {
|
|
376
|
+
if (domains === void 0) return [];
|
|
377
|
+
if (!Array.isArray(domains)) throw new Error("sandbox.egressTracePropagationDomains must be an array");
|
|
378
|
+
return [...new Set(domains.map((domain) => {
|
|
379
|
+
if (typeof domain !== "string") throw new Error("sandbox.egressTracePropagationDomains entries must be strings");
|
|
380
|
+
const normalized = domain.trim().toLowerCase();
|
|
381
|
+
if (!normalized) throw new Error("sandbox.egressTracePropagationDomains entries must be non-empty");
|
|
382
|
+
if (!isValidDomainPattern(normalized)) throw new Error("sandbox.egressTracePropagationDomains entries must be exact domains or leading wildcard domains");
|
|
383
|
+
return normalized;
|
|
384
|
+
}))].sort((left, right) => left.localeCompare(right));
|
|
385
|
+
}
|
|
386
|
+
/** Return whether a host may carry sandbox egress trace propagation headers. */
|
|
387
|
+
function shouldPropagateSandboxEgressTrace(host, config = {}) {
|
|
388
|
+
const normalizedHost = host.trim().toLowerCase();
|
|
389
|
+
return (config.domains ?? []).some((domain) => {
|
|
390
|
+
if (domain.startsWith("*.")) {
|
|
391
|
+
const suffix = domain.slice(1);
|
|
392
|
+
return normalizedHost.endsWith(suffix) && normalizedHost !== domain.slice(2);
|
|
393
|
+
}
|
|
394
|
+
return domain === normalizedHost;
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
// src/chat/sandbox/egress/policy.ts
|
|
398
|
+
/** Return whether an outbound host is covered by a provider domain rule. */
|
|
399
|
+
function matchesSandboxEgressDomain(host, domain) {
|
|
400
|
+
return host.toLowerCase() === domain.toLowerCase();
|
|
401
|
+
}
|
|
402
|
+
function manifestDomains(manifest) {
|
|
403
|
+
return [.../* @__PURE__ */ new Set([...manifest.credentials?.domains ?? [], ...manifest.domains ?? []])].sort((left, right) => left.localeCompare(right));
|
|
404
|
+
}
|
|
405
|
+
function providerEntries() {
|
|
406
|
+
return pluginCatalogRuntime.getProviders().map((plugin) => ({
|
|
407
|
+
provider: plugin.manifest.name,
|
|
408
|
+
domains: manifestDomains(plugin.manifest)
|
|
409
|
+
})).filter((entry) => entry.domains.length > 0).sort((left, right) => left.provider.localeCompare(right.provider));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Resolve the plugin provider responsible for an outbound sandbox host.
|
|
413
|
+
*
|
|
414
|
+
* Only plugin-declared provider domains are eligible for credentialed sandbox
|
|
415
|
+
* egress. Hosts without a matching provider are blocked by the proxy even if a
|
|
416
|
+
* malformed or stale network policy tried to forward them.
|
|
417
|
+
*/
|
|
418
|
+
function resolveSandboxEgressProviderForHost(host) {
|
|
419
|
+
return providerEntries().find((entry) => entry.domains.some((domain) => matchesSandboxEgressDomain(host, domain)))?.provider;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Build the provider-neutral egress policy for one sandbox command context.
|
|
423
|
+
*
|
|
424
|
+
* Provider domains go through Junior's credentialed egress when a signed
|
|
425
|
+
* credential token is given. The token binds each request to the actor and
|
|
426
|
+
* sandbox VM that created the command. Configured trace-only domains get trace
|
|
427
|
+
* headers in place. The sandbox receives placeholder env vars, not provider
|
|
428
|
+
* credentials.
|
|
429
|
+
*/
|
|
430
|
+
function buildSandboxEgressNetworkPolicy(input) {
|
|
431
|
+
const credentialToken = input?.credentialToken;
|
|
432
|
+
const credentialDomains = credentialToken ? [...new Set(providerEntries().flatMap((entry) => entry.domains))].sort((left, right) => left.localeCompare(right)) : [];
|
|
433
|
+
const traceHeaders = Object.fromEntries(Object.entries(input?.traceHeaders ?? {}).filter(([, value]) => typeof value === "string" && value.trim()));
|
|
434
|
+
const traceDomains = Object.keys(traceHeaders).length > 0 ? [...new Set(input?.traceConfig?.domains ?? [])].filter((domain) => !credentialDomains.includes(domain) && shouldPropagateSandboxEgressTrace(domain, input?.traceConfig)).sort((left, right) => left.localeCompare(right)) : [];
|
|
435
|
+
return {
|
|
436
|
+
...credentialToken && credentialDomains.length > 0 ? { credentialEgress: {
|
|
437
|
+
credentialToken,
|
|
438
|
+
domains: credentialDomains
|
|
439
|
+
} } : void 0,
|
|
440
|
+
...traceDomains.length > 0 ? { traceHeaders: {
|
|
441
|
+
domains: traceDomains,
|
|
442
|
+
headers: traceHeaders
|
|
443
|
+
} } : void 0
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Resolve non-secret command environment values for registered sandbox providers.
|
|
448
|
+
*
|
|
449
|
+
* Credential env vars are placeholders that tell tools which auth variable name
|
|
450
|
+
* exists; real credential headers are issued lazily by host egress.
|
|
451
|
+
*/
|
|
452
|
+
async function resolveSandboxCommandEnvironment() {
|
|
453
|
+
const env = {};
|
|
454
|
+
for (const plugin of pluginCatalogRuntime.getProviders().sort((left, right) => left.manifest.name.localeCompare(right.manifest.name))) {
|
|
455
|
+
Object.assign(env, resolvePluginCommandEnv(plugin.manifest));
|
|
456
|
+
const credentials = plugin.manifest.credentials;
|
|
457
|
+
if (credentials?.type === "oauth-bearer" && credentials.authTokenEnv) env[credentials.authTokenEnv] = resolveAuthTokenPlaceholder(credentials);
|
|
458
|
+
}
|
|
459
|
+
return env;
|
|
460
|
+
}
|
|
461
|
+
// src/chat/capabilities/router.ts
|
|
462
|
+
var ProviderCredentialRouter = class {
|
|
463
|
+
brokersByProvider;
|
|
464
|
+
constructor(input) {
|
|
465
|
+
this.brokersByProvider = input.brokersByProvider;
|
|
466
|
+
}
|
|
467
|
+
async issue(input) {
|
|
468
|
+
const broker = this.brokersByProvider[input.provider];
|
|
469
|
+
if (!broker) throw new Error(`No credential broker registered for provider: ${input.provider}`);
|
|
470
|
+
return await broker.issue({
|
|
471
|
+
context: input.context,
|
|
472
|
+
...input.operation ? { operation: input.operation } : void 0,
|
|
473
|
+
reason: input.reason
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
// src/chat/credentials/legacy-web-tokens.ts
|
|
478
|
+
/**
|
|
479
|
+
* Move OAuth tokens saved under a legacy web Actor id to the User id.
|
|
480
|
+
*
|
|
481
|
+
* Dashboard connections made before web Actors used the User id are saved
|
|
482
|
+
* under `dashboard:<hash>`. When a read for a User id finds no tokens, this
|
|
483
|
+
* moves the legacy tokens, so the person keeps the connection. A delete also
|
|
484
|
+
* deletes the legacy key, so a disconnect cannot bring it back later.
|
|
485
|
+
*
|
|
486
|
+
* TODO(dcramer): Delete after no `oauth-token:dashboard:*` keys remain.
|
|
487
|
+
*/
|
|
488
|
+
/** Read through to legacy web tokens when a User id has none. */
|
|
489
|
+
function withLegacyWebTokens(store) {
|
|
490
|
+
return {
|
|
491
|
+
async get(userId, provider) {
|
|
492
|
+
const tokens = await store.get(userId, provider);
|
|
493
|
+
if (tokens) return tokens;
|
|
494
|
+
const legacyUserId = await findLegacyWebActorUserId(userId);
|
|
495
|
+
if (!legacyUserId) return void 0;
|
|
496
|
+
const legacy = await store.get(legacyUserId, provider);
|
|
497
|
+
if (!legacy) return void 0;
|
|
498
|
+
await store.set(userId, provider, legacy);
|
|
499
|
+
await store.delete(legacyUserId, provider);
|
|
500
|
+
return legacy;
|
|
501
|
+
},
|
|
502
|
+
set: (userId, provider, tokens) => store.set(userId, provider, tokens),
|
|
503
|
+
async delete(userId, provider) {
|
|
504
|
+
await store.delete(userId, provider);
|
|
505
|
+
const legacyUserId = await findLegacyWebActorUserId(userId);
|
|
506
|
+
if (legacyUserId) await store.delete(legacyUserId, provider);
|
|
507
|
+
},
|
|
508
|
+
withRefresh: (userId, provider, callback) => store.withRefresh(userId, provider, callback)
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
// src/chat/credentials/user-token-store.ts
|
|
512
|
+
const storedTokensSchema = pluginStoredTokensSchema;
|
|
513
|
+
// src/chat/credentials/state-adapter-token-store.ts
|
|
514
|
+
const KEY_PREFIX = "oauth-token";
|
|
515
|
+
const BUFFER_MS = 864e5;
|
|
516
|
+
const LONG_LIVED_TTL_MS = 31536e6;
|
|
517
|
+
const REFRESH_LOCK_WAIT_MS = 3e4;
|
|
518
|
+
const REFRESH_LOCK_RETRY_MS = 100;
|
|
519
|
+
function tokenKey(userId, provider) {
|
|
520
|
+
return `${KEY_PREFIX}:${userId}:${provider}`;
|
|
521
|
+
}
|
|
522
|
+
function refreshLockKey(userId, provider) {
|
|
523
|
+
return `${tokenKey(userId, provider)}:refresh`;
|
|
524
|
+
}
|
|
525
|
+
var StateAdapterTokenStore = class {
|
|
526
|
+
state;
|
|
527
|
+
secrets;
|
|
528
|
+
constructor(stateAdapter) {
|
|
529
|
+
this.state = stateAdapter;
|
|
530
|
+
this.secrets = createEncryptedState(stateAdapter);
|
|
531
|
+
}
|
|
532
|
+
async get(userId, provider) {
|
|
533
|
+
const stored = await readEncryptedState(this.state, tokenKey(userId, provider));
|
|
534
|
+
if (!stored) return void 0;
|
|
535
|
+
const tokens = storedTokensSchema.parse(stored.value);
|
|
536
|
+
if (stored.stale) await this.saveStale(userId, provider);
|
|
537
|
+
return tokens;
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Save stale tokens again with the active key. It runs only when the
|
|
541
|
+
* refresh gate is free, so it cannot write back a refresh token that a
|
|
542
|
+
* refresh replaced.
|
|
543
|
+
*/
|
|
544
|
+
async saveStale(userId, provider) {
|
|
545
|
+
await withLock(this.state, refreshLockKey(userId, provider), async () => {
|
|
546
|
+
const key = tokenKey(userId, provider);
|
|
547
|
+
const current = await readEncryptedState(this.state, key);
|
|
548
|
+
if (!current?.stale) return;
|
|
549
|
+
await this.set(userId, provider, storedTokensSchema.parse(current.value));
|
|
550
|
+
}, { ttlMs: MUTATION_LOCK_TTL_MS });
|
|
551
|
+
}
|
|
552
|
+
async set(userId, provider, tokens) {
|
|
553
|
+
const parsed = storedTokensSchema.parse(tokens);
|
|
554
|
+
const expiresAt = parsed.refreshTokenExpiresAt ?? parsed.expiresAt;
|
|
555
|
+
const ttlMs = expiresAt ? Math.max(expiresAt - Date.now() + BUFFER_MS, BUFFER_MS) : LONG_LIVED_TTL_MS;
|
|
556
|
+
await this.secrets.set(tokenKey(userId, provider), parsed, ttlMs);
|
|
557
|
+
}
|
|
558
|
+
async delete(userId, provider) {
|
|
559
|
+
await this.state.delete(tokenKey(userId, provider));
|
|
560
|
+
}
|
|
561
|
+
/** Wait for the per-slot refresh gate so rotated refresh tokens are used once. */
|
|
562
|
+
async withRefresh(userId, provider, callback) {
|
|
563
|
+
const lockKey = refreshLockKey(userId, provider);
|
|
564
|
+
const deadline = Date.now() + REFRESH_LOCK_WAIT_MS;
|
|
565
|
+
while (true) {
|
|
566
|
+
const lock = await acquireActiveLock(this.state, lockKey);
|
|
567
|
+
if (lock) try {
|
|
568
|
+
return await callback();
|
|
569
|
+
} finally {
|
|
570
|
+
await this.state.releaseLock(lock);
|
|
571
|
+
}
|
|
572
|
+
if (Date.now() >= deadline) throw new Error(`Could not acquire OAuth token refresh lock`);
|
|
573
|
+
await sleep(REFRESH_LOCK_RETRY_MS);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
// src/chat/capabilities/factory.ts
|
|
578
|
+
const sandboxEgressRouters = /* @__PURE__ */ new WeakMap();
|
|
579
|
+
/** Create the user token store used by OAuth-backed credential brokers. */
|
|
580
|
+
function createUserTokenStore() {
|
|
581
|
+
return withLegacyWebTokens(new StateAdapterTokenStore(getStateAdapter()));
|
|
582
|
+
}
|
|
583
|
+
function createProviderCredentialRouter(userTokenStore) {
|
|
584
|
+
const brokersByProvider = {};
|
|
585
|
+
for (const plugin of pluginCatalogRuntime.getProviders()) {
|
|
586
|
+
const { name } = plugin.manifest;
|
|
587
|
+
if (!plugin.manifest.credentials && !plugin.manifest.apiHeaders) continue;
|
|
588
|
+
brokersByProvider[name] = pluginCatalogRuntime.createBroker(name, { userTokenStore });
|
|
589
|
+
}
|
|
590
|
+
return new ProviderCredentialRouter({ brokersByProvider });
|
|
591
|
+
}
|
|
592
|
+
function getSandboxEgressRouter() {
|
|
593
|
+
const stateAdapter = getStateAdapter();
|
|
594
|
+
let router = sandboxEgressRouters.get(stateAdapter);
|
|
595
|
+
if (!router) {
|
|
596
|
+
router = createProviderCredentialRouter(withLegacyWebTokens(new StateAdapterTokenStore(stateAdapter)));
|
|
597
|
+
sandboxEgressRouters.set(stateAdapter, router);
|
|
598
|
+
}
|
|
599
|
+
return router;
|
|
600
|
+
}
|
|
601
|
+
/** Issue one provider credential lease for host-side sandbox egress proxying. */
|
|
602
|
+
async function issueProviderCredentialLease(input) {
|
|
603
|
+
return await getSandboxEgressRouter().issue(input);
|
|
604
|
+
}
|
|
605
|
+
// src/chat/sandbox/egress/schemas.ts
|
|
606
|
+
const finiteNumberSchema = z.number().refine(Number.isFinite);
|
|
607
|
+
const httpStatusSchema = z.number().int().min(100).max(599);
|
|
608
|
+
const providerNameSchema = z.string().regex(/^[a-z][a-z0-9-]*$/);
|
|
609
|
+
const credentialSignalKindSchema = z.enum(["auth_required", "unavailable"]);
|
|
610
|
+
const sandboxEgressGrantSchema = pluginGrantSchema;
|
|
611
|
+
const sandboxEgressCredentialContextSchema = z.object({
|
|
612
|
+
credentials: credentialContextSchema,
|
|
613
|
+
/**
|
|
614
|
+
* Conversation that the credentials act for. Telemetry and per-Conversation
|
|
615
|
+
* limits only; it grants nothing.
|
|
616
|
+
*/
|
|
617
|
+
conversationId: z.string().min(1).optional(),
|
|
618
|
+
egressId: z.string().min(1),
|
|
619
|
+
expiresAtMs: finiteNumberSchema,
|
|
620
|
+
contextId: z.string().min(1),
|
|
621
|
+
/** Run Source that write audit events name. Telemetry only; it grants nothing. */
|
|
622
|
+
source: credentialAuditSourceSchema.optional()
|
|
623
|
+
}).strict();
|
|
624
|
+
const sandboxEgressCredentialLeaseSchema = z.object({
|
|
625
|
+
account: pluginProviderAccountSchema.optional(),
|
|
626
|
+
authorization: pluginAuthorizationSchema.optional(),
|
|
627
|
+
grant: sandboxEgressGrantSchema,
|
|
628
|
+
provider: providerNameSchema,
|
|
629
|
+
expiresAt: z.string().min(1),
|
|
630
|
+
headerTransforms: z.array(pluginCredentialHeaderTransformSchema).min(1)
|
|
631
|
+
}).strict();
|
|
632
|
+
const sandboxEgressAuthRequiredSignalSchema = z.object({
|
|
633
|
+
authorization: pluginAuthorizationSchema.optional(),
|
|
634
|
+
grant: sandboxEgressGrantSchema,
|
|
635
|
+
kind: credentialSignalKindSchema.default("auth_required"),
|
|
636
|
+
provider: providerNameSchema,
|
|
637
|
+
message: z.string().optional(),
|
|
638
|
+
createdAtMs: finiteNumberSchema
|
|
639
|
+
}).strict().superRefine((signal, ctx) => {
|
|
640
|
+
if (signal.authorization && signal.authorization.provider !== signal.provider) ctx.addIssue({
|
|
641
|
+
code: z.ZodIssueCode.custom,
|
|
642
|
+
message: "Auth signal authorization provider must match provider",
|
|
643
|
+
path: ["authorization", "provider"]
|
|
644
|
+
});
|
|
645
|
+
});
|
|
646
|
+
const sandboxEgressUpstreamPermissionDeniedSignalSchema = z.object({
|
|
647
|
+
account: pluginProviderAccountSchema.optional(),
|
|
648
|
+
grant: sandboxEgressGrantSchema,
|
|
649
|
+
message: z.string().min(1),
|
|
650
|
+
provider: providerNameSchema,
|
|
651
|
+
source: z.literal("upstream"),
|
|
652
|
+
status: httpStatusSchema,
|
|
653
|
+
upstreamHost: z.string().min(1),
|
|
654
|
+
upstreamPath: z.string().min(1),
|
|
655
|
+
createdAtMs: finiteNumberSchema
|
|
656
|
+
}).strict();
|
|
657
|
+
/** A request that Junior's egress policy refused before it chose a credential. */
|
|
658
|
+
const sandboxEgressPolicyDeniedSignalSchema = z.object({
|
|
659
|
+
message: z.string().min(1),
|
|
660
|
+
method: z.string().min(1),
|
|
661
|
+
provider: providerNameSchema,
|
|
662
|
+
source: z.literal("policy"),
|
|
663
|
+
upstreamHost: z.string().min(1),
|
|
664
|
+
upstreamPath: z.string().min(1),
|
|
665
|
+
createdAtMs: finiteNumberSchema
|
|
666
|
+
}).strict();
|
|
667
|
+
const sandboxEgressPermissionDeniedSignalSchema = z.discriminatedUnion("source", [sandboxEgressUpstreamPermissionDeniedSignalSchema, sandboxEgressPolicyDeniedSignalSchema]);
|
|
668
|
+
const sandboxEgressSignalsResponseSchema = z.object({
|
|
669
|
+
auth_required: sandboxEgressAuthRequiredSignalSchema.optional(),
|
|
670
|
+
permission_denied: sandboxEgressPermissionDeniedSignalSchema.optional()
|
|
671
|
+
}).strict();
|
|
672
|
+
/** Parse a host-owned sandbox egress auth signal from state or tool results. */
|
|
673
|
+
function parseSandboxEgressAuthRequiredSignal(value) {
|
|
674
|
+
const result = sandboxEgressAuthRequiredSignalSchema.safeParse(value);
|
|
675
|
+
return result.success ? result.data : void 0;
|
|
676
|
+
}
|
|
677
|
+
/** Parse a host-owned sandbox egress permission-denied signal from state or tool results. */
|
|
678
|
+
function parseSandboxEgressPermissionDeniedSignal(value) {
|
|
679
|
+
const result = sandboxEgressPermissionDeniedSignalSchema.safeParse(value);
|
|
680
|
+
return result.success ? result.data : void 0;
|
|
681
|
+
}
|
|
682
|
+
// src/chat/sandbox/egress/session.ts
|
|
683
|
+
const SANDBOX_EGRESS_TOKEN_VERSION = "v1";
|
|
684
|
+
const SANDBOX_EGRESS_HMAC_CONTEXT = "junior.sandbox_egress.v1";
|
|
685
|
+
const SANDBOX_EGRESS_AUTH_SIGNAL_PREFIX = "sandbox-egress-auth-required";
|
|
686
|
+
const SANDBOX_EGRESS_PERMISSION_SIGNAL_PREFIX = "sandbox-egress-permission-denied";
|
|
687
|
+
const SANDBOX_EGRESS_LEASE_PREFIX = "sandbox-egress-lease";
|
|
688
|
+
const DEFAULT_SESSION_TTL_MS = 18e5;
|
|
689
|
+
/** Treat a cached lease as expired this long before its provider expiry. */
|
|
690
|
+
const LEASE_REFRESH_BUFFER_MS = 3e5;
|
|
691
|
+
/** True when this grant may keep shared auth headers on the host. */
|
|
692
|
+
function isSharedInstallationGrant(grant) {
|
|
693
|
+
return grant.name.startsWith("installation-");
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Build the host key for a shared installation grant.
|
|
697
|
+
*
|
|
698
|
+
* Only installation grants are remembered. User and other grants issue live
|
|
699
|
+
* headers each time, so they never write a host key.
|
|
700
|
+
*/
|
|
701
|
+
function leaseKey(provider, grant) {
|
|
702
|
+
return `${SANDBOX_EGRESS_LEASE_PREFIX}:${provider}:${grant.name}:shared`;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Build the command signal key for credential issuance failures by access level.
|
|
706
|
+
*/
|
|
707
|
+
function authSignalKey(egressId, access) {
|
|
708
|
+
return `${SANDBOX_EGRESS_AUTH_SIGNAL_PREFIX}:${egressId}:${access}`;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Build the command signal key for upstream permission denials by access level.
|
|
712
|
+
*/
|
|
713
|
+
function permissionSignalKey(egressId, access) {
|
|
714
|
+
return `${SANDBOX_EGRESS_PERMISSION_SIGNAL_PREFIX}:${egressId}:${access}`;
|
|
715
|
+
}
|
|
716
|
+
function base64Url(input) {
|
|
717
|
+
return Buffer.from(input, "utf8").toString("base64url");
|
|
718
|
+
}
|
|
719
|
+
function fromBase64Url(input) {
|
|
720
|
+
return Buffer.from(input, "base64url").toString("utf8");
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Sign a versioned context payload in the sandbox egress HMAC domain.
|
|
724
|
+
*
|
|
725
|
+
* `JUNIOR_SECRET` is the shared secret so proxy URLs cannot be forged by code
|
|
726
|
+
* running inside the sandbox.
|
|
727
|
+
*/
|
|
728
|
+
function signPayload(payload) {
|
|
729
|
+
return createHmac("sha256", getSandboxEgressSecret()).update(`${SANDBOX_EGRESS_HMAC_CONTEXT}:${payload}`).digest("base64url");
|
|
730
|
+
}
|
|
731
|
+
function timingSafeMatch(expected, actual) {
|
|
732
|
+
const expectedBuffer = Buffer.from(expected);
|
|
733
|
+
const actualBuffer = Buffer.from(actual);
|
|
734
|
+
if (expectedBuffer.length !== actualBuffer.length) return false;
|
|
735
|
+
return timingSafeEqual(expectedBuffer, actualBuffer);
|
|
736
|
+
}
|
|
737
|
+
function parseSandboxEgressContext(value) {
|
|
738
|
+
const result = sandboxEgressCredentialContextSchema.safeParse(value);
|
|
739
|
+
if (!result.success) return;
|
|
740
|
+
if (result.data.expiresAtMs <= Date.now()) return;
|
|
741
|
+
return result.data;
|
|
742
|
+
}
|
|
743
|
+
function parseLease(value) {
|
|
744
|
+
const result = sandboxEgressCredentialLeaseSchema.safeParse(value);
|
|
745
|
+
if (!result.success) return;
|
|
746
|
+
const expiresAtMs = Date.parse(result.data.expiresAt);
|
|
747
|
+
if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now() + LEASE_REFRESH_BUFFER_MS) return;
|
|
748
|
+
return result.data;
|
|
749
|
+
}
|
|
750
|
+
function getSandboxEgressSecret() {
|
|
751
|
+
const secret = getChatConfig().secrets.juniorSecret;
|
|
752
|
+
if (secret) return secret;
|
|
753
|
+
throw new Error("Cannot determine sandbox egress secret (set JUNIOR_SECRET)");
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Create the signed Junior credential context embedded in the proxy URL.
|
|
757
|
+
*
|
|
758
|
+
* The token binds actor credentials to a specific sandbox egress id and a
|
|
759
|
+
* short expiry. Vercel OIDC proves which VM sent a request; this token proves
|
|
760
|
+
* which Junior actor and credential context that VM is allowed to use.
|
|
761
|
+
*/
|
|
762
|
+
function createSandboxEgressCredentialToken(input) {
|
|
763
|
+
const ttlMs = Math.max(1, input.ttlMs ?? DEFAULT_SESSION_TTL_MS);
|
|
764
|
+
const now = Date.now();
|
|
765
|
+
const context = {
|
|
766
|
+
...input.conversationId ? { conversationId: input.conversationId } : void 0,
|
|
767
|
+
credentials: input.credentials,
|
|
768
|
+
egressId: input.egressId,
|
|
769
|
+
expiresAtMs: now + ttlMs,
|
|
770
|
+
contextId: randomUUID(),
|
|
771
|
+
...input.source ? { source: input.source } : void 0
|
|
772
|
+
};
|
|
773
|
+
const payload = `${SANDBOX_EGRESS_TOKEN_VERSION}.${base64Url(JSON.stringify(context))}`;
|
|
774
|
+
return `${payload}.${signPayload(payload)}`;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Verify the signed Junior credential context from the proxy URL.
|
|
778
|
+
*
|
|
779
|
+
* Returning `undefined` means the token is missing, expired, malformed, or not
|
|
780
|
+
* signed with the current `JUNIOR_SECRET`.
|
|
781
|
+
*/
|
|
782
|
+
function parseSandboxEgressCredentialToken(token) {
|
|
783
|
+
if (!token) return;
|
|
784
|
+
const parts = token.split(".");
|
|
785
|
+
if (parts.length !== 3 || parts[0] !== SANDBOX_EGRESS_TOKEN_VERSION) return;
|
|
786
|
+
const encodedSession = parts[1];
|
|
787
|
+
const signature = parts[2];
|
|
788
|
+
if (!encodedSession || !signature) return;
|
|
789
|
+
if (!timingSafeMatch(signPayload(`${parts[0]}.${encodedSession}`), signature)) return;
|
|
790
|
+
try {
|
|
791
|
+
return parseSandboxEgressContext(JSON.parse(fromBase64Url(encodedSession)));
|
|
792
|
+
} catch {
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Remember auth headers for a shared installation grant.
|
|
798
|
+
*
|
|
799
|
+
* User and other grants are ignored here. TTL follows the provider expiry.
|
|
800
|
+
* Sandbox context expiry still decides whether a request may use the headers;
|
|
801
|
+
* it does not shorten a shared installation grant for other sandboxes.
|
|
802
|
+
*/
|
|
803
|
+
async function setSandboxEgressCredentialLease(_context, lease) {
|
|
804
|
+
if (!isSharedInstallationGrant(lease.grant)) return;
|
|
805
|
+
const leaseExpiresAtMs = Date.parse(lease.expiresAt);
|
|
806
|
+
if (!Number.isFinite(leaseExpiresAtMs) || leaseExpiresAtMs <= Date.now()) return;
|
|
807
|
+
const ttlMs = Math.max(1, leaseExpiresAtMs - Date.now());
|
|
808
|
+
const state = getStateAdapter();
|
|
809
|
+
await state.connect();
|
|
810
|
+
await createEncryptedState(state).set(leaseKey(lease.provider, lease.grant), lease, ttlMs);
|
|
811
|
+
}
|
|
812
|
+
/** Load remembered auth headers for a shared installation grant. */
|
|
813
|
+
async function getSandboxEgressCredentialLease(provider, grant, _context) {
|
|
814
|
+
if (!isSharedInstallationGrant(grant)) return;
|
|
815
|
+
const state = getStateAdapter();
|
|
816
|
+
await state.connect();
|
|
817
|
+
const stored = await readEncryptedState(state, leaseKey(provider, grant));
|
|
818
|
+
return stored?.stale ? void 0 : parseLease(stored?.value);
|
|
819
|
+
}
|
|
820
|
+
/** Drop remembered installation headers after the upstream rejects them. */
|
|
821
|
+
async function clearSandboxEgressCredentialLease(provider, grant, _context) {
|
|
822
|
+
if (!isSharedInstallationGrant(grant)) return;
|
|
823
|
+
const state = getStateAdapter();
|
|
824
|
+
await state.connect();
|
|
825
|
+
await state.delete(leaseKey(provider, grant));
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Record that credential issuance needs user authorization for this command.
|
|
829
|
+
*
|
|
830
|
+
* The command runner consumes this after the sandbox tool finishes so the agent
|
|
831
|
+
* can present a normal authorization-required response instead of a raw proxy
|
|
832
|
+
* failure.
|
|
833
|
+
*/
|
|
834
|
+
async function setSandboxEgressAuthRequiredSignal(context, signal) {
|
|
835
|
+
const ttlMs = Math.max(1, context.expiresAtMs - Date.now());
|
|
836
|
+
const state = getStateAdapter();
|
|
837
|
+
await state.connect();
|
|
838
|
+
await state.set(authSignalKey(context.egressId, signal.grant.access), {
|
|
839
|
+
...signal,
|
|
840
|
+
createdAtMs: Date.now()
|
|
841
|
+
}, ttlMs);
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Record that the provider rejected an issued credential, or that Junior's
|
|
845
|
+
* egress policy refused the request before it chose a credential.
|
|
846
|
+
*/
|
|
847
|
+
async function setSandboxEgressPermissionDeniedSignal(context, signal) {
|
|
848
|
+
const ttlMs = Math.max(1, context.expiresAtMs - Date.now());
|
|
849
|
+
const state = getStateAdapter();
|
|
850
|
+
await state.connect();
|
|
851
|
+
await state.set(permissionSignalKey(context.egressId, signal.source === "upstream" ? signal.grant.access : "write"), {
|
|
852
|
+
...signal,
|
|
853
|
+
createdAtMs: Date.now()
|
|
854
|
+
}, ttlMs);
|
|
855
|
+
}
|
|
856
|
+
/** Remove pending auth/permission signals before or after a sandbox command. */
|
|
857
|
+
async function clearSandboxEgressSignals(egressId) {
|
|
858
|
+
if (!egressId) return;
|
|
859
|
+
const state = getStateAdapter();
|
|
860
|
+
await state.connect();
|
|
861
|
+
await Promise.all([
|
|
862
|
+
state.delete(authSignalKey(egressId, "read")),
|
|
863
|
+
state.delete(authSignalKey(egressId, "write")),
|
|
864
|
+
state.delete(permissionSignalKey(egressId, "read")),
|
|
865
|
+
state.delete(permissionSignalKey(egressId, "write"))
|
|
866
|
+
]);
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Consume the auth signal produced during a sandbox command, preferring writes.
|
|
870
|
+
*/
|
|
871
|
+
async function consumeSandboxEgressAuthRequiredSignal(egressId) {
|
|
872
|
+
if (!egressId) return;
|
|
873
|
+
const state = getStateAdapter();
|
|
874
|
+
await state.connect();
|
|
875
|
+
const [writeSignal, readSignal] = await Promise.all([state.get(authSignalKey(egressId, "write")), state.get(authSignalKey(egressId, "read"))]);
|
|
876
|
+
const signal = parseSandboxEgressAuthRequiredSignal(writeSignal) ?? parseSandboxEgressAuthRequiredSignal(readSignal);
|
|
877
|
+
await Promise.all([state.delete(authSignalKey(egressId, "read")), state.delete(authSignalKey(egressId, "write"))]);
|
|
878
|
+
return signal;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Consume the permission signal produced during a sandbox command, preferring writes.
|
|
882
|
+
*/
|
|
883
|
+
async function consumeSandboxEgressPermissionDeniedSignal(egressId) {
|
|
884
|
+
if (!egressId) return;
|
|
885
|
+
const state = getStateAdapter();
|
|
886
|
+
await state.connect();
|
|
887
|
+
const [writeSignal, readSignal] = await Promise.all([state.get(permissionSignalKey(egressId, "write")), state.get(permissionSignalKey(egressId, "read"))]);
|
|
888
|
+
const signal = parseSandboxEgressPermissionDeniedSignal(writeSignal) ?? parseSandboxEgressPermissionDeniedSignal(readSignal);
|
|
889
|
+
await Promise.all([state.delete(permissionSignalKey(egressId, "read")), state.delete(permissionSignalKey(egressId, "write"))]);
|
|
890
|
+
return signal;
|
|
891
|
+
}
|
|
892
|
+
// src/chat/sandbox/egress/credentials.ts
|
|
893
|
+
const HTTP_READ_METHODS = /* @__PURE__ */ new Set([
|
|
894
|
+
"GET",
|
|
895
|
+
"HEAD",
|
|
896
|
+
"OPTIONS"
|
|
897
|
+
]);
|
|
898
|
+
const WORKLOAD_IDENTITY_GRANT_NAME = "installation-workload-identity";
|
|
899
|
+
/**
|
|
900
|
+
* Signals that egress selected a grant but could not issue credential headers.
|
|
901
|
+
*
|
|
902
|
+
* Callers convert this into command-level auth-required state so the agent can
|
|
903
|
+
* request authorization without exposing provider-specific lease internals.
|
|
904
|
+
*/
|
|
905
|
+
var SandboxEgressCredentialError = class extends Error {
|
|
906
|
+
authorization;
|
|
907
|
+
grant;
|
|
908
|
+
kind;
|
|
909
|
+
provider;
|
|
910
|
+
constructor(input) {
|
|
911
|
+
super(input.message);
|
|
912
|
+
this.name = "SandboxEgressCredentialError";
|
|
913
|
+
this.authorization = input.authorization;
|
|
914
|
+
this.grant = input.grant;
|
|
915
|
+
this.kind = input.kind;
|
|
916
|
+
this.provider = input.provider;
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
/** True when the provider's credential is a host-minted workload identity token. */
|
|
920
|
+
function isWorkloadIdentityProvider(provider) {
|
|
921
|
+
return pluginCatalogRuntime.getDefinition(provider)?.manifest.credentials?.type === "workload-identity";
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Add a workload identity plugin's static `api-headers` to its lease.
|
|
925
|
+
*
|
|
926
|
+
* The shared lease in host state holds only the minted token. Static values,
|
|
927
|
+
* such as an app API key, resolve from env on each request instead.
|
|
928
|
+
*/
|
|
929
|
+
function withStaticApiHeaders(lease) {
|
|
930
|
+
const manifest = pluginCatalogRuntime.getDefinition(lease.provider)?.manifest;
|
|
931
|
+
if (manifest?.credentials?.type !== "workload-identity") return lease;
|
|
932
|
+
return {
|
|
933
|
+
...lease,
|
|
934
|
+
headerTransforms: mergeHeaderTransforms([...resolveApiHeaderTransforms(manifest), ...lease.headerTransforms])
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
function defaultGrantForProvider(input) {
|
|
938
|
+
const access = HTTP_READ_METHODS.has(input.method.toUpperCase()) ? "read" : "write";
|
|
939
|
+
return {
|
|
940
|
+
source: "broker",
|
|
941
|
+
grant: {
|
|
942
|
+
name: isWorkloadIdentityProvider(input.provider) ? WORKLOAD_IDENTITY_GRANT_NAME : "default",
|
|
943
|
+
access,
|
|
944
|
+
reason: `sandbox-egress:${input.provider}:${access}`
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
function hasGenericCredentials(provider) {
|
|
949
|
+
const manifest = pluginCatalogRuntime.getDefinition(provider)?.manifest;
|
|
950
|
+
return Boolean(manifest?.credentials || manifest?.apiHeaders);
|
|
951
|
+
}
|
|
952
|
+
function oauthAuthorizationForProvider(provider) {
|
|
953
|
+
const oauth = pluginCatalogRuntime.getOAuthConfig(provider);
|
|
954
|
+
return oauth ? {
|
|
955
|
+
type: "oauth",
|
|
956
|
+
provider,
|
|
957
|
+
...oauth.scope ? { scope: oauth.scope } : void 0
|
|
958
|
+
} : void 0;
|
|
959
|
+
}
|
|
960
|
+
function credentialSubjectFromContext(context) {
|
|
961
|
+
return "subject" in context.credentials && context.credentials.subject ? {
|
|
962
|
+
type: "user",
|
|
963
|
+
userId: context.credentials.subject.userId
|
|
964
|
+
} : void 0;
|
|
965
|
+
}
|
|
966
|
+
function assertLeaseTransformsOwnedByProvider(provider, lease) {
|
|
967
|
+
for (const transform of lease.headerTransforms) if (resolveSandboxEgressProviderForHost(transform.domain) !== provider) throw new Error(`Credential lease for ${provider} included header transform for unowned domain ${transform.domain}`);
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Select the grant needed for one outbound request.
|
|
971
|
+
*
|
|
972
|
+
* GitHub GraphQL and other plugin-owned APIs may need body-aware grant choices;
|
|
973
|
+
* providers without hooks use a simple read/write default based on HTTP method.
|
|
974
|
+
* A hook plugin that also declares generic credentials can return no grant to
|
|
975
|
+
* use that default for one request.
|
|
976
|
+
*/
|
|
977
|
+
async function selectSandboxEgressGrant(input) {
|
|
978
|
+
if (input.userOAuthOnly) {
|
|
979
|
+
const manifest = pluginCatalogRuntime.getDefinition(input.provider)?.manifest;
|
|
980
|
+
if (!manifest?.credentials || !manifest.oauth) throw new Error(`Plugin "${input.provider}" has no user OAuth for user-only egress`);
|
|
981
|
+
return defaultGrantForProvider(input);
|
|
982
|
+
}
|
|
983
|
+
if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
|
|
984
|
+
const pluginGrant = await selectPluginGrant({
|
|
985
|
+
...input.withoutCredential ? { withoutCredential: true } : void 0,
|
|
986
|
+
...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
|
|
987
|
+
...input.conversationId ? { conversationId: input.conversationId } : void 0,
|
|
988
|
+
...input.gitPush ? { gitPush: input.gitPush } : void 0,
|
|
989
|
+
...input.graphql ? { graphql: input.graphql } : void 0,
|
|
990
|
+
...input.operation ? { operation: input.operation } : void 0,
|
|
991
|
+
provider: input.provider,
|
|
992
|
+
method: input.method,
|
|
993
|
+
upstreamUrl: input.upstreamUrl
|
|
994
|
+
});
|
|
995
|
+
if (input.withoutCredential) return defaultGrantForProvider(input);
|
|
996
|
+
if (!pluginGrant) {
|
|
997
|
+
if (hasGenericCredentials(input.provider)) return defaultGrantForProvider(input);
|
|
998
|
+
throw new Error(`Plugin "${input.provider}" grantForEgress must return a grant for sandbox egress`);
|
|
999
|
+
}
|
|
1000
|
+
return {
|
|
1001
|
+
source: "plugin",
|
|
1002
|
+
grant: pluginGrant
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Resolve the authorization flow attached to a broker-selected egress grant.
|
|
1007
|
+
*
|
|
1008
|
+
* Plugin-selected grants can return their own authorization metadata when
|
|
1009
|
+
* issuing credentials; broker defaults use the provider OAuth config.
|
|
1010
|
+
*/
|
|
1011
|
+
function authorizationForSandboxEgressGrant(provider, selection) {
|
|
1012
|
+
return selection.source === "broker" ? oauthAuthorizationForProvider(provider) : void 0;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Return credential header transforms for a selected grant.
|
|
1016
|
+
*
|
|
1017
|
+
* Only shared installation grants are remembered on the host. User and other
|
|
1018
|
+
* grants always issue from the live credential source so a saved login change
|
|
1019
|
+
* cannot leave stale auth headers in place. The sandbox context only authorizes
|
|
1020
|
+
* the request.
|
|
1021
|
+
*/
|
|
1022
|
+
async function sandboxEgressCredentialLease(provider, selection, context, operation) {
|
|
1023
|
+
const { grant } = selection;
|
|
1024
|
+
const cached = await getSandboxEgressCredentialLease(provider, grant, context);
|
|
1025
|
+
if (cached) {
|
|
1026
|
+
if (selection.source === "plugin" && cached.grant.access !== grant.access) throw new Error(`Cached credential lease for ${provider}/${grant.name} has ${cached.grant.access} access, but ${grant.access} was selected`);
|
|
1027
|
+
return withStaticApiHeaders({
|
|
1028
|
+
...cached,
|
|
1029
|
+
grant
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
let lease;
|
|
1033
|
+
if (selection.source === "plugin") {
|
|
1034
|
+
const credentialSubject = credentialSubjectFromContext(context);
|
|
1035
|
+
const pluginResult = await issuePluginCredential({
|
|
1036
|
+
provider,
|
|
1037
|
+
grant,
|
|
1038
|
+
actor: context.credentials.actor,
|
|
1039
|
+
...credentialSubject ? { credentialSubject } : void 0,
|
|
1040
|
+
userTokenStore: createUserTokenStore()
|
|
1041
|
+
});
|
|
1042
|
+
if (pluginResult.type === "needed") throw new SandboxEgressCredentialError({
|
|
1043
|
+
provider,
|
|
1044
|
+
grant,
|
|
1045
|
+
kind: "auth_required",
|
|
1046
|
+
authorization: pluginResult.authorization,
|
|
1047
|
+
message: pluginResult.message
|
|
1048
|
+
});
|
|
1049
|
+
if (pluginResult.type === "unavailable") throw new SandboxEgressCredentialError({
|
|
1050
|
+
provider,
|
|
1051
|
+
grant,
|
|
1052
|
+
kind: "unavailable",
|
|
1053
|
+
message: pluginResult.message
|
|
1054
|
+
});
|
|
1055
|
+
lease = pluginResult.lease;
|
|
1056
|
+
} else try {
|
|
1057
|
+
lease = await issueProviderCredentialLease({
|
|
1058
|
+
context: context.credentials,
|
|
1059
|
+
...operation ? { operation } : void 0,
|
|
1060
|
+
provider,
|
|
1061
|
+
reason: grant.reason ?? `sandbox-egress:${provider}:default`
|
|
1062
|
+
});
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
if (error instanceof CredentialMintError || error instanceof ServiceAccountUnavailableError) throw new SandboxEgressCredentialError({
|
|
1065
|
+
provider,
|
|
1066
|
+
grant,
|
|
1067
|
+
kind: "unavailable",
|
|
1068
|
+
message: error.message
|
|
1069
|
+
});
|
|
1070
|
+
if (error instanceof CredentialUnavailableError) throw new SandboxEgressCredentialError({
|
|
1071
|
+
provider,
|
|
1072
|
+
grant,
|
|
1073
|
+
kind: "auth_required",
|
|
1074
|
+
authorization: authorizationForSandboxEgressGrant(provider, selection),
|
|
1075
|
+
message: error.message
|
|
1076
|
+
});
|
|
1077
|
+
throw error;
|
|
1078
|
+
}
|
|
1079
|
+
const headerTransforms = lease.headerTransforms ?? [];
|
|
1080
|
+
if (headerTransforms.length === 0) throw new Error(`Credential lease for ${provider} did not include header transforms`);
|
|
1081
|
+
const leaseExpiresAtMs = Date.parse(lease.expiresAt);
|
|
1082
|
+
if (!Number.isFinite(leaseExpiresAtMs) || leaseExpiresAtMs <= Date.now()) throw new Error(`Credential lease for ${provider} is expired`);
|
|
1083
|
+
const authorization = selection.source === "broker" ? oauthAuthorizationForProvider(provider) : lease.authorization;
|
|
1084
|
+
const issuedLease = {
|
|
1085
|
+
provider,
|
|
1086
|
+
grant,
|
|
1087
|
+
...lease.account ? { account: lease.account } : void 0,
|
|
1088
|
+
...authorization ? { authorization } : void 0,
|
|
1089
|
+
expiresAt: lease.expiresAt,
|
|
1090
|
+
headerTransforms
|
|
1091
|
+
};
|
|
1092
|
+
assertLeaseTransformsOwnedByProvider(provider, issuedLease);
|
|
1093
|
+
await setSandboxEgressCredentialLease(context, issuedLease);
|
|
1094
|
+
return withStaticApiHeaders(issuedLease);
|
|
1095
|
+
}
|
|
1096
|
+
/** Return whether a credential lease can modify requests to the target host. */
|
|
1097
|
+
function hasSandboxEgressLeaseTransformForHost(lease, host) {
|
|
1098
|
+
return lease.headerTransforms.some((transform) => matchesSandboxEgressDomain(host, transform.domain));
|
|
1099
|
+
}
|
|
1100
|
+
// src/chat/egress/response-text.ts
|
|
1101
|
+
const RESPONSE_BODY_TEXT_LIMIT_BYTES = 65536;
|
|
1102
|
+
function responseContentLength(upstream) {
|
|
1103
|
+
const raw = upstream.headers.get("content-length");
|
|
1104
|
+
if (!raw) return;
|
|
1105
|
+
const parsed = Number(raw);
|
|
1106
|
+
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
|
|
1107
|
+
}
|
|
1108
|
+
/** Read a copy of a response body as text, or undefined past `maxBytes`. */
|
|
1109
|
+
async function responseTextWithinLimit(upstream, maxBytes) {
|
|
1110
|
+
const limit = Math.min(Math.max(0, Math.floor(maxBytes)), RESPONSE_BODY_TEXT_LIMIT_BYTES);
|
|
1111
|
+
if (limit <= 0) return;
|
|
1112
|
+
const contentLength = responseContentLength(upstream);
|
|
1113
|
+
if (contentLength !== void 0 && contentLength > limit) return;
|
|
1114
|
+
let clone;
|
|
1115
|
+
try {
|
|
1116
|
+
clone = upstream.clone();
|
|
1117
|
+
} catch {
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
const body = clone.body;
|
|
1121
|
+
if (!body) return "";
|
|
1122
|
+
const chunks = [];
|
|
1123
|
+
let bytes = 0;
|
|
1124
|
+
try {
|
|
1125
|
+
for await (const value of body) {
|
|
1126
|
+
bytes += value.byteLength;
|
|
1127
|
+
if (bytes > limit) return;
|
|
1128
|
+
chunks.push(value);
|
|
1129
|
+
}
|
|
1130
|
+
} catch {
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
const combined = new Uint8Array(bytes);
|
|
1134
|
+
let offset = 0;
|
|
1135
|
+
for (const chunk of chunks) {
|
|
1136
|
+
combined.set(chunk, offset);
|
|
1137
|
+
offset += chunk.byteLength;
|
|
1138
|
+
}
|
|
1139
|
+
return new TextDecoder().decode(combined);
|
|
1140
|
+
}
|
|
1141
|
+
// src/chat/sandbox/egress/signals.ts
|
|
1142
|
+
/** Starts the body of the egress proxy's response for a missing credential. */
|
|
1143
|
+
const SANDBOX_EGRESS_AUTH_REQUIRED_MARKER = "junior-auth-required";
|
|
1144
|
+
// src/chat/egress/credentialed.ts
|
|
1145
|
+
const HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
1146
|
+
"connection",
|
|
1147
|
+
"host",
|
|
1148
|
+
"keep-alive",
|
|
1149
|
+
"proxy-authenticate",
|
|
1150
|
+
"proxy-authorization",
|
|
1151
|
+
"te",
|
|
1152
|
+
"trailer",
|
|
1153
|
+
"transfer-encoding",
|
|
1154
|
+
"upgrade"
|
|
1155
|
+
]);
|
|
1156
|
+
const PROXY_ONLY_HEADERS = /* @__PURE__ */ new Set([
|
|
1157
|
+
"vercel-sandbox-oidc-token",
|
|
1158
|
+
"vercel-forwarded-host",
|
|
1159
|
+
"vercel-forwarded-scheme",
|
|
1160
|
+
"vercel-forwarded-port",
|
|
1161
|
+
"vercel-forwarded-path"
|
|
1162
|
+
]);
|
|
1163
|
+
const TRACE_PROPAGATION_HEADERS = /* @__PURE__ */ new Set([
|
|
1164
|
+
"baggage",
|
|
1165
|
+
"sentry-trace",
|
|
1166
|
+
"traceparent"
|
|
1167
|
+
]);
|
|
1168
|
+
const DECODED_RESPONSE_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length"]);
|
|
1169
|
+
const UPSTREAM_TOKEN_REJECTION_STATUS = 401;
|
|
1170
|
+
const UPSTREAM_PERMISSION_REJECTION_STATUS = 403;
|
|
1171
|
+
const GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES = 65536;
|
|
1172
|
+
function authRequiredResult(authRequired, responseMessage = authRequired.message) {
|
|
1173
|
+
return {
|
|
1174
|
+
authRequired,
|
|
1175
|
+
response: new Response(`${SANDBOX_EGRESS_AUTH_REQUIRED_MARKER} provider=${authRequired.provider} grant=${authRequired.grant.name} access=${authRequired.grant.access} 401 unauthorized\n${responseMessage}`, {
|
|
1176
|
+
status: 401,
|
|
1177
|
+
headers: {
|
|
1178
|
+
"content-type": "text/plain; charset=utf-8",
|
|
1179
|
+
"cache-control": "no-store"
|
|
1180
|
+
}
|
|
1181
|
+
})
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
function policyDeniedResponse(error) {
|
|
1185
|
+
return Response.json({ error: error.message }, {
|
|
1186
|
+
status: 403,
|
|
1187
|
+
headers: { "cache-control": "no-store" }
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Name the egress decision on every outcome event, so one query over
|
|
1192
|
+
* `app.egress.policy.decision` gives the full trail for a request.
|
|
1193
|
+
*/
|
|
1194
|
+
function egressDecisionAttributes(decision, reason) {
|
|
1195
|
+
return reason ? {
|
|
1196
|
+
"app.egress.policy.decision": decision,
|
|
1197
|
+
"app.sandbox.egress.policy.reason": reason
|
|
1198
|
+
} : { "app.egress.policy.decision": decision };
|
|
1199
|
+
}
|
|
1200
|
+
function egressAttributes(input) {
|
|
1201
|
+
return {
|
|
1202
|
+
...input.egressId ? { "app.sandbox.egress_id": input.egressId } : void 0,
|
|
1203
|
+
...input.provider ? { "app.provider.name": input.provider } : void 0,
|
|
1204
|
+
...input.grantName ? { "app.grant.name": input.grantName } : void 0,
|
|
1205
|
+
...input.grantAccess ? { "app.grant.access": input.grantAccess } : void 0,
|
|
1206
|
+
...input.grantReason ? { "app.grant.reason": input.grantReason } : void 0,
|
|
1207
|
+
...input.host ? { "server.address": input.host } : void 0,
|
|
1208
|
+
...input.method ? { "http.request.method": input.method } : void 0,
|
|
1209
|
+
...input.path ? { "url.path": input.path } : void 0,
|
|
1210
|
+
...input.status ? { "http.response.status_code": input.status } : void 0
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
function routingAttributes(request, upstreamUrl) {
|
|
1214
|
+
const proxyUrl = new URL(request.url);
|
|
1215
|
+
const attributes = { "app.sandbox.egress.proxy_path": redactSandboxEgressProxyPath(proxyUrl.pathname) };
|
|
1216
|
+
if (upstreamUrl) {
|
|
1217
|
+
attributes["app.sandbox.egress.upstream_path"] = upstreamUrl.pathname;
|
|
1218
|
+
const gitService = upstreamUrl.searchParams.get("service");
|
|
1219
|
+
if (upstreamUrl.hostname.toLowerCase() === "github.com" && (gitService === "git-upload-pack" || gitService === "git-receive-pack")) attributes["app.sandbox.egress.git_service"] = gitService;
|
|
1220
|
+
}
|
|
1221
|
+
return attributes;
|
|
1222
|
+
}
|
|
1223
|
+
function displayedUpstreamPath(upstreamUrl) {
|
|
1224
|
+
const gitService = upstreamUrl.searchParams.get("service");
|
|
1225
|
+
if (upstreamUrl.hostname.toLowerCase() === "github.com" && (gitService === "git-upload-pack" || gitService === "git-receive-pack")) return `${upstreamUrl.pathname}?service=${gitService}`;
|
|
1226
|
+
return upstreamUrl.pathname;
|
|
1227
|
+
}
|
|
1228
|
+
function permissionDeniedMessage(provider, grant) {
|
|
1229
|
+
return `${provider} returned HTTP 403 after the runtime injected the ${grant.name} grant. The request was forwarded; this is not a local runtime block.`;
|
|
1230
|
+
}
|
|
1231
|
+
function isEgressAuthRequired(error) {
|
|
1232
|
+
return error instanceof EgressAuthRequired || error instanceof Error && error.name === "EgressAuthRequired";
|
|
1233
|
+
}
|
|
1234
|
+
function isEgressPolicyDenied(error) {
|
|
1235
|
+
return error instanceof EgressPolicyDenied || error instanceof Error && error.name === "EgressPolicyDenied";
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Record one forwarded provider request as an audit event, so Sentry keeps
|
|
1239
|
+
* reads and writes in production.
|
|
1240
|
+
*/
|
|
1241
|
+
function logSandboxEgressUpstreamRequest(input) {
|
|
1242
|
+
const { grant } = input.lease;
|
|
1243
|
+
logAudit("sandbox.egress.upstream.requested", {
|
|
1244
|
+
...egressAttributes({
|
|
1245
|
+
egressId: input.egressId,
|
|
1246
|
+
grantAccess: grant.access,
|
|
1247
|
+
grantName: grant.name,
|
|
1248
|
+
grantReason: grant.reason,
|
|
1249
|
+
host: input.upstreamUrl.hostname,
|
|
1250
|
+
method: input.request.method,
|
|
1251
|
+
path: input.upstreamUrl.pathname,
|
|
1252
|
+
provider: input.provider,
|
|
1253
|
+
status: input.upstream.status
|
|
1254
|
+
}),
|
|
1255
|
+
...routingAttributes(input.request, input.upstreamUrl),
|
|
1256
|
+
...credentialAuditAttributes(input.credentialContext.source),
|
|
1257
|
+
...grant.auditAttributes,
|
|
1258
|
+
"app.credential.account": credentialAccount(input.lease, input.credentialContext.credentials),
|
|
1259
|
+
...egressDecisionAttributes("allowed"),
|
|
1260
|
+
"app.sandbox.egress.upstream_ok": input.upstream.ok
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
async function requestBodyBytes(request) {
|
|
1264
|
+
if (request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS" || request.body === null) return;
|
|
1265
|
+
return await request.arrayBuffer();
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Explain a request body that the runtime delivered already used.
|
|
1269
|
+
*
|
|
1270
|
+
* The forwarded headers cannot show whether the body was empty, so the proxy
|
|
1271
|
+
* does not send a credentialed write upstream without its payload.
|
|
1272
|
+
*/
|
|
1273
|
+
function unreadableBodyResponse(eventId) {
|
|
1274
|
+
return Response.json({
|
|
1275
|
+
source: "junior-egress",
|
|
1276
|
+
error: "The sandbox egress proxy could not read the request body, so it did not send the request upstream.",
|
|
1277
|
+
...eventId ? { sentryEventId: eventId } : void 0
|
|
1278
|
+
}, {
|
|
1279
|
+
status: 500,
|
|
1280
|
+
headers: { "cache-control": "no-store" }
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
/** Identify GitHub review writes whose body decides whether a grant is safe. */
|
|
1284
|
+
function isGitHubPullRequestReviewPost(input) {
|
|
1285
|
+
return input.provider === "github" && input.requestMethod.toUpperCase() === "POST" && input.upstreamUrl.hostname.toLowerCase() === "api.github.com" && /^\/repos\/[^/]+\/[^/]+\/pulls\/[^/]+\/reviews(?:\/[^/]+\/events)?$/.test(input.upstreamUrl.pathname.toLowerCase());
|
|
1286
|
+
}
|
|
1287
|
+
function grantSelectionBodyText(body) {
|
|
1288
|
+
if (body === void 0) return;
|
|
1289
|
+
if (body.byteLength > GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES) throw new EgressPolicyDenied("GitHub pull request review request body is too large to inspect before issuing credentials.");
|
|
1290
|
+
return new TextDecoder().decode(body);
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Build the upstream request headers.
|
|
1294
|
+
*
|
|
1295
|
+
* Sandbox/proxy-only headers are stripped so they cannot leak to providers, and
|
|
1296
|
+
* trace headers are preserved only for hosts opted into trace propagation.
|
|
1297
|
+
* Credential lease transforms win last because they are the host-issued
|
|
1298
|
+
* authority for provider auth headers.
|
|
1299
|
+
*/
|
|
1300
|
+
function requestHeaders$1(request, headerTransforms, upstreamHost, tracePropagation) {
|
|
1301
|
+
const headers = new Headers();
|
|
1302
|
+
const mayPropagateTrace = shouldPropagateSandboxEgressTrace(upstreamHost, tracePropagation);
|
|
1303
|
+
for (const [key, value] of request.headers) {
|
|
1304
|
+
const normalized = key.toLowerCase();
|
|
1305
|
+
if (HOP_BY_HOP_HEADERS.has(normalized) || PROXY_ONLY_HEADERS.has(normalized)) continue;
|
|
1306
|
+
if (TRACE_PROPAGATION_HEADERS.has(normalized) && !mayPropagateTrace) continue;
|
|
1307
|
+
headers.append(key, value);
|
|
1308
|
+
}
|
|
1309
|
+
for (const transform of headerTransforms) {
|
|
1310
|
+
if (!matchesSandboxEgressDomain(upstreamHost, transform.domain)) continue;
|
|
1311
|
+
for (const [key, value] of Object.entries(transform.headers)) {
|
|
1312
|
+
if (TRACE_PROPAGATION_HEADERS.has(key.toLowerCase()) && !mayPropagateTrace) continue;
|
|
1313
|
+
headers.set(key, value);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
return headers;
|
|
1317
|
+
}
|
|
1318
|
+
function responseHeaders(upstream) {
|
|
1319
|
+
const headers = new Headers();
|
|
1320
|
+
for (const [key, value] of upstream.headers) {
|
|
1321
|
+
const normalized = key.toLowerCase();
|
|
1322
|
+
if (!HOP_BY_HOP_HEADERS.has(normalized) && !DECODED_RESPONSE_HEADERS.has(normalized)) headers.append(key, value);
|
|
1323
|
+
}
|
|
1324
|
+
return headers;
|
|
1325
|
+
}
|
|
1326
|
+
function leaseLogAttributes(input) {
|
|
1327
|
+
return {
|
|
1328
|
+
...egressAttributes({
|
|
1329
|
+
egressId: input.egressId,
|
|
1330
|
+
grantAccess: input.lease.grant.access,
|
|
1331
|
+
grantName: input.lease.grant.name,
|
|
1332
|
+
grantReason: input.lease.grant.reason,
|
|
1333
|
+
host: input.upstreamUrl.hostname,
|
|
1334
|
+
method: input.request.method,
|
|
1335
|
+
path: input.upstreamUrl.pathname,
|
|
1336
|
+
provider: input.provider,
|
|
1337
|
+
status: input.status
|
|
1338
|
+
}),
|
|
1339
|
+
...routingAttributes(input.request, input.upstreamUrl)
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
async function recordSandboxPermissionDenied(input) {
|
|
1343
|
+
await setSandboxEgressPermissionDeniedSignal(input.credentialContext, {
|
|
1344
|
+
provider: input.provider,
|
|
1345
|
+
grant: input.lease.grant,
|
|
1346
|
+
...input.lease.account ? { account: input.lease.account } : void 0,
|
|
1347
|
+
message: input.message,
|
|
1348
|
+
source: "upstream",
|
|
1349
|
+
status: input.upstream.status,
|
|
1350
|
+
upstreamHost: input.upstreamUrl.hostname,
|
|
1351
|
+
upstreamPath: displayedUpstreamPath(input.upstreamUrl)
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
async function recordSandboxPolicyDenied(input) {
|
|
1355
|
+
await setSandboxEgressPermissionDeniedSignal(input.credentialContext, {
|
|
1356
|
+
message: input.message,
|
|
1357
|
+
method: input.request.method.toUpperCase(),
|
|
1358
|
+
provider: input.provider,
|
|
1359
|
+
source: "policy",
|
|
1360
|
+
upstreamHost: input.upstreamUrl.hostname,
|
|
1361
|
+
upstreamPath: displayedUpstreamPath(input.upstreamUrl)
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* Forward a request that gets no credential, with its own headers.
|
|
1366
|
+
*
|
|
1367
|
+
* Proxy-only and hop-by-hop headers are still stripped, and trace headers
|
|
1368
|
+
* follow the same propagation rules as credentialed requests.
|
|
1369
|
+
*/
|
|
1370
|
+
async function forwardWithoutCredential(input) {
|
|
1371
|
+
const { body, deps, provider, request, upstreamUrl } = input;
|
|
1372
|
+
const headers = requestHeaders$1(request, [], upstreamUrl.hostname, deps.tracePropagation ?? {});
|
|
1373
|
+
const intercepted = await deps.interceptHttp?.({
|
|
1374
|
+
provider,
|
|
1375
|
+
request: new Request(upstreamUrl, {
|
|
1376
|
+
method: request.method,
|
|
1377
|
+
headers,
|
|
1378
|
+
...body !== void 0 ? { body } : void 0
|
|
1379
|
+
}),
|
|
1380
|
+
upstreamUrl
|
|
1381
|
+
});
|
|
1382
|
+
if (intercepted) return intercepted;
|
|
1383
|
+
const upstream = await (deps.fetch ?? fetch)(upstreamUrl, {
|
|
1384
|
+
method: request.method,
|
|
1385
|
+
headers,
|
|
1386
|
+
...body !== void 0 ? { body } : void 0,
|
|
1387
|
+
redirect: "manual"
|
|
1388
|
+
});
|
|
1389
|
+
logAudit("sandbox.egress.upstream.requested", {
|
|
1390
|
+
...egressAttributes({
|
|
1391
|
+
egressId: input.activeEgressId,
|
|
1392
|
+
host: upstreamUrl.hostname,
|
|
1393
|
+
method: request.method,
|
|
1394
|
+
path: upstreamUrl.pathname,
|
|
1395
|
+
provider,
|
|
1396
|
+
status: upstream.status
|
|
1397
|
+
}),
|
|
1398
|
+
...routingAttributes(request, upstreamUrl),
|
|
1399
|
+
...credentialAuditAttributes(input.credentialContext.source),
|
|
1400
|
+
...egressDecisionAttributes("allowed"),
|
|
1401
|
+
"app.sandbox.egress.credential_request": input.credentialRequest,
|
|
1402
|
+
"app.sandbox.egress.upstream_ok": upstream.ok
|
|
1403
|
+
});
|
|
1404
|
+
return new Response(upstream.body, {
|
|
1405
|
+
status: upstream.status,
|
|
1406
|
+
statusText: upstream.statusText,
|
|
1407
|
+
headers: responseHeaders(upstream)
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* Forward one verified sandbox egress request with host-managed credentials.
|
|
1412
|
+
*
|
|
1413
|
+
* The caller must already have authenticated the sandbox VM, checked the signed
|
|
1414
|
+
* credential context, and resolved the provider for `upstreamUrl`. This function
|
|
1415
|
+
* then selects the read/write grant, issues or reuses a short-lived credential
|
|
1416
|
+
* lease, and applies its header transforms. A provider auth failure becomes a
|
|
1417
|
+
* 401 response and `authRequired`, not raw upstream details for the agent.
|
|
1418
|
+
*/
|
|
1419
|
+
async function executeCredentialedEgressRequest(input) {
|
|
1420
|
+
const { activeEgressId, credentialContext, deps, operation, provider, request, upstreamUrl } = input;
|
|
1421
|
+
let body;
|
|
1422
|
+
try {
|
|
1423
|
+
body = await requestBodyBytes(request);
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
if (!(error instanceof TypeError)) throw error;
|
|
1426
|
+
return { response: unreadableBodyResponse(logException(error, "sandbox.egress.request_body.unreadable", {
|
|
1427
|
+
...egressAttributes({
|
|
1428
|
+
egressId: activeEgressId,
|
|
1429
|
+
host: upstreamUrl.hostname,
|
|
1430
|
+
method: request.method,
|
|
1431
|
+
path: upstreamUrl.pathname,
|
|
1432
|
+
provider,
|
|
1433
|
+
status: 500
|
|
1434
|
+
}),
|
|
1435
|
+
...routingAttributes(request, upstreamUrl),
|
|
1436
|
+
...credentialAuditAttributes(credentialContext.source),
|
|
1437
|
+
...egressDecisionAttributes("denied", "request body is unreadable")
|
|
1438
|
+
})) };
|
|
1439
|
+
}
|
|
1440
|
+
let grantSelection;
|
|
1441
|
+
try {
|
|
1442
|
+
grantSelection = await selectSandboxEgressGrant({
|
|
1443
|
+
...isGitHubPullRequestReviewPost({
|
|
1444
|
+
provider,
|
|
1445
|
+
requestMethod: request.method,
|
|
1446
|
+
upstreamUrl
|
|
1447
|
+
}) ? { bodyText: grantSelectionBodyText(body) } : void 0,
|
|
1448
|
+
...credentialContext.conversationId ? { conversationId: credentialContext.conversationId } : void 0,
|
|
1449
|
+
...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
|
|
1450
|
+
...isGraphqlPost(request.method, upstreamUrl) ? { graphql: await readGraphqlRequest(body) } : void 0,
|
|
1451
|
+
...operation ? { operation } : void 0,
|
|
1452
|
+
...input.userOAuthOnly ? { userOAuthOnly: true } : void 0,
|
|
1453
|
+
...input.withoutCredential ? { withoutCredential: true } : void 0,
|
|
1454
|
+
provider,
|
|
1455
|
+
method: request.method,
|
|
1456
|
+
upstreamUrl
|
|
1457
|
+
});
|
|
1458
|
+
} catch (error) {
|
|
1459
|
+
if (isEgressPolicyDenied(error)) {
|
|
1460
|
+
logWarn("sandbox.egress.policy.denied", {
|
|
1461
|
+
...egressAttributes({
|
|
1462
|
+
egressId: activeEgressId,
|
|
1463
|
+
host: upstreamUrl.hostname,
|
|
1464
|
+
method: request.method,
|
|
1465
|
+
path: upstreamUrl.pathname,
|
|
1466
|
+
provider,
|
|
1467
|
+
status: 403
|
|
1468
|
+
}),
|
|
1469
|
+
...routingAttributes(request, upstreamUrl),
|
|
1470
|
+
...credentialAuditAttributes(credentialContext.source),
|
|
1471
|
+
...pluginAuditAttributesSchema.safeParse(error.auditAttributes).data,
|
|
1472
|
+
...egressDecisionAttributes("denied", error.message)
|
|
1473
|
+
});
|
|
1474
|
+
await recordSandboxPolicyDenied({
|
|
1475
|
+
credentialContext,
|
|
1476
|
+
message: error.message,
|
|
1477
|
+
provider,
|
|
1478
|
+
request,
|
|
1479
|
+
upstreamUrl
|
|
1480
|
+
});
|
|
1481
|
+
return { response: policyDeniedResponse(error) };
|
|
1482
|
+
}
|
|
1483
|
+
throw error;
|
|
1484
|
+
}
|
|
1485
|
+
if (input.withoutCredential) return { response: await forwardWithoutCredential({
|
|
1486
|
+
activeEgressId,
|
|
1487
|
+
body,
|
|
1488
|
+
credentialContext,
|
|
1489
|
+
credentialRequest: input.withoutCredential,
|
|
1490
|
+
deps,
|
|
1491
|
+
provider,
|
|
1492
|
+
request,
|
|
1493
|
+
upstreamUrl
|
|
1494
|
+
}) };
|
|
1495
|
+
async function resolveLease() {
|
|
1496
|
+
try {
|
|
1497
|
+
return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext, operation);
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
if (!(error instanceof SandboxEgressCredentialError)) throw error;
|
|
1500
|
+
const isAuthRequired = error.kind === "auth_required";
|
|
1501
|
+
logWarn(isAuthRequired ? "sandbox.egress.credential.needed" : "sandbox.egress.credential.unavailable", {
|
|
1502
|
+
...egressAttributes({
|
|
1503
|
+
egressId: activeEgressId,
|
|
1504
|
+
grantAccess: error.grant.access,
|
|
1505
|
+
grantName: error.grant.name,
|
|
1506
|
+
grantReason: error.grant.reason,
|
|
1507
|
+
host: upstreamUrl.hostname,
|
|
1508
|
+
method: request.method,
|
|
1509
|
+
path: upstreamUrl.pathname,
|
|
1510
|
+
provider: error.provider,
|
|
1511
|
+
status: 401
|
|
1512
|
+
}),
|
|
1513
|
+
...routingAttributes(request, upstreamUrl),
|
|
1514
|
+
...credentialAuditAttributes(credentialContext.source),
|
|
1515
|
+
...egressDecisionAttributes("denied", error.message)
|
|
1516
|
+
});
|
|
1517
|
+
return authRequiredResult({
|
|
1518
|
+
...error.authorization ? { authorization: error.authorization } : void 0,
|
|
1519
|
+
grant: error.grant,
|
|
1520
|
+
kind: error.kind,
|
|
1521
|
+
message: error.message,
|
|
1522
|
+
provider: error.provider
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
let leased = await resolveLease();
|
|
1527
|
+
if ("response" in leased) return leased;
|
|
1528
|
+
let lease = leased;
|
|
1529
|
+
const attributes = (activeLease, status) => leaseLogAttributes({
|
|
1530
|
+
egressId: activeEgressId,
|
|
1531
|
+
lease: activeLease,
|
|
1532
|
+
provider,
|
|
1533
|
+
request,
|
|
1534
|
+
status,
|
|
1535
|
+
upstreamUrl
|
|
1536
|
+
});
|
|
1537
|
+
if (!hasSandboxEgressLeaseTransformForHost(lease, upstreamUrl.hostname)) {
|
|
1538
|
+
logWarn("sandbox.egress.transform.missing", {
|
|
1539
|
+
...attributes(lease, 403),
|
|
1540
|
+
...credentialAuditAttributes(credentialContext.source),
|
|
1541
|
+
...egressDecisionAttributes("denied", "credential lease does not cover forwarded host"),
|
|
1542
|
+
"app.sandbox.egress.transform_domains": lease.headerTransforms.map((transform) => transform.domain)
|
|
1543
|
+
});
|
|
1544
|
+
return { response: Response.json({ error: "Credential lease does not cover forwarded host" }, { status: 403 }) };
|
|
1545
|
+
}
|
|
1546
|
+
const fetchImpl = deps.fetch ?? fetch;
|
|
1547
|
+
let retriedAfter403 = false;
|
|
1548
|
+
while (true) {
|
|
1549
|
+
const headers = requestHeaders$1(request, lease.headerTransforms, upstreamUrl.hostname, deps.tracePropagation ?? {});
|
|
1550
|
+
const intercepted = await deps.interceptHttp?.({
|
|
1551
|
+
provider,
|
|
1552
|
+
request: new Request(upstreamUrl, {
|
|
1553
|
+
method: request.method,
|
|
1554
|
+
headers,
|
|
1555
|
+
...body !== void 0 ? { body } : void 0
|
|
1556
|
+
}),
|
|
1557
|
+
upstreamUrl
|
|
1558
|
+
});
|
|
1559
|
+
if (intercepted) return { response: intercepted };
|
|
1560
|
+
const requestBody = body instanceof ArrayBuffer ? body.slice(0) : body;
|
|
1561
|
+
const upstream = await fetchImpl(upstreamUrl, {
|
|
1562
|
+
method: request.method,
|
|
1563
|
+
headers,
|
|
1564
|
+
...requestBody !== void 0 ? { body: requestBody } : void 0,
|
|
1565
|
+
redirect: "manual"
|
|
1566
|
+
});
|
|
1567
|
+
let pluginPermissionDenied;
|
|
1568
|
+
try {
|
|
1569
|
+
pluginPermissionDenied = (await onPluginEgressResponse({
|
|
1570
|
+
...credentialContext.conversationId ? { conversationId: credentialContext.conversationId } : void 0,
|
|
1571
|
+
provider,
|
|
1572
|
+
grant: lease.grant,
|
|
1573
|
+
method: request.method,
|
|
1574
|
+
...operation ? { operation } : void 0,
|
|
1575
|
+
upstreamUrl,
|
|
1576
|
+
response: {
|
|
1577
|
+
headers: new Headers(upstream.headers),
|
|
1578
|
+
readText: async (maxBytes) => await responseTextWithinLimit(upstream, maxBytes),
|
|
1579
|
+
status: upstream.status
|
|
1580
|
+
}
|
|
1581
|
+
})).permissionDenied;
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
if (!isEgressAuthRequired(error)) throw error;
|
|
1584
|
+
await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
|
|
1585
|
+
logWarn("sandbox.egress.upstream_auth_requirement.classified", { ...attributes(lease, upstream.status) });
|
|
1586
|
+
await upstream.body?.cancel().catch(() => void 0);
|
|
1587
|
+
const authorization = error.authorization ?? lease.authorization;
|
|
1588
|
+
return authRequiredResult({
|
|
1589
|
+
...authorization ? { authorization } : void 0,
|
|
1590
|
+
grant: lease.grant,
|
|
1591
|
+
kind: "auth_required",
|
|
1592
|
+
message: error.message,
|
|
1593
|
+
provider
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
logSandboxEgressUpstreamRequest({
|
|
1597
|
+
credentialContext,
|
|
1598
|
+
egressId: activeEgressId,
|
|
1599
|
+
lease,
|
|
1600
|
+
provider,
|
|
1601
|
+
request,
|
|
1602
|
+
upstream,
|
|
1603
|
+
upstreamUrl
|
|
1604
|
+
});
|
|
1605
|
+
if (upstream.status >= 400) logWarn("sandbox.egress.upstream_response.failed", {
|
|
1606
|
+
...attributes(lease, upstream.status),
|
|
1607
|
+
"error.type": `http_${upstream.status}`
|
|
1608
|
+
});
|
|
1609
|
+
const workloadIdentity = isWorkloadIdentityProvider(provider);
|
|
1610
|
+
if (upstream.status === UPSTREAM_TOKEN_REJECTION_STATUS && workloadIdentity) {
|
|
1611
|
+
const message = `Upstream rejected the ${provider} workload identity credential with HTTP ${upstream.status}.`;
|
|
1612
|
+
logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
|
|
1613
|
+
await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
|
|
1614
|
+
await upstream.body?.cancel().catch(() => void 0);
|
|
1615
|
+
return authRequiredResult({
|
|
1616
|
+
grant: lease.grant,
|
|
1617
|
+
kind: "unavailable",
|
|
1618
|
+
message,
|
|
1619
|
+
provider
|
|
1620
|
+
}, `${message}\n`);
|
|
1621
|
+
}
|
|
1622
|
+
if (upstream.status === UPSTREAM_TOKEN_REJECTION_STATUS) {
|
|
1623
|
+
logWarn("sandbox.egress.upstream_auth.rejected", {
|
|
1624
|
+
...attributes(lease, upstream.status),
|
|
1625
|
+
"app.sandbox.egress.www_authenticate": upstream.headers.get("www-authenticate") ?? void 0
|
|
1626
|
+
});
|
|
1627
|
+
await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
|
|
1628
|
+
await upstream.body?.cancel().catch(() => void 0);
|
|
1629
|
+
const message = `Provider rejected the injected ${provider} credential.`;
|
|
1630
|
+
return authRequiredResult({
|
|
1631
|
+
...lease.authorization ? { authorization: lease.authorization } : void 0,
|
|
1632
|
+
grant: lease.grant,
|
|
1633
|
+
kind: "auth_required",
|
|
1634
|
+
message,
|
|
1635
|
+
provider
|
|
1636
|
+
}, `${message}\n`);
|
|
1637
|
+
}
|
|
1638
|
+
if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS && !retriedAfter403 && !workloadIdentity) {
|
|
1639
|
+
logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
|
|
1640
|
+
await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
|
|
1641
|
+
await upstream.body?.cancel().catch(() => void 0);
|
|
1642
|
+
logWarn("sandbox.egress.upstream_auth.retrying", { ...attributes(lease, upstream.status) });
|
|
1643
|
+
leased = await resolveLease();
|
|
1644
|
+
if ("response" in leased) return leased;
|
|
1645
|
+
lease = leased;
|
|
1646
|
+
retriedAfter403 = true;
|
|
1647
|
+
continue;
|
|
1648
|
+
}
|
|
1649
|
+
if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS) {
|
|
1650
|
+
logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
|
|
1651
|
+
if (!workloadIdentity) await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
|
|
1652
|
+
await recordSandboxPermissionDenied({
|
|
1653
|
+
credentialContext,
|
|
1654
|
+
provider,
|
|
1655
|
+
lease,
|
|
1656
|
+
message: pluginPermissionDenied?.message ?? permissionDeniedMessage(provider, lease.grant),
|
|
1657
|
+
upstream,
|
|
1658
|
+
upstreamUrl
|
|
1659
|
+
});
|
|
1660
|
+
if (pluginPermissionDenied) logWarn("sandbox.egress.upstream_permission.classified", { ...attributes(lease, upstream.status) });
|
|
1661
|
+
return { response: new Response(upstream.body, {
|
|
1662
|
+
status: upstream.status,
|
|
1663
|
+
statusText: upstream.statusText,
|
|
1664
|
+
headers: responseHeaders(upstream)
|
|
1665
|
+
}) };
|
|
1666
|
+
}
|
|
1667
|
+
if (pluginPermissionDenied) {
|
|
1668
|
+
await recordSandboxPermissionDenied({
|
|
1669
|
+
credentialContext,
|
|
1670
|
+
provider,
|
|
1671
|
+
lease,
|
|
1672
|
+
message: pluginPermissionDenied.message,
|
|
1673
|
+
upstream,
|
|
1674
|
+
upstreamUrl
|
|
1675
|
+
});
|
|
1676
|
+
logWarn("sandbox.egress.upstream_permission.classified", { ...attributes(lease, upstream.status) });
|
|
1677
|
+
}
|
|
1678
|
+
return { response: new Response(upstream.body, {
|
|
1679
|
+
status: upstream.status,
|
|
1680
|
+
statusText: upstream.statusText,
|
|
1681
|
+
headers: responseHeaders(upstream)
|
|
1682
|
+
}) };
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
// src/chat/sandbox/http-error-details.ts
|
|
1686
|
+
const DEFAULT_PREVIEW_LIMIT = 512;
|
|
1687
|
+
function toTrimmedString(value, maxChars) {
|
|
1688
|
+
if (typeof value !== "string") return;
|
|
1689
|
+
const normalized = value.trim();
|
|
1690
|
+
if (!normalized) return;
|
|
1691
|
+
return normalized.length > maxChars ? `${normalized.slice(0, maxChars)}…` : normalized;
|
|
1692
|
+
}
|
|
1693
|
+
/** Extract structured HTTP error metadata (status, headers, body preview) for logging. */
|
|
1694
|
+
function extractHttpErrorDetails(error, options = {}) {
|
|
1695
|
+
const prefix = options.attributePrefix ?? "app.http_error";
|
|
1696
|
+
const previewLimit = options.previewLimit ?? DEFAULT_PREVIEW_LIMIT;
|
|
1697
|
+
const normalizedError = error instanceof Error ? error : new Error(String(error));
|
|
1698
|
+
const err = error ?? {};
|
|
1699
|
+
const attributes = {
|
|
1700
|
+
"error.type": normalizedError.name || "Error",
|
|
1701
|
+
"exception.message": toTrimmedString(normalizedError.message, previewLimit) ?? "HTTP error"
|
|
1702
|
+
};
|
|
1703
|
+
const response = err.response;
|
|
1704
|
+
const statusCode = typeof response?.status === "number" ? response.status : void 0;
|
|
1705
|
+
const statusText = toTrimmedString(response?.statusText, previewLimit);
|
|
1706
|
+
const responseUrl = toTrimmedString(response?.url, previewLimit);
|
|
1707
|
+
const responseText = toTrimmedString(err.text, previewLimit);
|
|
1708
|
+
const responseJson = toTrimmedString(err.json && typeof err.json === "object" ? JSON.stringify(err.json) : void 0, previewLimit);
|
|
1709
|
+
const contentType = toTrimmedString(response?.headers?.get?.("content-type"), previewLimit);
|
|
1710
|
+
const requestIdHeader = toTrimmedString(response?.headers?.get?.("x-request-id"), previewLimit);
|
|
1711
|
+
const vercelIdHeader = toTrimmedString(response?.headers?.get?.("x-vercel-id"), previewLimit);
|
|
1712
|
+
const requestId = requestIdHeader ?? vercelIdHeader;
|
|
1713
|
+
if (statusCode !== void 0) attributes["http.response.status_code"] = statusCode;
|
|
1714
|
+
if (statusText) attributes[`${prefix}.status_text`] = statusText;
|
|
1715
|
+
if (responseUrl) attributes["url.full"] = responseUrl;
|
|
1716
|
+
if (contentType) attributes["http.response.header.content-type"] = [contentType];
|
|
1717
|
+
if (requestIdHeader) attributes["http.response.header.x-request-id"] = [requestIdHeader];
|
|
1718
|
+
if (vercelIdHeader) attributes["http.response.header.x-vercel-id"] = [vercelIdHeader];
|
|
1719
|
+
if (responseText) {
|
|
1720
|
+
attributes[`${prefix}.response_text_preview`] = responseText;
|
|
1721
|
+
attributes[`${prefix}.response_text_length`] = responseText.length;
|
|
1722
|
+
}
|
|
1723
|
+
if (responseJson) attributes[`${prefix}.response_json_preview`] = responseJson;
|
|
1724
|
+
const summaryParts = [];
|
|
1725
|
+
if (statusCode !== void 0) summaryParts.push(`status=${statusCode}`);
|
|
1726
|
+
if (statusText) summaryParts.push(`statusText=${statusText}`);
|
|
1727
|
+
if (responseUrl) summaryParts.push(`url=${responseUrl}`);
|
|
1728
|
+
if (requestId) summaryParts.push(`requestId=${requestId}`);
|
|
1729
|
+
for (const field of options.extraFields ?? []) {
|
|
1730
|
+
const value = toTrimmedString(err[field.sourceKey], previewLimit);
|
|
1731
|
+
if (!value) continue;
|
|
1732
|
+
attributes[`${prefix}.${field.attributeKey}`] = value;
|
|
1733
|
+
summaryParts.push(`${field.summaryKey ?? field.attributeKey}=${value}`);
|
|
1734
|
+
}
|
|
1735
|
+
if (responseJson) summaryParts.push(`json=${responseJson}`);
|
|
1736
|
+
else if (responseText) summaryParts.push(`text=${responseText}`);
|
|
1737
|
+
const searchableText = `${normalizedError.message} ${responseText ?? ""} ${responseJson ?? ""}`.toLowerCase();
|
|
1738
|
+
return {
|
|
1739
|
+
attributes,
|
|
1740
|
+
summary: summaryParts.join(", "),
|
|
1741
|
+
searchableText
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
// src/chat/sandbox/snapshot/not-ready-error.ts
|
|
1745
|
+
/** Report that a Workspace snapshot is not ready to use. */
|
|
1746
|
+
var WorkspaceSnapshotNotReadyError = class extends Error {
|
|
1747
|
+
workspaceName;
|
|
1748
|
+
constructor(workspaceName) {
|
|
1749
|
+
super(`Workspace ${workspaceName} snapshot is not ready`);
|
|
1750
|
+
this.name = "WorkspaceSnapshotNotReadyError";
|
|
1751
|
+
this.workspaceName = workspaceName;
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
/** Return WorkspaceSnapshotNotReadyError from this error or its causes. */
|
|
1755
|
+
function getWorkspaceSnapshotNotReadyError(error) {
|
|
1756
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1757
|
+
let current = error;
|
|
1758
|
+
while (current instanceof Error && !seen.has(current)) {
|
|
1759
|
+
if (current instanceof WorkspaceSnapshotNotReadyError) return current;
|
|
1760
|
+
seen.add(current);
|
|
1761
|
+
current = current.cause;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
/** True when this error or a cause is WorkspaceSnapshotNotReadyError. */
|
|
1765
|
+
function isWorkspaceSnapshotNotReadyError(error) {
|
|
1766
|
+
return getWorkspaceSnapshotNotReadyError(error) !== void 0;
|
|
1767
|
+
}
|
|
1768
|
+
/** User message when a Workspace sandbox is still preparing. */
|
|
1769
|
+
function workspaceSnapshotNotReadyUserMessage(error) {
|
|
1770
|
+
return `The ${error.workspaceName} workspace is still preparing its sandbox. Wait for that preparation to finish, then try again.`;
|
|
1771
|
+
}
|
|
1772
|
+
// src/chat/sandbox/errors.ts
|
|
1773
|
+
const SANDBOX_ERROR_FIELDS = [{
|
|
1774
|
+
sourceKey: "sandboxId",
|
|
1775
|
+
attributeKey: "sandbox_id",
|
|
1776
|
+
summaryKey: "sandboxId"
|
|
1777
|
+
}];
|
|
1778
|
+
/** Extract HTTP error details from a sandbox error for span data and checks. */
|
|
1779
|
+
function getSandboxErrorDetails(error) {
|
|
1780
|
+
return extractHttpErrorDetails(error, {
|
|
1781
|
+
attributePrefix: "app.sandbox.api_error",
|
|
1782
|
+
extraFields: [...SANDBOX_ERROR_FIELDS]
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
/** Return true when any error in the `cause` chain matches the predicate. */
|
|
1786
|
+
function findInErrorChain(error, predicate) {
|
|
1787
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1788
|
+
let current = error;
|
|
1789
|
+
while (current && !seen.has(current)) {
|
|
1790
|
+
if (predicate(current)) return true;
|
|
1791
|
+
seen.add(current);
|
|
1792
|
+
current = typeof current === "object" ? current.cause : void 0;
|
|
1793
|
+
}
|
|
1794
|
+
return false;
|
|
1795
|
+
}
|
|
1796
|
+
function getFirstErrorMessage(error) {
|
|
1797
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1798
|
+
let current = error;
|
|
1799
|
+
while (current && !seen.has(current)) {
|
|
1800
|
+
if (current instanceof Error) {
|
|
1801
|
+
const message = current.message.trim();
|
|
1802
|
+
if (message) return message;
|
|
1803
|
+
}
|
|
1804
|
+
seen.add(current);
|
|
1805
|
+
current = typeof current === "object" ? current.cause : void 0;
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
/** Detect sandbox filesystem operations that can safely ignore existing directories. */
|
|
1809
|
+
function isAlreadyExistsError(error) {
|
|
1810
|
+
const details = getSandboxErrorDetails(error);
|
|
1811
|
+
return details.searchableText.includes("already exists") || details.searchableText.includes("file exists") || details.searchableText.includes("eexist");
|
|
1812
|
+
}
|
|
1813
|
+
/** Detect cancellation so a durable builder stays available for check-in. */
|
|
1814
|
+
function isAbortError(error) {
|
|
1815
|
+
return findInErrorChain(error, (candidate) => {
|
|
1816
|
+
if (typeof DOMException !== "undefined" && candidate instanceof DOMException) return candidate.name === "AbortError";
|
|
1817
|
+
return candidate instanceof Error && candidate.name === "AbortError";
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
/** A sandbox call that Junior owns did not finish within its time limit. */
|
|
1821
|
+
var SandboxCallTimeoutError = class extends Error {
|
|
1822
|
+
constructor(operation, timeoutMs, options) {
|
|
1823
|
+
super(`${operation} did not finish within ${timeoutMs}ms`, options);
|
|
1824
|
+
this.name = "SandboxCallTimeoutError";
|
|
1825
|
+
}
|
|
1826
|
+
};
|
|
1827
|
+
/** Wrap setup failures. Keep WorkspaceSnapshotNotReadyError as-is. */
|
|
1828
|
+
function wrapSandboxSetupError(error) {
|
|
1829
|
+
const notReady = getWorkspaceSnapshotNotReadyError(error);
|
|
1830
|
+
if (notReady) return notReady;
|
|
1831
|
+
try {
|
|
1832
|
+
const details = getSandboxErrorDetails(error);
|
|
1833
|
+
if (details.summary) return new Error(`sandbox setup failed (${details.summary})`, { cause: error });
|
|
1834
|
+
} catch {}
|
|
1835
|
+
let causeMessage;
|
|
1836
|
+
try {
|
|
1837
|
+
causeMessage = getFirstErrorMessage(error);
|
|
1838
|
+
} catch (cause) {
|
|
1839
|
+
causeMessage = cause instanceof Error ? cause.message : void 0;
|
|
1840
|
+
}
|
|
1841
|
+
if (causeMessage && causeMessage.trim() && causeMessage !== "sandbox setup failed") {
|
|
1842
|
+
const oneLine = causeMessage.replace(/\s+/g, " ").trim();
|
|
1843
|
+
return new Error(`sandbox setup failed (${oneLine})`, { cause: error });
|
|
1844
|
+
}
|
|
1845
|
+
return new Error("sandbox setup failed", { cause: error });
|
|
1846
|
+
}
|
|
1847
|
+
/** Record span data and throw one stable sandbox operation error. */
|
|
1848
|
+
function throwSandboxOperationError(action, error, includeMissingPath = false) {
|
|
1849
|
+
const details = getSandboxErrorDetails(error);
|
|
1850
|
+
setSpanAttributes({
|
|
1851
|
+
...details.attributes,
|
|
1852
|
+
...includeMissingPath ? { "app.sandbox.api_error.missing_path": details.searchableText.includes("no such file") || details.searchableText.includes("enoent") } : void 0,
|
|
1853
|
+
"app.sandbox.success": false
|
|
1854
|
+
});
|
|
1855
|
+
throw new Error(details.summary ? `${action} failed (${details.summary})` : `${action} failed`, { cause: error });
|
|
1856
|
+
}
|
|
1857
|
+
// src/chat/sandbox/docker/api.ts
|
|
1858
|
+
const API_VERSION = "v1.43";
|
|
1859
|
+
const DEFAULT_SOCKET_PATH = "/var/run/docker.sock";
|
|
1860
|
+
/** Error response from the Docker Engine API. */
|
|
1861
|
+
var DockerApiError = class extends Error {
|
|
1862
|
+
statusCode;
|
|
1863
|
+
constructor(statusCode, message) {
|
|
1864
|
+
super(`Docker API error status=${statusCode}: ${message}`);
|
|
1865
|
+
this.name = "DockerApiError";
|
|
1866
|
+
this.statusCode = statusCode;
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
/** Return the unix socket path of the Docker daemon from `DOCKER_HOST`. */
|
|
1870
|
+
function dockerSocketPath() {
|
|
1871
|
+
const { host } = getChatConfig().sandbox.docker;
|
|
1872
|
+
if (!host) return DEFAULT_SOCKET_PATH;
|
|
1873
|
+
if (!host.startsWith("unix://")) throw new Error(`The Docker sandbox provider supports only unix sockets. DOCKER_HOST is ${host}`);
|
|
1874
|
+
return host.slice(7);
|
|
1875
|
+
}
|
|
1876
|
+
function requestPath(input) {
|
|
1877
|
+
const params = new URLSearchParams();
|
|
1878
|
+
for (const [key, value] of Object.entries(input.query ?? {})) if (value !== void 0) params.set(key, String(value));
|
|
1879
|
+
const query = params.toString();
|
|
1880
|
+
return `/${API_VERSION}${input.path}${query ? `?${query}` : ""}`;
|
|
1881
|
+
}
|
|
1882
|
+
/** Send one request and return the response stream with its status. */
|
|
1883
|
+
function dockerStream(input) {
|
|
1884
|
+
input.signal?.throwIfAborted();
|
|
1885
|
+
const raw = input.body instanceof Uint8Array ? Buffer.from(input.body) : void 0;
|
|
1886
|
+
const json = input.body !== void 0 && !raw ? JSON.stringify(input.body) : void 0;
|
|
1887
|
+
return new Promise((resolve, reject) => {
|
|
1888
|
+
const request = http.request({
|
|
1889
|
+
socketPath: dockerSocketPath(),
|
|
1890
|
+
agent: false,
|
|
1891
|
+
path: requestPath(input),
|
|
1892
|
+
method: input.method ?? "GET",
|
|
1893
|
+
headers: {
|
|
1894
|
+
...json ? { "content-type": "application/json" } : void 0,
|
|
1895
|
+
...raw ? { "content-type": "application/x-tar" } : void 0
|
|
1896
|
+
},
|
|
1897
|
+
signal: input.signal
|
|
1898
|
+
});
|
|
1899
|
+
request.on("response", resolve);
|
|
1900
|
+
request.on("error", reject);
|
|
1901
|
+
request.end(raw ?? json);
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
/** Read a whole response stream into one buffer. */
|
|
1905
|
+
async function readStream(stream) {
|
|
1906
|
+
const chunks = [];
|
|
1907
|
+
for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1908
|
+
return Buffer.concat(chunks);
|
|
1909
|
+
}
|
|
1910
|
+
async function errorFrom(response) {
|
|
1911
|
+
const body = (await readStream(response)).toString("utf8");
|
|
1912
|
+
let message = body.trim() || response.statusMessage || "request failed";
|
|
1913
|
+
try {
|
|
1914
|
+
const parsed = JSON.parse(body);
|
|
1915
|
+
if (typeof parsed.message === "string") message = parsed.message;
|
|
1916
|
+
} catch {}
|
|
1917
|
+
throw new DockerApiError(response.statusCode ?? 0, message);
|
|
1918
|
+
}
|
|
1919
|
+
/** Send one request and return its body. Error statuses throw `DockerApiError`. */
|
|
1920
|
+
async function dockerRequest(input) {
|
|
1921
|
+
const response = await dockerStream(input);
|
|
1922
|
+
if ((response.statusCode ?? 0) >= 400) return await errorFrom(response);
|
|
1923
|
+
return await readStream(response);
|
|
1924
|
+
}
|
|
1925
|
+
/** Send one request and parse its JSON body. */
|
|
1926
|
+
async function dockerJson(input) {
|
|
1927
|
+
const body = await dockerRequest(input);
|
|
1928
|
+
return body.length > 0 ? JSON.parse(body.toString("utf8")) : {};
|
|
1929
|
+
}
|
|
1930
|
+
/** Send one request and return the response stream. Error statuses throw. */
|
|
1931
|
+
async function dockerOkStream(input) {
|
|
1932
|
+
const response = await dockerStream(input);
|
|
1933
|
+
if ((response.statusCode ?? 0) >= 400) return await errorFrom(response);
|
|
1934
|
+
return response;
|
|
1935
|
+
}
|
|
1936
|
+
// src/chat/sandbox/docker/exec.ts
|
|
1937
|
+
/** Directory for command state in each sandbox. The runtime image creates it. */
|
|
1938
|
+
const COMMAND_STATE_DIR = "/var/tmp/junior-commands";
|
|
1939
|
+
/** User for commands without `sudo`. It matches Vercel Sandbox. */
|
|
1940
|
+
const SANDBOX_USER = "vercel-sandbox";
|
|
1941
|
+
const KILL_GRACE_MS = 2e3;
|
|
1942
|
+
const EXIT_POLL_MS = 250;
|
|
1943
|
+
function timeoutArgs(timeoutMs) {
|
|
1944
|
+
if (!timeoutMs || timeoutMs <= 0) return [];
|
|
1945
|
+
return [
|
|
1946
|
+
"timeout",
|
|
1947
|
+
"-k",
|
|
1948
|
+
"5",
|
|
1949
|
+
`${Math.ceil(timeoutMs / 1e3)}s`
|
|
1950
|
+
];
|
|
1951
|
+
}
|
|
1952
|
+
function envList(env) {
|
|
1953
|
+
return Object.entries(env ?? {}).map(([key, value]) => `${key}=${value}`);
|
|
1954
|
+
}
|
|
1955
|
+
async function createExec(containerId, input, signal) {
|
|
1956
|
+
return (await dockerJson({
|
|
1957
|
+
method: "POST",
|
|
1958
|
+
path: `/containers/${encodeURIComponent(containerId)}/exec`,
|
|
1959
|
+
body: {
|
|
1960
|
+
AttachStdout: input.attach,
|
|
1961
|
+
AttachStderr: input.attach,
|
|
1962
|
+
Cmd: input.cmd,
|
|
1963
|
+
Env: envList(input.env),
|
|
1964
|
+
User: input.root ? "root" : SANDBOX_USER,
|
|
1965
|
+
...input.cwd ? { WorkingDir: input.cwd } : void 0
|
|
1966
|
+
},
|
|
1967
|
+
signal
|
|
1968
|
+
})).Id;
|
|
1969
|
+
}
|
|
1970
|
+
/** Split Docker's multiplexed exec stream into stdout and stderr. */
|
|
1971
|
+
async function demux(stream) {
|
|
1972
|
+
const stdout = [];
|
|
1973
|
+
const stderr = [];
|
|
1974
|
+
let pending = Buffer.alloc(0);
|
|
1975
|
+
for await (const chunk of stream) {
|
|
1976
|
+
pending = Buffer.concat([pending, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
1977
|
+
while (pending.length >= 8) {
|
|
1978
|
+
const size = pending.readUInt32BE(4);
|
|
1979
|
+
if (pending.length < 8 + size) break;
|
|
1980
|
+
const frame = pending.subarray(8, 8 + size);
|
|
1981
|
+
if (pending[0] === 2) stderr.push(frame);
|
|
1982
|
+
else stdout.push(frame);
|
|
1983
|
+
pending = pending.subarray(8 + size);
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
return {
|
|
1987
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
1988
|
+
stderr: Buffer.concat(stderr).toString("utf8")
|
|
1989
|
+
};
|
|
1990
|
+
}
|
|
1991
|
+
async function waitForExit(execId) {
|
|
1992
|
+
for (;;) {
|
|
1993
|
+
const inspect = await dockerJson({ path: `/exec/${execId}/json` });
|
|
1994
|
+
if (!inspect.Running) return inspect.ExitCode ?? -1;
|
|
1995
|
+
await sleep(EXIT_POLL_MS);
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
async function killGroup(containerId, id, signalName) {
|
|
1999
|
+
const pidFile = `${COMMAND_STATE_DIR}/${id}.pid`;
|
|
2000
|
+
await runRawExec(containerId, {
|
|
2001
|
+
cmd: [
|
|
2002
|
+
"sh",
|
|
2003
|
+
"-c",
|
|
2004
|
+
`[ -f ${pidFile} ] && kill -${signalName} -- -"$(cat ${pidFile})" 2>/dev/null; true`
|
|
2005
|
+
],
|
|
2006
|
+
root: true
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
2009
|
+
/** Run one exec without the process-group wrapper. Used for internal steps. */
|
|
2010
|
+
async function runRawExec(containerId, input, signal) {
|
|
2011
|
+
const execId = await createExec(containerId, {
|
|
2012
|
+
...input,
|
|
2013
|
+
attach: true
|
|
2014
|
+
}, signal);
|
|
2015
|
+
const output = await demux(await dockerOkStream({
|
|
2016
|
+
method: "POST",
|
|
2017
|
+
path: `/exec/${execId}/start`,
|
|
2018
|
+
body: {
|
|
2019
|
+
Detach: false,
|
|
2020
|
+
Tty: false
|
|
2021
|
+
},
|
|
2022
|
+
signal
|
|
2023
|
+
}));
|
|
2024
|
+
return {
|
|
2025
|
+
exitCode: await waitForExit(execId),
|
|
2026
|
+
...output
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
/** Run one command in a sandbox container. Abort kills its process group. */
|
|
2030
|
+
async function runSandboxCommand(containerId, input) {
|
|
2031
|
+
input.signal?.throwIfAborted();
|
|
2032
|
+
const id = randomUUID();
|
|
2033
|
+
const pidFile = `${COMMAND_STATE_DIR}/${id}.pid`;
|
|
2034
|
+
const execId = await createExec(containerId, {
|
|
2035
|
+
cmd: [
|
|
2036
|
+
"setsid",
|
|
2037
|
+
"-w",
|
|
2038
|
+
"sh",
|
|
2039
|
+
"-c",
|
|
2040
|
+
`echo $$ > ${pidFile}; exec "$@"`,
|
|
2041
|
+
"sh",
|
|
2042
|
+
...timeoutArgs(input.timeoutMs),
|
|
2043
|
+
input.cmd,
|
|
2044
|
+
...input.args ?? []
|
|
2045
|
+
],
|
|
2046
|
+
cwd: input.cwd,
|
|
2047
|
+
env: input.env,
|
|
2048
|
+
root: input.sudo,
|
|
2049
|
+
attach: true
|
|
2050
|
+
});
|
|
2051
|
+
const stream = await dockerOkStream({
|
|
2052
|
+
method: "POST",
|
|
2053
|
+
path: `/exec/${execId}/start`,
|
|
2054
|
+
body: {
|
|
2055
|
+
Detach: false,
|
|
2056
|
+
Tty: false
|
|
2057
|
+
}
|
|
2058
|
+
});
|
|
2059
|
+
const signal = input.signal;
|
|
2060
|
+
const onAbort = () => {
|
|
2061
|
+
(async () => {
|
|
2062
|
+
await killGroup(containerId, id, "TERM");
|
|
2063
|
+
await sleep(KILL_GRACE_MS);
|
|
2064
|
+
await killGroup(containerId, id, "KILL");
|
|
2065
|
+
})().catch(() => {});
|
|
2066
|
+
};
|
|
2067
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2068
|
+
try {
|
|
2069
|
+
const output = await demux(stream);
|
|
2070
|
+
signal?.throwIfAborted();
|
|
2071
|
+
return {
|
|
2072
|
+
exitCode: await waitForExit(execId),
|
|
2073
|
+
...output
|
|
2074
|
+
};
|
|
2075
|
+
} finally {
|
|
2076
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2077
|
+
runRawExec(containerId, {
|
|
2078
|
+
cmd: [
|
|
2079
|
+
"rm",
|
|
2080
|
+
"-f",
|
|
2081
|
+
pidFile
|
|
2082
|
+
],
|
|
2083
|
+
root: true
|
|
2084
|
+
}).catch(() => {});
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
/** Start a command that keeps running after this request. Return its id. */
|
|
2088
|
+
async function startDetachedCommand(containerId, input) {
|
|
2089
|
+
const id = randomUUID();
|
|
2090
|
+
const dir = `${COMMAND_STATE_DIR}/${id}`;
|
|
2091
|
+
await dockerJson({
|
|
2092
|
+
method: "POST",
|
|
2093
|
+
path: `/exec/${await createExec(containerId, {
|
|
2094
|
+
cmd: [
|
|
2095
|
+
"sh",
|
|
2096
|
+
"-c",
|
|
2097
|
+
[
|
|
2098
|
+
`mkdir -p ${dir}`,
|
|
2099
|
+
`"$@" >${dir}/stdout 2>${dir}/stderr`,
|
|
2100
|
+
`echo $? >${dir}/exit.tmp`,
|
|
2101
|
+
`mv ${dir}/exit.tmp ${dir}/exit`
|
|
2102
|
+
].join("; "),
|
|
2103
|
+
"sh",
|
|
2104
|
+
...timeoutArgs(input.timeoutMs),
|
|
2105
|
+
input.cmd,
|
|
2106
|
+
...input.args ?? []
|
|
2107
|
+
],
|
|
2108
|
+
cwd: input.cwd,
|
|
2109
|
+
env: input.env,
|
|
2110
|
+
root: input.sudo,
|
|
2111
|
+
attach: false
|
|
2112
|
+
}, input.signal)}/start`,
|
|
2113
|
+
body: {
|
|
2114
|
+
Detach: true,
|
|
2115
|
+
Tty: false
|
|
2116
|
+
},
|
|
2117
|
+
signal: input.signal
|
|
2118
|
+
});
|
|
2119
|
+
return id;
|
|
2120
|
+
}
|
|
2121
|
+
async function readCommandFile(containerId, id, name, signal) {
|
|
2122
|
+
const result = await runRawExec(containerId, {
|
|
2123
|
+
cmd: ["cat", `${COMMAND_STATE_DIR}/${id}/${name}`],
|
|
2124
|
+
root: true
|
|
2125
|
+
}, signal);
|
|
2126
|
+
return result.exitCode === 0 ? result.stdout : null;
|
|
2127
|
+
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Wait until a detached command writes its exit code.
|
|
2130
|
+
*
|
|
2131
|
+
* The state lives in files in the container, so any process can wait for a
|
|
2132
|
+
* command that another process started.
|
|
2133
|
+
*/
|
|
2134
|
+
async function waitForDetachedCommand(containerId, id, signal) {
|
|
2135
|
+
for (;;) {
|
|
2136
|
+
signal.throwIfAborted();
|
|
2137
|
+
const exit = await readCommandFile(containerId, id, "exit", signal);
|
|
2138
|
+
if (exit !== null) return {
|
|
2139
|
+
exitCode: Number.parseInt(exit.trim(), 10),
|
|
2140
|
+
stdout: async () => await readCommandFile(containerId, id, "stdout") ?? "",
|
|
2141
|
+
stderr: async () => await readCommandFile(containerId, id, "stderr") ?? ""
|
|
2142
|
+
};
|
|
2143
|
+
await sleep(EXIT_POLL_MS, signal);
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
// src/chat/sandbox/docker/settings.ts
|
|
2147
|
+
/** Label on every container, network, and image that this provider owns. */
|
|
2148
|
+
const DOCKER_SANDBOX_LABEL = "dev.junior.sandbox";
|
|
2149
|
+
/**
|
|
2150
|
+
* Directory for machine-wide provider files, such as the egress CA key.
|
|
2151
|
+
* `JUNIOR_DOCKER_SANDBOX_DIR` overrides the default.
|
|
2152
|
+
*/
|
|
2153
|
+
function dockerSandboxDir() {
|
|
2154
|
+
const configured = getChatConfig().sandbox.docker.dir;
|
|
2155
|
+
if (configured) return configured;
|
|
2156
|
+
return path.join(os.homedir(), ".cache", "junior", "docker-sandbox");
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* Optional PEM file with more CA certificates for each sandbox to trust.
|
|
2160
|
+
*
|
|
2161
|
+
* Use this when the Docker host itself sits behind a TLS proxy, such as the
|
|
2162
|
+
* network proxy of a Vercel Sandbox. Without it, sandbox containers cannot
|
|
2163
|
+
* verify the certificates that this proxy shows.
|
|
2164
|
+
*/
|
|
2165
|
+
function dockerSandboxExtraCaFile() {
|
|
2166
|
+
return getChatConfig().sandbox.docker.extraCaCertsFile;
|
|
2167
|
+
}
|
|
2168
|
+
// src/chat/sandbox/docker/tar.ts
|
|
2169
|
+
const BLOCK = 512;
|
|
2170
|
+
function writeString(header, value, offset, length) {
|
|
2171
|
+
header.write(value, offset, Math.min(Buffer.byteLength(value), length));
|
|
2172
|
+
}
|
|
2173
|
+
function writeOctal(header, value, offset, length) {
|
|
2174
|
+
writeString(header, `${value.toString(8).padStart(length - 1, "0")}\0`, offset, length);
|
|
2175
|
+
}
|
|
2176
|
+
function header(input) {
|
|
2177
|
+
const block = Buffer.alloc(BLOCK);
|
|
2178
|
+
writeString(block, input.name, 0, 100);
|
|
2179
|
+
writeOctal(block, input.mode & 4095, 100, 8);
|
|
2180
|
+
writeOctal(block, input.uid, 108, 8);
|
|
2181
|
+
writeOctal(block, input.gid, 116, 8);
|
|
2182
|
+
writeOctal(block, input.size, 124, 12);
|
|
2183
|
+
writeOctal(block, Math.floor(Date.now() / 1e3), 136, 12);
|
|
2184
|
+
block.fill(" ", 148, 156);
|
|
2185
|
+
writeString(block, input.type, 156, 1);
|
|
2186
|
+
writeString(block, "ustar\0", 257, 6);
|
|
2187
|
+
writeString(block, "00", 263, 2);
|
|
2188
|
+
let checksum = 0;
|
|
2189
|
+
for (const byte of block) checksum += byte;
|
|
2190
|
+
writeString(block, `${checksum.toString(8).padStart(6, "0")}\0 `, 148, 8);
|
|
2191
|
+
return block;
|
|
2192
|
+
}
|
|
2193
|
+
function padding(size) {
|
|
2194
|
+
const remainder = size % BLOCK;
|
|
2195
|
+
return Buffer.alloc(remainder === 0 ? 0 : BLOCK - remainder);
|
|
2196
|
+
}
|
|
2197
|
+
/** A PAX record such as `30 path=some/long/name\n`. */
|
|
2198
|
+
function paxRecord(key, value) {
|
|
2199
|
+
const body = ` ${key}=${value}\n`;
|
|
2200
|
+
let length = Buffer.byteLength(body);
|
|
2201
|
+
length += String(length).length;
|
|
2202
|
+
if (String(length).length !== String(length - 1).length) length += 1;
|
|
2203
|
+
return Buffer.from(`${length}${body}`);
|
|
2204
|
+
}
|
|
2205
|
+
/** Write regular files into one uncompressed tar archive. */
|
|
2206
|
+
function packTar(files) {
|
|
2207
|
+
const parts = [];
|
|
2208
|
+
for (const file of files) {
|
|
2209
|
+
const content = Buffer.from(file.content);
|
|
2210
|
+
let name = file.path;
|
|
2211
|
+
if (Buffer.byteLength(name) > 99) {
|
|
2212
|
+
const pax = paxRecord("path", name);
|
|
2213
|
+
parts.push(header({
|
|
2214
|
+
...file,
|
|
2215
|
+
name: "PaxHeader",
|
|
2216
|
+
size: pax.length,
|
|
2217
|
+
type: "x"
|
|
2218
|
+
}), pax, padding(pax.length));
|
|
2219
|
+
name = name.slice(-99);
|
|
2220
|
+
}
|
|
2221
|
+
parts.push(header({
|
|
2222
|
+
...file,
|
|
2223
|
+
name,
|
|
2224
|
+
size: content.length,
|
|
2225
|
+
type: "0"
|
|
2226
|
+
}), content, padding(content.length));
|
|
2227
|
+
}
|
|
2228
|
+
parts.push(Buffer.alloc(BLOCK * 2));
|
|
2229
|
+
return Buffer.concat(parts);
|
|
2230
|
+
}
|
|
2231
|
+
function readOctal(block, offset, length) {
|
|
2232
|
+
const text = block.subarray(offset, offset + length).toString("ascii").replace(/\0.*$/s, "").trim();
|
|
2233
|
+
return text ? Number.parseInt(text, 8) : 0;
|
|
2234
|
+
}
|
|
2235
|
+
/** Return the content of the first regular file in a tar archive. */
|
|
2236
|
+
function unpackFirstFile(archive) {
|
|
2237
|
+
let offset = 0;
|
|
2238
|
+
while (offset + BLOCK <= archive.length) {
|
|
2239
|
+
const block = archive.subarray(offset, offset + BLOCK);
|
|
2240
|
+
if (block.every((byte) => byte === 0)) return null;
|
|
2241
|
+
const size = readOctal(block, 124, 12);
|
|
2242
|
+
const type = String.fromCharCode(block[156] ?? 0);
|
|
2243
|
+
const start = offset + BLOCK;
|
|
2244
|
+
if (type === "0" || type === "\0") return archive.subarray(start, start + size);
|
|
2245
|
+
offset = start + size + padding(size).length;
|
|
2246
|
+
}
|
|
2247
|
+
return null;
|
|
2248
|
+
}
|
|
2249
|
+
// src/chat/sandbox/docker/container.ts
|
|
2250
|
+
const SUBNET_PREFIX = "10.213";
|
|
2251
|
+
const CA_ANCHOR = "/etc/pki/ca-trust/source/anchors/junior-docker-sandbox.pem";
|
|
2252
|
+
/** Amazon Linux's combined CA bundle, rebuilt by `update-ca-trust`. */
|
|
2253
|
+
const SYSTEM_CA_BUNDLE = "/etc/pki/tls/certs/ca-bundle.crt";
|
|
2254
|
+
/** Runtimes that ignore the system trust store but read these env vars. */
|
|
2255
|
+
const CA_BUNDLE_ENV = [
|
|
2256
|
+
"NODE_EXTRA_CA_CERTS",
|
|
2257
|
+
"REQUESTS_CA_BUNDLE",
|
|
2258
|
+
"SSL_CERT_FILE",
|
|
2259
|
+
"CURL_CA_BUNDLE",
|
|
2260
|
+
"AWS_CA_BUNDLE"
|
|
2261
|
+
];
|
|
2262
|
+
const READY_TIMEOUT_MS = 3e4;
|
|
2263
|
+
const READY_POLL_MS = 100;
|
|
2264
|
+
/**
|
|
2265
|
+
* PID 1 script of every sandbox container. `docker-init` runs it.
|
|
2266
|
+
*
|
|
2267
|
+
* It clears state that a snapshot or restart leaves behind, then stops the
|
|
2268
|
+
* container when its deadline passes. `extendTimeout` moves the deadline.
|
|
2269
|
+
* The ready file holds the start time of PID 1, so a check never sees the
|
|
2270
|
+
* ready file of an earlier start.
|
|
2271
|
+
*/
|
|
2272
|
+
const INIT_SCRIPT = `set -u
|
|
2273
|
+
rm -f /var/run/docker.pid /run/junior/ready
|
|
2274
|
+
mkdir -p /run/junior
|
|
2275
|
+
echo $(( $(date +%s) + JUNIOR_SANDBOX_TIMEOUT_SECONDS )) > /run/junior/deadline
|
|
2276
|
+
cut -d' ' -f22 /proc/1/stat > /run/junior/ready
|
|
2277
|
+
trap 'exit 0' TERM INT
|
|
2278
|
+
while :; do
|
|
2279
|
+
deadline=$(cat /run/junior/deadline 2>/dev/null || echo 0)
|
|
2280
|
+
[ "$(date +%s)" -ge "$deadline" ] && exit 0
|
|
2281
|
+
sleep 2 & wait $!
|
|
2282
|
+
done
|
|
2283
|
+
`;
|
|
2284
|
+
function isStatus(error, status) {
|
|
2285
|
+
return error instanceof DockerApiError && error.statusCode === status;
|
|
2286
|
+
}
|
|
2287
|
+
/** Return the name of a sandbox's egress relay container. See `relay.ts`. */
|
|
2288
|
+
function egressRelayName(name) {
|
|
2289
|
+
return `${name}-egress`;
|
|
2290
|
+
}
|
|
2291
|
+
/** Return a sandbox name for a sandbox that the caller did not name. */
|
|
2292
|
+
function newSandboxName() {
|
|
2293
|
+
return `junior-${randomUUID()}`;
|
|
2294
|
+
}
|
|
2295
|
+
async function listSandboxResources(kind) {
|
|
2296
|
+
return await dockerJson({
|
|
2297
|
+
path: kind === "containers" ? "/containers/json" : "/networks",
|
|
2298
|
+
query: {
|
|
2299
|
+
...kind === "containers" ? { all: true } : void 0,
|
|
2300
|
+
filters: JSON.stringify({ label: [DOCKER_SANDBOX_LABEL] })
|
|
2301
|
+
}
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
/** Remove sandbox networks whose container no longer exists. */
|
|
2305
|
+
async function pruneNetworks() {
|
|
2306
|
+
const containers = await listSandboxResources("containers");
|
|
2307
|
+
const used = new Set(containers.map((container) => container.Labels[DOCKER_SANDBOX_LABEL]));
|
|
2308
|
+
const networks = await listSandboxResources("networks");
|
|
2309
|
+
await mapBounded(networks.filter((network) => !used.has(network.Labels[DOCKER_SANDBOX_LABEL])), async (network) => {
|
|
2310
|
+
await forceRemove(egressRelayName(network.Name));
|
|
2311
|
+
await removeNetwork(network.Name);
|
|
2312
|
+
});
|
|
2313
|
+
}
|
|
2314
|
+
async function createNetwork(name, signal) {
|
|
2315
|
+
await pruneNetworks();
|
|
2316
|
+
const networks = await listSandboxResources("networks");
|
|
2317
|
+
const taken = new Set(networks.flatMap((network) => (network.IPAM.Config ?? []).map((config) => config.Subnet)));
|
|
2318
|
+
for (let index = 0; index < 256; index += 1) {
|
|
2319
|
+
const subnet = `${SUBNET_PREFIX}.${index}.0/24`;
|
|
2320
|
+
if (taken.has(subnet)) continue;
|
|
2321
|
+
try {
|
|
2322
|
+
await dockerJson({
|
|
2323
|
+
method: "POST",
|
|
2324
|
+
path: "/networks/create",
|
|
2325
|
+
body: {
|
|
2326
|
+
Name: name,
|
|
2327
|
+
Driver: "bridge",
|
|
2328
|
+
CheckDuplicate: true,
|
|
2329
|
+
IPAM: { Config: [{ Subnet: subnet }] },
|
|
2330
|
+
Labels: { [DOCKER_SANDBOX_LABEL]: name }
|
|
2331
|
+
},
|
|
2332
|
+
signal
|
|
2333
|
+
});
|
|
2334
|
+
return;
|
|
2335
|
+
} catch (error) {
|
|
2336
|
+
if (error instanceof DockerApiError && /overlap/i.test(error.message)) continue;
|
|
2337
|
+
throw error;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
throw new Error(`No free ${SUBNET_PREFIX}.x.0/24 subnet for sandbox ${name}`);
|
|
2341
|
+
}
|
|
2342
|
+
async function removeNetwork(name) {
|
|
2343
|
+
try {
|
|
2344
|
+
await dockerRequest({
|
|
2345
|
+
method: "DELETE",
|
|
2346
|
+
path: `/networks/${encodeURIComponent(name)}`
|
|
2347
|
+
});
|
|
2348
|
+
} catch (error) {
|
|
2349
|
+
if (!isStatus(error, 404)) throw error;
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
async function inspect(name, signal) {
|
|
2353
|
+
return await dockerJson({
|
|
2354
|
+
path: `/containers/${encodeURIComponent(name)}/json`,
|
|
2355
|
+
signal
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
function toContainer(details) {
|
|
2359
|
+
const name = details.Name.replace(/^\//, "");
|
|
2360
|
+
const network = details.NetworkSettings.Networks[name];
|
|
2361
|
+
if (!network?.IPAddress) throw new Error(`Sandbox container ${name} has no address on its network`);
|
|
2362
|
+
return {
|
|
2363
|
+
id: details.Id,
|
|
2364
|
+
name,
|
|
2365
|
+
ip: network.IPAddress,
|
|
2366
|
+
gateway: network.Gateway,
|
|
2367
|
+
startedAtMs: Date.parse(details.State.StartedAt)
|
|
2368
|
+
};
|
|
2369
|
+
}
|
|
2370
|
+
async function waitUntilReady(id, signal) {
|
|
2371
|
+
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
2372
|
+
while (Date.now() < deadline) {
|
|
2373
|
+
if ((await runRawExec(id, {
|
|
2374
|
+
cmd: [
|
|
2375
|
+
"sh",
|
|
2376
|
+
"-c",
|
|
2377
|
+
`[ "$(cat /run/junior/ready 2>/dev/null)" = "$(cut -d' ' -f22 /proc/1/stat)" ]`
|
|
2378
|
+
],
|
|
2379
|
+
root: true
|
|
2380
|
+
}, signal)).exitCode === 0) return;
|
|
2381
|
+
await sleep(READY_POLL_MS, signal);
|
|
2382
|
+
}
|
|
2383
|
+
throw new Error(`Sandbox container ${id} did not become ready`);
|
|
2384
|
+
}
|
|
2385
|
+
async function caCertificates(egressCaPem) {
|
|
2386
|
+
const extraFile = dockerSandboxExtraCaFile();
|
|
2387
|
+
const extra = extraFile ? await fs.readFile(extraFile, "utf8") : "";
|
|
2388
|
+
return `${egressCaPem.trim()}\n${extra.trim()}\n`;
|
|
2389
|
+
}
|
|
2390
|
+
/** Put the egress CA into the sandbox's system trust store. */
|
|
2391
|
+
async function trustEgressCa(id, egressCaPem) {
|
|
2392
|
+
await dockerRequest({
|
|
2393
|
+
method: "PUT",
|
|
2394
|
+
path: `/containers/${id}/archive`,
|
|
2395
|
+
query: { path: "/" },
|
|
2396
|
+
body: packTar([{
|
|
2397
|
+
path: `${CA_ANCHOR.slice(1)}.new`,
|
|
2398
|
+
content: Buffer.from(await caCertificates(egressCaPem)),
|
|
2399
|
+
mode: 420,
|
|
2400
|
+
uid: 0,
|
|
2401
|
+
gid: 0
|
|
2402
|
+
}])
|
|
2403
|
+
});
|
|
2404
|
+
const result = await runRawExec(id, {
|
|
2405
|
+
cmd: [
|
|
2406
|
+
"sh",
|
|
2407
|
+
"-c",
|
|
2408
|
+
[
|
|
2409
|
+
"set -eu",
|
|
2410
|
+
`if cmp -s ${CA_ANCHOR}.new ${CA_ANCHOR}; then rm ${CA_ANCHOR}.new; exit 0; fi`,
|
|
2411
|
+
`mv ${CA_ANCHOR}.new ${CA_ANCHOR}`,
|
|
2412
|
+
"update-ca-trust extract"
|
|
2413
|
+
].join("\n")
|
|
2414
|
+
],
|
|
2415
|
+
root: true
|
|
2416
|
+
});
|
|
2417
|
+
if (result.exitCode !== 0) throw new Error(`Could not trust the egress CA: ${result.stderr}`);
|
|
2418
|
+
}
|
|
2419
|
+
async function start(name, signal) {
|
|
2420
|
+
try {
|
|
2421
|
+
await dockerRequest({
|
|
2422
|
+
method: "POST",
|
|
2423
|
+
path: `/containers/${encodeURIComponent(name)}/start`,
|
|
2424
|
+
signal
|
|
2425
|
+
});
|
|
2426
|
+
} catch (error) {
|
|
2427
|
+
if (!isStatus(error, 304)) throw error;
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* Create and start one sandbox container, then wait until it is ready.
|
|
2432
|
+
*
|
|
2433
|
+
* A container that is not persistent removes itself when it stops, like a
|
|
2434
|
+
* Vercel Sandbox that is not persistent.
|
|
2435
|
+
*/
|
|
2436
|
+
async function createContainer(input, egressCaPem) {
|
|
2437
|
+
await createNetwork(input.name, input.signal);
|
|
2438
|
+
try {
|
|
2439
|
+
await dockerJson({
|
|
2440
|
+
method: "POST",
|
|
2441
|
+
path: "/containers/create",
|
|
2442
|
+
query: { name: input.name },
|
|
2443
|
+
body: {
|
|
2444
|
+
Image: input.image,
|
|
2445
|
+
Cmd: [
|
|
2446
|
+
"sh",
|
|
2447
|
+
"-c",
|
|
2448
|
+
INIT_SCRIPT
|
|
2449
|
+
],
|
|
2450
|
+
User: "root",
|
|
2451
|
+
WorkingDir: SANDBOX_WORKSPACE_ROOT,
|
|
2452
|
+
Env: [`JUNIOR_SANDBOX_TIMEOUT_SECONDS=${Math.ceil(input.timeoutMs / 1e3)}`, ...CA_BUNDLE_ENV.map((name) => `${name}=${SYSTEM_CA_BUNDLE}`)],
|
|
2453
|
+
Labels: { [DOCKER_SANDBOX_LABEL]: input.name },
|
|
2454
|
+
HostConfig: {
|
|
2455
|
+
Init: true,
|
|
2456
|
+
Privileged: true,
|
|
2457
|
+
AutoRemove: !input.persistent,
|
|
2458
|
+
NetworkMode: input.name,
|
|
2459
|
+
Mounts: [{
|
|
2460
|
+
Type: "volume",
|
|
2461
|
+
Target: "/var/lib/docker"
|
|
2462
|
+
}],
|
|
2463
|
+
...input.vcpus ? { NanoCpus: input.vcpus * 1e9 } : void 0
|
|
2464
|
+
}
|
|
2465
|
+
},
|
|
2466
|
+
signal: input.signal
|
|
2467
|
+
});
|
|
2468
|
+
} catch (error) {
|
|
2469
|
+
await removeNetwork(input.name).catch(() => void 0);
|
|
2470
|
+
throw error;
|
|
2471
|
+
}
|
|
2472
|
+
try {
|
|
2473
|
+
await start(input.name, input.signal);
|
|
2474
|
+
const details = await inspect(input.name, input.signal);
|
|
2475
|
+
await waitUntilReady(details.Id, input.signal);
|
|
2476
|
+
await trustEgressCa(details.Id, egressCaPem);
|
|
2477
|
+
return toContainer(details);
|
|
2478
|
+
} catch (error) {
|
|
2479
|
+
await removeContainer(input.name).catch(() => void 0);
|
|
2480
|
+
throw error;
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Return a running sandbox container. Start it again when it stopped.
|
|
2485
|
+
* A missing container throws a 404 `DockerApiError`.
|
|
2486
|
+
*/
|
|
2487
|
+
async function getContainer(name, egressCaPem, signal) {
|
|
2488
|
+
let details = await inspect(name, signal);
|
|
2489
|
+
if (!details.State.Running) {
|
|
2490
|
+
await start(name, signal);
|
|
2491
|
+
details = await inspect(name, signal);
|
|
2492
|
+
}
|
|
2493
|
+
await waitUntilReady(details.Id, signal);
|
|
2494
|
+
await trustEgressCa(details.Id, egressCaPem);
|
|
2495
|
+
return toContainer(details);
|
|
2496
|
+
}
|
|
2497
|
+
async function forceRemove(name) {
|
|
2498
|
+
try {
|
|
2499
|
+
await dockerRequest({
|
|
2500
|
+
method: "DELETE",
|
|
2501
|
+
path: `/containers/${encodeURIComponent(name)}`,
|
|
2502
|
+
query: {
|
|
2503
|
+
force: true,
|
|
2504
|
+
v: true
|
|
2505
|
+
}
|
|
2506
|
+
});
|
|
2507
|
+
} catch (error) {
|
|
2508
|
+
if (!isStatus(error, 404) && !isStatus(error, 409)) throw error;
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* Remove a sandbox container, its inner Docker volume, its egress relay, and
|
|
2513
|
+
* its network.
|
|
2514
|
+
*/
|
|
2515
|
+
async function removeContainer(name) {
|
|
2516
|
+
await forceRemove(name);
|
|
2517
|
+
await forceRemove(egressRelayName(name));
|
|
2518
|
+
await removeNetwork(name);
|
|
2519
|
+
}
|
|
2520
|
+
/**
|
|
2521
|
+
* Stop a sandbox container and remove its egress relay. A container that is
|
|
2522
|
+
* not persistent goes away. The next policy update starts a new relay.
|
|
2523
|
+
*/
|
|
2524
|
+
async function stopContainer(container) {
|
|
2525
|
+
try {
|
|
2526
|
+
await dockerRequest({
|
|
2527
|
+
method: "POST",
|
|
2528
|
+
path: `/containers/${container.id}/stop`,
|
|
2529
|
+
query: { t: 5 }
|
|
2530
|
+
});
|
|
2531
|
+
} catch (error) {
|
|
2532
|
+
if (!isStatus(error, 304) && !isStatus(error, 404)) throw error;
|
|
2533
|
+
}
|
|
2534
|
+
await forceRemove(egressRelayName(container.name));
|
|
2535
|
+
}
|
|
2536
|
+
/** Move the container's stop deadline later by `durationMs`. */
|
|
2537
|
+
async function extendDeadline(id, durationMs) {
|
|
2538
|
+
const result = await runRawExec(id, {
|
|
2539
|
+
cmd: [
|
|
2540
|
+
"sh",
|
|
2541
|
+
"-c",
|
|
2542
|
+
`d=$(cat /run/junior/deadline); echo $((d + ${Math.ceil(durationMs / 1e3)})) > /run/junior/deadline`
|
|
2543
|
+
],
|
|
2544
|
+
root: true
|
|
2545
|
+
});
|
|
2546
|
+
if (result.exitCode !== 0) throw new Error(`Could not extend sandbox timeout: ${result.stderr}`);
|
|
2547
|
+
}
|
|
2548
|
+
/** The uid and gid of the sandbox user, for files that Junior writes. */
|
|
2549
|
+
const SANDBOX_FILE_OWNER = {
|
|
2550
|
+
uid: 1e3,
|
|
2551
|
+
gid: 1e3,
|
|
2552
|
+
user: SANDBOX_USER
|
|
2553
|
+
};
|
|
2554
|
+
// src/chat/sandbox/docker/certificates.ts
|
|
2555
|
+
const CA_COMMON_NAME = "Docker Sandbox Egress CA";
|
|
2556
|
+
const CA_VALID_DAYS = 3650;
|
|
2557
|
+
/** Clients reject long-lived leaf certificates, so keep them short. */
|
|
2558
|
+
const LEAF_VALID_DAYS = 365;
|
|
2559
|
+
const DAY_MS = 864e5;
|
|
2560
|
+
const OID = {
|
|
2561
|
+
ecdsaWithSha256: "1.2.840.10045.4.3.2",
|
|
2562
|
+
commonName: "2.5.4.3",
|
|
2563
|
+
subjectKeyIdentifier: "2.5.29.14",
|
|
2564
|
+
keyUsage: "2.5.29.15",
|
|
2565
|
+
subjectAltName: "2.5.29.17",
|
|
2566
|
+
basicConstraints: "2.5.29.19",
|
|
2567
|
+
authorityKeyIdentifier: "2.5.29.35",
|
|
2568
|
+
extKeyUsage: "2.5.29.37",
|
|
2569
|
+
serverAuth: "1.3.6.1.5.5.7.3.1",
|
|
2570
|
+
clientAuth: "1.3.6.1.5.5.7.3.2"
|
|
2571
|
+
};
|
|
2572
|
+
function tlv(tag, content) {
|
|
2573
|
+
const length = content.length;
|
|
2574
|
+
if (length < 128) return Buffer.concat([Buffer.from([tag, length]), content]);
|
|
2575
|
+
const bytes = [];
|
|
2576
|
+
for (let value = length; value > 0; value >>= 8) bytes.unshift(value & 255);
|
|
2577
|
+
return Buffer.concat([Buffer.from([
|
|
2578
|
+
tag,
|
|
2579
|
+
128 | bytes.length,
|
|
2580
|
+
...bytes
|
|
2581
|
+
]), content]);
|
|
2582
|
+
}
|
|
2583
|
+
const sequence = (...parts) => tlv(48, Buffer.concat(parts));
|
|
2584
|
+
const set = (...parts) => tlv(49, Buffer.concat(parts));
|
|
2585
|
+
const octetString = (value) => tlv(4, value);
|
|
2586
|
+
const bitString = (value) => tlv(3, Buffer.concat([Buffer.from([0]), value]));
|
|
2587
|
+
const explicit = (index, value) => tlv(160 + index, value);
|
|
2588
|
+
const booleanTrue = () => tlv(1, Buffer.from([255]));
|
|
2589
|
+
function integer(value) {
|
|
2590
|
+
return tlv(2, (value[0] ?? 0) & 128 ? Buffer.concat([Buffer.from([0]), value]) : value);
|
|
2591
|
+
}
|
|
2592
|
+
function oid(value) {
|
|
2593
|
+
const [first = 0, second = 0, ...rest] = value.split(".").map(Number);
|
|
2594
|
+
const bytes = [first * 40 + second];
|
|
2595
|
+
for (const part of rest) {
|
|
2596
|
+
const chunk = [part & 127];
|
|
2597
|
+
for (let remaining = part >> 7; remaining > 0; remaining >>= 7) chunk.unshift(remaining & 127 | 128);
|
|
2598
|
+
bytes.push(...chunk);
|
|
2599
|
+
}
|
|
2600
|
+
return tlv(6, Buffer.from(bytes));
|
|
2601
|
+
}
|
|
2602
|
+
function time(date) {
|
|
2603
|
+
const iso = date.toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
2604
|
+
return date.getUTCFullYear() < 2050 ? tlv(23, Buffer.from(`${iso.slice(2)}Z`)) : tlv(24, Buffer.from(`${iso}Z`));
|
|
2605
|
+
}
|
|
2606
|
+
function name(commonName) {
|
|
2607
|
+
return sequence(set(sequence(oid(OID.commonName), tlv(12, Buffer.from(commonName)))));
|
|
2608
|
+
}
|
|
2609
|
+
function extension(id, critical, value) {
|
|
2610
|
+
return sequence(oid(id), ...critical ? [booleanTrue()] : [], octetString(value));
|
|
2611
|
+
}
|
|
2612
|
+
function publicKeyInfo(key) {
|
|
2613
|
+
return createPublicKey(key).export({
|
|
2614
|
+
type: "spki",
|
|
2615
|
+
format: "der"
|
|
2616
|
+
});
|
|
2617
|
+
}
|
|
2618
|
+
function keyIdentifier(key) {
|
|
2619
|
+
return createHash("sha1").update(publicKeyInfo(key)).digest();
|
|
2620
|
+
}
|
|
2621
|
+
function certificate(input) {
|
|
2622
|
+
const serial = randomBytes(16);
|
|
2623
|
+
serial[0] = (serial[0] ?? 0) & 127;
|
|
2624
|
+
const algorithm = sequence(oid(OID.ecdsaWithSha256));
|
|
2625
|
+
const now = Date.now();
|
|
2626
|
+
const tbs = sequence(explicit(0, integer(Buffer.from([2]))), integer(serial), algorithm, input.issuer, sequence(time(/* @__PURE__ */ new Date(now - DAY_MS)), time(new Date(now + input.validDays * DAY_MS))), input.subject, publicKeyInfo(input.publicKey), explicit(3, sequence(...input.extensions)));
|
|
2627
|
+
const signature = sign("sha256", tbs, {
|
|
2628
|
+
key: input.signingKey,
|
|
2629
|
+
dsaEncoding: "der"
|
|
2630
|
+
});
|
|
2631
|
+
return `-----BEGIN CERTIFICATE-----\n${sequence(tbs, algorithm, bitString(signature)).toString("base64").replace(/(.{64})/g, "$1\n").trim()}\n-----END CERTIFICATE-----\n`;
|
|
2632
|
+
}
|
|
2633
|
+
function newKey() {
|
|
2634
|
+
return generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey;
|
|
2635
|
+
}
|
|
2636
|
+
function createCa() {
|
|
2637
|
+
const key = newKey();
|
|
2638
|
+
const subject = name(CA_COMMON_NAME);
|
|
2639
|
+
return {
|
|
2640
|
+
certPem: certificate({
|
|
2641
|
+
subject,
|
|
2642
|
+
issuer: subject,
|
|
2643
|
+
publicKey: key,
|
|
2644
|
+
signingKey: key,
|
|
2645
|
+
validDays: CA_VALID_DAYS,
|
|
2646
|
+
extensions: [
|
|
2647
|
+
extension(OID.basicConstraints, true, sequence(booleanTrue())),
|
|
2648
|
+
extension(OID.keyUsage, true, tlv(3, Buffer.from([1, 6]))),
|
|
2649
|
+
extension(OID.subjectKeyIdentifier, false, octetString(keyIdentifier(key)))
|
|
2650
|
+
]
|
|
2651
|
+
}),
|
|
2652
|
+
keyPem: key.export({
|
|
2653
|
+
type: "pkcs8",
|
|
2654
|
+
format: "pem"
|
|
2655
|
+
}).toString()
|
|
2656
|
+
};
|
|
2657
|
+
}
|
|
2658
|
+
async function readOrCreate(file, create) {
|
|
2659
|
+
try {
|
|
2660
|
+
return await fs.readFile(file, "utf8");
|
|
2661
|
+
} catch (error) {
|
|
2662
|
+
if (error.code !== "ENOENT") throw error;
|
|
2663
|
+
}
|
|
2664
|
+
try {
|
|
2665
|
+
await fs.writeFile(file, create(), {
|
|
2666
|
+
flag: "wx",
|
|
2667
|
+
mode: 384
|
|
2668
|
+
});
|
|
2669
|
+
} catch (error) {
|
|
2670
|
+
if (error.code !== "EEXIST") throw error;
|
|
2671
|
+
}
|
|
2672
|
+
return await fs.readFile(file, "utf8");
|
|
2673
|
+
}
|
|
2674
|
+
/**
|
|
2675
|
+
* Load this machine's egress CA from `dir`, or create it.
|
|
2676
|
+
*
|
|
2677
|
+
* Every Junior process on the machine shares one CA, so a sandbox trusts the
|
|
2678
|
+
* proxy of any process that applies its network policy.
|
|
2679
|
+
*/
|
|
2680
|
+
async function loadEgressCa(dir) {
|
|
2681
|
+
await fs.mkdir(dir, {
|
|
2682
|
+
recursive: true,
|
|
2683
|
+
mode: 448
|
|
2684
|
+
});
|
|
2685
|
+
const keyFile = path.join(dir, "egress-ca-key.pem");
|
|
2686
|
+
const certFile = path.join(dir, "egress-ca.pem");
|
|
2687
|
+
let created;
|
|
2688
|
+
const make = () => created ??= createCa();
|
|
2689
|
+
const keyPem = await readOrCreate(keyFile, () => make().keyPem);
|
|
2690
|
+
const certPem = await readOrCreate(certFile, () => {
|
|
2691
|
+
if (!created) throw new Error(`${keyFile} exists without ${certFile}. Delete it.`);
|
|
2692
|
+
return created.certPem;
|
|
2693
|
+
});
|
|
2694
|
+
const key = createPrivateKey(keyPem);
|
|
2695
|
+
return {
|
|
2696
|
+
certPem,
|
|
2697
|
+
key,
|
|
2698
|
+
keyId: keyIdentifier(key),
|
|
2699
|
+
subject: name(CA_COMMON_NAME)
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
/**
|
|
2703
|
+
* Issue a TLS certificate for one name, signed by the egress CA.
|
|
2704
|
+
* It works as a server certificate and as an egress relay client certificate.
|
|
2705
|
+
*/
|
|
2706
|
+
function issueLeafCertificate(ca, host, key) {
|
|
2707
|
+
return certificate({
|
|
2708
|
+
subject: name(host),
|
|
2709
|
+
issuer: ca.subject,
|
|
2710
|
+
publicKey: key,
|
|
2711
|
+
signingKey: ca.key,
|
|
2712
|
+
validDays: LEAF_VALID_DAYS,
|
|
2713
|
+
extensions: [
|
|
2714
|
+
extension(OID.basicConstraints, true, sequence()),
|
|
2715
|
+
extension(OID.keyUsage, true, tlv(3, Buffer.from([7, 128]))),
|
|
2716
|
+
extension(OID.extKeyUsage, false, sequence(oid(OID.serverAuth), oid(OID.clientAuth))),
|
|
2717
|
+
extension(OID.subjectAltName, false, sequence(tlv(130, Buffer.from(host)))),
|
|
2718
|
+
extension(OID.authorityKeyIdentifier, false, sequence(tlv(128, ca.keyId)))
|
|
2719
|
+
]
|
|
2720
|
+
});
|
|
2721
|
+
}
|
|
2722
|
+
/** Create the private key that this process uses for every leaf certificate. */
|
|
2723
|
+
function createLeafKey() {
|
|
2724
|
+
return newKey();
|
|
2725
|
+
}
|
|
2726
|
+
// src/chat/sandbox/docker/runtime-image.ts
|
|
2727
|
+
const BASE_IMAGE = {
|
|
2728
|
+
name: "amazonlinux",
|
|
2729
|
+
tag: "2023"
|
|
2730
|
+
};
|
|
2731
|
+
const RUNTIME_REPOSITORY = "junior-sandbox-runtime";
|
|
2732
|
+
/** System packages for each runtime, installed on top of the base image. */
|
|
2733
|
+
const RUNTIME_PACKAGES = { node24: ["nodejs24", "nodejs24-npm"] };
|
|
2734
|
+
const COMMON_PACKAGES = [
|
|
2735
|
+
"coreutils",
|
|
2736
|
+
"diffutils",
|
|
2737
|
+
"findutils",
|
|
2738
|
+
"git",
|
|
2739
|
+
"gzip",
|
|
2740
|
+
"iptables-nft",
|
|
2741
|
+
"openssl",
|
|
2742
|
+
"procps-ng",
|
|
2743
|
+
"shadow-utils",
|
|
2744
|
+
"socat",
|
|
2745
|
+
"sudo",
|
|
2746
|
+
"tar",
|
|
2747
|
+
"unzip",
|
|
2748
|
+
"util-linux",
|
|
2749
|
+
"which"
|
|
2750
|
+
];
|
|
2751
|
+
function buildScript(runtime) {
|
|
2752
|
+
const packages = RUNTIME_PACKAGES[runtime];
|
|
2753
|
+
if (!packages) throw new Error(`The Docker sandbox provider has no runtime ${runtime}`);
|
|
2754
|
+
return [
|
|
2755
|
+
"set -eu",
|
|
2756
|
+
`dnf install -y --allowerasing ${[...packages, ...COMMON_PACKAGES].join(" ")}`,
|
|
2757
|
+
"dnf clean all",
|
|
2758
|
+
`useradd --create-home --uid 1000 ${SANDBOX_USER}`,
|
|
2759
|
+
`echo '${SANDBOX_USER} ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/${SANDBOX_USER}`,
|
|
2760
|
+
`chmod 0440 /etc/sudoers.d/${SANDBOX_USER}`,
|
|
2761
|
+
`mkdir -p ${SANDBOX_WORKSPACE_ROOT}`,
|
|
2762
|
+
`chown ${SANDBOX_USER}:${SANDBOX_USER} ${SANDBOX_WORKSPACE_ROOT}`,
|
|
2763
|
+
`mkdir -p -m 1777 ${COMMAND_STATE_DIR}`
|
|
2764
|
+
].join("\n");
|
|
2765
|
+
}
|
|
2766
|
+
function runtimeTag(runtime) {
|
|
2767
|
+
return `${runtime}-${createHash("sha256").update(`${BASE_IMAGE.name}:${BASE_IMAGE.tag}\n${buildScript(runtime)}`).digest("hex").slice(0, 12)}`;
|
|
2768
|
+
}
|
|
2769
|
+
async function imageExists(reference) {
|
|
2770
|
+
try {
|
|
2771
|
+
await dockerRequest({ path: `/images/${encodeURIComponent(reference)}/json` });
|
|
2772
|
+
return true;
|
|
2773
|
+
} catch (error) {
|
|
2774
|
+
if (error instanceof DockerApiError && error.statusCode === 404) return false;
|
|
2775
|
+
throw error;
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
async function pullBaseImage(signal) {
|
|
2779
|
+
const lines = (await readStream(await dockerOkStream({
|
|
2780
|
+
method: "POST",
|
|
2781
|
+
path: "/images/create",
|
|
2782
|
+
query: {
|
|
2783
|
+
fromImage: BASE_IMAGE.name,
|
|
2784
|
+
tag: BASE_IMAGE.tag
|
|
2785
|
+
},
|
|
2786
|
+
signal
|
|
2787
|
+
}))).toString("utf8").split("\n");
|
|
2788
|
+
for (const line of lines) {
|
|
2789
|
+
if (!line.trim()) continue;
|
|
2790
|
+
const event = JSON.parse(line);
|
|
2791
|
+
if (event.error) throw new Error(`Docker pull failed: ${event.error}`);
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
/**
|
|
2795
|
+
* Return the local image for a sandbox runtime. Build it on first use.
|
|
2796
|
+
*
|
|
2797
|
+
* The tag holds a hash of the build script, so a changed script builds a new
|
|
2798
|
+
* image. Two processes may build the same image at once. The last commit wins,
|
|
2799
|
+
* and both images work.
|
|
2800
|
+
*/
|
|
2801
|
+
async function ensureRuntimeImage(runtime, signal) {
|
|
2802
|
+
const reference = `${RUNTIME_REPOSITORY}:${runtimeTag(runtime)}`;
|
|
2803
|
+
if (await imageExists(reference)) return reference;
|
|
2804
|
+
const base = `${BASE_IMAGE.name}:${BASE_IMAGE.tag}`;
|
|
2805
|
+
if (!await imageExists(base)) await pullBaseImage(signal);
|
|
2806
|
+
const name = `junior-runtime-build-${randomUUID()}`;
|
|
2807
|
+
const created = await dockerJson({
|
|
2808
|
+
method: "POST",
|
|
2809
|
+
path: "/containers/create",
|
|
2810
|
+
query: { name },
|
|
2811
|
+
body: {
|
|
2812
|
+
Image: base,
|
|
2813
|
+
Cmd: ["sleep", "infinity"],
|
|
2814
|
+
Labels: { [DOCKER_SANDBOX_LABEL]: name }
|
|
2815
|
+
},
|
|
2816
|
+
signal
|
|
2817
|
+
});
|
|
2818
|
+
try {
|
|
2819
|
+
await dockerRequest({
|
|
2820
|
+
method: "POST",
|
|
2821
|
+
path: `/containers/${created.Id}/start`,
|
|
2822
|
+
signal
|
|
2823
|
+
});
|
|
2824
|
+
const result = await runRawExec(created.Id, {
|
|
2825
|
+
cmd: [
|
|
2826
|
+
"sh",
|
|
2827
|
+
"-c",
|
|
2828
|
+
buildScript(runtime)
|
|
2829
|
+
],
|
|
2830
|
+
root: true
|
|
2831
|
+
}, signal);
|
|
2832
|
+
if (result.exitCode !== 0) throw new Error(`Docker sandbox runtime ${runtime} build failed (exit ${result.exitCode}): ${result.stderr.slice(-2e3)}`);
|
|
2833
|
+
const [repo, tag] = reference.split(":");
|
|
2834
|
+
await dockerRequest({
|
|
2835
|
+
method: "POST",
|
|
2836
|
+
path: "/commit",
|
|
2837
|
+
query: {
|
|
2838
|
+
container: created.Id,
|
|
2839
|
+
repo,
|
|
2840
|
+
tag,
|
|
2841
|
+
changes: `LABEL ${DOCKER_SANDBOX_LABEL}=runtime`
|
|
2842
|
+
},
|
|
2843
|
+
signal
|
|
2844
|
+
});
|
|
2845
|
+
return reference;
|
|
2846
|
+
} finally {
|
|
2847
|
+
await dockerRequest({
|
|
2848
|
+
method: "DELETE",
|
|
2849
|
+
path: `/containers/${created.Id}`,
|
|
2850
|
+
query: {
|
|
2851
|
+
force: true,
|
|
2852
|
+
v: true
|
|
2853
|
+
}
|
|
2854
|
+
}).catch(() => {});
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
// src/chat/sandbox/snapshot/runtime.ts
|
|
2858
|
+
/** Runtime used to build and start reusable Sandbox snapshots. */
|
|
2859
|
+
const SANDBOX_RUNTIME = "node24";
|
|
2860
|
+
// src/chat/sandbox/docker/relay.ts
|
|
2861
|
+
/** Host name of the Docker host as seen from a container. */
|
|
2862
|
+
const RELAY_PROXY_HOST = "host.docker.internal";
|
|
2863
|
+
const RELAY_PORT = 15080;
|
|
2864
|
+
const RELAY_DIR = "/run/junior-relay";
|
|
2865
|
+
/** Label with the proxy port that the relay sends to. */
|
|
2866
|
+
const TARGET_LABEL = "dev.junior.sandbox.relay-target";
|
|
2867
|
+
/**
|
|
2868
|
+
* Return whether sandboxes reach the proxy through a relay.
|
|
2869
|
+
*
|
|
2870
|
+
* On Linux, the Docker daemon runs on this host, and the sandbox network
|
|
2871
|
+
* gateway is a host address. Other systems run the daemon in a VM.
|
|
2872
|
+
*/
|
|
2873
|
+
function usesEgressRelay() {
|
|
2874
|
+
return process.platform !== "linux";
|
|
2875
|
+
}
|
|
2876
|
+
async function inspectRelay(name) {
|
|
2877
|
+
try {
|
|
2878
|
+
return await dockerJson({ path: `/containers/${encodeURIComponent(name)}/json` });
|
|
2879
|
+
} catch (error) {
|
|
2880
|
+
if (error instanceof DockerApiError && error.statusCode === 404) return;
|
|
2881
|
+
throw error;
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
function relayAddress(container, relay) {
|
|
2885
|
+
const ip = relay.NetworkSettings.Networks[container.name]?.IPAddress;
|
|
2886
|
+
if (!ip) throw new Error(`Egress relay of ${container.name} has no address`);
|
|
2887
|
+
return `${ip}:${RELAY_PORT}`;
|
|
2888
|
+
}
|
|
2889
|
+
function relayFiles(ca, container) {
|
|
2890
|
+
const key = createLeafKey();
|
|
2891
|
+
const files = {
|
|
2892
|
+
"client.pem": issueLeafCertificate(ca, container.id, key),
|
|
2893
|
+
"client-key.pem": key.export({
|
|
2894
|
+
type: "pkcs8",
|
|
2895
|
+
format: "pem"
|
|
2896
|
+
}).toString(),
|
|
2897
|
+
"ca.pem": ca.certPem
|
|
2898
|
+
};
|
|
2899
|
+
return packTar(Object.entries(files).map(([file, content]) => ({
|
|
2900
|
+
path: `${RELAY_DIR.slice(1)}/${file}`,
|
|
2901
|
+
content: Buffer.from(content),
|
|
2902
|
+
mode: 384,
|
|
2903
|
+
uid: 0,
|
|
2904
|
+
gid: 0
|
|
2905
|
+
})));
|
|
2906
|
+
}
|
|
2907
|
+
/**
|
|
2908
|
+
* Start the egress relay of one sandbox, or reuse it, and return the address
|
|
2909
|
+
* that the sandbox's redirect rules send traffic to.
|
|
2910
|
+
*
|
|
2911
|
+
* A relay sends to one proxy port. When another process applies the policy,
|
|
2912
|
+
* this replaces the relay so that it sends to that process's proxy.
|
|
2913
|
+
*/
|
|
2914
|
+
async function ensureEgressRelay(container, ca, proxyPort) {
|
|
2915
|
+
const name = egressRelayName(container.name);
|
|
2916
|
+
const existing = await inspectRelay(name);
|
|
2917
|
+
if (existing?.State.Running && existing.Config.Labels[TARGET_LABEL] === String(proxyPort)) return relayAddress(container, existing);
|
|
2918
|
+
if (existing) await dockerRequest({
|
|
2919
|
+
method: "DELETE",
|
|
2920
|
+
path: `/containers/${existing.Id}`,
|
|
2921
|
+
query: { force: true }
|
|
2922
|
+
});
|
|
2923
|
+
const created = await dockerJson({
|
|
2924
|
+
method: "POST",
|
|
2925
|
+
path: "/containers/create",
|
|
2926
|
+
query: { name },
|
|
2927
|
+
body: {
|
|
2928
|
+
Image: await ensureRuntimeImage(SANDBOX_RUNTIME),
|
|
2929
|
+
Cmd: [
|
|
2930
|
+
"socat",
|
|
2931
|
+
`TCP-LISTEN:${RELAY_PORT},fork,reuseaddr`,
|
|
2932
|
+
`OPENSSL:${RELAY_PROXY_HOST}:${proxyPort},cert=${RELAY_DIR}/client.pem,key=${RELAY_DIR}/client-key.pem,cafile=${RELAY_DIR}/ca.pem`
|
|
2933
|
+
],
|
|
2934
|
+
User: "root",
|
|
2935
|
+
Labels: {
|
|
2936
|
+
[DOCKER_SANDBOX_LABEL]: `relay:${container.name}`,
|
|
2937
|
+
[TARGET_LABEL]: String(proxyPort)
|
|
2938
|
+
},
|
|
2939
|
+
HostConfig: {
|
|
2940
|
+
NetworkMode: container.name,
|
|
2941
|
+
ExtraHosts: [`${RELAY_PROXY_HOST}:host-gateway`]
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
});
|
|
2945
|
+
await dockerRequest({
|
|
2946
|
+
method: "PUT",
|
|
2947
|
+
path: `/containers/${created.Id}/archive`,
|
|
2948
|
+
query: { path: "/" },
|
|
2949
|
+
body: relayFiles(ca, container)
|
|
2950
|
+
});
|
|
2951
|
+
await dockerRequest({
|
|
2952
|
+
method: "POST",
|
|
2953
|
+
path: `/containers/${created.Id}/start`
|
|
2954
|
+
});
|
|
2955
|
+
const started = await inspectRelay(created.Id);
|
|
2956
|
+
if (!started?.State.Running) throw new Error(`Egress relay of ${container.name} did not start`);
|
|
2957
|
+
return relayAddress(container, started);
|
|
2958
|
+
}
|
|
2959
|
+
// src/chat/sandbox/egress/credential-request.ts
|
|
2960
|
+
const CREDENTIAL_HEADERS = ["authorization", "cookie"];
|
|
2961
|
+
const BROWSER_HEADER = "sec-fetch-site";
|
|
2962
|
+
function placeholders(manifest) {
|
|
2963
|
+
const credentials = manifest.credentials;
|
|
2964
|
+
return [HOST_MANAGED_CREDENTIAL_PLACEHOLDER, ...credentials?.type === "oauth-bearer" ? [resolveAuthTokenPlaceholder(credentials)] : []];
|
|
2965
|
+
}
|
|
2966
|
+
function credentialHeaders(manifest) {
|
|
2967
|
+
const credentials = manifest.credentials;
|
|
2968
|
+
return new Set([
|
|
2969
|
+
...CREDENTIAL_HEADERS,
|
|
2970
|
+
...Object.keys(manifest.apiHeaders ?? {}),
|
|
2971
|
+
...credentials?.type === "oauth-bearer" ? Object.keys(credentials.apiHeaders ?? {}) : [],
|
|
2972
|
+
...credentials?.type === "workload-identity" ? [workloadIdentityHeader(credentials)] : []
|
|
2973
|
+
].map((name) => name.toLowerCase()));
|
|
2974
|
+
}
|
|
2975
|
+
function decodedBasicAuth(value) {
|
|
2976
|
+
const match = /^basic\s+(\S+)$/i.exec(value.trim());
|
|
2977
|
+
if (!match?.[1]) return;
|
|
2978
|
+
return Buffer.from(match[1], "base64").toString("utf8");
|
|
2979
|
+
}
|
|
2980
|
+
function hasPlaceholder(value, markers) {
|
|
2981
|
+
const decoded = decodedBasicAuth(value);
|
|
2982
|
+
return markers.some((marker) => value.includes(marker) || decoded !== void 0 && decoded.includes(marker));
|
|
2983
|
+
}
|
|
2984
|
+
/**
|
|
2985
|
+
* Classify one Sandbox request by the credential it sends.
|
|
2986
|
+
*
|
|
2987
|
+
* A browser request is `browser`, whatever it sends. Otherwise a credential
|
|
2988
|
+
* header with any value other than a placeholder makes the request `carried`, even when another header has a placeholder, so the host
|
|
2989
|
+
* never replaces a credential that the request brought.
|
|
2990
|
+
*/
|
|
2991
|
+
function classifySandboxCredentialRequest(manifest, headers) {
|
|
2992
|
+
if (headers.has(BROWSER_HEADER)) return "browser";
|
|
2993
|
+
const markers = placeholders(manifest);
|
|
2994
|
+
const names = credentialHeaders(manifest);
|
|
2995
|
+
let sawPlaceholder = false;
|
|
2996
|
+
for (const [key, value] of headers) if (hasPlaceholder(value, markers)) sawPlaceholder = true;
|
|
2997
|
+
else if (names.has(key) && value.trim()) return "carried";
|
|
2998
|
+
return sawPlaceholder ? "placeholder" : "none";
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Return whether the host adds the plugin's credential to a Sandbox request.
|
|
3002
|
+
*
|
|
3003
|
+
* A request gets a credential when it sends the plugin's placeholder, or when
|
|
3004
|
+
* it sends no credential and the plugin says that its tools send none.
|
|
3005
|
+
*/
|
|
3006
|
+
function sandboxRequestGetsCredential(manifest, request) {
|
|
3007
|
+
return request === "placeholder" || request === "none" && manifest.toolsSendNoCredential === true;
|
|
3008
|
+
}
|
|
3009
|
+
// src/chat/sandbox/egress/proxy.ts
|
|
3010
|
+
function jsonError$1(message, status) {
|
|
3011
|
+
return Response.json({ error: message }, { status });
|
|
3012
|
+
}
|
|
3013
|
+
/** Return log attributes that identify one sandbox egress request. */
|
|
3014
|
+
function sandboxEgressAttributes(input) {
|
|
3015
|
+
return {
|
|
3016
|
+
...input.egressId ? { "app.sandbox.egress_id": input.egressId } : void 0,
|
|
3017
|
+
...input.provider ? { "app.provider.name": input.provider } : void 0,
|
|
3018
|
+
...input.host ? { "server.address": input.host } : void 0,
|
|
3019
|
+
...input.method ? { "http.request.method": input.method } : void 0,
|
|
3020
|
+
...input.path ? { "url.path": input.path } : void 0,
|
|
3021
|
+
...input.status ? { "http.response.status_code": input.status } : void 0
|
|
3022
|
+
};
|
|
3023
|
+
}
|
|
3024
|
+
/** Return log attributes for the proxy route and the upstream path. */
|
|
3025
|
+
function sandboxEgressRoutingAttributes(request, upstreamUrl) {
|
|
3026
|
+
const proxyUrl = new URL(request.url);
|
|
3027
|
+
const attributes = { "app.sandbox.egress.proxy_path": redactSandboxEgressProxyPath(proxyUrl.pathname) };
|
|
3028
|
+
if (upstreamUrl) {
|
|
3029
|
+
attributes["app.sandbox.egress.upstream_path"] = upstreamUrl.pathname;
|
|
3030
|
+
const gitService = upstreamUrl.searchParams.get("service");
|
|
3031
|
+
if (upstreamUrl.hostname.toLowerCase() === "github.com" && (gitService === "git-upload-pack" || gitService === "git-receive-pack")) attributes["app.sandbox.egress.git_service"] = gitService;
|
|
3032
|
+
}
|
|
3033
|
+
return attributes;
|
|
3034
|
+
}
|
|
3035
|
+
/**
|
|
3036
|
+
* Name the Conversation and the accountable person from the verified token.
|
|
3037
|
+
* Each proxy request is a new HTTP request with no run log context, so the
|
|
3038
|
+
* proxy binds the same fields that the run binds.
|
|
3039
|
+
*/
|
|
3040
|
+
function sandboxEgressLogContext(context) {
|
|
3041
|
+
return {
|
|
3042
|
+
...context.conversationId ? { conversationId: context.conversationId } : void 0,
|
|
3043
|
+
...credentialLogContext(context.credentials)
|
|
3044
|
+
};
|
|
3045
|
+
}
|
|
3046
|
+
/** Continue inbound trace context only after sandbox egress verification succeeds. */
|
|
3047
|
+
function continueSandboxEgressTrace(request, upstreamHost, tracePropagation, credentialContext, callback) {
|
|
3048
|
+
const sentryTrace = request.headers.get("sentry-trace") ?? void 0;
|
|
3049
|
+
const baggage = request.headers.get("baggage") ?? void 0;
|
|
3050
|
+
const logContext = sandboxEgressLogContext(credentialContext);
|
|
3051
|
+
const run = () => withSpan("sandbox.egress", "http.server", logContext, async () => {
|
|
3052
|
+
setSentryUser(logContext.userId ? { id: logContext.userId } : void 0);
|
|
3053
|
+
return await callback();
|
|
3054
|
+
}, {
|
|
3055
|
+
"http.request.method": request.method,
|
|
3056
|
+
"url.path": redactSandboxEgressProxyPath(new URL(request.url).pathname)
|
|
3057
|
+
});
|
|
3058
|
+
if (!shouldPropagateSandboxEgressTrace(upstreamHost, tracePropagation) || !sentryTrace && !baggage) return run();
|
|
3059
|
+
return continueTrace({
|
|
3060
|
+
sentryTrace,
|
|
3061
|
+
baggage
|
|
3062
|
+
}, run);
|
|
3063
|
+
}
|
|
3064
|
+
/**
|
|
3065
|
+
* Choose whether this request gets the plugin's credential. Only a request
|
|
3066
|
+
* that asks for one gets it, so Sandbox code does not act as the Actor only
|
|
3067
|
+
* because it calls a provider domain.
|
|
3068
|
+
*/
|
|
3069
|
+
function credentialRequestInput(provider, request) {
|
|
3070
|
+
const manifest = pluginCatalogRuntime.getDefinition(provider)?.manifest;
|
|
3071
|
+
if (!manifest) throw new Error(`Plugin "${provider}" has no manifest for sandbox egress`);
|
|
3072
|
+
const credentialRequest = classifySandboxCredentialRequest(manifest, request.headers);
|
|
3073
|
+
if (credentialRequest === "placeholder" || sandboxRequestGetsCredential(manifest, credentialRequest)) return {};
|
|
3074
|
+
return { withoutCredential: credentialRequest };
|
|
3075
|
+
}
|
|
3076
|
+
/**
|
|
3077
|
+
* Run one sandbox egress request that its sandbox provider authenticated.
|
|
3078
|
+
*
|
|
3079
|
+
* This is the shared authorization boundary. It rejects upstream hosts that no
|
|
3080
|
+
* plugin owns, rejects signed credential contexts that do not match the
|
|
3081
|
+
* verified VM id, and only then asks the credentialed egress engine to issue
|
|
3082
|
+
* credentials and contact the upstream provider.
|
|
3083
|
+
*/
|
|
3084
|
+
async function executeSandboxEgressRequest(input, deps = {}) {
|
|
3085
|
+
const { request, upstreamUrl } = input;
|
|
3086
|
+
const activeEgressId = input.egressId;
|
|
3087
|
+
const provider = resolveSandboxEgressProviderForHost(upstreamUrl.hostname);
|
|
3088
|
+
if (!provider) {
|
|
3089
|
+
logWarn("sandbox.egress.provider.unresolved", {
|
|
3090
|
+
...sandboxEgressAttributes({
|
|
3091
|
+
egressId: activeEgressId,
|
|
3092
|
+
host: upstreamUrl.hostname,
|
|
3093
|
+
method: request.method,
|
|
3094
|
+
path: upstreamUrl.pathname,
|
|
3095
|
+
status: 403
|
|
3096
|
+
}),
|
|
3097
|
+
...sandboxEgressRoutingAttributes(request, upstreamUrl),
|
|
3098
|
+
...egressDecisionAttributes("denied", "no provider owns forwarded host")
|
|
3099
|
+
});
|
|
3100
|
+
return jsonError$1("No provider owns forwarded host", 403);
|
|
3101
|
+
}
|
|
3102
|
+
const credentialContext = parseSandboxEgressCredentialToken(input.credentialToken);
|
|
3103
|
+
if (!credentialContext || credentialContext.egressId !== activeEgressId) {
|
|
3104
|
+
logWarn("sandbox.egress.credential_context.unauthorized", {
|
|
3105
|
+
...sandboxEgressAttributes({
|
|
3106
|
+
egressId: activeEgressId,
|
|
3107
|
+
host: upstreamUrl.hostname,
|
|
3108
|
+
method: request.method,
|
|
3109
|
+
path: upstreamUrl.pathname,
|
|
3110
|
+
provider,
|
|
3111
|
+
status: 403
|
|
3112
|
+
}),
|
|
3113
|
+
...sandboxEgressRoutingAttributes(request, upstreamUrl),
|
|
3114
|
+
...egressDecisionAttributes("denied", "credential context is not authorized")
|
|
3115
|
+
});
|
|
3116
|
+
return jsonError$1("Sandbox egress credential context is not authorized", 403);
|
|
3117
|
+
}
|
|
3118
|
+
return await continueSandboxEgressTrace(request, upstreamUrl.hostname, deps.tracePropagation ?? {}, credentialContext, async () => {
|
|
3119
|
+
const result = await executeCredentialedEgressRequest({
|
|
3120
|
+
activeEgressId,
|
|
3121
|
+
credentialContext,
|
|
3122
|
+
deps,
|
|
3123
|
+
provider,
|
|
3124
|
+
request,
|
|
3125
|
+
upstreamUrl,
|
|
3126
|
+
...credentialRequestInput(provider, request)
|
|
3127
|
+
});
|
|
3128
|
+
if (result.authRequired) await setSandboxEgressAuthRequiredSignal(credentialContext, result.authRequired);
|
|
3129
|
+
return result.response;
|
|
3130
|
+
});
|
|
3131
|
+
}
|
|
3132
|
+
// src/chat/sandbox/docker/egress.ts
|
|
3133
|
+
const CHAIN = "JUNIOR_EGRESS";
|
|
3134
|
+
/** Private destinations never go to the proxy. Provider domains are public. */
|
|
3135
|
+
const DIRECT_RANGES = [
|
|
3136
|
+
"127.0.0.0/8",
|
|
3137
|
+
"10.0.0.0/8",
|
|
3138
|
+
"172.16.0.0/12",
|
|
3139
|
+
"192.168.0.0/16"
|
|
3140
|
+
];
|
|
3141
|
+
/**
|
|
3142
|
+
* Pass-through connections start in the Junior process, so a sandbox could
|
|
3143
|
+
* name a host-local or internal service in SNI or `Host`. Block every
|
|
3144
|
+
* address that is not public.
|
|
3145
|
+
*/
|
|
3146
|
+
const BLOCKED_PASS_THROUGH = new net.BlockList();
|
|
3147
|
+
for (const [address, prefix] of [
|
|
3148
|
+
["0.0.0.0", 8],
|
|
3149
|
+
["10.0.0.0", 8],
|
|
3150
|
+
["100.64.0.0", 10],
|
|
3151
|
+
["127.0.0.0", 8],
|
|
3152
|
+
["169.254.0.0", 16],
|
|
3153
|
+
["172.16.0.0", 12],
|
|
3154
|
+
["192.0.0.0", 24],
|
|
3155
|
+
["192.168.0.0", 16],
|
|
3156
|
+
["198.18.0.0", 15],
|
|
3157
|
+
["224.0.0.0", 3]
|
|
3158
|
+
]) BLOCKED_PASS_THROUGH.addSubnet(address, prefix, "ipv4");
|
|
3159
|
+
for (const [address, prefix] of [
|
|
3160
|
+
["::", 128],
|
|
3161
|
+
["::1", 128],
|
|
3162
|
+
["64:ff9b::", 96],
|
|
3163
|
+
["fc00::", 7],
|
|
3164
|
+
["fe80::", 10],
|
|
3165
|
+
["ff00::", 8]
|
|
3166
|
+
]) BLOCKED_PASS_THROUGH.addSubnet(address, prefix, "ipv6");
|
|
3167
|
+
const MAX_PEEK_BYTES = 65536;
|
|
3168
|
+
const PEEK_TIMEOUT_MS = 1e4;
|
|
3169
|
+
const HOP_BY_HOP = /* @__PURE__ */ new Set([
|
|
3170
|
+
"connection",
|
|
3171
|
+
"host",
|
|
3172
|
+
"keep-alive",
|
|
3173
|
+
"proxy-authenticate",
|
|
3174
|
+
"proxy-authorization",
|
|
3175
|
+
"te",
|
|
3176
|
+
"trailer",
|
|
3177
|
+
"transfer-encoding",
|
|
3178
|
+
"upgrade"
|
|
3179
|
+
]);
|
|
3180
|
+
let proxyPromise;
|
|
3181
|
+
/** Load the egress CA. Each sandbox trusts it. */
|
|
3182
|
+
async function egressCaPem() {
|
|
3183
|
+
return (await loadEgressCa(dockerSandboxDir())).certPem;
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Return how the proxy handles a host, and the policy domain that it matched.
|
|
3187
|
+
* Upstream URLs use that domain, not the host name that the sandbox sent.
|
|
3188
|
+
*/
|
|
3189
|
+
function interceptMode(route, host) {
|
|
3190
|
+
const policy = route?.policy;
|
|
3191
|
+
const find = (domains) => (domains ?? []).find((domain) => matchesSandboxEgressDomain(host, domain));
|
|
3192
|
+
const credentialDomain = find(policy?.credentialEgress?.domains);
|
|
3193
|
+
if (credentialDomain) return {
|
|
3194
|
+
mode: "credential",
|
|
3195
|
+
domain: credentialDomain
|
|
3196
|
+
};
|
|
3197
|
+
const traceDomain = find(policy?.traceHeaders?.domains);
|
|
3198
|
+
if (traceDomain) return {
|
|
3199
|
+
mode: "trace",
|
|
3200
|
+
domain: traceDomain
|
|
3201
|
+
};
|
|
3202
|
+
}
|
|
3203
|
+
/**
|
|
3204
|
+
* Return the path and query of an origin-form request target.
|
|
3205
|
+
* An absolute or `//` target could name another host, so it is rejected.
|
|
3206
|
+
*/
|
|
3207
|
+
function originFormPath(target) {
|
|
3208
|
+
if (!target?.startsWith("/") || target.startsWith("//") || /[\r\n#]/.test(target)) return;
|
|
3209
|
+
const url = new URL(target, "http://sandbox-request.local");
|
|
3210
|
+
return `${url.pathname}${url.search}`;
|
|
3211
|
+
}
|
|
3212
|
+
/** Return the SNI host name of a complete TLS ClientHello record. */
|
|
3213
|
+
function parseSni(record) {
|
|
3214
|
+
let offset = 43;
|
|
3215
|
+
const read = (bytes) => {
|
|
3216
|
+
const value = record.readUIntBE(offset, bytes);
|
|
3217
|
+
offset += bytes;
|
|
3218
|
+
return value;
|
|
3219
|
+
};
|
|
3220
|
+
const skip = (lengthBytes) => {
|
|
3221
|
+
const length = read(lengthBytes);
|
|
3222
|
+
offset += length;
|
|
3223
|
+
};
|
|
3224
|
+
try {
|
|
3225
|
+
skip(1);
|
|
3226
|
+
skip(2);
|
|
3227
|
+
skip(1);
|
|
3228
|
+
const extensionsLength = read(2);
|
|
3229
|
+
const end = offset + extensionsLength;
|
|
3230
|
+
while (offset + 4 <= end) {
|
|
3231
|
+
const type = read(2);
|
|
3232
|
+
const length = read(2);
|
|
3233
|
+
if (type === 0) {
|
|
3234
|
+
offset += 3;
|
|
3235
|
+
const nameLength = read(2);
|
|
3236
|
+
return record.toString("ascii", offset, offset + nameLength);
|
|
3237
|
+
}
|
|
3238
|
+
offset += length;
|
|
3239
|
+
}
|
|
3240
|
+
} catch {}
|
|
3241
|
+
}
|
|
3242
|
+
/** Read until the first TLS record or HTTP request head is complete. */
|
|
3243
|
+
function peek(socket) {
|
|
3244
|
+
return new Promise((resolve, reject) => {
|
|
3245
|
+
let data = Buffer.alloc(0);
|
|
3246
|
+
const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("peek timeout")), PEEK_TIMEOUT_MS);
|
|
3247
|
+
const finish = (error, host) => {
|
|
3248
|
+
clearTimeout(timer);
|
|
3249
|
+
socket.off("data", onData);
|
|
3250
|
+
socket.off("error", finish);
|
|
3251
|
+
socket.pause();
|
|
3252
|
+
if (error) reject(error);
|
|
3253
|
+
else resolve({
|
|
3254
|
+
data,
|
|
3255
|
+
host,
|
|
3256
|
+
scheme: data[0] === 22 ? "https" : "http"
|
|
3257
|
+
});
|
|
3258
|
+
};
|
|
3259
|
+
const onData = (chunk) => {
|
|
3260
|
+
data = Buffer.concat([data, chunk]);
|
|
3261
|
+
if (data[0] === 22) {
|
|
3262
|
+
if (data.length < 5) return;
|
|
3263
|
+
const end = 5 + data.readUInt16BE(3);
|
|
3264
|
+
if (data.length >= end) return finish(void 0, parseSni(data.subarray(0, end)));
|
|
3265
|
+
} else {
|
|
3266
|
+
const head = data.indexOf("\r\n\r\n");
|
|
3267
|
+
if (head >= 0) {
|
|
3268
|
+
const match = /^host:[ \t]*([^\r\n:]+)/im.exec(data.toString("latin1", 0, head));
|
|
3269
|
+
return finish(void 0, match?.[1]?.trim());
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
if (data.length > MAX_PEEK_BYTES) finish(/* @__PURE__ */ new Error("request head too large"));
|
|
3273
|
+
};
|
|
3274
|
+
socket.on("data", onData);
|
|
3275
|
+
socket.once("error", finish);
|
|
3276
|
+
});
|
|
3277
|
+
}
|
|
3278
|
+
function requestHeaders(rawHeaders) {
|
|
3279
|
+
const headers = new Headers();
|
|
3280
|
+
for (let index = 0; index + 1 < rawHeaders.length; index += 2) {
|
|
3281
|
+
const name = rawHeaders[index] ?? "";
|
|
3282
|
+
if (HOP_BY_HOP.has(name.toLowerCase())) continue;
|
|
3283
|
+
headers.append(name, rawHeaders[index + 1] ?? "");
|
|
3284
|
+
}
|
|
3285
|
+
return headers;
|
|
3286
|
+
}
|
|
3287
|
+
async function writeResponse(response, res) {
|
|
3288
|
+
const headers = {};
|
|
3289
|
+
for (const [name, value] of response.headers) if (name !== "set-cookie" && !HOP_BY_HOP.has(name)) headers[name] = value;
|
|
3290
|
+
const cookies = response.headers.getSetCookie();
|
|
3291
|
+
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
3292
|
+
res.writeHead(response.status, headers);
|
|
3293
|
+
if (!response.body) return void res.end();
|
|
3294
|
+
Readable.fromWeb(response.body).pipe(res);
|
|
3295
|
+
}
|
|
3296
|
+
/** Send a trace-domain request upstream with the policy's trace headers. */
|
|
3297
|
+
async function forwardWithTraceHeaders(request, route) {
|
|
3298
|
+
const headers = new Headers(request.headers);
|
|
3299
|
+
for (const [name, value] of Object.entries(route.policy.traceHeaders?.headers ?? {})) headers.set(name, value);
|
|
3300
|
+
const upstream = await fetch(request.url, {
|
|
3301
|
+
method: request.method,
|
|
3302
|
+
headers,
|
|
3303
|
+
body: request.body,
|
|
3304
|
+
redirect: "manual",
|
|
3305
|
+
duplex: "half"
|
|
3306
|
+
});
|
|
3307
|
+
const responseHeaders = new Headers(upstream.headers);
|
|
3308
|
+
responseHeaders.delete("content-encoding");
|
|
3309
|
+
responseHeaders.delete("content-length");
|
|
3310
|
+
return new Response(upstream.body, {
|
|
3311
|
+
status: upstream.status,
|
|
3312
|
+
statusText: upstream.statusText,
|
|
3313
|
+
headers: responseHeaders
|
|
3314
|
+
});
|
|
3315
|
+
}
|
|
3316
|
+
async function handleRequest(proxy, connection, req, res) {
|
|
3317
|
+
const route = proxy.routes.get(connection.sourceIp);
|
|
3318
|
+
const host = req.headers.host?.split(":")[0]?.toLowerCase();
|
|
3319
|
+
if (host !== connection.host) {
|
|
3320
|
+
res.writeHead(421).end("Host does not match the TLS server name");
|
|
3321
|
+
return;
|
|
3322
|
+
}
|
|
3323
|
+
const intercept = interceptMode(route, host);
|
|
3324
|
+
if (!route || !intercept) {
|
|
3325
|
+
res.writeHead(403).end("Sandbox egress route is gone");
|
|
3326
|
+
return;
|
|
3327
|
+
}
|
|
3328
|
+
if (intercept.mode === "credential" && connection.scheme !== "https") {
|
|
3329
|
+
res.writeHead(403).end("Credentialed egress requires HTTPS");
|
|
3330
|
+
return;
|
|
3331
|
+
}
|
|
3332
|
+
const path = originFormPath(req.url);
|
|
3333
|
+
if (!path) {
|
|
3334
|
+
res.writeHead(400).end("Request target must be a path");
|
|
3335
|
+
return;
|
|
3336
|
+
}
|
|
3337
|
+
const upstreamUrl = new URL(`${connection.scheme}://${intercept.domain}${path}`);
|
|
3338
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
3339
|
+
const request = new Request(upstreamUrl, {
|
|
3340
|
+
method: req.method,
|
|
3341
|
+
headers: requestHeaders(req.rawHeaders),
|
|
3342
|
+
...hasBody ? {
|
|
3343
|
+
body: Readable.toWeb(req),
|
|
3344
|
+
duplex: "half"
|
|
3345
|
+
} : void 0
|
|
3346
|
+
});
|
|
3347
|
+
await writeResponse(intercept.mode === "credential" ? await executeSandboxEgressRequest({
|
|
3348
|
+
request,
|
|
3349
|
+
egressId: route.egressId,
|
|
3350
|
+
upstreamUrl,
|
|
3351
|
+
credentialToken: route.policy.credentialEgress?.credentialToken
|
|
3352
|
+
}) : await forwardWithTraceHeaders(request, route), res);
|
|
3353
|
+
}
|
|
3354
|
+
function secureContext(proxy, host) {
|
|
3355
|
+
let context = proxy.contexts.get(host);
|
|
3356
|
+
if (!context) {
|
|
3357
|
+
context = tls.createSecureContext({
|
|
3358
|
+
key: proxy.leafKey.export({
|
|
3359
|
+
type: "pkcs8",
|
|
3360
|
+
format: "pem"
|
|
3361
|
+
}),
|
|
3362
|
+
cert: issueLeafCertificate(proxy.ca, host, proxy.leafKey)
|
|
3363
|
+
});
|
|
3364
|
+
proxy.contexts.set(host, context);
|
|
3365
|
+
}
|
|
3366
|
+
return context;
|
|
3367
|
+
}
|
|
3368
|
+
/**
|
|
3369
|
+
* Check that the route's container still has this address on its own network.
|
|
3370
|
+
* A removed sandbox's address can come back on a new sandbox network.
|
|
3371
|
+
*/
|
|
3372
|
+
async function ownsAddress(route, sourceIp) {
|
|
3373
|
+
try {
|
|
3374
|
+
const details = await dockerJson({ path: `/containers/${route.egressId}/json` });
|
|
3375
|
+
return details.State.Running && details.NetworkSettings.Networks[route.name]?.IPAddress === sourceIp;
|
|
3376
|
+
} catch {
|
|
3377
|
+
return false;
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
3380
|
+
/**
|
|
3381
|
+
* Wrap a socket in a stream that first replays the bytes that `peek` read.
|
|
3382
|
+
* TLS and HTTP servers read a net.Socket's handle directly, so they would skip
|
|
3383
|
+
* bytes put back with `unshift`.
|
|
3384
|
+
*/
|
|
3385
|
+
function replay(socket, data) {
|
|
3386
|
+
const stream = new Duplex({
|
|
3387
|
+
read() {
|
|
3388
|
+
socket.resume();
|
|
3389
|
+
},
|
|
3390
|
+
write(chunk, encoding, callback) {
|
|
3391
|
+
socket.write(chunk, encoding, callback);
|
|
3392
|
+
},
|
|
3393
|
+
final(callback) {
|
|
3394
|
+
socket.end(callback);
|
|
3395
|
+
},
|
|
3396
|
+
destroy(error, callback) {
|
|
3397
|
+
socket.destroy(error ?? void 0);
|
|
3398
|
+
callback(error);
|
|
3399
|
+
}
|
|
3400
|
+
});
|
|
3401
|
+
stream.push(data);
|
|
3402
|
+
socket.on("data", (chunk) => {
|
|
3403
|
+
if (!stream.push(chunk)) socket.pause();
|
|
3404
|
+
});
|
|
3405
|
+
socket.on("end", () => stream.push(null));
|
|
3406
|
+
socket.on("error", (error) => stream.destroy(error));
|
|
3407
|
+
return stream;
|
|
3408
|
+
}
|
|
3409
|
+
/**
|
|
3410
|
+
* Resolve a pass-through host once and return its address. Return undefined
|
|
3411
|
+
* when any address is not public. The caller connects to this address, so a
|
|
3412
|
+
* second DNS answer cannot change the target.
|
|
3413
|
+
*/
|
|
3414
|
+
async function publicAddress(host) {
|
|
3415
|
+
const records = await dns.lookup(host, {
|
|
3416
|
+
all: true,
|
|
3417
|
+
verbatim: true
|
|
3418
|
+
}).catch(() => []);
|
|
3419
|
+
return records.some((record) => BLOCKED_PASS_THROUGH.check(record.address, record.family === 6 ? "ipv6" : "ipv4")) ? void 0 : records[0]?.address;
|
|
3420
|
+
}
|
|
3421
|
+
function passThrough(socket, data, host, port) {
|
|
3422
|
+
const upstream = net.connect({
|
|
3423
|
+
host,
|
|
3424
|
+
port
|
|
3425
|
+
}, () => {
|
|
3426
|
+
upstream.write(data);
|
|
3427
|
+
socket.pipe(upstream);
|
|
3428
|
+
upstream.pipe(socket);
|
|
3429
|
+
socket.resume();
|
|
3430
|
+
});
|
|
3431
|
+
upstream.on("error", () => socket.destroy());
|
|
3432
|
+
socket.on("error", () => upstream.destroy());
|
|
3433
|
+
}
|
|
3434
|
+
/** Return the sandbox address of a direct connection from a sandbox. */
|
|
3435
|
+
function directSource(socket) {
|
|
3436
|
+
return (socket.remoteAddress ?? "").replace(/^::ffff:/, "");
|
|
3437
|
+
}
|
|
3438
|
+
/**
|
|
3439
|
+
* Return the sandbox address of a relay connection. The client certificate
|
|
3440
|
+
* names the sandbox's container id.
|
|
3441
|
+
*/
|
|
3442
|
+
function relaySource(proxy, socket) {
|
|
3443
|
+
const egressId = socket.getPeerCertificate().subject?.CN;
|
|
3444
|
+
for (const [sourceIp, route] of proxy.routes) if (route.egressId === egressId) return sourceIp;
|
|
3445
|
+
return "";
|
|
3446
|
+
}
|
|
3447
|
+
async function handleConnection(proxy, server, connections, socket, sourceIp) {
|
|
3448
|
+
const route = proxy.routes.get(sourceIp);
|
|
3449
|
+
if (!route || !await ownsAddress(route, sourceIp)) {
|
|
3450
|
+
logWarn("sandbox.egress.docker.unknown_source", { "client.address": socket.remoteAddress ?? "" });
|
|
3451
|
+
socket.destroy();
|
|
3452
|
+
return;
|
|
3453
|
+
}
|
|
3454
|
+
const { data, host: rawHost, scheme } = await peek(socket);
|
|
3455
|
+
const host = rawHost?.toLowerCase();
|
|
3456
|
+
if (!host) {
|
|
3457
|
+
socket.destroy();
|
|
3458
|
+
return;
|
|
3459
|
+
}
|
|
3460
|
+
if (!interceptMode(route, host)) {
|
|
3461
|
+
const address = await publicAddress(host);
|
|
3462
|
+
if (!address) {
|
|
3463
|
+
logWarn("sandbox.egress.docker.pass_through_blocked", { "server.address": host });
|
|
3464
|
+
socket.destroy();
|
|
3465
|
+
return;
|
|
3466
|
+
}
|
|
3467
|
+
passThrough(socket, data, address, scheme === "https" ? 443 : 80);
|
|
3468
|
+
return;
|
|
3469
|
+
}
|
|
3470
|
+
const replayed = replay(socket, data);
|
|
3471
|
+
const target = scheme === "https" ? new tls.TLSSocket(replayed, {
|
|
3472
|
+
isServer: true,
|
|
3473
|
+
secureContext: secureContext(proxy, host),
|
|
3474
|
+
ALPNProtocols: ["http/1.1"]
|
|
3475
|
+
}) : replayed;
|
|
3476
|
+
connections.set(target, {
|
|
3477
|
+
sourceIp,
|
|
3478
|
+
host,
|
|
3479
|
+
scheme
|
|
3480
|
+
});
|
|
3481
|
+
target.on("error", () => socket.destroy());
|
|
3482
|
+
server.emit("connection", target);
|
|
3483
|
+
}
|
|
3484
|
+
async function startProxy() {
|
|
3485
|
+
const proxy = {
|
|
3486
|
+
port: 0,
|
|
3487
|
+
ca: await loadEgressCa(dockerSandboxDir()),
|
|
3488
|
+
leafKey: createLeafKey(),
|
|
3489
|
+
contexts: /* @__PURE__ */ new Map(),
|
|
3490
|
+
routes: /* @__PURE__ */ new Map()
|
|
3491
|
+
};
|
|
3492
|
+
const connections = /* @__PURE__ */ new WeakMap();
|
|
3493
|
+
const server = http.createServer((req, res) => {
|
|
3494
|
+
const connection = connections.get(req.socket);
|
|
3495
|
+
if (!connection) return void res.writeHead(500).end();
|
|
3496
|
+
handleRequest(proxy, connection, req, res).catch((error) => {
|
|
3497
|
+
logWarn("sandbox.egress.docker.request_failed", { "error.message": error instanceof Error ? error.message : String(error) });
|
|
3498
|
+
if (!res.headersSent) res.writeHead(502);
|
|
3499
|
+
res.end();
|
|
3500
|
+
});
|
|
3501
|
+
});
|
|
3502
|
+
const handle = (socket, sourceIp) => handleConnection(proxy, server, connections, socket, sourceIp).catch(() => socket.destroy());
|
|
3503
|
+
const listener = usesEgressRelay() ? tls.createServer({
|
|
3504
|
+
key: proxy.leafKey.export({
|
|
3505
|
+
type: "pkcs8",
|
|
3506
|
+
format: "pem"
|
|
3507
|
+
}),
|
|
3508
|
+
cert: issueLeafCertificate(proxy.ca, RELAY_PROXY_HOST, proxy.leafKey),
|
|
3509
|
+
ca: proxy.ca.certPem,
|
|
3510
|
+
requestCert: true,
|
|
3511
|
+
rejectUnauthorized: true
|
|
3512
|
+
}, (socket) => void handle(socket, relaySource(proxy, socket))) : net.createServer((socket) => void handle(socket, directSource(socket)));
|
|
3513
|
+
await new Promise((resolve, reject) => {
|
|
3514
|
+
listener.once("error", reject);
|
|
3515
|
+
listener.listen(0, "0.0.0.0", () => resolve());
|
|
3516
|
+
});
|
|
3517
|
+
listener.unref();
|
|
3518
|
+
proxy.port = listener.address().port;
|
|
3519
|
+
return proxy;
|
|
3520
|
+
}
|
|
3521
|
+
function getProxy() {
|
|
3522
|
+
proxyPromise ??= startProxy().catch((error) => {
|
|
3523
|
+
proxyPromise = void 0;
|
|
3524
|
+
throw error;
|
|
3525
|
+
});
|
|
3526
|
+
return proxyPromise;
|
|
3527
|
+
}
|
|
3528
|
+
function rulesScript(target) {
|
|
3529
|
+
const lines = [
|
|
3530
|
+
"set -eu",
|
|
3531
|
+
`iptables -t nat -N ${CHAIN} 2>/dev/null || iptables -t nat -F ${CHAIN}`,
|
|
3532
|
+
`iptables -t nat -C OUTPUT -j ${CHAIN} 2>/dev/null || iptables -t nat -A OUTPUT -j ${CHAIN}`,
|
|
3533
|
+
`iptables -t nat -C PREROUTING ! -i eth0 -j ${CHAIN} 2>/dev/null || iptables -t nat -A PREROUTING ! -i eth0 -j ${CHAIN}`
|
|
3534
|
+
];
|
|
3535
|
+
if (target) {
|
|
3536
|
+
for (const range of DIRECT_RANGES) lines.push(`iptables -t nat -A ${CHAIN} -d ${range} -j RETURN`);
|
|
3537
|
+
for (const port of [80, 443]) lines.push(`iptables -t nat -A ${CHAIN} -p tcp --dport ${port} -j DNAT --to-destination ${target}`);
|
|
3538
|
+
}
|
|
3539
|
+
return lines.join("\n");
|
|
3540
|
+
}
|
|
3541
|
+
function hasDomains(policy) {
|
|
3542
|
+
return Boolean(policy.credentialEgress?.domains.length || policy.traceHeaders?.domains.length);
|
|
3543
|
+
}
|
|
3544
|
+
/**
|
|
3545
|
+
* Apply one network policy to a sandbox container.
|
|
3546
|
+
*
|
|
3547
|
+
* A policy with credentialed or trace domains sends the container's web
|
|
3548
|
+
* traffic to this process's proxy. `allow-all` removes the redirect.
|
|
3549
|
+
*/
|
|
3550
|
+
async function applyEgressPolicy(container, policy) {
|
|
3551
|
+
let target;
|
|
3552
|
+
if (policy !== "allow-all" && hasDomains(policy)) {
|
|
3553
|
+
const proxy = await getProxy();
|
|
3554
|
+
proxy.routes.set(container.ip, {
|
|
3555
|
+
egressId: container.id,
|
|
3556
|
+
name: container.name,
|
|
3557
|
+
policy
|
|
3558
|
+
});
|
|
3559
|
+
target = usesEgressRelay() ? await ensureEgressRelay(container, proxy.ca, proxy.port) : `${container.gateway}:${proxy.port}`;
|
|
3560
|
+
} else if (proxyPromise) (await proxyPromise).routes.delete(container.ip);
|
|
3561
|
+
const result = await runRawExec(container.id, {
|
|
3562
|
+
cmd: [
|
|
3563
|
+
"sh",
|
|
3564
|
+
"-c",
|
|
3565
|
+
rulesScript(target)
|
|
3566
|
+
],
|
|
3567
|
+
root: true
|
|
3568
|
+
});
|
|
3569
|
+
if (result.exitCode !== 0) throw new Error(`Could not apply the sandbox network policy: ${result.stderr.trim()}`);
|
|
3570
|
+
}
|
|
3571
|
+
// src/chat/sandbox/docker/errors.ts
|
|
3572
|
+
function apiError(error, match) {
|
|
3573
|
+
return findInErrorChain(error, (candidate) => candidate instanceof DockerApiError && match(candidate));
|
|
3574
|
+
}
|
|
3575
|
+
function isMissingContainer(candidate) {
|
|
3576
|
+
return candidate.statusCode === 404 && /no such container/i.test(candidate.message) || candidate.statusCode === 409 && /marked for removal|removal .*in progress/i.test(candidate.message);
|
|
3577
|
+
}
|
|
3578
|
+
function isUnavailable$1(error) {
|
|
3579
|
+
return apiError(error, (candidate) => isMissingContainer(candidate) || candidate.statusCode === 409 && /is not running|is paused|restarting/i.test(candidate.message));
|
|
3580
|
+
}
|
|
3581
|
+
function isMissing$1(error) {
|
|
3582
|
+
return apiError(error, isMissingContainer);
|
|
3583
|
+
}
|
|
3584
|
+
function isSnapshotMissing$1(error) {
|
|
3585
|
+
return apiError(error, (candidate) => candidate.statusCode === 404 && /no such image/i.test(candidate.message));
|
|
3586
|
+
}
|
|
3587
|
+
function isTransient$1(error) {
|
|
3588
|
+
return findInErrorChain(error, (candidate) => {
|
|
3589
|
+
const code = candidate?.code;
|
|
3590
|
+
return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE";
|
|
3591
|
+
});
|
|
3592
|
+
}
|
|
3593
|
+
/** Map Docker Engine API errors to the shared sandbox error cases. */
|
|
3594
|
+
const dockerSandboxErrors = {
|
|
3595
|
+
isUnavailable: isUnavailable$1,
|
|
3596
|
+
isMissing: isMissing$1,
|
|
3597
|
+
isSnapshotMissing: isSnapshotMissing$1,
|
|
3598
|
+
isSnapshotting: () => false,
|
|
3599
|
+
isTransient: isTransient$1,
|
|
3600
|
+
isCommandStreamInterrupted: () => false
|
|
3601
|
+
};
|
|
3602
|
+
// src/chat/sandbox/docker/session.ts
|
|
3603
|
+
/** Image repository for every snapshot that this provider captures. */
|
|
3604
|
+
const SNAPSHOT_REPOSITORY = "junior-sandbox-snapshot";
|
|
3605
|
+
/** Go's `os.ModeDir` bit in Docker's path stat header. */
|
|
3606
|
+
const MODE_DIR = 2 ** 31;
|
|
3607
|
+
function absolute(filePath, cwd) {
|
|
3608
|
+
return path.posix.resolve(cwd ?? "/vercel/sandbox", filePath);
|
|
3609
|
+
}
|
|
3610
|
+
function notFound(filePath) {
|
|
3611
|
+
return Object.assign(/* @__PURE__ */ new Error(`ENOENT: no such file or directory, '${filePath}'`), { code: "ENOENT" });
|
|
3612
|
+
}
|
|
3613
|
+
async function readFile(id, filePath, signal) {
|
|
3614
|
+
try {
|
|
3615
|
+
return unpackFirstFile(await dockerRequest({
|
|
3616
|
+
path: `/containers/${id}/archive`,
|
|
3617
|
+
query: { path: filePath },
|
|
3618
|
+
signal
|
|
3619
|
+
}));
|
|
3620
|
+
} catch (error) {
|
|
3621
|
+
if (error instanceof DockerApiError && error.statusCode === 404) return null;
|
|
3622
|
+
throw error;
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
async function writeFiles(id, files, signal) {
|
|
3626
|
+
const entries = files.map((file) => ({
|
|
3627
|
+
path: absolute(file.path),
|
|
3628
|
+
content: typeof file.content === "string" ? Buffer.from(file.content) : file.content,
|
|
3629
|
+
mode: file.mode ?? 420
|
|
3630
|
+
}));
|
|
3631
|
+
await runRawExec(id, { cmd: [
|
|
3632
|
+
"mkdir",
|
|
3633
|
+
"-p",
|
|
3634
|
+
...[...new Set(entries.map((entry) => path.posix.dirname(entry.path)))]
|
|
3635
|
+
] }, signal);
|
|
3636
|
+
await dockerRequest({
|
|
3637
|
+
method: "PUT",
|
|
3638
|
+
path: `/containers/${id}/archive`,
|
|
3639
|
+
query: { path: "/" },
|
|
3640
|
+
body: packTar(entries.map((entry) => ({
|
|
3641
|
+
...entry,
|
|
3642
|
+
path: entry.path.replace(/^\/+/, ""),
|
|
3643
|
+
uid: SANDBOX_FILE_OWNER.uid,
|
|
3644
|
+
gid: SANDBOX_FILE_OWNER.gid
|
|
3645
|
+
}))),
|
|
3646
|
+
signal
|
|
3647
|
+
});
|
|
3648
|
+
}
|
|
3649
|
+
async function statMode(id, filePath, signal) {
|
|
3650
|
+
const response = await dockerStream({
|
|
3651
|
+
method: "HEAD",
|
|
3652
|
+
path: `/containers/${id}/archive`,
|
|
3653
|
+
query: { path: filePath },
|
|
3654
|
+
signal
|
|
3655
|
+
});
|
|
3656
|
+
response.resume();
|
|
3657
|
+
if (response.statusCode === 404) return null;
|
|
3658
|
+
const header = response.headers["x-docker-container-path-stat"];
|
|
3659
|
+
if ((response.statusCode ?? 0) >= 400 || typeof header !== "string") throw new DockerApiError(response.statusCode ?? 0, `stat ${filePath} failed`);
|
|
3660
|
+
return JSON.parse(Buffer.from(header, "base64").toString("utf8")).mode;
|
|
3661
|
+
}
|
|
3662
|
+
function fileSystem(id) {
|
|
3663
|
+
return {
|
|
3664
|
+
async readFile(filePath, options) {
|
|
3665
|
+
const target = absolute(filePath);
|
|
3666
|
+
const content = await readFile(id, target, options.signal);
|
|
3667
|
+
if (!content) throw notFound(target);
|
|
3668
|
+
return content.toString(options.encoding);
|
|
3669
|
+
},
|
|
3670
|
+
async writeFile(filePath, content, options) {
|
|
3671
|
+
await writeFiles(id, [{
|
|
3672
|
+
path: filePath,
|
|
3673
|
+
content: Buffer.from(content, options?.encoding ?? "utf8")
|
|
3674
|
+
}], options?.signal);
|
|
3675
|
+
},
|
|
3676
|
+
async readdir(filePath, options) {
|
|
3677
|
+
const target = absolute(filePath);
|
|
3678
|
+
const result = await runRawExec(id, { cmd: [
|
|
3679
|
+
"find",
|
|
3680
|
+
target,
|
|
3681
|
+
"-mindepth",
|
|
3682
|
+
"1",
|
|
3683
|
+
"-maxdepth",
|
|
3684
|
+
"1",
|
|
3685
|
+
"-printf",
|
|
3686
|
+
"%f\\0"
|
|
3687
|
+
] }, options?.signal);
|
|
3688
|
+
if (result.exitCode !== 0) throw notFound(target);
|
|
3689
|
+
return result.stdout.split("\0").filter(Boolean);
|
|
3690
|
+
},
|
|
3691
|
+
async stat(filePath, options) {
|
|
3692
|
+
const target = absolute(filePath);
|
|
3693
|
+
const mode = await statMode(id, target, options?.signal);
|
|
3694
|
+
if (mode === null) throw notFound(target);
|
|
3695
|
+
return { isDirectory: () => mode >= MODE_DIR };
|
|
3696
|
+
}
|
|
3697
|
+
};
|
|
3698
|
+
}
|
|
3699
|
+
/** Commit the container to a local image and return the image id. */
|
|
3700
|
+
async function commitSnapshot(id, tag, signal) {
|
|
3701
|
+
return (await dockerJson({
|
|
3702
|
+
method: "POST",
|
|
3703
|
+
path: "/commit",
|
|
3704
|
+
query: {
|
|
3705
|
+
container: id,
|
|
3706
|
+
repo: SNAPSHOT_REPOSITORY,
|
|
3707
|
+
tag,
|
|
3708
|
+
changes: `LABEL ${DOCKER_SANDBOX_LABEL}=snapshot`
|
|
3709
|
+
},
|
|
3710
|
+
signal
|
|
3711
|
+
})).Id;
|
|
3712
|
+
}
|
|
3713
|
+
/** Junior's sandbox session contract for one running sandbox container. */
|
|
3714
|
+
function adaptSession$1(container, options) {
|
|
3715
|
+
const { id } = container;
|
|
3716
|
+
const run = async (operation) => {
|
|
3717
|
+
options?.scopeSignal?.throwIfAborted();
|
|
3718
|
+
try {
|
|
3719
|
+
return await operation();
|
|
3720
|
+
} catch (error) {
|
|
3721
|
+
if (dockerSandboxErrors.isUnavailable(error)) options?.onUnavailable?.(id);
|
|
3722
|
+
throw error;
|
|
3723
|
+
}
|
|
3724
|
+
};
|
|
3725
|
+
const fs = fileSystem(id);
|
|
3726
|
+
return {
|
|
3727
|
+
sandboxId: container.name,
|
|
3728
|
+
sessionId: id,
|
|
3729
|
+
keepsFilesAcrossSessions: false,
|
|
3730
|
+
startedAtMs: container.startedAtMs,
|
|
3731
|
+
fs: {
|
|
3732
|
+
readFile: (filePath, readOptions) => run(() => fs.readFile(filePath, readOptions)),
|
|
3733
|
+
writeFile: (filePath, content, writeOptions) => run(() => fs.writeFile(filePath, content, writeOptions)),
|
|
3734
|
+
readdir: (filePath, readOptions) => run(() => fs.readdir(filePath, readOptions)),
|
|
3735
|
+
stat: (filePath, statOptions) => run(() => fs.stat(filePath, statOptions))
|
|
3736
|
+
},
|
|
3737
|
+
extendTimeout: (duration) => run(() => extendDeadline(id, duration)),
|
|
3738
|
+
mkDir: (dirPath) => run(async () => {
|
|
3739
|
+
const target = absolute(dirPath);
|
|
3740
|
+
const result = await runRawExec(id, { cmd: ["mkdir", target] });
|
|
3741
|
+
if (result.exitCode !== 0) throw new Error(`mkdir ${target} failed: ${result.stderr.trim()}`);
|
|
3742
|
+
}),
|
|
3743
|
+
readFileToBuffer: (input) => run(() => readFile(id, absolute(input.path, input.cwd))),
|
|
3744
|
+
runCommand: (input) => run(() => runSandboxCommand(id, {
|
|
3745
|
+
...input,
|
|
3746
|
+
cwd: input.cwd ?? "/vercel/sandbox",
|
|
3747
|
+
signal: input.signal ?? options?.scopeSignal
|
|
3748
|
+
})),
|
|
3749
|
+
snapshot: (snapshotOptions) => run(async () => ({ snapshotId: await commitSnapshot(id, container.name, snapshotOptions?.signal) })),
|
|
3750
|
+
stop: () => run(() => stopContainer(container)),
|
|
3751
|
+
update: (params) => run(async () => {
|
|
3752
|
+
if (params.networkPolicy) await applyEgressPolicy(container, params.networkPolicy);
|
|
3753
|
+
}),
|
|
3754
|
+
writeFiles: (files) => run(() => writeFiles(id, files))
|
|
3755
|
+
};
|
|
3756
|
+
}
|
|
3757
|
+
// src/chat/sandbox/docker/provider.ts
|
|
3758
|
+
/** Create a sandbox container and return a session for it. */
|
|
3759
|
+
async function createSession(input) {
|
|
3760
|
+
const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node24", input.signal);
|
|
3761
|
+
const container = await createContainer({
|
|
3762
|
+
name: input.name ?? newSandboxName(),
|
|
3763
|
+
image,
|
|
3764
|
+
timeoutMs: input.timeoutMs,
|
|
3765
|
+
persistent: input.persistent ?? false,
|
|
3766
|
+
vcpus: input.resources?.vcpus,
|
|
3767
|
+
signal: input.signal
|
|
3768
|
+
}, await egressCaPem());
|
|
3769
|
+
try {
|
|
3770
|
+
if (input.networkPolicy) await applyEgressPolicy(container, input.networkPolicy);
|
|
3771
|
+
} catch (error) {
|
|
3772
|
+
await removeContainer(container.name).catch(() => void 0);
|
|
3773
|
+
throw error;
|
|
3774
|
+
}
|
|
3775
|
+
return adaptSession$1(container, input);
|
|
3776
|
+
}
|
|
3777
|
+
/** Return a session for a named sandbox container. Start it if it stopped. */
|
|
3778
|
+
async function getSession(input) {
|
|
3779
|
+
return adaptSession$1(await getContainer(input.name, await egressCaPem(), input.scopeSignal), input);
|
|
3780
|
+
}
|
|
3781
|
+
/** Create the persistent container that runs one Workspace snapshot build. */
|
|
3782
|
+
async function createWorkspaceSnapshotBuilder$1(input) {
|
|
3783
|
+
await createContainer({
|
|
3784
|
+
name: input.name,
|
|
3785
|
+
image: await ensureRuntimeImage(input.runtime, input.signal),
|
|
3786
|
+
timeoutMs: input.timeoutMs,
|
|
3787
|
+
persistent: true,
|
|
3788
|
+
vcpus: input.resources?.vcpus,
|
|
3789
|
+
signal: input.signal
|
|
3790
|
+
}, await egressCaPem());
|
|
3791
|
+
}
|
|
3792
|
+
/**
|
|
3793
|
+
* Return the container that runs one Workspace snapshot build.
|
|
3794
|
+
*
|
|
3795
|
+
* A Docker snapshot is an image that does not depend on its builder. So
|
|
3796
|
+
* `snapshot()` removes the builder right after the commit, and the image tag
|
|
3797
|
+
* keeps the builder's name. Deleting the builder later removes that tag.
|
|
3798
|
+
*/
|
|
3799
|
+
async function getWorkspaceSnapshotBuilder$1(name, signal) {
|
|
3800
|
+
const container = await getContainer(name, await egressCaPem(), signal);
|
|
3801
|
+
return {
|
|
3802
|
+
session: () => adaptSession$1(container),
|
|
3803
|
+
startDetachedCommand: (input) => startDetachedCommand(container.id, input),
|
|
3804
|
+
async getCommand(commandId) {
|
|
3805
|
+
return { wait: ({ signal: waitSignal }) => waitForDetachedCommand(container.id, commandId, waitSignal) };
|
|
3806
|
+
},
|
|
3807
|
+
async snapshot(options) {
|
|
3808
|
+
const snapshotId = await commitSnapshot(container.id, name, options?.signal);
|
|
3809
|
+
await removeContainer(name);
|
|
3810
|
+
return { snapshotId };
|
|
3811
|
+
}
|
|
3812
|
+
};
|
|
3813
|
+
}
|
|
3814
|
+
async function deleteSnapshotTag(name) {
|
|
3815
|
+
try {
|
|
3816
|
+
await dockerRequest({
|
|
3817
|
+
method: "DELETE",
|
|
3818
|
+
path: `/images/${encodeURIComponent(`${SNAPSHOT_REPOSITORY}:${name}`)}`,
|
|
3819
|
+
query: { force: true }
|
|
3820
|
+
});
|
|
3821
|
+
} catch (error) {
|
|
3822
|
+
if (!(error instanceof DockerApiError && error.statusCode === 404)) throw error;
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
/**
|
|
3826
|
+
* Remove Workspace builders and the snapshot images tagged with their names.
|
|
3827
|
+
*
|
|
3828
|
+
* Shared snapshot code calls this when a Workspace snapshot is no longer
|
|
3829
|
+
* used. Each name is tried, and the first failure is thrown at the end.
|
|
3830
|
+
*/
|
|
3831
|
+
async function deleteWorkspaceSnapshotBuilders$1(names) {
|
|
3832
|
+
const failures = [];
|
|
3833
|
+
const removeAll = async (name) => {
|
|
3834
|
+
for (const remove of [removeContainer, deleteSnapshotTag]) try {
|
|
3835
|
+
await remove(name);
|
|
3836
|
+
} catch (error) {
|
|
3837
|
+
failures.push(error);
|
|
3838
|
+
}
|
|
3839
|
+
};
|
|
3840
|
+
await mapBounded([...new Set(names)], (name) => removeAll(name));
|
|
3841
|
+
if (failures.length > 0) throw failures[0];
|
|
3842
|
+
}
|
|
3843
|
+
const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
|
|
3844
|
+
"spal-release",
|
|
3845
|
+
"ripgrep",
|
|
3846
|
+
"gh",
|
|
3847
|
+
"jq"
|
|
3848
|
+
]);
|
|
3849
|
+
/**
|
|
3850
|
+
* Keep only the small Docker base from the declared runtime dependencies.
|
|
3851
|
+
*
|
|
3852
|
+
* Postinstall commands are skipped, because they often download large tools.
|
|
3853
|
+
* A base package that no plugin declares is not installed.
|
|
3854
|
+
*/
|
|
3855
|
+
function selectSnapshotRuntime(runtime) {
|
|
3856
|
+
return {
|
|
3857
|
+
dependencies: runtime.dependencies.filter((dependency) => "package" in dependency && DOCKER_SNAPSHOT_PACKAGES.has(dependency.package)),
|
|
3858
|
+
postinstall: []
|
|
3859
|
+
};
|
|
3860
|
+
}
|
|
3861
|
+
/** Local Docker implementation of the sandbox provider contract. */
|
|
3862
|
+
const dockerSandboxProvider = {
|
|
3863
|
+
errors: dockerSandboxErrors,
|
|
3864
|
+
createSession,
|
|
3865
|
+
getSession,
|
|
3866
|
+
createWorkspaceSnapshotBuilder: createWorkspaceSnapshotBuilder$1,
|
|
3867
|
+
getWorkspaceSnapshotBuilder: getWorkspaceSnapshotBuilder$1,
|
|
3868
|
+
deleteWorkspaceSnapshotBuilders: deleteWorkspaceSnapshotBuilders$1,
|
|
3869
|
+
selectSnapshotRuntime
|
|
3870
|
+
};
|
|
3871
|
+
// src/chat/sandbox/vercel/credentials.ts
|
|
3872
|
+
/**
|
|
3873
|
+
* Resolve explicit Vercel Sandbox credentials, or return undefined to let
|
|
3874
|
+
* the SDK read ambient Vercel auth from its own environment detection.
|
|
3875
|
+
*/
|
|
3876
|
+
function getVercelSandboxCredentials() {
|
|
3877
|
+
const { token, teamId, projectId } = getChatConfig().sandbox.vercel;
|
|
3878
|
+
if (token && teamId && projectId) return {
|
|
3879
|
+
token,
|
|
3880
|
+
teamId,
|
|
3881
|
+
projectId
|
|
3882
|
+
};
|
|
3883
|
+
}
|
|
3884
|
+
// src/chat/sandbox/egress/oidc.ts
|
|
3885
|
+
const OIDC_DISCOVERY_CACHE_TTL_MS = 36e5;
|
|
3886
|
+
const OIDC_DISCOVERY_CACHE_MAX_ENTRIES = 8;
|
|
3887
|
+
const jwksByIssuer = /* @__PURE__ */ new Map();
|
|
3888
|
+
function buildDiscoveryUrl(issuer) {
|
|
3889
|
+
const url = new URL(issuer);
|
|
3890
|
+
if (url.protocol !== "https:" || url.hostname !== "oidc.vercel.com") throw new Error("Unexpected Vercel OIDC issuer");
|
|
3891
|
+
url.pathname = `${url.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
3892
|
+
url.search = "";
|
|
3893
|
+
url.hash = "";
|
|
3894
|
+
return url;
|
|
3895
|
+
}
|
|
3896
|
+
function buildJwksUrl(value) {
|
|
3897
|
+
const url = new URL(value);
|
|
3898
|
+
if (url.protocol !== "https:") throw new Error("Vercel OIDC discovery jwks_uri must use HTTPS");
|
|
3899
|
+
return url;
|
|
3900
|
+
}
|
|
3901
|
+
async function getJwks(issuer) {
|
|
3902
|
+
const now = Date.now();
|
|
3903
|
+
const cached = jwksByIssuer.get(issuer);
|
|
3904
|
+
if (cached && cached.expiresAtMs > now) return cached.jwks;
|
|
3905
|
+
if (cached) jwksByIssuer.delete(issuer);
|
|
3906
|
+
const response = await fetch(buildDiscoveryUrl(issuer), { redirect: "error" });
|
|
3907
|
+
if (!response.ok) throw new Error("Unable to load Vercel OIDC discovery metadata");
|
|
3908
|
+
const config = await response.json();
|
|
3909
|
+
if (!config.jwks_uri) throw new Error("Vercel OIDC discovery metadata did not include jwks_uri");
|
|
3910
|
+
const jwks = createRemoteJWKSet(buildJwksUrl(config.jwks_uri));
|
|
3911
|
+
if (!jwksByIssuer.has(issuer) && jwksByIssuer.size >= OIDC_DISCOVERY_CACHE_MAX_ENTRIES) {
|
|
3912
|
+
const oldestIssuer = jwksByIssuer.keys().next().value;
|
|
3913
|
+
if (oldestIssuer) jwksByIssuer.delete(oldestIssuer);
|
|
3914
|
+
}
|
|
3915
|
+
jwksByIssuer.set(issuer, {
|
|
3916
|
+
jwks,
|
|
3917
|
+
expiresAtMs: now + OIDC_DISCOVERY_CACHE_TTL_MS
|
|
3918
|
+
});
|
|
3919
|
+
return jwks;
|
|
3920
|
+
}
|
|
3921
|
+
/**
|
|
3922
|
+
* Verify Vercel signed this Sandbox firewall proxy request for the active VM session.
|
|
3923
|
+
*
|
|
3924
|
+
* `currentDate` is the time for the `exp` and `nbf` checks. It defaults to
|
|
3925
|
+
* now. Evals pass the real time because they replace `Date`.
|
|
3926
|
+
*/
|
|
3927
|
+
async function verifyVercelSandboxOidcToken(token, options = {}) {
|
|
3928
|
+
const unverified = decodeJwt(token);
|
|
3929
|
+
if (typeof unverified.iss !== "string") throw new Error("Vercel OIDC token did not include an issuer");
|
|
3930
|
+
const jwks = await getJwks(unverified.iss);
|
|
3931
|
+
return (await jwtVerify(token, jwks, {
|
|
3932
|
+
issuer: unverified.iss,
|
|
3933
|
+
...options.currentDate ? { currentDate: options.currentDate } : void 0
|
|
3934
|
+
})).payload;
|
|
3935
|
+
}
|
|
3936
|
+
// src/chat/sandbox/egress/vercel.ts
|
|
3937
|
+
const OIDC_TOKEN_HEADER = "vercel-sandbox-oidc-token";
|
|
3938
|
+
const FORWARDED_HOST_HEADER = "vercel-forwarded-host";
|
|
3939
|
+
const FORWARDED_SCHEME_HEADER = "vercel-forwarded-scheme";
|
|
3940
|
+
const FORWARDED_PORT_HEADER = "vercel-forwarded-port";
|
|
3941
|
+
const FORWARDED_PATH_HEADER = "vercel-forwarded-path";
|
|
3942
|
+
function jsonError(message, status) {
|
|
3943
|
+
return Response.json({ error: message }, { status });
|
|
3944
|
+
}
|
|
3945
|
+
function forwardUrl(credentialToken) {
|
|
3946
|
+
const baseUrl = getChatConfig().deployment.baseUrl;
|
|
3947
|
+
if (!baseUrl) throw new Error("Cannot determine base URL for sandbox credential egress (set JUNIOR_BASE_URL or deploy to Vercel)");
|
|
3948
|
+
return new URL(`${SANDBOX_EGRESS_PROXY_PATH}/${credentialToken}`, baseUrl).toString();
|
|
3949
|
+
}
|
|
3950
|
+
/**
|
|
3951
|
+
* Turn Junior's network policy into Vercel Sandbox network rules.
|
|
3952
|
+
*
|
|
3953
|
+
* Every other domain stays open through the `*` rule. Credentialed domains
|
|
3954
|
+
* forward to Junior's egress route, and trace domains get a header transform.
|
|
3955
|
+
*/
|
|
3956
|
+
function toVercelNetworkPolicy(policy) {
|
|
3957
|
+
if (policy === "allow-all") return policy;
|
|
3958
|
+
const rules = /* @__PURE__ */ new Map();
|
|
3959
|
+
const credentialEgress = policy.credentialEgress;
|
|
3960
|
+
if (credentialEgress && credentialEgress.domains.length > 0) {
|
|
3961
|
+
const forwardURL = forwardUrl(credentialEgress.credentialToken);
|
|
3962
|
+
for (const domain of credentialEgress.domains) rules.set(domain, [{ forwardURL }]);
|
|
3963
|
+
}
|
|
3964
|
+
const traceHeaders = policy.traceHeaders;
|
|
3965
|
+
if (traceHeaders) for (const domain of traceHeaders.domains) rules.set(domain, [{ transform: [{ headers: traceHeaders.headers }] }]);
|
|
3966
|
+
return { allow: {
|
|
3967
|
+
"*": [],
|
|
3968
|
+
...Object.fromEntries([...rules.entries()].sort(([left], [right]) => left.localeCompare(right)))
|
|
3969
|
+
} };
|
|
3970
|
+
}
|
|
3971
|
+
/** Read the signed credential token from the forward URL path. */
|
|
3972
|
+
function credentialTokenFromRequest(request) {
|
|
3973
|
+
const pathname = new URL(request.url).pathname;
|
|
3974
|
+
const prefix = `${SANDBOX_EGRESS_PROXY_PATH}/`;
|
|
3975
|
+
if (!pathname.startsWith(prefix)) return;
|
|
3976
|
+
const token = pathname.slice(prefix.length).split("/")[0];
|
|
3977
|
+
if (!token) return;
|
|
3978
|
+
try {
|
|
3979
|
+
return decodeURIComponent(token);
|
|
3980
|
+
} catch {
|
|
3981
|
+
return;
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
function normalizeHost(value) {
|
|
3985
|
+
const trimmed = value.trim().toLowerCase();
|
|
3986
|
+
if (!trimmed || trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes(":")) return;
|
|
3987
|
+
return trimmed.replace(/\.$/, "");
|
|
3988
|
+
}
|
|
3989
|
+
function normalizeScheme(value) {
|
|
3990
|
+
return value.trim().toLowerCase() === "https" ? "https" : void 0;
|
|
3991
|
+
}
|
|
3992
|
+
function normalizePort(value) {
|
|
3993
|
+
if (!value) return;
|
|
3994
|
+
const trimmed = value.trim();
|
|
3995
|
+
if (!/^\d{1,5}$/.test(trimmed)) return;
|
|
3996
|
+
const port = Number.parseInt(trimmed, 10);
|
|
3997
|
+
return port >= 1 && port <= 65535 ? trimmed : void 0;
|
|
3998
|
+
}
|
|
3999
|
+
function sandboxIdFromPayload(payload) {
|
|
4000
|
+
return typeof payload["sandbox_id"] === "string" ? payload["sandbox_id"] : void 0;
|
|
4001
|
+
}
|
|
4002
|
+
function normalizedForwardedPath(path) {
|
|
4003
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("#") || /[\r\n]/.test(path)) return {
|
|
4004
|
+
ok: false,
|
|
4005
|
+
error: "Invalid forwarded path"
|
|
4006
|
+
};
|
|
4007
|
+
try {
|
|
4008
|
+
const url = new URL(path, "https://sandbox-forwarded.local");
|
|
4009
|
+
return {
|
|
4010
|
+
ok: true,
|
|
4011
|
+
path: `${url.pathname}${url.search}`
|
|
4012
|
+
};
|
|
4013
|
+
} catch {
|
|
4014
|
+
return {
|
|
4015
|
+
ok: false,
|
|
4016
|
+
error: "Invalid forwarded path"
|
|
4017
|
+
};
|
|
4018
|
+
}
|
|
4019
|
+
}
|
|
4020
|
+
function upstreamPath(request) {
|
|
4021
|
+
const forwardedPath = request.headers.get(FORWARDED_PATH_HEADER);
|
|
4022
|
+
if (!forwardedPath?.trim()) return {
|
|
4023
|
+
ok: false,
|
|
4024
|
+
error: "Missing forwarded path"
|
|
4025
|
+
};
|
|
4026
|
+
return normalizedForwardedPath(forwardedPath.trim());
|
|
4027
|
+
}
|
|
4028
|
+
/**
|
|
4029
|
+
* Rebuild the HTTPS upstream URL from Vercel forwarding headers.
|
|
4030
|
+
*
|
|
4031
|
+
* This is the proxy's wire-format boundary for forwarded requests: host, path,
|
|
4032
|
+
* scheme, and port must normalize before the request can reach provider egress.
|
|
4033
|
+
*/
|
|
4034
|
+
function buildUpstreamUrl(request) {
|
|
4035
|
+
const forwardedHost = request.headers.get(FORWARDED_HOST_HEADER);
|
|
4036
|
+
if (!forwardedHost?.trim()) return {
|
|
4037
|
+
ok: false,
|
|
4038
|
+
error: "Missing forwarded host"
|
|
4039
|
+
};
|
|
4040
|
+
const host = normalizeHost(forwardedHost);
|
|
4041
|
+
if (!host) return {
|
|
4042
|
+
ok: false,
|
|
4043
|
+
error: "Invalid forwarded host"
|
|
4044
|
+
};
|
|
4045
|
+
const forwardedScheme = request.headers.get(FORWARDED_SCHEME_HEADER);
|
|
4046
|
+
if (!forwardedScheme?.trim()) return {
|
|
4047
|
+
ok: false,
|
|
4048
|
+
error: "Missing forwarded scheme"
|
|
4049
|
+
};
|
|
4050
|
+
const scheme = normalizeScheme(forwardedScheme);
|
|
4051
|
+
if (!scheme) return {
|
|
4052
|
+
ok: false,
|
|
4053
|
+
error: "Forwarded scheme must be https"
|
|
4054
|
+
};
|
|
4055
|
+
const forwardedPort = request.headers.get(FORWARDED_PORT_HEADER);
|
|
4056
|
+
const port = normalizePort(forwardedPort);
|
|
4057
|
+
if (forwardedPort && !port) return {
|
|
4058
|
+
ok: false,
|
|
4059
|
+
error: "Invalid forwarded port"
|
|
4060
|
+
};
|
|
4061
|
+
const path = upstreamPath(request);
|
|
4062
|
+
if (!path.ok) return {
|
|
4063
|
+
ok: false,
|
|
4064
|
+
error: path.error
|
|
4065
|
+
};
|
|
4066
|
+
try {
|
|
4067
|
+
return {
|
|
4068
|
+
ok: true,
|
|
4069
|
+
url: new URL(`${scheme}://${host}${port ? `:${port}` : ""}${path.path}`)
|
|
4070
|
+
};
|
|
4071
|
+
} catch {
|
|
4072
|
+
return {
|
|
4073
|
+
ok: false,
|
|
4074
|
+
error: "Invalid forwarded URL"
|
|
4075
|
+
};
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
/**
|
|
4079
|
+
* Return whether a request carries the forwarding headers expected from Vercel.
|
|
4080
|
+
*
|
|
4081
|
+
* This is only a cheap classifier for routing into the proxy handler. Real
|
|
4082
|
+
* authentication happens in `proxyVercelSandboxEgressRequest`, which verifies
|
|
4083
|
+
* the OIDC token, and in `executeSandboxEgressRequest`, which verifies the
|
|
4084
|
+
* signed Junior credential context.
|
|
4085
|
+
*/
|
|
4086
|
+
function isVercelSandboxEgressRequest(request) {
|
|
4087
|
+
return Boolean(request.headers.get(OIDC_TOKEN_HEADER)?.trim() && request.headers.get(FORWARDED_HOST_HEADER)?.trim() && request.headers.get(FORWARDED_SCHEME_HEADER)?.trim());
|
|
4088
|
+
}
|
|
4089
|
+
/**
|
|
4090
|
+
* Handle one sandbox egress request that Vercel's network layer forwarded.
|
|
4091
|
+
*
|
|
4092
|
+
* This is the Vercel side of the proxy boundary. It rejects requests without a
|
|
4093
|
+
* valid Vercel Sandbox OIDC token and rejects invalid forwarded URLs. Then it
|
|
4094
|
+
* hands the verified VM id, upstream URL, and credential token to the shared
|
|
4095
|
+
* `executeSandboxEgressRequest`.
|
|
4096
|
+
*/
|
|
4097
|
+
async function proxyVercelSandboxEgressRequest(request, deps = {}) {
|
|
4098
|
+
const oidcToken = request.headers.get(OIDC_TOKEN_HEADER)?.trim();
|
|
4099
|
+
if (!oidcToken) return jsonError("Missing Vercel Sandbox OIDC token", 401);
|
|
4100
|
+
let oidcPayload;
|
|
4101
|
+
try {
|
|
4102
|
+
oidcPayload = await (deps.verifyOidc ?? verifyVercelSandboxOidcToken)(oidcToken);
|
|
4103
|
+
} catch (error) {
|
|
4104
|
+
logWarn("sandbox.egress.oidc_verification.failed", { "app.sandbox.oidc_error": error instanceof Error ? error.message : String(error) });
|
|
4105
|
+
return jsonError("Invalid Vercel Sandbox OIDC token", 401);
|
|
4106
|
+
}
|
|
4107
|
+
const activeEgressId = sandboxIdFromPayload(oidcPayload);
|
|
4108
|
+
if (!activeEgressId) {
|
|
4109
|
+
logWarn("sandbox.egress.oidc_session.missing", {
|
|
4110
|
+
"http.request.method": request.method,
|
|
4111
|
+
"url.path": redactSandboxEgressProxyPath(new URL(request.url).pathname)
|
|
4112
|
+
});
|
|
4113
|
+
return jsonError("Vercel Sandbox OIDC token did not include sandbox_id", 401);
|
|
4114
|
+
}
|
|
4115
|
+
const upstreamResult = buildUpstreamUrl(request);
|
|
4116
|
+
if (!upstreamResult.ok) {
|
|
4117
|
+
logWarn("sandbox.egress.upstream_url.invalid", {
|
|
4118
|
+
...sandboxEgressAttributes({
|
|
4119
|
+
egressId: activeEgressId,
|
|
4120
|
+
method: request.method,
|
|
4121
|
+
path: redactSandboxEgressProxyPath(new URL(request.url).pathname),
|
|
4122
|
+
status: 400
|
|
4123
|
+
}),
|
|
4124
|
+
...sandboxEgressRoutingAttributes(request)
|
|
4125
|
+
});
|
|
4126
|
+
return jsonError(upstreamResult.error, 400);
|
|
4127
|
+
}
|
|
4128
|
+
return await executeSandboxEgressRequest({
|
|
4129
|
+
request,
|
|
4130
|
+
egressId: activeEgressId,
|
|
4131
|
+
upstreamUrl: upstreamResult.url,
|
|
4132
|
+
credentialToken: credentialTokenFromRequest(request)
|
|
4133
|
+
}, deps);
|
|
4134
|
+
}
|
|
4135
|
+
// src/chat/sandbox/vercel/errors.ts
|
|
4136
|
+
const invalidTokenErrorSchema = z.object({ json: z.object({ invalidToken: z.literal(true) }) });
|
|
4137
|
+
const sessionForbiddenErrorSchema = z.object({ response: z.object({
|
|
4138
|
+
status: z.literal(403),
|
|
4139
|
+
url: z.string().includes("/sandboxes/sessions")
|
|
4140
|
+
}) });
|
|
4141
|
+
const serverErrorResponseSchema = z.object({ response: z.object({ status: z.number().min(500).lt(600) }) });
|
|
4142
|
+
function searchableText(error) {
|
|
4143
|
+
const details = getSandboxErrorDetails(error);
|
|
4144
|
+
return `${details.searchableText} ${details.summary}`.toLowerCase();
|
|
4145
|
+
}
|
|
4146
|
+
function isInvalidSandboxSessionError(error) {
|
|
4147
|
+
return invalidTokenErrorSchema.safeParse(error).success || sessionForbiddenErrorSchema.safeParse(error).success;
|
|
4148
|
+
}
|
|
4149
|
+
function isUnavailable(error) {
|
|
4150
|
+
return findInErrorChain(error, (candidate) => {
|
|
4151
|
+
if (isInvalidSandboxSessionError(candidate)) return true;
|
|
4152
|
+
const searchable = searchableText(candidate);
|
|
4153
|
+
return searchable.includes("sandbox_stopped") || searchable.includes("status=410") || searchable.includes("status code 410") || searchable.includes("no longer available") || searchable.includes("stream was closed and is not accepting commands");
|
|
4154
|
+
});
|
|
4155
|
+
}
|
|
4156
|
+
function isMissing(error) {
|
|
4157
|
+
return findInErrorChain(error, (candidate) => {
|
|
4158
|
+
const searchable = searchableText(candidate);
|
|
4159
|
+
return searchable.includes("status=404") || searchable.includes("status code 404") || searchable.includes("snapshot_not_found");
|
|
4160
|
+
});
|
|
4161
|
+
}
|
|
4162
|
+
function isSnapshotMissing(error) {
|
|
4163
|
+
const searchable = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
|
|
4164
|
+
return searchable.includes("snapshot") && (searchable.includes("not found") || searchable.includes("unknown") || searchable.includes("404"));
|
|
4165
|
+
}
|
|
4166
|
+
function isSnapshotting(error) {
|
|
4167
|
+
return findInErrorChain(error, (candidate) => {
|
|
4168
|
+
const searchable = searchableText(candidate);
|
|
4169
|
+
return searchable.includes("sandbox_snapshotting") || searchable.includes("creating a snapshot") || searchable.includes("stopped shortly");
|
|
4170
|
+
});
|
|
4171
|
+
}
|
|
4172
|
+
function isTransient(error) {
|
|
4173
|
+
return findInErrorChain(error, (candidate) => {
|
|
4174
|
+
const searchable = searchableText(candidate);
|
|
4175
|
+
if (searchable.includes("internal_server_error") || searchable.includes("status=500") || searchable.includes("status code 500") || searchable.includes("status=502") || searchable.includes("status code 502") || searchable.includes("status=503") || searchable.includes("status code 503") || searchable.includes("status=504") || searchable.includes("status code 504")) return true;
|
|
4176
|
+
return serverErrorResponseSchema.safeParse(candidate).success;
|
|
4177
|
+
});
|
|
4178
|
+
}
|
|
4179
|
+
const socketFailureCauseSchema = z.object({ code: z.enum(["ECONNRESET", "UND_ERR_SOCKET"]) });
|
|
4180
|
+
function isFetchSocketFailure(error) {
|
|
4181
|
+
return error.name === "TypeError" && (error.message === "terminated" || error.message === "fetch failed") && socketFailureCauseSchema.safeParse(error.cause).success;
|
|
4182
|
+
}
|
|
4183
|
+
function isCommandStreamInterrupted(error) {
|
|
4184
|
+
return findInErrorChain(error, (candidate) => {
|
|
4185
|
+
if (!(candidate instanceof Error)) return false;
|
|
4186
|
+
return candidate.name === "StreamError" && candidate.message.toLowerCase().includes("stream ended before command finished") || isFetchSocketFailure(candidate);
|
|
4187
|
+
});
|
|
4188
|
+
}
|
|
4189
|
+
/** Map Vercel Sandbox API and SDK errors to the shared sandbox error cases. */
|
|
4190
|
+
const vercelSandboxErrors = {
|
|
4191
|
+
isUnavailable,
|
|
4192
|
+
isMissing,
|
|
4193
|
+
isSnapshotMissing,
|
|
4194
|
+
isSnapshotting,
|
|
4195
|
+
isTransient,
|
|
4196
|
+
isCommandStreamInterrupted
|
|
4197
|
+
};
|
|
4198
|
+
// src/chat/sandbox/vercel/provider.ts
|
|
4199
|
+
/**
|
|
4200
|
+
* Sandbox client options. Since 4.0, a client without `fetch` uses the SDK's
|
|
4201
|
+
* own undici `fetch` and skips process-level `fetch` replacements, such as the
|
|
4202
|
+
* eval proxy. So every request reads `globalThis.fetch` when it starts, and
|
|
4203
|
+
* the scope signal, when there is one, can abort it.
|
|
4204
|
+
*/
|
|
4205
|
+
function clientOptions(signal) {
|
|
4206
|
+
const fetch = (input, init) => {
|
|
4207
|
+
if (!signal) return globalThis.fetch(input, init);
|
|
4208
|
+
const requestSignal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
|
|
4209
|
+
return globalThis.fetch(input, {
|
|
4210
|
+
...init,
|
|
4211
|
+
signal: requestSignal ? AbortSignal.any([requestSignal, signal]) : signal
|
|
4212
|
+
});
|
|
4213
|
+
};
|
|
4214
|
+
return {
|
|
4215
|
+
...getVercelSandboxCredentials(),
|
|
4216
|
+
fetch
|
|
4217
|
+
};
|
|
4218
|
+
}
|
|
4219
|
+
/** Pin Junior's sandbox contract to one Vercel session without SDK replay. */
|
|
4220
|
+
function adaptSession(sandbox, options) {
|
|
4221
|
+
const session = sandbox.currentSession();
|
|
4222
|
+
const fileSystem = new FileSystem(session);
|
|
4223
|
+
const run = async (operation) => {
|
|
4224
|
+
try {
|
|
4225
|
+
return await operation();
|
|
4226
|
+
} catch (error) {
|
|
4227
|
+
if (vercelSandboxErrors.isUnavailable(error)) options?.onUnavailable?.(session.sessionId);
|
|
4228
|
+
throw error;
|
|
4229
|
+
}
|
|
4230
|
+
};
|
|
4231
|
+
return {
|
|
4232
|
+
sandboxId: sandbox.name,
|
|
4233
|
+
sessionId: session.sessionId,
|
|
4234
|
+
keepsFilesAcrossSessions: sandbox.persistent,
|
|
4235
|
+
startedAtMs: (session.startedAt ?? session.createdAt).getTime(),
|
|
4236
|
+
fs: {
|
|
4237
|
+
readFile: async (filePath, readOptions) => await run(async () => await fileSystem.readFile(filePath, readOptions)),
|
|
4238
|
+
writeFile: async (filePath, content, writeOptions) => await run(async () => await fileSystem.writeFile(filePath, content, writeOptions)),
|
|
4239
|
+
readdir: async (filePath, readOptions) => await run(async () => await fileSystem.readdir(filePath, readOptions)),
|
|
4240
|
+
stat: async (filePath, statOptions) => await run(async () => await fileSystem.stat(filePath, statOptions))
|
|
4241
|
+
},
|
|
4242
|
+
createPreview(port) {
|
|
4243
|
+
return run(async () => {
|
|
4244
|
+
const ports = new Set(session.routes.map((route) => route.port));
|
|
4245
|
+
if (!ports.has(port)) await sandbox.update({ ports: [...ports, port] });
|
|
4246
|
+
return session.domain(port);
|
|
4247
|
+
});
|
|
4248
|
+
},
|
|
4249
|
+
previewUrls() {
|
|
4250
|
+
return session.routes.map((route) => session.domain(route.port));
|
|
4251
|
+
},
|
|
4252
|
+
extendTimeout(duration) {
|
|
4253
|
+
return run(async () => await session.extendTimeout(duration));
|
|
4254
|
+
},
|
|
4255
|
+
mkDir(path) {
|
|
4256
|
+
return run(async () => await session.mkDir(path));
|
|
4257
|
+
},
|
|
4258
|
+
readFileToBuffer(input) {
|
|
4259
|
+
return run(async () => await session.readFileToBuffer(input));
|
|
4260
|
+
},
|
|
4261
|
+
async runCommand(input) {
|
|
4262
|
+
const result = await run(async () => await session.runCommand(input));
|
|
4263
|
+
const [stdout, stderr] = await Promise.all([run(async () => await result.stdout()), run(async () => await result.stderr())]);
|
|
4264
|
+
return {
|
|
4265
|
+
exitCode: result.exitCode,
|
|
4266
|
+
stdout,
|
|
4267
|
+
stderr
|
|
4268
|
+
};
|
|
4269
|
+
},
|
|
4270
|
+
snapshot(snapshotOptions) {
|
|
4271
|
+
return run(async () => {
|
|
4272
|
+
return { snapshotId: (await session.snapshot(snapshotOptions)).snapshotId };
|
|
4273
|
+
});
|
|
4274
|
+
},
|
|
4275
|
+
stop() {
|
|
4276
|
+
return run(async () => await session.stop());
|
|
4277
|
+
},
|
|
4278
|
+
update(params) {
|
|
4279
|
+
return run(async () => await session.update(params.networkPolicy ? { networkPolicy: toVercelNetworkPolicy(params.networkPolicy) } : {}));
|
|
4280
|
+
},
|
|
4281
|
+
writeFiles(files) {
|
|
4282
|
+
return run(async () => await session.writeFiles(files));
|
|
4283
|
+
}
|
|
4284
|
+
};
|
|
4285
|
+
}
|
|
4286
|
+
/**
|
|
4287
|
+
* Each new VM session runs `update-ca-trust` from the guest init process, and
|
|
4288
|
+
* the session accepts commands before it finishes. While it rebuilds
|
|
4289
|
+
* `/etc/pki/ca-trust/extracted`, `/etc/ssl/certs/ca-certificates.crt` is
|
|
4290
|
+
* briefly missing, and an HTTPS client that starts then fails, such as curl
|
|
4291
|
+
* with exit 77. The `[u]` keeps the pattern from matching this command.
|
|
4292
|
+
*/
|
|
4293
|
+
const WAIT_FOR_BOOT_CA_REFRESH = "while grep -qsa '[u]pdate-ca-trust' /proc/[0-9]*/cmdline; do sleep 0.05; done";
|
|
4294
|
+
/** Wait until the guest's boot CA refresh is done, so HTTPS works. */
|
|
4295
|
+
async function waitForBootCaRefresh(session, signal) {
|
|
4296
|
+
await session.runCommand({
|
|
4297
|
+
cmd: "sh",
|
|
4298
|
+
args: ["-c", WAIT_FOR_BOOT_CA_REFRESH],
|
|
4299
|
+
signal
|
|
4300
|
+
});
|
|
4301
|
+
}
|
|
4302
|
+
/** Create a Sandbox and return a session pinned to its first VM session. */
|
|
4303
|
+
async function createSandboxSession(input) {
|
|
4304
|
+
const shared = {
|
|
4305
|
+
timeout: input.timeoutMs,
|
|
4306
|
+
...input.name ? { name: input.name } : void 0,
|
|
4307
|
+
...input.persistent !== void 0 ? { persistent: input.persistent } : void 0,
|
|
4308
|
+
...input.networkPolicy ? { networkPolicy: toVercelNetworkPolicy(input.networkPolicy) } : void 0,
|
|
4309
|
+
...input.resources ? { resources: input.resources } : void 0,
|
|
4310
|
+
...input.signal ? { signal: input.signal } : void 0,
|
|
4311
|
+
...clientOptions(input.scopeSignal)
|
|
4312
|
+
};
|
|
4313
|
+
const session = adaptSession(await Sandbox.create(input.snapshotId ? {
|
|
4314
|
+
...shared,
|
|
4315
|
+
source: {
|
|
4316
|
+
type: "snapshot",
|
|
4317
|
+
snapshotId: input.snapshotId
|
|
4318
|
+
}
|
|
4319
|
+
} : {
|
|
4320
|
+
...shared,
|
|
4321
|
+
...input.runtime ? { runtime: input.runtime } : void 0
|
|
4322
|
+
}), input);
|
|
4323
|
+
await waitForBootCaRefresh(session, input.signal);
|
|
4324
|
+
return session;
|
|
4325
|
+
}
|
|
4326
|
+
/** Resume a named Sandbox and return a session pinned to its VM session. */
|
|
4327
|
+
async function getSandboxSession(input) {
|
|
4328
|
+
const session = adaptSession(await Sandbox.get({
|
|
4329
|
+
name: input.name,
|
|
4330
|
+
resume: true,
|
|
4331
|
+
...clientOptions(input.scopeSignal)
|
|
4332
|
+
}), input);
|
|
4333
|
+
await waitForBootCaRefresh(session);
|
|
4334
|
+
return session;
|
|
4335
|
+
}
|
|
4336
|
+
/** Create the named, persistent Sandbox that owns one Workspace snapshot build. */
|
|
4337
|
+
async function createWorkspaceSnapshotBuilder(input) {
|
|
4338
|
+
await Sandbox.create({
|
|
4339
|
+
name: input.name,
|
|
4340
|
+
persistent: true,
|
|
4341
|
+
timeout: input.timeoutMs,
|
|
4342
|
+
runtime: input.runtime,
|
|
4343
|
+
signal: input.signal,
|
|
4344
|
+
...clientOptions(),
|
|
4345
|
+
...input.resources ? { resources: input.resources } : void 0
|
|
4346
|
+
});
|
|
4347
|
+
}
|
|
4348
|
+
/** Resume the named Sandbox that owns one Workspace snapshot build. */
|
|
4349
|
+
async function getWorkspaceSnapshotBuilder(name, signal) {
|
|
4350
|
+
const sandbox = await Sandbox.get({
|
|
4351
|
+
name,
|
|
4352
|
+
resume: true,
|
|
4353
|
+
signal,
|
|
4354
|
+
...clientOptions()
|
|
4355
|
+
});
|
|
4356
|
+
return {
|
|
4357
|
+
session: () => adaptSession(sandbox),
|
|
4358
|
+
async startDetachedCommand(input) {
|
|
4359
|
+
return (await sandbox.runCommand({
|
|
4360
|
+
...input,
|
|
4361
|
+
detached: true
|
|
4362
|
+
})).cmdId;
|
|
4363
|
+
},
|
|
4364
|
+
getCommand: (commandId, options) => sandbox.getCommand(commandId, options),
|
|
4365
|
+
async snapshot(options) {
|
|
4366
|
+
const snapshot = await sandbox.snapshot(options);
|
|
4367
|
+
return {
|
|
4368
|
+
snapshotId: snapshot.snapshotId,
|
|
4369
|
+
...typeof snapshot.sizeBytes === "number" ? { sizeBytes: snapshot.sizeBytes } : void 0
|
|
4370
|
+
};
|
|
4371
|
+
}
|
|
4372
|
+
};
|
|
4373
|
+
}
|
|
4374
|
+
/** Permanently delete named Workspace snapshot builders without resuming them. */
|
|
4375
|
+
async function deleteWorkspaceSnapshotBuilders(names) {
|
|
4376
|
+
let hasError = false;
|
|
4377
|
+
let firstError;
|
|
4378
|
+
await mapBounded([...new Set(names)], async (name) => {
|
|
4379
|
+
try {
|
|
4380
|
+
await (await Sandbox.get({
|
|
4381
|
+
name,
|
|
4382
|
+
resume: false,
|
|
4383
|
+
...clientOptions()
|
|
4384
|
+
})).delete();
|
|
4385
|
+
} catch (error) {
|
|
4386
|
+
if (!vercelSandboxErrors.isMissing(error)) {
|
|
4387
|
+
if (!hasError) firstError = error;
|
|
4388
|
+
hasError = true;
|
|
4389
|
+
}
|
|
4390
|
+
}
|
|
4391
|
+
});
|
|
4392
|
+
if (hasError) throw firstError;
|
|
4393
|
+
}
|
|
4394
|
+
/** Vercel Sandbox implementation of the sandbox provider contract. */
|
|
4395
|
+
const vercelSandboxProvider = {
|
|
4396
|
+
errors: vercelSandboxErrors,
|
|
4397
|
+
createSession: createSandboxSession,
|
|
4398
|
+
getSession: getSandboxSession,
|
|
4399
|
+
createWorkspaceSnapshotBuilder,
|
|
4400
|
+
getWorkspaceSnapshotBuilder,
|
|
4401
|
+
deleteWorkspaceSnapshotBuilders
|
|
4402
|
+
};
|
|
4403
|
+
// src/chat/sandbox/provider.ts
|
|
4404
|
+
/** Return the sandbox provider for this deployment. */
|
|
4405
|
+
function getSandboxProvider() {
|
|
4406
|
+
return getChatConfig().sandbox.provider === "docker" ? dockerSandboxProvider : vercelSandboxProvider;
|
|
4407
|
+
}
|
|
4408
|
+
/**
|
|
4409
|
+
* True when a sandbox call failed for a short time or lost its VM session, so
|
|
4410
|
+
* the work can retry from a saved point and reacquire the sandbox.
|
|
4411
|
+
*/
|
|
4412
|
+
function isRetryableSandboxFailure(error) {
|
|
4413
|
+
const errors = getSandboxProvider().errors;
|
|
4414
|
+
return findInErrorChain(error, (candidate) => candidate instanceof SandboxCallTimeoutError) || errors.isTransient(error) || errors.isUnavailable(error) || errors.isCommandStreamInterrupted(error);
|
|
4415
|
+
}
|
|
4416
|
+
// src/chat/sandbox/guest-docker.ts
|
|
4417
|
+
/** Docker daemon config for Vercel sandbox guests (nested containers). */
|
|
4418
|
+
const DOCKER_DAEMON_JSON = `{
|
|
4419
|
+
"storage-driver": "overlay2",
|
|
4420
|
+
"live-restore": false
|
|
4421
|
+
}
|
|
4422
|
+
`;
|
|
4423
|
+
/**
|
|
4424
|
+
* Start dockerd when the socket is missing and wait until `docker info` works.
|
|
4425
|
+
* Re-execs through sudo so the sandbox user can call it without root.
|
|
4426
|
+
*/
|
|
4427
|
+
const DOCKER_ENSURE_SCRIPT = `#!/bin/sh
|
|
4428
|
+
set -eu
|
|
4429
|
+
|
|
4430
|
+
if [ "$(id -u)" -ne 0 ]; then
|
|
4431
|
+
exec sudo -n "$0" "$@"
|
|
4432
|
+
fi
|
|
4433
|
+
|
|
4434
|
+
SOCK=/var/run/docker.sock
|
|
4435
|
+
PIDFILE=/var/run/docker.pid
|
|
4436
|
+
LOG=/var/log/junior-dockerd.log
|
|
4437
|
+
|
|
4438
|
+
is_ready() {
|
|
4439
|
+
[ -S "$SOCK" ] && /usr/bin/docker info >/dev/null 2>&1
|
|
4440
|
+
}
|
|
4441
|
+
|
|
4442
|
+
if is_ready; then
|
|
4443
|
+
chmod 666 "$SOCK" 2>/dev/null || true
|
|
4444
|
+
exit 0
|
|
4445
|
+
fi
|
|
4446
|
+
|
|
4447
|
+
mkdir -p /etc/docker /var/lib/docker /var/run /var/log
|
|
4448
|
+
if [ ! -f /etc/docker/daemon.json ]; then
|
|
4449
|
+
cat > /etc/docker/daemon.json <<'EOF'
|
|
4450
|
+
{
|
|
4451
|
+
"storage-driver": "overlay2",
|
|
4452
|
+
"live-restore": false
|
|
4453
|
+
}
|
|
4454
|
+
EOF
|
|
4455
|
+
fi
|
|
4456
|
+
|
|
4457
|
+
if [ -f "$PIDFILE" ]; then
|
|
4458
|
+
oldpid="$(cat "$PIDFILE" 2>/dev/null || true)"
|
|
4459
|
+
if [ -n "\${oldpid:-}" ] && ! kill -0 "$oldpid" 2>/dev/null; then
|
|
4460
|
+
rm -f "$PIDFILE"
|
|
4461
|
+
fi
|
|
4462
|
+
fi
|
|
4463
|
+
|
|
4464
|
+
if [ ! -f "$PIDFILE" ] || ! kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null; then
|
|
4465
|
+
# dockerd must outlive this helper; nohup + background is intentional.
|
|
4466
|
+
nohup dockerd --host="unix://$SOCK" --pidfile="$PIDFILE" >"$LOG" 2>&1 &
|
|
4467
|
+
fi
|
|
4468
|
+
|
|
4469
|
+
i=0
|
|
4470
|
+
while [ "$i" -lt 50 ]; do
|
|
4471
|
+
if is_ready; then
|
|
4472
|
+
chmod 666 "$SOCK" 2>/dev/null || true
|
|
4473
|
+
exit 0
|
|
4474
|
+
fi
|
|
4475
|
+
i=$((i + 1))
|
|
4476
|
+
sleep 0.1
|
|
4477
|
+
done
|
|
4478
|
+
|
|
4479
|
+
echo "junior-ensure-docker: dockerd failed to become ready" >&2
|
|
4480
|
+
if [ -f "$LOG" ]; then
|
|
4481
|
+
tail -n 50 "$LOG" >&2 || true
|
|
4482
|
+
fi
|
|
4483
|
+
exit 1
|
|
4484
|
+
`;
|
|
4485
|
+
/** PATH wrapper so plain `docker` starts the daemon on first use. */
|
|
4486
|
+
const DOCKER_CLI_WRAPPER_SCRIPT = `#!/bin/sh
|
|
4487
|
+
set -eu
|
|
4488
|
+
if command -v junior-ensure-docker >/dev/null 2>&1; then
|
|
4489
|
+
junior-ensure-docker
|
|
4490
|
+
fi
|
|
4491
|
+
exec /usr/bin/docker "$@"
|
|
4492
|
+
`;
|
|
4493
|
+
/** PATH wrapper so plain `docker-compose` starts the daemon on first use. */
|
|
4494
|
+
const DOCKER_COMPOSE_CLI_WRAPPER_SCRIPT = `#!/bin/sh
|
|
4495
|
+
set -eu
|
|
4496
|
+
if command -v junior-ensure-docker >/dev/null 2>&1; then
|
|
4497
|
+
junior-ensure-docker
|
|
4498
|
+
fi
|
|
4499
|
+
exec /usr/local/libexec/junior-docker-compose "$@"
|
|
4500
|
+
`;
|
|
4501
|
+
/**
|
|
4502
|
+
* Best-effort dockerd start during sandbox prepare.
|
|
4503
|
+
* Missing helper is a no-op so tests and base sandboxes stay green.
|
|
4504
|
+
*/
|
|
4505
|
+
async function ensureDockerDaemon(sandbox, signal) {
|
|
4506
|
+
await runNonInteractiveCommand(sandbox, {
|
|
4507
|
+
cmd: "sh",
|
|
4508
|
+
args: ["-c", "command -v junior-ensure-docker >/dev/null 2>&1 && junior-ensure-docker || true"],
|
|
4509
|
+
signal
|
|
4510
|
+
});
|
|
4511
|
+
}
|
|
4512
|
+
// src/chat/sandbox/runtime-dependencies.ts
|
|
4513
|
+
const GLOBAL_RUNTIME_DEPENDENCIES = [
|
|
4514
|
+
{
|
|
4515
|
+
type: "system",
|
|
4516
|
+
package: "docker"
|
|
4517
|
+
},
|
|
4518
|
+
{
|
|
4519
|
+
type: "system",
|
|
4520
|
+
package: "spal-release"
|
|
4521
|
+
},
|
|
4522
|
+
{
|
|
4523
|
+
type: "system",
|
|
4524
|
+
package: "ripgrep"
|
|
4525
|
+
}
|
|
4526
|
+
];
|
|
4527
|
+
/**
|
|
4528
|
+
* Download flags for snapshot builds. `--retry` repeats only failures that
|
|
4529
|
+
* curl treats as transient, such as timeouts and HTTP 408, 429, 500, 502,
|
|
4530
|
+
* 503, and 504. Other errors, such as a 404, still fail the build at once.
|
|
4531
|
+
*/
|
|
4532
|
+
const CURL_DOWNLOAD_ARGS = [
|
|
4533
|
+
"--fail",
|
|
4534
|
+
"--location",
|
|
4535
|
+
"--silent",
|
|
4536
|
+
"--show-error",
|
|
4537
|
+
"--retry",
|
|
4538
|
+
"3"
|
|
4539
|
+
];
|
|
4540
|
+
function writeFileCommand(path, contents, mode = "0644") {
|
|
4541
|
+
return [`printf '%s' '${Buffer.from(contents, "utf8").toString("base64")}' | base64 -d > ${path}`, `chmod ${mode} ${path}`].join("\n");
|
|
4542
|
+
}
|
|
4543
|
+
function writeExecutableCommand(path, contents) {
|
|
4544
|
+
return writeFileCommand(path, contents, "0755");
|
|
4545
|
+
}
|
|
4546
|
+
const GLOBAL_RUNTIME_POSTINSTALL = [{
|
|
4547
|
+
cmd: "sh",
|
|
4548
|
+
args: ["-c", [
|
|
4549
|
+
"set -eu",
|
|
4550
|
+
"case \"$(uname -m)\" in",
|
|
4551
|
+
" x86_64) asset=\"x86_64\"; sha256=\"7af95166a730b87e172d4fc9aefea8725d3c6c7327d59149267b452114ddb7d4\" ;;",
|
|
4552
|
+
" aarch64) asset=\"aarch64\"; sha256=\"49082844b87f03cdcd5f5bbef1ba8c9c897b7a2dfb80cea18d61ec8ca6117e0c\" ;;",
|
|
4553
|
+
" *) echo \"unsupported Docker Compose architecture: $(uname -m)\" >&2; exit 1 ;;",
|
|
4554
|
+
"esac",
|
|
4555
|
+
"tmp=\"$(mktemp)\"",
|
|
4556
|
+
"trap 'rm -f \"$tmp\"' EXIT",
|
|
4557
|
+
`curl ${CURL_DOWNLOAD_ARGS.join(" ")} "https://github.com/docker/compose/releases/download/v2.39.4/docker-compose-linux-\${asset}" --output "$tmp"`,
|
|
4558
|
+
"echo \"${sha256} ${tmp}\" | sha256sum --check --status",
|
|
4559
|
+
"install -D -m 0755 \"$tmp\" /usr/local/libexec/junior-docker-compose",
|
|
4560
|
+
"mkdir -p /usr/local/lib/docker/cli-plugins /usr/local/libexec /etc/docker /usr/local/bin",
|
|
4561
|
+
`mkdir -p ${SANDBOX_WORKSPACE_ROOT}/.junior/bin`,
|
|
4562
|
+
writeFileCommand("/etc/docker/daemon.json", DOCKER_DAEMON_JSON),
|
|
4563
|
+
writeExecutableCommand("/usr/local/bin/junior-ensure-docker", DOCKER_ENSURE_SCRIPT),
|
|
4564
|
+
"ln -sfn /usr/local/libexec/junior-docker-compose /usr/local/lib/docker/cli-plugins/docker-compose",
|
|
4565
|
+
writeExecutableCommand("/usr/local/bin/docker-compose", DOCKER_COMPOSE_CLI_WRAPPER_SCRIPT),
|
|
4566
|
+
writeExecutableCommand(`${SANDBOX_WORKSPACE_ROOT}/.junior/bin/docker`, DOCKER_CLI_WRAPPER_SCRIPT),
|
|
4567
|
+
writeExecutableCommand(`${SANDBOX_WORKSPACE_ROOT}/.junior/bin/docker-compose`, DOCKER_COMPOSE_CLI_WRAPPER_SCRIPT),
|
|
4568
|
+
writeExecutableCommand("/usr/local/bin/docker", DOCKER_CLI_WRAPPER_SCRIPT)
|
|
4569
|
+
].join("\n")],
|
|
4570
|
+
sudo: true
|
|
4571
|
+
}];
|
|
4572
|
+
// src/chat/sandbox/snapshot/profile.ts
|
|
4573
|
+
const VERSION = 1;
|
|
4574
|
+
function isExactNpmVersion(version) {
|
|
4575
|
+
return /^\d+\.\d+\.\d+(?:[-+][a-z0-9.]+)?$/i.test(version.trim());
|
|
4576
|
+
}
|
|
4577
|
+
function isFloating(dep) {
|
|
4578
|
+
return dep.type === "npm" && !isExactNpmVersion(dep.version);
|
|
4579
|
+
}
|
|
4580
|
+
/**
|
|
4581
|
+
* Merge dependencies for one global install, rejecting competing npm versions.
|
|
4582
|
+
*/
|
|
4583
|
+
function mergeDependencies(dependencies) {
|
|
4584
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4585
|
+
const npmVersions = /* @__PURE__ */ new Map();
|
|
4586
|
+
const merged = [];
|
|
4587
|
+
for (const dependency of dependencies) {
|
|
4588
|
+
const key = dependency.type === "npm" ? `${dependency.type}:${dependency.package}:${dependency.version}` : "package" in dependency ? `${dependency.type}:package:${dependency.package}` : `${dependency.type}:url:${dependency.url}:${dependency.sha256}`;
|
|
4589
|
+
if (seen.has(key)) continue;
|
|
4590
|
+
seen.add(key);
|
|
4591
|
+
if (dependency.type === "npm") {
|
|
4592
|
+
const version = npmVersions.get(dependency.package);
|
|
4593
|
+
if (version !== void 0 && version !== dependency.version) throw new Error(`Conflicting runtime dependency versions for ${dependency.package}: ${version} and ${dependency.version}`);
|
|
4594
|
+
npmVersions.set(dependency.package, dependency.version);
|
|
4595
|
+
}
|
|
4596
|
+
merged.push(dependency);
|
|
4597
|
+
}
|
|
4598
|
+
return merged;
|
|
4599
|
+
}
|
|
4600
|
+
/** Locale-independent string order for stable profile hashes. */
|
|
4601
|
+
function compareCodePoints(left, right) {
|
|
4602
|
+
if (left < right) return -1;
|
|
4603
|
+
if (left > right) return 1;
|
|
4604
|
+
return 0;
|
|
4605
|
+
}
|
|
4606
|
+
function workspaceRecipe(workspace) {
|
|
4607
|
+
const repos = [...workspace.repos].map(({ provider, repo }) => ({
|
|
4608
|
+
provider,
|
|
4609
|
+
repo
|
|
4610
|
+
})).sort((left, right) => {
|
|
4611
|
+
const provider = compareCodePoints(left.provider, right.provider);
|
|
4612
|
+
if (provider !== 0) return provider;
|
|
4613
|
+
return compareCodePoints(left.repo, right.repo);
|
|
4614
|
+
});
|
|
4615
|
+
return {
|
|
4616
|
+
id: workspace.id,
|
|
4617
|
+
repos,
|
|
4618
|
+
setupScript: workspace.setupScript
|
|
4619
|
+
};
|
|
4620
|
+
}
|
|
4621
|
+
/** Build the complete profile that selects one reusable sandbox snapshot. */
|
|
4622
|
+
function create(runtime, workspace) {
|
|
4623
|
+
const declared = {
|
|
4624
|
+
dependencies: mergeDependencies([...GLOBAL_RUNTIME_DEPENDENCIES, ...pluginCatalogRuntime.getRuntimeDependencies()]),
|
|
4625
|
+
postinstall: [...GLOBAL_RUNTIME_POSTINSTALL, ...pluginCatalogRuntime.getRuntimePostinstall()]
|
|
4626
|
+
};
|
|
4627
|
+
const { dependencies, postinstall } = getSandboxProvider().selectSnapshotRuntime?.(declared) ?? declared;
|
|
4628
|
+
const pluginPostinstall = postinstall.filter((command) => !GLOBAL_RUNTIME_POSTINSTALL.includes(command));
|
|
4629
|
+
if (dependencies.length === 0 && postinstall.length === 0 && !workspace) return null;
|
|
4630
|
+
const { rebuildEpoch } = getChatConfig().sandbox.snapshot;
|
|
4631
|
+
const floating = dependencies.some((dependency) => isFloating(dependency)) || pluginPostinstall.length > 0 || Boolean(workspace);
|
|
4632
|
+
return {
|
|
4633
|
+
hash: createHash("sha256").update(JSON.stringify({
|
|
4634
|
+
version: VERSION,
|
|
4635
|
+
runtime,
|
|
4636
|
+
rebuildEpoch,
|
|
4637
|
+
dependencies,
|
|
4638
|
+
postinstall,
|
|
4639
|
+
...workspace ? { workspace: workspaceRecipe(workspace) } : void 0
|
|
4640
|
+
})).digest("hex"),
|
|
4641
|
+
dependencyCount: dependencies.length,
|
|
4642
|
+
floating,
|
|
4643
|
+
dependencies,
|
|
4644
|
+
postinstall
|
|
4645
|
+
};
|
|
4646
|
+
}
|
|
4647
|
+
/** Return the current dependency profile hash without building its snapshot. */
|
|
4648
|
+
function hash(runtime, workspace) {
|
|
4649
|
+
return create(runtime, workspace)?.hash;
|
|
4650
|
+
}
|
|
4651
|
+
/** Decide whether a cached snapshot has outlived a floating profile. */
|
|
4652
|
+
function isStale(profile, createdAtMs) {
|
|
4653
|
+
if (!profile.floating) return false;
|
|
4654
|
+
const maxAgeMs = getChatConfig().sandbox.snapshot.floatingMaxAgeMs;
|
|
4655
|
+
return maxAgeMs === 0 || Date.now() - createdAtMs > maxAgeMs;
|
|
4656
|
+
}
|
|
4657
|
+
export { createUserTokenStore as A, clearSandboxEgressSignals as C, parseSandboxEgressCredentialToken as D, createSandboxEgressCredentialToken as E, getOAuthAccountProviders as F, resolvePluginOAuthAccount as I, credentialAuditAttributes as L, resolveSandboxCommandEnvironment as M, resolveSandboxEgressProviderForHost as N, parseSandboxEgressAuthRequiredSignal as O, normalizeSandboxEgressTracePropagationDomains as P, credentialAuditSource as R, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as S, consumeSandboxEgressPermissionDeniedSignal as T, WorkspaceSnapshotNotReadyError as _, ensureDockerDaemon as a, workspaceSnapshotNotReadyUserMessage as b, isVercelSandboxEgressRequest as c, SandboxCallTimeoutError as d, findInErrorChain as f, wrapSandboxSetupError as g, throwSandboxOperationError as h, CURL_DOWNLOAD_ARGS as i, buildSandboxEgressNetworkPolicy as j, sandboxEgressSignalsResponseSchema as k, proxyVercelSandboxEgressRequest as l, isAlreadyExistsError as m, hash as n, getSandboxProvider as o, isAbortError as p, isStale as r, isRetryableSandboxFailure as s, create as t, SANDBOX_RUNTIME as u, getWorkspaceSnapshotNotReadyError as v, consumeSandboxEgressAuthRequiredSignal as w, executeCredentialedEgressRequest as x, isWorkspaceSnapshotNotReadyError as y };
|