@agent-native/core 0.15.10 → 0.15.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/dev-mode.d.ts +14 -0
- package/dist/client/dev-mode.d.ts.map +1 -0
- package/dist/client/dev-mode.js +14 -0
- package/dist/client/dev-mode.js.map +1 -0
- package/dist/client/extensions/EmbeddedTool.d.ts +20 -0
- package/dist/client/extensions/EmbeddedTool.d.ts.map +1 -0
- package/dist/client/extensions/EmbeddedTool.js +199 -0
- package/dist/client/extensions/EmbeddedTool.js.map +1 -0
- package/dist/client/extensions/ToolEditor.d.ts +5 -0
- package/dist/client/extensions/ToolEditor.d.ts.map +1 -0
- package/dist/client/extensions/ToolEditor.js +129 -0
- package/dist/client/extensions/ToolEditor.js.map +1 -0
- package/dist/client/extensions/ToolViewer.d.ts +5 -0
- package/dist/client/extensions/ToolViewer.d.ts.map +1 -0
- package/dist/client/extensions/ToolViewer.js +400 -0
- package/dist/client/extensions/ToolViewer.js.map +1 -0
- package/dist/client/extensions/ToolViewerPage.d.ts +2 -0
- package/dist/client/extensions/ToolViewerPage.d.ts.map +1 -0
- package/dist/client/extensions/ToolViewerPage.js +24 -0
- package/dist/client/extensions/ToolViewerPage.js.map +1 -0
- package/dist/client/extensions/ToolsListPage.d.ts +2 -0
- package/dist/client/extensions/ToolsListPage.d.ts.map +1 -0
- package/dist/client/extensions/ToolsListPage.js +67 -0
- package/dist/client/extensions/ToolsListPage.js.map +1 -0
- package/dist/client/extensions/ToolsSidebarSection.d.ts +2 -0
- package/dist/client/extensions/ToolsSidebarSection.d.ts.map +1 -0
- package/dist/client/extensions/ToolsSidebarSection.js +236 -0
- package/dist/client/extensions/ToolsSidebarSection.js.map +1 -0
- package/dist/client/extensions/tool-order.d.ts +7 -0
- package/dist/client/extensions/tool-order.d.ts.map +1 -0
- package/dist/client/extensions/tool-order.js +47 -0
- package/dist/client/extensions/tool-order.js.map +1 -0
- package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
- package/dist/client/settings/useBuilderStatus.js +5 -28
- package/dist/client/settings/useBuilderStatus.js.map +1 -1
- package/dist/client/settings/useBuilderStatus.spec.js +11 -6
- package/dist/client/settings/useBuilderStatus.spec.js.map +1 -1
- package/dist/client/tools/EmbeddedTool.d.ts +20 -0
- package/dist/client/tools/EmbeddedTool.d.ts.map +1 -0
- package/dist/client/tools/EmbeddedTool.js +199 -0
- package/dist/client/tools/EmbeddedTool.js.map +1 -0
- package/dist/client/tools/ExtensionSlot.d.ts +27 -0
- package/dist/client/tools/ExtensionSlot.d.ts.map +1 -0
- package/dist/client/tools/ExtensionSlot.js +96 -0
- package/dist/client/tools/ExtensionSlot.js.map +1 -0
- package/dist/client/tools/ToolEditor.d.ts +5 -0
- package/dist/client/tools/ToolEditor.d.ts.map +1 -0
- package/dist/client/tools/ToolEditor.js +129 -0
- package/dist/client/tools/ToolEditor.js.map +1 -0
- package/dist/client/tools/ToolViewer.d.ts +5 -0
- package/dist/client/tools/ToolViewer.d.ts.map +1 -0
- package/dist/client/tools/ToolViewer.js +400 -0
- package/dist/client/tools/ToolViewer.js.map +1 -0
- package/dist/client/tools/ToolViewerPage.d.ts +2 -0
- package/dist/client/tools/ToolViewerPage.d.ts.map +1 -0
- package/dist/client/tools/ToolViewerPage.js +24 -0
- package/dist/client/tools/ToolViewerPage.js.map +1 -0
- package/dist/client/tools/ToolsListPage.d.ts +2 -0
- package/dist/client/tools/ToolsListPage.d.ts.map +1 -0
- package/dist/client/tools/ToolsListPage.js +67 -0
- package/dist/client/tools/ToolsListPage.js.map +1 -0
- package/dist/client/tools/ToolsSidebarSection.d.ts +2 -0
- package/dist/client/tools/ToolsSidebarSection.d.ts.map +1 -0
- package/dist/client/tools/ToolsSidebarSection.js +236 -0
- package/dist/client/tools/ToolsSidebarSection.js.map +1 -0
- package/dist/client/tools/iframe-bridge.d.ts +38 -0
- package/dist/client/tools/iframe-bridge.d.ts.map +1 -0
- package/dist/client/tools/iframe-bridge.js +207 -0
- package/dist/client/tools/iframe-bridge.js.map +1 -0
- package/dist/client/tools/index.d.ts +8 -0
- package/dist/client/tools/index.d.ts.map +1 -0
- package/dist/client/tools/index.js +8 -0
- package/dist/client/tools/index.js.map +1 -0
- package/dist/client/tools/tool-order.d.ts +7 -0
- package/dist/client/tools/tool-order.d.ts.map +1 -0
- package/dist/client/tools/tool-order.js +47 -0
- package/dist/client/tools/tool-order.js.map +1 -0
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +4 -2
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/local-migration.d.ts +41 -0
- package/dist/server/local-migration.d.ts.map +1 -0
- package/dist/server/local-migration.js +235 -0
- package/dist/server/local-migration.js.map +1 -0
- package/dist/tools/actions.d.ts +3 -0
- package/dist/tools/actions.d.ts.map +1 -0
- package/dist/tools/actions.js +272 -0
- package/dist/tools/actions.js.map +1 -0
- package/dist/tools/fetch-tool.d.ts +23 -0
- package/dist/tools/fetch-tool.d.ts.map +1 -0
- package/dist/tools/fetch-tool.js +178 -0
- package/dist/tools/fetch-tool.js.map +1 -0
- package/dist/tools/html-shell.d.ts +45 -0
- package/dist/tools/html-shell.d.ts.map +1 -0
- package/dist/tools/html-shell.js +514 -0
- package/dist/tools/html-shell.js.map +1 -0
- package/dist/tools/proxy-security.d.ts +12 -0
- package/dist/tools/proxy-security.d.ts.map +1 -0
- package/dist/tools/proxy-security.js +158 -0
- package/dist/tools/proxy-security.js.map +1 -0
- package/dist/tools/routes.d.ts +2 -0
- package/dist/tools/routes.d.ts.map +1 -0
- package/dist/tools/routes.js +627 -0
- package/dist/tools/routes.js.map +1 -0
- package/dist/tools/schema.d.ts +664 -0
- package/dist/tools/schema.d.ts.map +1 -0
- package/dist/tools/schema.js +146 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/slots/routes.d.ts +15 -0
- package/dist/tools/slots/routes.d.ts.map +1 -0
- package/dist/tools/slots/routes.js +94 -0
- package/dist/tools/slots/routes.js.map +1 -0
- package/dist/tools/slots/schema.d.ts +303 -0
- package/dist/tools/slots/schema.d.ts.map +1 -0
- package/dist/tools/slots/schema.js +76 -0
- package/dist/tools/slots/schema.js.map +1 -0
- package/dist/tools/slots/store.d.ts +66 -0
- package/dist/tools/slots/store.d.ts.map +1 -0
- package/dist/tools/slots/store.js +227 -0
- package/dist/tools/slots/store.js.map +1 -0
- package/dist/tools/store.d.ts +40 -0
- package/dist/tools/store.d.ts.map +1 -0
- package/dist/tools/store.js +193 -0
- package/dist/tools/store.js.map +1 -0
- package/dist/tools/theme.d.ts +2 -0
- package/dist/tools/theme.d.ts.map +1 -0
- package/dist/tools/theme.js +67 -0
- package/dist/tools/theme.js.map +1 -0
- package/dist/tools/url-safety.d.ts +24 -0
- package/dist/tools/url-safety.d.ts.map +1 -0
- package/dist/tools/url-safety.js +224 -0
- package/dist/tools/url-safety.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { ToolsSidebarSection } from "./ToolsSidebarSection.js";
|
|
2
|
+
export { ToolViewer, type ToolViewerProps } from "./ToolViewer.js";
|
|
3
|
+
export { ToolEditor, type ToolEditorProps } from "./ToolEditor.js";
|
|
4
|
+
export { ToolsListPage } from "./ToolsListPage.js";
|
|
5
|
+
export { ToolViewerPage } from "./ToolViewerPage.js";
|
|
6
|
+
export { EmbeddedTool, type EmbeddedToolProps } from "./EmbeddedTool.js";
|
|
7
|
+
export { ExtensionSlot, type ExtensionSlotProps } from "./ExtensionSlot.js";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { ToolsSidebarSection } from "./ToolsSidebarSection.js";
|
|
2
|
+
export { ToolViewer } from "./ToolViewer.js";
|
|
3
|
+
export { ToolEditor } from "./ToolEditor.js";
|
|
4
|
+
export { ToolsListPage } from "./ToolsListPage.js";
|
|
5
|
+
export { ToolViewerPage } from "./ToolViewerPage.js";
|
|
6
|
+
export { EmbeddedTool } from "./EmbeddedTool.js";
|
|
7
|
+
export { ExtensionSlot } from "./ExtensionSlot.js";
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAwB,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,UAAU,EAAwB,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAA0B,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,aAAa,EAA2B,MAAM,oBAAoB,CAAC","sourcesContent":["export { ToolsSidebarSection } from \"./ToolsSidebarSection.js\";\nexport { ToolViewer, type ToolViewerProps } from \"./ToolViewer.js\";\nexport { ToolEditor, type ToolEditorProps } from \"./ToolEditor.js\";\nexport { ToolsListPage } from \"./ToolsListPage.js\";\nexport { ToolViewerPage } from \"./ToolViewerPage.js\";\nexport { EmbeddedTool, type EmbeddedToolProps } from \"./EmbeddedTool.js\";\nexport { ExtensionSlot, type ExtensionSlotProps } from \"./ExtensionSlot.js\";\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const TOOLS_ORDER_CHANGE_EVENT = "tools-order-change";
|
|
2
|
+
export declare function getToolsOrder(): string[];
|
|
3
|
+
export declare function setToolsOrder(order: string[]): void;
|
|
4
|
+
export declare function applyToolsOrder<T extends {
|
|
5
|
+
id: string;
|
|
6
|
+
}>(items: T[], savedOrder: string[]): T[];
|
|
7
|
+
//# sourceMappingURL=tool-order.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-order.d.ts","sourceRoot":"","sources":["../../../src/client/tools/tool-order.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,wBAAwB,uBAAuB,CAAC;AAI7D,wBAAgB,aAAa,IAAI,MAAM,EAAE,CAYxC;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAU5C;AAED,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,EACtD,KAAK,EAAE,CAAC,EAAE,EACV,UAAU,EAAE,MAAM,EAAE,GACnB,CAAC,EAAE,CAeL"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const TOOLS_ORDER_CHANGE_EVENT = "tools-order-change";
|
|
2
|
+
const TOOLS_ORDER_KEY = "tools-order";
|
|
3
|
+
export function getToolsOrder() {
|
|
4
|
+
if (typeof window === "undefined")
|
|
5
|
+
return [];
|
|
6
|
+
try {
|
|
7
|
+
const raw = window.localStorage.getItem(TOOLS_ORDER_KEY);
|
|
8
|
+
if (!raw)
|
|
9
|
+
return [];
|
|
10
|
+
const parsed = JSON.parse(raw);
|
|
11
|
+
return Array.isArray(parsed)
|
|
12
|
+
? parsed.filter((id) => typeof id === "string")
|
|
13
|
+
: [];
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function setToolsOrder(order) {
|
|
20
|
+
if (typeof window === "undefined")
|
|
21
|
+
return;
|
|
22
|
+
try {
|
|
23
|
+
window.localStorage.setItem(TOOLS_ORDER_KEY, JSON.stringify(order));
|
|
24
|
+
window.dispatchEvent(new CustomEvent(TOOLS_ORDER_CHANGE_EVENT, { detail: order }));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// localStorage unavailable / quota — ignore, order is best-effort
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function applyToolsOrder(items, savedOrder) {
|
|
31
|
+
if (savedOrder.length === 0)
|
|
32
|
+
return items;
|
|
33
|
+
const idToItem = new Map(items.map((item) => [item.id, item]));
|
|
34
|
+
const ordered = [];
|
|
35
|
+
for (const id of savedOrder) {
|
|
36
|
+
const item = idToItem.get(id);
|
|
37
|
+
if (item) {
|
|
38
|
+
ordered.push(item);
|
|
39
|
+
idToItem.delete(id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const item of idToItem.values()) {
|
|
43
|
+
ordered.push(item);
|
|
44
|
+
}
|
|
45
|
+
return ordered;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=tool-order.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-order.js","sourceRoot":"","sources":["../../../src/client/tools/tool-order.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,wBAAwB,GAAG,oBAAoB,CAAC;AAE7D,MAAM,eAAe,GAAG,aAAa,CAAC;AAEtC,MAAM,UAAU,aAAa;IAC3B,IAAI,OAAO,MAAM,KAAK,WAAW;QAAE,OAAO,EAAE,CAAC;IAC7C,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,CAA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AC9B,IAAI,IAAI,EAAE,CAAC;YACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["export const TOOLS_ORDER_CHANGE_EVENT = \"tools-order-change\";\n\nconst TOOLS_ORDER_KEY = \"tools-order\";\n\nexport function getToolsOrder(): string[] {\n if (typeof window === \"undefined\") return [];\n try {\n const raw = window.localStorage.getItem(TOOLS_ORDER_KEY);\n if (!raw) return [];\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed)\n ? parsed.filter((id) => typeof id === \"string\")\n : [];\n } catch {\n return [];\n }\n}\n\nexport function setToolsOrder(order: string[]) {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(TOOLS_ORDER_KEY, JSON.stringify(order));\n window.dispatchEvent(\n new CustomEvent(TOOLS_ORDER_CHANGE_EVENT, { detail: order }),\n );\n } catch {\n // localStorage unavailable / quota — ignore, order is best-effort\n }\n}\n\nexport function applyToolsOrder<T extends { id: string }>(\n items: T[],\n savedOrder: string[],\n): T[] {\n if (savedOrder.length === 0) return items;\n const idToItem = new Map(items.map((item) => [item.id, item]));\n const ordered: T[] = [];\n for (const id of savedOrder) {\n const item = idToItem.get(id);\n if (item) {\n ordered.push(item);\n idToItem.delete(id);\n }\n }\n for (const item of idToItem.values()) {\n ordered.push(item);\n }\n return ordered;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-provider.d.ts","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAMH;;;;;;;;GAQG;AACH,wBAA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kspaceRuntime() {
|
|
86
|
-
if (isLocalDatabase())
|
|
87
|
-
return false;
|
|
88
86
|
const hasFusionPreview = Boolean(process.env.FUSION_ENVIRONMENT ||
|
|
89
87
|
process.env.FUSION_ENV_ORIGIN ||
|
|
90
88
|
process.env.VITE_FUSION_ENV_ORIGIN);
|
|
@@ -94,6 +92,10 @@ function isHostedWorkspaceRuntime() {
|
|
|
94
92
|
}
|
|
95
93
|
function canUseBuilderDeployCredentialFallbackForRequest() {
|
|
96
94
|
const email = getRequestUserEmail();
|
|
95
|
+
// Builder workspace previews can run with NODE_ENV=development and their DB
|
|
96
|
+
// detection can look local during early startup. Once a real signed-in user
|
|
97
|
+
// is present, hosted workspace flags are enough to make deployment-level
|
|
98
|
+
// Builder keys unsafe as an identity fallback.
|
|
97
99
|
if (email && isHostedWorkspaceRuntime())
|
|
98
100
|
return false;
|
|
99
101
|
return canUseDeployCredentialFallbackForRequest();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,KAAgC,EAChC,IAA+B;IAE/B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,OA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yE;AACzE,MAAM,UAAU,qBAAqB;IACnC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,oBAAoB;QAChC,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,gBAAgB;QAC5B,wBAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,wBAAwB;QACpC,gDAAgD,CACjD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,iCAAiC;QAC7C,+CAA+C,CAChD,CAAC;AACJ,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n return isDeployCredentialFallbackAllowed();\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\nfunction isBuilderCredentialKey(key: string): boolean {\n return (BUILDER_CREDENTIAL_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHostedWorkspaceRuntime(): boolean {\n if (isLocalDatabase()) return false;\n const hasFusionPreview = Boolean(\n process.env.FUSION_ENVIRONMENT ||\n process.env.FUSION_ENV_ORIGIN ||\n process.env.VITE_FUSION_ENV_ORIGIN,\n );\n return (\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_WORKSPACE ?? \"\") ||\n /^(1|true)$/i.test(process.env.VITE_AGENT_NATIVE_WORKSPACE ?? \"\") ||\n hasFusionPreview\n );\n}\n\nfunction canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (email && isHostedWorkspaceRuntime()) return false;\n return canUseDeployCredentialFallbackForRequest();\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"workspace\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" | \"workspace\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n // Always trace Builder lookups — these come up in \"I connected Builder but\n // chat still says Use Builder\" support requests, and without scope-by-scope\n // visibility into where the lookup actually went, the only diagnostic move\n // is to ask the user to redo the connect flow. Mirrors `resolveSecret`'s\n // default-on trace gate for BUILDER_* keys.\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\n );\n return { value: userSecret.value, source: \"user\" };\n }\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n return { value: orgSecret.value, source: \"org\" };\n }\n\n // Older setup flows wrote shared credentials at workspace scope.\n // Keep reading those rows so status UIs and runtime resolution agree\n // for users who connected before org-scoped Builder credentials existed.\n scopeAttempted = \"workspace\";\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\n );\n } else {\n scopeAttempted = \"workspace-solo\";\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n } catch (err) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseBuilderDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_AUTH_FAILURE_SETTING_PREFIX = \"builder-auth-failure:\";\n\nexport interface BuilderCredentialAuthFailure {\n fingerprint: string;\n message: string;\n status?: number;\n code?: string;\n at: number;\n ownerEmail?: string | null;\n orgId?: string | null;\n}\n\nexport function builderCredentialFingerprint(\n privateKey?: string | null,\n publicKey?: string | null,\n): string | null {\n if (!privateKey || !publicKey) return null;\n return createHash(\"sha256\")\n .update(privateKey)\n .update(\"\\0\")\n .update(publicKey)\n .digest(\"hex\")\n .slice(0, 24);\n}\n\nfunction builderAuthFailureSettingKey(fingerprint: string): string {\n return `${BUILDER_AUTH_FAILURE_SETTING_PREFIX}${fingerprint}`;\n}\n\nexport async function getBuilderCredentialAuthFailure(\n creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n } = {},\n): Promise<BuilderCredentialAuthFailure | null> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return null;\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const row = await getSetting(builderAuthFailureSettingKey(fingerprint));\n if (!row) return null;\n return {\n fingerprint,\n message:\n typeof row.message === \"string\" && row.message\n ? row.message\n : \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n status: typeof row.status === \"number\" ? row.status : undefined,\n code: typeof row.code === \"string\" ? row.code : undefined,\n at: typeof row.at === \"number\" ? row.at : Date.now(),\n ownerEmail:\n typeof row.ownerEmail === \"string\" ? row.ownerEmail : undefined,\n orgId: typeof row.orgId === \"string\" ? row.orgId : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport async function recordBuilderCredentialAuthFailure(details?: {\n status?: number;\n code?: string;\n message?: string;\n}): Promise<void> {\n try {\n const creds = await resolveBuilderCredentials();\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n const { putSetting } = await import(\"../settings/store.js\");\n await putSetting(builderAuthFailureSettingKey(fingerprint), {\n fingerprint,\n message:\n details?.message ||\n \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n ...(typeof details?.status === \"number\" && { status: details.status }),\n ...(details?.code && { code: details.code }),\n at: Date.now(),\n ownerEmail: getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n });\n } catch {\n // Best-effort marker only; the chat error is still returned to the user.\n }\n}\n\nexport async function clearBuilderCredentialAuthFailure(creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n}): Promise<void> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n try {\n const { deleteSetting } = await import(\"../settings/store.js\");\n await deleteSetting(builderAuthFailureSettingKey(fingerprint));\n } catch {\n // A stale failure marker should not block writing fresh credentials.\n }\n}\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Stale-credential cleanup: before writing the new values we (1) clear ALL\n * five BUILDER_* keys at the target scope, so optional fields the new\n * connection doesn't carry (e.g. user picked a Builder space that returns\n * no orgName) don't leave the previous connection's metadata behind, and\n * (2) when writing at org scope, also clear the writer's own user-scope\n * BUILDER_* rows so a stale personal override from an earlier connect\n * doesn't shadow the new org write on resolution (user scope wins org\n * scope by design — see `resolveScopedBuilderCredential`). The org-scope\n * row is intentionally left alone when writing at user scope: that row is\n * shared with the rest of the org and a single user's personal override\n * shouldn't blow it away. (Victoria's \"I signed in again with my Builder\n * space and it still says no credits\" report on 2026-05-11 was exactly\n * this stale-shadow case.)\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret, deleteAppSecret } =\n await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n // Clear stale rows before writing the new connection. See the function's\n // doc comment for the two cases this handles.\n const cleanups: Array<Promise<unknown>> = BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n );\n if (target.scope === \"org\") {\n for (const key of BUILDER_CREDENTIAL_KEYS) {\n cleanups.push(\n deleteAppSecret({ key, scope: \"user\", scopeId: email }).catch(() => {}),\n );\n }\n }\n await Promise.all(cleanups);\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only when the deploy fallback policy allows it.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n // Log Builder-credential lookups by default so \"I connected Builder but\n // chat says no LLM\" reports can be diagnosed from server logs without\n // re-running anything. Keep noise low by gating other keys behind a flag.\n const traceLookup =\n key.startsWith(\"BUILDER_\") ||\n /^(1|true)$/i.test(process.env.DEBUG_CREDENTIAL_RESOLVE ?? \"\");\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return userSecret.value;\n }\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return orgSecret.value;\n }\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return workspaceSecret.value;\n }\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return soloWorkspaceSecret.value;\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=error err=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n // Authenticated multi-tenant context: never fall back to process.env.\n // The deploy-level value would silently impersonate the actual key\n // owner across every tenant. Local/single-tenant deployments keep the\n // original env fallback for BYO-server workflows.\n const envFallback = (\n isBuilderCredentialKey(key)\n ? canUseBuilderDeployCredentialFallbackForRequest()\n : canUseDeployCredentialFallbackForRequest()\n )\n ? process.env[key] || null\n : null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${getRequestOrgId() ?? \"(none)\"} scope=${envFallback ? \"env-fallback\" : \"none\"} hit=${!!envFallback}`,\n );\n }\n return envFallback;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n const value = process.env[key] || null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=(none) scope=env-anonymous hit=${!!value}`,\n );\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://api.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway, which lives at\n * api.builder.io/agent-native/gateway.\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,KAAgC,EAChC,IAA+B;IAE/B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACzC,kBAAkB,CAAS;IAC3B,iBAAiB,CAAU;IAC3B,WAAW,CAAU;IAE9B,YAAY,IAKX;QACC,KAAK,CACH,IAAI,CAAC,OAAO;YACV,gCAAgC,IAAI,CAAC,kBAAkB,yCAAyC,CACnG,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAClD,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,iBAAiB,CAAC;QAChD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;IACtC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAW;IACjD,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC;AACvC,C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C,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n return isDeployCredentialFallbackAllowed();\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\nfunction isBuilderCredentialKey(key: string): boolean {\n return (BUILDER_CREDENTIAL_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHostedWorkspaceRuntime(): boolean {\n const hasFusionPreview = Boolean(\n process.env.FUSION_ENVIRONMENT ||\n process.env.FUSION_ENV_ORIGIN ||\n process.env.VITE_FUSION_ENV_ORIGIN,\n );\n return (\n /^(1|true)$/i.test(process.env.AGENT_NATIVE_WORKSPACE ?? \"\") ||\n /^(1|true)$/i.test(process.env.VITE_AGENT_NATIVE_WORKSPACE ?? \"\") ||\n hasFusionPreview\n );\n}\n\nfunction canUseBuilderDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n // Builder workspace previews can run with NODE_ENV=development and their DB\n // detection can look local during early startup. Once a real signed-in user\n // is present, hosted workspace flags are enough to make deployment-level\n // Builder keys unsafe as an identity fallback.\n if (email && isHostedWorkspaceRuntime()) return false;\n return canUseDeployCredentialFallbackForRequest();\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"workspace\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" | \"workspace\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n // Always trace Builder lookups — these come up in \"I connected Builder but\n // chat still says Use Builder\" support requests, and without scope-by-scope\n // visibility into where the lookup actually went, the only diagnostic move\n // is to ask the user to redo the connect flow. Mirrors `resolveSecret`'s\n // default-on trace gate for BUILDER_* keys.\n let scopeAttempted = \"user\";\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=user hit=true`,\n );\n return { value: userSecret.value, source: \"user\" };\n }\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n scopeAttempted = \"org\";\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n return { value: orgSecret.value, source: \"org\" };\n }\n\n // Older setup flows wrote shared credentials at workspace scope.\n // Keep reading those rows so status UIs and runtime resolution agree\n // for users who connected before org-scoped Builder credentials existed.\n scopeAttempted = \"workspace\";\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=${orgId} miss tried=user,org,workspace`,\n );\n } else {\n scopeAttempted = \"workspace-solo\";\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n console.log(\n `[builder-credential] key=${key} email=${email} orgId=(none) miss tried=user,workspace-solo`,\n );\n }\n } catch (err) {\n console.log(\n `[builder-credential] key=${key} email=${email} scope=${scopeAttempted} error=${(err as Error)?.message ?? err}`,\n );\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseBuilderDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseBuilderDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_AUTH_FAILURE_SETTING_PREFIX = \"builder-auth-failure:\";\n\nexport interface BuilderCredentialAuthFailure {\n fingerprint: string;\n message: string;\n status?: number;\n code?: string;\n at: number;\n ownerEmail?: string | null;\n orgId?: string | null;\n}\n\nexport function builderCredentialFingerprint(\n privateKey?: string | null,\n publicKey?: string | null,\n): string | null {\n if (!privateKey || !publicKey) return null;\n return createHash(\"sha256\")\n .update(privateKey)\n .update(\"\\0\")\n .update(publicKey)\n .digest(\"hex\")\n .slice(0, 24);\n}\n\nfunction builderAuthFailureSettingKey(fingerprint: string): string {\n return `${BUILDER_AUTH_FAILURE_SETTING_PREFIX}${fingerprint}`;\n}\n\nexport async function getBuilderCredentialAuthFailure(\n creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n } = {},\n): Promise<BuilderCredentialAuthFailure | null> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return null;\n try {\n const { getSetting } = await import(\"../settings/store.js\");\n const row = await getSetting(builderAuthFailureSettingKey(fingerprint));\n if (!row) return null;\n return {\n fingerprint,\n message:\n typeof row.message === \"string\" && row.message\n ? row.message\n : \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n status: typeof row.status === \"number\" ? row.status : undefined,\n code: typeof row.code === \"string\" ? row.code : undefined,\n at: typeof row.at === \"number\" ? row.at : Date.now(),\n ownerEmail:\n typeof row.ownerEmail === \"string\" ? row.ownerEmail : undefined,\n orgId: typeof row.orgId === \"string\" ? row.orgId : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport async function recordBuilderCredentialAuthFailure(details?: {\n status?: number;\n code?: string;\n message?: string;\n}): Promise<void> {\n try {\n const creds = await resolveBuilderCredentials();\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n const { putSetting } = await import(\"../settings/store.js\");\n await putSetting(builderAuthFailureSettingKey(fingerprint), {\n fingerprint,\n message:\n details?.message ||\n \"Builder rejected the connected credentials. Reconnect Builder.io.\",\n ...(typeof details?.status === \"number\" && { status: details.status }),\n ...(details?.code && { code: details.code }),\n at: Date.now(),\n ownerEmail: getRequestUserEmail() ?? null,\n orgId: getRequestOrgId() ?? null,\n });\n } catch {\n // Best-effort marker only; the chat error is still returned to the user.\n }\n}\n\nexport async function clearBuilderCredentialAuthFailure(creds: {\n privateKey?: string | null;\n publicKey?: string | null;\n}): Promise<void> {\n const fingerprint = builderCredentialFingerprint(\n creds.privateKey,\n creds.publicKey,\n );\n if (!fingerprint) return;\n try {\n const { deleteSetting } = await import(\"../settings/store.js\");\n await deleteSetting(builderAuthFailureSettingKey(fingerprint));\n } catch {\n // A stale failure marker should not block writing fresh credentials.\n }\n}\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Stale-credential cleanup: before writing the new values we (1) clear ALL\n * five BUILDER_* keys at the target scope, so optional fields the new\n * connection doesn't carry (e.g. user picked a Builder space that returns\n * no orgName) don't leave the previous connection's metadata behind, and\n * (2) when writing at org scope, also clear the writer's own user-scope\n * BUILDER_* rows so a stale personal override from an earlier connect\n * doesn't shadow the new org write on resolution (user scope wins org\n * scope by design — see `resolveScopedBuilderCredential`). The org-scope\n * row is intentionally left alone when writing at user scope: that row is\n * shared with the rest of the org and a single user's personal override\n * shouldn't blow it away. (Victoria's \"I signed in again with my Builder\n * space and it still says no credits\" report on 2026-05-11 was exactly\n * this stale-shadow case.)\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret, deleteAppSecret } =\n await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n // Clear stale rows before writing the new connection. See the function's\n // doc comment for the two cases this handles.\n const cleanups: Array<Promise<unknown>> = BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n );\n if (target.scope === \"org\") {\n for (const key of BUILDER_CREDENTIAL_KEYS) {\n cleanups.push(\n deleteAppSecret({ key, scope: \"user\", scopeId: email }).catch(() => {}),\n );\n }\n }\n await Promise.all(cleanups);\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only when the deploy fallback policy allows it.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n // Log Builder-credential lookups by default so \"I connected Builder but\n // chat says no LLM\" reports can be diagnosed from server logs without\n // re-running anything. Keep noise low by gating other keys behind a flag.\n const traceLookup =\n key.startsWith(\"BUILDER_\") ||\n /^(1|true)$/i.test(process.env.DEBUG_CREDENTIAL_RESOLVE ?? \"\");\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=user hit=true`,\n );\n }\n return userSecret.value;\n }\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=org hit=true`,\n );\n }\n return orgSecret.value;\n }\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${orgId} scope=workspace hit=true`,\n );\n }\n return workspaceSecret.value;\n }\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=workspace-solo hit=true`,\n );\n }\n return soloWorkspaceSecret.value;\n }\n }\n } catch (err) {\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} scope=error err=${(err as Error)?.message ?? err}`,\n );\n }\n // Secrets table not ready — treat as missing.\n }\n // Authenticated multi-tenant context: never fall back to process.env.\n // The deploy-level value would silently impersonate the actual key\n // owner across every tenant. Local/single-tenant deployments keep the\n // original env fallback for BYO-server workflows.\n const envFallback = (\n isBuilderCredentialKey(key)\n ? canUseBuilderDeployCredentialFallbackForRequest()\n : canUseDeployCredentialFallbackForRequest()\n )\n ? process.env[key] || null\n : null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=${email} orgId=${getRequestOrgId() ?? \"(none)\"} scope=${envFallback ? \"env-fallback\" : \"none\"} hit=${!!envFallback}`,\n );\n }\n return envFallback;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n const value = process.env[key] || null;\n if (traceLookup) {\n console.log(\n `[resolve-secret] key=${key} email=(none) scope=env-anonymous hit=${!!value}`,\n );\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://api.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway, which lives at\n * api.builder.io/agent-native/gateway.\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migrate data owned by `local@localhost` to a real account.
|
|
3
|
+
*
|
|
4
|
+
* When a user starts an app in local mode and later signs in to create a real
|
|
5
|
+
* account, this function moves all of their existing data over to the new
|
|
6
|
+
* account so they don't lose anything.
|
|
7
|
+
*
|
|
8
|
+
* Scope of the migration:
|
|
9
|
+
* - `application_state`: rows with `session_id = 'local'`
|
|
10
|
+
* - `settings`: keys prefixed with `u:local@localhost:`
|
|
11
|
+
* - `oauth_tokens`: rows with `owner = 'local@localhost'`
|
|
12
|
+
* - Any template table that has an `owner_email` column: rows with
|
|
13
|
+
* `owner_email = 'local@localhost'`
|
|
14
|
+
*
|
|
15
|
+
* The operation is a no-op if the target email is itself `local@localhost`,
|
|
16
|
+
* empty, or if there is nothing to migrate.
|
|
17
|
+
*/
|
|
18
|
+
export interface LocalMigrationResult {
|
|
19
|
+
/** Whether anything was actually migrated. */
|
|
20
|
+
migrated: boolean;
|
|
21
|
+
/** Per-table row counts that were updated. Omits tables with zero updates. */
|
|
22
|
+
tables: Record<string, number>;
|
|
23
|
+
/** Target email the data now belongs to. */
|
|
24
|
+
targetEmail: string;
|
|
25
|
+
/**
|
|
26
|
+
* Non-fatal per-step errors encountered during migration. One bad table
|
|
27
|
+
* no longer fails the whole upgrade — we migrate everything we can and
|
|
28
|
+
* report any steps that threw here so the UI can surface them.
|
|
29
|
+
*/
|
|
30
|
+
errors?: Array<{
|
|
31
|
+
step: string;
|
|
32
|
+
message: string;
|
|
33
|
+
}>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Migrate every piece of local-mode data to the given real account email.
|
|
37
|
+
* Safe to call multiple times — it only touches rows that are still attached
|
|
38
|
+
* to `local@localhost`.
|
|
39
|
+
*/
|
|
40
|
+
export declare function migrateLocalUserData(targetEmail: string): Promise<LocalMigrationResult>;
|
|
41
|
+
//# sourceMappingURL=local-migration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-migration.d.ts","sourceRoot":"","sources":["../../src/server/local-migration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAQH,MAAM,WAAW,oBAAoB;IACnC,8CAA8C;IAC9C,QAAQ,EAAE,OAAO,CAAC;IAClB,8EAA8E;IAC9E,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACnD;AAoLD;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,oBAAoB,CAAC,CAyD/B"}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migrate data owned by `local@localhost` to a real account.
|
|
3
|
+
*
|
|
4
|
+
* When a user starts an app in local mode and later signs in to create a real
|
|
5
|
+
* account, this function moves all of their existing data over to the new
|
|
6
|
+
* account so they don't lose anything.
|
|
7
|
+
*
|
|
8
|
+
* Scope of the migration:
|
|
9
|
+
* - `application_state`: rows with `session_id = 'local'`
|
|
10
|
+
* - `settings`: keys prefixed with `u:local@localhost:`
|
|
11
|
+
* - `oauth_tokens`: rows with `owner = 'local@localhost'`
|
|
12
|
+
* - Any template table that has an `owner_email` column: rows with
|
|
13
|
+
* `owner_email = 'local@localhost'`
|
|
14
|
+
*
|
|
15
|
+
* The operation is a no-op if the target email is itself `local@localhost`,
|
|
16
|
+
* empty, or if there is nothing to migrate.
|
|
17
|
+
*/
|
|
18
|
+
import { getDbExec, isPostgres } from "../db/client.js";
|
|
19
|
+
const LOCAL_EMAIL = "local@localhost";
|
|
20
|
+
const LOCAL_SESSION_ID = "local";
|
|
21
|
+
const OWNER_COLUMN = "owner_email";
|
|
22
|
+
/**
|
|
23
|
+
* Error messages that indicate a missing/inaccessible table or column — the
|
|
24
|
+
* migration treats these as "feature not enabled" and skips silently.
|
|
25
|
+
*/
|
|
26
|
+
const SCHEMA_SKIP_ERR = /no such table|no such column|does not exist|undefined table|undefined column|relation .* does not exist|column .* does not exist|permission denied|is not a table|cannot update view|cannot change column in a view/i;
|
|
27
|
+
function shouldSkipSchemaError(err) {
|
|
28
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
29
|
+
return SCHEMA_SKIP_ERR.test(message);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Discover every table (not view) in `public` that has an `owner_email`
|
|
33
|
+
* column. Views and materialized views are excluded — they can't be updated
|
|
34
|
+
* directly and would 500 the migration.
|
|
35
|
+
*/
|
|
36
|
+
async function discoverOwnerEmailTables() {
|
|
37
|
+
const client = getDbExec();
|
|
38
|
+
if (isPostgres()) {
|
|
39
|
+
// Join against information_schema.tables to filter out views and
|
|
40
|
+
// materialized views (anything that isn't a plain BASE TABLE).
|
|
41
|
+
const { rows } = await client.execute({
|
|
42
|
+
sql: `SELECT c.table_name
|
|
43
|
+
FROM information_schema.columns c
|
|
44
|
+
JOIN information_schema.tables t
|
|
45
|
+
ON t.table_schema = c.table_schema
|
|
46
|
+
AND t.table_name = c.table_name
|
|
47
|
+
WHERE c.table_schema = 'public'
|
|
48
|
+
AND c.column_name = $1
|
|
49
|
+
AND t.table_type = 'BASE TABLE'`,
|
|
50
|
+
args: [OWNER_COLUMN],
|
|
51
|
+
});
|
|
52
|
+
return rows.map((r) => r.table_name ?? r[0]).filter(Boolean);
|
|
53
|
+
}
|
|
54
|
+
// SQLite path: iterate tables (type='table', not 'view') and inspect columns via PRAGMA
|
|
55
|
+
const tablesRes = await client.execute(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`);
|
|
56
|
+
const tables = tablesRes.rows
|
|
57
|
+
.map((r) => (r.name ?? r[0]))
|
|
58
|
+
.filter(Boolean);
|
|
59
|
+
const withOwner = [];
|
|
60
|
+
for (const table of tables) {
|
|
61
|
+
const escaped = table.replace(/"/g, '""');
|
|
62
|
+
const colsRes = await client.execute(`PRAGMA table_info("${escaped}")`);
|
|
63
|
+
const hasOwner = colsRes.rows.some((row) => (row.name ?? row[1]) === OWNER_COLUMN);
|
|
64
|
+
if (hasOwner)
|
|
65
|
+
withOwner.push(table);
|
|
66
|
+
}
|
|
67
|
+
return withOwner;
|
|
68
|
+
}
|
|
69
|
+
/** Replace `?` placeholders with `$1`, `$2`, … for Postgres. */
|
|
70
|
+
function sqlWithParams(sql) {
|
|
71
|
+
if (!isPostgres())
|
|
72
|
+
return sql;
|
|
73
|
+
let i = 0;
|
|
74
|
+
return sql.replace(/\?/g, () => `$${++i}`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Rename `settings` keys so a user's config carries over. Keys are prefixed
|
|
78
|
+
* with `u:<email>:` — moving from one email to another is a prefix swap.
|
|
79
|
+
*
|
|
80
|
+
* If a destination key already exists (unlikely but possible if the user had
|
|
81
|
+
* previously signed in with the same email) we leave the destination alone
|
|
82
|
+
* and drop the local row, so we never clobber real-account state.
|
|
83
|
+
*/
|
|
84
|
+
async function migrateSettings(targetEmail) {
|
|
85
|
+
const client = getDbExec();
|
|
86
|
+
const oldPrefix = `u:${LOCAL_EMAIL}:`;
|
|
87
|
+
const newPrefix = `u:${targetEmail}:`;
|
|
88
|
+
const { rows } = await client.execute({
|
|
89
|
+
sql: sqlWithParams(`SELECT key FROM settings WHERE key LIKE ? ESCAPE '\\'`),
|
|
90
|
+
args: [oldPrefix.replace(/([\\%_])/g, "\\$1") + "%"],
|
|
91
|
+
});
|
|
92
|
+
let updated = 0;
|
|
93
|
+
for (const row of rows) {
|
|
94
|
+
const oldKey = (row.key ?? row[0]);
|
|
95
|
+
if (!oldKey.startsWith(oldPrefix))
|
|
96
|
+
continue;
|
|
97
|
+
const newKey = newPrefix + oldKey.slice(oldPrefix.length);
|
|
98
|
+
// Skip if the destination already exists — don't overwrite real data.
|
|
99
|
+
const existsRes = await client.execute({
|
|
100
|
+
sql: sqlWithParams(`SELECT 1 FROM settings WHERE key = ?`),
|
|
101
|
+
args: [newKey],
|
|
102
|
+
});
|
|
103
|
+
if (existsRes.rows.length > 0) {
|
|
104
|
+
await client.execute({
|
|
105
|
+
sql: sqlWithParams(`DELETE FROM settings WHERE key = ?`),
|
|
106
|
+
args: [oldKey],
|
|
107
|
+
});
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
await client.execute({
|
|
111
|
+
sql: sqlWithParams(`UPDATE settings SET key = ? WHERE key = ?`),
|
|
112
|
+
args: [newKey, oldKey],
|
|
113
|
+
});
|
|
114
|
+
updated++;
|
|
115
|
+
}
|
|
116
|
+
return updated;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Move application_state rows from `session_id='local'` to the target email.
|
|
120
|
+
* Rows that already exist for the destination session are left alone.
|
|
121
|
+
*/
|
|
122
|
+
async function migrateApplicationState(targetEmail) {
|
|
123
|
+
const client = getDbExec();
|
|
124
|
+
// Only migrate keys that don't already exist under the destination session.
|
|
125
|
+
const { rows } = await client.execute({
|
|
126
|
+
sql: sqlWithParams(`SELECT key FROM application_state WHERE session_id = ?`),
|
|
127
|
+
args: [LOCAL_SESSION_ID],
|
|
128
|
+
});
|
|
129
|
+
let updated = 0;
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
const key = (row.key ?? row[0]);
|
|
132
|
+
const existsRes = await client.execute({
|
|
133
|
+
sql: sqlWithParams(`SELECT 1 FROM application_state WHERE session_id = ? AND key = ?`),
|
|
134
|
+
args: [targetEmail, key],
|
|
135
|
+
});
|
|
136
|
+
if (existsRes.rows.length > 0) {
|
|
137
|
+
await client.execute({
|
|
138
|
+
sql: sqlWithParams(`DELETE FROM application_state WHERE session_id = ? AND key = ?`),
|
|
139
|
+
args: [LOCAL_SESSION_ID, key],
|
|
140
|
+
});
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
await client.execute({
|
|
144
|
+
sql: sqlWithParams(`UPDATE application_state SET session_id = ? WHERE session_id = ? AND key = ?`),
|
|
145
|
+
args: [targetEmail, LOCAL_SESSION_ID, key],
|
|
146
|
+
});
|
|
147
|
+
updated++;
|
|
148
|
+
}
|
|
149
|
+
return updated;
|
|
150
|
+
}
|
|
151
|
+
/** Move oauth_tokens rows. `owner` is the user's email in core tables. */
|
|
152
|
+
async function migrateOauthTokens(targetEmail) {
|
|
153
|
+
const client = getDbExec();
|
|
154
|
+
const res = await client.execute({
|
|
155
|
+
sql: sqlWithParams(`UPDATE oauth_tokens SET owner = ? WHERE owner = ?`),
|
|
156
|
+
args: [targetEmail, LOCAL_EMAIL],
|
|
157
|
+
});
|
|
158
|
+
return res.rowsAffected ?? 0;
|
|
159
|
+
}
|
|
160
|
+
/** Move rows in a template table that uses the `owner_email` convention. */
|
|
161
|
+
async function migrateOwnerEmailTable(table, targetEmail) {
|
|
162
|
+
const client = getDbExec();
|
|
163
|
+
const escaped = table.replace(/"/g, '""');
|
|
164
|
+
const res = await client.execute({
|
|
165
|
+
sql: sqlWithParams(`UPDATE "${escaped}" SET owner_email = ? WHERE owner_email = ?`),
|
|
166
|
+
args: [targetEmail, LOCAL_EMAIL],
|
|
167
|
+
});
|
|
168
|
+
return res.rowsAffected ?? 0;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Migrate every piece of local-mode data to the given real account email.
|
|
172
|
+
* Safe to call multiple times — it only touches rows that are still attached
|
|
173
|
+
* to `local@localhost`.
|
|
174
|
+
*/
|
|
175
|
+
export async function migrateLocalUserData(targetEmail) {
|
|
176
|
+
const email = targetEmail?.trim().toLowerCase();
|
|
177
|
+
if (!email || email === LOCAL_EMAIL) {
|
|
178
|
+
return { migrated: false, tables: {}, targetEmail: email || "" };
|
|
179
|
+
}
|
|
180
|
+
const tables = {};
|
|
181
|
+
// Core tables — best-effort. A missing table just means the feature isn't
|
|
182
|
+
// enabled in this app (e.g. an app that doesn't use oauth_tokens).
|
|
183
|
+
const coreSteps = [
|
|
184
|
+
["settings", () => migrateSettings(email)],
|
|
185
|
+
["application_state", () => migrateApplicationState(email)],
|
|
186
|
+
["oauth_tokens", () => migrateOauthTokens(email)],
|
|
187
|
+
];
|
|
188
|
+
const errors = [];
|
|
189
|
+
for (const [name, fn] of coreSteps) {
|
|
190
|
+
try {
|
|
191
|
+
const count = await fn();
|
|
192
|
+
if (count > 0)
|
|
193
|
+
tables[name] = count;
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
// Missing table or column — skip silently. Other errors are logged
|
|
197
|
+
// per-step so one bad table doesn't 500 the entire migration.
|
|
198
|
+
if (!shouldSkipSchemaError(err)) {
|
|
199
|
+
const message = err?.message ?? String(err);
|
|
200
|
+
errors.push({ step: name, message });
|
|
201
|
+
console.error(`[local-migration] ${name} failed:`, err);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// Template tables — discovered dynamically. If discovery itself fails,
|
|
206
|
+
// fall back to an empty list so the migration doesn't 500.
|
|
207
|
+
let templateTables = [];
|
|
208
|
+
try {
|
|
209
|
+
templateTables = await discoverOwnerEmailTables();
|
|
210
|
+
}
|
|
211
|
+
catch (err) {
|
|
212
|
+
console.error("[local-migration] owner_email table discovery failed:", err);
|
|
213
|
+
templateTables = [];
|
|
214
|
+
}
|
|
215
|
+
for (const table of templateTables) {
|
|
216
|
+
try {
|
|
217
|
+
const count = await migrateOwnerEmailTable(table, email);
|
|
218
|
+
if (count > 0)
|
|
219
|
+
tables[table] = count;
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
if (!shouldSkipSchemaError(err)) {
|
|
223
|
+
const message = err?.message ?? String(err);
|
|
224
|
+
errors.push({ step: table, message });
|
|
225
|
+
console.error(`[local-migration] ${table} failed:`, err);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const migrated = Object.values(tables).some((n) => n > 0);
|
|
230
|
+
const result = { migrated, tables, targetEmail: email };
|
|
231
|
+
if (errors.length > 0)
|
|
232
|
+
result.errors = errors;
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
//# sourceMappingURL=local-migration.js.map
|