Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(tenancy): owner-only enrollment CLI for tenant bindings

Abdurrahman Fakhrul9cd1f07548a9
diff --git a/bin/mso b/bin/mso
index 99115d3e..9e711813 100755
--- a/bin/mso
+++ b/bin/mso
@@ -109,6 +109,7 @@
#
# reset [--scope config|all] Preview local factory reset; explicit token required to apply
# uninstall [--purge] [--remove-code] Preview owned installation removal
+# tenant * Owner-only local enrollment: status | list | init | enroll | set-enabled
#
# Escape hatches
# crud * Generic resource CRUD, incl. editor documents
@@ -176,6 +177,13 @@ case "${1-}" in
[ -z "$BASE_OVERRIDE$ENV_OVERRIDE${MSO_BASE:-}${OS_BASE:-}${MSO_ENV:-}${OS_ENV:-}" ] \
|| die "maintenance is local-only; omit --base/--env and run over SSH on the intended host"
exec node "$ROOT/scripts/mso-maintenance.mjs" "$@" ;;
+ tenant)
+ [ -z "$BASE_OVERRIDE$ENV_OVERRIDE${MSO_BASE:-}${OS_BASE:-}${MSO_ENV:-}${OS_ENV:-}" ] \
+ || die "tenant enrollment is local-only; omit --base/--env and run over SSH on the intended host"
+ shift
+ set -a; . "$ROOT/.env.local" 2>/dev/null || true; set +a
+ export PATH="$HOME/.bun/bin:$PATH"
+ exec bun "$ROOT/scripts/mso-tenant.ts" "$@" ;;
esac
B="${BASE_OVERRIDE:-${MSO_BASE:-${OS_BASE:-http://127.0.0.1:4005}}}"
diff --git a/docs/CLI.md b/docs/CLI.md
index c5567c15..6947bd56 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -149,6 +149,7 @@ Commands:
reset [--scope config|all] Preview local factory reset; explicit token required to apply
uninstall [--purge] [--remove-code] Preview owned installation removal
+ tenant * Owner-only local enrollment: status | list | init | enroll | set-enabled
Escape hatches
crud * Generic resource CRUD, incl. editor documents
diff --git a/scripts/mso-tenant.test.ts b/scripts/mso-tenant.test.ts
new file mode 100644
index 00000000..41423774
--- /dev/null
+++ b/scripts/mso-tenant.test.ts
@@ -0,0 +1,106 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { spawnSync } from "node:child_process";
+import { afterEach, describe, expect, it } from "vitest";
+
+const fixtures: string[] = [];
+afterEach(() => { for (const dir of fixtures.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-tenant-cli-"));
+ fs.chmodSync(root, 0o700);
+ fixtures.push(root);
+ const script = path.join(process.cwd(), "scripts/mso-tenant.ts");
+ const env = { ...process.env, OS_TENANCY_STORAGE_ROOT: root, HOME: root };
+ const run = (...args: string[]) => spawnSync(process.execPath.includes("bun") ? "bun" : "bun", [script, ...args], { encoding: "utf8", env, cwd: process.cwd() });
+ return { root, env, run };
+}
+function token(stdout: string) {
+ const match = /TENANT:[a-f0-9]+/.exec(stdout);
+ if (!match) throw new Error("no preview token in output: " + stdout);
+ return match[0];
+}
+
+describe("tenant enrollment CLI boundary", () => {
+ it("refuses every action without a configured store root", () => {
+ const run = spawnSync("bun", [path.join(process.cwd(), "scripts/mso-tenant.ts"), "status"], { encoding: "utf8", env: { ...process.env, OS_TENANCY_STORAGE_ROOT: "" } });
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain("OS_TENANCY_STORAGE_ROOT");
+ });
+
+ it("init preview creates no state and refuses to overwrite an existing store", () => {
+ const f = fixture();
+ const preview = f.run("init");
+ expect(preview.stdout).toContain("PREVIEW ONLY");
+ expect(fs.existsSync(path.join(f.root, "state.json"))).toBe(false);
+ const applied = f.run("init", "--apply", "--confirm", token(preview.stdout));
+ expect(applied.status).toBe(0);
+ expect(fs.existsSync(path.join(f.root, "state.json"))).toBe(true);
+ const again = f.run("init", "--apply", "--confirm", "TENANT:whatever");
+ expect(again.status).not.toBe(0);
+ expect(again.stderr).toContain("already exists");
+ });
+
+ it("requires the exact current preview token before any enroll mutation", () => {
+ const f = fixture(); f.run("init", "--apply", "--confirm", token(f.run("init").stdout));
+ const enroll = ["enroll", "--issuer", "fixture", "--subject", "alice", "--tenant", "tenant-a", "--principal", "person-a"];
+ expect(f.run(...enroll).stdout).toContain("PREVIEW ONLY");
+ expect(f.run("list", "--json").stdout.trim()).toBe("[]");
+ expect(f.run(...enroll, "--apply", "--confirm", "TENANT:deadbeef").status).not.toBe(0);
+ expect(f.run("list", "--json").stdout.trim()).toBe("[]");
+ });
+
+ it("enrolls, guards remap, disables and lists a real binding with an audit trail", () => {
+ const f = fixture(); f.run("init", "--apply", "--confirm", token(f.run("init").stdout));
+ const enroll = (extra: string[] = []) => {
+ const args = ["enroll", "--issuer", "fixture", "--subject", "alice", "--tenant", "tenant-a", "--principal", "person-a", ...extra];
+ return f.run(...args, "--apply", "--confirm", token(f.run(...args).stdout));
+ };
+ expect(enroll().status).toBe(0);
+ const rows = JSON.parse(f.run("list", "--json").stdout);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ tenantId: "tenant-a", principalId: "person-a", enabled: true, tenantEnabled: true, mappingRevision: 1 });
+
+ const remap = ["enroll", "--issuer", "fixture", "--subject", "alice", "--tenant", "tenant-b", "--principal", "person-b"];
+ expect(f.run(...remap).status).not.toBe(0);
+ expect(f.run(...remap, "--remap").stdout).toContain("PREVIEW ONLY");
+ expect(f.run(...remap, "--remap", "--apply", "--confirm", token(f.run(...remap, "--remap").stdout)).status).toBe(0);
+
+ const disable = ["set-enabled", "--issuer", "fixture", "--subject", "alice", "--enabled", "false"];
+ expect(f.run(...disable, "--apply", "--confirm", token(f.run(...disable).stdout)).status).toBe(0);
+ expect(JSON.parse(f.run("list", "--json").stdout)[0]).toMatchObject({ enabled: false, mappingRevision: 3 });
+
+ const status = JSON.parse(f.run("status", "--json").stdout);
+ expect(status).toMatchObject({ initialized: true, revision: 3, auditEntries: 3 });
+ });
+
+ it("surfaces the adapter guard when a principal is already bound elsewhere", () => {
+ const f = fixture(); f.run("init", "--apply", "--confirm", token(f.run("init").stdout));
+ const enroll = (subject: string) => {
+ const args = ["enroll", "--issuer", "fixture", "--subject", subject, "--tenant", "tenant-a", "--principal", "person-a"];
+ return f.run(...args, "--apply", "--confirm", token(f.run(...args).stdout));
+ };
+ expect(enroll("alice").status).toBe(0);
+ const dup = enroll("bob");
+ expect(dup.status).not.toBe(0);
+ expect(dup.stderr).toContain("already bound");
+ });
+
+ it.each([["--issuer", "fixture"], ["enroll", "--subject", "alice", "--tenant", "t", "--principal", "p"]])("refuses an incomplete identifier set %j", (...args) => {
+ const f = fixture(); f.run("init", "--apply", "--confirm", token(f.run("init").stdout));
+ expect(f.run(...args).status).not.toBe(0);
+ });
+});
+
+describe("tenant CLI is local-only", () => {
+ it("refuses --base/--env targeting and never sources the env file", () => {
+ const f = fixture();
+ const marker = path.join(f.root, "sourced");
+ fs.writeFileSync(path.join(f.root, "danger.env"), `touch '${marker}'\n`, { mode: 0o600 });
+ const run = spawnSync("bash", [path.join(process.cwd(), "bin/mso"), "--env", path.join(f.root, "danger.env"), "tenant", "status"], { encoding: "utf8", env: { ...process.env, HOME: f.root } });
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain("local-only");
+ expect(fs.existsSync(marker)).toBe(false);
+ });
+});
diff --git a/scripts/mso-tenant.ts b/scripts/mso-tenant.ts
new file mode 100644
index 00000000..adf531cf
--- /dev/null
+++ b/scripts/mso-tenant.ts
@@ -0,0 +1,175 @@
+#!/usr/bin/env bun
+// Owner-only tenant enrollment control plane. Deliberately local, never an
+// HTTP/MCP route or tool: it wraps the persistence adapter's trusted
+// administration.setBinding, which is not reachable from any request path.
+//
+// Every mutation is PREVIEW ONLY unless --apply and --confirm <token> are both
+// present. Inputs are owner-supplied at enrollment time; a tenant can never
+// select its own directory, tenant ID, principal ID or provider. The store root
+// comes from server-owned configuration (OS_TENANCY_STORAGE_ROOT), never argv.
+import { createHash } from "node:crypto";
+import { openTenantPersistence } from "../lib/tenancy/persistence";
+import { tenantFile } from "../lib/tenancy/persistence-file";
+import { validBinding, validId, validSubject } from "../lib/tenancy/persistence-schema";
+import type { TenantSnapshot } from "../lib/tenancy/persistence-schema";
+
+const HELP = `mso tenant — owner-only tenant enrollment (local installation only)
+
+ mso tenant status
+ mso tenant list [--json]
+ mso tenant init
+ mso tenant enroll --issuer <id> --subject <id> --tenant <id> --principal <id>
+ [--disabled] [--tenant-disabled] [--remap] [--json]
+ [--apply --confirm <preview-token>]
+ mso tenant set-enabled --issuer <id> --subject <id> --tenant <id> --principal <id>
+ --enabled <true|false> [--tenant-enabled <true|false>]
+
+Root comes from OS_TENANCY_STORAGE_ROOT (canonical absolute Linux directory, mode 0700,
+owned by this service account). init creates only an empty snapshot and refuses when
+state already exists. enroll/set-enabled are PREVIEW ONLY without --apply --confirm.
+
+No credential value belongs in argv, the plan, the audit event or this help. Enrollment
+authorizes a binding; it does NOT issue a credential or enable the runtime mode.
+See docs/TENANT-ROLLOUT.md and docs/TENANT-PERSISTENCE.md.`;
+
+type Options = Record<string, string | boolean | undefined>;
+const argv = process.argv.slice(2);
+const action = argv[0];
+const flags: Options = {};
+for (let i = 1; i < argv.length; i++) {
+ const arg = argv[i];
+ if (!arg.startsWith("--")) fail(`unexpected argument: ${arg}`);
+ if (["--apply", "--json", "--disabled", "--tenant-disabled", "--remap"].includes(arg)) { flags[arg.slice(2)] = true; continue; }
+ const value = argv[i + 1];
+ if (value === undefined || value.startsWith("--")) fail(`${arg} needs a value`);
+ flags[arg.slice(2)] = value; i++;
+}
+function fail(message: string): never { process.stderr.write(`mso tenant: ${message}\n`); process.exit(1); }
+function str(name: string): string | undefined { const v = flags[name]; return typeof v === "string" ? v : undefined; }
+function bool(name: string): boolean | undefined {
+ const v = str(name); if (v === undefined) return undefined;
+ if (v !== "true" && v !== "false") fail(`--${name} must be true or false`);
+ return v === "true";
+}
+const root = process.env.OS_TENANCY_STORAGE_ROOT?.trim();
+
+async function main() {
+ if (!action || action === "help" || action === "--help" || action === "-h") { process.stdout.write(HELP + "\n"); return; }
+ if (!root) fail("OS_TENANCY_STORAGE_ROOT is not set (server-owned store root)");
+
+ if (action === "status") return status();
+ if (action === "list") return list();
+ if (action === "init") return init();
+ if (action === "enroll") return setEnabled("enroll");
+ if (action === "set-enabled") return setEnabled("set-enabled");
+ fail(`unknown action: ${action} (see mso tenant --help)`);
+}
+
+async function status() {
+ const store = await open();
+ const s = await store.administration.status();
+ emit({ root, initialized: true, revision: s.revision, auditEntries: s.auditEntries });
+}
+
+async function list() {
+ const snapshot = await readSnapshot();
+ emit(snapshot.bindings.map(b => ({
+ issuer: b.issuer, subject: b.subject, tenantId: b.tenantId, principalId: b.principalId,
+ mappingRevision: b.mappingRevision, enabled: b.enabled, tenantEnabled: b.tenantEnabled,
+ })));
+}
+
+async function init() {
+ const existing = await openSnapshotOrNull();
+ if (existing) fail("tenant store already exists; init refuses to overwrite it");
+ const plan = { action: "init", root };
+ if (!confirmed(plan)) return preview(plan);
+ await openTenantPersistence({ root: root!, initialize: true });
+ emit({ action: "init", root, initialized: true });
+}
+
+async function setEnabled(mode: "enroll" | "set-enabled") {
+ const issuer = str("issuer"), subject = str("subject"), tenantId = str("tenant"), principalId = str("principal");
+ for (const [name, value] of [["issuer", issuer], ["subject", subject]] as const) {
+ if (!value) fail(`--${name} is required`);
+ }
+ if (!validSubject({ issuer: issuer!, subject: subject! })) fail("--issuer/--subject must be bounded registry ids");
+ const subjectKey = { issuer: issuer!, subject: subject! };
+
+ const snapshot = await readSnapshot();
+ const current = snapshot.bindings.find(b => b.issuer === issuer && b.subject === subject);
+
+ let binding: { tenantId: string; principalId: string; enabled: boolean; tenantEnabled: boolean };
+ if (mode === "enroll") {
+ if (!tenantId || !principalId) fail("--tenant and --principal are required");
+ if (!validId(tenantId) || !validId(principalId)) fail("--tenant/--principal must be bounded registry ids");
+ binding = {
+ tenantId, principalId,
+ enabled: flags["disabled"] ? false : true,
+ tenantEnabled: flags["tenant-disabled"] ? false : true,
+ };
+ } else {
+ if (!current) fail("no existing binding for that issuer/subject; use `enroll`");
+ binding = {
+ tenantId: current.tenantId, principalId: current.principalId,
+ enabled: bool("enabled") ?? current.enabled,
+ tenantEnabled: bool("tenant-enabled") ?? current.tenantEnabled,
+ };
+ if (!validBinding({ ...binding, mappingRevision: 1 })) fail("resulting binding is invalid");
+ }
+
+ if (!validBinding({ ...binding, mappingRevision: 1 })) fail("binding is invalid");
+ if (current && mode === "enroll"
+ && (current.tenantId !== binding.tenantId || current.principalId !== binding.principalId)
+ && !flags["remap"]) fail("subject is already bound to another tenant/principal; re-run with --remap to reassign");
+
+ const plan = { action: mode, root, issuer, subject, binding, expectedRevision: snapshot.revision, replaces: current ? current.mappingRevision : null };
+ if (!confirmed(plan)) return preview(plan);
+
+ const store = await open();
+ const live = await store.administration.status();
+ if (live.revision !== plan.expectedRevision) fail("store changed since preview; re-run to get a fresh plan");
+ const result = await store.administration.setBinding(subjectKey, binding, live.revision);
+ emit({ action: mode, root, binding: result.result, revision: result.revision, operationId: result.operationId });
+}
+
+async function open() {
+ const snapshot = await openSnapshotOrNull();
+ if (!snapshot) fail("tenant store is not initialized at OS_TENANCY_STORAGE_ROOT");
+ return await openTenantPersistence({ root: root!, initialize: false });
+}
+async function openSnapshotOrNull(): Promise<TenantSnapshot | null> {
+ try { return await readSnapshot(); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
+}
+async function readSnapshot(): Promise<TenantSnapshot> {
+ const file = await tenantFile(root!);
+ return file.transaction((directory) => file.read(directory));
+}
+
+function confirmation(plan: unknown) {
+ return "TENANT:" + createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 16);
+}
+function preview(plan: Record<string, unknown>) {
+ const token = confirmation(plan);
+ process.stdout.write("MSO tenant · PREVIEW ONLY\n" + JSON.stringify(plan, null, 2)
+ + `\n\nNo state changed. Apply with:\n --apply --confirm ${token}\n`);
+}
+function confirmed(plan: unknown) {
+ if (!flags["apply"]) return false;
+ const token = str("confirm");
+ if (token !== confirmation(plan)) fail("--confirm token does not match the current plan");
+ return true;
+}
+function emit(value: unknown) {
+ if (flags["json"]) process.stdout.write(JSON.stringify(value, null, 2) + "\n");
+ else process.stdout.write(format(value) + "\n");
+}
+function format(value: unknown): string {
+ if (Array.isArray(value)) return value.length ? value.map(row => format(row)).join("\n") : "(no bindings)";
+ if (value && typeof value === "object") return JSON.stringify(value);
+ return String(value);
+}
+
+try { await main(); }
+catch (error) { fail((error as Error).message); }