Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ const hmacKey = randomBytes(32);
export const VIEWER_NONCE_PLACEHOLDER = "__AGENTMEMORY_VIEWER_NONCE__";

export function timingSafeCompare(a: string, b: string): boolean {
const hmacA = createHmac("sha256", hmacKey).update(a).digest();
const hmacB = createHmac("sha256", hmacKey).update(b).digest();
return timingSafeEqual(hmacA, hmacB);
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

export function createViewerNonce(): string {
Expand Down
13 changes: 10 additions & 3 deletions src/functions/claude-bridge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ISdk } from "iii-sdk";
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { readFileSync, writeFileSync, mkdirSync, existsSync, constants, openSync, closeSync } from "node:fs";
import { dirname } from "node:path";
import type { Memory, ClaudeBridgeConfig } from "../types.js";
import { KV } from "../state/schema.js";
Expand Down Expand Up @@ -139,8 +139,15 @@ export function registerClaudeBridgeFunction(
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(config.memoryFilePath, md, "utf-8");

const fd = openSync(
config.memoryFilePath,
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
);
try {
writeFileSync(fd, md, "utf-8");
} finally {
closeSync(fd);
}
await recordAudit(kv, "export", "mem::claude-bridge-sync", [], {
path: config.memoryFilePath,
memoryCount: latestMemories.length,
Expand Down
17 changes: 11 additions & 6 deletions src/functions/snapshot.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ISdk } from "iii-sdk";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { existsSync, mkdirSync, writeFileSync, readFileSync, constants, openSync, closeSync } from "node:fs";
import { join } from "node:path";
import type {
SnapshotMeta,
Expand Down Expand Up @@ -75,12 +75,17 @@ export function registerSnapshotFunction(
accessLogs,
};

writeFileSync(
join(snapshotDir, "state.json"),
JSON.stringify(state, null, 2),
"utf-8",
const stateContent = JSON.stringify(state, null, 2);
const statePath = join(snapshotDir, "state.json");
const fd = openSync(
statePath,
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
);

try {
writeFileSync(fd, stateContent, "utf-8");
} finally {
closeSync(fd);
}
await gitExec(snapshotDir, ["add", "."]);

const message = data?.message || `Snapshot ${ts}`;
Expand Down
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,11 @@ async function main() {
const imageEmbeddingProvider = createImageEmbeddingProvider();

console.log(`[agentmemory] Starting worker v${VERSION}...`);
console.log(`[agentmemory] Engine: ${config.engineUrl}`);
const engineDisplayUrl = config.engineUrl.includes("@")
? config.engineUrl.replace(/\/\/[^@]+@/, "//***@")
: config.engineUrl;
console.log(`[agentmemory] Engine: ${engineDisplayUrl}`);

console.log(
`[agentmemory] Provider: ${config.provider.provider} (${config.provider.model})`,
);
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ export function registerMcpEndpoints(
if (!sec) return null;
const auth =
req.headers?.["authorization"] || req.headers?.["Authorization"];
if (typeof auth !== "string" || !timingSafeCompare(auth, `Bearer ${sec}`)) {
const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null;
if (!match || !timingSafeCompare(match[1], sec)) {
return { status_code: 401, body: { error: "unauthorized" } };
}
return null;
Expand Down
12 changes: 4 additions & 8 deletions src/triggers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,8 @@ function checkAuth(
): Response | null {
if (!secret) return null;
const auth = req.headers?.["authorization"] || req.headers?.["Authorization"];
if (
typeof auth !== "string" ||
!timingSafeCompare(auth, `Bearer ${secret}`)
) {
const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null;
if (!match || !timingSafeCompare(match[1], secret)) {
return { status_code: 401, body: { error: "unauthorized" } };
}
return null;
Expand Down Expand Up @@ -126,10 +124,8 @@ export function registerApiTriggers(
if (!secret) return { action: "continue" };
const headers = input?.request?.headers || {};
const auth = headers["authorization"] || headers["Authorization"];
if (
typeof auth !== "string" ||
!timingSafeCompare(auth, `Bearer ${secret}`)
) {
const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null;
if (!match || !timingSafeCompare(match[1], secret)) {
return {
action: "respond",
response: { status_code: 401, body: { error: "unauthorized" } },
Expand Down
22 changes: 21 additions & 1 deletion src/viewer/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type ServerResponse,
} from "node:http";
import { renderViewerDocument } from "./document.js";
import { timingSafeCompare } from "../auth.js";

const ALLOWED_ORIGINS = (
process.env.VIEWER_ALLOWED_ORIGINS ||
Expand Down Expand Up @@ -58,6 +59,15 @@ function readBody(req: IncomingMessage): Promise<string> {
});
}

/**
* Starts the memory viewer server.
* @param port The port to listen on.
* @param _kv The KV store instance.
* @param _sdk The SDK instance.
* @param secret Optional authorization secret.
* @param restPort Optional port of the REST API to proxy to.
* @returns The HTTP server instance.
*/
export function startViewerServer(
port: number,
_kv: unknown,
Expand Down Expand Up @@ -104,10 +114,20 @@ export function startViewerServer(
return;
}

if (secret) {
const auth = req.headers["authorization"];
const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null;
if (!match || !timingSafeCompare(match[1], secret)) {
json(res, 401, { error: "unauthorized" }, req);
return;
}
}

try {
await proxyToRestApi(resolvedRestPort, pathname, qs, method, req, res, secret);
} catch (err) {
console.error(`[viewer] proxy error on ${method} ${pathname}:`, err);
const safePath = pathname.replace(/[\r\n]/g, " ");
console.error(`[viewer] proxy error on ${method} ${safePath}:`, err);
json(res, 502, { error: "upstream error" }, req);
}
});
Expand Down
15 changes: 13 additions & 2 deletions test/claude-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ vi.mock("node:fs", () => ({
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
constants: {
O_WRONLY: 1,
O_CREAT: 2,
O_TRUNC: 4,
O_NOFOLLOW: 8,
},
openSync: vi.fn().mockReturnValue(123),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
closeSync: vi.fn(),
}));

vi.mock("node:path", async () => ({
Expand All @@ -17,7 +25,7 @@ vi.mock("node:path", async () => ({
}));

import { registerClaudeBridgeFunction } from "../src/functions/claude-bridge.js";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync, writeFileSync, openSync, closeSync } from "node:fs";
import type { ClaudeBridgeConfig, Memory } from "../src/types.js";

function mockKV() {
Expand Down Expand Up @@ -148,8 +156,11 @@ describe("Claude Bridge Functions", () => {

expect(result.success).toBe(true);
expect(result.path).toBe("/tmp/.claude/MEMORY.md");
expect(writeFileSync).toHaveBeenCalled();
expect(openSync).toHaveBeenCalled();
expect(writeFileSync).toHaveBeenCalledWith(123, expect.any(String), "utf-8");
expect(closeSync).toHaveBeenCalledWith(123);
const writtenContent = vi.mocked(writeFileSync).mock.calls[0][1] as string;

expect(writtenContent).toContain("Auth pattern");
});

Expand Down
15 changes: 13 additions & 2 deletions test/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@ vi.mock("node:fs", () => ({
readFileSync: vi
.fn()
.mockReturnValue('{"version":"0.4.0","sessions":[],"memories":[]}'),
constants: {
O_WRONLY: 1,
O_CREAT: 2,
O_TRUNC: 4,
O_NOFOLLOW: 8,
},
openSync: vi.fn().mockReturnValue(123),
closeSync: vi.fn(),
}));

import { registerSnapshotFunction } from "../src/functions/snapshot.js";
import { openSync, closeSync, writeFileSync } from "node:fs";
import type { Session, Memory, SnapshotMeta } from "../src/types.js";

function mockKV() {
Expand Down Expand Up @@ -123,8 +132,10 @@ describe("Snapshot Functions", () => {
expect(result.snapshot.message).toBe("Test snapshot");
expect(result.snapshot.stats.sessions).toBe(1);
expect(result.snapshot.stats.memories).toBe(1);
});

expect(openSync).toHaveBeenCalled();
expect(writeFileSync).toHaveBeenCalledWith(123, expect.any(String), "utf-8");
expect(closeSync).toHaveBeenCalledWith(123);
});
it("snapshot-list returns snapshots from git log", async () => {
const result = (await sdk.trigger("mem::snapshot-list", {})) as {
snapshots: Array<{
Expand Down