@chibitek/chibi 0.1.186 → 0.1.190
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/assets/{abnfDiagram-O67JEVCF-T4rFqxxY.js → abnfDiagram-O67JEVCF-Bz3wlNsQ.js} +1 -1
- package/dist/assets/{arc-BE0n08tb.js → arc-CX0dJSa0.js} +1 -1
- package/dist/assets/{architectureDiagram-NJMV4G6O-W248FhnN.js → architectureDiagram-NJMV4G6O-APIM9yGf.js} +1 -1
- package/dist/assets/{blockDiagram-BEXU5L5S-YQUaYL76.js → blockDiagram-BEXU5L5S-DNmNNaVY.js} +1 -1
- package/dist/assets/{c4Diagram-YGBWAQC7-DvtNnJ7Q.js → c4Diagram-YGBWAQC7-CAPPUeMU.js} +1 -1
- package/dist/assets/channel-CnfDal05.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-r9zB0AN4.js → chunk-2Q5K7J3B-DfCDsQgU.js} +1 -1
- package/dist/assets/{chunk-3FUC2YCW-DcaWZ44l.js → chunk-3FUC2YCW-vdffwGmy.js} +2 -2
- package/dist/assets/{chunk-5VM5RSS4-B9BoCCOM.js → chunk-5VM5RSS4-BazIL_2e.js} +1 -1
- package/dist/assets/{chunk-GTNCS2PH-jiyufqr5.js → chunk-GTNCS2PH-GpKjNZ-V.js} +1 -1
- package/dist/assets/{chunk-GWA4HPMP-86KjuKSi.js → chunk-GWA4HPMP-BuRq21LZ.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-P-CZmlpX.js → chunk-JWPE2WC7-CqNGOyHV.js} +1 -1
- package/dist/assets/{chunk-NETBCI7D-DOwQkah7.js → chunk-NETBCI7D-B1DpzVCP.js} +1 -1
- package/dist/assets/{chunk-WEXAMYUT-BYpUWdau.js → chunk-WEXAMYUT-DcH1Euc6.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-BNWicp85.js → chunk-XXDRQBXY-M1JLd_cm.js} +1 -1
- package/dist/assets/{classDiagram-v2-NBCMYWYE-DeSoK71a.js → classDiagram-v2-NBCMYWYE-C8mBZ7i2.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-DRvyy4x6.js → cose-bilkent-JH36ORCC-Cr3TqHDz.js} +1 -1
- package/dist/assets/{cynefin-OW5HDTMX-BPgTdM9o.js → cynefin-OW5HDTMX-BKPr6l0I.js} +1 -1
- package/dist/assets/{cynefinDiagram-VND7K2PF-CVqWmCzX.js → cynefinDiagram-VND7K2PF-Cbg5mrIM.js} +1 -1
- package/dist/assets/{dagre-6A5THRUB-C8Nn1Pd7.js → dagre-6A5THRUB-9I9X1J3r.js} +1 -1
- package/dist/assets/{diagram-22UHCM2B-BoFPCHMw.js → diagram-22UHCM2B-B43b8pqQ.js} +1 -1
- package/dist/assets/{diagram-3UASUU5V-Bw55J1mb.js → diagram-3UASUU5V-CIehgEkZ.js} +1 -1
- package/dist/assets/{diagram-ATOU4E4O-DGQrBqML.js → diagram-ATOU4E4O-gx8nkXLZ.js} +1 -1
- package/dist/assets/{diagram-CDSNMT55-COdY5ptf.js → diagram-CDSNMT55-BZzWgYHa.js} +1 -1
- package/dist/assets/{diagram-MLGK6HIB-BPZDoncY.js → diagram-MLGK6HIB-BqoCqkZD.js} +1 -1
- package/dist/assets/{diagram-MPIPVDR6-Fi29WkCR.js → diagram-MPIPVDR6-Bsc7x0UT.js} +1 -1
- package/dist/assets/{ebnfDiagram-ZINNZB2B-BXquz6x1.js → ebnfDiagram-ZINNZB2B-8HjdD_s8.js} +1 -1
- package/dist/assets/{elk-276RUBZZ-C_e9eijP.js → elk-276RUBZZ-bmxiEFtT.js} +1 -1
- package/dist/assets/{erDiagram-OPXOYQCR-C4PKtrfT.js → erDiagram-OPXOYQCR-BU-sRLe3.js} +1 -1
- package/dist/assets/{flowDiagram-KWPJA3E3-BlEulfZP.js → flowDiagram-KWPJA3E3-D45vn40U.js} +1 -1
- package/dist/assets/{ganttDiagram-FUAMR5RP-BksDszQx.js → ganttDiagram-FUAMR5RP-CArB98Hu.js} +1 -1
- package/dist/assets/{gitGraphDiagram-X574FWY7-EYJKMot5.js → gitGraphDiagram-X574FWY7-fPB1k-W7.js} +1 -1
- package/dist/assets/{index-Bf2yMkX_.js → index-QsXeEMxJ.js} +142 -142
- package/dist/assets/{index-Do0zrygp.js → index-u1wvoacp.js} +1 -1
- package/dist/assets/{infoDiagram-VRGFBTTK-BuX8YJRd.js → infoDiagram-VRGFBTTK-ZRVWXAr4.js} +1 -1
- package/dist/assets/{ishikawaDiagram-OU5B5YK6-BOOBBq5e.js → ishikawaDiagram-OU5B5YK6-DOaurRbX.js} +1 -1
- package/dist/assets/{journeyDiagram-ZHPQQLJL-2VfxHa4O.js → journeyDiagram-ZHPQQLJL-Ca9B-09w.js} +1 -1
- package/dist/assets/{kanban-definition-PNTS6WVX-DniBc17b.js → kanban-definition-PNTS6WVX-CA2XswEJ.js} +1 -1
- package/dist/assets/{linear-CrF1eGjn.js → linear-B-F7icip.js} +1 -1
- package/dist/assets/{mermaid.core-BL_dHjXO.js → mermaid.core-ymtCpbZ5.js} +5 -5
- package/dist/assets/{mindmap-definition-NLK3R4M7-DUGzdUse.js → mindmap-definition-NLK3R4M7-02vIazCi.js} +1 -1
- package/dist/assets/{pegDiagram-GJSIUBJH-CO3xT6J0.js → pegDiagram-GJSIUBJH-DRb7Pn72.js} +1 -1
- package/dist/assets/{pieDiagram-5QR66LMP-8gmuAKxu.js → pieDiagram-5QR66LMP-B2YwP3S_.js} +1 -1
- package/dist/assets/{quadrantDiagram-O4NWA36T-D0I0xUDm.js → quadrantDiagram-O4NWA36T-CbR573mu.js} +1 -1
- package/dist/assets/{railroadDiagram-XR7U4H2S-DY0BvxgQ.js → railroadDiagram-XR7U4H2S-CqHuDCnM.js} +1 -1
- package/dist/assets/{requirementDiagram-PLB6GJNP-DhGe1AaP.js → requirementDiagram-PLB6GJNP-BSeC-H1j.js} +1 -1
- package/dist/assets/{sankeyDiagram-IPEJSGJF-CeCrbMFN.js → sankeyDiagram-IPEJSGJF-BMFuhoh1.js} +1 -1
- package/dist/assets/{sequenceDiagram-PO4LG4MO-fWSeitKd.js → sequenceDiagram-PO4LG4MO-DRT_EI9u.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-Dtg_1bqe.js → sizeCapture-INFHLROL-BLFT4fV7.js} +1 -1
- package/dist/assets/{stateDiagram-v2-GCMORJYK-DGUAiQQE.js → stateDiagram-v2-GCMORJYK-C8vB_69H.js} +1 -1
- package/dist/assets/{swimlanes-2SLR337P-DebVwPYw.js → swimlanes-2SLR337P-T6BBolT8.js} +1 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-BIY4fGCv.js +8 -0
- package/dist/assets/{timeline-definition-EJHVYXUP-Dg7oYgtr.js → timeline-definition-EJHVYXUP-DjdjBRQV.js} +1 -1
- package/dist/assets/{usecaseDiagram-POWQR4AR-uqTnPXSC.js → usecaseDiagram-POWQR4AR-CDGccZMN.js} +1 -1
- package/dist/assets/{vennDiagram-UO4OBE2U-CzMUwXwR.js → vennDiagram-UO4OBE2U-CgYSihtW.js} +1 -1
- package/dist/assets/{wardleyDiagram-VNRHLVJA-BsyaKB_7.js → wardleyDiagram-VNRHLVJA-Bub5ScM8.js} +1 -1
- package/dist/assets/{xychartDiagram-PMCCYNJV-7hUye0pF.js → xychartDiagram-PMCCYNJV-DK5iMX67.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/drivers/agents-proxy.js +52 -2
- package/dist-server/index.js +4413 -3656
- package/dist-server/openmausbot.js +1432 -878
- package/dist-server/pair-cli.js +1432 -878
- package/dist-server/server/about-me-sync.js +16 -5
- package/dist-server/server/box.js +18 -14
- package/dist-server/server/browser-engine.js +4 -26
- package/dist-server/server/browser-runtime.js +41 -5
- package/dist-server/server/calendar-calls.js +2 -1
- package/dist-server/server/capped-body.js +26 -0
- package/dist-server/server/chibi-defaults.js +96 -0
- package/dist-server/server/cli-login.js +4 -0
- package/dist-server/server/connection-cap-failover.js +0 -2
- package/dist-server/server/container-computer.js +9 -9
- package/dist-server/server/drivers/agents-call.js +3 -3
- package/dist-server/server/drivers/agents-catalog.js +2 -2
- package/dist-server/server/drivers/agents-credential.js +6 -0
- package/dist-server/server/drivers/agents-vault.js +36 -0
- package/dist-server/server/engine-failover.js +6 -3
- package/dist-server/server/engine-tiers.js +8 -8
- package/dist-server/server/hidden-ai-text.js +56 -0
- package/dist-server/server/index.js +37 -41
- package/dist-server/server/local-vm-run.js +10 -0
- package/dist-server/server/model-levels/aliases.js +7 -2
- package/dist-server/server/model-levels/index.js +7 -0
- package/dist-server/server/request-auth.js +15 -18
- package/dist-server/server/routes/message-file.js +1 -1
- package/dist-server/server/routines.js +6 -6
- package/dist-server/server/store.js +1 -1
- package/dist-server/server/stream-tail.js +25 -0
- package/dist-server/server/system-prompt.js +17 -2
- package/dist-server/server/team-rooms/backend.js +9 -4
- package/dist-server/server/team-rooms/service.js +1 -1
- package/dist-server/server/team-rooms/testing/fake-rooms-backend.js +10 -4
- package/dist-server/server/vault/fill.js +338 -0
- package/dist-server/server/vault/request.js +178 -0
- package/dist-server/server/vault/routes.js +14 -2
- package/dist-server/server/vault/runtime.js +27 -3
- package/dist-server/server/vault/store.js +60 -5
- package/dist-server/server/vps-computer.js +12 -30
- package/dist-server/server/watch-along/budget.js +11 -3
- package/dist-server/server/watch-along/live.js +4 -2
- package/dist-server/shared/engine-tiers.js +23 -1
- package/dist-server/shared/provider-accounts.js +5 -3
- package/dist-server/shared/subscription-bots.js +14 -6
- package/dist-server/shared/vault-api-providers.js +48 -0
- package/dist-server/shared/vault-csv.js +62 -14
- package/dist-server/shared/vault.js +20 -2
- package/dist-server/vps-container-mcp.js +3 -1
- package/package.json +1 -1
- package/dist/assets/channel-DhsCc8Nd.js +0 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-B5p2N9qd.js +0 -8
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
// Trusted login fill for the built-in browser. A bot names a Vault login;
|
|
2
|
+
// Atomic checks the grant against the page's real address, finds the sign-in
|
|
3
|
+
// fields itself and types the username and password. The bot never receives
|
|
4
|
+
// the password, and for as long as that browser session lives every way it
|
|
5
|
+
// could read the page back is guarded:
|
|
6
|
+
//
|
|
7
|
+
// - page JavaScript (eval) and copy/cut shortcuts are refused;
|
|
8
|
+
// - the password is removed from every text result (snapshot, read, text,
|
|
9
|
+
// url, title), in plain and URL-encoded form;
|
|
10
|
+
// - a screenshot is withheld while the password is readable on the page,
|
|
11
|
+
// and is never written to a path the bot chose;
|
|
12
|
+
// - a password field the bot edited is emptied before anything else runs,
|
|
13
|
+
// so an edited copy of the password can never be shown and read;
|
|
14
|
+
// - while the password is readable on the page, only looking and clicking
|
|
15
|
+
// work, so it cannot be edited or probed there either.
|
|
16
|
+
//
|
|
17
|
+
// This guards Atomic's browser tools. An engine with a shell on this
|
|
18
|
+
// computer can reach the browser by other means; that is the limit the Vault
|
|
19
|
+
// spec states, not one this module removes.
|
|
20
|
+
import { randomBytes } from "node:crypto";
|
|
21
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
22
|
+
import { dirname } from "node:path";
|
|
23
|
+
import { writeFileAtomic } from "../atomic.js";
|
|
24
|
+
import { vaultOrigin } from "../../shared/vault.js";
|
|
25
|
+
import { VaultError } from "./store.js";
|
|
26
|
+
export const VAULT_FILL_TOOL = "vault_fill_login";
|
|
27
|
+
export const vaultFillTool = {
|
|
28
|
+
name: VAULT_FILL_TOOL,
|
|
29
|
+
description: "Sign in with a login saved in the person's Atomic Vault. Atomic types the username and password into the sign-in form on the current page itself, so you never see the password. Open the site's sign-in page first; it must be on the item's website. Item ids come from vault_request with no arguments. Then click the sign-in button. After a fill, eval and copy shortcuts are off in this browser.",
|
|
30
|
+
inputSchema: {
|
|
31
|
+
type: "object",
|
|
32
|
+
properties: { item_id: { type: "string", description: "The login's id from vault_request." } },
|
|
33
|
+
required: ["item_id"],
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
/** Advertise the fill tool beside the engine's own. */
|
|
38
|
+
export function withVaultFillTool(list) {
|
|
39
|
+
if (!list || typeof list !== "object" || !Array.isArray(list.tools))
|
|
40
|
+
return list;
|
|
41
|
+
return { ...list, tools: [...list.tools, vaultFillTool] };
|
|
42
|
+
}
|
|
43
|
+
const REFUSED = "This bot may not use that Vault login on this page. vault_request with no arguments lists each login's website.";
|
|
44
|
+
const EVAL_OFF = "Page JavaScript is off in this browser because a Vault password was filled. Use snapshot, click, fill and the other browser tools, or close the browser to start clean.";
|
|
45
|
+
const COPY_OFF = "Copy and cut shortcuts are off in this browser because a Vault password was filled.";
|
|
46
|
+
const SHOT_WITHHELD = "Screenshot withheld: a Vault password is readable on this page. Hide the password field's text, or use snapshot, which has it removed.";
|
|
47
|
+
const VALUE_SELECTOR_OFF = "Selectors that match on a field's value are off in this browser because a Vault password was filled. Select by id, name, role or label.";
|
|
48
|
+
const VALUE_SELECTOR = /\[\s*value\b|@value\b/i;
|
|
49
|
+
export const SCREENSHOT_WITHHELD = { content: [{ type: "text", text: SHOT_WITHHELD }], isError: true };
|
|
50
|
+
const ALTERED = "The password field was changed after Atomic filled it, so Atomic emptied it. Call vault_fill_login again to sign in. Until this browser is closed, a password field on this site only accepts a Vault fill.";
|
|
51
|
+
const SHOWN = "A Vault password is readable on this page, so only looking and clicking work here: snapshot, get_text, click and scroll by @ref or CSS selector, navigation, tabs and close. Hide the password, sign in or leave the page to continue.";
|
|
52
|
+
const UNREADABLE = "Atomic could not check this page for a filled Vault password, so only looking and clicking work until it can: snapshot, get_text, click and scroll by @ref or CSS selector, navigation, tabs and close.";
|
|
53
|
+
/** What a bot may still call while the password is readable on the page.
|
|
54
|
+
* Nothing here types, presses a key or matches on the page's text. */
|
|
55
|
+
const LOOK_ONLY = new Set(["snapshot", "get_text", "get_url", "get_title", "click", "scroll", "wait_ms", "wait_for_selector", "wait_for_load", "open", "back", "forward", "reload", "tab_new", "tab_list", "tab_switch", "tab_close", "tools_profiles"].map((name) => `agent_browser_${name}`));
|
|
56
|
+
/** A selector that matches on text answers yes or no about what the page shows. */
|
|
57
|
+
const TEXT_SELECTOR = /text|contains\s*\(/i;
|
|
58
|
+
const STALE = "This browser still holds a Vault password from before Atomic restarted. Close the browser with agent_browser_close, then open the page again.";
|
|
59
|
+
const COPY_KEYS = /^(?:(?:meta|control|ctrl|cmd|command)\+(?:shift\+)?(?:c|x|insert)|copy|cut)$/i;
|
|
60
|
+
const text = (value, isError = false) => ({ content: [{ type: "text", text: value }], ...(isError ? { isError: true } : {}) });
|
|
61
|
+
const textOf = (result) => (Array.isArray(result.content) ? result.content : [])
|
|
62
|
+
.map((part) => part && typeof part === "object" && typeof part.text === "string" ? part.text : "").join("\n");
|
|
63
|
+
/** Run a script that reports through one base64 marker, so the answer reads
|
|
64
|
+
* the same however the engine quotes or wraps an eval result. */
|
|
65
|
+
async function pageReport(call, body) {
|
|
66
|
+
const script = `(() => { const report = (value) => "af1:" + btoa(encodeURIComponent(JSON.stringify(value))) + ":1fa"; try { ${body} } catch (error) { return report({ failed: true }); } })()`;
|
|
67
|
+
const result = await call("agent_browser_eval", { script });
|
|
68
|
+
if (result.isError)
|
|
69
|
+
return null;
|
|
70
|
+
const match = /af1:([A-Za-z0-9+/=]+):1fa/.exec(textOf(result));
|
|
71
|
+
if (!match)
|
|
72
|
+
return null;
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(decodeURIComponent(Buffer.from(match[1], "base64").toString("latin1")));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Find the sign-in fields in the top document and tag them for one fill.
|
|
81
|
+
* Only a real password field receives the password: a bot cannot point it at
|
|
82
|
+
* a field whose text it could read. Fields inside frames are never used. */
|
|
83
|
+
const locate = (tag) => `
|
|
84
|
+
const visible = (el) => { const box = el.getBoundingClientRect(); const style = getComputedStyle(el);
|
|
85
|
+
return box.width > 0 && box.height > 0 && style.visibility !== "hidden" && style.display !== "none" && !el.disabled && !el.readOnly; };
|
|
86
|
+
const inputs = [...document.querySelectorAll("input")].filter(visible);
|
|
87
|
+
const named = (el) => (el.getAttribute("autocomplete") || "") + " " + (el.getAttribute("name") || "") + " " + (el.id || "");
|
|
88
|
+
const textual = (el) => ["text", "email", "tel", ""].includes((el.getAttribute("type") || "").toLowerCase());
|
|
89
|
+
const passwords = inputs.filter((el) => el.type === "password");
|
|
90
|
+
const password = passwords.length === 1 ? passwords[0] : null;
|
|
91
|
+
let user = null;
|
|
92
|
+
if (password) {
|
|
93
|
+
const scope = password.form ? [...password.form.querySelectorAll("input")].filter(visible) : inputs;
|
|
94
|
+
const before = scope.filter((el) => textual(el) && (el.compareDocumentPosition(password) & Node.DOCUMENT_POSITION_FOLLOWING));
|
|
95
|
+
user = before.find((el) => /username|email/i.test(el.getAttribute("autocomplete") || "")) || before[before.length - 1] || null;
|
|
96
|
+
} else if (passwords.length === 0) {
|
|
97
|
+
const candidates = inputs.filter(textual);
|
|
98
|
+
user = candidates.find((el) => /user|email|login|ident|account/i.test(named(el))) || (candidates.length === 1 ? candidates[0] : null);
|
|
99
|
+
}
|
|
100
|
+
const form = (password || user) ? (password || user).form : null;
|
|
101
|
+
let action = location.origin;
|
|
102
|
+
if (form && form.getAttribute("action")) { try { action = new URL(form.getAttribute("action"), location.href).origin; } catch (error) { action = "invalid"; } }
|
|
103
|
+
for (const el of document.querySelectorAll("[data-atomic-vault]")) el.removeAttribute("data-atomic-vault");
|
|
104
|
+
if (user) user.setAttribute("data-atomic-vault", ${JSON.stringify(`${tag}-u`)});
|
|
105
|
+
if (password) password.setAttribute("data-atomic-vault", ${JSON.stringify(`${tag}-p`)});
|
|
106
|
+
return report({ passwords: passwords.length, user: Boolean(user), password: Boolean(password), action, top: window.top === window });`;
|
|
107
|
+
const untag = `for (const el of document.querySelectorAll("[data-atomic-vault]")) el.removeAttribute("data-atomic-vault"); return report({ ok: true });`;
|
|
108
|
+
/** What Atomic reads from the page to judge it: everything a screenshot
|
|
109
|
+
* could show as readable text (the page's text and the values of fields that
|
|
110
|
+
* are not password fields), and the values held by the top document's
|
|
111
|
+
* password fields. The password is never sent into the page to be compared
|
|
112
|
+
* there, because a page the bot opened later could be built to catch it; the
|
|
113
|
+
* comparison happens in Atomic. */
|
|
114
|
+
const READABLE_CAP = 3_000_000;
|
|
115
|
+
const inspect = `
|
|
116
|
+
const out = []; const fields = []; let size = 0; let cut = false;
|
|
117
|
+
const add = (value) => { if (typeof value !== "string" || !value) return; size += value.length; if (size > ${READABLE_CAP}) { cut = true; return; } out.push(value); };
|
|
118
|
+
const scan = (doc) => {
|
|
119
|
+
for (const el of doc.querySelectorAll("input, textarea")) {
|
|
120
|
+
if (el.type !== "password") add(el.value);
|
|
121
|
+
else if (doc === document && el.value) fields.push(String(el.value).slice(0, 10000));
|
|
122
|
+
}
|
|
123
|
+
add(doc.documentElement ? doc.documentElement.innerText : "");
|
|
124
|
+
for (const frame of doc.querySelectorAll("iframe, frame")) { try { if (frame.contentDocument) scan(frame.contentDocument); } catch (error) { /* another origin */ } }
|
|
125
|
+
};
|
|
126
|
+
scan(document);
|
|
127
|
+
return report({ origin: location.origin, texts: out, fields, cut });`;
|
|
128
|
+
/** Empty every password field in the top document the way typing would, so
|
|
129
|
+
* a page that keeps its own copy of the value forgets it too. */
|
|
130
|
+
const empty = `
|
|
131
|
+
const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
|
|
132
|
+
for (const el of document.querySelectorAll("input")) {
|
|
133
|
+
if (el.type !== "password" || !el.value) continue;
|
|
134
|
+
set.call(el, "");
|
|
135
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
136
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
137
|
+
}
|
|
138
|
+
return report({ ok: true });`;
|
|
139
|
+
export class VaultFill {
|
|
140
|
+
/** Browser session → the passwords filled into it, kept in memory only. */
|
|
141
|
+
filled = new Map();
|
|
142
|
+
/** Browser session → the websites a password was filled on. */
|
|
143
|
+
origins = new Map();
|
|
144
|
+
stateFile;
|
|
145
|
+
/** `stateFile` names where tainted session names (never passwords) are
|
|
146
|
+
* kept, so a browser that outlives an Atomic crash stays guarded. */
|
|
147
|
+
constructor(stateFile = () => null) { this.stateFile = stateFile; }
|
|
148
|
+
remembered() {
|
|
149
|
+
const file = this.stateFile();
|
|
150
|
+
if (!file)
|
|
151
|
+
return [];
|
|
152
|
+
try {
|
|
153
|
+
const value = JSON.parse(readFileSync(file, "utf8"));
|
|
154
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return [];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
remember(session, held) {
|
|
161
|
+
const file = this.stateFile();
|
|
162
|
+
if (!file)
|
|
163
|
+
return;
|
|
164
|
+
const sessions = new Set(this.remembered());
|
|
165
|
+
if (held === sessions.has(session))
|
|
166
|
+
return;
|
|
167
|
+
if (held)
|
|
168
|
+
sessions.add(session);
|
|
169
|
+
else
|
|
170
|
+
sessions.delete(session);
|
|
171
|
+
try {
|
|
172
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
173
|
+
writeFileAtomic(file, JSON.stringify([...sessions]), { mode: 0o600 });
|
|
174
|
+
}
|
|
175
|
+
catch { /* The in-memory guard still holds for this run. */ }
|
|
176
|
+
}
|
|
177
|
+
tainted(session) { return this.filled.has(session) || this.remembered().includes(session); }
|
|
178
|
+
/** A password was filled before Atomic restarted and the browser may still
|
|
179
|
+
* hold it. Atomic no longer knows the value, so nothing can be checked. */
|
|
180
|
+
stale(session) { return !this.filled.has(session) && this.remembered().includes(session); }
|
|
181
|
+
/** The browser session ended: its pages, and the passwords in them, are gone. */
|
|
182
|
+
clear(session) { this.filled.delete(session); this.origins.delete(session); this.remember(session, false); }
|
|
183
|
+
/** Each filled password as a page or an address could carry it: as typed,
|
|
184
|
+
* percent-encoded, form-encoded with "+" or "%20" for a space, and escaped
|
|
185
|
+
* for JSON or HTML. */
|
|
186
|
+
secrets(session) {
|
|
187
|
+
const out = new Set();
|
|
188
|
+
for (const secret of this.filled.get(session) ?? []) {
|
|
189
|
+
if (!secret)
|
|
190
|
+
continue;
|
|
191
|
+
const form = new URLSearchParams({ v: secret }).toString().slice(2);
|
|
192
|
+
const html = secret.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
193
|
+
for (const variant of [secret, encodeURIComponent(secret), encodeURI(secret), form, form.replace(/\+/g, "%20"), JSON.stringify(secret).slice(1, -1),
|
|
194
|
+
html, html.replace(/"/g, """), html.replace(/"/g, """).replace(/'/g, "'")])
|
|
195
|
+
out.add(variant);
|
|
196
|
+
}
|
|
197
|
+
return [...out].sort((x, y) => y.length - x.length);
|
|
198
|
+
}
|
|
199
|
+
/** Before a bot's call reaches the engine: a refusal, or the arguments to send. */
|
|
200
|
+
before(session, name, args) {
|
|
201
|
+
if (!this.tainted(session))
|
|
202
|
+
return { args };
|
|
203
|
+
if (this.stale(session) && name !== "agent_browser_close")
|
|
204
|
+
return { refuse: text(STALE, true) };
|
|
205
|
+
if (name === "agent_browser_eval")
|
|
206
|
+
return { refuse: text(EVAL_OFF, true) };
|
|
207
|
+
if (name === "agent_browser_press" && typeof args.key === "string" && COPY_KEYS.test(args.key.replace(/\s+/g, "")))
|
|
208
|
+
return { refuse: text(COPY_OFF, true) };
|
|
209
|
+
// A selector that tests a field's value answers yes or no, which reads
|
|
210
|
+
// the password out one character at a time.
|
|
211
|
+
if (Object.entries(args).some(([key, value]) => /selector/i.test(key) && typeof value === "string" && VALUE_SELECTOR.test(value)))
|
|
212
|
+
return { refuse: text(VALUE_SELECTOR_OFF, true) };
|
|
213
|
+
if (name === "agent_browser_screenshot") {
|
|
214
|
+
const { path: _path, screenshotDir: _dir, ...rest } = args;
|
|
215
|
+
return { args: rest };
|
|
216
|
+
}
|
|
217
|
+
return { args };
|
|
218
|
+
}
|
|
219
|
+
/** Read the page and judge it. A password field on a filled website that
|
|
220
|
+
* holds anything but a filled password was edited: it is emptied here,
|
|
221
|
+
* before the bot's next call, because an edited copy would pass every
|
|
222
|
+
* comparison once the site showed it as text. */
|
|
223
|
+
async state(session, call) {
|
|
224
|
+
const report = await pageReport(call, inspect).catch(() => null);
|
|
225
|
+
if (!report || report.failed || report.cut || !Array.isArray(report.texts) || !Array.isArray(report.fields))
|
|
226
|
+
return "unknown";
|
|
227
|
+
const filled = this.filled.get(session) ?? new Set();
|
|
228
|
+
const here = typeof report.origin === "string" && this.origins.get(session)?.has(report.origin) === true;
|
|
229
|
+
const altered = here && report.fields.some((value) => typeof value !== "string" || !filled.has(value));
|
|
230
|
+
if (altered)
|
|
231
|
+
await pageReport(call, empty).catch(() => null);
|
|
232
|
+
const secrets = this.secrets(session);
|
|
233
|
+
const shown = report.texts.some((value) => typeof value === "string" && secrets.some((secret) => value.includes(secret)));
|
|
234
|
+
return shown ? "shown" : altered ? "altered" : "clean";
|
|
235
|
+
}
|
|
236
|
+
/** Before a bot's call reaches the engine, after `before`: a refusal when
|
|
237
|
+
* the page's state does not allow the call, or null to let it through. */
|
|
238
|
+
async guard(session, name, args, call) {
|
|
239
|
+
if (!this.tainted(session) || name === "agent_browser_close")
|
|
240
|
+
return null;
|
|
241
|
+
const state = await this.state(session, call);
|
|
242
|
+
if (state === "clean")
|
|
243
|
+
return null;
|
|
244
|
+
if (state === "altered")
|
|
245
|
+
return text(ALTERED, true);
|
|
246
|
+
if (name === "agent_browser_screenshot")
|
|
247
|
+
return SCREENSHOT_WITHHELD;
|
|
248
|
+
const probing = Object.entries(args).some(([key, value]) => /selector/i.test(key) && typeof value === "string" && TEXT_SELECTOR.test(value));
|
|
249
|
+
return LOOK_ONLY.has(name) && !probing ? null : text(state === "shown" ? SHOWN : UNREADABLE, true);
|
|
250
|
+
}
|
|
251
|
+
/** The result with every filled password removed from its text. Runs
|
|
252
|
+
* before a long result is cut to size, so a cut can never leave part of a
|
|
253
|
+
* password behind. */
|
|
254
|
+
scrub(session, result) {
|
|
255
|
+
if (!this.filled.has(session) || !result || typeof result !== "object" || !Array.isArray(result.content))
|
|
256
|
+
return result;
|
|
257
|
+
const secrets = this.secrets(session);
|
|
258
|
+
const clean = (value) => secrets.reduce((out, secret) => out.split(secret).join("[redacted]"), value);
|
|
259
|
+
return {
|
|
260
|
+
...result,
|
|
261
|
+
content: result.content.map((part) => part && typeof part === "object" && typeof part.text === "string"
|
|
262
|
+
? { ...part, text: clean(part.text) } : part),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/** After the engine answered a bot's call: the result the bot may see. */
|
|
266
|
+
async after(session, result, call) {
|
|
267
|
+
if (!this.tainted(session) || !result || typeof result !== "object")
|
|
268
|
+
return result;
|
|
269
|
+
const state = await this.state(session, call);
|
|
270
|
+
if (state === "altered")
|
|
271
|
+
return text(ALTERED, true);
|
|
272
|
+
const image = (Array.isArray(result.content) ? result.content : []).some((part) => part && typeof part === "object" && part.type !== "text");
|
|
273
|
+
if (image && state !== "clean")
|
|
274
|
+
return SCREENSHOT_WITHHELD;
|
|
275
|
+
return this.scrub(session, result);
|
|
276
|
+
}
|
|
277
|
+
/** The vault_fill_login tool. Every refusal about the item reads the same
|
|
278
|
+
* whether it is missing, not granted, expired, not a login or for another site. */
|
|
279
|
+
async fill(session, access, args, call, now = Date.now()) {
|
|
280
|
+
if (this.stale(session))
|
|
281
|
+
return text(STALE, true);
|
|
282
|
+
if (!access)
|
|
283
|
+
return text("Vault is locked on this computer. It unlocks when the Atomic desktop app is open.", true);
|
|
284
|
+
const itemId = typeof args.item_id === "string" ? args.item_id : "";
|
|
285
|
+
if (!/^[0-9a-f-]{36}$/.test(itemId))
|
|
286
|
+
return text("vault_fill_login needs item_id from vault_request.", true);
|
|
287
|
+
const pageOrigin = async () => vaultOrigin(textOf(await call("agent_browser_get_url", {})).match(/https:\/\/[^\s"'<>]+/)?.[0] ?? "");
|
|
288
|
+
const destination = await pageOrigin();
|
|
289
|
+
if (!destination)
|
|
290
|
+
return text("Open the site's sign-in page (an https:// address) before filling a login.", true);
|
|
291
|
+
let login;
|
|
292
|
+
try {
|
|
293
|
+
login = access.store.loginFor({ ownerId: access.ownerId, botId: access.botId, destination }, itemId, now);
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
return text(error instanceof VaultError ? error.message : "Vault could not complete the request.", true);
|
|
297
|
+
}
|
|
298
|
+
if (!login)
|
|
299
|
+
return text(REFUSED, true);
|
|
300
|
+
const tag = randomBytes(8).toString("hex");
|
|
301
|
+
const found = await pageReport(call, locate(tag));
|
|
302
|
+
if (!found || found.failed)
|
|
303
|
+
return text("The sign-in form could not be read on this page.", true);
|
|
304
|
+
try {
|
|
305
|
+
if (!found.top)
|
|
306
|
+
return text("The sign-in form is inside a frame. Open the sign-in page directly.", true);
|
|
307
|
+
if (found.passwords > 1)
|
|
308
|
+
return text("This page has more than one password field, so it looks like a sign-up or change-password form. A saved login is only filled into a sign-in form.", true);
|
|
309
|
+
if (!found.user && !found.password)
|
|
310
|
+
return text("No sign-in field was found on this page. Open the sign-in form first.", true);
|
|
311
|
+
if (found.action !== destination)
|
|
312
|
+
return text("This form sends what is typed to a different website, so the login was not filled.", true);
|
|
313
|
+
if (found.user) {
|
|
314
|
+
const typed = await call("agent_browser_fill", { selector: `[data-atomic-vault="${tag}-u"]`, text: login.username });
|
|
315
|
+
if (typed.isError)
|
|
316
|
+
return text("The username field could not be filled.", true);
|
|
317
|
+
}
|
|
318
|
+
if (!found.password)
|
|
319
|
+
return text("Filled the username. Continue to the password step, then call vault_fill_login again.");
|
|
320
|
+
// The page may have moved while the username was typed.
|
|
321
|
+
if (await pageOrigin() !== destination)
|
|
322
|
+
return text("The page changed before the password was typed, so it was not filled.", true);
|
|
323
|
+
// From here the password is in the page: guard the session first.
|
|
324
|
+
const set = this.filled.get(session) ?? new Set();
|
|
325
|
+
set.add(login.password);
|
|
326
|
+
this.filled.set(session, set);
|
|
327
|
+
this.origins.set(session, (this.origins.get(session) ?? new Set()).add(destination));
|
|
328
|
+
this.remember(session, true);
|
|
329
|
+
const typed = await call("agent_browser_fill", { selector: `[data-atomic-vault="${tag}-p"]`, text: login.password });
|
|
330
|
+
if (typed.isError)
|
|
331
|
+
return text("The password field could not be filled.", true);
|
|
332
|
+
return text(found.user ? "Filled the username and password. Click the sign-in button to continue." : "Filled the password. Click the sign-in button to continue.");
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
await pageReport(call, untag).catch(() => null);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { vaultOrigin } from "../../shared/vault.js";
|
|
6
|
+
import { PASS } from "../routes/table.js";
|
|
7
|
+
import { VaultError } from "./store.js";
|
|
8
|
+
const MAX_REQUEST_BODY = 1_000_000;
|
|
9
|
+
const MAX_TEXT = 100_000;
|
|
10
|
+
const MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
11
|
+
const REQUEST_TIMEOUT_MS = 120_000;
|
|
12
|
+
const DOWNLOAD_KEEP_MS = 7 * 24 * 60 * 60_000;
|
|
13
|
+
// Set by the transport, or able to reroute or smuggle the request.
|
|
14
|
+
const REFUSED_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "upgrade", "proxy-authorization", "te", "trailer"]);
|
|
15
|
+
const EXTENSIONS = {
|
|
16
|
+
"audio/mpeg": ".mp3", "audio/wav": ".wav", "audio/x-wav": ".wav", "audio/ogg": ".ogg", "audio/flac": ".flac", "audio/mp4": ".m4a",
|
|
17
|
+
"video/mp4": ".mp4", "video/webm": ".webm", "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif",
|
|
18
|
+
"application/pdf": ".pdf", "application/zip": ".zip", "application/json": ".json", "text/plain": ".txt", "text/csv": ".csv",
|
|
19
|
+
};
|
|
20
|
+
const requestSchema = z.object({
|
|
21
|
+
item_id: z.string().uuid(),
|
|
22
|
+
url: z.string().min(1).max(4096),
|
|
23
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("GET"),
|
|
24
|
+
headers: z.record(z.string().regex(/^[A-Za-z0-9-]{1,64}$/), z.string().regex(/^[\x20-\x7E]{0,4096}$/))
|
|
25
|
+
.refine((headers) => Object.keys(headers).length <= 40).default({}),
|
|
26
|
+
body: z.string().max(MAX_REQUEST_BODY).optional(),
|
|
27
|
+
save_as: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/).optional(),
|
|
28
|
+
}).strict();
|
|
29
|
+
const REFUSED = "This bot may not use that Vault item at that address. Call vault_request with no arguments to see each item's allowed addresses.";
|
|
30
|
+
function isText(contentType) {
|
|
31
|
+
return /^text\/|[/+](?:json|xml)\b|^application\/(?:x-www-form-urlencoded|javascript|x-ndjson)\b/i.test(contentType);
|
|
32
|
+
}
|
|
33
|
+
async function readCapped(response) {
|
|
34
|
+
if (!response.body)
|
|
35
|
+
return Buffer.alloc(0);
|
|
36
|
+
const chunks = [];
|
|
37
|
+
let total = 0;
|
|
38
|
+
const reader = response.body.getReader();
|
|
39
|
+
for (;;) {
|
|
40
|
+
const { done, value } = await reader.read();
|
|
41
|
+
if (done)
|
|
42
|
+
break;
|
|
43
|
+
total += value.byteLength;
|
|
44
|
+
if (total > MAX_RESPONSE_BYTES) {
|
|
45
|
+
await reader.cancel().catch(() => undefined);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
chunks.push(Buffer.from(value));
|
|
49
|
+
}
|
|
50
|
+
return Buffer.concat(chunks);
|
|
51
|
+
}
|
|
52
|
+
function save(directory, name, data, now) {
|
|
53
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
54
|
+
for (const entry of readdirSync(directory)) {
|
|
55
|
+
const file = join(directory, entry);
|
|
56
|
+
try {
|
|
57
|
+
if (now - statSync(file).mtimeMs > DOWNLOAD_KEEP_MS)
|
|
58
|
+
unlinkSync(file);
|
|
59
|
+
}
|
|
60
|
+
catch { /* another turn removed it */ }
|
|
61
|
+
}
|
|
62
|
+
const file = join(directory, `${now}-${randomBytes(3).toString("hex")}-${name}`);
|
|
63
|
+
writeFileSync(file, data, { mode: 0o600, flag: "wx" });
|
|
64
|
+
return file;
|
|
65
|
+
}
|
|
66
|
+
/** One request on a bot's behalf. Every refusal reads the same whether the
|
|
67
|
+
* item is missing, another owner's, not granted, expired, of another kind or
|
|
68
|
+
* bound to a different address. */
|
|
69
|
+
export async function vaultRequest(raw, deps) {
|
|
70
|
+
const parsed = requestSchema.safeParse(raw);
|
|
71
|
+
if (!parsed.success)
|
|
72
|
+
return { ok: false, status: 400, error: "vault_request needs item_id and an HTTPS url. method, headers, body and save_as are optional." };
|
|
73
|
+
const input = parsed.data;
|
|
74
|
+
const now = (deps.now ?? Date.now)();
|
|
75
|
+
const destination = vaultOrigin(input.url);
|
|
76
|
+
if (!destination)
|
|
77
|
+
return { ok: false, status: 400, error: "The url must be an https:// address with no username or password in it." };
|
|
78
|
+
let key;
|
|
79
|
+
try {
|
|
80
|
+
key = deps.store.apiKeyFor({ ownerId: deps.ownerId, botId: deps.botId, destination }, input.item_id, now);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
return { ok: false, status: 503, error: error instanceof VaultError ? error.message : "Vault could not complete the request." };
|
|
84
|
+
}
|
|
85
|
+
if (!key)
|
|
86
|
+
return { ok: false, status: 403, error: REFUSED };
|
|
87
|
+
const headers = new Headers();
|
|
88
|
+
for (const [name, value] of Object.entries(input.headers)) {
|
|
89
|
+
const lower = name.toLowerCase();
|
|
90
|
+
if (REFUSED_HEADERS.has(lower))
|
|
91
|
+
return { ok: false, status: 400, error: `The ${name} header cannot be set.` };
|
|
92
|
+
if (lower === key.header.toLowerCase())
|
|
93
|
+
return { ok: false, status: 400, error: `Leave out the ${name} header. Atomic adds it from the Vault item.` };
|
|
94
|
+
headers.set(name, value);
|
|
95
|
+
}
|
|
96
|
+
headers.set(key.header, key.value);
|
|
97
|
+
let response;
|
|
98
|
+
let data;
|
|
99
|
+
try {
|
|
100
|
+
response = await (deps.fetch ?? fetch)(input.url, {
|
|
101
|
+
method: input.method, headers, redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
102
|
+
...(input.body !== undefined && input.method !== "GET" ? { body: input.body } : {}),
|
|
103
|
+
});
|
|
104
|
+
data = await readCapped(response);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
const timedOut = error instanceof Error && error.name === "TimeoutError";
|
|
108
|
+
return { ok: false, status: 502, error: timedOut ? "The service did not answer in time." : "The service could not be reached." };
|
|
109
|
+
}
|
|
110
|
+
if (!data)
|
|
111
|
+
return { ok: false, status: 502, error: "The response was larger than 50 MB and was not kept." };
|
|
112
|
+
const contentType = (response.headers.get("content-type") ?? "").slice(0, 200);
|
|
113
|
+
const result = { ok: true, status: response.status, contentType, bytes: data.length };
|
|
114
|
+
// A redirect could carry the key to an address the owner never listed.
|
|
115
|
+
const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
|
|
116
|
+
if (location)
|
|
117
|
+
result.location = location.split(key.secret).join("[redacted]").slice(0, 2048);
|
|
118
|
+
const text = isText(contentType) || data.length === 0;
|
|
119
|
+
const scrubbed = text ? data.toString("utf8").split(key.value).join("[redacted]").split(key.secret).join("[redacted]") : "";
|
|
120
|
+
if (text && !input.save_as) {
|
|
121
|
+
result.text = scrubbed.slice(0, MAX_TEXT);
|
|
122
|
+
if (scrubbed.length > MAX_TEXT)
|
|
123
|
+
result.truncated = true;
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
const mime = contentType.split(";")[0].trim().toLowerCase();
|
|
127
|
+
const name = input.save_as ?? `response${EXTENSIONS[mime] ?? ".bin"}`;
|
|
128
|
+
try {
|
|
129
|
+
result.savedTo = save(deps.downloadDir, name, text ? Buffer.from(scrubbed) : data, now);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return { ok: false, status: 503, error: "The response could not be saved on this computer." };
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
/** The two routes the vault tools call, on the loopback internal API. `bot`
|
|
137
|
+
* answers from the capability the harness minted for the turn; nothing in
|
|
138
|
+
* the request body says who is asking. */
|
|
139
|
+
export function createVaultBotRoutes(deps) {
|
|
140
|
+
return async ({ req, res, path, method, json, readBody }) => {
|
|
141
|
+
if (!path.startsWith("/api/internal/vault/"))
|
|
142
|
+
return PASS;
|
|
143
|
+
res.setHeader("cache-control", "no-store");
|
|
144
|
+
const botId = deps.bot(req);
|
|
145
|
+
if (!botId)
|
|
146
|
+
return json(res, 401, { error: "Vault tools are available to a bot during its own turn only." });
|
|
147
|
+
const store = deps.store();
|
|
148
|
+
const ownerId = deps.ownerId();
|
|
149
|
+
if (!store || !ownerId)
|
|
150
|
+
return json(res, 503, { error: "Vault is locked on this computer. It unlocks when the Atomic desktop app is open." });
|
|
151
|
+
try {
|
|
152
|
+
if (path === "/api/internal/vault/keys" && method === "GET") {
|
|
153
|
+
const now = (deps.now ?? Date.now)();
|
|
154
|
+
const items = store.apiKeysFor(ownerId, botId, now)
|
|
155
|
+
.map(({ id, label, hints, origins, header, expiresAt }) => ({ id, label, hints, origins, header, expiresAt }));
|
|
156
|
+
// Logins are filled by the browser's vault_fill_login tool, on their website only.
|
|
157
|
+
const logins = store.loginsFor(ownerId, botId, now)
|
|
158
|
+
.map(({ id, label, hints, origins, username, expiresAt }) => ({ id, label, hints, website: origins[0], username, expiresAt }));
|
|
159
|
+
return json(res, 200, { items, logins });
|
|
160
|
+
}
|
|
161
|
+
if (path === "/api/internal/vault/request" && method === "POST") {
|
|
162
|
+
const body = await readBody(req, MAX_REQUEST_BODY + 200_000).catch(() => null);
|
|
163
|
+
if (deps.bot(req) !== botId || deps.store() !== store)
|
|
164
|
+
return json(res, 403, { error: "Vault access changed. Try again." });
|
|
165
|
+
const result = await vaultRequest(body, { store, ownerId, botId, downloadDir: deps.downloadDir(botId), fetch: deps.fetch, now: deps.now });
|
|
166
|
+
const item = body && typeof body === "object" && "item_id" in body ? String(body.item_id).slice(0, 36) : "";
|
|
167
|
+
console.log(`[vault] bot=${botId} item=${item} status=${result.status}${result.ok ? "" : " refused"}`);
|
|
168
|
+
return result.ok ? json(res, 200, result) : json(res, result.status, { error: result.error });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (error instanceof VaultError)
|
|
173
|
+
return json(res, 503, { error: error.message });
|
|
174
|
+
return json(res, 503, { error: "Vault could not complete the request." });
|
|
175
|
+
}
|
|
176
|
+
return json(res, 404, { error: "not found" });
|
|
177
|
+
};
|
|
178
|
+
}
|
|
@@ -23,8 +23,8 @@ export function createVaultRoutes(deps) {
|
|
|
23
23
|
if (typeof body?.csv !== "string")
|
|
24
24
|
return json(res, 400, { error: "Choose a CSV file exported from your password manager." });
|
|
25
25
|
try {
|
|
26
|
-
const { logins, skipped } = vaultLoginsFromCsv(body.csv, typeof body.group === "string" && body.group ? body.group : undefined);
|
|
27
|
-
return json(res, 200, { ...store.importLogins(ownerId, logins), skipped });
|
|
26
|
+
const { logins, apiKeys, skipped, needAddress } = vaultLoginsFromCsv(body.csv, typeof body.group === "string" && body.group ? body.group : undefined);
|
|
27
|
+
return json(res, 200, { ...store.importLogins(ownerId, [...logins, ...apiKeys]), skipped, needAddress });
|
|
28
28
|
}
|
|
29
29
|
catch (error) {
|
|
30
30
|
// Neither message echoes anything from a row.
|
|
@@ -33,6 +33,18 @@ export function createVaultRoutes(deps) {
|
|
|
33
33
|
return json(res, 503, { error: "Vault could not complete the request." });
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
+
if (path === "/api/vault/allow-all-bots") {
|
|
37
|
+
if (method !== "POST")
|
|
38
|
+
return json(res, 405, { error: "Method not allowed." });
|
|
39
|
+
try {
|
|
40
|
+
return json(res, 200, { changed: store.allowAllBots(ownerId) });
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error instanceof VaultError)
|
|
44
|
+
return json(res, 400, { error: error.message });
|
|
45
|
+
return json(res, 503, { error: "Vault could not complete the request." });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
36
48
|
const item = /^\/api\/vault\/([0-9a-f-]{36})$/.exec(path);
|
|
37
49
|
if (path !== "/api/vault" && !item)
|
|
38
50
|
return json(res, 404, { error: "Vault item is unavailable." });
|
|
@@ -4,6 +4,7 @@ import { VaultStore } from "./store.js";
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { ROUTES } from "../routes/table.js";
|
|
6
6
|
import { createVaultRoutes } from "./routes.js";
|
|
7
|
+
import { createVaultBotRoutes } from "./request.js";
|
|
7
8
|
const keyMessage = z.object({ type: z.literal("atomic:native-vault-key"), ownerId: z.string().uuid(), key: z.string().regex(/^[0-9a-f]{64}$/) }).strict();
|
|
8
9
|
/** Constructed by the server, bootstrapped only on Electron's private port.
|
|
9
10
|
* No HTTP endpoint can unlock the vault or replace its owner. */
|
|
@@ -29,6 +30,8 @@ export class NativeVaultRuntime {
|
|
|
29
30
|
return true;
|
|
30
31
|
}
|
|
31
32
|
store() { return this.#store; }
|
|
33
|
+
/** The owner whose items bots may be granted: set with the key, never from a request. */
|
|
34
|
+
ownerId() { return this.#ownerId; }
|
|
32
35
|
/** Until paired owner identity is established, remote clients fail closed.
|
|
33
36
|
* GET needs the desktop capability too; loopback alone is not authority. */
|
|
34
37
|
owner(req, auth, desktopToken) {
|
|
@@ -40,9 +43,30 @@ export class NativeVaultRuntime {
|
|
|
40
43
|
return this.#ownerId ?? "pending";
|
|
41
44
|
}
|
|
42
45
|
}
|
|
43
|
-
/** Keep bootstrapping and route registration together, outside index.ts.
|
|
44
|
-
|
|
46
|
+
/** Keep bootstrapping and route registration together, outside index.ts.
|
|
47
|
+
* Owner routes refuse every bot. The bot routes answer only the agents tools
|
|
48
|
+
* of a bot's own turn on this computer, never an external runtime. */
|
|
49
|
+
export function installNativeVault(dataDir, port, desktopToken, caller) {
|
|
45
50
|
const runtime = new NativeVaultRuntime(join(dataDir, "providers", "native-vault"));
|
|
51
|
+
installed = runtime;
|
|
52
|
+
fillState = join(dataDir, "providers", "native-vault", "filled-sessions.json");
|
|
46
53
|
port?.on("message", (event) => { runtime.receive(event?.data); });
|
|
47
|
-
ROUTES.push(createVaultRoutes({ store: () => runtime.store(), owner: (req, auth) =>
|
|
54
|
+
ROUTES.push(createVaultRoutes({ store: () => runtime.store(), owner: (req, auth) => caller(req) ? null : runtime.owner(req, auth, desktopToken()) }));
|
|
55
|
+
ROUTES.push(createVaultBotRoutes({ store: () => runtime.store(), ownerId: () => runtime.ownerId(),
|
|
56
|
+
bot: (req) => vaultBot(caller(req)), downloadDir: (botId) => join(dataDir, "vault-downloads", botId) }));
|
|
57
|
+
}
|
|
58
|
+
let fillState = null;
|
|
59
|
+
/** Where the browser sessions holding a filled password are remembered
|
|
60
|
+
* across a restart. Session names only, never a password. */
|
|
61
|
+
export function vaultFillStateFile() { return fillState; }
|
|
62
|
+
let installed = null;
|
|
63
|
+
/** The unlocked vault, for the browser's trusted login fill. Null while the
|
|
64
|
+
* vault is locked or this server has none. */
|
|
65
|
+
export function unlockedVault() {
|
|
66
|
+
const store = installed?.store();
|
|
67
|
+
const ownerId = installed?.ownerId();
|
|
68
|
+
return store && ownerId ? { store, ownerId } : null;
|
|
69
|
+
}
|
|
70
|
+
export function vaultBot(caller) {
|
|
71
|
+
return caller && caller.kind === "agents" && !caller.externalRuntime ? caller.botId : null;
|
|
48
72
|
}
|