openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
236 lines (235 loc) • 6.92 kB
JavaScript
import { l as ignoreMissingPath, y as toErrorObject } from "./paths-0xDagtub.mjs";
import { F as resolveTimerTimeoutMs, a as resolveStateDir, f as resolveRequiredOsHomeDir } from "./path-guards-quCEQx1i.mjs";
import { p as resolveDatabasePathKey } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { d as object, i as boolean, m as string, o as discriminatedUnion, r as array, s as literal, u as number } from "./schemas-DA6xYxQu.mjs";
import path from "node:path";
import crypto from "node:crypto";
import fsPromises from "node:fs/promises";
import net from "node:net";
import { addAbortListener } from "node:events";
import { clearTimeout, setTimeout } from "node:timers";
//#region src/infra/jsonl-socket.ts
const JSONL_SOCKET_MAX_LINE_BYTES = 16777216;
/**
* Sends one JSONL request line, half-closes the write side, and waits for an accepted response line.
*/
async function requestJsonlSocket(e) {
const { socketPath: t, requestLine: n, accept: r, signal: i } = e;
const a = e.timeoutMs === 0 ? 0 : resolveTimerTimeoutMs(e.timeoutMs, 1);
return await new Promise((o, s) => {
const c = new net.Socket();
let l = false;
let u = false;
let d;
const f = [];
let p = 0;
const cleanup = () => {
if (l) return false;
l = true;
clearTimeout(d);
m?.[Symbol.dispose]();
c.destroy();
return true;
};
const finish = (e) => {
if (cleanup()) o(e);
};
const fail = (e) => {
if (cleanup()) s(toErrorObject(e, "Socket request failed before sending."));
};
const finishPeerLoss = () => finish(u ? e.onResponseLost?.() ?? null : null);
const appendLineChunk = (t) => {
if (p + t.byteLength > (e.maxResponseLineBytes ?? JSONL_SOCKET_MAX_LINE_BYTES)) {
finishPeerLoss();
return false;
}
if (t.byteLength > 0) {
f.push(t);
p += t.byteLength;
}
return true;
};
if (a > 0) d = setTimeout(() => finish(u ? e.onTimeout?.() ?? null : null), a);
const m = i ? addAbortListener(i, () => finish(null)) : void 0;
if (i?.aborted) {
finish(null);
return;
}
c.on("error", finishPeerLoss);
c.on("end", finishPeerLoss);
c.on("close", finishPeerLoss);
c.connect(t, () => {
if (l) return;
try {
e.beforeSend?.();
} catch (e) {
fail(e);
return;
}
if (l) return;
u = true;
c.end(`${n}\n`);
});
c.on("data", (e) => {
let t = 0;
while (t < e.byteLength) {
const n = e.indexOf(10, t);
if (n === -1) {
appendLineChunk(e.subarray(t));
return;
}
if (!appendLineChunk(e.subarray(t, n))) return;
const i = (f.length > 1 ? Buffer.concat(f, p) : f[0])?.toString("utf8").trim() ?? "";
f.length = 0;
p = 0;
t = n + 1;
if (!i) continue;
try {
const e = JSON.parse(i);
const t = r(e);
if (t === void 0) continue;
finish(t);
return;
} catch {}
}
});
});
}
//#endregion
//#region src/infra/client-credential-ipc.ts
const identity = object({
identity_key: string(),
device_id: string(),
public_key_pem: string(),
private_key_pem: string(),
created_at_ms: number(),
updated_at_ms: number()
});
const token = object({
device_id: string(),
role: string(),
token: string(),
scopes_json: string(),
updated_at_ms: number()
});
const socket = object({
socket_key: literal("current"),
socket_path: string().nullable(),
socket_token: string().nullable(),
updated_at_ms: number()
});
const resultSchema = discriminatedUnion("kind", [
object({
kind: literal("identity"),
identity: identity.nullable()
}),
object({
kind: literal("identityRepair"),
identity,
repaired: boolean(),
rotated: boolean()
}),
object({
kind: literal("token"),
token: token.nullable()
}),
object({
kind: literal("tokens"),
tokens: array(token),
nextRole: string().nullable()
}),
object({
kind: literal("socket"),
socket: socket.nullable()
}),
object({
kind: literal("changed"),
changed: boolean()
}),
object({
kind: literal("cleared"),
count: number().int().nonnegative()
})
]);
const responseSchema = discriminatedUnion("ok", [object({
ok: literal(true),
result: resultSchema
}), object({
ok: literal(false),
error: object({
code: string(),
message: string()
})
})]);
/** AppProfile's control endpoint follows the OS home, independently of the client root. */
function controlDirectory(e) {
const t = e.OPENCLAW_PROFILE?.trim();
if (t && t.toLowerCase() !== "default" && (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(t) || [
"gateway",
"mac",
"node"
].includes(t))) throw new Error("Client credentials require a valid macOS app profile.");
return path.join(resolveRequiredOsHomeDir(e), `.openclaw${t && t.toLowerCase() !== "default" ? `-${t}` : ""}`);
}
async function requestClientCredentialsFromApp(e, t, n, r) {
if (process.platform !== "darwin") return;
const i = controlDirectory(e);
const a = path.join(i, "mac-control.token");
const o = await fsPromises.open(a, fsPromises.constants.O_RDONLY | fsPromises.constants.O_NOFOLLOW).catch(ignoreMissingPath);
if (!o) return;
let s;
try {
const e = await o.stat();
if (!e.isFile() || e.nlink !== 1 || e.size < 1 || e.size > 256 || (e.mode & 511) !== 384 || process.getuid && e.uid !== process.getuid()) throw new Error("App control credentials are unsafe; restart the matching OpenClaw app.");
s = (await o.readFile("utf8")).replace(/\n+$/, "");
if (!s) throw new Error("App control credentials are empty; restart the matching OpenClaw app.");
} finally {
await o.close();
}
n?.throwIfAborted();
r?.();
const c = JSON.stringify({
operation: "client.credentials",
credentialRoot: resolveDatabasePathKey(resolveStateDir(e)),
credentialOperation: t
});
const l = crypto.randomUUID();
const u = Date.now();
const d = JSON.stringify({
id: crypto.randomUUID(),
nonce: l,
ts: u,
requestJson: c,
hmac: crypto.createHmac("sha256", s).update(`${l}:${u}:${c}`).digest("hex")
});
if (Buffer.byteLength(d) >= 65536) throw new Error("Client credential request exceeds the app control limit.");
const f = await requestJsonlSocket({
socketPath: path.join(i, "mac-control.sock"),
requestLine: d,
timeoutMs: 15e3,
signal: n,
beforeSend: () => {
n?.throwIfAborted();
r?.();
},
maxResponseLineBytes: 65535,
accept: (e) => ({
kind: "response",
response: responseSchema.parse(e)
}),
onResponseLost: () => ({ kind: "lost" }),
onTimeout: () => ({ kind: "lost" })
});
n?.throwIfAborted();
if (!f) return;
if (f.kind === "lost") throw new Error("The client credential owner did not reply; retry through the matching OpenClaw app.");
const { response: p } = f;
if (!p.ok) {
const { code: e, message: t } = p.error;
if (e === "credential_root_unowned" || e === "invalid_request" && t === "Unknown control operation.") return;
throw new Error(`Client credential owner refused the operation: ${t}`);
}
return p.result;
}
//#endregion
export { requestClientCredentialsFromApp };