A personal agent with a browser, terminal, files, and work that keeps going built with CopilotKit and AG-UI.
TypeScript
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { Config } from "./config.ts";
import type { Store } from "./db.ts";
import { AppError } from "./errors.ts";
const digest = (value: string) => createHash("sha256").update(value).digest();
export class Auth {
constructor(
private readonly db: Store,
private readonly config: Config,
private readonly signingKey: string,
) {}
async session(accessKey?: string) {
if (
this.config.mode === "live" &&
(!accessKey ||
!this.config.accessKey ||
!timingSafeEqual(digest(accessKey), digest(this.config.accessKey)))
)
throw new AppError("Access key is incorrect", 401);
const token = randomBytes(32).toString("base64url");
await this.db.put("system", "sessions", {
id: digest(token).toString("hex"),
owner: "local-user",
expiresAt: Date.now() + 24 * 60 * 60 * 1000,
});
return { token, mode: this.config.mode };
}
async owner(authorization?: string) {
if (!authorization?.startsWith("Bearer ")) throw new AppError("Sign in to OpenMuse", 401);
const id = digest(authorization.slice(7)).toString("hex");
const session = await this.db.get<{ owner: string; expiresAt: number }>(
"system",
"sessions",
id,
);
if (!session || session.expiresAt < Date.now()) {
// Expired sessions can never be valid again, so drop the row instead of keeping it forever.
// Best-effort: a failed cleanup must not turn the rejection into a 5xx.
if (session) await this.db.remove("system", "sessions", id).catch(() => {});
throw new AppError("Session expired. Sign in again.", 401);
}
return session.owner;
}
async revoke(authorization?: string) {
if (authorization?.startsWith("Bearer "))
await this.db.remove("system", "sessions", digest(authorization.slice(7)).toString("hex"));
}
sign(owner: string, path: string) {
const expires = String(Date.now() + 15 * 60 * 1000);
const signature = createHmac("sha256", this.signingKey)
.update(`${owner}\n${path}\n${expires}`)
.digest("hex");
return `${this.config.publicUrl}${path}?owner=${encodeURIComponent(owner)}&expires=${expires}&signature=${signature}`;
}
verify(url: URL) {
const owner = url.searchParams.get("owner") ?? "";
const expires = url.searchParams.get("expires") ?? "";
const signature = url.searchParams.get("signature") ?? "";
if (
!owner ||
!/^\d+$/.test(expires) ||
Number(expires) < Date.now() ||
!/^\w{64}$/.test(signature)
)
throw new AppError("Document link expired; refresh the workspace", 401);
const expected = createHmac("sha256", this.signingKey)
.update(`${owner}\n${url.pathname}\n${expires}`)
.digest("hex");
if (!timingSafeEqual(Buffer.from(expected), Buffer.from(signature)))
throw new AppError("Invalid access link", 403);
return owner;
}
}
export async function createAuth(db: Store, config: Config) {
await mkdir(config.dataDir, { recursive: true, mode: 0o700 });
const key = await readOrCreate(join(config.dataDir, "session-signing-key"), () =>
randomBytes(32).toString("base64"),
);
return new Auth(db, config, key);
}
/** Reads a private file, or creates it without replacing another process's value. */
export async function readOrCreate(path: string, create: () => string) {
try {
return await readFile(path, "utf8");
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
}
let value = create();
const temporary = `${path}.${randomBytes(16).toString("hex")}.tmp`;
await writeFile(temporary, value, { mode: 0o600, flag: "wx" });
try {
// Publish only complete bytes, without replacing another process's value.
await link(temporary, path);
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
value = await readFile(path, "utf8");
} finally {
await unlink(temporary);
}
return value;
}