Add HMAC auth, user permissions, snake_case rename

Each request is signed with HMAC-SHA256 over timestamp+body using a
per-user secret loaded from a --secrets file (never env vars or git).
Users have a canApprove list controlling who may approve queued actions.
Queue entries track submitted_by for permission checks on approve/deny.

Also renames all identifiers to snake_case throughout the codebase.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-07 20:18:41 +00:00
parent f02e2a746d
commit 67c1c3f9a4
11 changed files with 226 additions and 55 deletions

View File

@@ -1,7 +1,7 @@
// Action registry — defines all available actions, their parameters, and policies.
// policy: "auto-accept" | "auto-deny" | "queue"
import { resolvePath, exec } from "./helpers.mjs";
import { resolve_path, exec } from "./helpers.mjs";
export const actions = {
"list-actions": {
@@ -23,7 +23,7 @@ export const actions = {
params: [{ name: "filename", required: true, type: "path" }],
policy: "auto-accept",
handler: async ({ filename }) => {
const resolved = resolvePath(filename);
const resolved = resolve_path(filename);
await exec("xdg-open", [resolved]);
return { opened: resolved };
},
@@ -34,7 +34,7 @@ export const actions = {
params: [{ name: "path", required: true, type: "path" }],
policy: "auto-accept",
handler: async ({ path }) => {
const resolved = resolvePath(path);
const resolved = resolve_path(path);
await exec("xdg-open", [resolved]);
return { opened: resolved };
},
@@ -55,7 +55,7 @@ export const actions = {
params: [{ name: "path", required: false, type: "path" }],
policy: "queue",
handler: async ({ path }) => {
const resolved = path ? resolvePath(path) : process.env.HOME;
const resolved = path ? resolve_path(path) : process.env.HOME;
await exec("xdg-open", [resolved]);
return { opened: resolved };
},

46
server/auth.mjs Normal file
View File

@@ -0,0 +1,46 @@
import { createHmac, timingSafeEqual } from "crypto";
export function create_auth_middleware(users) {
return function hmac_auth(req, res, next) {
const username = req.headers["x-conduit-user"];
const timestamp = req.headers["x-conduit-timestamp"];
const signature = req.headers["x-conduit-signature"];
if (!username || !timestamp || !signature) {
return res.status(401).json({ error: "Missing auth headers" });
}
const ts = parseInt(timestamp, 10);
if (!Number.isFinite(ts) || Date.now() - ts > 30_000) {
return res.status(401).json({ error: "Request expired" });
}
const user = users[username];
if (!user) {
return res.status(401).json({ error: "Unknown user" });
}
const raw_body = req.raw_body ?? "";
const expected = createHmac("sha256", user.secret)
.update(timestamp + "." + raw_body)
.digest("hex");
const sig_buf = Buffer.from(signature, "hex");
const expected_buf = Buffer.from(expected, "hex");
if (sig_buf.length !== expected_buf.length || !timingSafeEqual(sig_buf, expected_buf)) {
return res.status(401).json({ error: "Invalid signature" });
}
req.conduit_user = username;
next();
};
}
export function check_can_approve(users, requester_name, submitter_name) {
const requester = users[requester_name];
if (!requester) {
return false;
}
return requester.canApprove.includes(submitter_name);
}

View File

@@ -4,10 +4,10 @@ import path from "path";
const WORKSPACE_ROOT = process.env.CONDUIT_ROOT || "/workspace";
// Resolve a path param relative to WORKSPACE_ROOT, preventing traversal.
export function resolvePath(userPath) {
const resolved = path.resolve(WORKSPACE_ROOT, userPath.replace(/^\//, ""));
export function resolve_path(user_path) {
const resolved = path.resolve(WORKSPACE_ROOT, user_path.replace(/^\//, ""));
if (!resolved.startsWith(WORKSPACE_ROOT)) {
throw new Error(`Path escapes workspace root: ${userPath}`);
throw new Error(`Path escapes workspace root: ${user_path}`);
}
return resolved;
}

View File

@@ -1,16 +1,37 @@
import express from "express";
import { actions } from "./actions.mjs";
import { enqueue, getEntry, listPending, resolve } from "./queue.mjs";
import { enqueue, get_entry, list_pending, resolve } from "./queue.mjs";
import { load_secrets } from "./secrets.mjs";
import { create_auth_middleware, check_can_approve } from "./auth.mjs";
const PORT = process.env.CONDUIT_PORT || 3015;
const app = express();
app.use(express.json());
function get_arg(argv, flag) {
const i = argv.indexOf(flag);
return i !== -1 ? argv[i + 1] : null;
}
// Validate that all required params are present.
function validateParams(actionDef, params) {
const secrets_path = get_arg(process.argv, "--secrets");
let secrets;
try {
secrets = load_secrets(secrets_path);
} catch (err) {
console.error(`Fatal: ${err.message}`);
process.exit(1);
}
const { users } = secrets;
const app = express();
app.use(express.json({
verify: (req, _res, buf) => {
req.raw_body = buf.toString("utf8");
},
}));
app.use(create_auth_middleware(users));
function validate_params(action_def, params) {
const errors = [];
for (const p of actionDef.params) {
for (const p of action_def.params) {
if (p.required && (params[p.name] === undefined || params[p.name] === null)) {
errors.push(`Missing required param: ${p.name}`);
}
@@ -31,7 +52,7 @@ app.post("/action", async (req, res) => {
return res.status(404).json({ error: `Unknown action: ${action}` });
}
const errors = validateParams(def, params);
const errors = validate_params(def, params);
if (errors.length) {
return res.status(400).json({ error: "Invalid params", details: errors });
}
@@ -50,25 +71,28 @@ app.post("/action", async (req, res) => {
}
if (def.policy === "queue") {
const id = enqueue(action, params);
const id = enqueue(action, params, req.conduit_user);
return res.status(202).json({ status: "queued", id });
}
});
// GET /queue — list pending items
app.get("/queue", (req, res) => {
res.json(listPending());
res.json(list_pending());
});
// POST /queue/:id/approve — user approves a queued action
app.post("/queue/:id/approve", async (req, res) => {
const entry = getEntry(req.params.id);
const entry = get_entry(req.params.id);
if (!entry) {
return res.status(404).json({ error: "Not found" });
}
if (entry.status !== "pending") {
return res.status(409).json({ error: "Already resolved" });
}
if (!check_can_approve(users, req.conduit_user, entry.submitted_by)) {
return res.status(403).json({ error: "Not authorized to approve this entry" });
}
resolve(req.params.id, "approved");
@@ -83,13 +107,16 @@ app.post("/queue/:id/approve", async (req, res) => {
// POST /queue/:id/deny — user denies a queued action
app.post("/queue/:id/deny", (req, res) => {
const entry = getEntry(req.params.id);
const entry = get_entry(req.params.id);
if (!entry) {
return res.status(404).json({ error: "Not found" });
}
if (entry.status !== "pending") {
return res.status(409).json({ error: "Already resolved" });
}
if (!check_can_approve(users, req.conduit_user, entry.submitted_by)) {
return res.status(403).json({ error: "Not authorized to deny this entry" });
}
resolve(req.params.id, "denied");
res.json({ status: "denied" });

View File

@@ -1,32 +1,32 @@
// Pending queue — holds actions awaiting user approval.
import { randomUUID } from "crypto";
const pending = new Map();
export function enqueue(action, params) {
export function enqueue(action, params, submitted_by) {
const id = randomUUID();
const entry = {
id,
action,
params,
submitted_by,
status: "pending",
createdAt: new Date().toISOString(),
created_at: new Date().toISOString(),
};
pending.set(id, entry);
console.log(`\n[QUEUE] New request #${id.slice(0, 8)}`);
console.log(` Action: ${action}`);
console.log(` Params: ${JSON.stringify(params)}`);
console.log(` Action: ${action}`);
console.log(` Params: ${JSON.stringify(params)}`);
console.log(` Submitted by: ${submitted_by}`);
console.log(` Approve: POST /queue/${id}/approve`);
console.log(` Deny: POST /queue/${id}/deny\n`);
return id;
}
export function getEntry(id) {
export function get_entry(id) {
return pending.get(id) ?? null;
}
export function listPending() {
export function list_pending() {
return [...pending.values()].filter((e) => e.status === "pending");
}
@@ -36,6 +36,6 @@ export function resolve(id, decision) {
return null;
}
entry.status = decision; // "approved" | "denied"
entry.resolvedAt = new Date().toISOString();
entry.resolved_at = new Date().toISOString();
return entry;
}

23
server/secrets.mjs Normal file
View File

@@ -0,0 +1,23 @@
import { readFileSync } from "fs";
export function load_secrets(file_path) {
if (!file_path) {
throw new Error("--secrets <path> is required");
}
let raw;
try {
raw = readFileSync(file_path, "utf8");
} catch (err) {
throw new Error(`Cannot read secrets file at ${file_path}: ${err.message}`);
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (err) {
throw new Error(`Secrets file is not valid JSON: ${err.message}`);
}
if (!parsed.users || typeof parsed.users !== "object") {
throw new Error("Secrets file must have a top-level 'users' object");
}
return parsed;
}