@codelia/runtime 0.1.86 → 0.1.89
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/{chunk-RJV3XRDN.js → chunk-LNUGYGST.js} +1071 -481
- package/dist/{chunk-ZFXISMDO.js → chunk-NPCH2IMV.js} +927 -400
- package/dist/index.cjs +2065 -1025
- package/dist/index.js +2 -2
- package/dist/sdk.cjs +2202 -1158
- package/dist/sdk.d.cts +38 -30
- package/dist/sdk.d.ts +38 -30
- package/dist/sdk.js +8 -2
- package/dist/subagents/child-entry.cjs +680 -291
- package/dist/subagents/child-entry.js +1 -1
- package/package.json +10 -10
|
@@ -16,7 +16,11 @@ import {
|
|
|
16
16
|
isModelReasoningLevel,
|
|
17
17
|
MODEL_REASONING_LEVELS
|
|
18
18
|
} from "@codelia/shared-types";
|
|
19
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
isSameConfigFilePath,
|
|
21
|
+
isTrustedGlobalConfigLocationSync,
|
|
22
|
+
StoragePathServiceImpl
|
|
23
|
+
} from "@codelia/storage";
|
|
20
24
|
var DEFAULT_SYSTEM_PROMPT = "You are a coding assistant.";
|
|
21
25
|
var DEFAULT_MCP_REQUEST_TIMEOUT_MS = 3e4;
|
|
22
26
|
var DEFAULT_SKILLS_INITIAL_MAX_ENTRIES = 200;
|
|
@@ -43,7 +47,13 @@ var resolveConfigPath = () => {
|
|
|
43
47
|
const storage = new StoragePathServiceImpl();
|
|
44
48
|
return storage.resolvePaths().configFile;
|
|
45
49
|
};
|
|
50
|
+
var SHARED_PROJECT_CONFIG_ERROR = "project config shares the global config file in this workspace; use global scope instead";
|
|
46
51
|
var resolveProjectConfigPath = (workingDir) => path.resolve(workingDir, ".codelia", "config.json");
|
|
52
|
+
var resolveDistinctProjectConfigPath = (workingDir) => {
|
|
53
|
+
if (!workingDir) return null;
|
|
54
|
+
const projectPath = resolveProjectConfigPath(workingDir);
|
|
55
|
+
return isSameConfigFilePath(resolveConfigPath(), projectPath) ? null : projectPath;
|
|
56
|
+
};
|
|
47
57
|
var loadConfigLayers = async (workingDir) => {
|
|
48
58
|
const configPath = resolveConfigPath();
|
|
49
59
|
let globalConfig = null;
|
|
@@ -54,8 +64,8 @@ var loadConfigLayers = async (workingDir) => {
|
|
|
54
64
|
throw new Error(`Failed to load config.json: ${message}`);
|
|
55
65
|
}
|
|
56
66
|
let projectConfig = null;
|
|
57
|
-
|
|
58
|
-
|
|
67
|
+
const projectPath = resolveDistinctProjectConfigPath(workingDir);
|
|
68
|
+
if (projectPath) {
|
|
59
69
|
try {
|
|
60
70
|
projectConfig = await loadConfig(projectPath);
|
|
61
71
|
} catch (error) {
|
|
@@ -65,6 +75,7 @@ var loadConfigLayers = async (workingDir) => {
|
|
|
65
75
|
}
|
|
66
76
|
return { globalConfig, projectConfig };
|
|
67
77
|
};
|
|
78
|
+
var resolveConfigLayers = async (workingDir) => loadConfigLayers(workingDir);
|
|
68
79
|
var resolveImageGenerationConfig = async (workingDir) => {
|
|
69
80
|
const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
|
|
70
81
|
return configRegistry.resolve([globalConfig, projectConfig]).image_generation ?? {
|
|
@@ -251,6 +262,7 @@ var normalizeMcpTimeoutMs = (value) => {
|
|
|
251
262
|
};
|
|
252
263
|
var resolveMcpServers = async (workingDir) => {
|
|
253
264
|
const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
|
|
265
|
+
const globalSource = workingDir && !isTrustedGlobalConfigLocationSync(workingDir, resolveConfigPath()) ? "project" : "global";
|
|
254
266
|
const globalServers = globalConfig?.mcp?.servers ?? {};
|
|
255
267
|
const projectServers = projectConfig?.mcp?.servers ?? {};
|
|
256
268
|
const allIds = /* @__PURE__ */ new Set([
|
|
@@ -266,7 +278,7 @@ var resolveMcpServers = async (workingDir) => {
|
|
|
266
278
|
resolved.push({
|
|
267
279
|
...server,
|
|
268
280
|
id,
|
|
269
|
-
source: project ? "project" :
|
|
281
|
+
source: project ? "project" : globalSource,
|
|
270
282
|
enabled: server.enabled !== false,
|
|
271
283
|
request_timeout_ms: normalizeMcpTimeoutMs(server.request_timeout_ms)
|
|
272
284
|
});
|
|
@@ -289,19 +301,19 @@ var hasDefinedGroup = (group, value) => {
|
|
|
289
301
|
};
|
|
290
302
|
var resolveWriteTarget = async (workingDir, group) => {
|
|
291
303
|
const globalPath = resolveConfigPath();
|
|
292
|
-
const projectPath =
|
|
304
|
+
const projectPath = resolveDistinctProjectConfigPath(workingDir);
|
|
293
305
|
const [globalConfig, projectConfig] = await Promise.all([
|
|
294
306
|
loadConfig(globalPath),
|
|
295
|
-
loadConfig(projectPath)
|
|
307
|
+
projectPath ? loadConfig(projectPath) : Promise.resolve(null)
|
|
296
308
|
]);
|
|
297
|
-
if (hasDefinedGroup(group, projectConfig)) {
|
|
309
|
+
if (projectPath && hasDefinedGroup(group, projectConfig)) {
|
|
298
310
|
return { scope: "project", path: projectPath };
|
|
299
311
|
}
|
|
300
312
|
if (hasDefinedGroup(group, globalConfig)) {
|
|
301
313
|
return { scope: "global", path: globalPath };
|
|
302
314
|
}
|
|
303
315
|
const defaultScope = CONFIG_GROUP_DEFAULT_WRITE_SCOPE[group];
|
|
304
|
-
return defaultScope === "project" ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
|
|
316
|
+
return defaultScope === "project" && projectPath ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
|
|
305
317
|
};
|
|
306
318
|
var updateModel = async (workingDir, model) => {
|
|
307
319
|
const target = await resolveWriteTarget(workingDir, "model");
|
|
@@ -778,6 +790,7 @@ var startOAuthCallbackServer = (options) => {
|
|
|
778
790
|
// src/auth/openai-oauth.ts
|
|
779
791
|
import { spawn } from "child_process";
|
|
780
792
|
import { ProviderFailureError } from "@codelia/core";
|
|
793
|
+
import { DEFAULT_OAUTH_REFRESH_TIMEOUT_MS } from "@codelia/storage";
|
|
781
794
|
var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
782
795
|
var ISSUER = "https://auth.openai.com";
|
|
783
796
|
var DEFAULT_PORT = 1455;
|
|
@@ -804,6 +817,32 @@ var buildAuthorizeUrl = (redirectUri, pkce, state) => {
|
|
|
804
817
|
});
|
|
805
818
|
return `${ISSUER}/oauth/authorize?${params.toString()}`;
|
|
806
819
|
};
|
|
820
|
+
var withSignalAbort = (promise, signal) => {
|
|
821
|
+
if (!signal) return promise;
|
|
822
|
+
if (signal.aborted) {
|
|
823
|
+
return Promise.reject(
|
|
824
|
+
signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
return new Promise((resolve, reject) => {
|
|
828
|
+
const onAbort = () => {
|
|
829
|
+
reject(
|
|
830
|
+
signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
|
|
831
|
+
);
|
|
832
|
+
};
|
|
833
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
834
|
+
promise.then(
|
|
835
|
+
(value) => {
|
|
836
|
+
signal.removeEventListener("abort", onAbort);
|
|
837
|
+
resolve(value);
|
|
838
|
+
},
|
|
839
|
+
(error) => {
|
|
840
|
+
signal.removeEventListener("abort", onAbort);
|
|
841
|
+
reject(error);
|
|
842
|
+
}
|
|
843
|
+
);
|
|
844
|
+
});
|
|
845
|
+
};
|
|
807
846
|
var requestToken = async (params, operation, signal) => {
|
|
808
847
|
const response = await fetch(`${ISSUER}/oauth/token`, {
|
|
809
848
|
method: "POST",
|
|
@@ -813,9 +852,9 @@ var requestToken = async (params, operation, signal) => {
|
|
|
813
852
|
body: new URLSearchParams(params).toString()
|
|
814
853
|
});
|
|
815
854
|
if (!response.ok) {
|
|
816
|
-
throw await tokenFailure(response, operation);
|
|
855
|
+
throw await withSignalAbort(tokenFailure(response, operation), signal);
|
|
817
856
|
}
|
|
818
|
-
return response.json();
|
|
857
|
+
return withSignalAbort(response.json(), signal);
|
|
819
858
|
};
|
|
820
859
|
var oauthReasons = {
|
|
821
860
|
refresh_token_reused: "The refresh token has already been used.",
|
|
@@ -852,16 +891,40 @@ var exchangeCodeForTokens = async (code, redirectUri, pkce) => {
|
|
|
852
891
|
"exchange"
|
|
853
892
|
);
|
|
854
893
|
};
|
|
855
|
-
var refreshAccessToken = async (refreshToken, signal) => {
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
894
|
+
var refreshAccessToken = async (refreshToken, signal, options) => {
|
|
895
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
|
|
896
|
+
const timeoutController = new AbortController();
|
|
897
|
+
let timedOut = false;
|
|
898
|
+
const timer = setTimeout(() => {
|
|
899
|
+
timedOut = true;
|
|
900
|
+
timeoutController.abort(new Error("OAuth token refresh timed out"));
|
|
901
|
+
}, timeoutMs);
|
|
902
|
+
const effectiveSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
|
903
|
+
try {
|
|
904
|
+
return await requestToken(
|
|
905
|
+
{
|
|
906
|
+
grant_type: "refresh_token",
|
|
907
|
+
refresh_token: refreshToken,
|
|
908
|
+
client_id: clientId()
|
|
909
|
+
},
|
|
910
|
+
"refresh",
|
|
911
|
+
effectiveSignal
|
|
912
|
+
);
|
|
913
|
+
} catch (error) {
|
|
914
|
+
if (timedOut) {
|
|
915
|
+
throw new ProviderFailureError({
|
|
916
|
+
provider: "openai",
|
|
917
|
+
kind: "provider",
|
|
918
|
+
code: "oauth_refresh_timeout",
|
|
919
|
+
safeMessage: "OpenAI OAuth token refresh timed out.",
|
|
920
|
+
detail: "The OAuth token endpoint did not respond before the timeout.",
|
|
921
|
+
retryable: true
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
throw error;
|
|
925
|
+
} finally {
|
|
926
|
+
clearTimeout(timer);
|
|
927
|
+
}
|
|
865
928
|
};
|
|
866
929
|
var parseJwt = (token) => {
|
|
867
930
|
const parts = token.split(".");
|
|
@@ -1150,93 +1213,335 @@ import {
|
|
|
1150
1213
|
openSync,
|
|
1151
1214
|
readFileSync
|
|
1152
1215
|
} from "fs";
|
|
1153
|
-
import {
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1216
|
+
import {
|
|
1217
|
+
AUTH_VERSION_V1,
|
|
1218
|
+
AUTH_VERSION_V2,
|
|
1219
|
+
authLockPathFor,
|
|
1220
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1221
|
+
CredentialConflictError,
|
|
1222
|
+
canonicalJsonEqual,
|
|
1223
|
+
clearStoreAcrossAllLocationsUnlocked,
|
|
1224
|
+
coordinateCredentialBackendUnlocked,
|
|
1225
|
+
ensureStorageDirs,
|
|
1226
|
+
keychainAccountForConfigDir,
|
|
1227
|
+
MacOsKeychainClient,
|
|
1228
|
+
mcpAuthStoreAdapter,
|
|
1229
|
+
parseAuthDocument,
|
|
1230
|
+
providerAuthStoreAdapter,
|
|
1231
|
+
readAuthStorageStateSync,
|
|
1232
|
+
resolveConfiguredAuthStorageMode,
|
|
1233
|
+
resolveStoragePaths,
|
|
1234
|
+
verifyWindowsCredentialFileAcl,
|
|
1235
|
+
verifyWindowsCredentialFileAclSync,
|
|
1236
|
+
withAuthStoreLock,
|
|
1237
|
+
writeFileAtomic
|
|
1238
|
+
} from "@codelia/storage";
|
|
1239
|
+
var normalizeAuthFileToV2 = (auth) => parseAuthDocument(JSON.stringify(auth)).normalized;
|
|
1240
|
+
var getChatProviderAuth = (auth, provider) => {
|
|
1241
|
+
if (!Object.hasOwn(auth.providers, provider)) return void 0;
|
|
1242
|
+
const entry = auth.providers[provider];
|
|
1243
|
+
if (entry.chat_method === "oauth" && entry.credentials.oauth) {
|
|
1244
|
+
return { method: "oauth", oauth: entry.credentials.oauth };
|
|
1245
|
+
}
|
|
1246
|
+
if (entry.chat_method === "api_key" && entry.credentials.api_key) {
|
|
1247
|
+
return { method: "api_key", ...entry.credentials.api_key };
|
|
1248
|
+
}
|
|
1249
|
+
return void 0;
|
|
1250
|
+
};
|
|
1251
|
+
var getStoredProviderApiKey = (auth, provider) => Object.hasOwn(auth.providers, provider) ? auth.providers[provider].credentials.api_key : void 0;
|
|
1252
|
+
var setProviderChatAuth = (auth, provider, next) => {
|
|
1253
|
+
const existing = Object.hasOwn(auth.providers, provider) ? auth.providers[provider] : void 0;
|
|
1254
|
+
const credentials = {
|
|
1255
|
+
...existing?.credentials ?? {}
|
|
1256
|
+
};
|
|
1257
|
+
if (next.method === "api_key") {
|
|
1258
|
+
credentials.api_key = {
|
|
1259
|
+
api_key: next.api_key,
|
|
1260
|
+
...next.api_base ? { api_base: next.api_base } : {}
|
|
1261
|
+
};
|
|
1262
|
+
} else {
|
|
1263
|
+
credentials.oauth = next.oauth;
|
|
1264
|
+
}
|
|
1265
|
+
auth.providers[provider] = {
|
|
1266
|
+
chat_method: next.method,
|
|
1267
|
+
credentials
|
|
1268
|
+
};
|
|
1269
|
+
};
|
|
1270
|
+
var updateProviderOAuthTokens = (auth, provider, oauth2) => {
|
|
1271
|
+
if (!Object.hasOwn(auth.providers, provider)) return false;
|
|
1272
|
+
const entry = auth.providers[provider];
|
|
1273
|
+
if (!entry.credentials.oauth) return false;
|
|
1274
|
+
auth.providers[provider] = {
|
|
1275
|
+
...entry.chat_method ? { chat_method: entry.chat_method } : {},
|
|
1276
|
+
credentials: {
|
|
1277
|
+
...entry.credentials,
|
|
1278
|
+
oauth: oauth2
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
return true;
|
|
1282
|
+
};
|
|
1283
|
+
var clearProviderEntry = (auth, provider) => {
|
|
1284
|
+
delete auth.providers[provider];
|
|
1285
|
+
};
|
|
1286
|
+
var projectAuthV2ToV1View = (auth) => {
|
|
1287
|
+
const providers = {};
|
|
1288
|
+
for (const name of Object.keys(auth.providers)) {
|
|
1289
|
+
const chatAuth = getChatProviderAuth(auth, name);
|
|
1290
|
+
if (chatAuth) {
|
|
1291
|
+
providers[name] = chatAuth;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
return { version: AUTH_VERSION_V1, providers };
|
|
1295
|
+
};
|
|
1296
|
+
var readTextIfPresent = async (filePath) => {
|
|
1297
|
+
if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
|
|
1298
|
+
try {
|
|
1299
|
+
return await fs2.readFile(filePath, "utf8");
|
|
1300
|
+
} catch (error) {
|
|
1301
|
+
if (error?.code === "ENOENT") return null;
|
|
1302
|
+
throw error;
|
|
1303
|
+
}
|
|
1166
1304
|
};
|
|
1305
|
+
var readAuthFileSyncStrict = (filePath, legacy = false) => {
|
|
1306
|
+
if (!verifyWindowsCredentialFileAclSync(filePath, legacy)) return null;
|
|
1307
|
+
let fd;
|
|
1308
|
+
try {
|
|
1309
|
+
fd = openSync(
|
|
1310
|
+
filePath,
|
|
1311
|
+
constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)
|
|
1312
|
+
);
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
if (error?.code === "ENOENT") return null;
|
|
1315
|
+
throw error;
|
|
1316
|
+
}
|
|
1317
|
+
try {
|
|
1318
|
+
const stat = fstatSync(fd);
|
|
1319
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) {
|
|
1320
|
+
throw new Error("auth.json cannot be read at approval time");
|
|
1321
|
+
}
|
|
1322
|
+
return parseAuthDocument(readFileSync(fd, "utf8")).normalized;
|
|
1323
|
+
} finally {
|
|
1324
|
+
closeSync(fd);
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
var isAuthNonEmpty = (doc) => doc !== null && Object.keys(doc.providers).length > 0;
|
|
1167
1328
|
var AuthStore = class {
|
|
1168
1329
|
paths;
|
|
1169
|
-
|
|
1330
|
+
lockOptions;
|
|
1331
|
+
storageMode;
|
|
1332
|
+
keychain;
|
|
1333
|
+
constructor(paths, options) {
|
|
1170
1334
|
this.paths = paths ?? resolveStoragePaths();
|
|
1335
|
+
this.lockOptions = options?.lock;
|
|
1336
|
+
this.storageMode = options?.storageMode;
|
|
1337
|
+
this.keychain = options?.keychain ?? new MacOsKeychainClient({
|
|
1338
|
+
credentialsDir: this.paths.credentialsDir
|
|
1339
|
+
});
|
|
1171
1340
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
return parseAuthFile(await fs2.readFile(this.paths.authFile, "utf8"));
|
|
1175
|
-
} catch (error) {
|
|
1176
|
-
return absentAuthFile(error);
|
|
1177
|
-
}
|
|
1341
|
+
lockPath() {
|
|
1342
|
+
return authLockPathFor(this.paths.credentialsDir);
|
|
1178
1343
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1344
|
+
keychainAccount() {
|
|
1345
|
+
return keychainAccountForConfigDir(this.paths.configDir);
|
|
1346
|
+
}
|
|
1347
|
+
resolveBackendUnlocked() {
|
|
1348
|
+
return coordinateCredentialBackendUnlocked({
|
|
1349
|
+
paths: this.paths,
|
|
1350
|
+
storageMode: this.storageMode,
|
|
1351
|
+
keychain: this.keychain,
|
|
1352
|
+
authAdapter: providerAuthStoreAdapter,
|
|
1353
|
+
mcpAdapter: mcpAuthStoreAdapter
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
async readFromBackend(active) {
|
|
1357
|
+
if (active === "keyring") {
|
|
1358
|
+
const text2 = await this.keychain.get(
|
|
1359
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1360
|
+
this.keychainAccount()
|
|
1186
1361
|
);
|
|
1187
|
-
|
|
1188
|
-
|
|
1362
|
+
if (text2 === null) {
|
|
1363
|
+
return { version: AUTH_VERSION_V2, providers: {} };
|
|
1364
|
+
}
|
|
1365
|
+
const parsed2 = parseAuthDocument(text2);
|
|
1366
|
+
if (parsed2.sourceVersion === 1) {
|
|
1367
|
+
await this.writeToBackend("keyring", parsed2.normalized);
|
|
1368
|
+
}
|
|
1369
|
+
return parsed2.normalized;
|
|
1189
1370
|
}
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1371
|
+
const text = await readTextIfPresent(this.paths.authFile);
|
|
1372
|
+
if (text === null) {
|
|
1373
|
+
return { version: AUTH_VERSION_V2, providers: {} };
|
|
1374
|
+
}
|
|
1375
|
+
const parsed = parseAuthDocument(text);
|
|
1376
|
+
if (parsed.sourceVersion === 1) {
|
|
1377
|
+
await this.writeToBackend("file", parsed.normalized);
|
|
1197
1378
|
}
|
|
1379
|
+
return parsed.normalized;
|
|
1198
1380
|
}
|
|
1199
|
-
async
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1381
|
+
async writeToBackend(active, auth) {
|
|
1382
|
+
if (active === "keyring") {
|
|
1383
|
+
await this.keychain.set(
|
|
1384
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1385
|
+
this.keychainAccount(),
|
|
1386
|
+
JSON.stringify(auth)
|
|
1387
|
+
);
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
await ensureStorageDirs(this.paths);
|
|
1391
|
+
const data = JSON.stringify(auth, null, 2);
|
|
1392
|
+
await writeFileAtomic(this.paths.authFile, data, { mode: 384 });
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Load normalized v2 credentials from the active backend (macOS Keychain or
|
|
1396
|
+
* protected `credentials/` file), running two-phase migration if needed.
|
|
1397
|
+
*/
|
|
1398
|
+
async loadV2() {
|
|
1399
|
+
return withAuthStoreLock(
|
|
1400
|
+
this.lockPath(),
|
|
1401
|
+
async () => {
|
|
1402
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
1403
|
+
return this.readFromBackend(resolved.active);
|
|
1404
|
+
},
|
|
1405
|
+
this.lockOptions
|
|
1206
1406
|
);
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* Synchronous v2 snapshot for a one-use local approval consumed immediately
|
|
1410
|
+
* before spawn. Fails closed (throws) on corrupt `storage-state.json`,
|
|
1411
|
+
* in-progress migrations or pending cleanup, dual-store conflicts, or
|
|
1412
|
+
* locked/unavailable/timed-out Keychain access.
|
|
1413
|
+
*/
|
|
1414
|
+
loadForApprovalV2() {
|
|
1415
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
1416
|
+
this.paths,
|
|
1417
|
+
this.storageMode
|
|
1418
|
+
);
|
|
1419
|
+
const state = readAuthStorageStateSync(this.paths.authStateFile);
|
|
1420
|
+
if (state?.status === "migrating") {
|
|
1421
|
+
throw new Error(
|
|
1422
|
+
"Credential storage migration is in progress; approval-time auth is unavailable"
|
|
1423
|
+
);
|
|
1424
|
+
}
|
|
1425
|
+
if (configured === "file" && state?.active_backend === "keyring") {
|
|
1426
|
+
throw new Error(
|
|
1427
|
+
"Credential reverse migration to file is pending; approval-time auth is unavailable"
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
const useKeychain = configured === "keyring" || configured === "auto" && state?.active_backend === "keyring";
|
|
1431
|
+
const currentFile = readAuthFileSyncStrict(this.paths.authFile);
|
|
1432
|
+
const legacyFile = readAuthFileSyncStrict(this.paths.legacyAuthFile, true);
|
|
1433
|
+
if (isAuthNonEmpty(currentFile) && isAuthNonEmpty(legacyFile) && !canonicalJsonEqual(currentFile, legacyFile)) {
|
|
1434
|
+
throw new CredentialConflictError("auth");
|
|
1435
|
+
}
|
|
1436
|
+
if (useKeychain) {
|
|
1437
|
+
const text = this.keychain.getSync(
|
|
1438
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1439
|
+
this.keychainAccount(),
|
|
1440
|
+
2e3
|
|
1441
|
+
);
|
|
1442
|
+
const keychainDoc = text === null ? { version: AUTH_VERSION_V2, providers: {} } : parseAuthDocument(text).normalized;
|
|
1443
|
+
for (const fileCandidate of [currentFile, legacyFile]) {
|
|
1444
|
+
if (isAuthNonEmpty(fileCandidate) && isAuthNonEmpty(keychainDoc) && !canonicalJsonEqual(keychainDoc, fileCandidate)) {
|
|
1445
|
+
throw new CredentialConflictError("auth");
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
return keychainDoc;
|
|
1212
1449
|
}
|
|
1450
|
+
if (isAuthNonEmpty(currentFile)) return currentFile;
|
|
1451
|
+
if (isAuthNonEmpty(legacyFile)) return legacyFile;
|
|
1452
|
+
return currentFile ?? legacyFile ?? { version: AUTH_VERSION_V2, providers: {} };
|
|
1453
|
+
}
|
|
1454
|
+
/** Legacy v1-projected read view over the underlying v2 store. */
|
|
1455
|
+
async load() {
|
|
1456
|
+
return projectAuthV2ToV1View(await this.loadV2());
|
|
1457
|
+
}
|
|
1458
|
+
/** Synchronous legacy v1-projected snapshot for approval checks. */
|
|
1459
|
+
loadForApproval() {
|
|
1460
|
+
return projectAuthV2ToV1View(this.loadForApprovalV2());
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Reload v2, mutate, and atomically save under the interprocess SQLite lock.
|
|
1464
|
+
* Skips writing if the serialized v2 document did not change.
|
|
1465
|
+
*/
|
|
1466
|
+
updateV2(mutate) {
|
|
1467
|
+
return withAuthStoreLock(
|
|
1468
|
+
this.lockPath(),
|
|
1469
|
+
async () => {
|
|
1470
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
1471
|
+
const auth = await this.readFromBackend(resolved.active);
|
|
1472
|
+
const before = JSON.stringify(auth);
|
|
1473
|
+
const result = await mutate(auth);
|
|
1474
|
+
if (JSON.stringify(auth) !== before) {
|
|
1475
|
+
await this.writeToBackend(resolved.active, auth);
|
|
1476
|
+
}
|
|
1477
|
+
return result;
|
|
1478
|
+
},
|
|
1479
|
+
this.lockOptions
|
|
1480
|
+
);
|
|
1213
1481
|
}
|
|
1214
1482
|
/**
|
|
1215
|
-
*
|
|
1216
|
-
*
|
|
1483
|
+
* Legacy v1-projected update helper. Applies v1 mutations onto the underlying
|
|
1484
|
+
* v2 document while preserving coexisting credentials on untouched slots.
|
|
1217
1485
|
*/
|
|
1218
1486
|
update(mutate) {
|
|
1219
|
-
return this.
|
|
1220
|
-
const
|
|
1221
|
-
const
|
|
1222
|
-
|
|
1487
|
+
return this.updateV2(async (v2) => {
|
|
1488
|
+
const beforeView = projectAuthV2ToV1View(v2);
|
|
1489
|
+
const workingView = {
|
|
1490
|
+
version: AUTH_VERSION_V1,
|
|
1491
|
+
providers: { ...beforeView.providers }
|
|
1492
|
+
};
|
|
1493
|
+
const result = await mutate(workingView);
|
|
1494
|
+
const touched = /* @__PURE__ */ new Set([
|
|
1495
|
+
...Object.keys(beforeView.providers),
|
|
1496
|
+
...Object.keys(workingView.providers)
|
|
1497
|
+
]);
|
|
1498
|
+
for (const name of touched) {
|
|
1499
|
+
const had = Object.hasOwn(beforeView.providers, name);
|
|
1500
|
+
const has = Object.hasOwn(workingView.providers, name);
|
|
1501
|
+
if (!has && had) {
|
|
1502
|
+
clearProviderEntry(v2, name);
|
|
1503
|
+
} else if (has) {
|
|
1504
|
+
const next = workingView.providers[name];
|
|
1505
|
+
if (!had || !canonicalJsonEqual(beforeView.providers[name], next)) {
|
|
1506
|
+
setProviderChatAuth(v2, name, next);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1223
1510
|
return result;
|
|
1224
1511
|
});
|
|
1225
1512
|
}
|
|
1226
|
-
/**
|
|
1513
|
+
/**
|
|
1514
|
+
* Locked removal of every provider across all credential locations
|
|
1515
|
+
* (`credentials/auth.json`, legacy `auth.json`, and Keychain if active/reachable).
|
|
1516
|
+
* Succeeds even when an `auth` storage conflict or corrupt file exists so
|
|
1517
|
+
* full logout always gives users a clean recovery path (never touches `mcp-auth`).
|
|
1518
|
+
*/
|
|
1227
1519
|
clearAll() {
|
|
1228
|
-
return
|
|
1229
|
-
|
|
1520
|
+
return withAuthStoreLock(
|
|
1521
|
+
this.lockPath(),
|
|
1522
|
+
async () => {
|
|
1523
|
+
await clearStoreAcrossAllLocationsUnlocked({
|
|
1524
|
+
paths: this.paths,
|
|
1525
|
+
adapter: providerAuthStoreAdapter,
|
|
1526
|
+
keychain: this.keychain
|
|
1527
|
+
});
|
|
1528
|
+
},
|
|
1529
|
+
this.lockOptions
|
|
1530
|
+
);
|
|
1531
|
+
}
|
|
1532
|
+
async saveV2(auth) {
|
|
1533
|
+
await withAuthStoreLock(
|
|
1534
|
+
this.lockPath(),
|
|
1535
|
+
async () => {
|
|
1536
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
1537
|
+
await this.writeToBackend(resolved.active, auth);
|
|
1538
|
+
},
|
|
1539
|
+
this.lockOptions
|
|
1230
1540
|
);
|
|
1231
1541
|
}
|
|
1232
1542
|
async save(auth) {
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
await fs2.writeFile(this.paths.authFile, data, { mode: 384 });
|
|
1236
|
-
try {
|
|
1237
|
-
await fs2.chmod(this.paths.authFile, 384);
|
|
1238
|
-
} catch {
|
|
1239
|
-
}
|
|
1543
|
+
const normalized = normalizeAuthFileToV2(auth);
|
|
1544
|
+
await this.saveV2(normalized);
|
|
1240
1545
|
}
|
|
1241
1546
|
};
|
|
1242
1547
|
|
|
@@ -1276,8 +1581,9 @@ var configuredApiKeyAuth = (provider, apiKey) => {
|
|
|
1276
1581
|
};
|
|
1277
1582
|
};
|
|
1278
1583
|
var readConfiguredProviderAuth = (provider) => {
|
|
1279
|
-
const
|
|
1280
|
-
|
|
1584
|
+
const auth = new AuthStore().loadForApprovalV2();
|
|
1585
|
+
const chatAuth = getChatProviderAuth(auth, provider);
|
|
1586
|
+
if (chatAuth) return chatAuth;
|
|
1281
1587
|
const apiKey = readProviderEnvApiKey(provider);
|
|
1282
1588
|
return apiKey ? configuredApiKeyAuth(provider, apiKey) : void 0;
|
|
1283
1589
|
};
|
|
@@ -1308,12 +1614,12 @@ var AuthResolver = class _AuthResolver {
|
|
|
1308
1614
|
}
|
|
1309
1615
|
static async create(state, log2, providers = {}) {
|
|
1310
1616
|
const store = new AuthStore();
|
|
1311
|
-
const auth = await store.
|
|
1617
|
+
const auth = await store.loadV2();
|
|
1312
1618
|
return new _AuthResolver(state, log2, store, auth, providers);
|
|
1313
1619
|
}
|
|
1314
1620
|
hasAnyAvailableAuth() {
|
|
1315
1621
|
return this.availableProviders.some((provider) => {
|
|
1316
|
-
if (this.auth
|
|
1622
|
+
if (getChatProviderAuth(this.auth, provider)) return true;
|
|
1317
1623
|
return Boolean(this.envApiKey(provider));
|
|
1318
1624
|
});
|
|
1319
1625
|
}
|
|
@@ -1323,7 +1629,7 @@ var AuthResolver = class _AuthResolver {
|
|
|
1323
1629
|
throw new Error(`Unsupported model.provider: ${preferred}`);
|
|
1324
1630
|
if (preferredProvider) return preferredProvider;
|
|
1325
1631
|
const providersWithAuth = this.availableProviders.filter(
|
|
1326
|
-
(provider) => !!this.auth
|
|
1632
|
+
(provider) => !!getChatProviderAuth(this.auth, provider)
|
|
1327
1633
|
);
|
|
1328
1634
|
if (providersWithAuth.length === 1) {
|
|
1329
1635
|
return providersWithAuth[0];
|
|
@@ -1354,13 +1660,11 @@ var AuthResolver = class _AuthResolver {
|
|
|
1354
1660
|
async resolveProviderAuth(provider) {
|
|
1355
1661
|
if (!this.availableProviders.includes(provider))
|
|
1356
1662
|
throw new Error(`Unsupported provider: ${provider}`);
|
|
1357
|
-
const existing = this.auth
|
|
1663
|
+
const existing = getChatProviderAuth(this.auth, provider);
|
|
1358
1664
|
if (existing) return existing;
|
|
1359
1665
|
const envValue = this.envApiKey(provider);
|
|
1360
1666
|
if (envValue) {
|
|
1361
|
-
|
|
1362
|
-
await this.setProviderAuth(provider, auth);
|
|
1363
|
-
return auth;
|
|
1667
|
+
return configuredApiKeyAuth(provider, envValue);
|
|
1364
1668
|
}
|
|
1365
1669
|
if (provider === "openai") {
|
|
1366
1670
|
return this.promptOpenAiAuth();
|
|
@@ -1395,7 +1699,7 @@ var AuthResolver = class _AuthResolver {
|
|
|
1395
1699
|
if (options?.matches && !options.matches(oauth3))
|
|
1396
1700
|
throw new Error("OpenAI OAuth account changed");
|
|
1397
1701
|
};
|
|
1398
|
-
const entry = this.auth
|
|
1702
|
+
const entry = getChatProviderAuth(this.auth, "openai");
|
|
1399
1703
|
if (entry?.method !== "oauth") {
|
|
1400
1704
|
throw new Error("OpenAI OAuth is not configured");
|
|
1401
1705
|
}
|
|
@@ -1403,15 +1707,15 @@ var AuthResolver = class _AuthResolver {
|
|
|
1403
1707
|
options?.signal?.throwIfAborted();
|
|
1404
1708
|
checkAccount(oauth2);
|
|
1405
1709
|
if (oauth2.expires_at <= Date.now() + 6e4) {
|
|
1406
|
-
|
|
1407
|
-
const current = auth
|
|
1710
|
+
const updated = await this.store.updateV2(async (auth) => {
|
|
1711
|
+
const current = getChatProviderAuth(auth, "openai");
|
|
1408
1712
|
if (current?.method !== "oauth") {
|
|
1409
1713
|
throw new Error("OpenAI OAuth is not configured");
|
|
1410
1714
|
}
|
|
1411
1715
|
options?.signal?.throwIfAborted();
|
|
1412
1716
|
checkAccount(current.oauth);
|
|
1413
1717
|
if (current.oauth.expires_at > Date.now() + 6e4) {
|
|
1414
|
-
return current.oauth;
|
|
1718
|
+
return { oauth: current.oauth, auth };
|
|
1415
1719
|
}
|
|
1416
1720
|
this.log("refreshing OpenAI OAuth token");
|
|
1417
1721
|
const tokens = await refreshAccessToken(current.oauth.refresh_token);
|
|
@@ -1423,10 +1727,13 @@ var AuthResolver = class _AuthResolver {
|
|
|
1423
1727
|
...accountId ? { account_id: accountId } : {}
|
|
1424
1728
|
};
|
|
1425
1729
|
checkAccount(refreshed);
|
|
1426
|
-
auth
|
|
1427
|
-
|
|
1730
|
+
if (!updateProviderOAuthTokens(auth, "openai", refreshed)) {
|
|
1731
|
+
throw new Error("OpenAI OAuth is not configured");
|
|
1732
|
+
}
|
|
1733
|
+
return { oauth: refreshed, auth };
|
|
1428
1734
|
});
|
|
1429
|
-
|
|
1735
|
+
oauth2 = updated.oauth;
|
|
1736
|
+
this.auth = updated.auth;
|
|
1430
1737
|
}
|
|
1431
1738
|
options?.signal?.throwIfAborted();
|
|
1432
1739
|
return { token: oauth2.access_token, accountId: oauth2.account_id };
|
|
@@ -1616,8 +1923,8 @@ var AuthResolver = class _AuthResolver {
|
|
|
1616
1923
|
return auth;
|
|
1617
1924
|
}
|
|
1618
1925
|
async setProviderAuth(provider, auth) {
|
|
1619
|
-
this.auth = await this.store.
|
|
1620
|
-
latest
|
|
1926
|
+
this.auth = await this.store.updateV2((latest) => {
|
|
1927
|
+
setProviderChatAuth(latest, provider, auth);
|
|
1621
1928
|
return latest;
|
|
1622
1929
|
});
|
|
1623
1930
|
}
|
|
@@ -1626,14 +1933,15 @@ var AuthResolver = class _AuthResolver {
|
|
|
1626
1933
|
// src/permissions/shell-backend.ts
|
|
1627
1934
|
import { spawn as spawn4, spawnSync as spawnSync3 } from "child_process";
|
|
1628
1935
|
import {
|
|
1629
|
-
lstatSync as
|
|
1936
|
+
lstatSync as lstatSync9,
|
|
1937
|
+
mkdirSync as mkdirSync2,
|
|
1630
1938
|
mkdtempSync as mkdtempSync2,
|
|
1631
|
-
realpathSync as
|
|
1939
|
+
realpathSync as realpathSync8,
|
|
1632
1940
|
rmSync as rmSync2,
|
|
1633
1941
|
statSync as statSync5
|
|
1634
1942
|
} from "fs";
|
|
1635
|
-
import
|
|
1636
|
-
import
|
|
1943
|
+
import os2 from "os";
|
|
1944
|
+
import path13 from "path";
|
|
1637
1945
|
import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
|
|
1638
1946
|
|
|
1639
1947
|
// src/sandbox/file-mutation-helper.ts
|
|
@@ -1939,25 +2247,171 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
|
|
|
1939
2247
|
var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
|
|
1940
2248
|
var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
|
|
1941
2249
|
|
|
2250
|
+
// src/permissions/home-dot-paths.ts
|
|
2251
|
+
import { readdirSync as readdirSync2, readlinkSync as readlinkSync2 } from "fs";
|
|
2252
|
+
import os from "os";
|
|
2253
|
+
import path6 from "path";
|
|
2254
|
+
|
|
2255
|
+
// src/permissions/resource-paths.ts
|
|
2256
|
+
import {
|
|
2257
|
+
lstatSync as lstatSync2,
|
|
2258
|
+
opendirSync,
|
|
2259
|
+
readlinkSync,
|
|
2260
|
+
realpathSync as realpathSync2
|
|
2261
|
+
} from "fs";
|
|
2262
|
+
import path5 from "path";
|
|
2263
|
+
var lookup = (pathname) => lstatSync2(pathname, { bigint: true, throwIfNoEntry: false });
|
|
2264
|
+
var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
|
|
2265
|
+
var comparableResourceName = (pathname) => {
|
|
2266
|
+
const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
|
|
2267
|
+
return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
|
|
2268
|
+
};
|
|
2269
|
+
function distinguishesAsciiCase(parent) {
|
|
2270
|
+
try {
|
|
2271
|
+
const directory = opendirSync(parent);
|
|
2272
|
+
try {
|
|
2273
|
+
for (let index = 0; index < 16; index++) {
|
|
2274
|
+
const name = directory.readSync()?.name;
|
|
2275
|
+
if (!name) break;
|
|
2276
|
+
const changed = name.replace(
|
|
2277
|
+
/[A-Za-z]/u,
|
|
2278
|
+
(letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
|
|
2279
|
+
);
|
|
2280
|
+
if (name === changed) continue;
|
|
2281
|
+
const original = lookup(path5.join(parent, name));
|
|
2282
|
+
const alternate = lookup(path5.join(parent, changed));
|
|
2283
|
+
if (original) return !alternate || !sameEntry(original, alternate);
|
|
2284
|
+
}
|
|
2285
|
+
} finally {
|
|
2286
|
+
directory.closeSync();
|
|
2287
|
+
}
|
|
2288
|
+
} catch {
|
|
2289
|
+
}
|
|
2290
|
+
return false;
|
|
2291
|
+
}
|
|
2292
|
+
function resourceContainsPath(resource, target) {
|
|
2293
|
+
if (target === resource || target.startsWith(
|
|
2294
|
+
resource.endsWith(path5.sep) ? resource : `${resource}${path5.sep}`
|
|
2295
|
+
))
|
|
2296
|
+
return true;
|
|
2297
|
+
const root = path5.parse(resource).root;
|
|
2298
|
+
const targetRoot = path5.parse(target).root;
|
|
2299
|
+
if (comparableResourceName(root) !== comparableResourceName(targetRoot))
|
|
2300
|
+
return false;
|
|
2301
|
+
const parts = resource.slice(root.length).split(path5.sep);
|
|
2302
|
+
const overlapping = target.slice(targetRoot.length).split(path5.sep).slice(0, parts.length);
|
|
2303
|
+
if (overlapping.length !== parts.length) return false;
|
|
2304
|
+
const candidate = path5.join(targetRoot, ...overlapping);
|
|
2305
|
+
const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
|
|
2306
|
+
try {
|
|
2307
|
+
const targetEntry = lookup(candidate);
|
|
2308
|
+
if (!targetEntry && !namesMayMatch) return false;
|
|
2309
|
+
const protectedEntry = lookup(resource);
|
|
2310
|
+
if (protectedEntry || targetEntry)
|
|
2311
|
+
return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
|
|
2312
|
+
if (!namesMayMatch) return false;
|
|
2313
|
+
const parent = path5.dirname(resource);
|
|
2314
|
+
return path5.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(path5.basename(resource)) || !/^[\x20-\x7e]+$/u.test(path5.basename(candidate)) || path5.basename(resource).toLowerCase() !== path5.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
|
|
2315
|
+
} catch {
|
|
2316
|
+
return namesMayMatch;
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
var missing = (error) => error.code === "ENOENT";
|
|
2320
|
+
function resolveReservedTarget(target, remaining = 64) {
|
|
2321
|
+
if (!remaining) throw new Error("reserved_path_unresolved");
|
|
2322
|
+
try {
|
|
2323
|
+
return realpathSync2(target);
|
|
2324
|
+
} catch (error) {
|
|
2325
|
+
const parent = path5.dirname(target);
|
|
2326
|
+
if (!missing(error) || parent === target) throw error;
|
|
2327
|
+
const canonicalParent = resolveReservedTarget(parent, remaining - 1);
|
|
2328
|
+
if (!lstatSync2(target, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
2329
|
+
return path5.join(canonicalParent, path5.basename(target));
|
|
2330
|
+
const referent = readlinkSync(target);
|
|
2331
|
+
let seenName = false;
|
|
2332
|
+
for (const part of referent.split(
|
|
2333
|
+
process.platform === "win32" ? /[\\/]/u : "/"
|
|
2334
|
+
)) {
|
|
2335
|
+
if (part === ".." && seenName)
|
|
2336
|
+
throw new Error("reserved_path_unresolved");
|
|
2337
|
+
if (part && part !== "." && part !== "..") seenName = true;
|
|
2338
|
+
}
|
|
2339
|
+
return resolveReservedTarget(
|
|
2340
|
+
path5.resolve(canonicalParent, referent),
|
|
2341
|
+
remaining - 1
|
|
2342
|
+
);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
// src/permissions/home-dot-paths.ts
|
|
2347
|
+
var homeDotDirectory = (writeRoots, home = os.homedir()) => {
|
|
2348
|
+
if (!writeRoots.length) return void 0;
|
|
2349
|
+
const canonicalHome = resolveReservedTarget(home);
|
|
2350
|
+
return writeRoots.some(
|
|
2351
|
+
(root) => resourceContainsPath(resolveReservedTarget(root), canonicalHome)
|
|
2352
|
+
) ? canonicalHome : void 0;
|
|
2353
|
+
};
|
|
2354
|
+
var isHomeDotTarget = (home, target, platform = process.platform) => {
|
|
2355
|
+
if (!resourceContainsPath(home, target)) return false;
|
|
2356
|
+
const root = path6.parse(home).root;
|
|
2357
|
+
const depth = home.slice(root.length).split(path6.sep).filter(Boolean).length;
|
|
2358
|
+
const first = target.slice(path6.parse(target).root.length).split(path6.sep).filter(Boolean)[depth];
|
|
2359
|
+
return !!first && (first.startsWith(".") || platform === "darwin" && resourceContainsPath(path6.join(home, "Library"), target));
|
|
2360
|
+
};
|
|
2361
|
+
var hasClosedHomeDotCycle = (home, start) => {
|
|
2362
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2363
|
+
let current = start;
|
|
2364
|
+
while (seen.size < 64) {
|
|
2365
|
+
if (seen.has(current)) return true;
|
|
2366
|
+
seen.add(current);
|
|
2367
|
+
let link;
|
|
2368
|
+
try {
|
|
2369
|
+
link = readlinkSync2(current);
|
|
2370
|
+
} catch {
|
|
2371
|
+
return false;
|
|
2372
|
+
}
|
|
2373
|
+
const next = path6.resolve(home, link);
|
|
2374
|
+
const name = path6.basename(next);
|
|
2375
|
+
if (path6.dirname(next) !== home || !isHomeDotTarget(home, next) || link !== next && link !== name && link !== `.${path6.sep}${name}`)
|
|
2376
|
+
return false;
|
|
2377
|
+
current = next;
|
|
2378
|
+
}
|
|
2379
|
+
return false;
|
|
2380
|
+
};
|
|
2381
|
+
var homeDotLinkTargets = (home) => readdirSync2(home, { withFileTypes: true }).filter(
|
|
2382
|
+
(entry) => entry.isSymbolicLink() && isHomeDotTarget(home, path6.join(home, entry.name))
|
|
2383
|
+
).flatMap((entry) => {
|
|
2384
|
+
const link = path6.join(home, entry.name);
|
|
2385
|
+
try {
|
|
2386
|
+
return [resolveReservedTarget(link)];
|
|
2387
|
+
} catch (error) {
|
|
2388
|
+
if (error.code === "ELOOP" && hasClosedHomeDotCycle(home, link))
|
|
2389
|
+
return [];
|
|
2390
|
+
throw error;
|
|
2391
|
+
}
|
|
2392
|
+
});
|
|
2393
|
+
var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
|
|
2394
|
+
|
|
1942
2395
|
// src/permissions/linux-shell-backend.ts
|
|
1943
2396
|
import { spawn as spawn2, spawnSync } from "child_process";
|
|
1944
2397
|
import {
|
|
1945
2398
|
accessSync as accessSync2,
|
|
1946
2399
|
constants as constants4,
|
|
2400
|
+
lstatSync as lstatSync5,
|
|
1947
2401
|
mkdirSync,
|
|
1948
2402
|
mkdtempSync,
|
|
1949
|
-
readdirSync as
|
|
2403
|
+
readdirSync as readdirSync5,
|
|
1950
2404
|
readFileSync as readFileSync3,
|
|
1951
|
-
realpathSync as
|
|
2405
|
+
realpathSync as realpathSync5,
|
|
1952
2406
|
rmSync,
|
|
1953
2407
|
statSync as statSync3,
|
|
1954
2408
|
writeFileSync
|
|
1955
2409
|
} from "fs";
|
|
1956
|
-
import
|
|
2410
|
+
import path10 from "path";
|
|
1957
2411
|
|
|
1958
2412
|
// src/permissions/linux-mountinfo.ts
|
|
1959
2413
|
import { readFileSync as readFileSync2 } from "fs";
|
|
1960
|
-
import
|
|
2414
|
+
import path7 from "path";
|
|
1961
2415
|
var within = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
|
|
1962
2416
|
var replacedSystemTrees = ["/proc", "/dev", "/sys"];
|
|
1963
2417
|
function parseMountInfo(text) {
|
|
@@ -2012,7 +2466,7 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
|
|
|
2012
2466
|
/[ \t\n\\]/g,
|
|
2013
2467
|
(char) => `\\${char.charCodeAt(0).toString(8).padStart(3, "0")}`
|
|
2014
2468
|
);
|
|
2015
|
-
const parent =
|
|
2469
|
+
const parent = path7.posix.dirname(executable);
|
|
2016
2470
|
const mounts = parseMountInfo(text);
|
|
2017
2471
|
const ancestors = mounts.filter(({ target }) => within(target, parent)).sort((left, right) => right.target.length - left.target.length);
|
|
2018
2472
|
const [selected] = ancestors;
|
|
@@ -2021,11 +2475,11 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
|
|
|
2021
2475
|
))
|
|
2022
2476
|
throw new Error("unbound_executable_mount");
|
|
2023
2477
|
checkMountViews([selected]);
|
|
2024
|
-
const installed =
|
|
2478
|
+
const installed = path7.posix.join(
|
|
2025
2479
|
selected.root,
|
|
2026
|
-
|
|
2480
|
+
path7.posix.relative(selected.target, parent)
|
|
2027
2481
|
);
|
|
2028
|
-
const directChild = (directory, entry) => entry !== directory &&
|
|
2482
|
+
const directChild = (directory, entry) => entry !== directory && path7.posix.dirname(entry) === directory;
|
|
2029
2483
|
const directMounts = mounts.filter(
|
|
2030
2484
|
({ target }) => directChild(parent, target)
|
|
2031
2485
|
);
|
|
@@ -2042,17 +2496,17 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
|
|
|
2042
2496
|
|
|
2043
2497
|
// src/permissions/protected-aliases.ts
|
|
2044
2498
|
import {
|
|
2045
|
-
lstatSync as
|
|
2046
|
-
readdirSync as
|
|
2047
|
-
realpathSync as
|
|
2499
|
+
lstatSync as lstatSync3,
|
|
2500
|
+
readdirSync as readdirSync3,
|
|
2501
|
+
realpathSync as realpathSync3
|
|
2048
2502
|
} from "fs";
|
|
2049
|
-
import
|
|
2503
|
+
import path8 from "path";
|
|
2050
2504
|
var maxEntries = 4096;
|
|
2051
2505
|
var inode = (stat) => `${stat.dev}:${stat.ino}`;
|
|
2052
2506
|
function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
|
|
2053
2507
|
const pending = roots.map((entry) => {
|
|
2054
2508
|
try {
|
|
2055
|
-
return
|
|
2509
|
+
return realpathSync3(entry);
|
|
2056
2510
|
} catch (error) {
|
|
2057
2511
|
if (error.code === "ENOENT") return entry;
|
|
2058
2512
|
throw error;
|
|
@@ -2068,7 +2522,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
|
|
|
2068
2522
|
const target = hooks.get(file);
|
|
2069
2523
|
if (!target) return false;
|
|
2070
2524
|
try {
|
|
2071
|
-
return
|
|
2525
|
+
return realpathSync3(file) === target && lstatSync3(target).isFile();
|
|
2072
2526
|
} catch {
|
|
2073
2527
|
return false;
|
|
2074
2528
|
}
|
|
@@ -2080,18 +2534,18 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
|
|
|
2080
2534
|
if (visited.size > entryLimit)
|
|
2081
2535
|
throw new Error("protected_alias_index_unavailable");
|
|
2082
2536
|
try {
|
|
2083
|
-
const metadata =
|
|
2537
|
+
const metadata = lstatSync3(file, { bigint: true });
|
|
2084
2538
|
if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
|
|
2085
2539
|
if (metadata.isSymbolicLink() && ignored.size) {
|
|
2086
2540
|
if (verifiedHook(file)) continue;
|
|
2087
2541
|
pending.push(...ignored);
|
|
2088
2542
|
ignored.clear();
|
|
2089
2543
|
} else if (metadata.isDirectory()) {
|
|
2090
|
-
const children =
|
|
2544
|
+
const children = readdirSync3(file);
|
|
2091
2545
|
if (children.length + pending.length + visited.size > entryLimit)
|
|
2092
2546
|
throw new Error("protected_alias_index_unavailable");
|
|
2093
2547
|
for (const name of children) {
|
|
2094
|
-
const child =
|
|
2548
|
+
const child = path8.join(file, name);
|
|
2095
2549
|
if (!ignored.has(child)) pending.push(child);
|
|
2096
2550
|
}
|
|
2097
2551
|
}
|
|
@@ -2365,28 +2819,28 @@ var analyzeShell = (invocation) => {
|
|
|
2365
2819
|
import {
|
|
2366
2820
|
accessSync,
|
|
2367
2821
|
constants as constants3,
|
|
2368
|
-
lstatSync as
|
|
2369
|
-
readdirSync as
|
|
2370
|
-
readlinkSync,
|
|
2371
|
-
realpathSync as
|
|
2822
|
+
lstatSync as lstatSync4,
|
|
2823
|
+
readdirSync as readdirSync4,
|
|
2824
|
+
readlinkSync as readlinkSync3,
|
|
2825
|
+
realpathSync as realpathSync4,
|
|
2372
2826
|
statSync as statSync2
|
|
2373
2827
|
} from "fs";
|
|
2374
|
-
import
|
|
2375
|
-
var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(
|
|
2376
|
-
var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(
|
|
2828
|
+
import path9 from "path";
|
|
2829
|
+
var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path9.delimiter));
|
|
2830
|
+
var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path9.delimiter);
|
|
2377
2831
|
var resolveShellExecutable = (name, paths, cwd = process.cwd()) => {
|
|
2378
|
-
if (!name || name.includes("\0") || !
|
|
2832
|
+
if (!name || name.includes("\0") || !path9.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
|
|
2379
2833
|
throw new Error("invalid_executable");
|
|
2380
|
-
const executable = process.platform === "win32" && !
|
|
2381
|
-
const candidates =
|
|
2834
|
+
const executable = process.platform === "win32" && !path9.extname(name) ? `${name}.exe` : name;
|
|
2835
|
+
const candidates = path9.isAbsolute(executable) ? [executable] : paths.map((entry) => {
|
|
2382
2836
|
const directory = process.platform === "win32" && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
|
|
2383
|
-
const resolved =
|
|
2384
|
-
return `${resolved}${
|
|
2837
|
+
const resolved = path9.isAbsolute(directory) ? directory : `${cwd}${path9.sep}${directory || "."}`;
|
|
2838
|
+
return `${resolved}${path9.sep}${executable}`;
|
|
2385
2839
|
});
|
|
2386
2840
|
for (const candidate of candidates) {
|
|
2387
2841
|
try {
|
|
2388
2842
|
accessSync(candidate, constants3.X_OK);
|
|
2389
|
-
const actual =
|
|
2843
|
+
const actual = realpathSync4(candidate);
|
|
2390
2844
|
if (statSync2(actual).isFile()) return actual;
|
|
2391
2845
|
} catch {
|
|
2392
2846
|
}
|
|
@@ -2401,11 +2855,11 @@ var inspectBashPath = (candidate, policy) => {
|
|
|
2401
2855
|
while (components.length) {
|
|
2402
2856
|
const component = components.shift();
|
|
2403
2857
|
if (!component || component === ".") continue;
|
|
2404
|
-
const name =
|
|
2858
|
+
const name = path9.join(current, component);
|
|
2405
2859
|
const restriction = policy(name);
|
|
2406
2860
|
if (restriction === "unbound") throw new Error("unbound_shell_path");
|
|
2407
2861
|
masked ||= restriction === "masked";
|
|
2408
|
-
const entry =
|
|
2862
|
+
const entry = lstatSync4(name, { throwIfNoEntry: false });
|
|
2409
2863
|
if (!entry) return void 0;
|
|
2410
2864
|
if (!entry.isSymbolicLink()) {
|
|
2411
2865
|
if (components.length && !entry.isDirectory()) return void 0;
|
|
@@ -2413,24 +2867,24 @@ var inspectBashPath = (candidate, policy) => {
|
|
|
2413
2867
|
continue;
|
|
2414
2868
|
}
|
|
2415
2869
|
if (++links > 40) throw new Error("unbound_shell_path");
|
|
2416
|
-
const destination =
|
|
2417
|
-
if (
|
|
2870
|
+
const destination = readlinkSync3(name);
|
|
2871
|
+
if (path9.isAbsolute(destination)) current = "/";
|
|
2418
2872
|
components = [...destination.split("/"), ...components];
|
|
2419
2873
|
}
|
|
2420
2874
|
return { file: current, masked };
|
|
2421
2875
|
};
|
|
2422
2876
|
var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
|
|
2423
|
-
const absolute =
|
|
2877
|
+
const absolute = path9.isAbsolute(name);
|
|
2424
2878
|
try {
|
|
2425
2879
|
for (const directory of absolute ? [""] : paths) {
|
|
2426
|
-
if (!absolute && (!
|
|
2880
|
+
if (!absolute && (!path9.isAbsolute(directory) || directory.split("/").includes("..")))
|
|
2427
2881
|
return void 0;
|
|
2428
2882
|
const inspected = inspectBashPath(
|
|
2429
2883
|
absolute ? name : `${directory}/${name}`,
|
|
2430
2884
|
policy
|
|
2431
2885
|
);
|
|
2432
2886
|
if (!inspected) continue;
|
|
2433
|
-
const executable =
|
|
2887
|
+
const executable = realpathSync4(inspected.file);
|
|
2434
2888
|
const restriction = policy(executable);
|
|
2435
2889
|
if (restriction === "unbound") return void 0;
|
|
2436
2890
|
const info = statSync2(executable, { bigint: true });
|
|
@@ -2456,11 +2910,11 @@ var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
|
|
|
2456
2910
|
};
|
|
2457
2911
|
function bindKnownSystemExecutable(program, paths, policy, directArgv) {
|
|
2458
2912
|
if (process.platform === "win32") return void 0;
|
|
2459
|
-
const name =
|
|
2913
|
+
const name = path9.basename(program);
|
|
2460
2914
|
const known = new Set(
|
|
2461
2915
|
[`/usr/bin/${name}`, `/bin/${name}`].flatMap((entry) => {
|
|
2462
2916
|
try {
|
|
2463
|
-
return [
|
|
2917
|
+
return [realpathSync4(entry)];
|
|
2464
2918
|
} catch {
|
|
2465
2919
|
return [];
|
|
2466
2920
|
}
|
|
@@ -2482,22 +2936,22 @@ var isRootControlledSharedExecutable = (file, info) => {
|
|
|
2482
2936
|
var sameLinkMetadata = (left, right) => left.dev === right.dev && left.ino === right.ino && left.nlink === right.nlink && left.mode === right.mode && left.uid === right.uid && left.gid === right.gid && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
|
|
2483
2937
|
function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
|
|
2484
2938
|
try {
|
|
2485
|
-
const parent =
|
|
2486
|
-
if (policy(parent) ||
|
|
2487
|
-
const directory =
|
|
2488
|
-
const executable =
|
|
2939
|
+
const parent = path9.dirname(file);
|
|
2940
|
+
if (policy(parent) || realpathSync4(parent) !== parent) return false;
|
|
2941
|
+
const directory = lstatSync4(parent, { bigint: true });
|
|
2942
|
+
const executable = lstatSync4(file, { bigint: true });
|
|
2489
2943
|
if (!directory.isDirectory() || !executable.isFile() || !sameLinkMetadata(executable, info) || executable.nlink < 2n)
|
|
2490
2944
|
return false;
|
|
2491
2945
|
const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
|
|
2492
2946
|
let links = 0n;
|
|
2493
2947
|
let foundExecutable = false;
|
|
2494
|
-
const entries =
|
|
2948
|
+
const entries = readdirSync4(parent, { encoding: "buffer" });
|
|
2495
2949
|
if (entries.length > 4096) return false;
|
|
2496
2950
|
for (const entry of entries) {
|
|
2497
2951
|
const name = entry.toString();
|
|
2498
2952
|
if (!Buffer.from(name).equals(entry)) return false;
|
|
2499
|
-
const peer =
|
|
2500
|
-
const peerInfo =
|
|
2953
|
+
const peer = path9.join(parent, name);
|
|
2954
|
+
const peerInfo = lstatSync4(peer, { bigint: true });
|
|
2501
2955
|
if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
|
|
2502
2956
|
continue;
|
|
2503
2957
|
if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
|
|
@@ -2505,7 +2959,7 @@ function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
|
|
|
2505
2959
|
foundExecutable ||= peer === file;
|
|
2506
2960
|
links++;
|
|
2507
2961
|
}
|
|
2508
|
-
return foundExecutable && links === executable.nlink &&
|
|
2962
|
+
return foundExecutable && links === executable.nlink && realpathSync4(parent) === parent && sameLinkMetadata(directory, lstatSync4(parent, { bigint: true })) && sameLinkMetadata(executable, lstatSync4(file, { bigint: true })) && (mounts === void 0 || executableMountSnapshot(file, executable.dev) === mounts);
|
|
2509
2963
|
} catch {
|
|
2510
2964
|
return false;
|
|
2511
2965
|
}
|
|
@@ -2525,7 +2979,7 @@ var notWritable = (file) => {
|
|
|
2525
2979
|
var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
|
|
2526
2980
|
var virtualRoots = ["/proc", "/dev", "/sys"];
|
|
2527
2981
|
var managedTool = (name) => {
|
|
2528
|
-
const resolved =
|
|
2982
|
+
const resolved = realpathSync5(name);
|
|
2529
2983
|
let current = resolved;
|
|
2530
2984
|
for (; ; ) {
|
|
2531
2985
|
const info = statSync3(current);
|
|
@@ -2534,18 +2988,18 @@ var managedTool = (name) => {
|
|
|
2534
2988
|
if (current === resolved && (!info.isFile() || (info.mode & 73) === 0))
|
|
2535
2989
|
throw new Error("sandbox_executable_unavailable");
|
|
2536
2990
|
if (current === "/") return resolved;
|
|
2537
|
-
current =
|
|
2991
|
+
current = path10.dirname(current);
|
|
2538
2992
|
}
|
|
2539
2993
|
};
|
|
2540
2994
|
var masksFor = (policy) => {
|
|
2541
2995
|
const paths = /* @__PURE__ */ new Set();
|
|
2542
2996
|
for (const item of [...policy.protectedPaths, "/run"]) {
|
|
2543
|
-
if (!
|
|
2997
|
+
if (!path10.isAbsolute(item) || item !== path10.normalize(item) || item === "/")
|
|
2544
2998
|
throw new Error("invalid_protected_path");
|
|
2545
2999
|
if (item === "/dev") continue;
|
|
2546
3000
|
let resolved;
|
|
2547
3001
|
try {
|
|
2548
|
-
resolved =
|
|
3002
|
+
resolved = realpathSync5(item);
|
|
2549
3003
|
} catch (error) {
|
|
2550
3004
|
if (error.code !== "ENOENT") throw error;
|
|
2551
3005
|
resolved = item;
|
|
@@ -2560,10 +3014,28 @@ var masksFor = (policy) => {
|
|
|
2560
3014
|
}
|
|
2561
3015
|
return selected;
|
|
2562
3016
|
};
|
|
2563
|
-
var
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
3017
|
+
var readOnlyMount = (entry, projectedHome) => {
|
|
3018
|
+
try {
|
|
3019
|
+
if (realpathSync5(entry) !== entry)
|
|
3020
|
+
throw new Error("unbound_read_only_path");
|
|
3021
|
+
return entry;
|
|
3022
|
+
} catch (error) {
|
|
3023
|
+
if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
|
|
3024
|
+
throw error;
|
|
3025
|
+
}
|
|
3026
|
+
let parent = path10.dirname(entry);
|
|
3027
|
+
while (within2(projectedHome, parent)) {
|
|
3028
|
+
const info = lstatSync5(parent, { throwIfNoEntry: false });
|
|
3029
|
+
if (info) {
|
|
3030
|
+
if (info.isDirectory() && realpathSync5(parent) === parent) return parent;
|
|
3031
|
+
break;
|
|
3032
|
+
}
|
|
3033
|
+
if (parent === projectedHome) break;
|
|
3034
|
+
parent = path10.dirname(parent);
|
|
3035
|
+
}
|
|
3036
|
+
throw new Error("unbound_read_only_path");
|
|
3037
|
+
};
|
|
3038
|
+
var linuxRunscMountArgs = (policy, state, masks) => {
|
|
2567
3039
|
const mountpoints = masks.map((target) => {
|
|
2568
3040
|
const info = statSync3(target, { throwIfNoEntry: false });
|
|
2569
3041
|
if (!info) throw new Error("missing_protected_mountpoint");
|
|
@@ -2574,13 +3046,89 @@ var prepare = (policy, state, runsc, unshare) => {
|
|
|
2574
3046
|
placeholder: info.isDirectory() ? "empty-dir" : "empty-file"
|
|
2575
3047
|
};
|
|
2576
3048
|
});
|
|
3049
|
+
const readOnly = policy.readOnlyPaths ?? [];
|
|
3050
|
+
const home = policy.homeDotDirectory;
|
|
3051
|
+
const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
|
|
3052
|
+
const protectedTargets = [...masks, ...readOnly];
|
|
3053
|
+
const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
|
|
3054
|
+
const writableRoots = /* @__PURE__ */ new Set();
|
|
3055
|
+
const flags = ["--ro-bind", "/", "/", "--ro-bind", "/tmp", "/tmp"];
|
|
3056
|
+
for (const root of policy.writeRoots) {
|
|
3057
|
+
if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
|
|
3058
|
+
throw new Error("unsupported_home_write_root");
|
|
3059
|
+
if (root === "/" || realpathSync5(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
|
|
3060
|
+
throw new Error("invalid_write_root");
|
|
3061
|
+
if (within2(state, root)) continue;
|
|
3062
|
+
if (masks.some((mask) => within2(mask, root)))
|
|
3063
|
+
throw new Error("invalid_write_root");
|
|
3064
|
+
if (readOnly.some((entry) => within2(entry, root))) continue;
|
|
3065
|
+
if (root !== home) writableRoots.add(root);
|
|
3066
|
+
}
|
|
3067
|
+
if (projectedHome) {
|
|
3068
|
+
if (projectedHome !== "/tmp")
|
|
3069
|
+
flags.push("--ro-bind", projectedHome, projectedHome);
|
|
3070
|
+
for (const name of readdirSync5(projectedHome)) {
|
|
3071
|
+
const child = path10.join(projectedHome, name);
|
|
3072
|
+
if (child === state || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
|
|
3073
|
+
continue;
|
|
3074
|
+
const info = lstatSync5(child, { throwIfNoEntry: false });
|
|
3075
|
+
if ((info?.isDirectory() || info?.isFile()) && realpathSync5(child) === child)
|
|
3076
|
+
writableRoots.add(child);
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
const readOnlyMounts = /* @__PURE__ */ new Set();
|
|
3080
|
+
const proposedRoots = [...writableRoots];
|
|
3081
|
+
for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
|
|
3082
|
+
if (!masks.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
|
|
3083
|
+
readOnlyMounts.add(readOnlyMount(entry, projectedHome));
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
protectedTargets.push(...readOnlyMounts);
|
|
3087
|
+
for (const root of writableRoots) {
|
|
3088
|
+
if (covered(root)) writableRoots.delete(root);
|
|
3089
|
+
}
|
|
3090
|
+
const writeRoots = [...writableRoots];
|
|
3091
|
+
const anchors = /* @__PURE__ */ new Set();
|
|
3092
|
+
for (const entry of [...readOnlyMounts, ...masks]) {
|
|
3093
|
+
let parent = path10.dirname(entry);
|
|
3094
|
+
while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
|
|
3095
|
+
if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
|
|
3096
|
+
parent = path10.dirname(parent);
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
for (const anchor of anchors) {
|
|
3100
|
+
const info = statSync3(anchor, { throwIfNoEntry: false });
|
|
3101
|
+
if (!info) {
|
|
3102
|
+
anchors.delete(anchor);
|
|
3103
|
+
continue;
|
|
3104
|
+
}
|
|
3105
|
+
if (!info.isDirectory() || realpathSync5(anchor) !== anchor)
|
|
3106
|
+
throw new Error("unbound_protected_ancestor");
|
|
3107
|
+
}
|
|
3108
|
+
for (const root of [...writeRoots, ...anchors].sort(
|
|
3109
|
+
(a, b) => a.length - b.length
|
|
3110
|
+
))
|
|
3111
|
+
flags.push("--bind", root, root);
|
|
3112
|
+
for (const entry of [...readOnlyMounts].sort((a, b) => a.length - b.length)) {
|
|
3113
|
+
if (!writeRoots.some((root) => within2(root, entry))) continue;
|
|
3114
|
+
flags.push("--ro-bind", entry, entry);
|
|
3115
|
+
}
|
|
3116
|
+
for (const { target, placeholder } of mountpoints)
|
|
3117
|
+
flags.push("--ro-bind", `${state}/${placeholder}`, target);
|
|
3118
|
+
flags.push("--tmpfs", state);
|
|
3119
|
+
return flags;
|
|
3120
|
+
};
|
|
3121
|
+
var prepare = (policy, state, runsc, unshare) => {
|
|
3122
|
+
if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length)
|
|
3123
|
+
throw new Error("unsupported_protection");
|
|
3124
|
+
const masks = masksFor(policy);
|
|
2577
3125
|
if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size)
|
|
2578
3126
|
throw new Error("protected_file_has_alias");
|
|
2579
3127
|
const readOnly = policy.readOnlyPaths ?? [];
|
|
2580
3128
|
if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
|
|
2581
3129
|
throw new Error("read_only_file_has_alias");
|
|
2582
3130
|
checkLinuxMountTopology(readFileSync3("/proc/self/mountinfo", "utf8"));
|
|
2583
|
-
|
|
3131
|
+
return [
|
|
2584
3132
|
"--pdeathsig",
|
|
2585
3133
|
"KILL",
|
|
2586
3134
|
"--",
|
|
@@ -2607,46 +3155,7 @@ var prepare = (policy, state, runsc, unshare) => {
|
|
|
2607
3155
|
"--cap-drop",
|
|
2608
3156
|
"ALL",
|
|
2609
3157
|
"--clearenv",
|
|
2610
|
-
|
|
2611
|
-
"/",
|
|
2612
|
-
"/",
|
|
2613
|
-
"--ro-bind",
|
|
2614
|
-
"/tmp",
|
|
2615
|
-
"/tmp"
|
|
2616
|
-
];
|
|
2617
|
-
for (const root of policy.writeRoots) {
|
|
2618
|
-
if (root === "/" || realpathSync4(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)) || readOnly.some((name) => within2(name, root)) || masks.some((mask) => within2(mask, root)))
|
|
2619
|
-
throw new Error("invalid_write_root");
|
|
2620
|
-
flags.push("--bind", root, root);
|
|
2621
|
-
}
|
|
2622
|
-
const anchors = /* @__PURE__ */ new Set();
|
|
2623
|
-
for (const entry of [...readOnly, ...masks]) {
|
|
2624
|
-
let parent = path8.dirname(entry);
|
|
2625
|
-
while (policy.writeRoots.some((root) => root !== parent && within2(root, parent))) {
|
|
2626
|
-
if (!masks.some((mask) => within2(mask, parent)) && !readOnly.some((ro) => within2(ro, parent)))
|
|
2627
|
-
anchors.add(parent);
|
|
2628
|
-
parent = path8.dirname(parent);
|
|
2629
|
-
}
|
|
2630
|
-
}
|
|
2631
|
-
for (const anchor of [...anchors].sort((a, b) => a.length - b.length)) {
|
|
2632
|
-
const info = statSync3(anchor, { throwIfNoEntry: false });
|
|
2633
|
-
if (!info) continue;
|
|
2634
|
-
if (!info.isDirectory() || realpathSync4(anchor) !== anchor)
|
|
2635
|
-
throw new Error("unbound_protected_ancestor");
|
|
2636
|
-
flags.push("--bind", anchor, anchor);
|
|
2637
|
-
}
|
|
2638
|
-
for (const entry of readOnly) {
|
|
2639
|
-
if (masks.some((mask) => within2(mask, entry))) continue;
|
|
2640
|
-
if (!policy.writeRoots.some((root) => within2(root, entry))) continue;
|
|
2641
|
-
if (realpathSync4(entry) !== entry)
|
|
2642
|
-
throw new Error("unbound_read_only_path");
|
|
2643
|
-
flags.push("--ro-bind", entry, entry);
|
|
2644
|
-
}
|
|
2645
|
-
for (const { target, placeholder } of mountpoints)
|
|
2646
|
-
flags.push("--ro-bind", `${state}/${placeholder}`, target);
|
|
2647
|
-
flags.push(
|
|
2648
|
-
"--tmpfs",
|
|
2649
|
-
state,
|
|
3158
|
+
...linuxRunscMountArgs(policy, state, masks),
|
|
2650
3159
|
"--setenv",
|
|
2651
3160
|
"HOME",
|
|
2652
3161
|
state,
|
|
@@ -2670,8 +3179,7 @@ var prepare = (policy, state, runsc, unshare) => {
|
|
|
2670
3179
|
"--chdir",
|
|
2671
3180
|
policy.cwd,
|
|
2672
3181
|
"--"
|
|
2673
|
-
|
|
2674
|
-
return flags;
|
|
3182
|
+
];
|
|
2675
3183
|
};
|
|
2676
3184
|
var release = (root) => rmSync(root, { recursive: true, force: true });
|
|
2677
3185
|
var allocate = () => {
|
|
@@ -2688,6 +3196,7 @@ var allocate = () => {
|
|
|
2688
3196
|
};
|
|
2689
3197
|
var LinuxRunscBackend = class {
|
|
2690
3198
|
supportsReadOnlyPaths = true;
|
|
3199
|
+
supportsHomeDotProtection = true;
|
|
2691
3200
|
supportsCommandBinding = true;
|
|
2692
3201
|
tools;
|
|
2693
3202
|
probed = /* @__PURE__ */ new Set();
|
|
@@ -2704,10 +3213,10 @@ var LinuxRunscBackend = class {
|
|
|
2704
3213
|
for (const candidate of ["/usr/local/bin/runsc", "/usr/bin/runsc"]) {
|
|
2705
3214
|
try {
|
|
2706
3215
|
const runsc = managedTool(candidate);
|
|
2707
|
-
const sidecars =
|
|
2708
|
-
accessSync2(
|
|
2709
|
-
for (const executable of
|
|
2710
|
-
managedTool(
|
|
3216
|
+
const sidecars = path10.join(path10.dirname(runsc), "gvisor-bin");
|
|
3217
|
+
accessSync2(path10.join(sidecars, "gvisor_sentry"), constants4.X_OK);
|
|
3218
|
+
for (const executable of readdirSync5(sidecars)) {
|
|
3219
|
+
managedTool(path10.join(sidecars, executable));
|
|
2711
3220
|
}
|
|
2712
3221
|
this.tools = { setpriv, unshare, runsc };
|
|
2713
3222
|
return this.tools;
|
|
@@ -2785,16 +3294,16 @@ var LinuxRunscBackend = class {
|
|
|
2785
3294
|
|
|
2786
3295
|
// src/permissions/mxc-launcher.ts
|
|
2787
3296
|
import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
|
|
2788
|
-
import { lstatSync as
|
|
2789
|
-
import
|
|
3297
|
+
import { lstatSync as lstatSync6, readFileSync as readFileSync4, realpathSync as realpathSync6, statSync as statSync4 } from "fs";
|
|
3298
|
+
import path11 from "path";
|
|
2790
3299
|
import { fileURLToPath } from "url";
|
|
2791
3300
|
var binaryName = "codelia-mxc-launcher";
|
|
2792
|
-
var packagePath =
|
|
2793
|
-
var moduleDir = typeof __dirname === "string" ? __dirname :
|
|
3301
|
+
var packagePath = path11.join("node_modules", "@codelia", "tui-darwin-arm64");
|
|
3302
|
+
var moduleDir = typeof __dirname === "string" ? __dirname : path11.dirname(fileURLToPath(import.meta.url));
|
|
2794
3303
|
var packageVersion = (directory, name) => {
|
|
2795
3304
|
try {
|
|
2796
|
-
const manifest =
|
|
2797
|
-
const info =
|
|
3305
|
+
const manifest = path11.join(directory, "package.json");
|
|
3306
|
+
const info = lstatSync6(manifest);
|
|
2798
3307
|
if (!info.isFile() || info.size > 64 * 1024) return void 0;
|
|
2799
3308
|
const parsed = JSON.parse(readFileSync4(manifest, "utf8"));
|
|
2800
3309
|
return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
|
|
@@ -2803,24 +3312,27 @@ var packageVersion = (directory, name) => {
|
|
|
2803
3312
|
}
|
|
2804
3313
|
};
|
|
2805
3314
|
var directoryId = (info) => `${info.dev}:${info.ino}`;
|
|
2806
|
-
var trustedLauncher = (candidate, writableDirs, uid) => {
|
|
3315
|
+
var trustedLauncher = (candidate, writableDirs, uid, protectedHome) => {
|
|
2807
3316
|
try {
|
|
2808
|
-
const directory =
|
|
2809
|
-
const file =
|
|
2810
|
-
const info =
|
|
3317
|
+
const directory = realpathSync6(path11.dirname(candidate));
|
|
3318
|
+
const file = path11.join(directory, binaryName);
|
|
3319
|
+
const info = lstatSync6(file, { bigint: true });
|
|
2811
3320
|
if (!info.isFile() || info.nlink !== 1n || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
|
|
2812
3321
|
return void 0;
|
|
3322
|
+
const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
|
|
2813
3323
|
let current = directory;
|
|
2814
3324
|
for (; ; ) {
|
|
2815
3325
|
const parent = statSync4(current, { bigint: true });
|
|
2816
3326
|
const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
|
|
2817
|
-
|
|
3327
|
+
const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
|
|
3328
|
+
if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
|
|
2818
3329
|
return void 0;
|
|
2819
|
-
const next =
|
|
3330
|
+
const next = path11.dirname(current);
|
|
2820
3331
|
if (next === current) break;
|
|
2821
3332
|
current = next;
|
|
2822
3333
|
}
|
|
2823
3334
|
return {
|
|
3335
|
+
candidate,
|
|
2824
3336
|
file,
|
|
2825
3337
|
identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
|
|
2826
3338
|
};
|
|
@@ -2838,13 +3350,13 @@ var resolveMxcLauncher = (protection) => {
|
|
|
2838
3350
|
(root) => directoryId(statSync4(root, { bigint: true }))
|
|
2839
3351
|
)
|
|
2840
3352
|
);
|
|
2841
|
-
const actualModule =
|
|
2842
|
-
const projectPackage =
|
|
2843
|
-
const suffix =
|
|
2844
|
-
if (projectPackage.endsWith(`${
|
|
2845
|
-
const checkout =
|
|
3353
|
+
const actualModule = realpathSync6(moduleDir);
|
|
3354
|
+
const projectPackage = path11.basename(actualModule) === "permissions" ? path11.resolve(actualModule, "../..") : path11.dirname(actualModule);
|
|
3355
|
+
const suffix = path11.join("packages", "runtime");
|
|
3356
|
+
if (projectPackage.endsWith(`${path11.sep}${suffix}`)) {
|
|
3357
|
+
const checkout = path11.resolve(projectPackage, "../..");
|
|
2846
3358
|
const built = trustedLauncher(
|
|
2847
|
-
|
|
3359
|
+
path11.join(checkout, "crates/mxc-launcher/target/release", binaryName),
|
|
2848
3360
|
mutable,
|
|
2849
3361
|
BigInt(uid)
|
|
2850
3362
|
);
|
|
@@ -2854,14 +3366,15 @@ var resolveMxcLauncher = (protection) => {
|
|
|
2854
3366
|
if (!version) return void 0;
|
|
2855
3367
|
let directory = actualModule;
|
|
2856
3368
|
for (; ; ) {
|
|
2857
|
-
const candidatePackage =
|
|
3369
|
+
const candidatePackage = path11.join(directory, packagePath);
|
|
2858
3370
|
const installed = packageVersion(candidatePackage, "@codelia/tui-darwin-arm64") === version ? trustedLauncher(
|
|
2859
|
-
|
|
3371
|
+
path11.join(candidatePackage, "bin", binaryName),
|
|
2860
3372
|
mutable,
|
|
2861
|
-
BigInt(uid)
|
|
3373
|
+
BigInt(uid),
|
|
3374
|
+
protection.homeDotDirectory
|
|
2862
3375
|
) : void 0;
|
|
2863
3376
|
if (installed) return installed;
|
|
2864
|
-
const parent =
|
|
3377
|
+
const parent = path11.dirname(directory);
|
|
2865
3378
|
if (parent === directory) return void 0;
|
|
2866
3379
|
directory = parent;
|
|
2867
3380
|
}
|
|
@@ -2952,80 +3465,20 @@ var launchMxc = (launcher, request, stdin) => {
|
|
|
2952
3465
|
return child;
|
|
2953
3466
|
};
|
|
2954
3467
|
|
|
2955
|
-
// src/permissions/resource-paths.ts
|
|
2956
|
-
import { lstatSync as lstatSync5, opendirSync } from "fs";
|
|
2957
|
-
import path10 from "path";
|
|
2958
|
-
var lookup = (pathname) => lstatSync5(pathname, { bigint: true, throwIfNoEntry: false });
|
|
2959
|
-
var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
|
|
2960
|
-
var comparableResourceName = (pathname) => {
|
|
2961
|
-
const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
|
|
2962
|
-
return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
|
|
2963
|
-
};
|
|
2964
|
-
function distinguishesAsciiCase(parent) {
|
|
2965
|
-
try {
|
|
2966
|
-
const directory = opendirSync(parent);
|
|
2967
|
-
try {
|
|
2968
|
-
for (let index = 0; index < 16; index++) {
|
|
2969
|
-
const name = directory.readSync()?.name;
|
|
2970
|
-
if (!name) break;
|
|
2971
|
-
const changed = name.replace(
|
|
2972
|
-
/[A-Za-z]/u,
|
|
2973
|
-
(letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
|
|
2974
|
-
);
|
|
2975
|
-
if (name === changed) continue;
|
|
2976
|
-
const original = lookup(path10.join(parent, name));
|
|
2977
|
-
const alternate = lookup(path10.join(parent, changed));
|
|
2978
|
-
if (original) return !alternate || !sameEntry(original, alternate);
|
|
2979
|
-
}
|
|
2980
|
-
} finally {
|
|
2981
|
-
directory.closeSync();
|
|
2982
|
-
}
|
|
2983
|
-
} catch {
|
|
2984
|
-
}
|
|
2985
|
-
return false;
|
|
2986
|
-
}
|
|
2987
|
-
function resourceContainsPath(resource, target) {
|
|
2988
|
-
if (target === resource || target.startsWith(
|
|
2989
|
-
resource.endsWith(path10.sep) ? resource : `${resource}${path10.sep}`
|
|
2990
|
-
))
|
|
2991
|
-
return true;
|
|
2992
|
-
const root = path10.parse(resource).root;
|
|
2993
|
-
const targetRoot = path10.parse(target).root;
|
|
2994
|
-
if (comparableResourceName(root) !== comparableResourceName(targetRoot))
|
|
2995
|
-
return false;
|
|
2996
|
-
const parts = resource.slice(root.length).split(path10.sep);
|
|
2997
|
-
const overlapping = target.slice(targetRoot.length).split(path10.sep).slice(0, parts.length);
|
|
2998
|
-
if (overlapping.length !== parts.length) return false;
|
|
2999
|
-
const candidate = path10.join(targetRoot, ...overlapping);
|
|
3000
|
-
const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
|
|
3001
|
-
try {
|
|
3002
|
-
const targetEntry = lookup(candidate);
|
|
3003
|
-
if (!targetEntry && !namesMayMatch) return false;
|
|
3004
|
-
const protectedEntry = lookup(resource);
|
|
3005
|
-
if (protectedEntry || targetEntry)
|
|
3006
|
-
return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
|
|
3007
|
-
if (!namesMayMatch) return false;
|
|
3008
|
-
const parent = path10.dirname(resource);
|
|
3009
|
-
return path10.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(path10.basename(resource)) || !/^[\x20-\x7e]+$/u.test(path10.basename(candidate)) || path10.basename(resource).toLowerCase() !== path10.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
|
|
3010
|
-
} catch {
|
|
3011
|
-
return namesMayMatch;
|
|
3012
|
-
}
|
|
3013
|
-
}
|
|
3014
|
-
|
|
3015
3468
|
// src/permissions/system-bash.ts
|
|
3016
3469
|
import {
|
|
3017
3470
|
accessSync as accessSync3,
|
|
3018
3471
|
constants as constants5,
|
|
3019
|
-
lstatSync as
|
|
3020
|
-
readlinkSync as
|
|
3472
|
+
lstatSync as lstatSync7,
|
|
3473
|
+
readlinkSync as readlinkSync4
|
|
3021
3474
|
} from "fs";
|
|
3022
3475
|
import { posix } from "path";
|
|
3023
3476
|
var conventional = ["/bin/bash", "/usr/bin/bash"];
|
|
3024
3477
|
var nixSystemBash = "/run/current-system/sw/bin/bash";
|
|
3025
3478
|
var nixStoreBash = /^\/nix\/store\/[^/]+\/bin\/bash$/u;
|
|
3026
3479
|
var hostEntries = {
|
|
3027
|
-
stat: (name) =>
|
|
3028
|
-
readLink:
|
|
3480
|
+
stat: (name) => lstatSync7(name, { throwIfNoEntry: false }),
|
|
3481
|
+
readLink: readlinkSync4,
|
|
3029
3482
|
canExecute: (name) => accessSync3(name, constants5.X_OK)
|
|
3030
3483
|
};
|
|
3031
3484
|
var trustedDirectory = (name, entry) => entry.uid === 0 && entry.isDirectory() && ((entry.mode & 18) === 0 || // Nix builders can create new store entries in a sticky store. They
|
|
@@ -3073,23 +3526,23 @@ var resolveSystemBash = (platform = process.platform, entries = hostEntries) =>
|
|
|
3073
3526
|
};
|
|
3074
3527
|
|
|
3075
3528
|
// src/permissions/workspace-config-paths.ts
|
|
3076
|
-
import { lstatSync as
|
|
3077
|
-
import
|
|
3529
|
+
import { lstatSync as lstatSync8, opendirSync as opendirSync2, readlinkSync as readlinkSync5, realpathSync as realpathSync7 } from "fs";
|
|
3530
|
+
import path12 from "path";
|
|
3078
3531
|
import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
|
|
3079
3532
|
var confinedAutoLaunchDirectoryName = "confined-auto-launch";
|
|
3080
|
-
var isWorkspaceConfigName = (root, target) => resourceContainsPath(
|
|
3081
|
-
var
|
|
3533
|
+
var isWorkspaceConfigName = (root, target) => resourceContainsPath(path12.dirname(resolveProjectConfigPath(root)), target);
|
|
3534
|
+
var missing2 = (error) => error.code === "ENOENT";
|
|
3082
3535
|
function resolveConfigTarget(target, remaining = 64) {
|
|
3083
3536
|
if (!remaining) throw new Error("workspace_config_path_unresolved");
|
|
3084
3537
|
try {
|
|
3085
|
-
return
|
|
3538
|
+
return realpathSync7(target);
|
|
3086
3539
|
} catch (error) {
|
|
3087
|
-
const parent =
|
|
3088
|
-
if (!
|
|
3540
|
+
const parent = path12.dirname(target);
|
|
3541
|
+
if (!missing2(error) || parent === target) throw error;
|
|
3089
3542
|
const canonicalParent = resolveConfigTarget(parent, remaining - 1);
|
|
3090
|
-
if (!
|
|
3091
|
-
return
|
|
3092
|
-
const referent =
|
|
3543
|
+
if (!lstatSync8(target, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
3544
|
+
return path12.join(canonicalParent, path12.basename(target));
|
|
3545
|
+
const referent = readlinkSync5(target);
|
|
3093
3546
|
let seenName = false;
|
|
3094
3547
|
for (const part of referent.split(
|
|
3095
3548
|
process.platform === "win32" ? /[\\/]/u : "/"
|
|
@@ -3099,14 +3552,14 @@ function resolveConfigTarget(target, remaining = 64) {
|
|
|
3099
3552
|
if (part && part !== "." && part !== "..") seenName = true;
|
|
3100
3553
|
}
|
|
3101
3554
|
return resolveConfigTarget(
|
|
3102
|
-
|
|
3555
|
+
path12.resolve(canonicalParent, referent),
|
|
3103
3556
|
remaining - 1
|
|
3104
3557
|
);
|
|
3105
3558
|
}
|
|
3106
3559
|
}
|
|
3107
3560
|
var workspaceConfigProtection = (root) => {
|
|
3108
3561
|
const config = resolveProjectConfigPath(root);
|
|
3109
|
-
const directory =
|
|
3562
|
+
const directory = path12.dirname(config);
|
|
3110
3563
|
const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
|
|
3111
3564
|
const readOnlyAliasPaths = /* @__PURE__ */ new Set();
|
|
3112
3565
|
const reserveTarget = (file) => {
|
|
@@ -3114,12 +3567,12 @@ var workspaceConfigProtection = (root) => {
|
|
|
3114
3567
|
readOnlyPaths.add(target);
|
|
3115
3568
|
readOnlyAliasPaths.add(target);
|
|
3116
3569
|
};
|
|
3117
|
-
if (
|
|
3570
|
+
if (lstatSync8(directory, { throwIfNoEntry: false })) {
|
|
3118
3571
|
const canonical = resolveConfigTarget(directory);
|
|
3119
3572
|
readOnlyPaths.add(canonical);
|
|
3120
|
-
if (
|
|
3121
|
-
const file =
|
|
3122
|
-
if (
|
|
3573
|
+
if (lstatSync8(canonical, { throwIfNoEntry: false })?.isDirectory()) {
|
|
3574
|
+
const file = path12.join(canonical, path12.basename(config));
|
|
3575
|
+
if (lstatSync8(file, { throwIfNoEntry: false })) reserveTarget(file);
|
|
3123
3576
|
const storage = resolveStoragePaths2();
|
|
3124
3577
|
const globalStorage = [
|
|
3125
3578
|
resolveStoragePaths2({ layout: "home" }).root,
|
|
@@ -3127,24 +3580,24 @@ var workspaceConfigProtection = (root) => {
|
|
|
3127
3580
|
storage.configDir
|
|
3128
3581
|
].some((entry) => {
|
|
3129
3582
|
try {
|
|
3130
|
-
return
|
|
3583
|
+
return realpathSync7(entry) === canonical;
|
|
3131
3584
|
} catch (error) {
|
|
3132
|
-
if (!
|
|
3585
|
+
if (!missing2(error)) throw error;
|
|
3133
3586
|
return false;
|
|
3134
3587
|
}
|
|
3135
3588
|
});
|
|
3136
3589
|
if (!globalStorage) {
|
|
3137
|
-
const worktrees =
|
|
3590
|
+
const worktrees = path12.join(canonical, "worktrees");
|
|
3138
3591
|
const pending = [canonical];
|
|
3139
3592
|
for (const current of pending) {
|
|
3140
3593
|
const children = opendirSync2(current);
|
|
3141
3594
|
try {
|
|
3142
3595
|
for (let entry = children.readSync(); entry; entry = children.readSync()) {
|
|
3143
|
-
const target =
|
|
3596
|
+
const target = path12.join(current, entry.name);
|
|
3144
3597
|
if (target === file || target === worktrees) continue;
|
|
3145
3598
|
if (entry.isSymbolicLink()) reserveTarget(target);
|
|
3146
3599
|
else if (entry.isDirectory()) pending.push(target);
|
|
3147
|
-
else if (entry.isFile() && (
|
|
3600
|
+
else if (entry.isFile() && (lstatSync8(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
|
|
3148
3601
|
readOnlyAliasPaths.add(target);
|
|
3149
3602
|
}
|
|
3150
3603
|
} finally {
|
|
@@ -3163,7 +3616,7 @@ var workspaceConfigProtection = (root) => {
|
|
|
3163
3616
|
// src/permissions/shell-backend.ts
|
|
3164
3617
|
var supportsProtectedShell = (backend, protection, invocation) => {
|
|
3165
3618
|
try {
|
|
3166
|
-
return (protection.profile === "full-access" || !protection.readOnlyPaths?.length || backend.supportsReadOnlyPaths === true) && backend.supports(protection) === true && (!invocation || !backend.supportsInvocation || backend.supportsInvocation(invocation, protection) === true);
|
|
3619
|
+
return (protection.profile === "full-access" || (!protection.readOnlyPaths?.length || backend.supportsReadOnlyPaths === true) && (!protection.homeDotDirectory || backend.supportsHomeDotProtection === true)) && backend.supports(protection) === true && (!invocation || !backend.supportsInvocation || backend.supportsInvocation(invocation, protection) === true);
|
|
3167
3620
|
} catch {
|
|
3168
3621
|
return false;
|
|
3169
3622
|
}
|
|
@@ -3182,11 +3635,11 @@ var platformShellSource = (source) => {
|
|
|
3182
3635
|
return fixedBash(source, executable);
|
|
3183
3636
|
}
|
|
3184
3637
|
const systemRoot = process.env.SystemRoot;
|
|
3185
|
-
if (!systemRoot || !
|
|
3638
|
+
if (!systemRoot || !path13.isAbsolute(systemRoot))
|
|
3186
3639
|
throw new Error("windows_system_directory_unavailable");
|
|
3187
3640
|
return Object.freeze({
|
|
3188
3641
|
kind: "source",
|
|
3189
|
-
executable:
|
|
3642
|
+
executable: path13.join(
|
|
3190
3643
|
systemRoot,
|
|
3191
3644
|
"System32",
|
|
3192
3645
|
"WindowsPowerShell",
|
|
@@ -3205,27 +3658,27 @@ var platformShellSource = (source) => {
|
|
|
3205
3658
|
};
|
|
3206
3659
|
var realOrLexical = (value) => {
|
|
3207
3660
|
try {
|
|
3208
|
-
return
|
|
3661
|
+
return realpathSync8(value);
|
|
3209
3662
|
} catch {
|
|
3210
|
-
return
|
|
3663
|
+
return path13.resolve(value);
|
|
3211
3664
|
}
|
|
3212
3665
|
};
|
|
3213
3666
|
var resolvePolicyPath = (target) => {
|
|
3214
|
-
const absolute =
|
|
3667
|
+
const absolute = path13.resolve(target);
|
|
3215
3668
|
try {
|
|
3216
|
-
return
|
|
3669
|
+
return realpathSync8(absolute);
|
|
3217
3670
|
} catch (error) {
|
|
3218
|
-
const parent =
|
|
3671
|
+
const parent = path13.dirname(absolute);
|
|
3219
3672
|
if (error.code !== "ENOENT" || parent === absolute)
|
|
3220
3673
|
throw error;
|
|
3221
|
-
if (
|
|
3674
|
+
if (lstatSync9(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
3222
3675
|
throw error;
|
|
3223
|
-
return
|
|
3676
|
+
return path13.join(resolvePolicyPath(parent), path13.basename(absolute));
|
|
3224
3677
|
}
|
|
3225
3678
|
};
|
|
3226
3679
|
var canonicalPolicyPaths = (paths) => Object.freeze([
|
|
3227
3680
|
...new Set(
|
|
3228
|
-
paths.flatMap((entry) => [
|
|
3681
|
+
paths.flatMap((entry) => [path13.resolve(entry), resolvePolicyPath(entry)])
|
|
3229
3682
|
)
|
|
3230
3683
|
]);
|
|
3231
3684
|
var runtimeReadOnlyPaths = () => {
|
|
@@ -3237,37 +3690,68 @@ var runtimeReadOnlyPaths = () => {
|
|
|
3237
3690
|
resolveConfigPath()
|
|
3238
3691
|
]);
|
|
3239
3692
|
};
|
|
3693
|
+
var runtimeProtectedCredentialPaths = () => {
|
|
3694
|
+
const storage = resolveStoragePaths3();
|
|
3695
|
+
const targets = [];
|
|
3696
|
+
if (process.platform === "linux") {
|
|
3697
|
+
try {
|
|
3698
|
+
mkdirSync2(storage.credentialsDir, { recursive: true, mode: 448 });
|
|
3699
|
+
targets.push(storage.credentialsDir);
|
|
3700
|
+
} catch {
|
|
3701
|
+
if (lstatSync9(storage.credentialsDir, { throwIfNoEntry: false })) {
|
|
3702
|
+
targets.push(storage.credentialsDir);
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3705
|
+
for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
|
|
3706
|
+
if (lstatSync9(legacy, { throwIfNoEntry: false })) {
|
|
3707
|
+
targets.push(legacy);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
} else {
|
|
3711
|
+
targets.push(
|
|
3712
|
+
storage.credentialsDir,
|
|
3713
|
+
storage.legacyAuthFile,
|
|
3714
|
+
storage.legacyMcpAuthFile
|
|
3715
|
+
);
|
|
3716
|
+
}
|
|
3717
|
+
return canonicalPolicyPaths(targets);
|
|
3718
|
+
};
|
|
3240
3719
|
var runtimeAuthorityAliasPaths = () => {
|
|
3241
3720
|
const storage = resolveStoragePaths3();
|
|
3242
3721
|
const databasePaths = [
|
|
3243
|
-
|
|
3244
|
-
|
|
3722
|
+
path13.join(storage.configDir, ".projects-policy-lock.sqlite"),
|
|
3723
|
+
path13.join(storage.sessionsDir, "state.db")
|
|
3245
3724
|
];
|
|
3246
3725
|
return canonicalPolicyPaths([
|
|
3247
3726
|
resolveConfigPath(),
|
|
3248
3727
|
storage.configFile,
|
|
3249
3728
|
storage.projectsFile,
|
|
3250
|
-
storage.authFile,
|
|
3251
|
-
storage.mcpAuthFile,
|
|
3252
3729
|
...[
|
|
3253
3730
|
"launch-approvals",
|
|
3254
3731
|
"auto-review.json",
|
|
3255
3732
|
confinedAutoLaunchDirectoryName
|
|
3256
|
-
].map((entry) =>
|
|
3733
|
+
].map((entry) => path13.join(storage.configDir, entry)),
|
|
3257
3734
|
...databasePaths.flatMap(
|
|
3258
3735
|
(file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
|
|
3259
3736
|
)
|
|
3260
3737
|
]);
|
|
3261
3738
|
};
|
|
3262
|
-
var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = []) => {
|
|
3739
|
+
var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
|
|
3263
3740
|
const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
|
|
3264
3741
|
const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
|
|
3265
|
-
const protectedPaths = canonicalPolicyPaths(
|
|
3742
|
+
const protectedPaths = canonicalPolicyPaths([
|
|
3743
|
+
...extraProtectedPaths,
|
|
3744
|
+
...runtimeProtectedCredentialPaths()
|
|
3745
|
+
]);
|
|
3266
3746
|
const projectConfig = workspaceConfigProtection(root);
|
|
3267
3747
|
const hostReadOnlyPaths = canonicalPolicyPaths(extraReadOnlyPaths);
|
|
3268
3748
|
const runtimeRoots = runtimeReadOnlyPaths();
|
|
3269
3749
|
const runtimeAuthority = runtimeAuthorityAliasPaths();
|
|
3750
|
+
const protectedHome = homeDotDirectory(
|
|
3751
|
+
homeScope.writeRoots ?? (sandboxMode === "readonly" ? [] : [root])
|
|
3752
|
+
);
|
|
3270
3753
|
const additionalReadOnlyPaths = [
|
|
3754
|
+
...protectedHome && !homeScope.recheckHomeLinksOnWrite ? homeDotLinkTargets(protectedHome) : [],
|
|
3271
3755
|
...reservedMarkers,
|
|
3272
3756
|
...projectConfig.readOnlyPaths,
|
|
3273
3757
|
...hostReadOnlyPaths,
|
|
@@ -3280,13 +3764,14 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
|
|
|
3280
3764
|
const objectDirectoriesWithSharedFiles = objectDirectories.filter(
|
|
3281
3765
|
(directory) => {
|
|
3282
3766
|
const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
|
|
3283
|
-
const commonDirectory =
|
|
3767
|
+
const commonDirectory = path13.dirname(directory.path);
|
|
3284
3768
|
return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
|
|
3285
3769
|
(other) => overlaps(other) && realOrLexical(other) !== commonDirectory
|
|
3286
3770
|
);
|
|
3287
3771
|
}
|
|
3288
3772
|
);
|
|
3289
3773
|
return {
|
|
3774
|
+
...protectedHome ? { homeDotDirectory: protectedHome } : {},
|
|
3290
3775
|
protectedPaths,
|
|
3291
3776
|
protectedAliasPaths: protectedPaths,
|
|
3292
3777
|
readOnlyPaths: Object.freeze(
|
|
@@ -3317,11 +3802,13 @@ var sbplString = (value) => {
|
|
|
3317
3802
|
var subpaths = (paths) => paths.map((entry) => `(subpath ${sbplString(entry)})`).join(" ");
|
|
3318
3803
|
var protectedSeatbeltAncestors = (base) => {
|
|
3319
3804
|
const parents = /* @__PURE__ */ new Set();
|
|
3805
|
+
if (base.homeDotDirectory) parents.add(base.homeDotDirectory);
|
|
3320
3806
|
for (const protectedPath of [
|
|
3321
3807
|
...base.protectedPaths,
|
|
3322
|
-
...base.readOnlyPaths ?? []
|
|
3808
|
+
...base.readOnlyPaths ?? [],
|
|
3809
|
+
...base.homeDotDirectory ? [base.homeDotDirectory] : []
|
|
3323
3810
|
]) {
|
|
3324
|
-
for (let child = protectedPath, parent =
|
|
3811
|
+
for (let child = protectedPath, parent = path13.dirname(child); parent !== child; child = parent, parent = path13.dirname(child)) {
|
|
3325
3812
|
if (base.writeRoots.some((root) => isWithin(root, parent)))
|
|
3326
3813
|
parents.add(parent);
|
|
3327
3814
|
}
|
|
@@ -3335,6 +3822,11 @@ var seatbeltProfile = (base, scratch, mutation) => {
|
|
|
3335
3822
|
...base,
|
|
3336
3823
|
protectedPaths: [...base.protectedPaths, ...deviceAndIpcPaths]
|
|
3337
3824
|
}).map(literal).join(" ");
|
|
3825
|
+
const home = base.homeDotDirectory;
|
|
3826
|
+
const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path13.join(home, "/")}.`)}) ${subpaths([path13.join(home, "Library")])})` : "";
|
|
3827
|
+
const approvedHomeDotRoots = !mutation && home ? base.writeRoots.filter(
|
|
3828
|
+
(root) => root !== home && isHomeDotTarget(home, root)
|
|
3829
|
+
) : [];
|
|
3338
3830
|
const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots];
|
|
3339
3831
|
const fixedWriteRules = mutation && [
|
|
3340
3832
|
mutation.directories.length ? `(allow file-write-create ${mutation.directories.map(literal).join(" ")})` : "",
|
|
@@ -3355,6 +3847,8 @@ ${fixedWriteRules ?? ""}
|
|
|
3355
3847
|
(allow file-read* (literal "/dev/null") (literal "/dev/zero")
|
|
3356
3848
|
(literal "/dev/random") (literal "/dev/urandom"))
|
|
3357
3849
|
(allow file-write-data (literal "/dev/null"))
|
|
3850
|
+
${homeRule}
|
|
3851
|
+
${approvedHomeDotRoots.length ? `(allow file-write* ${subpaths(approvedHomeDotRoots)})` : ""}
|
|
3358
3852
|
${base.protectedPaths.length ? `(deny file-read* file-write* ${subpaths(base.protectedPaths)})` : ""}
|
|
3359
3853
|
${base.readOnlyPaths?.length ? `(deny file-write* ${subpaths(base.readOnlyPaths)})` : ""}
|
|
3360
3854
|
${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
|
|
@@ -3363,12 +3857,28 @@ ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
|
|
|
3363
3857
|
`;
|
|
3364
3858
|
};
|
|
3365
3859
|
var sandboxExec = "/usr/bin/sandbox-exec";
|
|
3860
|
+
var macAdditionalWriteLauncherPaths = (protection) => {
|
|
3861
|
+
const baseline = resolveMxcLauncher({
|
|
3862
|
+
...protection,
|
|
3863
|
+
writeRoots: [protection.root],
|
|
3864
|
+
homeDotDirectory: homeDotDirectory([protection.root])
|
|
3865
|
+
});
|
|
3866
|
+
const selected = resolveMxcLauncher(protection);
|
|
3867
|
+
return [
|
|
3868
|
+
...new Set(
|
|
3869
|
+
[baseline, selected].flatMap(
|
|
3870
|
+
(launcher) => launcher ? [launcher.candidate, launcher.file] : []
|
|
3871
|
+
)
|
|
3872
|
+
)
|
|
3873
|
+
];
|
|
3874
|
+
};
|
|
3366
3875
|
var MacSeatbeltBackend = class {
|
|
3367
3876
|
constructor(launcher = "seatbelt") {
|
|
3368
3877
|
this.launcher = launcher;
|
|
3369
3878
|
}
|
|
3370
3879
|
launcher;
|
|
3371
3880
|
supportsReadOnlyPaths = true;
|
|
3881
|
+
supportsHomeDotProtection = true;
|
|
3372
3882
|
supportsCommandBinding = true;
|
|
3373
3883
|
available;
|
|
3374
3884
|
mxcProbe;
|
|
@@ -3385,7 +3895,7 @@ var MacSeatbeltBackend = class {
|
|
|
3385
3895
|
return false;
|
|
3386
3896
|
try {
|
|
3387
3897
|
if (mutation && (protection.profile !== "development" || protection.stdin !== "pipe" || [...mutation.directories, mutation.destination, mutation.source].some(
|
|
3388
|
-
(entry) => entry !== void 0 && (!
|
|
3898
|
+
(entry) => entry !== void 0 && (!path13.isAbsolute(entry) || path13.normalize(entry) !== entry || !protection.writeRoots.some(
|
|
3389
3899
|
(root) => entry !== root && isWithin(root, entry)
|
|
3390
3900
|
))
|
|
3391
3901
|
)))
|
|
@@ -3470,8 +3980,8 @@ var MacSeatbeltBackend = class {
|
|
|
3470
3980
|
launchWithPolicy(invocation, protection, mutation) {
|
|
3471
3981
|
if (!(mutation ? this.supportsPolicy(protection, mutation) : this.supports(protection)))
|
|
3472
3982
|
throw new Error("sandbox_unavailable");
|
|
3473
|
-
const scratch =
|
|
3474
|
-
mkdtempSync2(
|
|
3983
|
+
const scratch = realpathSync8(
|
|
3984
|
+
mkdtempSync2(path13.join(os2.tmpdir(), "codelia-shell-"))
|
|
3475
3985
|
);
|
|
3476
3986
|
const cleanup = () => {
|
|
3477
3987
|
try {
|
|
@@ -3548,15 +4058,15 @@ var UserShellBackend = class {
|
|
|
3548
4058
|
windowsHide: true,
|
|
3549
4059
|
env: {
|
|
3550
4060
|
PATH: shellPathForLaunch(protection.binPaths),
|
|
3551
|
-
HOME:
|
|
3552
|
-
TMPDIR:
|
|
4061
|
+
HOME: os2.homedir(),
|
|
4062
|
+
TMPDIR: os2.tmpdir(),
|
|
3553
4063
|
LANG: "C",
|
|
3554
4064
|
...protection.toolchainHomes,
|
|
3555
4065
|
...process.platform === "win32" && {
|
|
3556
4066
|
SystemRoot: process.env.SystemRoot,
|
|
3557
|
-
USERPROFILE:
|
|
3558
|
-
TEMP:
|
|
3559
|
-
TMP:
|
|
4067
|
+
USERPROFILE: os2.homedir(),
|
|
4068
|
+
TEMP: os2.tmpdir(),
|
|
4069
|
+
TMP: os2.tmpdir()
|
|
3560
4070
|
}
|
|
3561
4071
|
},
|
|
3562
4072
|
stdio: [protection.stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe"]
|
|
@@ -4527,10 +5037,10 @@ var createRuntimeModel = async ({
|
|
|
4527
5037
|
|
|
4528
5038
|
// src/runtime-state.ts
|
|
4529
5039
|
import crypto from "crypto";
|
|
4530
|
-
import { realpathSync as
|
|
5040
|
+
import { realpathSync as realpathSync9 } from "fs";
|
|
4531
5041
|
|
|
4532
5042
|
// src/environment.ts
|
|
4533
|
-
import
|
|
5043
|
+
import path14 from "path";
|
|
4534
5044
|
import {
|
|
4535
5045
|
parseSandboxMode
|
|
4536
5046
|
} from "@codelia/shared-types";
|
|
@@ -4543,7 +5053,7 @@ var cloneContract = (contract) => ({
|
|
|
4543
5053
|
persistence: { ...contract.persistence },
|
|
4544
5054
|
events: { ...contract.events }
|
|
4545
5055
|
});
|
|
4546
|
-
var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ?
|
|
5056
|
+
var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path14.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
|
|
4547
5057
|
var runtimeEnvironmentPresets = {
|
|
4548
5058
|
"tui-local": {
|
|
4549
5059
|
workspace: {
|
|
@@ -4668,11 +5178,11 @@ var resolveRuntimeEnvironment = (options = {}) => {
|
|
|
4668
5178
|
if (contract.workspace.sandboxMode !== void 0 && !parseSandboxMode(contract.workspace.sandboxMode))
|
|
4669
5179
|
throw new Error("Invalid workspace.sandboxMode");
|
|
4670
5180
|
if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
|
|
4671
|
-
contract.workspace.root =
|
|
5181
|
+
contract.workspace.root = path14.resolve(
|
|
4672
5182
|
contract.workspace.root ?? defaultWorkspaceRoot()
|
|
4673
5183
|
);
|
|
4674
5184
|
} else if (contract.workspace.root) {
|
|
4675
|
-
contract.workspace.root =
|
|
5185
|
+
contract.workspace.root = path14.resolve(contract.workspace.root);
|
|
4676
5186
|
}
|
|
4677
5187
|
rejectContract(
|
|
4678
5188
|
contract.workspace.filesystem === "disabled" && (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config" || contract.tools.builtin === "full-coding-agent" || contract.tools.mcp === "from-config"),
|
|
@@ -4912,7 +5422,7 @@ var RuntimeState = class {
|
|
|
4912
5422
|
if (scope === "workspace") {
|
|
4913
5423
|
const root = this.runtimeSandboxRoot ?? this.runtimeWorkingDir;
|
|
4914
5424
|
return JSON.stringify([
|
|
4915
|
-
root === null ? null :
|
|
5425
|
+
root === null ? null : realpathSync9(root),
|
|
4916
5426
|
this.sandboxMode.value,
|
|
4917
5427
|
connection,
|
|
4918
5428
|
authority
|
|
@@ -5212,7 +5722,7 @@ var RuntimeState = class {
|
|
|
5212
5722
|
};
|
|
5213
5723
|
|
|
5214
5724
|
// src/subagents/bootstrap.ts
|
|
5215
|
-
import
|
|
5725
|
+
import path15 from "path";
|
|
5216
5726
|
import { sandboxModes } from "@codelia/shared-types";
|
|
5217
5727
|
import { z as z3 } from "zod";
|
|
5218
5728
|
|
|
@@ -5286,8 +5796,8 @@ var subagentBootstrapSchema = z3.object({
|
|
|
5286
5796
|
version: z3.literal(1),
|
|
5287
5797
|
task_id: z3.string().uuid(),
|
|
5288
5798
|
prompt: z3.string().min(1).max(32768),
|
|
5289
|
-
workspace_root: z3.string().refine(
|
|
5290
|
-
protected_paths: z3.array(z3.string().refine(
|
|
5799
|
+
workspace_root: z3.string().refine(path15.isAbsolute),
|
|
5800
|
+
protected_paths: z3.array(z3.string().refine(path15.isAbsolute)).optional(),
|
|
5291
5801
|
lineage: z3.object({
|
|
5292
5802
|
name: subagentNameSchema.optional(),
|
|
5293
5803
|
tree_id: z3.string().min(1),
|
|
@@ -6209,7 +6719,7 @@ var redactSubagentJson = (value, secrets = []) => JSON.parse(
|
|
|
6209
6719
|
|
|
6210
6720
|
// src/subagents/read-tools.ts
|
|
6211
6721
|
import { promises as fs6 } from "fs";
|
|
6212
|
-
import
|
|
6722
|
+
import path18 from "path";
|
|
6213
6723
|
import { defineTool } from "@codelia/core";
|
|
6214
6724
|
import { z as z5 } from "zod";
|
|
6215
6725
|
|
|
@@ -6218,10 +6728,10 @@ import crypto3 from "crypto";
|
|
|
6218
6728
|
import {
|
|
6219
6729
|
constants as constants6,
|
|
6220
6730
|
promises as fs4,
|
|
6221
|
-
lstatSync as
|
|
6222
|
-
realpathSync as
|
|
6731
|
+
lstatSync as lstatSync10,
|
|
6732
|
+
realpathSync as realpathSync10
|
|
6223
6733
|
} from "fs";
|
|
6224
|
-
import
|
|
6734
|
+
import path16 from "path";
|
|
6225
6735
|
var SecurityError = class extends Error {
|
|
6226
6736
|
constructor(message) {
|
|
6227
6737
|
super(message);
|
|
@@ -6231,22 +6741,22 @@ var SecurityError = class extends Error {
|
|
|
6231
6741
|
var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
6232
6742
|
var directoryIdentity2 = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
|
|
6233
6743
|
var selectMissingFile = (entry) => {
|
|
6234
|
-
let parent =
|
|
6744
|
+
let parent = path16.dirname(entry.target);
|
|
6235
6745
|
for (; ; ) {
|
|
6236
6746
|
try {
|
|
6237
|
-
const stat =
|
|
6238
|
-
if (!stat.isDirectory() ||
|
|
6747
|
+
const stat = lstatSync10(parent, { bigint: true });
|
|
6748
|
+
if (!stat.isDirectory() || realpathSync10(parent) !== parent)
|
|
6239
6749
|
throw new SecurityError("Expected a canonical parent directory");
|
|
6240
6750
|
return Object.freeze({
|
|
6241
6751
|
...entry,
|
|
6242
6752
|
identity: null,
|
|
6243
6753
|
parent,
|
|
6244
6754
|
parentIdentity: directoryIdentity2(stat),
|
|
6245
|
-
tail:
|
|
6755
|
+
tail: path16.relative(parent, entry.target)
|
|
6246
6756
|
});
|
|
6247
6757
|
} catch (error) {
|
|
6248
6758
|
if (error.code !== "ENOENT") throw error;
|
|
6249
|
-
const ancestor =
|
|
6759
|
+
const ancestor = path16.dirname(parent);
|
|
6250
6760
|
if (ancestor === parent) throw error;
|
|
6251
6761
|
parent = ancestor;
|
|
6252
6762
|
}
|
|
@@ -6254,15 +6764,15 @@ var selectMissingFile = (entry) => {
|
|
|
6254
6764
|
};
|
|
6255
6765
|
var missingDestinationCurrent = (selection) => {
|
|
6256
6766
|
try {
|
|
6257
|
-
const segments = selection.tail.split(
|
|
6767
|
+
const segments = selection.tail.split(path16.sep);
|
|
6258
6768
|
if (segments.some(
|
|
6259
6769
|
(segment) => !segment || segment === "." || segment === ".."
|
|
6260
|
-
) ||
|
|
6770
|
+
) || path16.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
|
|
6261
6771
|
return false;
|
|
6262
6772
|
let current = selection.parent;
|
|
6263
6773
|
for (const [index, segment] of segments.entries()) {
|
|
6264
|
-
current =
|
|
6265
|
-
const stat =
|
|
6774
|
+
current = path16.join(current, segment);
|
|
6775
|
+
const stat = lstatSync10(current);
|
|
6266
6776
|
if (index === segments.length - 1 || !stat.isDirectory()) return false;
|
|
6267
6777
|
}
|
|
6268
6778
|
return false;
|
|
@@ -6272,8 +6782,8 @@ var missingDestinationCurrent = (selection) => {
|
|
|
6272
6782
|
};
|
|
6273
6783
|
var directoryBindingCurrent = (selection) => {
|
|
6274
6784
|
try {
|
|
6275
|
-
const stat =
|
|
6276
|
-
return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity &&
|
|
6785
|
+
const stat = lstatSync10(selection.parent, { bigint: true });
|
|
6786
|
+
return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync10(selection.parent) === selection.parent;
|
|
6277
6787
|
} catch {
|
|
6278
6788
|
return false;
|
|
6279
6789
|
}
|
|
@@ -6286,6 +6796,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6286
6796
|
approvalMode;
|
|
6287
6797
|
protectedPaths;
|
|
6288
6798
|
protectedAliasPaths;
|
|
6799
|
+
homeDotDirectory;
|
|
6289
6800
|
readOnlyPaths;
|
|
6290
6801
|
readOnlyAliasPaths;
|
|
6291
6802
|
mutations;
|
|
@@ -6298,6 +6809,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6298
6809
|
this.approvalMode = init.approvalMode;
|
|
6299
6810
|
this.protectedPaths = init.protectedPaths;
|
|
6300
6811
|
this.protectedAliasPaths = init.protectedAliasPaths;
|
|
6812
|
+
this.homeDotDirectory = init.homeDotDirectory;
|
|
6301
6813
|
this.readOnlyPaths = init.readOnlyPaths ?? [];
|
|
6302
6814
|
this.readOnlyAliasPaths = init.readOnlyAliasPaths ?? this.readOnlyPaths;
|
|
6303
6815
|
this.selections = init.selections;
|
|
@@ -6305,7 +6817,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6305
6817
|
}
|
|
6306
6818
|
static async create(rootDir, options = {}) {
|
|
6307
6819
|
const sessionId = crypto3.randomUUID().slice(0, 8);
|
|
6308
|
-
const root = rootDir ?
|
|
6820
|
+
const root = rootDir ? path16.resolve(rootDir) : process.cwd();
|
|
6309
6821
|
if (options.sandboxMode !== "readonly")
|
|
6310
6822
|
await fs4.mkdir(root, { recursive: true });
|
|
6311
6823
|
const directory = options.protectResources ? await fs4.realpath(root) : root;
|
|
@@ -6318,7 +6830,8 @@ var SandboxContext = class _SandboxContext {
|
|
|
6318
6830
|
[],
|
|
6319
6831
|
options.sandboxMode,
|
|
6320
6832
|
false,
|
|
6321
|
-
options.extraReadOnlyPaths
|
|
6833
|
+
options.extraReadOnlyPaths,
|
|
6834
|
+
{ recheckHomeLinksOnWrite: true }
|
|
6322
6835
|
) : {},
|
|
6323
6836
|
sessionId,
|
|
6324
6837
|
mutations: typeof options.mutations === "function" ? await options.mutations(directory) : options.mutations,
|
|
@@ -6329,7 +6842,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6329
6842
|
resolvePath(targetPath, access = "write") {
|
|
6330
6843
|
if (access === "write" && this.sandboxMode === "readonly")
|
|
6331
6844
|
throw new SecurityError("Sandbox mode is readonly");
|
|
6332
|
-
const resolved =
|
|
6845
|
+
const resolved = path16.isAbsolute(targetPath) ? path16.resolve(targetPath) : path16.resolve(this.workingDir, targetPath);
|
|
6333
6846
|
if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
|
|
6334
6847
|
if (this.approvalMode === "full-access") {
|
|
6335
6848
|
return resolved;
|
|
@@ -6347,12 +6860,12 @@ var SandboxContext = class _SandboxContext {
|
|
|
6347
6860
|
selectFile(operand, access, directoryEntry = false) {
|
|
6348
6861
|
const target = this.resolvePath(operand, access);
|
|
6349
6862
|
if (directoryEntry) {
|
|
6350
|
-
const lexical =
|
|
6351
|
-
const name =
|
|
6352
|
-
resolvePolicyPath(
|
|
6353
|
-
|
|
6863
|
+
const lexical = path16.resolve(this.workingDir, operand);
|
|
6864
|
+
const name = path16.join(
|
|
6865
|
+
resolvePolicyPath(path16.dirname(lexical)),
|
|
6866
|
+
path16.basename(lexical)
|
|
6354
6867
|
);
|
|
6355
|
-
if (target !== name ||
|
|
6868
|
+
if (target !== name || lstatSync10(name, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
6356
6869
|
throw new SecurityError(
|
|
6357
6870
|
"Patch deletion and move require a regular directory entry without a symbolic link"
|
|
6358
6871
|
);
|
|
@@ -6364,7 +6877,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6364
6877
|
...directoryEntry ? { directoryEntry: true } : {}
|
|
6365
6878
|
};
|
|
6366
6879
|
try {
|
|
6367
|
-
const info =
|
|
6880
|
+
const info = lstatSync10(target, { bigint: true });
|
|
6368
6881
|
if (!info.isFile())
|
|
6369
6882
|
throw new SecurityError("Expected a regular file for this operation");
|
|
6370
6883
|
return Object.freeze({
|
|
@@ -6385,6 +6898,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6385
6898
|
sandboxMode: this.sandboxMode,
|
|
6386
6899
|
protectedPaths: this.protectedPaths,
|
|
6387
6900
|
protectedAliasPaths: this.protectedAliasPaths,
|
|
6901
|
+
homeDotDirectory: this.homeDotDirectory,
|
|
6388
6902
|
readOnlyPaths: this.readOnlyPaths,
|
|
6389
6903
|
readOnlyAliasPaths: this.readOnlyAliasPaths,
|
|
6390
6904
|
mutations: this.mutations,
|
|
@@ -6505,7 +7019,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6505
7019
|
writeProtection(target, alias = false) {
|
|
6506
7020
|
const { readOnlyPaths } = gitMetadataPaths(
|
|
6507
7021
|
this.rootDir,
|
|
6508
|
-
|
|
7022
|
+
path16.dirname(target)
|
|
6509
7023
|
);
|
|
6510
7024
|
const projectConfig = workspaceConfigProtection(this.rootDir);
|
|
6511
7025
|
return [
|
|
@@ -6527,7 +7041,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
6527
7041
|
if (access !== "write") return;
|
|
6528
7042
|
if (!isWithin(this.rootDir, value))
|
|
6529
7043
|
throw new SecurityError("Write path escapes the workspace");
|
|
6530
|
-
if (isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
|
|
7044
|
+
if (this.homeDotDirectory && isHomeWriteReserved(this.homeDotDirectory, value) || isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
|
|
6531
7045
|
(entry) => resourceContainsPath(entry, value)
|
|
6532
7046
|
))
|
|
6533
7047
|
throw new SecurityError("Path is read-only under the resource policy");
|
|
@@ -6537,16 +7051,16 @@ var SandboxContext = class _SandboxContext {
|
|
|
6537
7051
|
let probe = resolved;
|
|
6538
7052
|
for (; ; ) {
|
|
6539
7053
|
try {
|
|
6540
|
-
const actual =
|
|
6541
|
-
const target =
|
|
7054
|
+
const actual = realpathSync10(probe);
|
|
7055
|
+
const target = path16.resolve(actual, path16.relative(probe, resolved));
|
|
6542
7056
|
rejectProtected(target);
|
|
6543
7057
|
if (target !== resolved) rejectWrite(target);
|
|
6544
7058
|
if (probe === resolved) {
|
|
6545
|
-
const stat =
|
|
7059
|
+
const stat = lstatSync10(target);
|
|
6546
7060
|
if (!stat.isFile() && !stat.isDirectory())
|
|
6547
7061
|
throw new SecurityError("Unsupported file type");
|
|
6548
7062
|
if (stat.isFile() && stat.nlink > 1) {
|
|
6549
|
-
const inode2 =
|
|
7063
|
+
const inode2 = lstatSync10(target, { bigint: true });
|
|
6550
7064
|
if (isProtectedAlias(inode2, protectedPaths))
|
|
6551
7065
|
throw new SecurityError("Path aliases a protected file");
|
|
6552
7066
|
if (access === "write" && this.isReadOnlyAlias(inode2, target))
|
|
@@ -6556,10 +7070,10 @@ var SandboxContext = class _SandboxContext {
|
|
|
6556
7070
|
return target;
|
|
6557
7071
|
} catch (error) {
|
|
6558
7072
|
if (error.code !== "ENOENT") throw error;
|
|
6559
|
-
const ancestor =
|
|
7073
|
+
const ancestor = path16.dirname(probe);
|
|
6560
7074
|
if (ancestor === probe) throw error;
|
|
6561
7075
|
try {
|
|
6562
|
-
if (
|
|
7076
|
+
if (lstatSync10(probe).isSymbolicLink())
|
|
6563
7077
|
throw new SecurityError("Path contains a dangling symlink");
|
|
6564
7078
|
} catch (entryError) {
|
|
6565
7079
|
if (entryError.code !== "ENOENT")
|
|
@@ -6606,7 +7120,7 @@ var appendReadMetadata = (output, content) => `${output}
|
|
|
6606
7120
|
|
|
6607
7121
|
// src/subagents/workspace-files.ts
|
|
6608
7122
|
import { constants as constants7, promises as fs5 } from "fs";
|
|
6609
|
-
import
|
|
7123
|
+
import path17 from "path";
|
|
6610
7124
|
var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
|
|
6611
7125
|
var readContent = async (handle) => {
|
|
6612
7126
|
const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
|
|
@@ -6619,6 +7133,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
|
|
|
6619
7133
|
const {
|
|
6620
7134
|
protectedPaths,
|
|
6621
7135
|
protectedAliasPaths,
|
|
7136
|
+
homeDotDirectory: homeDotDirectory2,
|
|
6622
7137
|
readOnlyPaths = [],
|
|
6623
7138
|
readOnlyAliasPaths = readOnlyPaths
|
|
6624
7139
|
} = workspacePathProtection(
|
|
@@ -6627,19 +7142,20 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
|
|
|
6627
7142
|
[],
|
|
6628
7143
|
"workspace-write",
|
|
6629
7144
|
false,
|
|
6630
|
-
extraReadOnlyPaths
|
|
7145
|
+
extraReadOnlyPaths,
|
|
7146
|
+
{ recheckHomeLinksOnWrite: true }
|
|
6631
7147
|
);
|
|
6632
7148
|
const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
|
|
6633
7149
|
const resolve = async (name, allowMissing = false) => {
|
|
6634
|
-
const candidate =
|
|
7150
|
+
const candidate = path17.resolve(root, name);
|
|
6635
7151
|
if (blocked(candidate))
|
|
6636
7152
|
throw new Error("Path is protected by the resource policy");
|
|
6637
|
-
const relative =
|
|
6638
|
-
if (relative === ".." || relative.startsWith(`..${
|
|
7153
|
+
const relative = path17.relative(root, candidate);
|
|
7154
|
+
if (relative === ".." || relative.startsWith(`..${path17.sep}`) || path17.isAbsolute(relative))
|
|
6639
7155
|
throw new Error("Path outside delegated workspace");
|
|
6640
7156
|
let part = root;
|
|
6641
|
-
for (const segment of relative.split(
|
|
6642
|
-
part =
|
|
7157
|
+
for (const segment of relative.split(path17.sep).filter(Boolean)) {
|
|
7158
|
+
part = path17.join(part, segment);
|
|
6643
7159
|
try {
|
|
6644
7160
|
if ((await fs5.lstat(part)).isSymbolicLink())
|
|
6645
7161
|
throw new Error(
|
|
@@ -6679,10 +7195,10 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
|
|
|
6679
7195
|
const file = await resolve(name, expected === "missing");
|
|
6680
7196
|
const repositoryReadOnly = gitMetadataPaths(
|
|
6681
7197
|
root,
|
|
6682
|
-
|
|
7198
|
+
path17.dirname(file)
|
|
6683
7199
|
).readOnlyPaths;
|
|
6684
7200
|
const projectConfig = workspaceConfigProtection(root);
|
|
6685
|
-
if (isWorkspaceConfigName(root, file) || [
|
|
7201
|
+
if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
|
|
6686
7202
|
...readOnlyPaths,
|
|
6687
7203
|
...repositoryReadOnly,
|
|
6688
7204
|
...projectConfig.readOnlyPaths
|
|
@@ -6702,7 +7218,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
|
|
|
6702
7218
|
if (approval && expected === "missing")
|
|
6703
7219
|
throw new Error("File already exists");
|
|
6704
7220
|
if (expected === "missing") {
|
|
6705
|
-
await fs5.mkdir(
|
|
7221
|
+
await fs5.mkdir(path17.dirname(file), { recursive: true });
|
|
6706
7222
|
await resolve(name, true);
|
|
6707
7223
|
}
|
|
6708
7224
|
const handle = await fs5.open(
|
|
@@ -6811,17 +7327,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
|
|
|
6811
7327
|
signal?.throwIfAborted();
|
|
6812
7328
|
const dir = pending.shift();
|
|
6813
7329
|
if (!dir) break;
|
|
6814
|
-
const entries = await fs6.opendir(await resolve(
|
|
7330
|
+
const entries = await fs6.opendir(await resolve(path18.relative(root2, dir)));
|
|
6815
7331
|
for await (const entry of entries) {
|
|
6816
7332
|
if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
|
|
6817
7333
|
continue;
|
|
6818
|
-
const child =
|
|
7334
|
+
const child = path18.join(dir, entry.name);
|
|
6819
7335
|
if (blocked(child)) continue;
|
|
6820
7336
|
if (entry.isDirectory()) {
|
|
6821
7337
|
if (pending.length >= 2e3) return { paths, truncated: true };
|
|
6822
7338
|
pending.push(child);
|
|
6823
7339
|
} else if (entry.isFile()) {
|
|
6824
|
-
const name =
|
|
7340
|
+
const name = path18.relative(root2, child);
|
|
6825
7341
|
const selected = await selectRead(name, sandbox).catch(
|
|
6826
7342
|
() => void 0
|
|
6827
7343
|
);
|
|
@@ -7314,7 +7830,10 @@ export {
|
|
|
7314
7830
|
openBrowser,
|
|
7315
7831
|
readEnvValue,
|
|
7316
7832
|
resolveConfigPath,
|
|
7833
|
+
SHARED_PROJECT_CONFIG_ERROR,
|
|
7317
7834
|
resolveProjectConfigPath,
|
|
7835
|
+
resolveDistinctProjectConfigPath,
|
|
7836
|
+
resolveConfigLayers,
|
|
7318
7837
|
resolveImageGenerationConfig,
|
|
7319
7838
|
updateImageGeneration,
|
|
7320
7839
|
resolveModelConfig,
|
|
@@ -7346,6 +7865,10 @@ export {
|
|
|
7346
7865
|
requestUiPrompt,
|
|
7347
7866
|
requestUiPick,
|
|
7348
7867
|
createOpenAiDeviceCodeSession,
|
|
7868
|
+
getChatProviderAuth,
|
|
7869
|
+
getStoredProviderApiKey,
|
|
7870
|
+
setProviderChatAuth,
|
|
7871
|
+
clearProviderEntry,
|
|
7349
7872
|
AuthStore,
|
|
7350
7873
|
SUPPORTED_PROVIDERS,
|
|
7351
7874
|
configuredProviders,
|
|
@@ -7358,6 +7881,10 @@ export {
|
|
|
7358
7881
|
AuthResolver,
|
|
7359
7882
|
isTuiLocalEnvironment,
|
|
7360
7883
|
isProcessEnabled,
|
|
7884
|
+
comparableResourceName,
|
|
7885
|
+
resourceContainsPath,
|
|
7886
|
+
isHomeDotTarget,
|
|
7887
|
+
isHomeWriteReserved,
|
|
7361
7888
|
mxcLifecycle,
|
|
7362
7889
|
singleCommandWords,
|
|
7363
7890
|
isSimpleAndChain,
|
|
@@ -7369,15 +7896,15 @@ export {
|
|
|
7369
7896
|
bindKnownSystemExecutable,
|
|
7370
7897
|
isRootControlledSharedExecutable,
|
|
7371
7898
|
areAllExecutableLinksOutsideRestrictedPaths,
|
|
7372
|
-
comparableResourceName,
|
|
7373
|
-
resourceContainsPath,
|
|
7374
7899
|
resolveSystemBash,
|
|
7375
7900
|
confinedAutoLaunchDirectoryName,
|
|
7376
7901
|
supportsProtectedShell,
|
|
7377
7902
|
platformShellSource,
|
|
7378
7903
|
resolvePolicyPath,
|
|
7379
7904
|
canonicalPolicyPaths,
|
|
7905
|
+
runtimeReadOnlyPaths,
|
|
7380
7906
|
workspacePathProtection,
|
|
7907
|
+
macAdditionalWriteLauncherPaths,
|
|
7381
7908
|
MacSeatbeltBackend,
|
|
7382
7909
|
createMacMxcShellBackend,
|
|
7383
7910
|
UserShellBackend,
|