Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Connected servers receive their licence; soft seats and a licence card on server installs (#7796)
Milind Sonic92fe04905bc
diff --git a/apps/docs/content/docs/self-hosting/connected-servers.mdx b/apps/docs/content/docs/self-hosting/connected-servers.mdxindex 8c60cb4b22..b9bc2a3369 100644--- a/apps/docs/content/docs/self-hosting/connected-servers.mdx+++ b/apps/docs/content/docs/self-hosting/connected-servers.mdx@@ -18,7 +18,7 @@ The whole list of what the Admin may run, ask and learn in this mode is one file- It only calls out: one HTTPS request to enrol, then one WebSocket to the Admin. It opens no port.- It makes its own Ed25519 key at enrolment. The private key stays on your server. It pins the Admin's signing keys.- It runs with every Linux capability dropped, a read-only file system and no new privileges.-- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: it starts and stops the two containers of your install, runs one fixed read inside your server's container (below), runs short helper containers that copy your data folder to and from a Docker volume on the same server, and replaces itself when you tell it to. It never makes a second MausBot and never changes your `.env` or your Compose file.+- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: it starts and stops the two containers of your install, runs one fixed read inside your server's container and, when MausBot sends your licence, one fixed write of that licence there (below), runs short helper containers that copy your data folder to and from a Docker volume on the same server, and replaces itself when you tell it to. It never makes a second MausBot and never changes your `.env` or your Compose file.- The mode is chosen on your server when it enrols, kept in the connector's own state, and told to the Admin. The Admin cannot change it.## It connects the server you installed@@ -77,6 +77,25 @@ On the same connection the Admin can send HTTP requests. In customer-run mode noThere is no pairing: the Admin cannot open a sign-in on your server, as a member or as anyone. A pairing request, and a request for the team summary, are refused and logged like any other.+## What MausBot can send: your licence++MausBot can send this server its licence, which the connector saves to the server's data folder; nothing else in that folder is read or written.++- The licence comes inside the Admin's signed configuration for your server, never as a job. Only text with the shape of a licence (`omb1.` and two base64url parts, a few kilobytes at most) is saved. Anything else is ignored and logged.+- The connector writes it from inside your server's container, as the user your server runs as, to `license.key` in the data folder (`/data/.openmausbot` in the container). The file is readable by that user only. It is written to a temporary file beside it and then renamed, so your server never reads half a licence.+- Before writing, it compares the file with the licence, inside the container, and writes nothing when they are the same. It checks again every hour, so a restore that put an older `license.key` back is corrected.+- A `license.key` changed in the last three minutes that holds a different licence is left alone until it is older, so a licence you paste by hand is read by your server first. A `license.key` that is a folder, or a link to one, is never written into; that counts as a failed write. After a failed write the connector waits five minutes before it tries again.+- It never removes a licence. When a configuration carries none, for example after a plan is cancelled, the licence on your server stays and runs out by itself.+- It never decides which licence wins. Your server reads every licence it has (`license.key`, `OMB_LICENSE_KEY` and the copy it keeps of the last one it accepted), checks each signature itself, and keeps the one issued last.+- It is not a job, so pausing remote management and your policy file do not stop it. A licence changes no bot, no data and no setting; refusing one would only let a paid server run into its grace period. To refuse licences from MausBot, stop the connector.+- Before each licence is written, one line goes to your audit log, with the first 12 characters of its SHA-256, never the licence itself. When that line cannot be written, the licence is not written either. A write that then fails gets a second line saying so.++Without a connection, the same file takes a licence you paste: download it from your MausBot account and run, on the server:++```sh+cd /opt/openmausbot && sudo docker compose exec -T omb sh -c 'umask 077; cat > "$OMB_DATA_DIR/license.key"' < licence.txt+```+## Signing in does not go through MausBotPeople sign in to your server with your server's own sign-in: a pairing code you make on the server, or a code emailed to an address on your sign-in list. Neither passes through the connector or the Admin.@@ -87,21 +106,21 @@ People sign in to your server with your server's own sign-in: a pairing code you## Your log, your rules, your switch-- **The audit log.** Every job, each of its steps, its result, every request and every refusal is one line in `/var/log/mausbot/audit.jsonl` on your server, owned by root. Each line carries the hash of the line before it, so a removed or changed line shows. A job that would change something is refused when the log cannot be written. A failed job's full reason is here; only its code leaves the server.+- **The audit log.** Every job, each of its steps, its result, every request, every refusal and every licence written is one line in `/var/log/mausbot/audit.jsonl` on your server, owned by root. Each line carries the hash of the line before it, so a removed or changed line shows. A job that would change something is refused when the log cannot be written. A failed job's full reason is here; only its code leaves the server.```shdocker exec mausbot-connector mausbot-connector audit --tail 50docker exec mausbot-connector mausbot-connector audit --verify```-- **Pause.** One command makes the connector refuse every job and every request from MausBot, and log each one. The server keeps running, people keep signing in, and the heartbeat below still goes out, saying that you paused. A switch in Settings is **planned**.+- **Pause.** One command makes the connector refuse every job and every request from MausBot, and log each one. The server keeps running, people keep signing in, and the heartbeat below still goes out, saying that you paused. A licence MausBot sends is still saved (see above). A switch in Settings is **planned**.```shdocker exec mausbot-connector mausbot-connector pausedocker exec mausbot-connector mausbot-connector resume```-- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, narrows the seven jobs further and can hold updates. The connector reads it before every job and never writes it.+- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, narrows the seven jobs further and can hold updates. The connector reads it before every job and never writes it. It does not cover the licence.```json{ "jobs": ["status", "host-health", "update", "backup"], "updates": "hold" }@@ -114,12 +133,14 @@ People sign in to your server with your server's own sign-in: a pairing code you| When | What ||---|---|| Once, at enrolment | The one-time code, the connector's public key, the mode, and the server's facts: operating system, kernel, architecture, CPU count, memory, free disk, Docker version, whether AppArmor and user namespaces are on |-| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and each server check as an id and a pass or fail; the server's state, image and version, and whether its bots' sandbox is on or off; the connector's version and image; the mode; whether you paused; the seat count |+| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and each server check as an id and a pass or fail; the server's state, image and version, and whether its bots' sandbox is on or off; the connector's version and image; the mode; whether you paused; the seat count; the server's own id (`environmentId`, a random identifier it made when it was installed); and the licence state as the server judges it: whether it is valid, the plan, the seats, the expiry date, the days of grace left once expired, and whether it was read from `license.key`, `OMB_LICENSE_KEY` or the server's kept copy || After each job | The result: the server's state, image and version, or the id and time of a backup. A failure is a fixed code and a fixed sentence |The seat count is the number of people who can sign in: the addresses on your sign-in list, plus any other address that has signed in, plus you when you signed in with a pairing code and no admin address is on the list. It is a number. No address, name or role is sent.-To build this the connector reads four things from your server, on the server's own loopback: that it answers, whether its bots' sandbox is on or off (not its checks), its version, and its seat count. It keeps those fields and drops the rest of each answer. It reads no chat, file, key, name or address, and it sends no line of any log.+The licence state never includes the licence, the name it was issued to, or its feature list. The server's own id lets MausBot issue a licence for this server.++To build this the connector reads six things from your server, on the server's own loopback: that it answers, whether its bots' sandbox is on or off (not its checks), its version, its own id, its seat count, and its licence state. It keeps those fields and drops the rest of each answer. It reads no chat, file, key, name or address, and it sends no line of any log. On a server where a local request without a session is treated as a bot's (`OMB_LOOPBACK_TRUST=service`), the licence-state read carries a SHA-256 digest of the licence the connector saved; the server answers it only for a licence it accepted, so no bot's shell can make the same read. The read also says it is the connector's, which does nothing but let your server's Settings show its licence card before the first licence arrives.## What your server itself still sends@@ -141,6 +162,6 @@ Traffic to the AI providers, engines and apps you set up is between your server- A pause switch in Settings.- Signed connector images, checked on your server before a connector is replaced.- A floor under `update` at the first release with the hardened profile.-- Seats and plan features delivered to the server as a signed document. Today the seat count is only reported.+- Checking a licence's server against the server's own id. Today a licence's `server` field is carried, not checked.- Connecting a server built from source or run without Docker.- A published list of the network addresses a connected server needs.diff --git a/connector/src/adopted-home.ts b/connector/src/adopted-home.tsindex f9be8f2637..bbc458c491 100644--- a/connector/src/adopted-home.ts+++ b/connector/src/adopted-home.ts@@ -6,12 +6,14 @@ import { randomBytes } from "node:crypto";import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";-import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, VERSION_LABEL, boxReport, olderVersionRefusal, parseHomeReads, type HomeFacts, type JobSource } from "./customer-run.ts";+import {+ CUSTOMER_HOME_IMAGE, LICENCE_EXIT, VERSION_LABEL, boxReport, homeReadsCommand, licenceCommand, olderVersionRefusal, parseHomeReads, type HomeFacts, type JobSource,+} from "./customer-run.ts";import type { ContainerInfo, Docker, Mount } from "./docker.ts";import { JobFailure } from "./failure.ts";import { backupId, helperSpec } from "./home.ts";import { errorText, type Log } from "./log.ts";-import type { CopyInfo, HomeHealth, HomeReport, HomeState, JobError, JobReply, JobResults, ServerMode } from "./protocol.ts";+import type { CopyInfo, HomeHealth, HomeReport, HomeState, JobError, JobReply, JobResults, LicenceReport, ServerMode } from "./protocol.ts";import { BACKUPS_KEPT, HOME_STOP_TIMEOUT_S, LABELS, NAMES } from "./settings.ts";import type { HomeRecord, Operation, StateStore } from "./state.ts";@@ -35,6 +37,9 @@ const MADE_BY_LABEL = "com.mausbot.by";const lastLine = (text: string) => text.trim().split("\n").pop()?.slice(0, 300) ?? "";const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10;+/** What licenceFile found or did. */+export type LicenceFileState = "no_home" | "same" | "recent" | "differs" | "written";+export interface Install {container: ContainerInfo;/** The folder on the server that the home mounts at /data. */@@ -102,6 +107,10 @@ export class AdoptedHome {private readonly pollMs: number;private lastHealth: HomeHealth | null = null;private lastSeats: number | null = null;+ private lastEnvironmentId: string | null = null;+ private lastLicence: LicenceReport | null = null;+ /** customer-run.ts `licenceProof` of the licence the connector saved, presented on the licence-state read. */+ licenceProof: string | null = null;private chain: Promise<unknown> = Promise.resolve();private active = 0;@@ -126,6 +135,33 @@ export class AdoptedHome {return this.lastSeats;}+ /** The server's own id, as the home last said; null when it does not say. */+ get environmentId(): string | null {+ return this.lastEnvironmentId;+ }++ /** The server's licence state, as the home last said; null when it does not say. */+ get licence(): LicenceReport | null {+ return this.lastLicence;+ }++ /**+ * Compares `licence` with license.key in the home's data folder (`check`), or saves it there (`write`), from inside the+ * home's container as the user it runs as (customer-run.ts, section 5). "no_home": the home is not running, so nothing+ * was read or written and the caller tries again later. Throws when the file cannot be written. Not exclusive with jobs:+ * it touches nothing a job does, and a long update must not hold up a licence.+ */+ async licenceFile(mode: "check" | "write", licence: string): Promise<LicenceFileState> {+ const container = await this.container(SERVICE);+ if (!container?.State.Running) return "no_home";+ const { code, output } = await this.docker.exec(container.Id, licenceCommand(mode, licence), 30_000);+ if (code === LICENCE_EXIT.same) return "same";+ if (code === LICENCE_EXIT.recent) return "recent";+ if (code === LICENCE_EXIT.differs && mode === "check") return "differs";+ if (code === LICENCE_EXIT.written && mode === "write") return "written";+ throw new Error(`the home could not save its licence (exit ${code}${output.trim() ? `: ${lastLine(output)}` : ""})`);+ }+get previousImage(): string | null {return this.state.home().previousImage;}@@ -162,6 +198,8 @@ export class AdoptedHome {}const facts = await this.read(container);this.lastSeats = facts.seats;+ this.lastEnvironmentId = facts.environmentId;+ this.lastLicence = facts.licence;this.lastHealth = { ok: facts.answers, version: facts.version, image: await this.imageOf(container), box: boxReport(facts.box), at: this.now() };return this.lastHealth;}@@ -406,9 +444,9 @@ export class AdoptedHome {private async read(container: ContainerInfo): Promise<HomeFacts> {try {- return parseHomeReads((await this.docker.exec(container.Id, [...HOME_READS_COMMAND], 30_000)).output);+ return parseHomeReads((await this.docker.exec(container.Id, homeReadsCommand(this.licenceProof), 30_000)).output);} catch {- return { answers: false, version: null, seats: null, box: null };+ return { answers: false, version: null, seats: null, box: null, environmentId: null, licence: null };}}diff --git a/connector/src/audit.ts b/connector/src/audit.tsindex f3c4ddab14..b1a7aa6116 100644--- a/connector/src/audit.ts+++ b/connector/src/audit.ts@@ -1,7 +1,8 @@// The audit log on the server: one JSON line for each job and for each request MausBot's Admin makes to the home, written-// by the connector to /var/log/mausbot/audit.jsonl on the host, root's, for the server's owner to read. It is only ever-// appended to. Each line carries the SHA-256 of the line before it, so a line taken out or changed breaks the chain-// (verifyAudit). It never holds a secret, an environment value or a pairing code.+// by the connector to /var/log/mausbot/audit.jsonl on the host, root's, for the server's owner to read, and on a+// customer-run server one before each licence it writes there (customer-run.ts, section 5). It is only ever appended to.+// Each line carries the SHA-256 of the line before it, so a line taken out or changed breaks the chain (verifyAudit).+// It never holds a secret, an environment value, a pairing code or a licence.import { createHash } from "node:crypto";import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync } from "node:fs";import { dirname } from "node:path";@@ -17,6 +18,11 @@ export type AuditEvent =/** The server's admin paused or resumed remote management (`mausbot-connector pause`, `resume`). */| { event: "management"; what: "paused" | "resumed"; by: "local" }| { event: "refused"; by: "admin"; code: JobErrorCode; why: string; id?: string; type?: string }+ /** Customer-run: the licence in MausBot's config is about to be written to the server's data folder as license.key+ * (written before the file, and the file is not written when this line cannot be), its write failed, or it was not a+ * licence and was ignored. `fingerprint`: the first 12 hex digits of its SHA-256, never the licence. */+ | { event: "licence"; what: "writing" | "failed"; by: "admin"; fingerprint: string }+ | { event: "licence"; what: "refused"; by: "admin"; why: string }| { event: "job"; by: AuditSource; id: string; type: JobType; args: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: true; detail?: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: false; error: JobError }diff --git a/connector/src/customer-run.ts b/connector/src/customer-run.tsindex 6090c22cb4..00b61e08c0 100644--- a/connector/src/customer-run.ts+++ b/connector/src/customer-run.ts@@ -4,9 +4,11 @@//// Security invariant: nothing in this file passes through text a person wrote. Every string that leaves is either a// constant below, an enumerated code, or matches one of the patterns below (a version, an image reference, an id).+import { createHash } from "node:crypto";+import {checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeHealth, type HomeReport, type HostFacts, type HomeState, type HostHealth,- type Job, type JobError, type JobErrorCode, type JobReply, type JobType,+ type Job, type JobError, type JobErrorCode, type JobReply, type JobType, type LicenceReport, type LicenceSource,} from "./protocol.ts";// 1. JOBS. The only kinds the Admin may run. Not here, so refused: `export-disk` (uploads the data to MausBot) and@@ -143,17 +145,33 @@ export function answerCustomerRunRequest(request: CustomerRunRequest, facts: Ser}}-// 3. WHAT THE CONNECTOR READS FROM THE HOME. Three GETs on the home's own loopback, with no body, and from them four-// fields: that it answers as MausBot and whether its bot box is on or off, its version, and its seat count. Every other field of those answers (the-// server's name among them) is dropped here and never kept.+// 3. WHAT THE CONNECTOR READS FROM THE HOME. Four GETs on the home's own loopback, with no body, and from them six+// fields: that it answers as MausBot and whether its bot box is on or off, its version, its own id, its seat count, and+// its licence state (section 5). Every other field of those answers (the server's name and the licence's customer among+// them) is dropped here and never kept. The licence state is the server's own judgement of its licence, never the licence.-export const HOME_READS = ["/api/health", "/.well-known/openmausbot/environment", "/api/seats"] as const;+export const HOME_READS = ["/api/health", "/.well-known/openmausbot/environment", "/api/seats", "/api/license"] as const;const RECORD_END = "\u001e";-/** Run inside the home's container: curl comes with the image, and the home listens on its own loopback only. */-export const HOME_READS_COMMAND = [- "sh", "-c",- `for path in ${HOME_READS.join(" ")}; do curl -s --max-time 5 "http://127.0.0.1:\${OMB_PORT:-8799}$path" || true; printf '\\n\\036\\n'; done`,-] as const;+/** The header that lets the licence-state read through on a server where a local request without a session is only a+ * service (a shared server, where every bot's shell is a local caller too): `licenceProof` of the licence the connector+ * saved. The server answers it with the six fields above and nothing else, and only while that licence is one it accepted. */+export const LICENCE_PROOF_HEADER = "x-openmausbot-licence-proof";+/** Says the read is the connector's, so the server's Settings shows its licence card even before a first licence. It+ * opens nothing: a request without a session or a proof is refused where it was refused before. */+export const CONNECTOR_HEADER = "x-openmausbot-connector";+/**+ * Run inside the home's container: curl comes with the image, and the home listens on its own loopback only. `proof` is+ * the one argument, after the fixed script: `licenceProof` of the licence the connector saved, or "" when it saved none.+ */+export function homeReadsCommand(proof: string | null): string[] {+ const safe = proof !== null && /^[0-9a-f]{64}$/.test(proof) ? proof : "";+ return [+ "sh", "-c",+ `for path in ${HOME_READS.slice(0, 3).join(" ")}; do curl -s --max-time 5 "http://127.0.0.1:\${OMB_PORT:-8799}$path" || true; printf '\\n\\036\\n'; done; `+ + `curl -s --max-time 5 -H "${CONNECTOR_HEADER}: customer-run" -H "${LICENCE_PROOF_HEADER}: $1" "http://127.0.0.1:\${OMB_PORT:-8799}${HOME_READS[3]}" || true; printf '\\n\\036\\n'`,+ "sh", safe,+ ];+}export interface HomeFacts {answers: boolean;@@ -161,6 +179,10 @@ export interface HomeFacts {seats: number | null;/** Whether its bots run in the bot box, from the health answer: on, off, or null when it does not say. */box: "on" | "off" | null;+ /** The server's own id, from its environment answer; null when it does not say. */+ environmentId: string | null;+ /** The server's licence state; null when it does not say (an older server, or one that refused the read). */+ licence: LicenceReport | null;}const parsed = (text: string | undefined): Record<string, unknown> => {@@ -173,9 +195,13 @@ const parsed = (text: string | undefined): Record<string, unknown> => {};export function parseHomeReads(output: string): HomeFacts {- const [health, environment, seats] = output.split(RECORD_END);+ const [health, environment, seats, licence] = output.split(RECORD_END);const said = parsed(health);- return { answers: said.app === "openmausbot", version: versionOrNull(parsed(environment).version), seats: seatsOrNull(parsed(seats).seats), box: boxOnOff(said.box) };+ const place = parsed(environment);+ return {+ answers: said.app === "openmausbot", version: versionOrNull(place.version), seats: seatsOrNull(parsed(seats).seats), box: boxOnOff(said.box),+ environmentId: environmentIdOrNull(place.environmentId), licence: licenceReport(parsed(licence)),+ };}// 4. WHAT LEAVES THE SERVER. The heartbeat (every 30 seconds) and each job's reply, rebuilt here field by field. A@@ -200,6 +226,28 @@ export const boxReport = (value: unknown): HomeHealth["box"] => {return said ? { box: said, checks: null, failed: [] } : null;};const seatsOrNull = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1_000_000 ? value : null);+const ENVIRONMENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const environmentIdOrNull = (value: unknown) => (typeof value === "string" && ENVIRONMENT_ID.test(value) ? value.toLowerCase() : null);+const PLAN = /^[a-z0-9][a-z0-9-]{0,39}$/;+const DAY = /^\d{4}-\d{2}-\d{2}$/;+const LICENCE_SOURCES: readonly LicenceSource[] = ["file", "env", "last-good"];++/** The server's licence state as it leaves: six fields, each a boolean, a number, a date, an enumerated word or a plan's+ * short id. Anything that is not the server's licence answer (a refusal, an error page) is null. */+export function licenceReport(value: unknown): LicenceReport | null {+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;+ const said = value as Record<string, unknown>;+ if (typeof said.valid !== "boolean") return null;+ const grace = said.graceDaysLeft;+ return {+ valid: said.valid,+ plan: typeof said.plan === "string" && PLAN.test(said.plan) ? said.plan : null,+ seats: typeof said.seats === "number" && Number.isInteger(said.seats) && said.seats > 0 && said.seats <= 1_000_000 ? said.seats : null,+ expiresAt: typeof said.expiresAt === "string" && DAY.test(said.expiresAt) ? said.expiresAt : null,+ graceDaysLeft: typeof grace === "number" && Number.isInteger(grace) && grace >= 0 && grace <= 366 ? grace : null,+ source: (LICENCE_SOURCES as readonly unknown[]).includes(said.source) ? said.source as LicenceSource : null,+ };+}/** The server's facts as they leave it, at enrolment and in every heartbeat. */export function reducedFacts(host: HostFacts): HostFacts {@@ -234,11 +282,14 @@ const reducedCopy = (copy: CopyInfo): CopyInfo => ({id: COPY_ID.test(copy.id) ? copy.id : "unknown", kind: copy.kind === "snapshot" ? "snapshot" : "backup", createdAt: count(copy.createdAt), image: imageOrNull(copy.image),});-export function reducedHeartbeat(facts: { host: HostHealth; home: HomeReport; connector: ConnectorIdentity; paused: boolean; seats: number | null }): Heartbeat {+export function reducedHeartbeat(facts: {+ host: HostHealth; home: HomeReport; connector: ConnectorIdentity; paused: boolean; seats: number | null; environmentId?: string | null; licence?: LicenceReport | null;+}): Heartbeat {return {heartbeat: {host: reducedHost(facts.host), home: reducedHome(facts.home), connector: reducedConnector(facts.connector),mode: "customer-run", paused: facts.paused === true, seats: seatsOrNull(facts.seats),+ environmentId: environmentIdOrNull(facts.environmentId), licence: licenceReport(facts.licence),},};}@@ -298,3 +349,65 @@ export function reducedReply(reply: JobReply): JobReply {if (typeof result.backupId === "string" && COPY_ID.test(result.backupId)) out.backupId = result.backupId;return { id: reply.id, ok: true, result: out } as JobReply;}++// 5. WHAT THE CONNECTOR WRITES. One file, in the server's data folder: `license.key`, the server's licence, when MausBot's+// signed config carries one (protocol.ts `ConfigPayload.licence`). It is written from inside the server's own container,+// as the user the server runs as, readable by that user only (umask 077), to a temporary file beside it and then renamed+// over the old one, so the server never reads half a licence. Nothing else in that folder is read or written: the command+// below compares the file with the licence before writing, and that comparison happens inside the container.+//+// - Only a licence of the right shape is written: `omb1`, then two base64url parts, at most a few kilobytes. This shape is+// also what makes it safe to hand to the command below as an argument.+// - An absent licence removes nothing. A cancelled plan stops new licences; the one on the server runs out by itself.+// - The connector never decides which of two licences is newer: the server reads every licence it has and keeps the one+// issued last (server/enterprise.ts). The connector compares licences as exact strings only, to skip writing one twice.+// - A license.key changed in the last three minutes that is not this licence is left alone until it is older: someone+// pasted a licence by hand, and the server, which looks at the file once a minute, must get to read it first.+// - A license.key that is a folder, or a link to one, is never written into: that is a failure, reported and retried later.+// - It is not a job: pausing remote management and the server's policy file do not stop it. A licence changes no bot, no+// data and no setting of the server; refusing one would only let a paid server run into its grace period. Before each+// licence is written, one line goes to the audit log, with a short fingerprint, never the licence; when that line cannot+// be written, neither is the licence.++export const LICENCE_FILE = "license.key";+const LICENCE_SHAPE = /^omb1\.[A-Za-z0-9_-]{16,6000}\.[A-Za-z0-9_-]{43,200}$/;+/** A license.key changed this recently, and different from the licence, is someone's own: the connector waits. */+export const LICENCE_PASTE_MINUTES = 3;++/** The licence, when it has the shape of one; null otherwise. */+export function checkLicence(value: unknown): string | null {+ return typeof value === "string" && LICENCE_SHAPE.test(value) ? value : null;+}++/** What the licence-state read presents (section 3), and what the server compares with each licence it accepted. */+export function licenceProof(licence: string): string {+ return createHash("sha256").update(`omb-licence-state\n${licence}`).digest("hex");+}++/** The first 12 hex digits of the licence's SHA-256: for the audit log, so the owner can tell two licences apart. */+export function licenceFingerprint(licence: string): string {+ return createHash("sha256").update(licence).digest("hex").slice(0, 12);+}++/** Exit codes of `licenceCommand`: written; cannot be written; already the licence; someone changed it just now; would+ * be written (`check` only). */+export const LICENCE_EXIT = { written: 0, failed: 1, same: 3, recent: 4, differs: 5 } as const;++/**+ * Run inside the home's container, as the user it runs as. `check` only compares; `write` compares and then writes.+ * `licence` has passed `checkLicence`; it and the mode are the two arguments after the fixed script.+ */+export function licenceCommand(mode: "check" | "write", licence: string): string[] {+ if (!checkLicence(licence)) throw new Error("not a licence");+ const { written, failed, same, recent, differs } = LICENCE_EXIT;+ return [+ "sh", "-c",+ `umask 077; set -C; dir="\${OMB_DATA_DIR:-/data/.openmausbot}"; file="$dir/${LICENCE_FILE}"; tmp="$dir/.${LICENCE_FILE}.connector.tmp"; `+ + `[ -d "$dir" ] || exit ${failed}; [ -d "$file" ] && exit ${failed}; `+ + `if [ -f "$file" ] && [ ! -L "$file" ] && [ "$(cat "$file")" = "$2" ]; then exit ${same}; fi; `+ + `if { [ -e "$file" ] || [ -L "$file" ]; } && [ -n "$(find "$file" -prune -mmin -${LICENCE_PASTE_MINUTES} 2>/dev/null)" ]; then exit ${recent}; fi; `+ + `[ "$1" = write ] || exit ${differs}; rm -f "$tmp"; `+ + `if printf '%s\\n' "$2" > "$tmp" && mv -f "$tmp" "$file"; then exit ${written}; fi; rm -f "$tmp"; exit ${failed}`,+ "sh", mode, licence,+ ];+}diff --git a/connector/src/licence.ts b/connector/src/licence.tsnew file mode 100644index 0000000000..ef9d77ccc4--- /dev/null+++ b/connector/src/licence.ts@@ -0,0 +1,121 @@+// A customer-run server's licence, from MausBot's signed config to license.key in the server's data folder. What may be+// written, and how, is customer-run.ts section 5; this is only when. The licence the config carries is offered here+// (each config the connector accepts, and the kept one at start); it is written once the home runs, checked again every+// hour (a restore or a rollback can put an older file back), and never removed.+import type { LicenceFileState } from "./adopted-home.ts";+import type { AuditEvent } from "./audit.ts";+import { checkLicence, licenceFingerprint, licenceProof } from "./customer-run.ts";+import { errorText, type Log } from "./log.ts";++/** How often the licence on the server is compared with the one MausBot sent last, to put it back if it was replaced. */+export const LICENCE_RECHECK_MS = 60 * 60_000;+/** After a write that failed, or an audit log that could not be written, the next try waits this long. */+export const LICENCE_RETRY_MS = 5 * 60_000;++export interface LicenceHome {+ licenceFile(mode: "check" | "write", licence: string): Promise<LicenceFileState>;+ licenceProof: string | null;+}++export interface LicenceDeliveryOptions {+ home: LicenceHome;+ log: Log;+ /** One audit line; it throws when the log cannot be written, and then the licence is not written either. */+ record: (event: Extract<AuditEvent, { event: "licence" }>) => void;+ now?: () => number;+ recheckMs?: number;+ retryMs?: number;+}++export class LicenceDelivery {+ private readonly options: LicenceDeliveryOptions;+ private readonly now: () => number;+ /** The newest well-formed licence MausBot sent. */+ private wanted: string | null = null;+ /** The licence the server's folder is known to hold, and when that was last checked. */+ private settled: { licence: string; at: number } | null = null;+ /** No try before this, after one that failed. */+ private retryAt = 0;+ private refused: string | null = null;+ private waitingSaid: string | null = null;+ private running: Promise<void> | null = null;++ constructor(options: LicenceDeliveryOptions) {+ this.options = options;+ this.now = options.now ?? Date.now;+ }++ /** The licence a config carries. Absent leaves everything as it is; one of the wrong shape is logged and never written. */+ offer(value: unknown): Promise<void> {+ if (value === undefined || value === null) return this.tick();+ const licence = checkLicence(value);+ if (!licence) {+ const why = typeof value === "string" ? `it is not a licence (${value.length} characters)` : "it is not text";+ if (this.refused !== why) {+ this.refused = why;+ this.options.log(`ignored the licence in MausBot's config: ${why}`);+ try { this.options.record({ event: "licence", what: "refused", by: "admin", why }); } catch { /* logged above */ }+ }+ return this.tick();+ }+ this.refused = null;+ if (licence !== this.wanted) {+ this.wanted = licence;+ this.retryAt = 0;+ this.options.home.licenceProof = licenceProof(licence);+ }+ return this.tick();+ }++ /** Writes the licence when it is not known to be on the server, or is due its hourly check. One try at a time. */+ tick(): Promise<void> {+ if (this.running) return this.running;+ const licence = this.wanted;+ if (!licence || this.now() < this.retryAt) return Promise.resolve();+ const due = !this.settled || this.settled.licence !== licence || this.now() - this.settled.at >= (this.options.recheckMs ?? LICENCE_RECHECK_MS);+ if (!due) return Promise.resolve();+ this.running = this.deliver(licence).finally(() => { this.running = null; });+ return this.running;+ }++ private failed(why: string): void {+ this.retryAt = this.now() + (this.options.retryMs ?? LICENCE_RETRY_MS);+ this.options.log(`could not save the licence MausBot sent: ${why}; trying again in ${Math.round((this.options.retryMs ?? LICENCE_RETRY_MS) / 60_000)} minutes`);+ }++ private settle(licence: string, state: LicenceFileState): boolean {+ if (state === "same" || state === "written") {+ this.settled = { licence, at: this.now() };+ this.waitingSaid = null;+ return true;+ }+ if (state === "recent" && this.waitingSaid !== licence) {+ this.waitingSaid = licence;+ this.options.log("license.key on the server was changed in the last few minutes, by hand or by the server's owner; the licence MausBot sent waits until the server has read it");+ }+ return state !== "differs";+ }++ private async deliver(licence: string): Promise<void> {+ const fingerprint = licenceFingerprint(licence);+ try {+ if (this.settle(licence, await this.options.home.licenceFile("check", licence))) return;+ } catch (error) {+ return this.failed(errorText(error));+ }+ // The audit line comes first: a licence the log could not record is not written.+ try {+ this.options.record({ event: "licence", what: "writing", by: "admin", fingerprint });+ } catch (error) {+ return this.failed(`the audit log cannot be written (${errorText(error)})`);+ }+ let state: LicenceFileState;+ try {+ state = await this.options.home.licenceFile("write", licence);+ } catch (error) {+ try { this.options.record({ event: "licence", what: "failed", by: "admin", fingerprint }); } catch { /* the log said why already */ }+ return this.failed(errorText(error));+ }+ if (this.settle(licence, state) && state === "written") this.options.log(`saved the licence MausBot sent (${fingerprint}) to the server's data folder`);+ }+}diff --git a/connector/src/main.ts b/connector/src/main.tsindex c02a89f84e..edc7d7cf1f 100644--- a/connector/src/main.ts+++ b/connector/src/main.ts@@ -19,6 +19,7 @@ import { serveRequest } from "./home-requests.ts";import { Home } from "./home.ts";import { hostChecks, hostFacts, hostHealth, probeBox, type BoxProbeResult, type HostReader } from "./host.ts";import { jobDesk, jobRunner, resultEvent } from "./jobs.ts";+import { LicenceDelivery } from "./licence.ts";import { sendLocalJob, serveLocalJobs } from "./local.ts";import { POLICY_FILE } from "./policy.ts";import { errorText, log, registerSecret } from "./log.ts";@@ -146,6 +147,9 @@ async function run(): Promise<void> {docker, state, log, diskFree: () => reader.disk().free, updateDir: PATHS.update,onStep: ({ id, type, step, detail }) => note({ event: "step", id, type, step, ...(detail ? { detail } : {}) }),}) : null;+ // The licence in MausBot's config goes to the server's data folder, paused or not (customer-run.ts, section 5).+ const licence = adopted ? new LicenceDelivery({ home: adopted, log, record: (event) => audit.append(event) }) : null;+ void licence?.offer(kept?.licence);const home = adopted ?? new Home({docker, state, log, readHealth, seccomp, transfer: httpTransfer,diskFree: () => reader.disk().free,@@ -158,7 +162,9 @@ async function run(): Promise<void> {const heartbeat = async (): Promise<Heartbeat> => {await home.refreshHealth().catch(() => null);const facts = { host: await host.health(false), home: await home.report(), connector: identity() };- return adopted ? reducedHeartbeat({ ...facts, paused: state.paused(), seats: adopted.seats }) : { heartbeat: facts };+ return adopted+ ? reducedHeartbeat({ ...facts, paused: state.paused(), seats: adopted.seats, environmentId: adopted.environmentId, licence: adopted.licence })+ : { heartbeat: facts };};let agent: Agent;const runner = jobRunner({@@ -183,7 +189,10 @@ async function run(): Promise<void> {log(`MausBot's signing keys are now ${Object.keys(keys).join(", ")}`);},config: { saved: () => state.adminConfig(), save: (config) => state.saveAdminConfig(config) },- onConfig: (config) => log(`MausBot's schedule and policy (version ${config.version}) are kept on this server`),+ onConfig: (config) => {+ log(`MausBot's schedule and policy (version ${config.version}) are kept on this server`);+ void licence?.offer(config.licence);+ },stream: (stream, accept) => (adopted? serveCustomerRunRequest(stream, accept, {paused: () => state.paused(), record: note,@@ -233,6 +242,7 @@ async function run(): Promise<void> {setInterval(() => {home.supervise().catch((error) => log(`supervising the home failed: ${errorText(error)}`));+ void licence?.tick();const latest = state.agent();if (latest && serverMode(latest) !== mode) {log("this server was connected again in another mode; the connector restarts to take it up");diff --git a/connector/src/policy.ts b/connector/src/policy.tsindex c9d64d57e6..09c3c7fa11 100644--- a/connector/src/policy.ts+++ b/connector/src/policy.ts@@ -6,6 +6,8 @@//// `jobs`: the only kinds MausBot may run here (absent: all of them). `updates: "hold"`: MausBot's home updates wait.// A self-update of the connector is always accepted, so a held or locked-down server never strands an old connector.+// A licence MausBot's config carries is not a job: this file does not limit it, and neither does a pause (customer-run.ts,+// section 5, says why).import { readFileSync } from "node:fs";import { JOB_TYPES, type Job, type JobType } from "./protocol.ts";diff --git a/connector/src/protocol.ts b/connector/src/protocol.tsindex 20e044c929..be4c729ecb 100644--- a/connector/src/protocol.ts+++ b/connector/src/protocol.ts@@ -151,9 +151,32 @@ export interface Heartbeat {paused?: boolean;/** Customer-run only: how many people can sign in to the home; null when the home does not say. Never who. */seats?: number | null;+ /** Customer-run only: the server's own id (its `environmentId`, a UUID), so a licence can name the server it is for;+ * null when the home does not say. */+ environmentId?: string | null;+ /** Customer-run only: the licence as the server itself judges it; null when the server does not say. Never the licence. */+ licence?: LicenceReport | null;};}+/** Where the licence in force was read from on the server: its data folder's `license.key`, its `OMB_LICENSE_KEY`, or the+ * copy it keeps of the last licence it accepted. */+export type LicenceSource = "file" | "env" | "last-good";++/** A customer-run server's licence state, from the server's own read (`GET /api/license` on its loopback). */+export interface LicenceReport {+ /** Licensed features work, grace included. */+ valid: boolean;+ /** e.g. "business-server". */+ plan: string | null;+ seats: number | null;+ /** YYYY-MM-DD, or null for a licence without an end. */+ expiresAt: string | null;+ /** Once expired: whole days until licensed features stop (0 after); null before expiry. */+ graceDaysLeft: number | null;+ source: LicenceSource | null;+}+export interface JobArgs {/** Writes the home's environment (kept 0600 on the server) and starts the home on `image`. */start: { image: string; env: Record<string, string> };@@ -329,6 +352,12 @@ export interface ConfigPayload {/** How long members' sessions last past the Admin's last check while it can't be reached. */offlineHours: number;};+ /**+ * Customer-run only: this server's licence (`omb1.<claims>.<signature>`), which the connector saves to the server's+ * data folder as `license.key` (customer-run.ts, section 5). Absent: nothing is written and nothing is removed. A new+ * licence comes in a config with a higher `version`, like any other change. An operated connector ignores it.+ */+ licence?: string;}/** Admin → connector before it restarts: reconnect after `reconnectInMs` plus a random part of `tryForMs`. */diff --git a/connector/test/customer-run.test.ts b/connector/test/customer-run.test.tsindex e822a8ab8c..4b655374ed 100644--- a/connector/test/customer-run.test.ts+++ b/connector/test/customer-run.test.ts@@ -4,17 +4,19 @@ import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { AdoptedHome, UPDATE_FILES, enrolmentRefusal, findInstall, standaloneServerPresent } from "../src/adopted-home.ts";-import { Agent, type Refusal, type Socket } from "../src/agent.ts";+import { Agent, savedConfig, type Refusal, type Socket } from "../src/agent.ts";import { AuditLog, type AuditEvent, type AuditLine } from "../src/audit.ts";import { serveCustomerRunRequest } from "../src/customer-run-requests.ts";import {- CUSTOMER_RUN_JOBS, CUSTOMER_RUN_LOCAL_JOBS, CUSTOMER_RUN_REQUESTS, HOME_READS, HOME_READS_COMMAND, checkCustomerRunJob, customerRunRefusal, olderVersionRefusal, parseHomeReads, reducedHeartbeat, reducedReply,+ CUSTOMER_RUN_JOBS, CUSTOMER_RUN_LOCAL_JOBS, CUSTOMER_RUN_REQUESTS, HOME_READS, LICENCE_PROOF_HEADER, checkCustomerRunJob, checkLicence, customerRunRefusal, homeReadsCommand,+ LICENCE_PASTE_MINUTES, licenceCommand, licenceFingerprint, licenceProof, licenceReport, olderVersionRefusal, parseHomeReads, reducedHeartbeat, reducedReply,} from "../src/customer-run.ts";+import { LicenceDelivery } from "../src/licence.ts";import { enroll } from "../src/enroll.ts";import { neverOlder } from "../src/images.ts";import { jobDesk, jobRunner } from "../src/jobs.ts";import { JOB_TYPES, checkJob, type HostFacts, type HostHealth, type Job, type JobReply, type JobType } from "../src/protocol.ts";-import { StateStore, type AgentRecord } from "../src/state.ts";+import { StateStore, type AgentRecord, type ConfigRecord } from "../src/state.ts";import { FakeAdmin } from "./fake-admin.ts";import { FakeDocker } from "./fake-docker.ts";@@ -28,6 +30,14 @@ const UNNAMED = digest("d");const EMAIL = "[email protected]";const WRITTEN = "Quarterly numbers for Project Nightingale";const SERVER_NAME = "Lovelace Analytical Engines";+const ENV_ID = "5d0c6f2e-9c1a-4c57-8f0e-2b7a1d3e4f50";+/** Licences of the right shape: the connector never verifies one, the server does. */+const licenceOf = (claims: string) => `omb1.${Buffer.from(JSON.stringify({ v: 1, customer: "Lovelace", claims })).toString("base64url")}.${"s".repeat(86)}`;+const LICENCE = licenceOf("first");+const RENEWED = licenceOf("renewed");+const LICENCE_STATE = { valid: true, source: "file", customer: SERVER_NAME, plan: "business-server", seats: 20, features: ["budgets"], expiresAt: "2026-12-31", expiresInDays: 34, graceEndsAt: "2027-01-14", graceDaysLeft: null, notice: EMAIL };+/** Where the server keeps license.key: OMB_DATA_DIR in the image is /data/.openmausbot, inside the data folder's mount. */+const LICENCE_PATH = ".openmausbot/license.key";const host: HostFacts = { os: "Ubuntu 24.04.3 LTS", kernel: "6.8.0-1021-azure", arch: "x86_64", cpus: 4, memMb: 16_000, diskGb: 120, docker: "28.0.4", apparmor: true, userns: true };const health: HostHealth = {...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0,@@ -64,16 +74,39 @@ async function server(options: { image?: string; seats?: number | null } = {}) {for (const [ref, version] of [[image, "v0.1.151"], [NEXT, "v0.1.152"], [OLDER, "v0.1.150"], [UNNAMED, null], ["caddy:2", null]] as const) docker.publish(ref, version);for (const ref of [image, "caddy:2"]) await docker.pull(ref);const compose = (service: string) => ({ "com.docker.compose.project": "openmausbot", "com.docker.compose.service": service });- const home = { answers: true, seats: options.seats === undefined ? 7 : options.seats, execs: [] as string[][] };+ const home = {+ answers: true, seats: options.seats === undefined ? 7 : options.seats, execs: [] as string[][],+ /** The licence-state answer; null: the server refuses the read. */+ licence: LICENCE_STATE as Record<string, unknown> | null,+ /** Proofs the server accepts, as GET /api/license checks them. */+ proofs: new Set<string>(),+ /** The data folder cannot be written (a full disk): the licence write fails. */+ readOnly: false,+ /** license.key was changed by hand within the paste window. */+ pastedJustNow: false,+ };docker.onExec = (_container, command) => {home.execs.push(command);- if (!home.answers) return { code: 0, output: "\n\u001e\n\n\u001e\n\n\u001e\n" };+ // The licence check and write, as the script does them (connector/test/licence-write.test.ts runs the script itself).+ if (command[3] === "sh" && (command[4] === "check" || command[4] === "write") && command[5]?.startsWith("omb1.")) {+ const files = docker.folder(dataDir).files;+ const licence = command[5];+ if (files.get(LICENCE_PATH) === `${licence}\n`) return { code: 3, output: "" };+ if (files.has(LICENCE_PATH) && home.pastedJustNow) return { code: 4, output: "" };+ if (command[4] === "check") return { code: 5, output: "" };+ if (home.readOnly) return { code: 1, output: "sh: can't create /data/.openmausbot/.license.key.connector.tmp: Read-only file system\n" };+ files.set(LICENCE_PATH, `${licence}\n`);+ return { code: 0, output: "" };+ }+ if (!home.answers) return { code: 0, output: "\n\u001e\n\n\u001e\n\n\u001e\n\n\u001e\n" };+ const proof = command[4] ?? "";return {code: 0,output: [JSON.stringify({ app: "openmausbot", pid: 41, owner: EMAIL, box: "on" }),- JSON.stringify({ environmentId: "env-1", label: SERVER_NAME, version: "0.1.151", admin: EMAIL }),+ JSON.stringify({ environmentId: ENV_ID, label: SERVER_NAME, version: "0.1.151", admin: EMAIL }),home.seats === null ? JSON.stringify({ error: "Not found" }) : JSON.stringify({ seats: home.seats, people: [EMAIL] }),+ home.licence && (home.proofs.size === 0 || home.proofs.has(proof)) ? JSON.stringify(home.licence) : JSON.stringify({ error: "Only the owner or an admin sees this server's licence." }),].map((answer) => `${answer}\n\u001e\n`).join(""),};};@@ -238,32 +271,49 @@ describe("a customer-run server: what leaves it", () => {return out;};- it("reads four fields from the home and drops everything else it answered", async () => {+ const NOTHING = { answers: false, version: null, seats: null, box: null, environmentId: null, licence: null };+ const STATE = { valid: true, plan: "business-server", seats: 20, expiresAt: "2026-12-31", graceDaysLeft: null, source: "file" };++ it("reads six fields from the home and drops everything else it answered", async () => {const fixture = await server();- expect(HOME_READS).toEqual(["/api/health", "/.well-known/openmausbot/environment", "/api/seats"]);+ expect(HOME_READS).toEqual(["/api/health", "/.well-known/openmausbot/environment", "/api/seats", "/api/license"]);const facts = parseHomeReads(fixture.docker.onExec!({} as never, []).output);- expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7, box: "on" });- expect(parseHomeReads("not json\n\u001e\n{\"version\":\"<script>\"}\n\u001e\n{\"seats\":\"seven\"}\n\u001e\n")).toEqual({ answers: false, version: null, seats: null, box: null });- expect(parseHomeReads("")).toEqual({ answers: false, version: null, seats: null, box: null });+ expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7, box: "on", environmentId: ENV_ID, licence: STATE });+ expect(parseHomeReads("not json\n\u001e\n{\"version\":\"<script>\",\"environmentId\":\"env-1\"}\n\u001e\n{\"seats\":\"seven\"}\n\u001e\n{\"error\":\"no\"}\n\u001e\n")).toEqual(NOTHING);+ expect(parseHomeReads("")).toEqual(NOTHING);// On or off, nothing else: a server without the field, or with anything else in it, says nothing about its box.expect(parseHomeReads(`${JSON.stringify({ app: "openmausbot", box: "off" })}\n\u001e\n`).box).toBe("off");expect(parseHomeReads(`${JSON.stringify({ app: "openmausbot", box: { checks: "33/33" } })}\n\u001e\n`).box).toBeNull();});- it("sends a heartbeat of versions, states, counts and the seat count, with no address, name or sentence in it", async () => {+ it("sends a heartbeat of versions, states, counts, the seat count, the server's id and its licence state, with no address, name or sentence in it", async () => {const fixture = await server();await fixture.install();await fixture.adopted.refreshHealth();- expect(fixture.home.execs).toEqual([[...HOME_READS_COMMAND]]);- const beat = reducedHeartbeat({ host: health, home: await fixture.adopted.report(), connector: identity, paused: false, seats: fixture.adopted.seats });+ expect(fixture.home.execs).toEqual([homeReadsCommand(null)]);+ const { adopted } = fixture;+ const beat = reducedHeartbeat({ host: health, home: await adopted.report(), connector: identity, paused: false, seats: adopted.seats, environmentId: adopted.environmentId, licence: adopted.licence });const sent = JSON.stringify(beat);- for (const secret of [EMAIL, "@customer", "lovelace", SERVER_NAME, "Lovelace", WRITTEN, "said so", "env-1"]) expect(sent, secret).not.toContain(secret);+ for (const secret of [EMAIL, "@customer", "lovelace", SERVER_NAME, "Lovelace", WRITTEN, "said so", "budgets", "omb1"]) expect(sent, secret).not.toContain(secret);expect(beat.heartbeat).toEqual({host: { ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0, checks: [{ id: "disk", ok: true, warning: true }, { id: "clock", ok: true }] },home: { state: "running", image: RUNNING, health: { ok: true, version: "0.1.151", image: RUNNING, box: { box: "on", checks: null, failed: [] }, at: 1_800_000_000_000 } },- connector: identity, mode: "customer-run", paused: false, seats: 7,+ connector: identity, mode: "customer-run", paused: false, seats: 7, environmentId: ENV_ID, licence: STATE,+ });+ for (const text of strings(beat).filter((text) => text !== ENV_ID && text !== "2026-12-31" && text !== "business-server")) expect(text, text).toMatch(TOLD);+ });++ it("sends the licence state as six fields of fixed kinds, and null for anything that is not the server's licence answer", () => {+ expect(licenceReport({ ...LICENCE_STATE, plan: `Business for ${EMAIL}`, seats: 2.5, expiresAt: "next year", graceDaysLeft: -1, source: "/data/license.key", valid: "yes" })).toBeNull();+ expect(licenceReport({ valid: false, plan: `Business for ${EMAIL}`, seats: 2.5, expiresAt: "next year", graceDaysLeft: 4000, source: "/data/license.key", key: LICENCE })).toEqual({+ valid: false, plan: null, seats: null, expiresAt: null, graceDaysLeft: null, source: null,});- for (const text of strings(beat)) expect(text, text).toMatch(TOLD);+ expect(licenceReport({ valid: true, plan: "business-server", seats: 25, expiresAt: "2026-12-01", graceDaysLeft: 9, source: "last-good" })).toEqual({+ valid: true, plan: "business-server", seats: 25, expiresAt: "2026-12-01", graceDaysLeft: 9, source: "last-good",+ });+ for (const refused of [null, [], "valid", { error: "forbidden" }]) expect(licenceReport(refused)).toBeNull();+ const beat = reducedHeartbeat({ host: health, home: { state: "running", image: RUNNING, health: null }, connector: identity, paused: false, seats: 1, environmentId: "../etc/passwd", licence: { ...STATE, plan: WRITTEN } as never });+ expect(beat.heartbeat).toMatchObject({ environmentId: null, licence: { plan: null } });});it("replaces anything that is not a version, an image or a machine's own name before it is sent", () => {@@ -302,6 +352,210 @@ describe("a customer-run server: what leaves it", () => {});});+describe("a customer-run server: its licence", () => {+ async function delivering(options: { paused?: boolean; audit?: string } = {}) {+ const fixture = await server();+ await fixture.install();+ if (options.paused) fixture.state.savePause(true);+ const audit = new AuditLog(options.audit ?? join(fixture.dir, "audit.jsonl"));+ let clock = 1_800_000_000_000;+ const delivery = new LicenceDelivery({+ home: fixture.adopted, log: (line) => fixture.lines.push(line), record: (event) => audit.append(event), now: () => clock, recheckMs: 60 * 60_000, retryMs: 5 * 60_000,+ });+ const writes = () => fixture.home.execs.filter((command) => command[4] === "write").length;+ const licenceExecs = () => fixture.home.execs.filter((command) => command[4] === "check" || command[4] === "write").length;+ const onDisk = () => fixture.docker.folder(fixture.dataDir).files.get(LICENCE_PATH);+ const audits = () => audit.tail(100).map((line) => JSON.parse(line) as AuditLine);+ const said = () => audits().filter((line) => line.event === "licence").map((line) => (line as { what: string }).what);+ return { ...fixture, audit, delivery, writes, licenceExecs, onDisk, audits, said, later: (ms: number) => { clock += ms; } };+ }++ it("saves a licence from MausBot's config once, as license.key in the server's data folder, from inside the server's container", async () => {+ const fixture = await delivering();+ await fixture.delivery.offer(LICENCE);+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ expect(fixture.writes()).toBe(1);+ // In the home's container, through its own shell: a check, then the write; the licence is an argument after a fixed script.+ expect(fixture.home.execs.slice(-2)).toEqual([licenceCommand("check", LICENCE), licenceCommand("write", LICENCE)]);+ const command = fixture.home.execs.at(-1)!;+ expect(command.slice(0, 2)).toEqual(["sh", "-c"]);+ expect(command[2]).not.toContain(LICENCE);+ expect(command[2]).toContain("umask 077; set -C;");+ expect(command[2]).toMatch(/> "\$tmp" && mv -f "\$tmp" "\$file"/);+ expect(command[2]).toContain(`-mmin -${LICENCE_PASTE_MINUTES}`);+ expect(fixture.docker.calls.filter((call) => call.startsWith("exec ")).every((call) => call === "exec openmausbot-omb-1")).toBe(true);+ expect(fixture.docker.calls.some((call) => /create|start|stop|remove|volume/.test(call))).toBe(false);+ });++ it("does not write the same licence again, and writes a renewed one", async () => {+ const fixture = await delivering();+ await fixture.delivery.offer(LICENCE);+ await fixture.delivery.offer(LICENCE);+ await fixture.delivery.tick();+ expect(fixture.writes()).toBe(1);+ await fixture.delivery.offer(RENEWED);+ expect(fixture.onDisk()).toBe(`${RENEWED}\n`);+ expect(fixture.writes()).toBe(2);+ expect(fixture.said()).toEqual(["writing", "writing"]);+ });++ it("ignores and logs a licence that does not have the shape of one, and writes nothing", async () => {+ const fixture = await delivering();+ for (const malformed of [`${LICENCE}; rm -rf /`, "omb1.short.sig", `omb2.${LICENCE.slice(5)}`, `${LICENCE}\n`, " ", 42, { licence: LICENCE }]) {+ expect(checkLicence(malformed), String(malformed)).toBeNull();+ await fixture.delivery.offer(malformed);+ }+ expect(checkLicence(LICENCE)).toBe(LICENCE);+ expect(fixture.licenceExecs()).toBe(0);+ expect(fixture.onDisk()).toBeUndefined();+ expect(fixture.lines.some((line) => line.startsWith("ignored the licence in MausBot's config: it is not a licence"))).toBe(true);+ expect(fixture.said().length).toBeGreaterThan(0);+ expect(fixture.said().every((what) => what === "refused")).toBe(true);+ expect(JSON.stringify(fixture.audits())).not.toContain("rm -rf");+ expect(() => licenceCommand("write", `${LICENCE}'; reboot; '`)).toThrow();+ });++ it("leaves the licence on the server when a config carries none: cancelling stops new licences, it removes nothing", async () => {+ const fixture = await delivering();+ await fixture.delivery.offer(LICENCE);+ await fixture.delivery.offer(undefined);+ await fixture.delivery.offer(null);+ fixture.later(2 * 60 * 60_000);+ await fixture.delivery.offer(undefined);+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ expect(fixture.home.execs.every((command) => !/\brm -f "\$file"|unlink/.test(command[2] ?? ""))).toBe(true);+ });++ it("writes one audit line before each licence it writes, with a fingerprint and never the licence", async () => {+ const fixture = await delivering();+ await fixture.delivery.offer(LICENCE);+ expect(fixture.audits().filter((line) => line.event === "licence")).toEqual([+ expect.objectContaining({ event: "licence", what: "writing", by: "admin", fingerprint: licenceFingerprint(LICENCE) }),+ ]);+ expect(licenceFingerprint(LICENCE)).toMatch(/^[0-9a-f]{12}$/);+ const text = readFileSync(fixture.audit.file, "utf8");+ expect(text).not.toContain(LICENCE.split(".")[1]);+ expect(text).not.toContain(LICENCE.split(".")[2]);+ });++ it("writes no licence when the audit log cannot be written, and tries again five minutes later", async () => {+ const blocked = mkdtempSync(join(tmpdir(), "omb-audit-blocked-"));+ cleanups.push(() => rmSync(blocked, { recursive: true, force: true }));+ writeFileSync(join(blocked, "not-a-folder"), "");+ const fixture = await delivering({ audit: join(blocked, "not-a-folder", "audit.jsonl") });+ await fixture.delivery.offer(LICENCE);+ expect(fixture.writes()).toBe(0);+ expect(fixture.onDisk()).toBeUndefined();+ expect(fixture.lines.some((line) => line.startsWith("could not save the licence MausBot sent: the audit log cannot be written") && line.endsWith("trying again in 5 minutes"))).toBe(true);+ const checks = fixture.licenceExecs();+ fixture.later(60_000);+ await fixture.delivery.tick();+ expect(fixture.licenceExecs()).toBe(checks);+ fixture.later(4 * 60_000);+ await fixture.delivery.tick();+ expect(fixture.licenceExecs()).toBe(checks + 1);+ });++ it("saves it while remote management is paused: a licence is not a job on the server's bots", async () => {+ const fixture = await delivering({ paused: true });+ expect(fixture.state.paused()).toBe(true);+ await fixture.delivery.offer(LICENCE);+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ });++ it("waits for the home to run, backs off five minutes after a failed write, and puts the licence back after the hourly check finds it replaced", async () => {+ const fixture = await delivering();+ await fixture.docker.stopContainer("openmausbot-omb-1");+ await fixture.delivery.offer(LICENCE);+ expect(fixture.onDisk()).toBeUndefined();+ await fixture.docker.startContainer("openmausbot-omb-1");+ fixture.home.readOnly = true;+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBeUndefined();+ expect(fixture.lines.filter((line) => line.startsWith("could not save the licence MausBot sent: the home could not save its licence (exit 1"))).toHaveLength(1);+ expect(fixture.said()).toEqual(["writing", "failed"]);+ fixture.home.readOnly = false;+ await fixture.delivery.tick();+ fixture.later(60_000);+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBeUndefined();+ fixture.later(4 * 60_000);+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ // A restore puts an older license.key back: the next hourly check writes the licence again; the same file, nothing.+ fixture.docker.folder(fixture.dataDir).files.set(LICENCE_PATH, `${licenceOf("older")}\n`);+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBe(`${licenceOf("older")}\n`);+ fixture.later(60 * 60_000);+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ fixture.later(60 * 60_000);+ await fixture.delivery.tick();+ expect(fixture.said()).toEqual(["writing", "failed", "writing", "writing"]);+ });++ it("leaves a licence someone pasted in the last few minutes for the server to read first, then writes MausBot's", async () => {+ const fixture = await delivering();+ fixture.docker.folder(fixture.dataDir).files.set(LICENCE_PATH, `${licenceOf("pasted")}\n`);+ fixture.home.pastedJustNow = true;+ await fixture.delivery.offer(LICENCE);+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBe(`${licenceOf("pasted")}\n`);+ expect(fixture.writes()).toBe(0);+ expect(fixture.said()).toEqual([]);+ expect(fixture.lines.filter((line) => line.includes("changed in the last few minutes"))).toHaveLength(1);+ fixture.home.pastedJustNow = false;+ await fixture.delivery.tick();+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ });++ it("reads the licence state with the licence's digest, so a shared server answers the connector and not a bot's shell", async () => {+ const fixture = await delivering();+ fixture.home.proofs.add(licenceProof(LICENCE));+ await fixture.adopted.refreshHealth();+ expect(fixture.adopted.licence).toBeNull();+ await fixture.delivery.offer(LICENCE);+ await fixture.adopted.refreshHealth();+ expect(fixture.home.execs.at(-1)).toEqual(homeReadsCommand(licenceProof(LICENCE)));+ expect(fixture.home.execs.at(-1)![2]).toContain(`-H "${LICENCE_PROOF_HEADER}: $1"`);+ expect(fixture.home.execs.at(-1)!.join(" ")).not.toContain(LICENCE);+ expect(fixture.adopted.licence).toMatchObject({ valid: true, seats: 20 });+ expect(licenceProof(LICENCE)).toMatch(/^[0-9a-f]{64}$/);+ expect(homeReadsCommand("not a digest; rm -rf /").at(-1)).toBe("");+ });++ it("takes the licence from a config MausBot signed, through the connection, and from the kept config after a restart", async () => {+ const fixture = await delivering();+ const admin = new FakeAdmin();+ await admin.listen();+ cleanups.push(() => admin.close());+ const record: AgentRecord = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector: identity, mode: "customer-run" });+ let saved: ConfigRecord | null = null;+ let count = 0;+ const agent = new Agent({+ identity: () => record, log: () => {}, random: () => 0, nextCount: () => ++count, mode: "customer-run", outgoing: reducedReply,+ heartbeat: async () => reducedHeartbeat({ host: health, home: { state: "running", image: RUNNING, health: null }, connector: identity, paused: false, seats: 7 }),+ handle: async () => null,+ config: { saved: () => saved, save: (config) => { saved = config; } },+ onConfig: (config) => void fixture.delivery.offer(config.licence),+ });+ cleanups.push(() => agent.stop());+ agent.start();+ await until(() => agent.connected);+ admin.sendConfig(record.boxId, { licence: LICENCE });+ await until(() => fixture.onDisk() === `${LICENCE}\n`);+ admin.sendConfig(record.boxId, { licence: "omb1.not a licence" });+ admin.sendConfig(record.boxId, {});+ await until(() => (saved?.version ?? 0) >= 3);+ await until(() => fixture.lines.some((line) => line.startsWith("ignored the licence")));+ expect(fixture.onDisk()).toBe(`${LICENCE}\n`);+ expect(fixture.writes()).toBe(1);+ // After a restart the connector goes by the config it kept: the newest it verified, which carries no licence, so+ // the licence on the server stays as it is.+ expect(savedConfig(saved, record)?.licence).toBeUndefined();+ });+});+describe("a customer-run server: the home its owner installed", () => {it("attaches to the Compose install, and says in plain words why it cannot when there is none or it was built here", async () => {const fixture = await server();diff --git a/connector/test/fake-admin.ts b/connector/test/fake-admin.tsindex a31f3137ac..389ed46505 100644--- a/connector/test/fake-admin.ts+++ b/connector/test/fake-admin.ts@@ -171,13 +171,15 @@ export class FakeAdmin {return reply;}- sendConfig(boxId: string, patch: Partial<Pick<ConfigPayload, "schedule" | "policy">> & { version?: number } = {}): number {+ /** `licence`: what the config carries for it (anything, to test what the connector refuses); absent leaves it out. */+ sendConfig(boxId: string, patch: Partial<Pick<ConfigPayload, "schedule" | "policy">> & { version?: number; licence?: unknown } = {}): number {const version = patch.version ?? ++this.configVersion;this.configVersion = Math.max(this.configVersion, version);const payload: Omit<ConfigPayload, "kid"> = {t: "config", box: boxId, iat: Date.now() + this.clockOffsetMs, version, state: this.boxes.get(boxId)!.state,schedule: patch.schedule ?? { window: { days: [0], start: "02:00", end: "05:00", timeZone: "Europe/Berlin" }, ring: "standard", holdUntil: null, image: null },policy: patch.policy ?? { offlineHours: 72 },+ ...("licence" in patch ? { licence: patch.licence as string } : {}),};this.send({ config: seal(payload, this.signingKid, this.keys[this.signingKid]!.privateKey) });return version;diff --git a/connector/test/licence-write.test.ts b/connector/test/licence-write.test.tsnew file mode 100644index 0000000000..54bfb0d9b2--- /dev/null+++ b/connector/test/licence-write.test.ts@@ -0,0 +1,121 @@+// The one write the connector makes on a customer-run server, run for real: customer-run.ts `licenceCommand` through sh,+// with OMB_DATA_DIR in a temporary folder, as it runs inside the server's container. POSIX shells only.+import { spawnSync } from "node:child_process";+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { LICENCE_EXIT, licenceCommand } from "../src/customer-run.ts";++const LICENCE = `omb1.${Buffer.from(JSON.stringify({ v: 1, customer: "Acme", features: [] })).toString("base64url")}.${"s".repeat(86)}`;+const OTHER = `omb1.${Buffer.from(JSON.stringify({ v: 1, customer: "Acme", features: ["budgets"] })).toString("base64url")}.${"t".repeat(86)}`;++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) {+ try { chmodSync(join(dir, "data"), 0o700); } catch { /* gone or never made */ }+ rmSync(dir, { recursive: true, force: true });+ }+});++/** A server's install folder with its data folder inside, and a file beside the data folder that must never change. */+function install() {+ const root = mkdtempSync(join(tmpdir(), "omb-licence-write-"));+ dirs.push(root);+ const data = join(root, "data");+ mkdirSync(data, { mode: 0o700 });+ writeFileSync(join(root, "license.key"), "outside\n");+ writeFileSync(join(root, "elsewhere.txt"), "a file a link points at\n");+ return { root, data, file: join(data, "license.key") };+}++function run(data: string, mode: "check" | "write", licence = LICENCE): number {+ const [shell, ...args] = licenceCommand(mode, licence);+ const result = spawnSync(shell!, args, { env: { PATH: process.env.PATH, OMB_DATA_DIR: data }, encoding: "utf8" });+ return result.status ?? -1;+}++/** Back-dated past the paste window, as a licence written an hour ago would be. */+const old = (path: string) => utimesSync(path, new Date(Date.now() - 60 * 60_000), new Date(Date.now() - 60 * 60_000));++describe.skipIf(process.platform === "win32")("the licence write, run through sh", () => {+ it("writes license.key in the data folder, readable by its owner only, and leaves nothing else", () => {+ const { root, data, file } = install();+ expect(run(data, "check")).toBe(LICENCE_EXIT.differs);+ expect(readdirSync(data)).toEqual([]);+ expect(run(data, "write")).toBe(LICENCE_EXIT.written);+ expect(readFileSync(file, "utf8")).toBe(`${LICENCE}\n`);+ expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(readdirSync(data)).toEqual(["license.key"]);+ // Not beside the data folder, and nothing there changed.+ expect(readFileSync(join(root, "license.key"), "utf8")).toBe("outside\n");+ expect(readdirSync(root).sort()).toEqual(["data", "elsewhere.txt", "license.key"]);+ });++ it("answers 3 for the same licence, with or without writing, and changes nothing", () => {+ const { data, file } = install();+ expect(run(data, "write")).toBe(LICENCE_EXIT.written);+ old(file);+ const before = statSync(file);+ expect(run(data, "check")).toBe(LICENCE_EXIT.same);+ expect(run(data, "write")).toBe(LICENCE_EXIT.same);+ expect(statSync(file).mtimeMs).toBe(before.mtimeMs);+ expect(statSync(file).ino).toBe(before.ino);+ });++ it("replaces an older licence in one rename, once the file is past the paste window", () => {+ const { data, file } = install();+ writeFileSync(file, `${OTHER}\n`, { mode: 0o600 });+ expect(run(data, "write")).toBe(LICENCE_EXIT.recent);+ expect(readFileSync(file, "utf8")).toBe(`${OTHER}\n`);+ old(file);+ const before = statSync(file).ino;+ expect(run(data, "check")).toBe(LICENCE_EXIT.differs);+ expect(run(data, "write")).toBe(LICENCE_EXIT.written);+ expect(readFileSync(file, "utf8")).toBe(`${LICENCE}\n`);+ expect(statSync(file).ino).not.toBe(before);+ expect(readdirSync(data)).toEqual(["license.key"]);+ });++ it("replaces a link at license.key with a file, and leaves what it pointed at alone", () => {+ const { root, data, file } = install();+ symlinkSync(join(root, "elsewhere.txt"), file);+ old(join(root, "elsewhere.txt"));+ spawnSync("touch", ["-h", "-t", "202001010000", file]);+ expect(run(data, "write")).toBe(LICENCE_EXIT.written);+ expect(lstatSync(file).isSymbolicLink()).toBe(false);+ expect(readFileSync(file, "utf8")).toBe(`${LICENCE}\n`);+ expect(readFileSync(join(root, "elsewhere.txt"), "utf8")).toBe("a file a link points at\n");+ });++ it("fails, writing nothing, when the data folder is missing, cannot be written, or license.key is a folder or a link to one", () => {+ const { root, data, file } = install();+ expect(run(join(root, "missing"), "write")).toBe(LICENCE_EXIT.failed);+ expect(readdirSync(root).sort()).toEqual(["data", "elsewhere.txt", "license.key"]);++ mkdirSync(file);+ expect(run(data, "check")).toBe(LICENCE_EXIT.failed);+ expect(run(data, "write")).toBe(LICENCE_EXIT.failed);+ expect(readdirSync(file)).toEqual([]);+ rmSync(file, { recursive: true });++ mkdirSync(join(root, "a-folder"));+ symlinkSync(join(root, "a-folder"), file);+ expect(run(data, "write")).toBe(LICENCE_EXIT.failed);+ expect(readdirSync(join(root, "a-folder"))).toEqual([]);+ rmSync(file);++ if (process.getuid?.() !== 0) {+ chmodSync(data, 0o500);+ expect(run(data, "write")).toBe(LICENCE_EXIT.failed);+ chmodSync(data, 0o700);+ expect(readdirSync(data)).toEqual([]);+ }+ expect(readFileSync(join(root, "license.key"), "utf8")).toBe("outside\n");+ });++ it("refuses to build the command for anything that is not a licence", () => {+ for (const bad of [`${LICENCE}"; touch /tmp/x; "`, "omb1.a.b", `${LICENCE}\n`]) expect(() => licenceCommand("write", bad)).toThrow();+ });+});diff --git a/licence-preview.html b/licence-preview.htmlnew file mode 100644index 0000000000..1100bd9a96--- /dev/null+++ b/licence-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Licence Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/licence-preview.tsx"></script>+ </body>+</html>diff --git a/server/enterprise.ts b/server/enterprise.tsindex 87da48c7a2..7bcdc48516 100644--- a/server/enterprise.ts+++ b/server/enterprise.ts@@ -2,6 +2,7 @@// core never imports it statically. Its one obligation is `register()`, turning a licence key into entitlements. The key// comes from <data>/license.key, OMB_LICENSE_KEY or the kept copy of the last one accepted (license-source.ts), and is// read again while a server install runs.+import { timingSafeEqual } from "node:crypto";import { existsSync } from "node:fs";import { join } from "node:path";import { pathToFileURL } from "node:url";@@ -10,6 +11,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";import type { RequestAuth } from "./request-auth.ts";import type { SessionRegistry } from "./sessions.ts";+import { licenseStateProof } from "./license-proof.ts";import { LAST_GOOD_FILE, LICENSE_FILE, licenseFilePath, readLicenseFile, writeLastGood, type LicenseFileRead, type LicenseSource } from "./license-source.ts";import { SERVER_ROOT } from "./proxy-paths.ts";@@ -67,7 +69,10 @@ type Register = (options: { licenseKey: string; graceDays: number }) => unknown;/** What the last load saw, so a re-read uses the same layer, data folder and environment key. */let loaded: { entry: string | undefined; dataDir: string | undefined; envKey: string | undefined; keyAtStart: boolean; register?: Register } | null = null;/** The licence in force beyond what EditionStatus carries; kept out of /api/edition, which bot shells may read. */-let held: { source: LicenseSource; layer: Layer } | null = null;+let held: { source: LicenseSource; layer: Layer; proof: string } | null = null;+/** licenseStateProof of each licence the last read accepted, and of the one in force: what the connector may present. */+let acceptedProofs: ReadonlySet<string> = new Set();+let everOffered = false;let clockWarned: string | undefined;let lastChangeLog = Number.NEGATIVE_INFINITY;/** The last licence problem logged, so an hourly re-read of the same bad file logs it once. */@@ -135,6 +140,7 @@ export function createWorkspaceAccess(options: Omit<WorkspaceAccessOptions, "entfunction oss(notice?: string): EditionStatus {current = notice ? { edition: "oss", features: [], notice } : { edition: "oss", features: [] };held = null;+ acceptedProofs = new Set();return current;}@@ -159,6 +165,7 @@ export async function loadEnterpriseLayer(const entry = dirs.map(layerEntry).find((candidate) => candidate !== undefined);const reads = await readSources(options.dataDir);const keyGiven = reads.file.state !== "absent" || reads.lastGood.state !== "absent" || Boolean(envKey);+ everOffered = keyGiven;loaded = { entry, dataDir: options.dataDir, envKey, keyAtStart: keyGiven || options.serverInstall === true };if (!entry) {const named = reads.file.state !== "absent" ? `${licenseFilePath(options.dataDir!)} holds a licence` : "OMB_LICENSE_KEY is set";@@ -238,6 +245,7 @@ async function grant(reads: { file: LicenseFileRead; lastGood: LicenseFileRead }const problems: string[] = [];const offered: { key: string; source: LicenseSource }[] = [];for (const [read, source] of [[reads.file, "file"], [envKey ? { state: "present", key: envKey } as const : { state: "absent" } as const, "env"], [reads.lastGood, "last-good"]] as const) {+ if (read.state !== "absent") everOffered = true;if (read.state === "present") offered.push({ key: read.key, source });else if (read.state === "unreadable") problems.push(read.error);}@@ -253,13 +261,15 @@ async function grant(reads: { file: LicenseFileRead; lastGood: LicenseFileRead }problems.push(candidate.source === "env" ? message(error) : `the licence in ${licenseFilePath(dataDir!, candidate.source === "file" ? LICENSE_FILE : LAST_GOOD_FILE)} was refused: ${message(error)}`);}}+ const proofsOf = () => new Set([...accepted.map((candidate) => licenseStateProof(candidate.key)), ...(held ? [held.proof] : [])]);const best = accepted.reduce<(typeof accepted)[number] | undefined>((top, next) => !top || issuedOrder(next.layer, top.layer) > 0 ? next : top, undefined);const file = accepted.find((candidate) => candidate.source === "file");if (best && (!active || issuedOrder(best.layer, held!.layer) >= 0)) {const { layer } = best;const fileGone = active && held!.source === "file" && reads.file.state === "absent";current = { edition: "enterprise", customer: layer.customer, features: [...new Set(layer.features)].sort(), expiresAt: layer.expiresAt };- held = { source: best.source, layer };+ held = { source: best.source, layer, proof: licenseStateProof(best.key) };+ acceptedProofs = proofsOf();if (reads.file.state !== "absent" && best.source !== "file") {note(`${file ? `the licence in ${licenseFilePath(dataDir!)} was issued before the one in ${sourceName(best.source)}` : problems[0]}; using ${sourceName(best.source)} instead`, log);} else if (fileGone) note(`no licence in ${licenseFilePath(dataDir!)} any more; using ${sourceName(best.source)} instead`, log);@@ -272,6 +282,7 @@ async function grant(reads: { file: LicenseFileRead; lastGood: LicenseFileRead }const why = file && issuedOrder(file.layer, held!.layer) < 0 ? `the licence in ${licenseFilePath(dataDir!)} was issued before the one in force`: problems[0] ?? `no licence in ${licenseFilePath(dataDir!)} any more`;note(`${why}; keeping the licence in force until it expires`, log);+ acceptedProofs = proofsOf();return current;}if (!problems.length) return current;@@ -392,6 +403,27 @@ export function licenseState(now: number = Date.now()): LicenseState {};}+/** Whether this server reads licence files (a server install, or a server run from a checkout or npm), so has a licence+ * card and soft seats; false on a desktop, a Cloud home and a hosted workspace, which read OMB_LICENSE_KEY alone. */+export function licenseFilesUsed(): boolean {+ return Boolean(loaded?.dataDir);+}++/** Which licence `proof` (licenseStateProof) is of: the one in force, another this server accepted at its last read, or+ * none it knows. The MausBot connector presents it to read the licence state on a server where loopback is a service. */+export function licenseProofMatch(proof: string | undefined): "in-force" | "accepted" | null {+ if (!proof || !/^[0-9a-f]{64}$/.test(proof)) return null;+ const same = (known: string) => timingSafeEqual(Buffer.from(known), Buffer.from(proof));+ if (held && current.edition === "enterprise" && same(held.proof)) return "in-force";+ return [...acceptedProofs].some(same) ? "accepted" : null;+}++/** Whether this server has, or has had since it started, a licence on offer: license.key, OMB_LICENSE_KEY or the kept+ * copy, accepted or not. A server that never had one shows no licence card. */+export function licenseEverOffered(): boolean {+ return everOffered;+}+/** No countdown, grace date or operator notice for a non-admin session. */export function editionForMembers(status: EditionStatus): EditionStatus {const { expiresInDays: _days, graceEndsAt: _grace, notice: _notice, ...shared } = status;diff --git a/server/license-proof.test.ts b/server/license-proof.test.tsnew file mode 100644index 0000000000..b2f64ef228--- /dev/null+++ b/server/license-proof.test.ts@@ -0,0 +1,29 @@+import { generateKeyPairSync, sign } from "node:crypto";+import { describe, expect, it } from "vitest";++import { checkLicence, licenceProof } from "../connector/src/customer-run.ts";+import { licenseStateProof } from "./license-proof.ts";++// A throwaway signing pair, and a licence made as enterprise/server/license.ts issueLicenseKey makes one (base64url JSON+// claims, then the Ed25519 signature of that text): core is built and tested without enterprise/, so it is not imported.+const { privateKey } = generateKeyPairSync("ed25519");+const issue = (claims: Record<string, unknown>) => {+ const part = Buffer.from(JSON.stringify(claims), "utf8").toString("base64url");+ return `omb1.${part}.${sign(null, Buffer.from(part, "utf8"), privateKey).toString("base64url")}`;+};++describe("the licence a connected server is sent, as the connector and the server each see it", () => {+ it("passes the connector's shape check, and both sides make the same digest of it", () => {+ for (const claims of [+ { v: 1, customer: "Acme Analytical", features: ["budgets", "whitelabel"], issued: "2026-11-27", expires: "2026-12-30" },+ { v: 1, customer: "Acme Analytical", features: ["budgets", "whitelabel", "per-model-prices"], issued: "2026-11-27", expires: "2026-12-30",+ seats: 25, plan: "business-server", sub: "sub_0NsqTest", server: "5d0c6f2e-9c1a-4c57-8f0e-2b7a1d3e4f50", iat: 1_795_000_000_000 },+ ]) {+ const key = issue(claims);+ expect(checkLicence(key)).toBe(key);+ expect(licenseStateProof(key)).toBe(licenceProof(key));+ // The server reads the file trimmed; the connector writes it with a newline.+ expect(licenseStateProof(`${key}\n`)).toBe(licenceProof(key));+ }+ });+});diff --git a/server/license-proof.ts b/server/license-proof.tsnew file mode 100644index 0000000000..8b7113c743--- /dev/null+++ b/server/license-proof.ts@@ -0,0 +1,15 @@+// The MausBot connector's licence-state read on a connected server (routes/license.ts): it presents a digest of the+// licence it saved in the data folder, never the licence. Kept apart so request-auth.ts can name the header without+// loading the licence files' module.+import { createHash } from "node:crypto";++export const LICENSE_PROOF_HEADER = "x-openmausbot-licence-proof";+/** The connector names itself on its read (connector/src/customer-run.ts CONNECTOR_HEADER), so Settings shows the licence+ * card on a connected server before its first licence. It grants nothing. */+export const CONNECTOR_HEADER = "x-openmausbot-connector";++/** Proof that a caller holds a licence this server accepted, without sending the licence: the same digest the connector+ * computes (connector/src/customer-run.ts licenceProof). Whoever can make it could read the licence's claims anyway. */+export function licenseStateProof(key: string): string {+ return createHash("sha256").update(`omb-licence-state\n${key.trim()}`).digest("hex");+}diff --git a/server/license-seats.test.ts b/server/license-seats.test.tsnew file mode 100644index 0000000000..01b8a391ff--- /dev/null+++ b/server/license-seats.test.ts@@ -0,0 +1,123 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { SignInAllowList } from "./account-signin.ts";+import { loadEnterpriseLayer } from "./enterprise.ts";+import { registerSeatSources, seatInviteRefusal, seatLimit, seatsInUse } from "./license-seats.ts";+import type { RequestAuth } from "./request-auth.ts";+import { createConfigRoutes, type ConfigRouteDeps } from "./routes/config.ts";+import { createSeatsRoutes } from "./routes/seats.ts";++const dirs: string[] = [];+afterEach(async () => {+ await loadEnterpriseLayer({ dir: join(tmpdir(), "omb-enterprise-absent"), licenseKey: undefined });+ registerSeatSources(null);+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++const DAY = 24 * 60 * 60_000;+const day = (offset: number) => new Date(Date.now() + offset * DAY).toISOString().slice(0, 10);++/** A server whose enterprise layer accepts the licence with these claims; `files: false` is a desktop or a Cloud home. */+async function licensed(claims: { seats?: number; expiresAt?: string | null } = {}, options: { files?: boolean } = {}) {+ const layer = mkdtempSync(join(tmpdir(), "omb-seats-layer-"));+ const data = mkdtempSync(join(tmpdir(), "omb-seats-data-"));+ dirs.push(layer, data);+ mkdirSync(join(layer, "server"));+ const said = { customer: "Acme", features: ["budgets"], expiresAt: claims.expiresAt === undefined ? day(30) : claims.expiresAt, plan: "business-server", ...(claims.seats ? { seats: claims.seats } : {}) };+ writeFileSync(join(layer, "server", "index.js"), `export function register() { return ${JSON.stringify(said)}; }`);+ const key = "omb1.eyJjbGFpbXMiOnRydWV9.c2lnbmF0dXJl";+ if (options.files === false) await loadEnterpriseLayer({ dir: layer, licenseKey: key });+ else {+ writeFileSync(join(data, "license.key"), key);+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });+ }+}++/** The server's sign-in list and sessions, counted by routes/seats.ts as the running server counts them. */+function people(admins: string[], members: string[], sessions: { email?: string; token?: boolean; scopes?: string[] }[] = []) {+ const list: SignInAllowList = { admins, members };+ createSeatsRoutes({ signInList: () => list, sessions: () => sessions as never });+ return list;+}++describe("seats on a licensed server install", () => {+ it("has no limit without a licence, without a seats claim, past the grace period, or where licence files are not read", async () => {+ const more = { admins: ["[email protected]"], members: ["[email protected]", "[email protected]", "[email protected]"] };+ expect(seatLimit()).toBeNull();+ expect(seatInviteRefusal(more)).toBeNull();+ await licensed({});+ expect(seatLimit()).toBeNull();+ expect(seatInviteRefusal(more)).toBeNull();+ await licensed({ seats: 2, expiresAt: day(-30) });+ expect(seatLimit()).toBeNull();+ expect(seatInviteRefusal(more)).toBeNull();+ await licensed({ seats: 2 }, { files: false });+ expect(seatLimit()).toBeNull();+ expect(seatInviteRefusal(more)).toBeNull();+ });++ it("lets people in up to the plan's seats and refuses the invite past them", async () => {+ await licensed({ seats: 3 });+ people(["[email protected]"], ["[email protected]"]);+ expect(seatsInUse()).toBe(2);+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]"] })).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]", "[email protected]"] })).toEqual({ seats: 3, used: 2 });+ // An address already signed in through an @domain entry is a person already: listing it adds nobody.+ people(["[email protected]"], ["@acme.test"], [{ email: "[email protected]" }, { email: "[email protected]" }]);+ expect(seatsInUse()).toBe(3);+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["@acme.test", "[email protected]"] })).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["@acme.test", "[email protected]"] })).toEqual({ seats: 3, used: 3 });+ });++ it("locks nobody out: over the limit, removing someone, changing a role and saving the list as it is all pass", async () => {+ await licensed({ seats: 2 });+ const list = people(["[email protected]"], ["[email protected]", "[email protected]", "[email protected]"]);+ expect(seatsInUse()).toBe(4);+ expect(seatInviteRefusal(list)).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]", "[email protected]"], members: ["[email protected]", "[email protected]"] })).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]"] })).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]", "[email protected]"] })).toBeNull();+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]", "[email protected]", "[email protected]"] })).toEqual({ seats: 2, used: 4 });+ });++ it("counts a list the environment pins, so a patch that sends only the other list cannot leave those people out", async () => {+ await licensed({ seats: 4 });+ expect(seatInviteRefusal({ members: ["[email protected]", "[email protected]"] }, env)).toEqual({ seats: 4, used: 4 });+ expect(seatInviteRefusal({ members: ["[email protected]"] }, env)).toBeNull();+ // Without the pin the same patch would replace the admins too, and the count after it would be two.+ expect(seatInviteRefusal({ members: ["[email protected]", "[email protected]"] }, {})).toBeNull();+ });++ it("keeps the last licence's seats during the grace period", async () => {+ await licensed({ seats: 2, expiresAt: day(-3) });+ people(["[email protected]"], ["[email protected]"]);+ expect(seatLimit()).toBe(2);+ expect(seatInviteRefusal({ admins: ["[email protected]"], members: ["[email protected]", "[email protected]"] })).toEqual({ seats: 2, used: 2 });+ });++ it("answers an invite past the seats with a plain sentence and saves nothing", async () => {+ await licensed({ seats: 2 });+ people(["[email protected]"], ["[email protected]"]);+ const replies: { status: number; body: unknown }[] = [];+ const route = createConfigRoutes({} as unknown as ConfigRouteDeps);+ const auth: RequestAuth = { kind: "session", session: { id: "owner", scopes: ["admin", "client"] } as never, via: "cookie", scopes: ["admin", "client"] };+ await route({+ req: { headers: {} }, res: {}, url: new URL("http://host/api/config"), path: "/api/config", method: "PUT", auth,+ json: (_res: unknown, status: number, body: unknown) => { replies.push({ status, body }); },+ readBody: async () => ({ signIn: { admins: ["[email protected]"], members: ["[email protected]", "[email protected]"] } }),+ } as unknown as Parameters<typeof route>[0]);+ expect(replies).toEqual([{+ status: 409,+ body: {+ error: "This server's plan has 2 seats, and 2 people can already sign in. Add seats from your MausBot account, then invite again.",+ errorKey: "serverError.seats.full", errorParams: { seats: "2", used: "2" }, code: "seats_full",+ },+ }]);+ });+});diff --git a/server/license-seats.ts b/server/license-seats.tsnew file mode 100644index 0000000000..c6cdde498c--- /dev/null+++ b/server/license-seats.ts@@ -0,0 +1,59 @@+// Seats on a licensed server install, soft: when the people who can sign in (routes/seats.ts seatCount) would go past the+// licence's `seats`, a new invite is refused and admins see a banner. Nobody already in is locked out: removing someone,+// changing a role and saving the list as it is always work, and sign-in itself is never checked here. No licence, a+// licence without `seats`, a licence past its grace period, a desktop or a Cloud home: no limit.+import { parseAllowList, type SignInAllowList } from "./account-signin.ts";+import { licenseFilesUsed, licenseState } from "./enterprise.ts";+import { signInFromEnv } from "./sign-in-env.ts";++/** The count of people routes/seats.ts makes, now and with another sign-in list in place of this server's. */+export interface SeatSources {+ used(): number;+ usedWith(list: SignInAllowList): number;+ /** The `@domain` entries on the sign-in list: anyone there can sign in, and counts once they have. */+ domains(): string[];+}++let sources: SeatSources | null = null;++/** routes/seats.ts registers the server's one sign-in list and session registry when its route is made (null: none, for tests). */+export function registerSeatSources(next: SeatSources | null): void {+ sources = next;+}++/** The sign-in list's `@domain` entries, for the seat banner. */+export function seatDomains(): string[] {+ return sources?.domains() ?? [];+}++/** How many people can sign in now; null before the server registered its sources. */+export function seatsInUse(): number | null {+ return sources ? sources.used() : null;+}++/** The licence's seats while it is in force (grace included) on a server that reads licence files; null: no limit. */+export function seatLimit(state = licenseState()): number | null {+ return licenseFilesUsed() && state.valid && state.seats !== null ? state.seats : null;+}++export interface SeatRefusal {+ seats: number;+ used: number;+}++/** Why saving `next` as the sign-in list is refused: it adds people, and the count after it would pass the licence's seats.+ * A list as long or shorter than before always passes, so a server already over its seats can still be tidied. Up to and+ * including `seats` people may sign in. The count after is of the list the server would then go by: what is saved+ * (`next` replaces both lists) with a list the environment pins in its place (sign-in-env.ts), so a patch that sends one+ * list cannot leave pinned people out of the count. */+export function seatInviteRefusal(next: { admins?: readonly string[]; members?: readonly string[] } | undefined, env: NodeJS.ProcessEnv = process.env): SeatRefusal | null {+ if (!next || !sources) return null;+ const limit = seatLimit();+ if (limit === null) return null;+ const used = sources.used();+ const pinned = signInFromEnv(env);+ const after = sources.usedWith({+ admins: parseAllowList((pinned.admins ?? next.admins)?.join(",")), members: parseAllowList((pinned.members ?? next.members)?.join(",")),+ });+ return after > used && after > limit ? { seats: limit, used } : null;+}diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 2f7bbe4f19..a7604f329c 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -781,6 +781,20 @@ describe("loopback trust: owner on one person's machine, service on a shared worexpect(check("GET", "/api/health/engines", { trust: "service", headers: { "x-forwarded-for": "203.0.113.9" } }).auth).toBeNull();});+ it("passes the MausBot connector's licence-state read on a service-trust server to its route, which checks the digest, and nothing else", () => {+ const proof = "ab".repeat(32);+ const headers = { "x-openmausbot-licence-proof": proof };+ expect(check("GET", "/api/license", { trust: "service", headers }).auth).toEqual({ kind: "loopback", scopes: ["client"], trust: "service" });+ expect(check("GET", "/api/license", { trust: "service" }).auth).toBeNull();+ expect(check("GET", "/api/license", { trust: "service", headers: { "x-openmausbot-licence-proof": "omb1.the.licence" } }).auth).toBeNull();+ expect(check("POST", "/api/license", { trust: "service", headers }).auth).toBeNull();+ expect(check("PUT", "/api/config", { trust: "service", headers }).auth).toBeNull();+ expect(check("GET", "/api/license", { trust: "service", headers: { ...headers, "x-forwarded-for": "203.0.113.9" } }).auth).toBeNull();+ for (const path of ["/api/config", "/api/license/x", "/api/licensex", "/api/license/", "/api/auth/pairing"]) {+ expect(check("GET", path, { trust: "service", headers }).auth, path).toBeNull();+ }+ });+it("still admits a real session with its own scopes on a service-trust server", () => {const admin = sessions.issue({ label: "Laptop", scopes: ["admin", "client"] });const member = sessions.issue({ label: "Phone", scopes: ["client"] });diff --git a/server/request-auth.ts b/server/request-auth.tsindex b74edabee1..5b515d121c 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -6,6 +6,7 @@ import { timingSafeEqual } from "node:crypto";import { isIP } from "node:net";import { BOT_PROFILE_PATCH_FIELDS } from "./bot-profile.ts";+import { LICENSE_PROOF_HEADER } from "./license-proof.ts";import type { Scope, SessionRecord, SessionRegistry } from "./sessions.ts";import { denyReason as companionDenial, isCompanionNotice } from "../companion/src/routes.ts";@@ -59,6 +60,12 @@ export const SERVICE_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Re{ methods: ["POST"], path: /^\/api\/testing\/internal-capability$/ }, // exists only with its private key];+/** `GET /api/license` carrying a licence-state proof (license-source.ts licenseStateProof): passed on to the route, which+ * checks the proof. Without the header, or with anything but a digest in it, the request is a bot shell's like any other. */+export function connectorLicenseRead(method: string, path: string, proof: string | undefined): boolean {+ return method.toUpperCase() === "GET" && path === "/api/license" && typeof proof === "string" && /^[0-9a-f]{64}$/.test(proof.trim());+}+export function serviceAllowed(method: string, path: string): boolean {const upper = method.toUpperCase();return SERVICE_ALLOW.some((rule) => rule.methods.includes(upper) && rule.path.test(path));@@ -750,6 +757,11 @@ export function resolveRequestAuth(req: IncomingMessage, options: ResolveOptions) {return { auth: { kind: "loopback", scopes: LOOPBACK_SCOPES }, status: 401, error: "" };}+ // The MausBot connector's licence-state read: it reaches the route, which answers only a digest of a licence this+ // server accepted (routes/license.ts), and with six fields of state, never the licence.+ if (connectorLicenseRead(method, path, headerValue(req.headers[LICENSE_PROOF_HEADER]))) {+ return { auth: { kind: "loopback", scopes: SERVICE_SCOPES, trust: "service" }, status: 401, error: "" };+ }// On a shared server "local" includes every bot's shell: default deny outside SERVICE_ALLOW.if (!serviceAllowed(method, path)) {return deny(403, "forbidden: on this shared server a local request without a session may only use the service routes; sign in to change settings, people or access");diff --git a/server/routes/config.ts b/server/routes/config.tsindex ad7287406c..575dfd3577 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -1,5 +1,6 @@import { liveSavePatch } from "../live-config.ts";import { signInEnvRefusal } from "../sign-in-env.ts";+import { seatInviteRefusal } from "../license-seats.ts";import * as boat from "../boat.ts";import { boatCreateRecoverySnapshot, retireDeletedBoatCreate } from "../boat-create-idempotency.ts";import { boatDeletionSnapshot } from "../boat-delete-journal.ts";@@ -176,6 +177,8 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {// Saved, it would be overruled by the environment at once: say so instead of answering 200 with nothing changed.const signInPinned = signInEnvRefusal(patch.signIn);if (signInPinned) return json(res, 409, { error: signInPinned, code: "signin_env" });+ const seatsFull = seatInviteRefusal(patch.signIn);+ if (seatsFull) return json(res, 409, { ...userError("serverError.seats.full", { seats: String(seatsFull.seats), used: String(seatsFull.used) }), code: "seats_full" });if (patch.newBotDefaults) {if (patch.newBotDefaults.profile.modelSelection) {const checked = checkedModelSelection(patch.newBotDefaults.profile.modelSelection);diff --git a/server/routes/license.test.ts b/server/routes/license.test.tsindex f5bf34ce82..770f93a41b 100644--- a/server/routes/license.test.ts+++ b/server/routes/license.test.ts@@ -8,7 +8,9 @@ import { afterEach, describe, expect, it } from "vitest";import { loadEnterpriseLayer } from "../enterprise.ts";import { json, readBody } from "../harness/http.ts";import { requiredScope, serviceAllowed, type RequestAuth } from "../request-auth.ts";-import { LICENSE_PATH, licenseRoutes } from "./license.ts";+import { licenseStateProof, LICENSE_PROOF_HEADER } from "../license-proof.ts";+import { registerSeatSources } from "../license-seats.ts";+import { LICENSE_PATH, licenseRoutes, resetLicenseRouteForTests } from "./license.ts";import { dispatchRoutes, ROUTES } from "./table.ts";const servers: Server[] = [];@@ -16,6 +18,8 @@ const dirs: string[] = [];afterEach(async () => {await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));await loadEnterpriseLayer({ dir: join(tmpdir(), "omb-enterprise-absent"), licenseKey: undefined });+ resetLicenseRouteForTests();+ registerSeatSources(null);for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });});@@ -74,6 +78,7 @@ describe("GET /api/license", () => {expect(await (await fetch(`${base}/api/license`)).json()).toEqual({valid: false, source: null, customer: null, plan: null, seats: null, features: [],expiresAt: null, expiresInDays: null, graceEndsAt: null, graceDaysLeft: null, notice: null,+ seatsUsed: null, seatDomains: [], files: false, connected: false, shown: false,});});@@ -85,4 +90,87 @@ describe("GET /api/license", () => {expect(await response.text()).not.toContain("valid");}});++ async function licensed(key = "omb1.eyJjbGFpbXMiOnRydWV9.c2lnbmF0dXJl") {+ const layer = mkdtempSync(join(tmpdir(), "omb-license-route-layer-"));+ const data = mkdtempSync(join(tmpdir(), "omb-license-route-data-"));+ dirs.push(layer, data);+ mkdirSync(join(layer, "server"));+ writeFileSync(join(layer, "server", "index.js"),+ `export function register() { return { customer: "Acme Analytical", features: ["budgets"], expiresAt: "2099-01-01", seats: 20, plan: "business-server" }; }`);+ writeFileSync(join(data, "license.key"), key);+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });+ return key;+ }+ const service: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };++ it("answers the MausBot connector on a shared server six fields of state, only for a digest of a licence this server accepted", async () => {+ const key = await licensed();+ const base = await serve(service);+ const read = (proof?: string) => fetch(`${base}/api/license`, proof === undefined ? {} : { headers: { [LICENSE_PROOF_HEADER]: proof } });+ const answer = await read(licenseStateProof(key));+ expect(answer.status).toBe(200);+ const text = await answer.text();+ expect(JSON.parse(text)).toEqual({ valid: true, plan: "business-server", seats: 20, expiresAt: "2099-01-01", graceDaysLeft: null, source: "file" });+ for (const hidden of ["Acme", "budgets", "omb1", "c2lnbmF0dXJl", "seatsUsed"]) expect(text).not.toContain(hidden);+ // A bot's shell knows no licence: a digest of anything else, the key itself, or nothing is refused.+ for (const proof of [undefined, "", licenseStateProof("omb1.other.licence"), key, "0".repeat(64)]) {+ const refused = await read(proof);+ expect(refused.status, String(proof)).toBe(403);+ expect(await refused.text()).not.toContain("valid");+ }+ });++ it("refuses a valid digest from a member's session, and on a place that reads no licence files", async () => {+ const key = await licensed();+ const proof = { [LICENSE_PROOF_HEADER]: licenseStateProof(key) };+ const member = await serve(session(["client"]));+ const refused = await fetch(`${member}/api/license`, { headers: proof });+ expect(refused.status).toBe(403);+ expect(await refused.text()).not.toContain("valid");+ // A desktop or a Cloud home reads OMB_LICENSE_KEY alone (no data folder): the same digest of the same licence opens nothing.+ const layer = mkdtempSync(join(tmpdir(), "omb-license-route-layer-"));+ dirs.push(layer);+ mkdirSync(join(layer, "server"));+ writeFileSync(join(layer, "server", "index.js"), `export function register() { return { customer: "Acme", features: [], expiresAt: "2099-01-01", seats: 20 }; }`);+ await loadEnterpriseLayer({ dir: layer, licenseKey: key });+ const desktop = await serve(service);+ expect((await fetch(`${desktop}/api/license`, { headers: proof })).status).toBe(403);+ });++ it("shows the licence card only on a server that reads licence files and has had a licence, or that the connector reads", async () => {+ const base = await serve(session(["admin", "client"]));+ const shown = async () => ((await (await fetch(`${base}/api/license`)).json()) as { shown: boolean }).shown;+ // A free server that never had a licence: nothing new.+ const data = mkdtempSync(join(tmpdir(), "omb-license-route-data-"));+ const layer = mkdtempSync(join(tmpdir(), "omb-license-route-layer-"));+ dirs.push(data, layer);+ mkdirSync(join(layer, "server"));+ writeFileSync(join(layer, "server", "index.js"), `export function register() { return { customer: "Acme", features: [], expiresAt: "2099-01-01" }; }`);+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined, serverInstall: true });+ expect(await shown()).toBe(false);+ // Connected: the connector's read through the owner's loopback.+ const owner = await serve({ kind: "loopback", scopes: ["admin", "client"] });+ await fetch(`${owner}/api/license`, { headers: { "x-openmausbot-connector": "customer-run" } });+ expect(await shown()).toBe(true);+ resetLicenseRouteForTests();+ // The same header from a bot's shell on a shared server, without a proof, is refused and changes nothing.+ await fetch(`${await serve(service)}/api/license`, { headers: { "x-openmausbot-connector": "customer-run" } });+ expect(await shown()).toBe(false);+ // A licence, even one this server refused, shows the card from then on.+ writeFileSync(join(data, "license.key"), "omb1.not.genuine");+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined, serverInstall: true });+ expect(await shown()).toBe(true);+ });++ it("tells the owner the seats in use, that this server reads licence files, and whether the connector delivered the licence", async () => {+ registerSeatSources({ used: () => 23, usedWith: () => 23, domains: () => ["@acme.test"] });+ const key = await licensed();+ const owner = await serve(session(["admin", "client"]));+ expect(await (await fetch(`${owner}/api/license`)).json()).toMatchObject({ valid: true, seats: 20, seatsUsed: 23, seatDomains: ["@acme.test"], files: true, connected: false, shown: true });+ // The connector's read marks the licence as delivered by MausBot; an owner's own read with a digest counts as well.+ const connector = await serve(service);+ expect((await fetch(`${connector}/api/license`, { headers: { [LICENSE_PROOF_HEADER]: licenseStateProof(key) } })).status).toBe(200);+ expect(await (await fetch(`${owner}/api/license`)).json()).toMatchObject({ source: "file", connected: true });+ });});diff --git a/server/routes/license.ts b/server/routes/license.tsindex 64add68032..aa556cd917 100644--- a/server/routes/license.ts+++ b/server/routes/license.ts@@ -1,17 +1,66 @@// GET /api/license: the licence state for the owner's own Settings (plan, seats, expiry, grace left, where it was read// from, whether it is valid). Never the key: it is a credential, and bot shells never reach this route.-import { licenseState } from "../enterprise.ts";+//+// One more reader: the MausBot connector on a connected server reads the state from the server's loopback and reports it+// (connector/src/customer-run.ts). Where loopback is a service (a shared server, where every bot's shell is a local caller+// too) it has no session, so it presents LICENSE_PROOF_HEADER, a digest of the licence it saved here, and gets six fields+// back. Only a caller that holds a licence this server accepted can make that digest, and such a caller could read those+// fields from the licence itself: the allowance lets nobody else in.+import type { IncomingMessage } from "node:http";++import { licenseEverOffered, licenseFilesUsed, licenseProofMatch, licenseState, type LicenseState } from "../enterprise.ts";+import { CONNECTOR_HEADER, LICENSE_PROOF_HEADER } from "../license-proof.ts";+import { seatDomains, seatsInUse } from "../license-seats.ts";import { ownerOrAdmin } from "../request-auth.ts";import { PASS, type RouteContext } from "./table.ts";export const LICENSE_PATH = "/api/license";+/** The connector reads every 30 seconds; a licence it read this recently came from MausBot and is renewed by it. */+const CONNECTED_MS = 10 * 60_000;++let connectorReadAt: number | null = null;+/** The connector's last read of any kind that reached this route: the server is connected, licensed or not yet. */+let connectorSeenAt: number | null = null;++/** What the connector reports: the server's own judgement of its licence, never its customer, features or notice. */+export function licenseForConnector(state: LicenseState) {+ return { valid: state.valid, plan: state.plan, seats: state.seats, expiresAt: state.expiresAt, graceDaysLeft: state.graceDaysLeft, source: state.source };+}++/** What the owner's Settings shows: the state, how many people can sign in now, whether licence files are used here at all+ * (false on a desktop or a Cloud home), whether the licence in force is one the MausBot connector delivered and still+ * reads, and `shown`: whether Settings has a licence card at all. That is a server that reads licence files and has, or+ * has had, a licence, or that the connector reads; a free server that never had a licence shows nothing new. */+export function licenseForSettings(state: LicenseState, now: number = Date.now()) {+ const recent = (at: number | null) => at !== null && now - at < CONNECTED_MS;+ const connected = recent(connectorReadAt) && state.source === "file";+ const files = licenseFilesUsed();+ return { ...state, seatsUsed: seatsInUse(), seatDomains: seatDomains(), files, connected, shown: files && (licenseEverOffered() || state.source !== null || recent(connectorSeenAt)) };+}++const proofOf = (req: IncomingMessage): string | undefined => {+ const value = req.headers[LICENSE_PROOF_HEADER];+ return typeof value === "string" ? value.trim() : undefined;+};// A function declaration, not a const: table.ts lists it, and a declaration is ready even when this module is the one// imported first.-export async function licenseRoutes({ res, path, method, auth, json }: RouteContext): Promise<typeof PASS | void> {+export async function licenseRoutes({ req, res, path, method, auth, json }: RouteContext): Promise<typeof PASS | void> {if (path !== LICENSE_PATH) return PASS;if (method !== "GET") return json(res, 405, { error: "GET only" });- if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin sees this server's licence." });+ const match = licenseProofMatch(proofOf(req));+ if (match === "in-force") connectorReadAt = Date.now();+ // Only a read this route answers marks the server as connected: the owner's loopback, or a proof it accepts.+ const connector = req.headers[CONNECTOR_HEADER] === "customer-run";+ if (connector && (ownerOrAdmin(auth) || match)) connectorSeenAt = Date.now();res.setHeader("cache-control", "no-store");- return json(res, 200, licenseState());+ if (ownerOrAdmin(auth)) return json(res, 200, licenseForSettings(licenseState()));+ if (match && auth.kind === "loopback" && licenseFilesUsed()) return json(res, 200, licenseForConnector(licenseState()));+ return json(res, 403, { error: "Only the owner or an admin sees this server's licence." });+}++/** For tests: forget the connector's last read. */+export function resetLicenseRouteForTests(): void {+ connectorReadAt = null;+ connectorSeenAt = null;}diff --git a/server/routes/seats.ts b/server/routes/seats.tsindex 9fc86fb9e2..15715bfcb6 100644--- a/server/routes/seats.ts+++ b/server/routes/seats.ts@@ -1,10 +1,11 @@// GET /api/seats: how many people can sign in to this server. A number and nothing about who: the MausBot connector on// a connected server reads it from the server's own loopback and reports it, so a plan's seats can be counted.import type { SignInAllowList } from "../account-signin.ts";+import { registerSeatSources } from "../license-seats.ts";import type { PublicSession } from "../sessions.ts";import { PASS, type RouteHandler } from "./table.ts";-type SeatSession = Pick<PublicSession, "email" | "token"> & { scopes?: readonly string[] };+export type SeatSession = Pick<PublicSession, "email" | "token"> & { scopes?: readonly string[] };/*** People, not devices: each address on the sign-in list, and each address that holds a session (someone let in by an@@ -32,7 +33,13 @@ export interface SeatsRouteDeps {sessions(): readonly SeatSession[];}+/** Also hands the count to license-seats.ts, which limits invites on a licensed server: this route is made once, with the+ * server's one sign-in list and session registry. */export function createSeatsRoutes(deps: SeatsRouteDeps): RouteHandler {+ registerSeatSources({+ used: () => seatCount(deps.signInList(), deps.sessions()), usedWith: (list) => seatCount(list, deps.sessions()),+ domains: () => { const list = deps.signInList(); return [...new Set([...list.admins, ...list.members].filter((entry) => entry.startsWith("@")))]; },+ });return async ({ res, path, method, json }) => {if (path !== "/api/seats" || method !== "GET") return PASS;return json(res, 200, { seats: seatCount(deps.signInList(), deps.sessions()) });diff --git a/server/user-errors.ts b/server/user-errors.tsindex 2b06cc4bed..332831c711 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -17,6 +17,7 @@ export const USER_ERROR = {"serverError.email.notSetUp": "email sign-in is not set up on this server; use a pairing code","serverError.signIn.tooMany": "too many failed sign-in attempts from your address; try again in {seconds}s","serverError.cloud.personal": "My Cloud is personal: only your own devices can connect.",+ "serverError.seats.full": "This server's plan has {seats} seats, and {used} people can already sign in. Add seats from your MausBot account, then invite again.","serverError.model.botBusy": "the bot is working — stop it before changing models","serverError.model.accountUpdating": "this provider account is being updated — try again shortly","serverError.chat.busyEdit": "the thread is working — stop it before editing",diff --git a/src/components/LicenceCard.dom.test.ts b/src/components/LicenceCard.dom.test.tsnew file mode 100644index 0000000000..56793d2c55--- /dev/null+++ b/src/components/LicenceCard.dom.test.ts@@ -0,0 +1,119 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import { overSeats, readLicenceState, type LicenceState } from "@/lib/licence-state";+import { SettingsLook } from "./SettingsPrimitives";+import { LICENCE_PASTE_COMMAND, LicenceCard, LicenceRows, SeatLimitBanner } from "./LicenceCard";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const STATE: LicenceState = {+ valid: true, source: "file", plan: "business-server", seats: 20, expiresAt: "2026-12-31", expiresInDays: 34, graceEndsAt: "2027-01-14",+ graceDaysLeft: null, seatsUsed: 7, seatDomains: [], files: true, shown: true, connected: true,+};++let host: HTMLDivElement;+let root: Root;+const fetches: string[] = [];+let answer: unknown = STATE;++beforeEach(() => {+ setLocale("en");+ fetches.length = 0;+ answer = STATE;+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ fetches.push(String(input));+ return Response.json(answer);+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+});++const draw = (node: ReturnType<typeof createElement>) => act(() => root.render(createElement(SettingsLook.Provider, { value: true }, node)));+const text = () => host.textContent ?? "";++describe("the licence card", () => {+ it("shows the plan, where the licence came from, seats used of seats, the renewal date and the paste line", () => {+ draw(createElement(LicenceRows, { state: STATE }));+ expect(text()).toContain("Business (self-hosted)");+ expect(text()).toContain("Connected to MausBot, which renews it automatically");+ expect(text()).toContain("7 of 20 used");+ expect(text()).toContain("Renews");+ expect(text()).toContain("December 31, 2026");+ expect(host.querySelector("code")?.textContent).toBe(LICENCE_PASTE_COMMAND);+ expect(host.querySelectorAll("input, select, [role=switch]")).toHaveLength(0);+ });++ it("names a pasted file, says when it expires, and counts the days of grace left once it has", () => {+ draw(createElement(LicenceRows, { state: { ...STATE, connected: false } }));+ expect(text()).toContain("From a licence file saved on this server (license.key)");+ expect(text()).toContain("Expires");+ draw(createElement(LicenceRows, { state: { ...STATE, connected: false, expiresInDays: -4, graceDaysLeft: 10 } }));+ expect(text()).toContain("Expired");+ expect(text()).toContain("10 days of grace left. Licensed features stop on January 14, 2027");+ draw(createElement(LicenceRows, { state: { ...STATE, valid: false, connected: false, graceDaysLeft: 0, source: "last-good" } }));+ expect(text()).toContain("Licensed features are off. Bots, data and sign-in keep working.");+ expect(text()).toContain("From the copy this server kept of its last licence");+ });++ it("says so when there is no licence, and when there is no seat limit", () => {+ draw(createElement(LicenceRows, { state: { ...STATE, valid: false, source: null, plan: null, seats: null, expiresAt: null, expiresInDays: null, graceEndsAt: null, connected: false } }));+ expect(text()).toContain("No licence");+ expect(text()).toContain("Add a licence by hand");+ draw(createElement(LicenceRows, { state: { ...STATE, seats: null } }));+ expect(text()).toContain("7 in use, no limit");+ });++ it("reads GET /api/license only when asked to, and shows nothing for a place that reads no licence files", async () => {+ draw(createElement(LicenceCard, { enabled: false }));+ await act(async () => {});+ expect(fetches).toEqual([]);+ expect(text()).toBe("");+ answer = { ...STATE, files: false };+ draw(createElement(LicenceCard, { enabled: true }));+ await act(async () => {});+ expect(fetches.some((url) => url.endsWith("/api/license"))).toBe(true);+ expect(text()).toBe("");+ expect(readLicenceState({ ...STATE, files: false })).toBeNull();+ // A free server install that never had a licence: no card either.+ answer = { ...STATE, valid: false, source: null, plan: null, seats: null, expiresAt: null, shown: false };+ draw(createElement(LicenceCard, { enabled: true }));+ await act(async () => {});+ expect(text()).toBe("");+ expect(readLicenceState(answer)).toBeNull();+ });+});++describe("the seat banner", () => {+ it("shows for an admin when more people can sign in than the plan has seats, and never otherwise", async () => {+ answer = { ...STATE, seatsUsed: 23 };+ draw(createElement(SeatLimitBanner, { enabled: true }));+ await act(async () => {});+ expect(host.querySelector("[data-seat-banner]")?.textContent).toBe(+ "This server counts 23 people, more than the 20 seats on its plan. New invites wait until seats are added from your MausBot account. Nobody is signed out.",+ );+ answer = { ...STATE, seatsUsed: 23, seatDomains: ["@acme.example", "@lab.acme.example"] };+ draw(createElement(SeatLimitBanner, { enabled: false }));+ draw(createElement(SeatLimitBanner, { enabled: true }));+ await act(async () => {});+ expect(host.querySelector("[data-seat-banner]")?.textContent).toContain(+ "Nobody is signed out. Anyone with an address at acme.example, lab.acme.example can still sign in, and counts once they have.",+ );+ expect(overSeats({ ...STATE, seatsUsed: 20 })).toBeNull();+ expect(overSeats({ ...STATE, seatsUsed: 23, valid: false })).toBeNull();+ expect(overSeats({ ...STATE, seatsUsed: 23, seats: null })).toBeNull();+ fetches.length = 0;+ draw(createElement(SeatLimitBanner, { enabled: false }));+ await act(async () => {});+ expect(host.querySelector("[data-seat-banner]")).toBeNull();+ });+});diff --git a/src/components/LicenceCard.tsx b/src/components/LicenceCard.tsxnew file mode 100644index 0000000000..6b4a1f3284--- /dev/null+++ b/src/components/LicenceCard.tsx@@ -0,0 +1,100 @@+// A server install's licence in its admins' Settings: plan, seats, renewal or expiry, grace left, where the licence came+// from, and how to put one in by hand. Read-only. The seat banner beside the licence expiry notice says when more people+// can sign in than the plan has seats. A desktop and a Cloud home show neither (their GET /api/license says `files: false`).+import { AlertTriangle } from "lucide-react";+import { namesLocale } from "@/lib/clock-time";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { overSeats, useLicenceState, type LicenceState } from "@/lib/licence-state";+import { CommandLine, SettingRow, SettingsGroup, SettingsRows } from "./SettingsPrimitives";++/** The installer's own paste line (deploy/install.sh), so the licence stays out of the shell's history. */+export const LICENCE_PASTE_COMMAND = `cd /opt/openmausbot && sudo docker compose exec -T omb sh -c 'umask 077; cat > "$OMB_DATA_DIR/license.key"' < licence.txt`;++const PLAN_NAMES: Record<string, Parameters<typeof t>[0]> = { "business-server": "settings.licence.plan.businessServer" };++/** "2026-12-31" in the reader's language, read as that calendar day wherever the reader is. */+export function licenceDate(day: string): string {+ const at = new Date(`${day}T00:00:00Z`);+ if (Number.isNaN(at.getTime())) return day;+ try {+ return at.toLocaleDateString(namesLocale(), { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });+ } catch {+ return day;+ }+}++function planName(state: LicenceState): string {+ if (!state.plan) return t("settings.licence.plan.other");+ const key = PLAN_NAMES[state.plan];+ return key ? t(key) : state.plan;+}++function sourceLine(state: LicenceState): string {+ if (state.source === "file") return t(state.connected ? "settings.licence.source.connected" : "settings.licence.source.file");+ if (state.source === "env") return t("settings.licence.source.env");+ return t("settings.licence.source.lastGood");+}++const value = (text: string, tone?: "warning" | "danger") => (+ <span className={cn("text-[13px] leading-5 tabular-nums", tone === "danger" ? "text-danger" : tone === "warning" ? "text-warning" : "text-ink-secondary")}>{text}</span>+);++function DateRow({ state }: { state: LicenceState }) {+ if (state.expiresAt === null) return <SettingRow title={t("settings.licence.expires")}>{value(t("settings.licence.never"))}</SettingRow>;+ const date = licenceDate(state.expiresAt);+ if (!state.valid) {+ return <SettingRow title={t("settings.licence.expired")} message={<span className="text-danger">{t("settings.licence.lapsed")}</span>}>{value(date, "danger")}</SettingRow>;+ }+ if (state.graceDaysLeft !== null) {+ const days = state.graceDaysLeft;+ const message = t(days === 1 ? "settings.licence.graceOne" : "settings.licence.grace", { days, date: state.graceEndsAt ? licenceDate(state.graceEndsAt) : "" });+ return <SettingRow title={t("settings.licence.expired")} message={<span className="text-danger">{message}</span>}>{value(date, "danger")}</SettingRow>;+ }+ return state.connected+ ? <SettingRow title={t("settings.licence.renews")} subtitle={t("settings.licence.renewsLine")}>{value(date)}</SettingRow>+ : <SettingRow title={t("settings.licence.expires")}>{value(date)}</SettingRow>;+}++/** The card itself, for a state already read (the Overview page reads it; the picture harness hands one in). */+export function LicenceRows({ state }: { state: LicenceState }) {+ const held = state.valid || state.expiresAt !== null || state.source !== null;+ const over = overSeats(state);+ return (+ <SettingsGroup label={t("settings.licence.title")} block="licence">+ <SettingsRows>+ {held ? <>+ <SettingRow title={planName(state)} subtitle={sourceLine(state)}>{null}</SettingRow>+ <SettingRow title={t("settings.licence.seats")}+ message={over ? <span className="text-warning">{t("settings.licence.seatsOver")}</span> : undefined}>+ {value(state.seats === null+ ? t("settings.licence.seatsNoLimit", { used: state.seatsUsed ?? 0 })+ : t("settings.licence.seatsUsed", { used: state.seatsUsed ?? 0, seats: state.seats }), over ? "warning" : undefined)}+ </SettingRow>+ <DateRow state={state} />+ </> : <SettingRow title={t("settings.licence.none")} subtitle={t("settings.licence.noneLine")}>{null}</SettingRow>}+ <SettingRow title={t("settings.licence.pasteTitle")} subtitle={t("settings.licence.pasteLine")}+ message={<CommandLine command={LICENCE_PASTE_COMMAND} copyLabel={t("settings.licence.pasteCopy")} />}>{null}</SettingRow>+ </SettingsRows>+ </SettingsGroup>+ );+}++/** Overview's licence card: admins of a server install only. */+export function LicenceCard({ enabled }: { enabled: boolean }) {+ const state = useLicenceState(enabled);+ return enabled && state ? <LicenceRows state={state} /> : null;+}++/** Beside the licence expiry notice on every Settings page: more people can sign in than the plan has seats. */+export function SeatLimitBanner({ enabled }: { enabled: boolean }) {+ const over = overSeats(useLicenceState(enabled));+ if (!enabled || !over) return null;+ return (+ <div role="status" data-seat-banner="" className="flex items-start gap-2 rounded-xl border border-warning/40 bg-warning/10 px-3 py-2.5 text-[13px] leading-relaxed text-warning">+ <AlertTriangle size={14} className="mt-0.5 shrink-0" />+ <span>{t("settings.licence.banner", { used: over.used, seats: over.seats })}+ {over.domains.length > 0 && <> {t("settings.licence.bannerDomains", { domains: over.domains.map((domain) => domain.slice(1)).join(", ") })}</>}</span>+ </div>+ );+}diff --git a/src/components/PeopleSection.tsx b/src/components/PeopleSection.tsxindex 07b37c2bc9..ae3e168d06 100644--- a/src/components/PeopleSection.tsx+++ b/src/components/PeopleSection.tsx@@ -6,6 +6,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useCopyFeedback } from "@/lib/copy-text";import { formatUsd, hasFiniteCost } from "@/lib/usage";+import { LICENCE_CHANGED } from "../lib/licence-state";import { readMembership, type Membership } from "../lib/membership";import type { SessionState } from "../lib/session";import { readSharedSessionState } from "../lib/shared-session";@@ -232,14 +233,18 @@ export function PeopleSection({ simple = false, startOpen = false }: { simple?:});}, [load]);- const save = async (next: SignInLists) => {+ /** True once saved; a refusal (a seat limit, a list the environment pins) shows its sentence instead. */+ const save = async (next: SignInLists): Promise<boolean> => {setBusy(true);setError(null);try {await api("/api/config", { method: "PUT", body: JSON.stringify({ signIn: next }) });+ window.dispatchEvent(new Event(LICENCE_CHANGED));await load();+ return true;} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));+ return false;} finally {setBusy(false);}@@ -253,7 +258,7 @@ export function PeopleSection({ simple = false, startOpen = false }: { simple?:setError(t("remote.signInAccess.invalid"));return;}- await save(withEntry(lists, entry, role));+ if (!(await save(withEntry(lists, entry, role)))) return;setDraft("");setLink(inviteLink(base, entry));};diff --git a/src/components/SignInAccessCard.tsx b/src/components/SignInAccessCard.tsxindex 265cb91106..3966ca135e 100644--- a/src/components/SignInAccessCard.tsx+++ b/src/components/SignInAccessCard.tsx@@ -6,6 +6,7 @@ import type { SessionState } from "../lib/session";import { readSharedSessionState } from "../lib/shared-session";import { canPairDevices } from "./ServerPairingCard";import { Card } from "./SettingsPrimitives";+import { LICENCE_CHANGED } from "@/lib/licence-state";export interface SignInLists {admins: string[];@@ -69,6 +70,7 @@ export function SignInAccessCard() {try {await api("/api/config", { method: "PUT", body: JSON.stringify({ signIn: next }) });setLists(next);+ window.dispatchEvent(new Event(LICENCE_CHANGED));} catch (e) {setError(t("remote.signInAccess.error", { error: e instanceof Error ? e.message : String(e) }));} finally {diff --git a/src/components/settings/SettingsWindow.tsx b/src/components/settings/SettingsWindow.tsxindex a5f04b77b5..ecabab6b9f 100644--- a/src/components/settings/SettingsWindow.tsx+++ b/src/components/settings/SettingsWindow.tsx@@ -10,6 +10,7 @@ import { api, type ConfigStatus } from "@/state/store";import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useIsTopLayer } from "../Layer";import { LicenseExpiryBanner } from "../LicenseExpiryBanner";+import { SeatLimitBanner } from "../LicenceCard";import { shortcutLabel } from "../ShortcutHint";import { SettingsLook } from "../SettingsPrimitives";import { SettingsPageBody } from "./pages/SettingsPageBody";@@ -201,6 +202,7 @@ export function SettingsWindow() {<SettingsPageHeader page={page} ctx={ctx} place={place} narrow={narrow} missing={missing} peek={!ctx.advanced && !page.when(ctx) && !anchor} sub={sub} action={headerAction} /><div key={target.page} data-settings-page-body={target.page} className={cn("flex flex-col gap-6", narrow && "px-4")}><LicenseExpiryBanner config={config} />+ <SeatLimitBanner enabled={place.kind === "server" && ctx.admin && !ctx.client} />{page.owner === "place" && config === null? unreachable ? <SettingsUnreachable place={place.name} onRetry={() => void api<ConfigStatus>("/api/config").then((config) => dispatch({ type: "configStatus", config })).catch(() => {})} />: <><SettingsSkeletonCard place={place.name} /><SettingsSkeletonCard place={place.name} /></>diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsxindex b3316f8403..d341981918 100644--- a/src/components/settings/pages/PlacePages.tsx+++ b/src/components/settings/pages/PlacePages.tsx@@ -20,6 +20,7 @@ import { DisplayNameSetting } from "../../DisplayNameSetting";import { DefaultBotSidebarRow } from "../../DefaultBotControls";import { EnginesSettings } from "../../EnginesSettings";import { ImageGenerationSettings } from "../../ImageGenerationSettings";+import { LicenceCard } from "../../LicenceCard";import { LocalComputerSection } from "../../LocalComputerSection";import { McpCallTimeoutSettings } from "../../McpCallTimeoutSettings";import { DefaultBotSettings } from "../../NewBotDialog";@@ -86,6 +87,7 @@ export function OverviewPage() {</SettingsRows>)}{place.kind === "server" && !ctx.client && !window.ogb?.updater && <SettingsGroup label={t("settings.updates.title")} block="version"><SettingsRows><ServerUpdateRow title={versionLine()} /></SettingsRows></SettingsGroup>}+ {place.kind === "server" && !ctx.client && ctx.admin && <LicenceCard enabled />}<SettingsGroup label={t("settings.overview.glance")} block="glance"><SettingsRows>{!ctx.client && <SettingsLinkRow title={t("settings.page.devices")} value={phoneValue} onClick={() => go("devices", "phones")} data={{ "data-glance": "devices" }} />}diff --git a/src/lib/licence-state.ts b/src/lib/licence-state.tsnew file mode 100644index 0000000000..d94d72d6be--- /dev/null+++ b/src/lib/licence-state.ts@@ -0,0 +1,74 @@+// A server install's licence as its admins' Settings shows it (GET /api/license, owner or admin only): the licence card+// and the seat banner. A desktop and a Cloud home answer `files: false` and show neither.+import { useEffect, useState } from "react";+import { api } from "@/state/api";++export interface LicenceState {+ valid: boolean;+ source: "file" | "env" | "last-good" | null;+ plan: string | null;+ seats: number | null;+ expiresAt: string | null;+ expiresInDays: number | null;+ graceEndsAt: string | null;+ graceDaysLeft: number | null;+ /** How many people the seats count now (server/routes/seats.ts): each address on the sign-in list and each person who+ * has signed in. */+ seatsUsed: number | null;+ /** The sign-in list's `@domain` entries: anyone there can sign in, and counts once they have. */+ seatDomains: string[];+ /** This server reads licence files: false on a desktop and a Cloud home. */+ files: boolean;+ /** Settings has a licence card: a server that has, or has had, a licence, or that the connector reads. */+ shown: boolean;+ /** The licence in force came from MausBot through the connector, which still reads it. */+ connected: boolean;+}++/** Saving the sign-in list changes the seat count: Settings reads the licence again. */+export const LICENCE_CHANGED = "omb-licence-changed";++export function readLicenceState(value: unknown): LicenceState | null {+ if (!value || typeof value !== "object") return null;+ const said = value as Partial<LicenceState>;+ if (typeof said.valid !== "boolean" || said.files !== true || said.shown !== true) return null;+ const count = (n: unknown) => (typeof n === "number" && Number.isFinite(n) ? n : null);+ const text = (s: unknown) => (typeof s === "string" && s ? s : null);+ return {+ valid: said.valid,+ source: said.source === "file" || said.source === "env" || said.source === "last-good" ? said.source : null,+ plan: text(said.plan), seats: count(said.seats), expiresAt: text(said.expiresAt), expiresInDays: count(said.expiresInDays),+ graceEndsAt: text(said.graceEndsAt), graceDaysLeft: count(said.graceDaysLeft), seatsUsed: count(said.seatsUsed),+ seatDomains: Array.isArray(said.seatDomains) ? said.seatDomains.filter((entry): entry is string => typeof entry === "string" && entry.startsWith("@")) : [],+ files: true, shown: true, connected: said.connected === true,+ };+}++/** Over the plan's seats: invites are refused until seats are added. Only while the licence is in force. */+export function overSeats(state: LicenceState | null): { used: number; seats: number; domains: string[] } | null {+ if (!state?.valid || state.seats === null || state.seatsUsed === null || state.seatsUsed <= state.seats) return null;+ return { used: state.seatsUsed, seats: state.seats, domains: state.seatDomains };+}++/** The licence of the server this page belongs to, read when `enabled` (an admin on a server's page) and again after the+ * sign-in list changes; null until read, and for anyone else. */+export function useLicenceState(enabled: boolean): LicenceState | null {+ const [state, setState] = useState<LicenceState | null>(null);+ const [round, setRound] = useState(0);+ useEffect(() => {+ if (!enabled) return;+ const again = () => setRound((value) => value + 1);+ window.addEventListener(LICENCE_CHANGED, again);+ return () => window.removeEventListener(LICENCE_CHANGED, again);+ }, [enabled]);+ useEffect(() => {+ if (!enabled) {+ setState(null);+ return;+ }+ let live = true;+ void api("/api/license", { background: true }).then((value) => { if (live) setState(readLicenceState(value)); }).catch(() => { if (live) setState(null); });+ return () => { live = false; };+ }, [enabled, round]);+ return state;+}diff --git a/src/licence-preview.tsx b/src/licence-preview.tsxnew file mode 100644index 0000000000..cccaca9eee--- /dev/null+++ b/src/licence-preview.tsx@@ -0,0 +1,96 @@+// Dev-only: the real Settings window of a self-hosted server, as its admin sees it, served at /licence-preview.html; not in+// the packaged app. Every request is answered here, so it needs no server.+// ?state=connected|pasted|env|kept|grace|graceover|lapsed|over|domains|waiting|never|unlicensed&page=overview|people&skin=midnight|daylight&lang=pt-br+// `never`: a free server install that never had a licence (no card, as before the card existed). `waiting`: connected to+// MausBot, no licence yet. `unlicensed`: a server from before the card, or a desktop.+import { StrictMode, useEffect } from "react";+import { createRoot } from "react-dom/client";+import "./styles.css";++const params = new URLSearchParams(location.search);+const page = params.get("page") ?? "overview";+const state = params.get("state") ?? "connected";++const BASE = {+ valid: true, source: "file", customer: "Acme Analytical", plan: "business-server", seats: 20, features: ["budgets", "whitelabel"],+ expiresAt: "2026-12-31", expiresInDays: 34, graceEndsAt: "2027-01-14", graceDaysLeft: null, notice: null, seatsUsed: 14, seatDomains: [] as string[],+ files: true, shown: true, connected: true,+};+const GRACE = { connected: false, expiresAt: "2026-11-23", expiresInDays: -4, graceEndsAt: "2026-12-07", graceDaysLeft: 10 };+const NONE = { valid: false, source: null, customer: null, plan: null, seats: null, features: [], expiresAt: null, expiresInDays: null, graceEndsAt: null, seatsUsed: 3, connected: false };+const LICENCE: Record<string, unknown> = {+ connected: BASE,+ pasted: { ...BASE, connected: false },+ env: { ...BASE, source: "env", connected: false },+ kept: { ...BASE, source: "last-good", connected: false },+ grace: { ...BASE, ...GRACE },+ graceover: { ...BASE, ...GRACE, seatsUsed: 23 },+ lapsed: { ...BASE, valid: false, connected: false, features: [], expiresAt: "2026-10-31", expiresInDays: -27, graceEndsAt: "2026-11-14", graceDaysLeft: 0 },+ over: { ...BASE, seatsUsed: 23 },+ domains: { ...BASE, seatsUsed: 23, seatDomains: ["@acme.example"] },+ waiting: { ...BASE, ...NONE },+ never: { ...BASE, ...NONE, shown: false },+ unlicensed: { error: "not found" },+};+const PEOPLE = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];++const CONFIG = {+ composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Maya Shah", email: "[email protected]" }, features: { savedSteps: false },+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },+ edition: { edition: state === "unlicensed" || state === "none" ? "oss" : "enterprise", features: [] }, browserProfiles: [], managedPolicy: null,+ signIn: { admins: [PEOPLE[0]], members: PEOPLE.slice(1) }, membership: { authority: "local", pairingCodes: true },+};+const ANSWERS: Record<string, unknown> = {+ "/api/instances": { instances: [] }, "/api/config": CONFIG,+ "/api/auth/session": { kind: "session", id: "s1", label: "Chrome on Mac", email: PEOPLE[0], scopes: ["admin", "client"], expiresAt: 0 },+ "/api/auth/sessions": { sessions: PEOPLE.map((email, index) => ({ id: `s${index}`, email, lastSeenAt: Date.now() - index * 3_600_000, scopes: index === 0 ? ["admin", "client"] : ["client"] })), current: "s0" },+ "/api/routines": { routines: [], runs: [] }, "/api/webhooks": { webhooks: [], attempts: [] }, "/api/bots": { bots: [], groups: [] },+ "/api/usage": { groups: [] },+ "/api/license": LICENCE[state] ?? BASE,+};+const realFetch = window.fetch.bind(window);+window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input instanceof Request ? input.url : input), location.href);+ if (url.origin !== location.origin || !(url.pathname.startsWith("/api/") || url.pathname.startsWith("/.well-known/"))) return realFetch(input, init);+ if (url.pathname === "/.well-known/openmausbot/environment") {+ return Promise.resolve(Response.json({ environmentId: "5d0c6f2e-9c1a-4c57-8f0e-2b7a1d3e4f50", label: "acme", capabilities: { emailSignIn: true } }));+ }+ const status = url.pathname === "/api/license" && state === "unlicensed" ? 404 : 200;+ return Promise.resolve(new Response(JSON.stringify(ANSWERS[url.pathname] ?? {}), { status, headers: { "content-type": "application/json" } }));+};+class QuietEventSource {+ onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null;+ readyState = 1;+ constructor(readonly url: string) { setTimeout(() => this.onmessage?.({ data: JSON.stringify({ kind: "hello", resumed: false, cursor: "run:0" }) }), 50); }+ addEventListener() {} removeEventListener() {} close() {}+}+Object.assign(window, { EventSource: QuietEventSource });+try {+ localStorage.setItem("omb-advanced-mode", params.get("mode") === "advanced" ? "1" : "0");+} catch { /* blocked storage */ }++const [{ StoreProvider }, { useStoreDispatch, useStoreSelector }, { SettingsModal }, { applySkin, readSkin, SKIN_IDS }, { loadLocale }] = await Promise.all([+ import("@/state/store"), import("@/state/store-select"), import("@/components/SettingsModal"), import("@/lib/skins"), import("@/lib/i18n"),+]);++function SettingsView() {+ const loaded = useStoreSelector((app) => app.config !== null), open = useStoreSelector((app) => app.appSettingsOpen), dispatch = useStoreDispatch();+ useEffect(() => { if (loaded) dispatch({ type: "toggleAppSettings", open: true, section: page as never }); }, [loaded, dispatch]);+ // A phone-width window opens on the list of pages: open the page, as a person would.+ useEffect(() => {+ if (!open) return;+ const timer = setInterval(() => {+ if (document.querySelector("[data-settings-page-body]")) return clearInterval(timer);+ document.querySelector<HTMLElement>(`[data-settings-page="${page}"]`)?.click();+ }, 100);+ return () => clearInterval(timer);+ }, [open]);+ return open ? <SettingsModal /> : null;+}++const asked = params.get("skin");+applySkin((SKIN_IDS as readonly string[]).includes(asked ?? "") ? asked as Parameters<typeof applySkin>[0] : readSkin());+await loadLocale(params.get("lang") ?? "en");+createRoot(document.getElementById("root")!).render(<StrictMode><StoreProvider><SettingsView /></StoreProvider></StrictMode>);diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..e59d5631a7 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1333,6 +1333,32 @@"settings.close": "Close settings","settings.license.expiring": "This installation's enterprise license expires on {date} ({days} day(s) left). Renew the key to keep enterprise features.","settings.license.grace": "This installation's enterprise license expired on {date}. Enterprise features keep working until {graceEnd}; renew the key before then.",+ "settings.licence.title": "Licence",+ "settings.licence.plan.businessServer": "Business (self-hosted)",+ "settings.licence.plan.other": "Enterprise licence",+ "settings.licence.source.connected": "Connected to MausBot, which renews it automatically",+ "settings.licence.source.file": "From a licence file saved on this server (license.key)",+ "settings.licence.source.env": "From OMB_LICENSE_KEY in the server's .env file",+ "settings.licence.source.lastGood": "From the copy this server kept of its last licence",+ "settings.licence.seats": "Seats",+ "settings.licence.seatsUsed": "{used} of {seats} used",+ "settings.licence.seatsNoLimit": "{used} in use, no limit",+ "settings.licence.seatsOver": "New invites wait until seats are added from your MausBot account. Nobody is signed out.",+ "settings.licence.renews": "Renews",+ "settings.licence.renewsLine": "MausBot sends this server its next licence before then.",+ "settings.licence.expires": "Expires",+ "settings.licence.expired": "Expired",+ "settings.licence.never": "Never",+ "settings.licence.grace": "{days} days of grace left. Licensed features stop on {date}; bots, data and sign-in keep working.",+ "settings.licence.graceOne": "1 day of grace left. Licensed features stop on {date}; bots, data and sign-in keep working.",+ "settings.licence.lapsed": "Licensed features are off. Bots, data and sign-in keep working. Renew from your MausBot account.",+ "settings.licence.none": "No licence",+ "settings.licence.noneLine": "This server runs without a licence.",+ "settings.licence.pasteTitle": "Add a licence by hand",+ "settings.licence.pasteLine": "Without a connection to MausBot, download the licence from your MausBot account and run this on the server. It takes effect within a minute.",+ "settings.licence.pasteCopy": "Copy command",+ "settings.licence.banner": "This server counts {used} people, more than the {seats} seats on its plan. New invites wait until seats are added from your MausBot account. Nobody is signed out.",+ "settings.licence.bannerDomains": "Anyone with an address at {domains} can still sign in, and counts once they have.","settings.noMatch": "Nothing matches “{query}”","settings.section.general": "General","settings.section.organization": "Organization",@@ -9883,6 +9909,7 @@"serverError.email.notSetUp": "email sign-in is not set up on this server; use a pairing code","serverError.signIn.tooMany": "too many failed sign-in attempts from your address; try again in {seconds}s","serverError.cloud.personal": "My Cloud is personal: only your own devices can connect.",+ "serverError.seats.full": "This server's plan has {seats} seats, and {used} people can already sign in. Add seats from your MausBot account, then invite again.","serverError.model.botBusy": "the bot is working — stop it before changing models","serverError.model.accountUpdating": "this provider account is being updated — try again shortly","serverError.chat.busyEdit": "the thread is working — stop it before editing",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0dd3959498..3a4225c3b5 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1262,6 +1262,32 @@"settings.close": "Fechar as configurações","settings.license.expiring": "A licença empresarial desta instalação expira em {date} (dias restantes: {days}). Renove a chave para manter os recursos empresariais.","settings.license.grace": "A licença empresarial desta instalação expirou em {date}. Os recursos empresariais continuam funcionando até {graceEnd}; renove a chave antes disso.",+ "settings.licence.title": "Licença",+ "settings.licence.plan.businessServer": "Business (auto-hospedado)",+ "settings.licence.plan.other": "Licença empresarial",+ "settings.licence.source.connected": "Conectado ao MausBot, que a renova automaticamente",+ "settings.licence.source.file": "De um arquivo de licença salvo neste servidor (license.key)",+ "settings.licence.source.env": "De OMB_LICENSE_KEY no arquivo .env do servidor",+ "settings.licence.source.lastGood": "Da cópia que este servidor guardou da última licença",+ "settings.licence.seats": "Vagas",+ "settings.licence.seatsUsed": "{used} de {seats} em uso",+ "settings.licence.seatsNoLimit": "{used} em uso, sem limite",+ "settings.licence.seatsOver": "Novos convites aguardam até que vagas sejam adicionadas na sua conta MausBot. Ninguém é desconectado.",+ "settings.licence.renews": "Renova em",+ "settings.licence.renewsLine": "O MausBot envia a próxima licença a este servidor antes dessa data.",+ "settings.licence.expires": "Expira em",+ "settings.licence.expired": "Expirou em",+ "settings.licence.never": "Nunca",+ "settings.licence.grace": "Restam {days} dias de carência. Os recursos licenciados param em {date}; bots, dados e login continuam funcionando.",+ "settings.licence.graceOne": "Resta 1 dia de carência. Os recursos licenciados param em {date}; bots, dados e login continuam funcionando.",+ "settings.licence.lapsed": "Os recursos licenciados estão desligados. Bots, dados e login continuam funcionando. Renove na sua conta MausBot.",+ "settings.licence.none": "Sem licença",+ "settings.licence.noneLine": "Este servidor funciona sem licença.",+ "settings.licence.pasteTitle": "Adicionar uma licença manualmente",+ "settings.licence.pasteLine": "Sem conexão com o MausBot, baixe a licença na sua conta MausBot e execute isto no servidor. Ela vale em até um minuto.",+ "settings.licence.pasteCopy": "Copiar comando",+ "settings.licence.banner": "Este servidor conta {used} pessoas, mais do que as {seats} vagas do seu plano. Novos convites aguardam até que vagas sejam adicionadas na sua conta MausBot. Ninguém é desconectado.",+ "settings.licence.bannerDomains": "Qualquer pessoa com endereço em {domains} ainda pode entrar, e passa a contar depois que entra.","settings.noMatch": "Nenhum resultado para “{query}”","settings.section.general": "Geral","settings.section.organization": "Organização",@@ -9808,6 +9834,7 @@"serverError.email.notSetUp": "O login por e-mail não está configurado neste servidor. Use um código de pareamento.","serverError.signIn.tooMany": "Houve muitas tentativas de login sem sucesso a partir do seu endereço. Tente novamente em {seconds} s.","serverError.cloud.personal": "O Cloud é pessoal: só os seus dispositivos podem se conectar.",+ "serverError.seats.full": "O plano deste servidor tem {seats} vagas, e {used} pessoas já podem entrar. Adicione vagas na sua conta MausBot e convide de novo.","serverError.model.botBusy": "O bot está trabalhando. Pare o bot antes de trocar de modelo.","serverError.forkBusy": "Aguarde esta conversa terminar antes de criar uma bifurcação.","serverError.forkNoText": "Esta conversa ainda não tem uma mensagem de texto para usar como ponto de partida da bifurcação.",