Add OpenShell Control auth and installer
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
const COOKIE_NAME = "openshell_control_session"
|
||||
const SESSION_TTL_SECONDS = 12 * 60 * 60
|
||||
|
||||
type SessionPayload = {
|
||||
sub: string
|
||||
iat: number
|
||||
exp: number
|
||||
}
|
||||
|
||||
function base64UrlEncode(value: string) {
|
||||
return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "")
|
||||
}
|
||||
|
||||
function base64UrlDecode(value: string) {
|
||||
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=")
|
||||
return atob(padded)
|
||||
}
|
||||
|
||||
function getSecret() {
|
||||
return process.env.OPENSHELL_CONTROL_AUTH_SECRET || process.env.OPENSHELL_CONTROL_PASSWORD || ""
|
||||
}
|
||||
|
||||
function isDisabled() {
|
||||
return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || "")
|
||||
}
|
||||
|
||||
async function hmac(payload: string) {
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
new TextEncoder().encode(getSecret()),
|
||||
{ name: "HMAC", hash: "SHA-256" },
|
||||
false,
|
||||
["sign"],
|
||||
)
|
||||
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload))
|
||||
const bytes = Array.from(new Uint8Array(signature), (byte) => String.fromCharCode(byte)).join("")
|
||||
return base64UrlEncode(bytes)
|
||||
}
|
||||
|
||||
function constantTimeEqual(left: string, right: string) {
|
||||
if (left.length !== right.length) return false
|
||||
let diff = 0
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
diff |= left.charCodeAt(index) ^ right.charCodeAt(index)
|
||||
}
|
||||
return diff === 0
|
||||
}
|
||||
|
||||
export function getAuthSettings() {
|
||||
return {
|
||||
cookieName: COOKIE_NAME,
|
||||
ttlSeconds: SESSION_TTL_SECONDS,
|
||||
disabled: isDisabled(),
|
||||
configured: Boolean(process.env.OPENSHELL_CONTROL_PASSWORD || isDisabled()),
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSessionCookieValue() {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const payload: SessionPayload = {
|
||||
sub: "operator",
|
||||
iat: now,
|
||||
exp: now + SESSION_TTL_SECONDS,
|
||||
}
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(payload))
|
||||
return `${encodedPayload}.${await hmac(encodedPayload)}`
|
||||
}
|
||||
|
||||
export async function verifySessionCookieValue(value: string | undefined) {
|
||||
const settings = getAuthSettings()
|
||||
if (settings.disabled) return true
|
||||
if (!settings.configured || !value) return false
|
||||
|
||||
const [payload, signature] = value.split(".")
|
||||
if (!payload || !signature) return false
|
||||
const expected = await hmac(payload)
|
||||
if (!constantTimeEqual(signature, expected)) return false
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(base64UrlDecode(payload)) as Partial<SessionPayload>
|
||||
return typeof parsed.exp === "number" && parsed.exp > Math.floor(Date.now() / 1000)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string) {
|
||||
const expected = process.env.OPENSHELL_CONTROL_PASSWORD || ""
|
||||
if (!expected) return false
|
||||
return constantTimeEqual(password, expected)
|
||||
}
|
||||
|
||||
export async function verifyRecoveryToken(token: string) {
|
||||
const expected = process.env.OPENSHELL_CONTROL_RECOVERY_TOKEN || ""
|
||||
if (!expected) return false
|
||||
return constantTimeEqual(token, expected)
|
||||
}
|
||||
|
||||
export const sessionCookieOptions = {
|
||||
httpOnly: true,
|
||||
sameSite: "lax" as const,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
path: "/",
|
||||
maxAge: SESSION_TTL_SECONDS,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { existsSync } from "node:fs"
|
||||
import { readFile, writeFile } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
const ENV_PATH = path.join(process.cwd(), ".env.local")
|
||||
|
||||
function quoteEnvValue(value: string) {
|
||||
if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) return value
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
async function readEnvFile() {
|
||||
if (!existsSync(ENV_PATH)) return ""
|
||||
return readFile(ENV_PATH, "utf8")
|
||||
}
|
||||
|
||||
function upsertEnv(content: string, key: string, value: string) {
|
||||
const line = `${key}=${quoteEnvValue(value)}`
|
||||
const matcher = new RegExp(`^${key}=.*$`, "m")
|
||||
if (matcher.test(content)) return content.replace(matcher, line)
|
||||
return `${content.trimEnd()}${content.trim() ? "\n" : ""}${line}\n`
|
||||
}
|
||||
|
||||
export function generateToken(bytes = 24) {
|
||||
return randomBytes(bytes).toString("base64url")
|
||||
}
|
||||
|
||||
export async function updateLocalAuthCredentials(password: string) {
|
||||
const secret = generateToken(32)
|
||||
const recoveryToken = generateToken(24)
|
||||
let content = await readEnvFile()
|
||||
content = upsertEnv(content, "OPENSHELL_CONTROL_PASSWORD", password)
|
||||
content = upsertEnv(content, "OPENSHELL_CONTROL_AUTH_SECRET", secret)
|
||||
content = upsertEnv(content, "OPENSHELL_CONTROL_RECOVERY_TOKEN", recoveryToken)
|
||||
await writeFile(ENV_PATH, content, "utf8")
|
||||
|
||||
process.env.OPENSHELL_CONTROL_PASSWORD = password
|
||||
process.env.OPENSHELL_CONTROL_AUTH_SECRET = secret
|
||||
process.env.OPENSHELL_CONTROL_RECOVERY_TOKEN = recoveryToken
|
||||
|
||||
return { recoveryToken }
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import path from "node:path"
|
||||
import { resolveSandboxRef } from "./openshellHost"
|
||||
|
||||
const HOME = process.env.HOME || ""
|
||||
const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell`
|
||||
const HOST_PATH = [
|
||||
`${HOME}/.local/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.2/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.1/bin`,
|
||||
"/usr/local/bin",
|
||||
"/usr/bin",
|
||||
"/bin",
|
||||
process.env.PATH || "",
|
||||
].filter(Boolean).join(":")
|
||||
|
||||
const MAX_FILE_BYTES = Number.parseInt(process.env.SANDBOX_FILE_TRANSFER_MAX_BYTES || String(128 * 1024 * 1024), 10)
|
||||
const ALLOWED_ROOTS = ["/sandbox", "/tmp"]
|
||||
|
||||
function shellQuote(value: string) {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`
|
||||
}
|
||||
|
||||
function sanitizeFileName(value: string) {
|
||||
const base = path.posix.basename(value.trim() || "upload.bin")
|
||||
return base.replace(/[^\w.@:+-]/g, "_") || "upload.bin"
|
||||
}
|
||||
|
||||
export function normalizeSandboxPath(input: string, fallbackFileName?: string) {
|
||||
const raw = input.trim()
|
||||
if (!raw) throw new Error("sandbox path is required")
|
||||
if (raw.includes("\0")) throw new Error("sandbox path contains unsupported characters")
|
||||
|
||||
const absolute = raw.startsWith("/") ? raw : path.posix.join("/sandbox", raw)
|
||||
const withFileName = absolute.endsWith("/") && fallbackFileName
|
||||
? path.posix.join(absolute, sanitizeFileName(fallbackFileName))
|
||||
: absolute
|
||||
const normalized = path.posix.normalize(withFileName)
|
||||
const allowed = ALLOWED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))
|
||||
if (!allowed) throw new Error("sandbox path must be under /sandbox or /tmp")
|
||||
return normalized
|
||||
}
|
||||
|
||||
function runSandboxExec(sandboxName: string, script: string, input?: Buffer, timeoutMs = 60000) {
|
||||
return new Promise<{ stdout: Buffer; stderr: string; code: number | null }>((resolve, reject) => {
|
||||
const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
})
|
||||
const stdout: Buffer[] = []
|
||||
let stderr = ""
|
||||
const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs)
|
||||
|
||||
child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)))
|
||||
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
})
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer)
|
||||
resolve({ stdout: Buffer.concat(stdout), stderr: stderr.trim(), code })
|
||||
})
|
||||
|
||||
if (input) child.stdin.end(input)
|
||||
else child.stdin.end()
|
||||
})
|
||||
}
|
||||
|
||||
export async function resolveSandboxName(sandboxId: string) {
|
||||
const resolved = await resolveSandboxRef(sandboxId)
|
||||
return resolved.name
|
||||
}
|
||||
|
||||
export async function uploadSandboxFile(sandboxId: string, destinationPath: string, fileName: string, payload: Buffer) {
|
||||
if (payload.byteLength > MAX_FILE_BYTES) {
|
||||
throw new Error(`file is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
|
||||
}
|
||||
|
||||
const sandboxName = await resolveSandboxName(sandboxId)
|
||||
const targetPath = normalizeSandboxPath(destinationPath, fileName)
|
||||
const targetDir = path.posix.dirname(targetPath)
|
||||
const script = [
|
||||
`mkdir -p ${shellQuote(targetDir)}`,
|
||||
`cat > ${shellQuote(targetPath)}`,
|
||||
`chmod 0644 ${shellQuote(targetPath)}`,
|
||||
].join(" && ")
|
||||
const result = await runSandboxExec(sandboxName, script, payload, 120000)
|
||||
if (result.code !== 0) throw new Error(result.stderr || "failed to upload file to sandbox")
|
||||
|
||||
return {
|
||||
sandboxName,
|
||||
path: targetPath,
|
||||
bytes: payload.byteLength,
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadSandboxFile(sandboxId: string, sourcePath: string) {
|
||||
const sandboxName = await resolveSandboxName(sandboxId)
|
||||
const targetPath = normalizeSandboxPath(sourcePath)
|
||||
const statScript = `test -f ${shellQuote(targetPath)} && wc -c < ${shellQuote(targetPath)}`
|
||||
const stat = await runSandboxExec(sandboxName, statScript, undefined, 30000)
|
||||
if (stat.code !== 0) throw new Error(stat.stderr || "sandbox file does not exist or is not a regular file")
|
||||
const size = Number.parseInt(stat.stdout.toString("utf8").trim(), 10)
|
||||
if (Number.isFinite(size) && size > MAX_FILE_BYTES) {
|
||||
throw new Error(`file is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
|
||||
}
|
||||
|
||||
const result = await runSandboxExec(sandboxName, `cat ${shellQuote(targetPath)}`, undefined, 120000)
|
||||
if (result.code !== 0) throw new Error(result.stderr || "failed to download file from sandbox")
|
||||
|
||||
return {
|
||||
sandboxName,
|
||||
path: targetPath,
|
||||
fileName: path.posix.basename(targetPath) || "download.bin",
|
||||
bytes: result.stdout,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { resolveSandboxRef } from "./openshellHost"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const HOME = process.env.HOME || ""
|
||||
const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell`
|
||||
const HOST_PATH = [
|
||||
`${HOME}/.local/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.2/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.1/bin`,
|
||||
"/usr/local/bin",
|
||||
"/usr/bin",
|
||||
"/bin",
|
||||
process.env.PATH || "",
|
||||
].filter(Boolean).join(":")
|
||||
|
||||
export type SandboxNetworkRule = {
|
||||
chunkId: string
|
||||
status: string
|
||||
rule: string
|
||||
binary: string
|
||||
confidence: string
|
||||
rationale: string
|
||||
endpoints: string[]
|
||||
binaries: string[]
|
||||
}
|
||||
|
||||
function runOpenShell(args: string[], timeout = 60000) {
|
||||
return execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
TERM: "dumb",
|
||||
},
|
||||
timeout,
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
})
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
||||
}
|
||||
|
||||
function parseList(value: string) {
|
||||
return value
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function parseNetworkRules(output: string): SandboxNetworkRule[] {
|
||||
const clean = stripAnsi(output)
|
||||
const chunks = clean.split(/\n\s*Chunk:\s+/).slice(1)
|
||||
|
||||
return chunks
|
||||
.map((chunk) => {
|
||||
const lines = chunk.split(/\r?\n/)
|
||||
const chunkId = lines.shift()?.trim() || ""
|
||||
const fields = new Map<string, string>()
|
||||
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*([^:]+):\s*(.*)$/)
|
||||
if (!match) continue
|
||||
fields.set(match[1].trim().toLowerCase(), match[2].trim())
|
||||
}
|
||||
|
||||
return {
|
||||
chunkId,
|
||||
status: fields.get("status") || "unknown",
|
||||
rule: fields.get("rule") || "",
|
||||
binary: fields.get("binary") || "",
|
||||
confidence: fields.get("confidence") || "",
|
||||
rationale: fields.get("rationale") || "",
|
||||
endpoints: parseList(fields.get("endpoints") || ""),
|
||||
binaries: parseList(fields.get("binaries") || ""),
|
||||
}
|
||||
})
|
||||
.filter((rule) => rule.chunkId)
|
||||
}
|
||||
|
||||
async function listRulesForStatus(sandboxName: string, status: "pending" | "approved" | "rejected") {
|
||||
const { stdout } = await runOpenShell(["rule", "get", "--status", status, sandboxName], 30000)
|
||||
return parseNetworkRules(String(stdout))
|
||||
}
|
||||
|
||||
export async function getSandboxPermissionFeed(sandboxId: string) {
|
||||
const resolved = await resolveSandboxRef(sandboxId)
|
||||
const [pending, approved, rejected] = await Promise.all([
|
||||
listRulesForStatus(resolved.name, "pending"),
|
||||
listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[]),
|
||||
listRulesForStatus(resolved.name, "rejected").catch(() => [] as SandboxNetworkRule[]),
|
||||
])
|
||||
|
||||
return {
|
||||
sandboxId,
|
||||
sandboxName: resolved.name,
|
||||
pending,
|
||||
recent: [...pending, ...approved, ...rejected].slice(0, 8),
|
||||
pendingCount: pending.length,
|
||||
approvedCount: approved.length,
|
||||
rejectedCount: rejected.length,
|
||||
latest: pending[0] ? { status: "Pending", chunkId: pending[0].chunkId } : { status: "Ready" },
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSandboxNetworkRule(sandboxId: string, action: string, chunkId: string, reason = "") {
|
||||
if (!/^[a-f0-9-]{8,}$/i.test(chunkId)) throw new Error("invalid network rule chunk id")
|
||||
const resolved = await resolveSandboxRef(sandboxId)
|
||||
const command = action === "reject" ? "reject" : action === "approve" ? "approve" : ""
|
||||
if (!command) throw new Error("unsupported permission action")
|
||||
|
||||
const args = ["rule", command, "--chunk-id", chunkId]
|
||||
if (command === "reject" && reason) args.push("--reason", reason)
|
||||
args.push(resolved.name)
|
||||
|
||||
const { stdout, stderr } = await runOpenShell(args, 60000)
|
||||
const feed = await getSandboxPermissionFeed(resolved.name).catch(() => null)
|
||||
|
||||
return {
|
||||
sandboxId,
|
||||
sandboxName: resolved.name,
|
||||
action: command,
|
||||
chunkId,
|
||||
stdout: String(stdout).trim(),
|
||||
stderr: String(stderr).trim(),
|
||||
feed,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user