@sentry/junior 0.313.0 → 0.314.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-CYAvJzZS.js → adapter-JARQvoLw.js} +1 -2
- package/dist/{adapter-context-CVsHoVSf.js → adapter-context-B4BrJZuS.js} +2 -2
- package/dist/{admin-Cyhb4TwZ.js → admin-BXGAySz0.js} +1 -1
- package/dist/{agent-runner-B5y9MsT-.js → agent-runner-qZU5TR8i.js} +797 -118
- package/dist/agent-update-cS7Z9mnG.js +26 -0
- package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +1 -1
- package/dist/api.js +334 -100
- package/dist/{app-DA8-hCMj.d.ts → app-D7tKnw9a.d.ts} +4 -21
- package/dist/app.d.ts +2 -2
- package/dist/app.js +80 -169
- package/dist/{background-compaction-queue-iZXadLV3.js → background-compaction-queue-C_uIBUvS.js} +6 -67
- package/dist/callback-C8SdXCwr.js +68 -0
- package/dist/{catalog-runtime-kkE3hvCX.js → catalog-runtime-BLKtnUL3.js} +1 -1
- package/dist/{channel-access-mt7K6dPh.js → channel-access-BOL29BG3.js} +6 -6
- package/dist/child-message--2G3Ft26.js +19 -0
- package/dist/cli/chat.js +18 -21
- package/dist/cli/check.js +4 -4
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +23 -4
- package/dist/{config-CWbwKj0j.js → config-BIfHKNXN.js} +40 -35
- package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-fnmD2Ifb.js} +5 -7
- package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-DdFQuQDR.js} +1 -1
- package/dist/{logging-DNt-qOIO.js → conversation-privacy-DtZhI91r.js} +188 -2
- package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-DScuDYmN.js} +418 -33
- package/dist/create-CrNt4Ewu.js +212 -0
- package/dist/{credential-sync-DWTOEQrm.js → credential-sync-CtqsGjj1.js} +14 -17
- package/dist/{credentialed-Dyv8b-lu.js → credentialed-dWRA3-oJ.js} +910 -426
- package/dist/{db-PwSRzWWn.js → db-BTmLKZrp.js} +2235 -38
- package/dist/{db-DYGcXYl3.d.ts → db-DcmzbA55.d.ts} +2 -2
- package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
- package/dist/{html-DidUcRhI.js → html-B8rBt7F4.js} +5 -7
- package/dist/{install-2urLLXNt.js → install-OtFboxOM.js} +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/{lineage-BXplQAVH.js → lineage-EULJkGO1.js} +1 -2
- package/dist/{list-DyIyReSV.js → list-C5400AlJ.js} +235 -77
- package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-DL3Lvsm0.js} +4698 -587
- package/dist/markers-DUP8aBOp.js +323 -0
- package/dist/{media-B0pZJ0bG.js → media-FYM-Bl3H.js} +33 -8
- package/dist/{message-Z5YKC-Af.js → message-DuDelZFr.js} +16 -29
- package/dist/{model-input-BhPJYdSV.js → model-input-0osF3pBS.js} +3 -3
- package/dist/nitro.d.ts +2 -4
- package/dist/nitro.js +340 -13
- package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
- package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-PwPMdZJv.js} +1 -1
- package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
- package/dist/{registry-POH4bZC4.js → registry-D6kS6xYH.js} +1402 -64
- package/dist/{resolve-CWtBNSKP.js → resolve-D8CPJcNK.js} +3 -3
- package/dist/result-D090hxr5.js +402 -0
- package/dist/{runner-CsZ_VRxp.js → runner-BU7fgrm-.js} +7 -8
- package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
- package/dist/{schema-DojR2uCL.js → schema-7gW9vBpJ.js} +90 -9
- package/dist/{schema-DBf18QPS.d.ts → schema-BB6E0wyV.d.ts} +138 -5
- package/dist/{service-account-CDYb9hfX.js → service-account-plA-uzIB.js} +6 -5
- package/dist/{skills-B0jP4whm.js → skills-CIosT6bS.js} +3 -3
- package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
- package/dist/{spawn-BjljgExZ.js → spawn-DRjdzh3R.js} +9 -17
- package/dist/{start-conversation-DbVujrwO.js → start-conversation-a4NXH4X9.js} +12 -15
- package/dist/{store-CjXrp-Up.js → store-BuhF1QDm.js} +2 -4
- package/dist/{task-queue-Cwlatjz3.js → task-queue-CrRjFzOh.js} +5 -16
- package/dist/{task-runner--Ke8KSMf.js → task-runner-C-pXsgHM.js} +104 -50
- package/dist/{thread-context-B8exINEe.js → thread-context-CDX4dSZd.js} +8 -9
- package/dist/turn-session-routing-CZTRU8IY.js +116 -0
- package/dist/turn-wake-Bzq1Efrm.js +154 -0
- package/dist/user-customization-B27StpVQ.js +9 -0
- package/dist/{validation-Ce0qbMlT.js → validation-bTq88sya.js} +1 -1
- package/dist/{vercel-queue-q4z8w5QO.js → vercel-queue-nL0Hq3hr.js} +32 -147
- package/dist/{version-DFh4n9nr.js → version-DGUa1dZK.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-D5hzqTcp.js → warmup-CCOuIwAS.js} +639 -137
- package/dist/{worker-CDg9Lbpg.js → worker-AkZg7Dg1.js} +5 -6
- package/migrations/0160_money_micro_usd_repair.sql +99 -0
- package/migrations/0161_agent_config_backfill.sql +34 -0
- package/migrations/0162_inbox_item_deliveries.sql +15 -0
- package/migrations/0163_pg_trgm.sql +2 -0
- package/migrations/0164_search_indexes.sql +4 -0
- package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
- package/migrations/0166_memory_prefix_index.sql +1 -0
- package/migrations/0167_todo_search_indexes.sql +2 -0
- package/migrations/0168_todo_inbox_items.sql +4 -0
- package/migrations/0169_drop_code_urls.sql +2 -0
- package/migrations/meta/0160_snapshot.json +6515 -0
- package/migrations/meta/0161_snapshot.json +6278 -0
- package/migrations/meta/0162_snapshot.json +6404 -0
- package/migrations/meta/0163_snapshot.json +6404 -0
- package/migrations/meta/0164_snapshot.json +6466 -0
- package/migrations/meta/0165_snapshot.json +6466 -0
- package/migrations/meta/0166_snapshot.json +6494 -0
- package/migrations/meta/0167_snapshot.json +6525 -0
- package/migrations/meta/0168_snapshot.json +6525 -0
- package/migrations/meta/0169_snapshot.json +6513 -0
- package/migrations/meta/_journal.json +70 -0
- package/package.json +9 -18
- package/skills/design-automation-skill/SKILL.md +2 -3
- package/dist/actor-BsBdxDXQ.js +0 -208
- package/dist/conversation-privacy-BrMiDN61.js +0 -189
- package/dist/executor-CgWyWfYz.js +0 -1858
- package/dist/fan-out-Cod-yEHG.js +0 -10
- package/dist/ingest-B0AggUEC.js +0 -7931
- package/dist/request-deadline-BUiRYQYj.js +0 -24
- package/dist/service-account-o15pZWcJ.js +0 -931
- package/dist/state-BTawTCme.js +0 -161
- package/dist/statuses-BKwqCPhj.js +0 -69
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { n as normalizePluginPackageNames, o as pluginRoots, t as discoverInstalledPluginPackageContent } from "./package-discovery-DD9vencX.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { C as logInfo, k as setSpanAttributes, w as logWarn } from "./conversation-privacy-DtZhI91r.js";
|
|
3
|
+
import { D as parseActorUserId, E as isUserActor, Wr as juniorUsers, a as getDb } from "./db-BTmLKZrp.js";
|
|
4
|
+
import { i as getStateAdapter } from "./adapter-JARQvoLw.js";
|
|
5
|
+
import { I as MUTATION_LOCK_TTL_MS, R as fenceLock, gt as mapBounded, n as botConfig, r as getChatConfig, z as withLock } from "./config-BIfHKNXN.js";
|
|
4
6
|
import * as z from "zod";
|
|
5
7
|
import path from "node:path";
|
|
6
|
-
import {
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
10
|
+
import { destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
11
|
+
import { eq } from "drizzle-orm";
|
|
7
12
|
import { parse } from "yaml";
|
|
8
13
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
14
|
+
import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
15
|
+
import { Client } from "@modelcontextprotocol/sdk/client";
|
|
16
|
+
import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
9
17
|
// src/chat/plugins/inline-manifest-source.ts
|
|
10
18
|
function setDefined$1(target, key, value) {
|
|
11
19
|
if (value !== void 0) target[key] = value;
|
|
@@ -218,7 +226,7 @@ const domainsSchema = z.array(z.unknown()).min(1, { error: "must be a non-empty
|
|
|
218
226
|
});
|
|
219
227
|
const oauthBearerCredentialsSchema = z.object({ domains: domainsSchema.optional() }).passthrough().extend({
|
|
220
228
|
"api-headers": stringMapSchema.optional(),
|
|
221
|
-
"auth-token-env": envVarString,
|
|
229
|
+
"auth-token-env": envVarString.optional(),
|
|
222
230
|
"auth-token-placeholder": nonEmptyTrimmedString.optional(),
|
|
223
231
|
type: z.literal("oauth-bearer")
|
|
224
232
|
});
|
|
@@ -258,7 +266,7 @@ const mcpOauthClientSourceSchema = z.object({
|
|
|
258
266
|
}).passthrough();
|
|
259
267
|
const accountsSourceSchema = z.object({
|
|
260
268
|
"user-oauth": z.boolean().optional(),
|
|
261
|
-
"service-account": z.object({ tools: nonEmptyStringArraySchema("tools") }).strict().optional()
|
|
269
|
+
"service-account": z.union([z.object({ tools: nonEmptyStringArraySchema("tools") }).strict(), z.object({ operations: nonEmptyStringArraySchema("operations") }).strict()]).optional()
|
|
262
270
|
}).strict();
|
|
263
271
|
const mcpSourceSchema = z.object({
|
|
264
272
|
transport: nonEmptyTrimmedString.refine((value) => value === "http", { error: "must be \"http\"" }).optional(),
|
|
@@ -480,18 +488,20 @@ function assertCommandEnvHostRefsAreExplicitlyExposed(commandEnv, envVars, plugi
|
|
|
480
488
|
if (declaration && declaration.default === void 0 && declaration.exposeToCommandEnv !== true) throw new Error(`Plugin ${pluginName} command-env.${key} references env var ${name}, but env-vars.${name} must set expose-to-command-env: true before host env can be exposed to sandbox`);
|
|
481
489
|
}
|
|
482
490
|
}
|
|
483
|
-
function normalizeCredentials(data, name) {
|
|
491
|
+
function normalizeCredentials(data, name, hasOAuth) {
|
|
484
492
|
if (data["type"] !== "oauth-bearer") throw new Error(`Plugin ${name} has unsupported credentials.type: "${String(data["type"])}"`);
|
|
485
493
|
const result = oauthBearerCredentialsSchema.safeParse(data);
|
|
486
494
|
if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} credentials`));
|
|
487
495
|
if (!result.data.domains) throw new Error(`Plugin ${name} credentials requires domains`);
|
|
488
496
|
const domains = result.data.domains;
|
|
497
|
+
const authTokenEnv = result.data["auth-token-env"];
|
|
498
|
+
if (!authTokenEnv && !hasOAuth) throw new Error(`Plugin ${name} credentials.auth-token-env is required without oauth`);
|
|
489
499
|
const apiHeaders = result.data["api-headers"] ? normalizeStringMap(result.data["api-headers"], `Plugin ${name} credentials.api-headers`, { forbiddenKeys: FORBIDDEN_API_HEADER_NAMES }) : void 0;
|
|
490
500
|
return {
|
|
491
501
|
type: "oauth-bearer",
|
|
492
502
|
domains,
|
|
493
503
|
...apiHeaders ? { apiHeaders } : void 0,
|
|
494
|
-
authTokenEnv:
|
|
504
|
+
...authTokenEnv ? { authTokenEnv } : void 0,
|
|
495
505
|
...result.data["auth-token-placeholder"] ? { authTokenPlaceholder: result.data["auth-token-placeholder"] } : void 0
|
|
496
506
|
};
|
|
497
507
|
}
|
|
@@ -648,16 +658,25 @@ function unloadedMcpTools(mcp, tools) {
|
|
|
648
658
|
}
|
|
649
659
|
/**
|
|
650
660
|
* Validate which accounts the plugin may use against the surfaces that
|
|
651
|
-
* support them
|
|
661
|
+
* support them: MCP OAuth lists tools, and a top-level `oauth` block with
|
|
662
|
+
* `oauth-bearer` credentials lists `egress.fetch` operations.
|
|
652
663
|
*/
|
|
653
|
-
function normalizeAccounts(data,
|
|
664
|
+
function normalizeAccounts(data, surfaces, name) {
|
|
654
665
|
const result = accountsSourceSchema.safeParse(data);
|
|
655
666
|
if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} accounts`));
|
|
656
667
|
const userOAuth = result.data["user-oauth"];
|
|
657
668
|
const serviceAccount = result.data["service-account"];
|
|
658
669
|
if (userOAuth === false && !serviceAccount) throw new Error(`Plugin ${name} accounts.user-oauth false requires accounts.service-account`);
|
|
659
670
|
if (!serviceAccount) return;
|
|
660
|
-
|
|
671
|
+
const { mcp } = surfaces;
|
|
672
|
+
if ("operations" in serviceAccount) {
|
|
673
|
+
if (mcp || !surfaces.oauthBearer) throw new Error(`Plugin ${name} accounts.service-account.operations requires oauth with oauth-bearer credentials and no mcp`);
|
|
674
|
+
return {
|
|
675
|
+
...userOAuth === false ? { userOAuth } : void 0,
|
|
676
|
+
serviceAccount: { operations: serviceAccount.operations }
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
if (!mcp || mcp.auth || mcp.oauthClient) throw new Error(`Plugin ${name} accounts.service-account.tools requires mcp without auth or oauth-client`);
|
|
661
680
|
const unknownTools = unloadedMcpTools(mcp, serviceAccount.tools);
|
|
662
681
|
if (unknownTools.length > 0) throw new Error(`Plugin ${name} accounts.service-account.tools must be listed in mcp.allowed-tools or mcp.wrapped-tools: ${unknownTools.join(", ")}`);
|
|
663
682
|
return {
|
|
@@ -698,11 +717,14 @@ function parseManifestSource(parsedSource, dir, config, options) {
|
|
|
698
717
|
if (apiHeaders && !domains) throw new Error(`Plugin ${data.name} api-headers requires domains`);
|
|
699
718
|
if (domains && !apiHeaders && !data.credentials && options?.allowHookManagedEgress !== true) throw new Error(`Plugin ${data.name} domains requires credentials or api-headers`);
|
|
700
719
|
const commandEnv = data["command-env"] ? normalizeCommandEnv(data["command-env"], `Plugin ${data.name} command-env`, envVars) : void 0;
|
|
701
|
-
const credentials = data.credentials ? normalizeCredentials(data.credentials, data.name) : void 0;
|
|
720
|
+
const credentials = data.credentials ? normalizeCredentials(data.credentials, data.name, Boolean(data.oauth)) : void 0;
|
|
702
721
|
const runtimeDependencies = data["runtime-dependencies"] ? normalizeRuntimeDependencies(data["runtime-dependencies"], data.name) : void 0;
|
|
703
722
|
const runtimePostinstall = data["runtime-postinstall"] ? normalizeRuntimePostinstall(data["runtime-postinstall"], data.name) : void 0;
|
|
704
723
|
const mcp = data.mcp ? normalizeMcp(data.mcp, envVars, data.name) : void 0;
|
|
705
|
-
const accounts = data.accounts ? normalizeAccounts(data.accounts,
|
|
724
|
+
const accounts = data.accounts ? normalizeAccounts(data.accounts, {
|
|
725
|
+
mcp,
|
|
726
|
+
oauthBearer: Boolean(data.oauth && credentials)
|
|
727
|
+
}, data.name) : void 0;
|
|
706
728
|
const manifest = {
|
|
707
729
|
name: data.name,
|
|
708
730
|
displayName: data["display-name"],
|
|
@@ -785,6 +807,16 @@ var CredentialUnavailableError = class extends Error {
|
|
|
785
807
|
this.provider = provider;
|
|
786
808
|
}
|
|
787
809
|
};
|
|
810
|
+
/**
|
|
811
|
+
* The plugin uses only its service account, and that account cannot serve
|
|
812
|
+
* this request. Asking the Actor to connect would not help.
|
|
813
|
+
*/
|
|
814
|
+
var ServiceAccountUnavailableError = class extends CredentialUnavailableError {
|
|
815
|
+
constructor(provider, message) {
|
|
816
|
+
super(provider, message);
|
|
817
|
+
this.name = "ServiceAccountUnavailableError";
|
|
818
|
+
}
|
|
819
|
+
};
|
|
788
820
|
// src/chat/credentials/context.ts
|
|
789
821
|
const exactActorIdSchema = z.string().refine((value) => parseActorUserId(value) === value);
|
|
790
822
|
const exactNonBlankStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
@@ -932,37 +964,6 @@ function credentialUserSubjectId(context) {
|
|
|
932
964
|
if ("type" in context.actor) return context.actor.userId;
|
|
933
965
|
return "subject" in context ? context.subject?.userId : void 0;
|
|
934
966
|
}
|
|
935
|
-
// src/chat/credentials/header-transforms.ts
|
|
936
|
-
/** Merge transforms by domain so later transforms override earlier headers. */
|
|
937
|
-
function mergeHeaderTransforms(transforms) {
|
|
938
|
-
const byDomain = /* @__PURE__ */ new Map();
|
|
939
|
-
for (const transform of transforms) byDomain.set(transform.domain, {
|
|
940
|
-
...byDomain.get(transform.domain) ?? {},
|
|
941
|
-
...transform.headers
|
|
942
|
-
});
|
|
943
|
-
return [...byDomain.entries()].map(([domain, headers]) => ({
|
|
944
|
-
domain,
|
|
945
|
-
headers
|
|
946
|
-
}));
|
|
947
|
-
}
|
|
948
|
-
// src/chat/credentials/oauth-scope.ts
|
|
949
|
-
function parseScope(scope) {
|
|
950
|
-
if (!scope) return [];
|
|
951
|
-
return [...new Set(scope.split(/\s+/).filter(Boolean))].sort();
|
|
952
|
-
}
|
|
953
|
-
/** Normalize OAuth scope strings so persisted grants can be compared reliably. */
|
|
954
|
-
function normalizeOAuthScope(scope) {
|
|
955
|
-
const parsed = parseScope(scope);
|
|
956
|
-
return parsed.length > 0 ? parsed.join(" ") : void 0;
|
|
957
|
-
}
|
|
958
|
-
/** Return whether the stored grant still satisfies the provider's current scope contract. */
|
|
959
|
-
function hasRequiredOAuthScope(storedScope, requiredScope) {
|
|
960
|
-
const required = parseScope(requiredScope);
|
|
961
|
-
if (required.length === 0) return true;
|
|
962
|
-
const stored = new Set(parseScope(storedScope));
|
|
963
|
-
if (stored.size === 0) return false;
|
|
964
|
-
return required.every((scope) => stored.has(scope));
|
|
965
|
-
}
|
|
966
967
|
// src/chat/oauth-response.ts
|
|
967
968
|
const MAX_OAUTH_ERROR_BODY_BYTES = 16384;
|
|
968
969
|
const MAX_OAUTH_ERROR_BODY_READS = MAX_OAUTH_ERROR_BODY_BYTES;
|
|
@@ -1057,6 +1058,83 @@ function fetchWithBoundedOAuthErrorBodies(fetchFn = globalThis.fetch, onErrorRes
|
|
|
1057
1058
|
});
|
|
1058
1059
|
};
|
|
1059
1060
|
}
|
|
1061
|
+
// src/chat/mcp/errors.ts
|
|
1062
|
+
/** Safe failure at an MCP network or OAuth boundary. */
|
|
1063
|
+
var McpProviderError = class extends Error {
|
|
1064
|
+
phase;
|
|
1065
|
+
provider;
|
|
1066
|
+
missingSession;
|
|
1067
|
+
resourceHost;
|
|
1068
|
+
status;
|
|
1069
|
+
constructor(details) {
|
|
1070
|
+
super(`MCP provider ${details.phase.replace("_", " ")} failed`);
|
|
1071
|
+
this.name = "McpProviderError";
|
|
1072
|
+
this.phase = details.phase;
|
|
1073
|
+
this.provider = details.provider;
|
|
1074
|
+
this.missingSession = details.missingSession;
|
|
1075
|
+
this.resourceHost = details.resourceHost;
|
|
1076
|
+
this.status = details.status;
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
function providerStatus(error) {
|
|
1080
|
+
if (!error || typeof error !== "object") return;
|
|
1081
|
+
const value = error;
|
|
1082
|
+
const status = typeof value.status === "number" ? value.status : typeof value.code === "number" ? value.code : void 0;
|
|
1083
|
+
return status !== void 0 && status >= 100 && status <= 599 ? status : void 0;
|
|
1084
|
+
}
|
|
1085
|
+
/** Replace an external MCP failure without retaining its provider-controlled cause. */
|
|
1086
|
+
function toMcpProviderError(error, details) {
|
|
1087
|
+
if (error instanceof McpProviderError) return error;
|
|
1088
|
+
return new McpProviderError({
|
|
1089
|
+
...details,
|
|
1090
|
+
status: details.status ?? providerStatus(error)
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
/** Return safe MCP provider fields for logs and spans. */
|
|
1094
|
+
function getMcpProviderErrorAttributes(error) {
|
|
1095
|
+
if (!(error instanceof McpProviderError)) return {};
|
|
1096
|
+
return {
|
|
1097
|
+
"app.credential.provider": error.provider,
|
|
1098
|
+
"app.mcp.error.phase": error.phase,
|
|
1099
|
+
...error.status !== void 0 ? { "http.response.status_code": error.status } : void 0,
|
|
1100
|
+
...error.resourceHost ? { "server.address": error.resourceHost } : void 0
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
/** Thrown when an MCP failure should be returned as a model-visible tool error. */
|
|
1104
|
+
var McpToolError = class extends Error {
|
|
1105
|
+
constructor(message) {
|
|
1106
|
+
super(message);
|
|
1107
|
+
this.name = "McpToolError";
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
/**
|
|
1111
|
+
* Thrown when a plugin uses only its service account and no Admin has
|
|
1112
|
+
* connected it. The model can tell the person to ask an Admin.
|
|
1113
|
+
*/
|
|
1114
|
+
var McpServiceAccountRequiredError = class extends McpToolError {
|
|
1115
|
+
provider;
|
|
1116
|
+
constructor(provider, displayName) {
|
|
1117
|
+
super(`${displayName} is not available yet. This app uses a shared ${displayName} account for everyone, and an admin must connect it on the dashboard Admin page.`);
|
|
1118
|
+
this.name = "McpServiceAccountRequiredError";
|
|
1119
|
+
this.provider = provider;
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
/** Return the OpenTelemetry error.type value for MCP-aware tool failures. */
|
|
1123
|
+
function getMcpAwareErrorType(error, fallback) {
|
|
1124
|
+
if (error instanceof McpToolError) return "tool_error";
|
|
1125
|
+
if (error instanceof McpProviderError) return "mcp_provider_error";
|
|
1126
|
+
return error instanceof Error ? error.name : fallback;
|
|
1127
|
+
}
|
|
1128
|
+
/** Return the display-safe error message for MCP-aware tool failures. */
|
|
1129
|
+
function getMcpAwareErrorMessage(error) {
|
|
1130
|
+
return error instanceof Error ? error.message : String(error);
|
|
1131
|
+
}
|
|
1132
|
+
/** Return an error message safe for logs and span attributes. */
|
|
1133
|
+
function getMcpAwareTelemetryMessage(error, _privacy) {
|
|
1134
|
+
if (error instanceof McpToolError) return "MCP tool call failed";
|
|
1135
|
+
if (error instanceof McpProviderError) return error.message;
|
|
1136
|
+
return getMcpAwareErrorMessage(error);
|
|
1137
|
+
}
|
|
1060
1138
|
// src/chat/plugins/command-env.ts
|
|
1061
1139
|
const ENV_PLACEHOLDER_RE$1 = /\$\{([A-Z_][A-Z0-9_]*)\}/g;
|
|
1062
1140
|
function resolveValue(manifest, value) {
|
|
@@ -1084,16 +1162,6 @@ function resolvePluginCommandEnv(manifest) {
|
|
|
1084
1162
|
}
|
|
1085
1163
|
return env;
|
|
1086
1164
|
}
|
|
1087
|
-
// src/chat/plugins/auth/auth-token-placeholder.ts
|
|
1088
|
-
/**
|
|
1089
|
-
* The marker that every built-in Sandbox credential placeholder contains,
|
|
1090
|
-
* such as `host_managed_credential` or `ghp_host_managed_credential`.
|
|
1091
|
-
*/
|
|
1092
|
-
const HOST_MANAGED_CREDENTIAL_PLACEHOLDER = "host_managed_credential";
|
|
1093
|
-
/** Resolve the non-secret sandbox token placeholder for token-backed credentials. */
|
|
1094
|
-
function resolveAuthTokenPlaceholder(credentials) {
|
|
1095
|
-
return credentials.authTokenPlaceholder?.trim() || "host_managed_credential";
|
|
1096
|
-
}
|
|
1097
1165
|
// src/chat/plugins/auth/api-headers-broker.ts
|
|
1098
1166
|
const MAX_LEASE_MS$1 = 36e5;
|
|
1099
1167
|
const ENV_PLACEHOLDER_RE = /\$\{([A-Z_][A-Z0-9_]*)\}/g;
|
|
@@ -1139,6 +1207,930 @@ function createApiHeadersBroker(manifest) {
|
|
|
1139
1207
|
};
|
|
1140
1208
|
} };
|
|
1141
1209
|
}
|
|
1210
|
+
// src/chat/conversations/legacy-web-actor-id.ts
|
|
1211
|
+
/**
|
|
1212
|
+
* Web Actor ids that Junior stored before web Actors used the User id.
|
|
1213
|
+
*
|
|
1214
|
+
* Mailbox input, web authorizations, and OAuth credentials saved before that
|
|
1215
|
+
* deploy still carry `dashboard:` and the first 24 hex characters of
|
|
1216
|
+
* sha256(email).
|
|
1217
|
+
*
|
|
1218
|
+
* TODO(dcramer): Delete with its callers after that input and those
|
|
1219
|
+
* authorizations expire and no `dashboard:` credential keys remain.
|
|
1220
|
+
*/
|
|
1221
|
+
const USER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
1222
|
+
/** Return the legacy web Actor id for one email. */
|
|
1223
|
+
function legacyWebActorUserId(email) {
|
|
1224
|
+
return `dashboard:${createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 24)}`;
|
|
1225
|
+
}
|
|
1226
|
+
/** Return every web Actor id that names this User, the User id first. */
|
|
1227
|
+
function webActorUserIds(user) {
|
|
1228
|
+
return [user.id, legacyWebActorUserId(user.email)];
|
|
1229
|
+
}
|
|
1230
|
+
/** Return the legacy web Actor id of a User id, when the User exists. */
|
|
1231
|
+
async function findLegacyWebActorUserId(userId) {
|
|
1232
|
+
if (!USER_ID_PATTERN.test(userId)) return void 0;
|
|
1233
|
+
const rows = await getDb().select({ email: juniorUsers.primaryEmailNormalized }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
|
|
1234
|
+
return rows[0] ? legacyWebActorUserId(rows[0].email) : void 0;
|
|
1235
|
+
}
|
|
1236
|
+
// src/chat/encryption/secret.ts
|
|
1237
|
+
/**
|
|
1238
|
+
* Encrypt secrets that Junior keeps at rest, such as provider credentials.
|
|
1239
|
+
*
|
|
1240
|
+
* AES-256-GCM with keys from `JUNIOR_ENCRYPTION_KEYS` (see `keyring.ts`).
|
|
1241
|
+
* Each value is bound to a context, usually its storage key, and to its key
|
|
1242
|
+
* id as additional authenticated data. A value copied to another key does not
|
|
1243
|
+
* decrypt.
|
|
1244
|
+
*
|
|
1245
|
+
* New values use the active key. Any listed key decrypts. A value from a key
|
|
1246
|
+
* that is not active reports `stale`, so its owner can save it again with the
|
|
1247
|
+
* active key. A value that cannot be decrypted gives `UnreadableSecretError`:
|
|
1248
|
+
* `unknown_key` when its key id is not listed, `invalid` when it is malformed,
|
|
1249
|
+
* altered, or bound to another context.
|
|
1250
|
+
*
|
|
1251
|
+
* There is no per-value salt. The keys are random, not passwords, and each
|
|
1252
|
+
* value has a random IV. The storage key in the AAD already names the
|
|
1253
|
+
* identity that owns the value.
|
|
1254
|
+
*
|
|
1255
|
+
* Envelope: `jenc:v1:<keyId>:<iv>.<ciphertext>.<tag>` (base64url parts).
|
|
1256
|
+
*/
|
|
1257
|
+
const ENVELOPE_PREFIX = "jenc:v1:";
|
|
1258
|
+
const ALGORITHM = "aes-256-gcm";
|
|
1259
|
+
const IV_BYTES = 12;
|
|
1260
|
+
const TAG_BYTES = 16;
|
|
1261
|
+
/** A stored secret that cannot be decrypted with the configured keys. */
|
|
1262
|
+
var UnreadableSecretError = class extends Error {
|
|
1263
|
+
reason;
|
|
1264
|
+
constructor(reason) {
|
|
1265
|
+
super(reason === "unknown_key" ? "Stored secret was encrypted with a key that is not configured" : "Stored secret is malformed or failed authentication");
|
|
1266
|
+
this.name = "UnreadableSecretError";
|
|
1267
|
+
this.reason = reason;
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
function additionalData(keyId, context) {
|
|
1271
|
+
return Buffer.from(`${ENVELOPE_PREFIX}${keyId}\0${context}`, "utf8");
|
|
1272
|
+
}
|
|
1273
|
+
/** Check whether a stored value is an encryption envelope. */
|
|
1274
|
+
function isEncryptedSecret(value) {
|
|
1275
|
+
return typeof value === "string" && value.startsWith(ENVELOPE_PREFIX);
|
|
1276
|
+
}
|
|
1277
|
+
/** Encrypt one secret with the active key and bind it to `context`. */
|
|
1278
|
+
function encryptSecret(plaintext, context, keyring = getChatConfig().encryption) {
|
|
1279
|
+
const { id, key } = keyring.active;
|
|
1280
|
+
const iv = randomBytes(IV_BYTES);
|
|
1281
|
+
const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
|
|
1282
|
+
cipher.setAAD(additionalData(id, context));
|
|
1283
|
+
const parts = [
|
|
1284
|
+
iv,
|
|
1285
|
+
Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]),
|
|
1286
|
+
cipher.getAuthTag()
|
|
1287
|
+
].map((part) => part.toString("base64url"));
|
|
1288
|
+
return `${ENVELOPE_PREFIX}${id}:${parts.join(".")}`;
|
|
1289
|
+
}
|
|
1290
|
+
/** Decrypt an `encryptSecret` envelope with the same `context`. */
|
|
1291
|
+
function decryptSecret(envelope, context, keyring = getChatConfig().encryption) {
|
|
1292
|
+
if (!isEncryptedSecret(envelope)) throw new Error("Stored secret is not an encryption envelope");
|
|
1293
|
+
const [keyId, payload] = envelope.slice(8).split(":");
|
|
1294
|
+
const [iv, ciphertext, tag] = (payload ?? "").split(".").map((part) => Buffer.from(part, "base64url"));
|
|
1295
|
+
if (!keyId || !iv || iv.length !== IV_BYTES || !ciphertext || !tag || tag.length !== TAG_BYTES) throw new UnreadableSecretError("invalid");
|
|
1296
|
+
const match = keyring.keys.find((candidate) => candidate.id === keyId);
|
|
1297
|
+
if (!match) throw new UnreadableSecretError("unknown_key");
|
|
1298
|
+
const decipher = createDecipheriv(ALGORITHM, match.key, iv, { authTagLength: TAG_BYTES });
|
|
1299
|
+
decipher.setAAD(additionalData(keyId, context));
|
|
1300
|
+
decipher.setAuthTag(tag);
|
|
1301
|
+
let text;
|
|
1302
|
+
try {
|
|
1303
|
+
text = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
1304
|
+
} catch {
|
|
1305
|
+
throw new UnreadableSecretError("invalid");
|
|
1306
|
+
}
|
|
1307
|
+
return {
|
|
1308
|
+
stale: match.id !== keyring.active.id,
|
|
1309
|
+
text
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
// src/chat/encryption/state.ts
|
|
1313
|
+
/**
|
|
1314
|
+
* Decrypt one stored envelope. The storage key is the encryption context.
|
|
1315
|
+
* A value that cannot be decrypted, such as one from a key that is no longer
|
|
1316
|
+
* configured or one that was altered, reads as missing. The owner then asks
|
|
1317
|
+
* for the credential again and saves it with the active key.
|
|
1318
|
+
*/
|
|
1319
|
+
function decode(key, envelope) {
|
|
1320
|
+
let decrypted;
|
|
1321
|
+
try {
|
|
1322
|
+
decrypted = decryptSecret(envelope, key);
|
|
1323
|
+
} catch (error) {
|
|
1324
|
+
if (!(error instanceof UnreadableSecretError)) throw error;
|
|
1325
|
+
logWarn("encryption.secret.unreadable", { "error.type": error.reason });
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
return {
|
|
1329
|
+
stale: decrypted.stale,
|
|
1330
|
+
value: JSON.parse(decrypted.text)
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Wrap a state adapter so values are JSON-encoded and encrypted before they
|
|
1335
|
+
* reach storage. Keys and TTLs stay readable. Use it for credentials and
|
|
1336
|
+
* other secrets; delete, lock, and keep plain state on the base adapter.
|
|
1337
|
+
*/
|
|
1338
|
+
function createEncryptedState(state) {
|
|
1339
|
+
return {
|
|
1340
|
+
async get(key) {
|
|
1341
|
+
const stored = await state.get(key);
|
|
1342
|
+
if (!isEncryptedSecret(stored)) return void 0;
|
|
1343
|
+
return decode(key, stored)?.value;
|
|
1344
|
+
},
|
|
1345
|
+
async set(key, value, ttlMs) {
|
|
1346
|
+
await state.set(key, encryptSecret(JSON.stringify(value), key), ttlMs);
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Read a value and report whether it is stale: encrypted with a key that is
|
|
1352
|
+
* not active, or saved before encryption. Long-lived owners save stale values
|
|
1353
|
+
* again, so they move to the active key.
|
|
1354
|
+
*/
|
|
1355
|
+
async function readEncryptedState(state, key) {
|
|
1356
|
+
const stored = await state.get(key);
|
|
1357
|
+
if (stored === null || stored === void 0) return void 0;
|
|
1358
|
+
if (!isEncryptedSecret(stored)) return {
|
|
1359
|
+
stale: true,
|
|
1360
|
+
value: stored
|
|
1361
|
+
};
|
|
1362
|
+
return decode(key, stored);
|
|
1363
|
+
}
|
|
1364
|
+
// src/chat/mcp/auth-store.ts
|
|
1365
|
+
const MCP_AUTH_SESSION_PREFIX = "junior:mcp_oauth_attempt:v2";
|
|
1366
|
+
const MCP_AUTH_CREDENTIALS_PREFIX = "junior:mcp_auth_credentials";
|
|
1367
|
+
const MCP_AUTH_SESSION_INDEX_PREFIX = "junior:mcp_oauth_attempt_index:v2";
|
|
1368
|
+
const MCP_SERVER_SESSION_PREFIX = "junior:mcp_server_session";
|
|
1369
|
+
const MCP_AUTH_SESSION_TTL_MS = 864e5;
|
|
1370
|
+
const MCP_AUTH_CREDENTIALS_TTL_MS = 2592e6;
|
|
1371
|
+
const MCP_SERVER_SESSION_TTL_MS = 864e5;
|
|
1372
|
+
function sessionKey(authSessionId) {
|
|
1373
|
+
return `${MCP_AUTH_SESSION_PREFIX}:${authSessionId}`;
|
|
1374
|
+
}
|
|
1375
|
+
function credentialsKey(userId, provider) {
|
|
1376
|
+
return `${MCP_AUTH_CREDENTIALS_PREFIX}:${userId}:${provider}`;
|
|
1377
|
+
}
|
|
1378
|
+
function sessionIndexKey(userId, provider) {
|
|
1379
|
+
return `${MCP_AUTH_SESSION_INDEX_PREFIX}:${userId}:${provider}`;
|
|
1380
|
+
}
|
|
1381
|
+
function serverSessionKey(userId, provider) {
|
|
1382
|
+
return `${MCP_SERVER_SESSION_PREFIX}:${userId}:${provider}`;
|
|
1383
|
+
}
|
|
1384
|
+
function parseSessionIndex(value) {
|
|
1385
|
+
if (typeof value !== "string") return [];
|
|
1386
|
+
try {
|
|
1387
|
+
const parsed = JSON.parse(value);
|
|
1388
|
+
if (!Array.isArray(parsed)) return [];
|
|
1389
|
+
return [...new Set(parsed.filter((id) => typeof id === "string"))];
|
|
1390
|
+
} catch {
|
|
1391
|
+
return [];
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
const optionalStoredString = z.string().optional().catch(void 0);
|
|
1395
|
+
const mcpAuthSessionSchema = z.object({
|
|
1396
|
+
schemaVersion: z.literal(2),
|
|
1397
|
+
authSessionId: z.string(),
|
|
1398
|
+
provider: z.string(),
|
|
1399
|
+
userId: z.string(),
|
|
1400
|
+
conversationId: z.string(),
|
|
1401
|
+
destination: destinationSchema.optional(),
|
|
1402
|
+
source: sourceSchema.optional(),
|
|
1403
|
+
sessionId: z.string(),
|
|
1404
|
+
userMessage: z.string(),
|
|
1405
|
+
channelId: optionalStoredString,
|
|
1406
|
+
threadTs: optionalStoredString,
|
|
1407
|
+
toolChannelId: optionalStoredString,
|
|
1408
|
+
configuration: z.record(z.string(), z.unknown()).optional().catch(void 0),
|
|
1409
|
+
authorizationUrl: optionalStoredString,
|
|
1410
|
+
codeVerifier: optionalStoredString,
|
|
1411
|
+
createdAtMs: z.number(),
|
|
1412
|
+
updatedAtMs: z.number()
|
|
1413
|
+
});
|
|
1414
|
+
function parseMcpAuthSession(value) {
|
|
1415
|
+
const parsed = mcpAuthSessionSchema.safeParse(value);
|
|
1416
|
+
return parsed.success ? parsed.data : void 0;
|
|
1417
|
+
}
|
|
1418
|
+
const serverSessionSchema = z.object({
|
|
1419
|
+
sessionId: z.string(),
|
|
1420
|
+
updatedAtMs: z.number()
|
|
1421
|
+
});
|
|
1422
|
+
function parseServerSession(value) {
|
|
1423
|
+
if (typeof value !== "string") return;
|
|
1424
|
+
try {
|
|
1425
|
+
const parsed = serverSessionSchema.safeParse(JSON.parse(value));
|
|
1426
|
+
return parsed.success ? parsed.data : void 0;
|
|
1427
|
+
} catch {
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
const storedOAuthClientInformationSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
|
|
1432
|
+
const storedOAuthDiscoveryStateSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
|
|
1433
|
+
const storedOAuthTokensSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
|
|
1434
|
+
const storedCredentialsSchema = z.object({
|
|
1435
|
+
clientInformation: storedOAuthClientInformationSchema$1.optional().catch(void 0),
|
|
1436
|
+
discoveryState: storedOAuthDiscoveryStateSchema$1.optional().catch(void 0),
|
|
1437
|
+
tokens: storedOAuthTokensSchema$1.optional().catch(void 0)
|
|
1438
|
+
});
|
|
1439
|
+
function parseStoredCredentials(value) {
|
|
1440
|
+
try {
|
|
1441
|
+
const parsed = storedCredentialsSchema.safeParse(typeof value === "string" ? JSON.parse(value) : value);
|
|
1442
|
+
return parsed.success ? parsed.data : void 0;
|
|
1443
|
+
} catch {
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
async function readMcpAuthSession(stateAdapter, authSessionId) {
|
|
1448
|
+
const stored = await readEncryptedState(stateAdapter, sessionKey(authSessionId));
|
|
1449
|
+
if (stored?.stale && typeof stored.value === "string") try {
|
|
1450
|
+
return JSON.parse(stored.value);
|
|
1451
|
+
} catch {
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
return stored?.value;
|
|
1455
|
+
}
|
|
1456
|
+
async function getConnectedStateAdapter() {
|
|
1457
|
+
const stateAdapter = getStateAdapter();
|
|
1458
|
+
await stateAdapter.connect();
|
|
1459
|
+
return stateAdapter;
|
|
1460
|
+
}
|
|
1461
|
+
async function getMcpAuthSession(authSessionId) {
|
|
1462
|
+
return parseMcpAuthSession(await readMcpAuthSession(await getConnectedStateAdapter(), authSessionId));
|
|
1463
|
+
}
|
|
1464
|
+
async function putMcpAuthSession(session, ttlMs = MCP_AUTH_SESSION_TTL_MS) {
|
|
1465
|
+
const stateAdapter = await getConnectedStateAdapter();
|
|
1466
|
+
await createEncryptedState(stateAdapter).set(sessionKey(session.authSessionId), session, ttlMs);
|
|
1467
|
+
const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(session.userId, session.provider)));
|
|
1468
|
+
if (!nextIndex.includes(session.authSessionId)) nextIndex.push(session.authSessionId);
|
|
1469
|
+
await stateAdapter.set(sessionIndexKey(session.userId, session.provider), JSON.stringify(nextIndex), ttlMs);
|
|
1470
|
+
}
|
|
1471
|
+
async function patchMcpAuthSession(authSessionId, patch) {
|
|
1472
|
+
const current = await getMcpAuthSession(authSessionId);
|
|
1473
|
+
if (!current) throw new Error(`Unknown MCP auth session: ${authSessionId}`);
|
|
1474
|
+
const next = {
|
|
1475
|
+
...current,
|
|
1476
|
+
...patch,
|
|
1477
|
+
schemaVersion: 2,
|
|
1478
|
+
authSessionId: current.authSessionId,
|
|
1479
|
+
provider: current.provider,
|
|
1480
|
+
userId: current.userId,
|
|
1481
|
+
conversationId: current.conversationId,
|
|
1482
|
+
...current.destination ? { destination: current.destination } : void 0,
|
|
1483
|
+
sessionId: current.sessionId,
|
|
1484
|
+
userMessage: current.userMessage,
|
|
1485
|
+
createdAtMs: current.createdAtMs,
|
|
1486
|
+
updatedAtMs: Date.now()
|
|
1487
|
+
};
|
|
1488
|
+
await putMcpAuthSession(next);
|
|
1489
|
+
return next;
|
|
1490
|
+
}
|
|
1491
|
+
async function deleteMcpAuthSession(authSessionId) {
|
|
1492
|
+
const stateAdapter = await getConnectedStateAdapter();
|
|
1493
|
+
const current = parseMcpAuthSession(await readMcpAuthSession(stateAdapter, authSessionId));
|
|
1494
|
+
await stateAdapter.delete(sessionKey(authSessionId));
|
|
1495
|
+
if (!current) return;
|
|
1496
|
+
const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(current.userId, current.provider))).filter((id) => id !== authSessionId);
|
|
1497
|
+
if (nextIndex.length > 0) {
|
|
1498
|
+
await stateAdapter.set(sessionIndexKey(current.userId, current.provider), JSON.stringify(nextIndex), MCP_AUTH_SESSION_TTL_MS);
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
await stateAdapter.delete(sessionIndexKey(current.userId, current.provider));
|
|
1502
|
+
}
|
|
1503
|
+
async function deleteMcpAuthSessionsForUserProvider(userId, provider) {
|
|
1504
|
+
const stateAdapter = await getConnectedStateAdapter();
|
|
1505
|
+
const indexKey = sessionIndexKey(userId, provider);
|
|
1506
|
+
const authSessionIds = parseSessionIndex(await stateAdapter.get(indexKey));
|
|
1507
|
+
await mapBounded(authSessionIds, (authSessionId) => stateAdapter.delete(sessionKey(authSessionId)));
|
|
1508
|
+
await stateAdapter.delete(indexKey);
|
|
1509
|
+
}
|
|
1510
|
+
async function getMcpStoredOAuthCredentials(userId, provider) {
|
|
1511
|
+
const stateAdapter = await getConnectedStateAdapter();
|
|
1512
|
+
const stored = parseStoredCredentials((await readEncryptedState(stateAdapter, credentialsKey(userId, provider)))?.value);
|
|
1513
|
+
if (stored) return stored;
|
|
1514
|
+
const legacyUserId = await findLegacyWebActorUserId(userId);
|
|
1515
|
+
if (!legacyUserId) return void 0;
|
|
1516
|
+
const legacyKey = credentialsKey(legacyUserId, provider);
|
|
1517
|
+
const legacy = parseStoredCredentials((await readEncryptedState(stateAdapter, legacyKey))?.value);
|
|
1518
|
+
if (!legacy) return void 0;
|
|
1519
|
+
await putMcpStoredOAuthCredentials(userId, provider, legacy);
|
|
1520
|
+
await stateAdapter.delete(legacyKey);
|
|
1521
|
+
return legacy;
|
|
1522
|
+
}
|
|
1523
|
+
async function putMcpStoredOAuthCredentials(userId, provider, value, ttlMs = MCP_AUTH_CREDENTIALS_TTL_MS) {
|
|
1524
|
+
await createEncryptedState(await getConnectedStateAdapter()).set(credentialsKey(userId, provider), value, ttlMs);
|
|
1525
|
+
}
|
|
1526
|
+
async function deleteMcpStoredOAuthCredentials(userId, provider) {
|
|
1527
|
+
const stateAdapter = await getConnectedStateAdapter();
|
|
1528
|
+
await stateAdapter.delete(credentialsKey(userId, provider));
|
|
1529
|
+
const legacyUserId = await findLegacyWebActorUserId(userId);
|
|
1530
|
+
if (legacyUserId) await stateAdapter.delete(credentialsKey(legacyUserId, provider));
|
|
1531
|
+
}
|
|
1532
|
+
async function getMcpServerSessionId(userId, provider) {
|
|
1533
|
+
return parseServerSession(await (await getConnectedStateAdapter()).get(serverSessionKey(userId, provider)))?.sessionId;
|
|
1534
|
+
}
|
|
1535
|
+
async function putMcpServerSessionId(userId, provider, sessionId, ttlMs = MCP_SERVER_SESSION_TTL_MS) {
|
|
1536
|
+
await (await getConnectedStateAdapter()).set(serverSessionKey(userId, provider), JSON.stringify({
|
|
1537
|
+
sessionId,
|
|
1538
|
+
updatedAtMs: Date.now()
|
|
1539
|
+
}), ttlMs);
|
|
1540
|
+
}
|
|
1541
|
+
async function deleteMcpServerSessionId(userId, provider) {
|
|
1542
|
+
await (await getConnectedStateAdapter()).delete(serverSessionKey(userId, provider));
|
|
1543
|
+
}
|
|
1544
|
+
// src/chat/mcp/token-refresh.ts
|
|
1545
|
+
/**
|
|
1546
|
+
* One MCP token refresh at a time for each person and provider.
|
|
1547
|
+
*
|
|
1548
|
+
* Providers such as Notion rotate the refresh token on each refresh and
|
|
1549
|
+
* revoke the whole grant when a retired refresh token comes back. A Turn
|
|
1550
|
+
* and a link card read can both find an expired access token at once, so
|
|
1551
|
+
* every refresh of a stored person login runs under one lock. A caller
|
|
1552
|
+
* that waited gets the tokens that the first caller saved, and its retired
|
|
1553
|
+
* refresh token never reaches the provider.
|
|
1554
|
+
*/
|
|
1555
|
+
const REFRESH_LOCK_TTL_MS$1 = 3e4;
|
|
1556
|
+
const REFRESH_WAIT_MS = 3e4;
|
|
1557
|
+
function refreshTokenOf(body) {
|
|
1558
|
+
const params = body instanceof URLSearchParams ? body : typeof body === "string" ? new URLSearchParams(body) : void 0;
|
|
1559
|
+
return params?.get("grant_type") === "refresh_token" ? params.get("refresh_token") ?? void 0 : void 0;
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* Wrap the fetch of an MCP client so that each refresh-token request for
|
|
1563
|
+
* this login runs under the shared lock. Other requests pass through.
|
|
1564
|
+
*/
|
|
1565
|
+
function serializeMcpTokenRefresh(owner, fetchFn = globalThis.fetch) {
|
|
1566
|
+
let sentAccessToken;
|
|
1567
|
+
return async (input, init) => {
|
|
1568
|
+
const sentRefreshToken = refreshTokenOf(init?.body);
|
|
1569
|
+
if (!sentRefreshToken) {
|
|
1570
|
+
const authorization = new Headers(init?.headers).get("authorization");
|
|
1571
|
+
if (authorization) sentAccessToken = authorization.replace(/^Bearer\s+/i, "");
|
|
1572
|
+
return await fetchFn(input, init);
|
|
1573
|
+
}
|
|
1574
|
+
const { provider, userId } = await owner();
|
|
1575
|
+
const state = getStateAdapter();
|
|
1576
|
+
await state.connect();
|
|
1577
|
+
const attempt = await withLock(state, `mcp-oauth-refresh:${userId}:${provider}`, async (lock) => {
|
|
1578
|
+
const stored = await getMcpStoredOAuthCredentials(userId, provider);
|
|
1579
|
+
const current = stored?.tokens;
|
|
1580
|
+
if (!current) return Response.json({ error: "invalid_grant" }, { status: 400 });
|
|
1581
|
+
if (current.refresh_token && current.refresh_token !== sentRefreshToken || sentAccessToken && current.access_token !== sentAccessToken) return Response.json(current);
|
|
1582
|
+
const response = await fetchFn(input, init);
|
|
1583
|
+
if (!response.ok) return response;
|
|
1584
|
+
const tokens = await response.clone().json();
|
|
1585
|
+
if (typeof tokens["access_token"] !== "string") return response;
|
|
1586
|
+
await fenceLock(state, lock, REFRESH_LOCK_TTL_MS$1);
|
|
1587
|
+
await putMcpStoredOAuthCredentials(userId, provider, {
|
|
1588
|
+
...stored,
|
|
1589
|
+
tokens: {
|
|
1590
|
+
...current,
|
|
1591
|
+
...tokens,
|
|
1592
|
+
refresh_token: typeof tokens["refresh_token"] === "string" ? tokens["refresh_token"] : sentRefreshToken
|
|
1593
|
+
}
|
|
1594
|
+
});
|
|
1595
|
+
return response;
|
|
1596
|
+
}, {
|
|
1597
|
+
keepAlive: true,
|
|
1598
|
+
ttlMs: REFRESH_LOCK_TTL_MS$1,
|
|
1599
|
+
waitMs: REFRESH_WAIT_MS
|
|
1600
|
+
});
|
|
1601
|
+
if (!attempt.acquired) throw new Error(`Timed out waiting for the ${provider} MCP token refresh`);
|
|
1602
|
+
return attempt.value;
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
// src/chat/mcp/client.ts
|
|
1606
|
+
const MCP_CLIENT_INFO = {
|
|
1607
|
+
name: "junior-mcp-client",
|
|
1608
|
+
version: "1.0.0"
|
|
1609
|
+
};
|
|
1610
|
+
const MCP_TOOLS_CALL_METHOD = "tools/call";
|
|
1611
|
+
function getDefaultPort(url) {
|
|
1612
|
+
if (url.protocol === "https:") return 443;
|
|
1613
|
+
if (url.protocol === "http:") return 80;
|
|
1614
|
+
}
|
|
1615
|
+
function getMcpNetworkAttributes(url) {
|
|
1616
|
+
const port = url.port ? Number(url.port) : getDefaultPort(url);
|
|
1617
|
+
return {
|
|
1618
|
+
"server.address": url.hostname,
|
|
1619
|
+
...port !== void 0 ? { "server.port": port } : void 0,
|
|
1620
|
+
...url.protocol === "http:" || url.protocol === "https:" ? {
|
|
1621
|
+
"network.protocol.name": "http",
|
|
1622
|
+
"network.transport": "tcp"
|
|
1623
|
+
} : void 0
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
var McpAuthorizationRequiredError = class extends Error {
|
|
1627
|
+
provider;
|
|
1628
|
+
constructor(provider, message) {
|
|
1629
|
+
super(message);
|
|
1630
|
+
this.name = "McpAuthorizationRequiredError";
|
|
1631
|
+
this.provider = provider;
|
|
1632
|
+
}
|
|
1633
|
+
};
|
|
1634
|
+
function isMissingSessionError(error) {
|
|
1635
|
+
return error instanceof StreamableHTTPError && (error.code === 404 || /Session not found/i.test(error.message));
|
|
1636
|
+
}
|
|
1637
|
+
var PluginMcpClient = class {
|
|
1638
|
+
client;
|
|
1639
|
+
clientPromise;
|
|
1640
|
+
lastAttemptedTransportSessionId;
|
|
1641
|
+
providerStatusStore = new AsyncLocalStorage();
|
|
1642
|
+
transport;
|
|
1643
|
+
listedTools;
|
|
1644
|
+
resourceHost;
|
|
1645
|
+
plugin;
|
|
1646
|
+
options;
|
|
1647
|
+
constructor(plugin, options = {}) {
|
|
1648
|
+
this.plugin = plugin;
|
|
1649
|
+
this.options = options;
|
|
1650
|
+
const url = plugin.manifest.mcp?.url;
|
|
1651
|
+
this.resourceHost = url ? new URL(url).hostname : void 0;
|
|
1652
|
+
}
|
|
1653
|
+
async listTools() {
|
|
1654
|
+
if (this.listedTools) return [...this.listedTools];
|
|
1655
|
+
return await this.withSessionRecovery(async () => {
|
|
1656
|
+
const client = await this.getClient();
|
|
1657
|
+
const discovered = [];
|
|
1658
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1659
|
+
let cursor;
|
|
1660
|
+
do {
|
|
1661
|
+
const result = await this.wrapAuth(() => client.listTools(cursor ? { cursor } : void 0), "list_tools");
|
|
1662
|
+
await this.syncTransportSessionId();
|
|
1663
|
+
for (const tool of result.tools) {
|
|
1664
|
+
if (seen.has(tool.name)) continue;
|
|
1665
|
+
seen.add(tool.name);
|
|
1666
|
+
discovered.push(tool);
|
|
1667
|
+
}
|
|
1668
|
+
cursor = result.nextCursor;
|
|
1669
|
+
} while (cursor);
|
|
1670
|
+
this.listedTools = discovered.sort((left, right) => left.name.localeCompare(right.name));
|
|
1671
|
+
return [...this.listedTools];
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
async callTool(name, args, signal) {
|
|
1675
|
+
return await this.withSessionRecovery(async () => {
|
|
1676
|
+
const client = await this.getClient();
|
|
1677
|
+
const mcp = this.plugin.manifest.mcp;
|
|
1678
|
+
if (mcp) {
|
|
1679
|
+
const url = new URL(mcp.url);
|
|
1680
|
+
setSpanAttributes({
|
|
1681
|
+
"mcp.method.name": MCP_TOOLS_CALL_METHOD,
|
|
1682
|
+
"gen_ai.operation.name": "execute_tool",
|
|
1683
|
+
...this.transport?.sessionId ? { "mcp.session.id": this.transport.sessionId } : void 0,
|
|
1684
|
+
...this.transport?.protocolVersion ? { "mcp.protocol.version": this.transport.protocolVersion } : void 0,
|
|
1685
|
+
...getMcpNetworkAttributes(url)
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1688
|
+
const result = await this.wrapAuth(() => client.callTool({
|
|
1689
|
+
name,
|
|
1690
|
+
arguments: args ?? {}
|
|
1691
|
+
}, void 0, signal ? { signal } : void 0), "call_tool");
|
|
1692
|
+
await this.syncTransportSessionId();
|
|
1693
|
+
return result;
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
async close() {
|
|
1697
|
+
await this.disposeClient();
|
|
1698
|
+
}
|
|
1699
|
+
async withSessionRecovery(operation) {
|
|
1700
|
+
try {
|
|
1701
|
+
return await operation();
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
await this.syncTransportSessionId();
|
|
1704
|
+
if (!await this.shouldResetMissingSession(error)) throw error;
|
|
1705
|
+
await this.clearStoredTransportSessionId();
|
|
1706
|
+
await this.cleanupClientAfterFailure();
|
|
1707
|
+
return await operation();
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
async getClient() {
|
|
1711
|
+
if (this.client) return this.client;
|
|
1712
|
+
if (this.clientPromise) return await this.clientPromise;
|
|
1713
|
+
const clientPromise = this.connectClient();
|
|
1714
|
+
this.clientPromise = clientPromise;
|
|
1715
|
+
try {
|
|
1716
|
+
return await clientPromise;
|
|
1717
|
+
} finally {
|
|
1718
|
+
if (this.clientPromise === clientPromise) this.clientPromise = void 0;
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
async connectClient() {
|
|
1722
|
+
const mcp = this.plugin.manifest.mcp;
|
|
1723
|
+
if (!mcp) throw new Error(`Plugin "${this.plugin.manifest.name}" does not declare MCP config`);
|
|
1724
|
+
const headers = mcp.headers ? resolvePluginHeaderEnvRefs(this.plugin.manifest.name, mcp.headers, "MCP header") : void 0;
|
|
1725
|
+
const sessionId = await this.getStoredTransportSessionId();
|
|
1726
|
+
this.lastAttemptedTransportSessionId = sessionId;
|
|
1727
|
+
const loginProvider = this.options.authProvider;
|
|
1728
|
+
const mcpLoginOwner = loginProvider?.mcpLoginOwner?.bind(loginProvider);
|
|
1729
|
+
const providerFetch = mcpLoginOwner ? serializeMcpTokenRefresh(mcpLoginOwner, this.options.fetch) : this.options.fetch;
|
|
1730
|
+
const transport = new StreamableHTTPClientTransport(new URL(mcp.url), {
|
|
1731
|
+
...headers ? { requestInit: { headers } } : void 0,
|
|
1732
|
+
fetch: fetchWithBoundedOAuthErrorBodies(providerFetch, (status) => {
|
|
1733
|
+
const store = this.providerStatusStore.getStore();
|
|
1734
|
+
if (store) store.status = status;
|
|
1735
|
+
}),
|
|
1736
|
+
...this.options.authProvider ? { authProvider: this.options.authProvider } : void 0,
|
|
1737
|
+
...sessionId ? { sessionId } : void 0
|
|
1738
|
+
});
|
|
1739
|
+
const client = new Client(MCP_CLIENT_INFO, { capabilities: {} });
|
|
1740
|
+
this.transport = transport;
|
|
1741
|
+
try {
|
|
1742
|
+
await this.wrapAuth(() => client.connect(transport), "connect");
|
|
1743
|
+
this.client = client;
|
|
1744
|
+
await this.syncTransportSessionId();
|
|
1745
|
+
return client;
|
|
1746
|
+
} catch (error) {
|
|
1747
|
+
await this.syncTransportSessionId();
|
|
1748
|
+
await this.cleanupClientAfterFailure();
|
|
1749
|
+
throw error;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
async wrapAuth(operation, phase) {
|
|
1753
|
+
const store = {};
|
|
1754
|
+
return await this.providerStatusStore.run(store, async () => {
|
|
1755
|
+
try {
|
|
1756
|
+
return await operation();
|
|
1757
|
+
} catch (error) {
|
|
1758
|
+
if (error instanceof McpAuthorizationRequiredError) throw error;
|
|
1759
|
+
if (error instanceof UnauthorizedError) throw new McpAuthorizationRequiredError(this.plugin.manifest.name, `MCP authorization required for plugin "${this.plugin.manifest.name}"`);
|
|
1760
|
+
throw toMcpProviderError(error, {
|
|
1761
|
+
phase,
|
|
1762
|
+
provider: this.plugin.manifest.name,
|
|
1763
|
+
missingSession: isMissingSessionError(error) || void 0,
|
|
1764
|
+
resourceHost: this.resourceHost,
|
|
1765
|
+
status: store.status
|
|
1766
|
+
});
|
|
1767
|
+
}
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
async shouldResetMissingSession(error) {
|
|
1771
|
+
if (!(error instanceof McpProviderError && error.missingSession || isMissingSessionError(error))) return false;
|
|
1772
|
+
return Boolean(this.transport?.sessionId ?? this.lastAttemptedTransportSessionId ?? await this.getStoredTransportSessionId());
|
|
1773
|
+
}
|
|
1774
|
+
resetClientState() {
|
|
1775
|
+
const transport = this.transport;
|
|
1776
|
+
this.listedTools = void 0;
|
|
1777
|
+
this.transport = void 0;
|
|
1778
|
+
this.client = void 0;
|
|
1779
|
+
this.clientPromise = void 0;
|
|
1780
|
+
return transport;
|
|
1781
|
+
}
|
|
1782
|
+
async cleanupClientAfterFailure() {
|
|
1783
|
+
const transport = this.resetClientState();
|
|
1784
|
+
if (!transport) return;
|
|
1785
|
+
try {
|
|
1786
|
+
await transport.close();
|
|
1787
|
+
} catch {}
|
|
1788
|
+
}
|
|
1789
|
+
async disposeClient() {
|
|
1790
|
+
const transport = this.resetClientState();
|
|
1791
|
+
if (transport) try {
|
|
1792
|
+
await transport.close();
|
|
1793
|
+
} catch (error) {
|
|
1794
|
+
throw toMcpProviderError(error, {
|
|
1795
|
+
phase: "close",
|
|
1796
|
+
provider: this.plugin.manifest.name,
|
|
1797
|
+
resourceHost: this.resourceHost
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
async getStoredTransportSessionId() {
|
|
1802
|
+
return await this.options.authProvider?.getMcpServerSessionId?.();
|
|
1803
|
+
}
|
|
1804
|
+
async clearStoredTransportSessionId() {
|
|
1805
|
+
const provider = this.options.authProvider;
|
|
1806
|
+
this.lastAttemptedTransportSessionId = void 0;
|
|
1807
|
+
await provider?.saveMcpServerSessionId?.(void 0);
|
|
1808
|
+
}
|
|
1809
|
+
async syncTransportSessionId() {
|
|
1810
|
+
const provider = this.options.authProvider;
|
|
1811
|
+
const sessionId = this.transport?.sessionId;
|
|
1812
|
+
if (!provider?.saveMcpServerSessionId || !sessionId) return;
|
|
1813
|
+
this.lastAttemptedTransportSessionId = sessionId;
|
|
1814
|
+
await provider.saveMcpServerSessionId(sessionId);
|
|
1815
|
+
}
|
|
1816
|
+
};
|
|
1817
|
+
// src/chat/mcp/service-account.ts
|
|
1818
|
+
/**
|
|
1819
|
+
* MCP service account credentials.
|
|
1820
|
+
*
|
|
1821
|
+
* This is the MCP surface of a plugin's service account. See
|
|
1822
|
+
* `@/chat/credentials/service-account` for the credential order and the
|
|
1823
|
+
* policy. An Admin connects the account from the dashboard Admin page, or
|
|
1824
|
+
* with `junior service-account connect <plugin>`. The credential stays on
|
|
1825
|
+
* the host. The sandbox and the model never get it.
|
|
1826
|
+
*/
|
|
1827
|
+
const SERVICE_ACCOUNT_KEY_PREFIX$1 = "junior:mcp_service_account";
|
|
1828
|
+
const SIGN_IN_KEY_PREFIX$1 = "junior:mcp_service_account_sign_in";
|
|
1829
|
+
const SIGN_IN_TTL_MS$1 = 6e5;
|
|
1830
|
+
const UPDATE_LOCK_WAIT_MS = 5e3;
|
|
1831
|
+
function serviceAccountKey$1(provider) {
|
|
1832
|
+
return `${SERVICE_ACCOUNT_KEY_PREFIX$1}:${provider}`;
|
|
1833
|
+
}
|
|
1834
|
+
function updateLockKey$1(provider) {
|
|
1835
|
+
return `${serviceAccountKey$1(provider)}:update`;
|
|
1836
|
+
}
|
|
1837
|
+
const storedOAuthClientInformationSchema = z.custom((value) => typeof value === "object" && value !== null);
|
|
1838
|
+
const storedOAuthDiscoveryStateSchema = z.custom((value) => typeof value === "object" && value !== null);
|
|
1839
|
+
const storedOAuthTokensSchema = z.custom((value) => typeof value === "object" && value !== null);
|
|
1840
|
+
const credentialsSchema$1 = z.object({
|
|
1841
|
+
clientInformation: storedOAuthClientInformationSchema,
|
|
1842
|
+
connectedAtMs: z.number(),
|
|
1843
|
+
connectedBy: z.string().optional().catch(void 0),
|
|
1844
|
+
discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
|
|
1845
|
+
redirectUrl: z.string(),
|
|
1846
|
+
tokens: storedOAuthTokensSchema
|
|
1847
|
+
});
|
|
1848
|
+
function parseCredentials$1(value) {
|
|
1849
|
+
try {
|
|
1850
|
+
const parsed = credentialsSchema$1.safeParse(typeof value === "string" ? JSON.parse(value) : value);
|
|
1851
|
+
return parsed.success ? parsed.data : void 0;
|
|
1852
|
+
} catch {
|
|
1853
|
+
return;
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
/** Read the connected service account for one plugin, if any. */
|
|
1857
|
+
async function getMcpServiceAccountCredentials(provider) {
|
|
1858
|
+
const stored = await readEncryptedState(getStateAdapter(), serviceAccountKey$1(provider));
|
|
1859
|
+
const credentials = parseCredentials$1(stored?.value);
|
|
1860
|
+
if (credentials && stored?.stale) await saveStaleCredentials(provider);
|
|
1861
|
+
return credentials;
|
|
1862
|
+
}
|
|
1863
|
+
/**
|
|
1864
|
+
* Save stale credentials again with the active key. It runs only when the
|
|
1865
|
+
* update lock is free, so it cannot write back a refresh token that an
|
|
1866
|
+
* update replaced.
|
|
1867
|
+
*/
|
|
1868
|
+
async function saveStaleCredentials(provider) {
|
|
1869
|
+
const state = getStateAdapter();
|
|
1870
|
+
await withLock(state, updateLockKey$1(provider), async (lock) => {
|
|
1871
|
+
const key = serviceAccountKey$1(provider);
|
|
1872
|
+
const current = await readEncryptedState(state, key);
|
|
1873
|
+
const credentials = parseCredentials$1(current?.value);
|
|
1874
|
+
if (!current?.stale || !credentials) return;
|
|
1875
|
+
await fenceLock(state, lock);
|
|
1876
|
+
await putMcpServiceAccountCredentials(provider, credentials);
|
|
1877
|
+
}, { ttlMs: MUTATION_LOCK_TTL_MS });
|
|
1878
|
+
}
|
|
1879
|
+
/** Save the service account for one plugin. It does not expire. */
|
|
1880
|
+
async function putMcpServiceAccountCredentials(provider, credentials) {
|
|
1881
|
+
await createEncryptedState(getStateAdapter()).set(serviceAccountKey$1(provider), credentials);
|
|
1882
|
+
}
|
|
1883
|
+
/** Remove the service account for one plugin. The provider grant stays until the provider revokes it. */
|
|
1884
|
+
async function deleteMcpServiceAccountCredentials(provider) {
|
|
1885
|
+
await getStateAdapter().delete(serviceAccountKey$1(provider));
|
|
1886
|
+
}
|
|
1887
|
+
function clientMetadata(redirectUrl) {
|
|
1888
|
+
return {
|
|
1889
|
+
client_name: `${botConfig.userName} MCP Service Account`,
|
|
1890
|
+
redirect_uris: [redirectUrl],
|
|
1891
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
1892
|
+
response_types: ["code"],
|
|
1893
|
+
token_endpoint_auth_method: "none"
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
function reconnectMessage(provider) {
|
|
1897
|
+
return `The ${provider} service account is not authorized anymore. An admin must run \`junior service-account connect ${provider}\`.`;
|
|
1898
|
+
}
|
|
1899
|
+
/**
|
|
1900
|
+
* Build the OAuth client provider for a connected service account.
|
|
1901
|
+
*
|
|
1902
|
+
* It refreshes tokens like a user connection but never starts a new sign-in.
|
|
1903
|
+
* Many turns share this account, so it reads the store on each request and
|
|
1904
|
+
* writes each change under a lock. When the provider rejects a refresh token
|
|
1905
|
+
* that another turn already replaced, it retries with the stored one. It
|
|
1906
|
+
* deletes the stored grant only when the provider rejected the stored token
|
|
1907
|
+
* itself, and then throws `McpAuthorizationRequiredError` so the tool manager
|
|
1908
|
+
* can fall back to Actor auth or report the missing account. A refresh that
|
|
1909
|
+
* fails for another reason, such as a network error, keeps the account.
|
|
1910
|
+
*/
|
|
1911
|
+
function createMcpServiceAccountClientProvider(provider, connected) {
|
|
1912
|
+
let lastRefreshToken = connected.tokens.refresh_token;
|
|
1913
|
+
let tokensRejected = false;
|
|
1914
|
+
const withStoreLock = async (run) => {
|
|
1915
|
+
const state = getStateAdapter();
|
|
1916
|
+
const result = await withLock(state, updateLockKey$1(provider), async (lock) => await run(() => fenceLock(state, lock)), {
|
|
1917
|
+
ttlMs: MUTATION_LOCK_TTL_MS,
|
|
1918
|
+
waitMs: UPDATE_LOCK_WAIT_MS
|
|
1919
|
+
});
|
|
1920
|
+
if (!result.acquired) throw new Error(`Timed out waiting to update the ${provider} service account`);
|
|
1921
|
+
return result.value;
|
|
1922
|
+
};
|
|
1923
|
+
const update = async (patch) => {
|
|
1924
|
+
await withStoreLock(async (fence) => {
|
|
1925
|
+
const current = await getMcpServiceAccountCredentials(provider);
|
|
1926
|
+
if (!current) throw new Error(reconnectMessage(provider));
|
|
1927
|
+
await fence();
|
|
1928
|
+
await putMcpServiceAccountCredentials(provider, {
|
|
1929
|
+
...current,
|
|
1930
|
+
...patch
|
|
1931
|
+
});
|
|
1932
|
+
});
|
|
1933
|
+
};
|
|
1934
|
+
return {
|
|
1935
|
+
redirectUrl: connected.redirectUrl,
|
|
1936
|
+
clientMetadata: clientMetadata(connected.redirectUrl),
|
|
1937
|
+
clientInformation: async () => (await getMcpServiceAccountCredentials(provider))?.clientInformation,
|
|
1938
|
+
saveClientInformation: async (clientInformation) => {
|
|
1939
|
+
await update({ clientInformation });
|
|
1940
|
+
},
|
|
1941
|
+
tokens: async () => {
|
|
1942
|
+
const tokens = (await getMcpServiceAccountCredentials(provider))?.tokens;
|
|
1943
|
+
if (tokensRejected) {
|
|
1944
|
+
if (!tokens || tokens.refresh_token === lastRefreshToken) return;
|
|
1945
|
+
tokensRejected = false;
|
|
1946
|
+
}
|
|
1947
|
+
lastRefreshToken = tokens?.refresh_token;
|
|
1948
|
+
return tokens;
|
|
1949
|
+
},
|
|
1950
|
+
saveTokens: async (tokens) => {
|
|
1951
|
+
tokensRejected = false;
|
|
1952
|
+
lastRefreshToken = tokens.refresh_token;
|
|
1953
|
+
await update({ tokens });
|
|
1954
|
+
},
|
|
1955
|
+
discoveryState: async () => (await getMcpServiceAccountCredentials(provider))?.discoveryState,
|
|
1956
|
+
saveDiscoveryState: async (discoveryState) => {
|
|
1957
|
+
await update({ discoveryState });
|
|
1958
|
+
},
|
|
1959
|
+
invalidateCredentials: (scope) => {
|
|
1960
|
+
if (scope === "all" || scope === "tokens") tokensRejected = true;
|
|
1961
|
+
},
|
|
1962
|
+
redirectToAuthorization: async () => {
|
|
1963
|
+
if (!await withStoreLock(async (fence) => {
|
|
1964
|
+
const stored = await getMcpServiceAccountCredentials(provider);
|
|
1965
|
+
if (!stored) return true;
|
|
1966
|
+
if (!tokensRejected && stored.tokens.refresh_token || stored.tokens.refresh_token !== lastRefreshToken) return false;
|
|
1967
|
+
await fence();
|
|
1968
|
+
await deleteMcpServiceAccountCredentials(provider);
|
|
1969
|
+
logWarn("mcp.service_account.disconnected", { "app.plugin.name": provider });
|
|
1970
|
+
return true;
|
|
1971
|
+
})) throw new Error(`The ${provider} service account could not refresh its token. Try again later.`);
|
|
1972
|
+
throw new McpAuthorizationRequiredError(provider, reconnectMessage(provider));
|
|
1973
|
+
},
|
|
1974
|
+
saveCodeVerifier: () => void 0,
|
|
1975
|
+
codeVerifier: () => {
|
|
1976
|
+
throw new Error(reconnectMessage(provider));
|
|
1977
|
+
}
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
function signInKey$1(state) {
|
|
1981
|
+
return `${SIGN_IN_KEY_PREFIX$1}:${state}`;
|
|
1982
|
+
}
|
|
1983
|
+
const signInSchema$1 = z.object({
|
|
1984
|
+
clientInformation: storedOAuthClientInformationSchema,
|
|
1985
|
+
codeVerifier: z.string(),
|
|
1986
|
+
discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
|
|
1987
|
+
provider: z.string(),
|
|
1988
|
+
redirectUrl: z.string(),
|
|
1989
|
+
startedBy: z.string().optional().catch(void 0)
|
|
1990
|
+
});
|
|
1991
|
+
function parseSignIn(value) {
|
|
1992
|
+
const parsed = signInSchema$1.safeParse(value);
|
|
1993
|
+
return parsed.success ? parsed.data : void 0;
|
|
1994
|
+
}
|
|
1995
|
+
/** Build an OAuth client provider that keeps sign-in state in memory. */
|
|
1996
|
+
function signInProvider(input) {
|
|
1997
|
+
const captured = {
|
|
1998
|
+
clientInformation: input.pending?.clientInformation,
|
|
1999
|
+
codeVerifier: input.pending?.codeVerifier,
|
|
2000
|
+
discoveryState: input.pending?.discoveryState
|
|
2001
|
+
};
|
|
2002
|
+
return {
|
|
2003
|
+
captured,
|
|
2004
|
+
provider: {
|
|
2005
|
+
redirectUrl: input.redirectUrl,
|
|
2006
|
+
clientMetadata: clientMetadata(input.redirectUrl),
|
|
2007
|
+
...input.state ? { state: () => input.state } : void 0,
|
|
2008
|
+
clientInformation: () => captured.clientInformation,
|
|
2009
|
+
saveClientInformation: (next) => {
|
|
2010
|
+
captured.clientInformation = next;
|
|
2011
|
+
},
|
|
2012
|
+
tokens: () => captured.tokens,
|
|
2013
|
+
saveTokens: (next) => {
|
|
2014
|
+
captured.tokens = next;
|
|
2015
|
+
},
|
|
2016
|
+
discoveryState: () => captured.discoveryState,
|
|
2017
|
+
saveDiscoveryState: (next) => {
|
|
2018
|
+
captured.discoveryState = next;
|
|
2019
|
+
},
|
|
2020
|
+
redirectToAuthorization: (url) => {
|
|
2021
|
+
captured.authorizationUrl = url;
|
|
2022
|
+
},
|
|
2023
|
+
saveCodeVerifier: (next) => {
|
|
2024
|
+
captured.codeVerifier = next;
|
|
2025
|
+
},
|
|
2026
|
+
codeVerifier: () => {
|
|
2027
|
+
if (!captured.codeVerifier) throw new Error("Missing MCP OAuth code verifier");
|
|
2028
|
+
return captured.codeVerifier;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
function requireServiceAccountMcp(plugin) {
|
|
2034
|
+
const mcp = plugin.manifest.mcp;
|
|
2035
|
+
if (!mcp || !plugin.manifest.accounts?.serviceAccount) throw new Error(`Plugin "${plugin.manifest.name}" does not support a service account`);
|
|
2036
|
+
return mcp;
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* Start a service account sign-in and return the provider sign-in URL.
|
|
2040
|
+
*
|
|
2041
|
+
* The pending sign-in is single use and expires after a short time. Whoever
|
|
2042
|
+
* signs in decides which account Junior uses, so only Junior admins may start
|
|
2043
|
+
* it.
|
|
2044
|
+
*/
|
|
2045
|
+
async function startMcpServiceAccountSignIn(input) {
|
|
2046
|
+
const mcp = requireServiceAccountMcp(input.plugin);
|
|
2047
|
+
const provider = input.plugin.manifest.name;
|
|
2048
|
+
const state = randomUUID();
|
|
2049
|
+
const signIn = signInProvider({
|
|
2050
|
+
redirectUrl: input.redirectUrl,
|
|
2051
|
+
state
|
|
2052
|
+
});
|
|
2053
|
+
if (await auth(signIn.provider, { serverUrl: mcp.url }) !== "REDIRECT") throw new Error(`${provider} did not start an OAuth sign-in`);
|
|
2054
|
+
const { authorizationUrl, clientInformation, codeVerifier, discoveryState } = signIn.captured;
|
|
2055
|
+
if (!authorizationUrl || !clientInformation || !codeVerifier) throw new Error(`${provider} did not return an authorization URL`);
|
|
2056
|
+
await createEncryptedState(getStateAdapter()).set(signInKey$1(state), {
|
|
2057
|
+
clientInformation,
|
|
2058
|
+
codeVerifier,
|
|
2059
|
+
...discoveryState ? { discoveryState } : void 0,
|
|
2060
|
+
provider,
|
|
2061
|
+
redirectUrl: input.redirectUrl,
|
|
2062
|
+
...input.startedBy ? { startedBy: input.startedBy } : void 0
|
|
2063
|
+
}, SIGN_IN_TTL_MS$1);
|
|
2064
|
+
return { authorizationUrl };
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* Finish a service account sign-in from the OAuth callback parameters.
|
|
2068
|
+
*
|
|
2069
|
+
* It accepts only a pending sign-in for the same plugin that the same Admin
|
|
2070
|
+
* started. It then saves the grant as the plugin's service account.
|
|
2071
|
+
*/
|
|
2072
|
+
async function finishMcpServiceAccountSignIn(input) {
|
|
2073
|
+
const mcp = requireServiceAccountMcp(input.plugin);
|
|
2074
|
+
const provider = input.plugin.manifest.name;
|
|
2075
|
+
const state = input.callback.get("state");
|
|
2076
|
+
const pending = state ? parseSignIn(await createEncryptedState(getStateAdapter()).get(signInKey$1(state))) : void 0;
|
|
2077
|
+
if (!state || !pending || pending.provider !== provider || pending.startedBy !== input.connectedBy) return {
|
|
2078
|
+
ok: false,
|
|
2079
|
+
message: "This sign-in expired or did not start here. Start it again."
|
|
2080
|
+
};
|
|
2081
|
+
await getStateAdapter().delete(signInKey$1(state));
|
|
2082
|
+
const error = input.callback.get("error");
|
|
2083
|
+
if (error) return {
|
|
2084
|
+
ok: false,
|
|
2085
|
+
message: `${provider} did not finish the sign-in (${error}).`
|
|
2086
|
+
};
|
|
2087
|
+
const authorizationCode = input.callback.get("code");
|
|
2088
|
+
if (!authorizationCode) return {
|
|
2089
|
+
ok: false,
|
|
2090
|
+
message: `${provider} did not return an authorization code.`
|
|
2091
|
+
};
|
|
2092
|
+
const signIn = signInProvider({
|
|
2093
|
+
pending,
|
|
2094
|
+
redirectUrl: pending.redirectUrl
|
|
2095
|
+
});
|
|
2096
|
+
await auth(signIn.provider, {
|
|
2097
|
+
serverUrl: mcp.url,
|
|
2098
|
+
authorizationCode
|
|
2099
|
+
});
|
|
2100
|
+
const { clientInformation, discoveryState, tokens } = signIn.captured;
|
|
2101
|
+
if (!clientInformation || !tokens) throw new Error(`${provider} did not issue tokens`);
|
|
2102
|
+
const credentials = {
|
|
2103
|
+
clientInformation,
|
|
2104
|
+
connectedAtMs: Date.now(),
|
|
2105
|
+
...input.connectedBy ? { connectedBy: input.connectedBy } : void 0,
|
|
2106
|
+
...discoveryState ? { discoveryState } : void 0,
|
|
2107
|
+
redirectUrl: pending.redirectUrl,
|
|
2108
|
+
tokens
|
|
2109
|
+
};
|
|
2110
|
+
await putMcpServiceAccountCredentials(provider, credentials);
|
|
2111
|
+
return {
|
|
2112
|
+
ok: true,
|
|
2113
|
+
credentials
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
// src/chat/credentials/oauth-scope.ts
|
|
2117
|
+
function parseScope(scope) {
|
|
2118
|
+
if (!scope) return [];
|
|
2119
|
+
return [...new Set(scope.split(/\s+/).filter(Boolean))].sort();
|
|
2120
|
+
}
|
|
2121
|
+
/** Normalize OAuth scope strings so persisted grants can be compared reliably. */
|
|
2122
|
+
function normalizeOAuthScope(scope) {
|
|
2123
|
+
const parsed = parseScope(scope);
|
|
2124
|
+
return parsed.length > 0 ? parsed.join(" ") : void 0;
|
|
2125
|
+
}
|
|
2126
|
+
/** Return whether the stored grant still satisfies the provider's current scope contract. */
|
|
2127
|
+
function hasRequiredOAuthScope(storedScope, requiredScope) {
|
|
2128
|
+
const required = parseScope(requiredScope);
|
|
2129
|
+
if (required.length === 0) return true;
|
|
2130
|
+
const stored = new Set(parseScope(storedScope));
|
|
2131
|
+
if (stored.size === 0) return false;
|
|
2132
|
+
return required.every((scope) => stored.has(scope));
|
|
2133
|
+
}
|
|
1142
2134
|
// src/chat/plugins/auth/oauth-request.ts
|
|
1143
2135
|
const DEFAULT_TOKEN_CONTENT_TYPE = "application/x-www-form-urlencoded";
|
|
1144
2136
|
function requireNonEmptyTokenField(data, field) {
|
|
@@ -1150,9 +2142,9 @@ function requireTokenResponseObject(data) {
|
|
|
1150
2142
|
if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("OAuth token response must be an object");
|
|
1151
2143
|
return data;
|
|
1152
2144
|
}
|
|
1153
|
-
const
|
|
2145
|
+
const parsedOAuthAccessTokenResponseSchema = z.object({
|
|
1154
2146
|
accessToken: z.string().min(1),
|
|
1155
|
-
refreshToken: z.string().min(1),
|
|
2147
|
+
refreshToken: z.string().min(1).optional(),
|
|
1156
2148
|
expiresAt: z.number().positive().optional(),
|
|
1157
2149
|
refreshTokenExpiresAt: z.number().positive().optional(),
|
|
1158
2150
|
scope: z.string().min(1).optional()
|
|
@@ -1183,10 +2175,22 @@ function buildOAuthTokenRequest(input) {
|
|
|
1183
2175
|
}
|
|
1184
2176
|
/** Parse provider tokens, retaining the request token when a refresh response omits rotation. */
|
|
1185
2177
|
function parseOAuthTokenResponse(data, requestedScope, options) {
|
|
2178
|
+
const parsed = parseOAuthAccessTokenResponse(data, requestedScope, options);
|
|
2179
|
+
const { refreshToken } = parsed;
|
|
2180
|
+
if (!refreshToken) throw new Error("OAuth token response missing refresh_token");
|
|
2181
|
+
return {
|
|
2182
|
+
...parsed,
|
|
2183
|
+
refreshToken
|
|
2184
|
+
};
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Parse provider tokens that may come without a refresh token, such as a
|
|
2188
|
+
* token that does not expire.
|
|
2189
|
+
*/
|
|
2190
|
+
function parseOAuthAccessTokenResponse(data, requestedScope, options) {
|
|
1186
2191
|
const response = requireTokenResponseObject(data);
|
|
1187
2192
|
const accessToken = requireNonEmptyTokenField(response, "access_token");
|
|
1188
2193
|
const resolvedRefreshToken = response["refresh_token"] === void 0 ? options?.refreshToken : requireNonEmptyTokenField(response, "refresh_token");
|
|
1189
|
-
if (!resolvedRefreshToken) throw new Error("OAuth token response missing refresh_token");
|
|
1190
2194
|
const expiresIn = response["expires_in"];
|
|
1191
2195
|
const refreshTokenExpiresIn = response["refresh_token_expires_in"];
|
|
1192
2196
|
const responseScope = response["scope"];
|
|
@@ -1200,7 +2204,7 @@ function parseOAuthTokenResponse(data, requestedScope, options) {
|
|
|
1200
2204
|
} else scope = normalizeOAuthScope(requestedScope);
|
|
1201
2205
|
const result = {
|
|
1202
2206
|
accessToken,
|
|
1203
|
-
refreshToken: resolvedRefreshToken,
|
|
2207
|
+
...resolvedRefreshToken ? { refreshToken: resolvedRefreshToken } : void 0,
|
|
1204
2208
|
...scope ? { scope } : void 0
|
|
1205
2209
|
};
|
|
1206
2210
|
if (expiresIn !== void 0) {
|
|
@@ -1211,7 +2215,297 @@ function parseOAuthTokenResponse(data, requestedScope, options) {
|
|
|
1211
2215
|
if (typeof refreshTokenExpiresIn !== "number" || !Number.isFinite(refreshTokenExpiresIn) || refreshTokenExpiresIn <= 0) throw new Error("OAuth token response returned invalid refresh_token_expires_in");
|
|
1212
2216
|
result.refreshTokenExpiresAt = Date.now() + refreshTokenExpiresIn * 1e3;
|
|
1213
2217
|
}
|
|
1214
|
-
return
|
|
2218
|
+
return parsedOAuthAccessTokenResponseSchema.parse(result);
|
|
2219
|
+
}
|
|
2220
|
+
// src/chat/plugins/auth/oauth-service-account.ts
|
|
2221
|
+
/**
|
|
2222
|
+
* OAuth service account credentials.
|
|
2223
|
+
*
|
|
2224
|
+
* This is the top-level `oauth` surface of a plugin's service account. See
|
|
2225
|
+
* `@/chat/credentials/service-account` for the credential order and the
|
|
2226
|
+
* policy. An Admin signs in once as the shared provider account. The
|
|
2227
|
+
* oauth-bearer broker then reads the stored token for host egress requests
|
|
2228
|
+
* that name an operation the account lists. The credential stays on the
|
|
2229
|
+
* host. The sandbox and the model never get it.
|
|
2230
|
+
*/
|
|
2231
|
+
const SERVICE_ACCOUNT_KEY_PREFIX = "junior:oauth_service_account";
|
|
2232
|
+
const SIGN_IN_KEY_PREFIX = "junior:oauth_service_account_sign_in";
|
|
2233
|
+
const SIGN_IN_TTL_MS = 6e5;
|
|
2234
|
+
const REFRESH_LOCK_TTL_MS = 3e4;
|
|
2235
|
+
const REFRESH_LOCK_WAIT_MS = 3e4;
|
|
2236
|
+
const TOKEN_EXCHANGE_TIMEOUT_MS = 2e4;
|
|
2237
|
+
const credentialsSchema = z.object({
|
|
2238
|
+
accessToken: z.string().min(1),
|
|
2239
|
+
connectedAtMs: z.number(),
|
|
2240
|
+
connectedBy: z.string().optional().catch(void 0),
|
|
2241
|
+
expiresAt: z.number().optional(),
|
|
2242
|
+
refreshToken: z.string().min(1).optional(),
|
|
2243
|
+
refreshTokenExpiresAt: z.number().optional(),
|
|
2244
|
+
scope: z.string().optional()
|
|
2245
|
+
});
|
|
2246
|
+
function serviceAccountKey(provider) {
|
|
2247
|
+
return `${SERVICE_ACCOUNT_KEY_PREFIX}:${provider}`;
|
|
2248
|
+
}
|
|
2249
|
+
function parseCredentials(value) {
|
|
2250
|
+
const parsed = credentialsSchema.safeParse(value);
|
|
2251
|
+
return parsed.success ? parsed.data : void 0;
|
|
2252
|
+
}
|
|
2253
|
+
/** Read the connected OAuth service account for one plugin, if any. */
|
|
2254
|
+
async function getOAuthServiceAccountCredentials(provider) {
|
|
2255
|
+
const state = getStateAdapter();
|
|
2256
|
+
const stored = await readEncryptedState(state, serviceAccountKey(provider));
|
|
2257
|
+
const credentials = parseCredentials(stored?.value);
|
|
2258
|
+
if (credentials && stored?.stale) await withLock(state, updateLockKey(provider), async (lock) => {
|
|
2259
|
+
const current = await readEncryptedState(state, serviceAccountKey(provider));
|
|
2260
|
+
const latest = parseCredentials(current?.value);
|
|
2261
|
+
if (!current?.stale || !latest) return;
|
|
2262
|
+
await fenceLock(state, lock);
|
|
2263
|
+
await putOAuthServiceAccountCredentials(provider, latest);
|
|
2264
|
+
}, { ttlMs: MUTATION_LOCK_TTL_MS });
|
|
2265
|
+
return credentials;
|
|
2266
|
+
}
|
|
2267
|
+
/** Save the OAuth service account for one plugin. */
|
|
2268
|
+
async function putOAuthServiceAccountCredentials(provider, credentials) {
|
|
2269
|
+
await createEncryptedState(getStateAdapter()).set(serviceAccountKey(provider), credentials);
|
|
2270
|
+
}
|
|
2271
|
+
/** Remove the OAuth service account. The provider grant stays until someone revokes it. */
|
|
2272
|
+
async function deleteOAuthServiceAccountCredentials(provider) {
|
|
2273
|
+
await getStateAdapter().delete(serviceAccountKey(provider));
|
|
2274
|
+
}
|
|
2275
|
+
function updateLockKey(provider) {
|
|
2276
|
+
return `${serviceAccountKey(provider)}:update`;
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Run a read and write of the stored account under one lock, so a turn
|
|
2280
|
+
* cannot write back or delete a refresh token that another turn replaced.
|
|
2281
|
+
*/
|
|
2282
|
+
async function withOAuthServiceAccountLock(provider, run) {
|
|
2283
|
+
const state = getStateAdapter();
|
|
2284
|
+
const result = await withLock(state, updateLockKey(provider), async (lock) => await run(() => fenceLock(state, lock)), {
|
|
2285
|
+
ttlMs: REFRESH_LOCK_TTL_MS,
|
|
2286
|
+
waitMs: REFRESH_LOCK_WAIT_MS
|
|
2287
|
+
});
|
|
2288
|
+
if (!result.acquired) throw new Error(`Timed out waiting to update the ${provider} service account`);
|
|
2289
|
+
return result.value;
|
|
2290
|
+
}
|
|
2291
|
+
/** Pending OAuth service account sign-in, kept until the callback. */
|
|
2292
|
+
const signInSchema = z.object({
|
|
2293
|
+
provider: z.string(),
|
|
2294
|
+
redirectUrl: z.string(),
|
|
2295
|
+
/** Email of the Admin who started the sign-in. Only they may finish it. */
|
|
2296
|
+
startedBy: z.string().optional().catch(void 0)
|
|
2297
|
+
});
|
|
2298
|
+
function signInKey(state) {
|
|
2299
|
+
return `${SIGN_IN_KEY_PREFIX}:${state}`;
|
|
2300
|
+
}
|
|
2301
|
+
function requireServiceAccountOAuth(plugin) {
|
|
2302
|
+
const { oauth, accounts, name } = plugin.manifest;
|
|
2303
|
+
if (!oauth || !accounts?.serviceAccount?.operations) throw new Error(`Plugin "${name}" does not support an OAuth service account`);
|
|
2304
|
+
return oauth;
|
|
2305
|
+
}
|
|
2306
|
+
function requireEnv(name) {
|
|
2307
|
+
const value = process.env[name]?.trim();
|
|
2308
|
+
if (!value) throw new Error(`Missing ${name} environment variable`);
|
|
2309
|
+
return value;
|
|
2310
|
+
}
|
|
2311
|
+
/**
|
|
2312
|
+
* Start an OAuth service account sign-in and return the provider sign-in URL.
|
|
2313
|
+
*
|
|
2314
|
+
* The pending sign-in is single use and expires after a short time.
|
|
2315
|
+
*/
|
|
2316
|
+
async function startOAuthServiceAccountSignIn(input) {
|
|
2317
|
+
const oauth = requireServiceAccountOAuth(input.plugin);
|
|
2318
|
+
const clientId = requireEnv(oauth.clientIdEnv);
|
|
2319
|
+
const state = randomBytes(32).toString("hex");
|
|
2320
|
+
await createEncryptedState(getStateAdapter()).set(signInKey(state), {
|
|
2321
|
+
provider: input.plugin.manifest.name,
|
|
2322
|
+
redirectUrl: input.redirectUrl,
|
|
2323
|
+
...input.startedBy ? { startedBy: input.startedBy } : void 0
|
|
2324
|
+
}, SIGN_IN_TTL_MS);
|
|
2325
|
+
const authorizationUrl = new URL(oauth.authorizeEndpoint);
|
|
2326
|
+
authorizationUrl.searchParams.set("client_id", clientId);
|
|
2327
|
+
authorizationUrl.searchParams.set("state", state);
|
|
2328
|
+
authorizationUrl.searchParams.set("redirect_uri", input.redirectUrl);
|
|
2329
|
+
authorizationUrl.searchParams.set("response_type", "code");
|
|
2330
|
+
if (oauth.scope) authorizationUrl.searchParams.set("scope", oauth.scope);
|
|
2331
|
+
for (const [key, value] of Object.entries(oauth.authorizeParams ?? {})) authorizationUrl.searchParams.set(key, value);
|
|
2332
|
+
return { authorizationUrl };
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Finish an OAuth service account sign-in from the callback parameters.
|
|
2336
|
+
*
|
|
2337
|
+
* It accepts only a pending sign-in for the same plugin that the same Admin
|
|
2338
|
+
* started, exchanges the code, and saves the tokens. A failure message is
|
|
2339
|
+
* safe to show the Admin. Network failures throw.
|
|
2340
|
+
*/
|
|
2341
|
+
async function finishOAuthServiceAccountSignIn(input) {
|
|
2342
|
+
const oauth = requireServiceAccountOAuth(input.plugin);
|
|
2343
|
+
const provider = input.plugin.manifest.name;
|
|
2344
|
+
const state = input.callback.get("state");
|
|
2345
|
+
const parsedPending = state ? signInSchema.safeParse(await createEncryptedState(getStateAdapter()).get(signInKey(state))) : void 0;
|
|
2346
|
+
const pending = parsedPending?.success ? parsedPending.data : void 0;
|
|
2347
|
+
if (!state || !pending || pending.provider !== provider || pending.startedBy !== input.connectedBy) return {
|
|
2348
|
+
ok: false,
|
|
2349
|
+
message: "This sign-in expired or did not start here. Start it again."
|
|
2350
|
+
};
|
|
2351
|
+
await getStateAdapter().delete(signInKey(state));
|
|
2352
|
+
const error = input.callback.get("error");
|
|
2353
|
+
if (error) return {
|
|
2354
|
+
ok: false,
|
|
2355
|
+
message: `${provider} did not finish the sign-in (${error}).`
|
|
2356
|
+
};
|
|
2357
|
+
const code = input.callback.get("code");
|
|
2358
|
+
if (!code) return {
|
|
2359
|
+
ok: false,
|
|
2360
|
+
message: `${provider} did not return an authorization code.`
|
|
2361
|
+
};
|
|
2362
|
+
const request = buildOAuthTokenRequest({
|
|
2363
|
+
clientId: requireEnv(oauth.clientIdEnv),
|
|
2364
|
+
clientSecret: requireEnv(oauth.clientSecretEnv),
|
|
2365
|
+
payload: {
|
|
2366
|
+
grant_type: "authorization_code",
|
|
2367
|
+
code,
|
|
2368
|
+
redirect_uri: pending.redirectUrl
|
|
2369
|
+
},
|
|
2370
|
+
tokenAuthMethod: oauth.tokenAuthMethod,
|
|
2371
|
+
tokenExtraHeaders: oauth.tokenExtraHeaders
|
|
2372
|
+
});
|
|
2373
|
+
const response = await fetch(oauth.tokenEndpoint, {
|
|
2374
|
+
method: "POST",
|
|
2375
|
+
headers: request.headers,
|
|
2376
|
+
body: request.body,
|
|
2377
|
+
signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS)
|
|
2378
|
+
});
|
|
2379
|
+
if (!response.ok) return {
|
|
2380
|
+
ok: false,
|
|
2381
|
+
message: `${provider} did not issue tokens (HTTP ${response.status}). Start the sign-in again.`
|
|
2382
|
+
};
|
|
2383
|
+
const tokens = parseOAuthAccessTokenResponse(await response.json(), oauth.scope, { treatEmptyScopeAsUnreported: oauth.treatEmptyScopeAsUnreported });
|
|
2384
|
+
if (!hasRequiredOAuthScope(tokens.scope, oauth.scope)) return {
|
|
2385
|
+
ok: false,
|
|
2386
|
+
message: `${provider} did not grant the required access (${oauth.scope}).`
|
|
2387
|
+
};
|
|
2388
|
+
await putOAuthServiceAccountCredentials(provider, {
|
|
2389
|
+
...tokens,
|
|
2390
|
+
connectedAtMs: Date.now(),
|
|
2391
|
+
...input.connectedBy ? { connectedBy: input.connectedBy } : void 0
|
|
2392
|
+
});
|
|
2393
|
+
return { ok: true };
|
|
2394
|
+
}
|
|
2395
|
+
// src/chat/credentials/service-account.ts
|
|
2396
|
+
/**
|
|
2397
|
+
* Service accounts.
|
|
2398
|
+
*
|
|
2399
|
+
* A plugin's `accounts` block can allow an optional install-wide provider
|
|
2400
|
+
* account, often a bot, that Junior itself uses. By default, the credential
|
|
2401
|
+
* order for one request is:
|
|
2402
|
+
*
|
|
2403
|
+
* 1. The Actor's own connection, when it exists.
|
|
2404
|
+
* 2. The plugin's service account, when an Admin connected it and
|
|
2405
|
+
* `accounts.service-account` lists what the request uses.
|
|
2406
|
+
* 3. Otherwise, the Actor must connect their own account.
|
|
2407
|
+
*
|
|
2408
|
+
* With `accounts.user-oauth: false`, Junior uses only the service account.
|
|
2409
|
+
* It ignores Actor connections, never asks an Actor to connect, and hides
|
|
2410
|
+
* what the account does not list. Until an Admin connects the account, the
|
|
2411
|
+
* plugin is not available.
|
|
2412
|
+
*
|
|
2413
|
+
* This module is the one place that decides which requests the service
|
|
2414
|
+
* account may serve. Each request surface asks it before it uses the shared
|
|
2415
|
+
* account. An MCP plugin lists the MCP tools it may call. A plugin with a
|
|
2416
|
+
* top-level `oauth` block lists the operations that its host code passes to
|
|
2417
|
+
* `egress.fetch`. Sandbox egress names no operation, so commands that the
|
|
2418
|
+
* model writes never get the shared account.
|
|
2419
|
+
*
|
|
2420
|
+
* This module also owns the connect flow that the dashboard Admin page and
|
|
2421
|
+
* the `junior service-account` CLI share. The MCP surface stores MCP OAuth
|
|
2422
|
+
* state, and the OAuth surface stores provider tokens.
|
|
2423
|
+
*/
|
|
2424
|
+
/** Return whether the plugin's service account may serve this request. */
|
|
2425
|
+
function serviceAccountAllows(manifest, request) {
|
|
2426
|
+
const serviceAccount = manifest.accounts?.serviceAccount;
|
|
2427
|
+
return "tool" in request ? serviceAccount?.tools?.includes(request.tool) ?? false : serviceAccount?.operations?.includes(request.operation) ?? false;
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* Return whether the plugin uses only its service account.
|
|
2431
|
+
*
|
|
2432
|
+
* Then no surface may fall back to an Actor's own connection or ask an
|
|
2433
|
+
* Actor to connect.
|
|
2434
|
+
*/
|
|
2435
|
+
function serviceAccountOnly(manifest) {
|
|
2436
|
+
return manifest.accounts?.userOAuth === false;
|
|
2437
|
+
}
|
|
2438
|
+
/** Return the plugins whose `accounts` block allows a service account. */
|
|
2439
|
+
function serviceAccountPlugins(plugins) {
|
|
2440
|
+
return plugins.filter((plugin) => plugin.manifest.accounts?.serviceAccount);
|
|
2441
|
+
}
|
|
2442
|
+
/** Read the service account status for one plugin. */
|
|
2443
|
+
async function getServiceAccountStatus(plugin) {
|
|
2444
|
+
const { manifest } = plugin;
|
|
2445
|
+
const serviceAccount = manifest.accounts?.serviceAccount;
|
|
2446
|
+
if (!serviceAccount) throw new Error(`Plugin ${manifest.name} does not allow a service account`);
|
|
2447
|
+
const credentials = manifest.mcp ? await getMcpServiceAccountCredentials(manifest.name) : await getOAuthServiceAccountCredentials(manifest.name);
|
|
2448
|
+
return {
|
|
2449
|
+
provider: manifest.name,
|
|
2450
|
+
displayName: manifest.displayName,
|
|
2451
|
+
userOAuth: !serviceAccountOnly(manifest),
|
|
2452
|
+
tools: serviceAccount.tools ?? [],
|
|
2453
|
+
operations: serviceAccount.operations ?? [],
|
|
2454
|
+
connected: Boolean(credentials),
|
|
2455
|
+
...credentials ? { connectedAt: new Date(credentials.connectedAtMs).toISOString() } : void 0,
|
|
2456
|
+
...credentials?.connectedBy ? { connectedBy: credentials.connectedBy } : void 0
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* Start signing in to a plugin's provider as its service account.
|
|
2461
|
+
*
|
|
2462
|
+
* Whoever signs in decides which account Junior uses, so only Junior admins
|
|
2463
|
+
* may start it. `startedBy` binds the sign-in to that Admin.
|
|
2464
|
+
*/
|
|
2465
|
+
async function startServiceAccountSignIn(input) {
|
|
2466
|
+
return input.plugin.manifest.mcp ? await startMcpServiceAccountSignIn(input) : await startOAuthServiceAccountSignIn(input);
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* Finish a sign-in from its OAuth callback and save the service account.
|
|
2470
|
+
*
|
|
2471
|
+
* A failure message is safe to show the Admin. Unexpected provider failures
|
|
2472
|
+
* throw.
|
|
2473
|
+
*/
|
|
2474
|
+
async function finishServiceAccountSignIn(input) {
|
|
2475
|
+
if (!input.plugin.manifest.mcp) return await finishOAuthServiceAccountSignIn(input);
|
|
2476
|
+
const result = await finishMcpServiceAccountSignIn(input);
|
|
2477
|
+
return result.ok ? { ok: true } : result;
|
|
2478
|
+
}
|
|
2479
|
+
/**
|
|
2480
|
+
* Remove a plugin's service account from Junior.
|
|
2481
|
+
*
|
|
2482
|
+
* The provider grant stays until someone revokes it in the provider.
|
|
2483
|
+
*/
|
|
2484
|
+
async function disconnectServiceAccount(plugin) {
|
|
2485
|
+
await (plugin.manifest.mcp ? deleteMcpServiceAccountCredentials(plugin.manifest.name) : deleteOAuthServiceAccountCredentials(plugin.manifest.name));
|
|
2486
|
+
}
|
|
2487
|
+
// src/chat/credentials/header-transforms.ts
|
|
2488
|
+
/** Merge transforms by domain so later transforms override earlier headers. */
|
|
2489
|
+
function mergeHeaderTransforms(transforms) {
|
|
2490
|
+
const byDomain = /* @__PURE__ */ new Map();
|
|
2491
|
+
for (const transform of transforms) byDomain.set(transform.domain, {
|
|
2492
|
+
...byDomain.get(transform.domain) ?? {},
|
|
2493
|
+
...transform.headers
|
|
2494
|
+
});
|
|
2495
|
+
return [...byDomain.entries()].map(([domain, headers]) => ({
|
|
2496
|
+
domain,
|
|
2497
|
+
headers
|
|
2498
|
+
}));
|
|
2499
|
+
}
|
|
2500
|
+
// src/chat/plugins/auth/auth-token-placeholder.ts
|
|
2501
|
+
/**
|
|
2502
|
+
* The marker that every built-in Sandbox credential placeholder contains,
|
|
2503
|
+
* such as `host_managed_credential` or `ghp_host_managed_credential`.
|
|
2504
|
+
*/
|
|
2505
|
+
const HOST_MANAGED_CREDENTIAL_PLACEHOLDER = "host_managed_credential";
|
|
2506
|
+
/** Resolve the non-secret sandbox token placeholder for token-backed credentials. */
|
|
2507
|
+
function resolveAuthTokenPlaceholder(credentials) {
|
|
2508
|
+
return credentials.authTokenPlaceholder?.trim() || "host_managed_credential";
|
|
1215
2509
|
}
|
|
1216
2510
|
// src/chat/plugins/auth/oauth-bearer-broker.ts
|
|
1217
2511
|
const MAX_LEASE_MS = 36e5;
|
|
@@ -1296,19 +2590,49 @@ function canUseStoredToken(stored) {
|
|
|
1296
2590
|
function shouldRefreshStoredToken(stored) {
|
|
1297
2591
|
return stored !== void 0 && stored.expiresAt !== void 0 && stored.expiresAt - Date.now() < REFRESH_BUFFER_MS;
|
|
1298
2592
|
}
|
|
2593
|
+
/**
|
|
2594
|
+
* Return a usable token of the plugin's OAuth service account, refreshing it
|
|
2595
|
+
* when it is about to expire. Returns nothing when no Admin connected it, or
|
|
2596
|
+
* when the provider rejected it, which removes the stored account.
|
|
2597
|
+
*/
|
|
2598
|
+
async function serviceAccountToken(provider, oauth) {
|
|
2599
|
+
const stored = await getOAuthServiceAccountCredentials(provider);
|
|
2600
|
+
if (!shouldRefreshStoredToken(stored) || !stored?.refreshToken) return canUseStoredToken(stored) ? stored : void 0;
|
|
2601
|
+
return await withOAuthServiceAccountLock(provider, async (fence) => {
|
|
2602
|
+
const latest = await getOAuthServiceAccountCredentials(provider);
|
|
2603
|
+
if (!shouldRefreshStoredToken(latest) || !latest?.refreshToken) return canUseStoredToken(latest) ? latest : void 0;
|
|
2604
|
+
let refreshed;
|
|
2605
|
+
try {
|
|
2606
|
+
refreshed = await refreshAccessToken(provider, latest.refreshToken, oauth, latest.scope ?? oauth.scope);
|
|
2607
|
+
} catch (error) {
|
|
2608
|
+
if (!(error instanceof OAuthRefreshRejectedError)) throw error;
|
|
2609
|
+
await fence();
|
|
2610
|
+
await deleteOAuthServiceAccountCredentials(provider);
|
|
2611
|
+
logWarn("oauth.service_account.disconnected", { "app.plugin.name": provider });
|
|
2612
|
+
return;
|
|
2613
|
+
}
|
|
2614
|
+
const next = {
|
|
2615
|
+
...latest,
|
|
2616
|
+
...refreshed,
|
|
2617
|
+
expiresAt: refreshed.expiresAt
|
|
2618
|
+
};
|
|
2619
|
+
await fence();
|
|
2620
|
+
await putOAuthServiceAccountCredentials(provider, next);
|
|
2621
|
+
return next;
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
1299
2624
|
function createOAuthBearerBroker(manifest, credentials, deps) {
|
|
1300
2625
|
const provider = manifest.name;
|
|
1301
2626
|
const { domains, apiHeaders, authTokenEnv } = credentials;
|
|
1302
2627
|
const authTokenPlaceholder = resolveAuthTokenPlaceholder(credentials);
|
|
1303
2628
|
const pluginHeaderTransforms = () => resolveApiHeaderTransforms(manifest);
|
|
1304
2629
|
function buildLease(token, expiresAtMs, reason) {
|
|
2630
|
+
const env = resolvePluginCommandEnv(manifest);
|
|
2631
|
+
if (authTokenEnv) env[authTokenEnv] = authTokenPlaceholder;
|
|
1305
2632
|
return {
|
|
1306
2633
|
id: randomUUID(),
|
|
1307
2634
|
provider,
|
|
1308
|
-
env
|
|
1309
|
-
...resolvePluginCommandEnv(manifest),
|
|
1310
|
-
[authTokenEnv]: authTokenPlaceholder
|
|
1311
|
-
},
|
|
2635
|
+
env,
|
|
1312
2636
|
headerTransforms: mergeHeaderTransforms([...pluginHeaderTransforms(), ...domains.map((domain) => ({
|
|
1313
2637
|
domain,
|
|
1314
2638
|
headers: {
|
|
@@ -1321,13 +2645,23 @@ function createOAuthBearerBroker(manifest, credentials, deps) {
|
|
|
1321
2645
|
};
|
|
1322
2646
|
}
|
|
1323
2647
|
return { async issue(input) {
|
|
1324
|
-
const envToken = process.env[authTokenEnv]?.trim();
|
|
2648
|
+
const envToken = authTokenEnv ? process.env[authTokenEnv]?.trim() : void 0;
|
|
1325
2649
|
const oauth = manifest.oauth;
|
|
1326
2650
|
const userSubjectId = credentialUserSubjectId(input.context);
|
|
2651
|
+
const serviceAccountMayServe = input.operation !== void 0 && serviceAccountAllows(manifest, { operation: input.operation });
|
|
2652
|
+
const serviceAccountLease = async () => {
|
|
2653
|
+
const token = serviceAccountMayServe && oauth ? await serviceAccountToken(provider, oauth) : void 0;
|
|
2654
|
+
return token ? buildLease(token.accessToken, getLeaseExpiry(token.expiresAt), input.reason) : void 0;
|
|
2655
|
+
};
|
|
1327
2656
|
if (!oauth) {
|
|
1328
2657
|
if (envToken) return buildLease(envToken, Date.now() + MAX_LEASE_MS, input.reason);
|
|
1329
2658
|
throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
|
|
1330
2659
|
}
|
|
2660
|
+
if (serviceAccountOnly(manifest)) {
|
|
2661
|
+
const lease = await serviceAccountLease();
|
|
2662
|
+
if (lease) return lease;
|
|
2663
|
+
throw new ServiceAccountUnavailableError(provider, serviceAccountMayServe ? `The ${provider} service account is not connected. An admin must connect it on the dashboard Admin page.` : `The ${provider} service account does not allow this request.`);
|
|
2664
|
+
}
|
|
1331
2665
|
if (userSubjectId) {
|
|
1332
2666
|
const stored = await deps.userTokenStore.get(userSubjectId, provider);
|
|
1333
2667
|
if (stored) {
|
|
@@ -1356,8 +2690,12 @@ function createOAuthBearerBroker(manifest, credentials, deps) {
|
|
|
1356
2690
|
if (canUseStoredToken(stored)) return buildLease(stored.accessToken, getLeaseExpiry(stored.expiresAt), input.reason);
|
|
1357
2691
|
throw new CredentialUnavailableError(provider, `Your ${provider} connection has expired.`);
|
|
1358
2692
|
}
|
|
2693
|
+
const lease = await serviceAccountLease();
|
|
2694
|
+
if (lease) return lease;
|
|
1359
2695
|
throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
|
|
1360
2696
|
}
|
|
2697
|
+
const lease = await serviceAccountLease();
|
|
2698
|
+
if (lease) return lease;
|
|
1361
2699
|
if (envToken) return buildLease(envToken, getLeaseExpiry(), input.reason);
|
|
1362
2700
|
throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
|
|
1363
2701
|
} };
|
|
@@ -1683,4 +3021,4 @@ function createPluginCatalogRuntime() {
|
|
|
1683
3021
|
}
|
|
1684
3022
|
};
|
|
1685
3023
|
}
|
|
1686
|
-
export { credentialUserSubjectId as _,
|
|
3024
|
+
export { parseInlinePluginManifest as $, readEncryptedState as A, getMcpProviderErrorAttributes as B, getMcpServerSessionId as C, putMcpServerSessionId as D, putMcpAuthSession as E, McpProviderError as F, actorLogContext as G, OAuthProviderError as H, McpServiceAccountRequiredError as I, credentialLogContext as J, credentialContextForActor as K, McpToolError as L, webActorUserIds as M, resolvePluginHeaderEnvRefs as N, putMcpStoredOAuthCredentials as O, resolvePluginCommandEnv as P, ServiceAccountUnavailableError as Q, getMcpAwareErrorType as R, getMcpAuthSession as S, patchMcpAuthSession as T, fetchWithBoundedOAuthErrorBodies as U, toMcpProviderError as V, getOAuthProviderErrorAttributes as W, credentialUserSubjectId as X, credentialSubjectSchema as Y, CredentialUnavailableError as Z, PluginMcpClient as _, finishServiceAccountSignIn as a, deleteMcpServerSessionId as b, serviceAccountOnly as c, buildOAuthTokenRequest as d, parsePluginManifest as et, parseOAuthTokenResponse as f, McpAuthorizationRequiredError as g, getMcpServiceAccountCredentials as h, disconnectServiceAccount as i, findLegacyWebActorUserId as j, createEncryptedState as k, serviceAccountPlugins as l, createMcpServiceAccountClientProvider as m, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as n, getServiceAccountStatus as o, hasRequiredOAuthScope as p, credentialContextSchema as q, resolveAuthTokenPlaceholder as r, serviceAccountAllows as s, createPluginCatalogRuntime as t, startServiceAccountSignIn as u, deleteMcpAuthSession as v, getMcpStoredOAuthCredentials as w, deleteMcpStoredOAuthCredentials as x, deleteMcpAuthSessionsForUserProvider as y, getMcpAwareTelemetryMessage as z };
|