Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Licence file with hourly re-read, subscription claims, 14-day grace and GET /api/license (#7761)

Milind Sonib2286fcc7aa3
diff --git a/compose.yaml b/compose.yaml
index d0361eb012..4b68c56cc1 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -30,6 +30,8 @@ services:
# "1": phones pair by QR through MausBot Relay (docs/phone-relay-server.md). Sign the
# container in once first: docker compose exec omb openmausbot login --relay
OMB_PHONE_RELAY: ${OMB_PHONE_RELAY:-}
+ # The licence; a license.key in the data folder (/data/.openmausbot) is read too, and the newer one wins.
+ OMB_LICENSE_KEY: ${OMB_LICENSE_KEY:-}
healthcheck:
test:
- CMD
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index c7112acd27..87bc8b2b83 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -54,6 +54,9 @@ services:
# "1": phones pair by QR through MausBot Relay (docs/phone-relay-server.md). Sign the
# container in once first: docker compose exec omb openmausbot login --relay
OMB_PHONE_RELAY:
+ # The licence, when .env sets it. A license.key in the data folder (/data/.openmausbot)
+ # is read first, and both are read again while the server runs.
+ OMB_LICENSE_KEY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
diff --git a/deploy/install.sh b/deploy/install.sh
index 51c2152897..907739d661 100755
--- a/deploy/install.sh
+++ b/deploy/install.sh
@@ -6,6 +6,11 @@
# ... | sudo sh -s -- --check --domain maus.example.com only checks the server; changes nothing
# ... | sudo sh -s -- --uninstall stops the server; keeps your data
# ... | sudo sh -s -- --domain maus.example.com <code> also connects the server to MausBot with a one-time code
+# ... | sudo OMB_LICENSE_KEY="$(cat licence.txt)" sh -s -- --domain maus.example.com also gives it its licence (kept in .env)
+#
+# A licence can also be put in later: the server reads license.key in its data folder (and OMB_LICENSE_KEY), checks the
+# file once a minute and takes a newer licence without a restart. From a file, so the licence stays out of your history:
+# cd /opt/openmausbot && sudo docker compose exec -T omb sh -c 'umask 077; cat > "$OMB_DATA_DIR/license.key"' < licence.txt
#
# Nothing runs until the last line calls main, so a download that is cut off part-way runs nothing. It sends no
# telemetry. The addresses it contacts are the ones the checks name: the image registries, Let's Encrypt, GitHub's
@@ -44,6 +49,7 @@ settings() {
DOMAIN=""
EMAIL=""
CODE=""
+ LICENSE_KEY="${OMB_LICENSE_KEY:-}"
INSTALL_DOCKER="${OMB_INSTALL_DOCKER:-}"
SANDBOX=yes
FAILED=0
@@ -82,6 +88,8 @@ usage() {
say " --dir PATH where the install lives (default /opt/openmausbot)"
say " --no-sandbox do not prepare this server for the bots' sandbox (only for a server you alone sign in to)"
say " <code> the one-time code MausBot shows, to also connect this server to MausBot"
+ say ""
+ say " A licence goes in as OMB_LICENSE_KEY after sudo: ... | sudo OMB_LICENSE_KEY=\"\$(cat licence.txt)\" sh -s -- --domain ..."
}
parse() {
@@ -128,6 +136,12 @@ parse() {
case "$CODE" in
*[!A-Za-z0-9-]*) fail "That code doesn't look right. Copy the install command from MausBot again." ;;
esac
+ case "$LICENSE_KEY" in
+ "") ;;
+ *[!A-Za-z0-9._-]*) fail "OMB_LICENSE_KEY doesn't look like a MausBot licence. Copy it again: it is one line starting with omb1." ;;
+ omb1.?*.?*) ;;
+ *) fail "OMB_LICENSE_KEY doesn't look like a MausBot licence. Copy it again: it is one line starting with omb1." ;;
+ esac
case "$INSTALL_DIR" in
/?*) ;;
*) fail "--dir needs a full path, like /opt/openmausbot." ;;
@@ -681,6 +695,8 @@ services:
OMB_SIGNIN_SMTP_FROM:
# "1": phones pair by QR through MausBot Relay. Sign in once: docker compose exec omb openmausbot login --relay
OMB_PHONE_RELAY:
+ # The licence, when .env sets it. A license.key in the data folder is read first, and again while the server runs.
+ OMB_LICENSE_KEY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
@@ -770,6 +786,7 @@ ENV
fi
set_env DOMAIN "$DOMAIN"
set_env OMB_IMAGE "$IMAGE"
+ if [ -n "$LICENSE_KEY" ]; then set_env OMB_LICENSE_KEY "$LICENSE_KEY"; fi
if [ -n "$EMAIL" ]; then
current=$(env_value OMB_SIGNIN_EMAILS)
case ",$(printf '%s' "$current" | tr -d ' ')," in
@@ -1100,10 +1117,26 @@ run_install() {
fi
if [ "$DOCKER_STATE" = missing ]; then offer_docker; fi
install_server
+ report_licence
if [ -n "$CODE" ]; then connect_server; fi
finish
}
+# When a licence was given, whether the server took it, in one line from its own edition notice. Never the licence:
+# the notice names what is wrong with a key, not the key, and a line that held it anyway is not printed.
+report_licence() {
+ [ -n "$LICENSE_KEY" ] || return 0
+ edition=$(compose exec -T omb curl -sf http://127.0.0.1:8799/api/edition 2>/dev/null || true)
+ case "$edition" in
+ *'"edition":"enterprise"'*) ok "The licence was accepted." ;;
+ *'"notice":"'*)
+ reason=$(printf '%s' "$edition" | tr -d '\r\n' | sed -n 's/.*"notice":"\([^"]*\)".*/\1/p' | cut -c1-300)
+ case "$reason" in *"$LICENSE_KEY"*) reason="see: cd $INSTALL_DIR && sudo docker compose logs omb" ;; esac
+ note "The licence was not accepted: $reason"
+ ;;
+ esac
+}
+
run_check() {
if [ -z "$DOMAIN" ]; then DOMAIN=$(env_value DOMAIN); fi
preflight
diff --git a/deploy/update.sh b/deploy/update.sh
index 3a274e7a47..56bce4030e 100755
--- a/deploy/update.sh
+++ b/deploy/update.sh
@@ -449,6 +449,8 @@ services:
OMB_SIGNIN_SMTP_FROM:
# "1": phones pair by QR through MausBot Relay. Sign in once: docker compose exec omb openmausbot login --relay
OMB_PHONE_RELAY:
+ # The licence, when .env sets it. A license.key in the data folder is read first, and again while the server runs.
+ OMB_LICENSE_KEY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index dfbac9ad15..689615916d 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -135,6 +135,28 @@ Add `--check` to only check the server. Running it again repairs;
writes and what it contacts are in
[Deploy on a VPS](deploy-vps.md#quick-start-one-command-on-your-own-domain).
+A licence goes in with the install, as `OMB_LICENSE_KEY` after `sudo` (it is
+kept in `/opt/openmausbot/.env`). Save the licence in a file first, so it does
+not end up in your shell history; the installer says whether it was accepted:
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/install.sh | sudo OMB_LICENSE_KEY="$(cat licence.txt)" sh -s -- --domain maus.example.com
+```
+
+Or put it in later, with no restart: the server also reads `license.key` in
+its data folder, checks it once a minute and takes a newer licence at once:
+
+```sh
+cd /opt/openmausbot && sudo docker compose exec -T omb sh -c 'umask 077; cat > "$OMB_DATA_DIR/license.key"' < licence.txt
+```
+
+When several licences are on offer (`license.key`, `OMB_LICENSE_KEY`, and the
+copy the server keeps of the last one it accepted, `license.last-good`), the
+one issued last wins. A file that is broken, missing or older never takes away
+the licence in force, not even across a restart: it is logged once, and the
+licence stays until its 14-day grace ends. To remove a licence, delete
+`license.key` and `license.last-good`, unset `OMB_LICENSE_KEY`, and restart.
+
By hand, on any system with Docker:
```sh
diff --git a/docs/verification/enterprise-license.md b/docs/verification/enterprise-license.md
index 3920ce5370..17e04e13fd 100644
--- a/docs/verification/enterprise-license.md
+++ b/docs/verification/enterprise-license.md
@@ -11,14 +11,25 @@
warning in the startup log, and a banner in Settings for admins. The dates
reach admin sessions only: a member's `/api/edition` and config leave out
`expiresInDays`, `graceEndsAt` and the notice.
-- For 7 days after it expires the entitlements keep working, with a notice,
+- For 14 days after it expires the entitlements keep working, with a notice,
`graceEndsAt` on `/api/edition`, and a banner saying until when. Then they
stop, without a restart. The key format and signature check are unchanged.
+- On a server install the key may be in `<data>/license.key`, in
+ `OMB_LICENSE_KEY`, or in `<data>/license.last-good` (the last one accepted);
+ the one issued last wins. The file is checked once a minute and everything
+ read hourly; a broken, missing or older file keeps the licence in force, even
+ across a restart, until its grace ends, logged once. Desktops, Cloud homes
+ and hosted workspaces read `OMB_LICENSE_KEY` alone, as before.
+- Optional `seats`, `plan`, `sub`, `server` and `iat` claims in the same
+ `omb1` / `v: 1` format, accepted by servers from before them.
+- `GET /api/license` (owner or admin): validity, source, plan, seats, expiry
+ and days of grace left, never the key.
## Driving it
```sh
pnpm exec vitest run server/enterprise.test.ts enterprise/server/register.test.ts
+pnpm exec vitest run enterprise/server/license.test.ts server/license-refresh.test.ts server/license-source.test.ts server/routes/license.test.ts
pnpm exec vitest run --no-file-parallelism server/license-expiry-api.test.ts server/hosted-access.test.ts
pnpm test:packaged-server
```
@@ -26,7 +37,7 @@ pnpm test:packaged-server
`server/enterprise.test.ts` builds each layout in a temporary directory and
checks which copy wins, the warning window, the grace period and the moment it
ends. `enterprise/server/register.test.ts` issues keys with a throwaway signing
-pair and checks the layer accepts a key that lapsed less than 7 days ago and
+pair and checks the layer accepts a key that lapsed less than 14 days ago and
refuses it after. `server/license-expiry-api.test.ts` boots the `control-omb`
fixture with a stand-in layer whose key expires in 12 days, expired 2 days
ago, or expires in 90 days, and reads `/api/edition`, the server log, and
diff --git a/enterprise/README.md b/enterprise/README.md
index 51e9822f75..d124d2b1f0 100644
--- a/enterprise/README.md
+++ b/enterprise/README.md
@@ -24,19 +24,49 @@ expires), signed with an Ed25519 key whose public half is baked into
`enterprise/server/license.ts`. Verification is offline, and one build serves
every customer, because the key decides the feature set rather than the code.
+On a server install the key may also be in `license.key` in the data folder
+(`OMB_DATA_DIR`; `/data/.openmausbot` in the Docker image). The server keeps a
+copy of the last licence it accepted in `license.last-good` (mode 0600), so a
+restart with a broken or missing file keeps a licence still in its paid
+period. Every candidate is verified; the one issued last wins (`issued`, then
+`iat` when both carry it, then the later expiry), the file first on a tie.
+While it runs, the server checks `license.key` once a minute (size, change
+time, inode) and reads everything every hour, at most once in 30 seconds. A
+licence in force is never replaced by one issued before it, nor dropped for a
+broken or missing file, until its grace ends; each such problem is logged
+once. The re-read runs on a server set up from the Docker image or the
+Podman service (as the installer sets one up), even before it has a licence,
+so a bought server's first licence, written later by the connector, loads
+without a restart; on another server (a checkout, npm) it runs when there
+was a licence at start. A desktop, a Cloud home and a hosted workspace (licensed by its
+operator's environment) read `OMB_LICENSE_KEY` alone, once at start, as before.
+
+Keys may also carry `seats`, `plan`, `sub` (subscription), `server` and `iat`
+(issue time, epoch ms) claims, in the same `omb1` / `v: 1` format: a server
+from before them ignores them, and a key without them works on every server.
+An issuer must validate claims with `validateClaims` from
+`enterprise/server/license.ts` before signing: a malformed optional claim makes
+a new server refuse the whole licence. `server` is carried, not yet checked.
+
`GET /api/edition` reports the outcome:
```json
{ "edition": "enterprise", "customer": "Acme", "features": ["budgets", "whitelabel"], "expiresAt": "2027-09-02", "expiresInDays": 12 }
-{ "edition": "enterprise", "customer": "Acme", "features": ["budgets", "whitelabel"], "expiresAt": "2027-09-02", "expiresInDays": -2, "graceEndsAt": "2027-09-09", "notice": "OMB_LICENSE_KEY expired on 2027-09-02; enterprise features keep working until 2027-09-09 while it is renewed" }
+{ "edition": "enterprise", "customer": "Acme", "features": ["budgets", "whitelabel"], "expiresAt": "2027-09-02", "expiresInDays": -2, "graceEndsAt": "2027-09-16", "notice": "OMB_LICENSE_KEY expired on 2027-09-02; enterprise features keep working until 2027-09-16 while it is renewed" }
{ "edition": "oss", "features": [], "notice": "enterprise layer disabled: OMB_LICENSE_KEY expired on 2027-09-02; renew it to keep enterprise features" }
```
+`GET /api/license`, for the owner or an admin only, reports the licence for
+Settings: `valid`, `source` (`file`, `env` or `last-good`), `customer`, `plan`, `seats`,
+`features`, `expiresAt`, `expiresInDays`, `graceEndsAt`, `graceDaysLeft`
+(once expired: whole days until the features stop, 0 after) and `notice`. It
+never includes the key.
+
`expiresInDays` is present whenever the key has an expiry; a non-admin
session's `/api/edition` leaves out `expiresInDays`, `graceEndsAt` and the
notice. From 30 days
before it, the server logs a warning at startup and admins see a banner in
-Settings. After the expiry date the features keep working for a 7-day grace
+Settings. After the expiry date the features keep working for a 14-day grace
period, with the notice above and a banner saying until when; then they stop,
without a restart. The key format and its signature check do not change: the
layer simply accepts a key that expired less than the grace period ago.
@@ -68,6 +98,8 @@ ahead of a feature landing.
```sh
node enterprise/scripts/issue-license.mjs keygen # once; prints the public key to add to license.ts
node enterprise/scripts/issue-license.mjs issue --customer "Acme" --features whitelabel,sso --expires 2027-09-02
+node enterprise/scripts/issue-license.mjs issue --customer "Acme" --features admin --expires 2027-01-03 \
+ --seats 20 --plan business-server --sub <subscription id> --server <server id> --iat 1795000000000
```
The signing key lives outside the repo (default
diff --git a/enterprise/scripts/issue-license.mjs b/enterprise/scripts/issue-license.mjs
index 54a4facca4..eca14de9a6 100644
--- a/enterprise/scripts/issue-license.mjs
+++ b/enterprise/scripts/issue-license.mjs
@@ -6,9 +6,13 @@
// part to append to LICENSE_PUBLIC_KEYS in enterprise/server/license.ts.
//
// node enterprise/scripts/issue-license.mjs issue --customer "Acme" --features whitelabel,sso \
-// [--expires 2027-09-02] [--key <path>]
-// Prints a key for OMB_LICENSE_KEY. Claims are visible to the customer
-// (base64url JSON); only the signature is secret-derived.
+// [--expires 2027-09-02] [--issued 2026-09-02] [--seats 20] [--plan business-server] \
+// [--sub <subscription id>] [--server <server id>] [--iat <epoch ms>] [--key <path>]
+// Prints a key for OMB_LICENSE_KEY or the server's <data>/license.key. Claims are visible to the customer
+// (base64url JSON); only the signature is secret-derived. --issued defaults to today; --seats, --plan, --sub,
+// --server and --iat (the issue time in epoch ms, which orders two keys issued the same day) are optional claims
+// that servers from before them ignore. Ed25519 signing is deterministic, so
+// the same claims and key always print the same licence: another issuer can be checked against this one.
//
// The private key never enters the repo, a chat, or a container image.
import { generateKeyPairSync } from "node:crypto";
@@ -55,18 +59,38 @@ if (command === "keygen") {
if (!existsSync(keyPath)) fail(`no signing key at ${keyPath}; run "keygen" first or pass --key`);
if (!opts.customer) fail("--customer is required (who the license is for)");
if (!opts.features) fail("--features is required (comma-separated entitlement ids, e.g. whitelabel,sso)");
+ let seats;
+ if (opts.seats !== undefined) {
+ seats = Number(opts.seats);
+ if (!/^[0-9]+$/.test(opts.seats) || !Number.isSafeInteger(seats) || seats < 1) fail("--seats must be a whole number of at least 1");
+ }
+ let iat;
+ if (opts.iat !== undefined) {
+ iat = Number(opts.iat);
+ if (!/^[0-9]+$/.test(opts.iat) || !Number.isSafeInteger(iat)) fail("--iat must be a time in epoch milliseconds");
+ }
const privateJwk = JSON.parse(readFileSync(keyPath, "utf8"));
- const key = issueLicenseKey(
- {
- v: 1,
- customer: opts.customer,
- features: opts.features.split(",").map((f) => f.trim()).filter(Boolean),
- issued: new Date().toISOString().slice(0, 10),
- expires: opts.expires ?? null,
- },
- privateJwk,
- );
+ let key;
+ try {
+ key = issueLicenseKey(
+ {
+ v: 1,
+ customer: opts.customer,
+ features: opts.features.split(",").map((f) => f.trim()).filter(Boolean),
+ issued: opts.issued ?? new Date().toISOString().slice(0, 10),
+ expires: opts.expires ?? null,
+ ...(seats !== undefined ? { seats } : {}),
+ ...(opts.plan !== undefined ? { plan: opts.plan } : {}),
+ ...(opts.sub !== undefined ? { sub: opts.sub } : {}),
+ ...(opts.server !== undefined ? { server: opts.server } : {}),
+ ...(iat !== undefined ? { iat } : {}),
+ },
+ privateJwk,
+ );
+ } catch (error) {
+ fail(`refused: ${error instanceof Error ? error.message : String(error)}`);
+ }
console.log(key);
} else {
- fail('usage: issue-license.mjs keygen [--out path] | issue --customer "Name" --features a,b [--expires YYYY-MM-DD] [--key path]');
+ fail('usage: issue-license.mjs keygen [--out path] | issue --customer "Name" --features a,b [--expires YYYY-MM-DD] [--issued YYYY-MM-DD] [--seats N] [--plan name] [--sub id] [--server id] [--iat ms] [--key path]');
}
diff --git a/enterprise/server/index.ts b/enterprise/server/index.ts
index ab943a7abb..5e56ec1a5f 100644
--- a/enterprise/server/index.ts
+++ b/enterprise/server/index.ts
@@ -7,6 +7,13 @@ export interface RegisteredLayer {
customer: string;
features: string[];
expiresAt: string | null;
+ seats?: number;
+ plan?: string;
+ sub?: string;
+ server?: string;
+ /** Core orders licences by these: the issue date, then `iat` when both carry it. */
+ issued: string;
+ iat?: number;
}
/** The longest grace core may ask for; a larger number is clamped, never trusted. */
@@ -19,5 +26,13 @@ export function register(options: { licenseKey: string | undefined; graceDays?:
// only the expiry comparison moves that many days earlier.
const graceDays = Math.min(MAX_GRACE_DAYS, Math.max(0, Number.isFinite(options.graceDays) ? options.graceDays! : 0));
const claims = verifyLicenseKey(options.licenseKey, { now: new Date((options.now ?? Date.now()) - graceDays * DAY_MS) });
- return { customer: claims.customer, features: claims.features, expiresAt: claims.expires };
+ return {
+ customer: claims.customer, features: claims.features, expiresAt: claims.expires,
+ ...(claims.seats !== undefined ? { seats: claims.seats } : {}),
+ ...(claims.plan !== undefined ? { plan: claims.plan } : {}),
+ ...(claims.sub !== undefined ? { sub: claims.sub } : {}),
+ ...(claims.server !== undefined ? { server: claims.server } : {}),
+ issued: claims.issued,
+ ...(claims.iat !== undefined ? { iat: claims.iat } : {}),
+ };
}
diff --git a/enterprise/server/license.test.ts b/enterprise/server/license.test.ts
index 1b101dbff7..883f0dc150 100644
--- a/enterprise/server/license.test.ts
+++ b/enterprise/server/license.test.ts
@@ -1,8 +1,13 @@
-import { generateKeyPairSync } from "node:crypto";
+import { createPrivateKey, generateKeyPairSync, sign } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { describe, expect, it } from "vitest";
+import { z } from "zod";
import { register } from "./index.ts";
-import { issueLicenseKey, verifyLicenseKey, type LicenseClaims } from "./license.ts";
+import { claimsSchema, issueLicenseKey, LICENSE_PUBLIC_KEYS, validateClaims, verifyLicenseKey, type LicenseClaims } from "./license.ts";
function keypair() {
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
@@ -72,3 +77,111 @@ describe("license keys", () => {
expect(() => register({ licenseKey: "omb1.bad.key" })).toThrow(/OMB_LICENSE_KEY/);
});
});
+
+/** Signs any claims object, as an issuer that knows more (or fewer) claims than this build would. */
+function signRaw(claims: object, privateJwk: ReturnType<typeof keypair>["privateJwk"]): string {
+ const part = Buffer.from(JSON.stringify(claims), "utf8").toString("base64url");
+ const signature = sign(null, Buffer.from(part, "utf8"), createPrivateKey({ key: privateJwk, format: "jwk" }));
+ return `omb1.${part}.${signature.toString("base64url")}`;
+}
+
+describe("subscription claims: seats, plan, sub, server", () => {
+ const subscription: LicenseClaims = { ...claims, seats: 20, plan: "business-server", sub: "sub_123", server: "srv_456", iat: 1_795_000_000_000 };
+
+ it("round-trips the new optional claims in the same omb1 / v:1 format", () => {
+ const { x, privateJwk } = keypair();
+ const key = issueLicenseKey(subscription, privateJwk);
+ expect(key.split(".")[0]).toBe("omb1");
+ const verified = verifyLicenseKey(key, { publicKeys: [x], now: new Date("2026-12-01") });
+ expect(verified).toEqual(subscription);
+ expect(verified.v).toBe(1);
+ });
+
+ it("still accepts a licence without them (an old key on a new server)", () => {
+ const { x, privateJwk } = keypair();
+ const old = signRaw({ v: 1, customer: "Acme", features: ["whitelabel"], issued: "2026-01-01", expires: "2027-01-01" }, privateJwk);
+ const verified = verifyLicenseKey(old, { publicKeys: [x], now: new Date("2026-06-01") });
+ expect(verified).toEqual({ v: 1, customer: "Acme", features: ["whitelabel"], issued: "2026-01-01", expires: "2027-01-01" });
+ expect(verified.seats).toBeUndefined();
+ });
+
+ it("is accepted by a server that predates them (a new key on an old server)", () => {
+ // The claims schema servers shipped before these fields, verbatim.
+ const before = z.object({
+ v: z.literal(1),
+ customer: z.string().min(1),
+ features: z.array(z.string().min(1)),
+ issued: z.iso.date("issued must be a YYYY-MM-DD date"),
+ expires: z.iso.date("expires must be a YYYY-MM-DD date").nullable(),
+ });
+ const { privateJwk } = keypair();
+ const claimsPart = issueLicenseKey(subscription, privateJwk).split(".")[1];
+ const parsed = before.safeParse(JSON.parse(Buffer.from(claimsPart, "base64url").toString("utf8")));
+ expect(parsed.success).toBe(true);
+ expect(parsed.data).toEqual(claims);
+ });
+
+ it("tolerates a claim this build has never heard of, so later claims need no new format", () => {
+ const { x, privateJwk } = keypair();
+ const future = signRaw({ ...subscription, region: "eu" }, privateJwk);
+ expect(verifyLicenseKey(future, { publicKeys: [x], now: new Date("2026-12-01") })).toEqual(subscription);
+ });
+
+ it("refuses malformed values for them, on both sides", () => {
+ const { x, privateJwk } = keypair();
+ for (const bad of [{ seats: 0 }, { seats: 2.5 }, { seats: "20" }, { plan: "" }, { sub: 7 }, { server: "" }, { iat: -1 }, { iat: 1.5 }]) {
+ expect(() => issueLicenseKey({ ...claims, ...bad } as LicenseClaims, privateJwk), JSON.stringify(bad)).toThrow();
+ expect(() => verifyLicenseKey(signRaw({ ...claims, ...bad }, privateJwk), { publicKeys: [x] }), JSON.stringify(bad)).toThrow(/claims are malformed/);
+ }
+ });
+
+ it("exports the exact validation an issuer must run before signing", () => {
+ expect(validateClaims(subscription)).toEqual(subscription);
+ expect(() => validateClaims({ ...claims, seats: 0 })).toThrow("licence claims are malformed (seats:");
+ expect(() => validateClaims({ ...claims, plan: "" })).toThrow("licence claims are malformed (plan:");
+ expect(validateClaims({ ...claims, region: "eu" })).toEqual(claims);
+ expect(claimsSchema.safeParse({ ...claims, iat: 5 }).success).toBe(true);
+ });
+
+ it("keeps the public key list append-only: the first key stays first", () => {
+ expect(LICENSE_PUBLIC_KEYS[0]).toBe("6CHdwwJzxKJFimRkC79eQ5FR__bX2WaU2BBGNGPQTQU");
+ expect(new Set(LICENSE_PUBLIC_KEYS).size).toBe(LICENSE_PUBLIC_KEYS.length);
+ });
+});
+
+describe("issue-license.mjs, the reference issuer", () => {
+ const script = join(import.meta.dirname, "..", "scripts", "issue-license.mjs");
+ const run = (args: string[]) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8", timeout: 60_000 });
+
+ it("writes the new claims, verifies against the public half keygen printed, and prints the same licence twice", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-issue-license-"));
+ try {
+ const keyPath = join(dir, "signing-key.json");
+ const made = run(["keygen", "--out", keyPath]);
+ expect(made.status, made.stderr).toBe(0);
+ const publicX = /"([A-Za-z0-9_-]{43})",/.exec(made.stdout)?.[1];
+ expect(publicX).toBeDefined();
+ // keygen prints only the public half
+ const privateD = String(JSON.parse(readFileSync(keyPath, "utf8")).d);
+ expect(made.stdout).not.toContain(privateD);
+ const args = ["issue", "--key", keyPath, "--customer", "Acme", "--features", "admin,budgets", "--issued", "2026-11-27",
+ "--expires", "2026-12-30", "--seats", "20", "--plan", "business-server", "--sub", "sub_123", "--server", "srv_456", "--iat", "1795000000000"];
+ const issued = run(args);
+ expect(issued.status, issued.stderr).toBe(0);
+ const key = issued.stdout.trim();
+ expect(verifyLicenseKey(key, { publicKeys: [publicX!], now: new Date("2026-12-01") })).toEqual({
+ v: 1, customer: "Acme", features: ["admin", "budgets"], issued: "2026-11-27", expires: "2026-12-30",
+ seats: 20, plan: "business-server", sub: "sub_123", server: "srv_456", iat: 1_795_000_000_000,
+ });
+ expect(run(args).stdout.trim()).toBe(key);
+ const plain = run(["issue", "--key", keyPath, "--customer", "Acme", "--features", "admin", "--issued", "2026-11-27"]);
+ expect(Object.keys(verifyLicenseKey(plain.stdout.trim(), { publicKeys: [publicX!] }))).toEqual(["v", "customer", "features", "issued", "expires"]);
+ const badSeats = run([...args.slice(0, -10), "--seats", "twenty"]);
+ expect(badSeats.status).toBe(1);
+ expect(badSeats.stderr).toContain("--seats must be a whole number of at least 1");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
diff --git a/enterprise/server/license.ts b/enterprise/server/license.ts
index 7f1de95da3..7c1b21228b 100644
--- a/enterprise/server/license.ts
+++ b/enterprise/server/license.ts
@@ -7,13 +7,25 @@
import { createPrivateKey, createPublicKey, sign, verify, type JsonWebKeyInput } from "node:crypto";
import { z } from "zod";
-/** Ed25519 public keys (JWK `x`), oldest first. Rotate by appending; never edit or remove
- * an entry while a key signed with it is still in the field. The matching private keys are
- * generated with scripts/issue-license.mjs and stay outside the repo. */
+/** Ed25519 public keys (JWK `x`), oldest first. A key verifies when any entry signed it.
+ *
+ * Adding a signing key:
+ * 1. Whoever holds the new private key runs `node enterprise/scripts/issue-license.mjs keygen --out <path>`.
+ * It writes the private half to <path> (mode 0600) and prints only the public half.
+ * 2. Append that public half as a new last line below, with a comment saying who signs with it.
+ * 3. Ship a release. Servers older than that release do not trust the new key yet, so keep issuing
+ * with the old key until the servers that need the new one are updated.
+ *
+ * Never edit or remove an entry while a key signed with it is still in the field. Private keys stay
+ * outside the repo. */
export const LICENSE_PUBLIC_KEYS: readonly string[] = [
+ // Hand-issued enterprise keys.
"6CHdwwJzxKJFimRkC79eQ5FR__bX2WaU2BBGNGPQTQU",
];
+/** The claims a licence may carry. An issuer (the cloud Admin's included) must validate with exactly this schema before
+ * signing, e.g. through `validateClaims`: a new server refuses the WHOLE licence when an optional claim is malformed (a
+ * `seats` of 0 or 2.5, an empty `plan`), it does not just drop that claim. */
export const claimsSchema = z.object({
v: z.literal(1),
/** Who the license was issued to; shown in the UI and the startup log. */
@@ -24,10 +36,30 @@ export const claimsSchema = z.object({
issued: z.iso.date("issued must be a YYYY-MM-DD date"),
/** ISO date (YYYY-MM-DD) the key stops working, or null for perpetual. */
expires: z.iso.date("expires must be a YYYY-MM-DD date").nullable(),
+ // Optional, added later in the same `v: 1` format. A server without them ignores them (unknown claims are dropped,
+ // never refused), and a key without them still verifies here, so old servers and old keys keep working.
+ /** How many people may sign in before new invites stop (soft: nobody is locked out). */
+ seats: z.number().int().positive().optional(),
+ /** The plan the key was sold under, e.g. "business-server". */
+ plan: z.string().min(1).optional(),
+ /** The subscription the key renews with. */
+ sub: z.string().min(1).optional(),
+ /** The server the key was issued for. Carried; not checked yet (server/enterprise.ts, licenseServerRefusal). */
+ server: z.string().min(1).optional(),
+ /** When the key was issued, in epoch milliseconds: orders two keys issued the same day, so a seat change made today
+ * cannot be undone by putting back this morning's key. */
+ iat: z.number().int().nonnegative().optional(),
});
export type LicenseClaims = z.infer<typeof claimsSchema>;
+/** The claims as a server will read them, or an error naming the first problem: what an issuer checks before it signs. */
+export function validateClaims(claims: unknown): LicenseClaims {
+ const result = claimsSchema.safeParse(claims);
+ if (!result.success) throw new Error(`licence claims are malformed (${result.error.issues[0]?.path.join(".") || "claims"}: ${result.error.issues[0]?.message ?? "invalid"})`);
+ return result.data;
+}
+
const PREFIX = "omb1";
function publicKeyFromX(x: string) {
diff --git a/enterprise/server/register.test.ts b/enterprise/server/register.test.ts
index 35a1fec968..c53c7d6245 100644
--- a/enterprise/server/register.test.ts
+++ b/enterprise/server/register.test.ts
@@ -26,14 +26,14 @@ const at = (iso: string) => new Date(iso).getTime();
describe("register() grace period", () => {
it("keeps a key that lapsed less than the grace period ago, with its real expiry", () => {
- expect(register({ licenseKey: key, graceDays: 7, now: at("2027-01-03T12:00:00Z") })).toEqual({
- customer: "Acme", features: ["budgets"], expiresAt: "2027-01-01",
+ expect(register({ licenseKey: key, graceDays: 14, now: at("2027-01-03T12:00:00Z") })).toEqual({
+ customer: "Acme", features: ["budgets"], expiresAt: "2027-01-01", issued: "2026-01-01",
});
- expect(register({ licenseKey: key, graceDays: 7, now: at("2027-01-07T23:59:59Z") })?.customer).toBe("Acme");
+ expect(register({ licenseKey: key, graceDays: 14, now: at("2027-01-14T23:59:59.999Z") })?.customer).toBe("Acme");
});
it("refuses the key once the grace period is over, and without one at the expiry instant", () => {
- expect(() => register({ licenseKey: key, graceDays: 7, now: at("2027-01-08T00:00:00Z") })).toThrow(/expired on 2027-01-01; renew it/);
+ expect(() => register({ licenseKey: key, graceDays: 14, now: at("2027-01-15T00:00:00Z") })).toThrow(/expired on 2027-01-01; renew it/);
expect(() => register({ licenseKey: key, now: at("2027-01-01T00:00:00Z") })).toThrow(/expired on 2027-01-01/);
expect(register({ licenseKey: key, now: at("2026-12-31T23:59:59Z") })?.expiresAt).toBe("2027-01-01");
});
@@ -43,3 +43,17 @@ describe("register() grace period", () => {
expect(() => register({ licenseKey: key, graceDays: Number.NaN, now: at("2027-01-02T00:00:00Z") })).toThrow(/expired/);
});
});
+
+describe("register() and the subscription claims", () => {
+ it("hands seats, plan, sub, server and iat to core when the key carries them, the issue date always", () => {
+ const subscription = issueLicenseKey(
+ { v: 1, customer: "Acme", features: ["admin"], issued: "2026-11-27", expires: "2026-12-30", seats: 20, plan: "business-server", sub: "sub_1", server: "srv_1", iat: 1_795_000_000_000 },
+ testKey.privateJwk,
+ );
+ expect(register({ licenseKey: subscription, now: at("2026-12-01T00:00:00Z") })).toEqual({
+ customer: "Acme", features: ["admin"], expiresAt: "2026-12-30", seats: 20, plan: "business-server", sub: "sub_1", server: "srv_1",
+ issued: "2026-11-27", iat: 1_795_000_000_000,
+ });
+ expect(Object.keys(register({ licenseKey: key, now: at("2026-06-01T00:00:00Z") })!)).toEqual(["customer", "features", "expiresAt", "issued"]);
+ });
+});
diff --git a/scripts/server-installer.test.ts b/scripts/server-installer.test.ts
index 9bba103c1c..ec669d5132 100644
--- a/scripts/server-installer.test.ts
+++ b/scripts/server-installer.test.ts
@@ -108,6 +108,7 @@ case "$*" in
"image inspect -f {{index .Config.Labels "*) echo "\${FAKE_IMAGE_VERSION-v0.1.151}" ;;
"compose exec -T omb node dist-server/bot-box/box-check.js --public=none") echo "$FAKE_BOX_CHECK"; case "$FAKE_BOX_CHECK" in *'"failed":[]'*) ;; *) exit 1 ;; esac ;;
"inspect --format {{.State.Health.Status}} c1") echo "$FAKE_HEALTH" ;;
+ "compose exec -T omb curl -sf http://127.0.0.1:8799/api/edition") printf '%s' "\${FAKE_EDITION:-}" ;;
esac`,
};
@@ -426,6 +427,49 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
expect(existsSync(join(missing.install, "data"))).toBe(true);
});
+ it("passes a licence given as OMB_LICENSE_KEY to the server through .env, never prints it, and keeps it on a re-run", () => {
+ const licence = "omb1.eyJ2IjoxfQ.c2lnbmF0dXJlLW9ubHktZm9yLXRlc3Rz";
+ const first = run(["--domain", "maus.example.com"], { env: { OMB_LICENSE_KEY: licence } });
+ expect(first.status).toBe(0);
+ const env = join(first.install, ".env");
+ expect(readFileSync(env, "utf8")).toContain(`\nOMB_LICENSE_KEY=${licence}\n`);
+ expect(statSync(env).mode & 0o777).toBe(0o600);
+ expect(readFileSync(join(first.install, "compose.yaml"), "utf8")).toMatch(/^ {6}OMB_LICENSE_KEY:$/m);
+ expect(first.all).not.toContain(licence);
+ const second = run([], { env: { FAKE_RELEASE: "v0.1.152" } }, { dir: first.dir });
+ expect(second.status).toBe(0);
+ expect(readFileSync(env, "utf8").split("\n").filter((line) => line.startsWith("OMB_LICENSE_KEY="))).toEqual([`OMB_LICENSE_KEY=${licence}`]);
+ // The paste fallback the installer's header names: license.key in the server's data folder, written as the server's
+ // user, readable by it alone, from a file rather than the command line.
+ expect(script).toContain(`sudo docker compose exec -T omb sh -c 'umask 077; cat > "$OMB_DATA_DIR/license.key"' < licence.txt`);
+ });
+
+ it("says in one line whether the server took the licence, from its own notice, never echoing the licence", () => {
+ const licence = "omb1.eyJ2IjoxfQ.c2lnbmF0dXJlLW9ubHktZm9yLXRlc3Rz";
+ const refused = run(["--domain", "maus.example.com"], { env: { OMB_LICENSE_KEY: licence,
+ FAKE_EDITION: '{"edition":"oss","features":[],"notice":"enterprise layer disabled: OMB_LICENSE_KEY signature does not match any OpenMausBot signing key"}' } });
+ expect(refused.status).toBe(0);
+ expect(refused.stdout).toContain(" note The licence was not accepted: enterprise layer disabled: OMB_LICENSE_KEY signature does not match any OpenMausBot signing key\n");
+ expect(refused.all).not.toContain(licence);
+ const accepted = run(["--domain", "maus.example.com"], { env: { OMB_LICENSE_KEY: licence, FAKE_EDITION: '{"edition":"enterprise","customer":"Acme","features":["admin"]}' } });
+ expect(accepted.stdout).toContain(" ok The licence was accepted.\n");
+ const leaky = run(["--domain", "maus.example.com"], { env: { OMB_LICENSE_KEY: licence, FAKE_EDITION: `{"edition":"oss","features":[],"notice":"bad key ${licence}"}` } });
+ expect(leaky.all).not.toContain(licence);
+ expect(leaky.stdout).toContain("The licence was not accepted: see: cd ");
+ const none = run(["--domain", "maus.example.com"], { env: { FAKE_EDITION: '{"edition":"oss","features":[],"notice":"x"}' } });
+ expect(none.docker.some((call) => call.includes("/api/edition"))).toBe(false);
+ });
+
+ it("refuses an OMB_LICENSE_KEY that is not a licence before changing anything, without echoing it", () => {
+ for (const bad of ["not-a-licence", "omb1.only-one-part", "omb1.a.b; rm -rf /", "omb1.a.b\nOMB_IMAGE=evil"]) {
+ const result = run(["--domain", "maus.example.com"], { env: { OMB_LICENSE_KEY: bad } });
+ expect(result.status, bad).toBe(1);
+ expect(result.stderr).toContain("OMB_LICENSE_KEY doesn't look like a MausBot licence.");
+ expect(result.all).not.toContain(bad);
+ expect(existsSync(result.install), bad).toBe(false);
+ }
+ });
+
it("run again, it repairs its own files and keeps the person's settings and data", () => {
const first = run(["--domain", "maus.example.com"]);
expect(first.status).toBe(0);
@@ -676,7 +720,7 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
const settings = (text: string) => [...text.matchAll(/^ {6}(OMB_[A-Z_]+:.*)$/gm)].map((match) => match[1]);
expect(settings(written)).toEqual(settings(manual));
// The sign-in lists and mail server are passed only when .env sets them: an empty one would still be set.
- for (const name of ["OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_URL", "OMB_SIGNIN_SMTP_FROM", "OMB_PHONE_RELAY"]) expect(settings(written)).toContain(`${name}:`);
+ for (const name of ["OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_URL", "OMB_SIGNIN_SMTP_FROM", "OMB_PHONE_RELAY", "OMB_LICENSE_KEY"]) expect(settings(written)).toContain(`${name}:`);
for (const line of ['test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]', "init: true", "shm_size: 512m", '- "80:80"', '- "443:443"',
"- edge:/run/openmausbot", "type: tmpfs"]) {
expect(written).toContain(line);
diff --git a/server/enterprise.test.ts b/server/enterprise.test.ts
index 9c9e0ab82f..8082f4c76c 100644
--- a/server/enterprise.test.ts
+++ b/server/enterprise.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { createWorkspaceAccess, describeEdition, editionForMembers, editionStatus, enterpriseLayerDirs, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer } from "./enterprise.ts";
+import { createWorkspaceAccess, describeEdition, editionForMembers, editionStatus, enterpriseLayerDirs, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, LICENSE_GRACE_DAYS, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer } from "./enterprise.ts";
import { SessionRegistry } from "./sessions.ts";
const dirs: string[] = [];
@@ -103,9 +103,10 @@ describe("enterprise hook point", () => {
expect(describeEdition(status)).toBe("openmausbot enterprise edition for Built: admin");
});
- it("warns for 30 days, keeps working for a 7-day grace, then stops granting features without a restart", async () => {
+ it("warns for 30 days, keeps working for a 14-day grace, then stops granting features without a restart", async () => {
+ expect(LICENSE_GRACE_DAYS).toBe(14);
const dir = fakeLayer(`export function register({ graceDays }) {
- if (graceDays !== 7) throw new Error("core must ask for its grace period");
+ if (graceDays !== 14) throw new Error("core must ask for its grace period");
return { customer: "Acme", features: ["sso"], expiresAt: "2027-01-01" };
}`);
await loadEnterpriseLayer({ dir, licenseKey: "k" });
@@ -123,13 +124,14 @@ describe("enterprise hook point", () => {
expect(entitled("sso", at("2026-12-31T23:59:59Z"))).toBe(true);
// expired, in grace: still enterprise, still entitled, and it says so
const grace = editionStatus(at("2027-01-03T00:00:00Z"));
- expect(grace).toMatchObject({ edition: "enterprise", features: ["sso"], expiresInDays: -2, graceEndsAt: "2027-01-08" });
- expect(grace.notice).toBe("OMB_LICENSE_KEY expired on 2027-01-01; enterprise features keep working until 2027-01-08 while it is renewed");
- expect(licenseWarning(grace)).toContain("keep working until 2027-01-08");
+ expect(grace).toMatchObject({ edition: "enterprise", features: ["sso"], expiresInDays: -2, graceEndsAt: "2027-01-15" });
+ expect(grace.notice).toBe("OMB_LICENSE_KEY expired on 2027-01-01; enterprise features keep working until 2027-01-15 while it is renewed");
+ expect(licenseWarning(grace)).toContain("keep working until 2027-01-15");
expect(entitled("sso", at("2027-01-01T00:00:00Z"))).toBe(true);
- expect(entitled("sso", at("2027-01-07T23:59:59Z"))).toBe(true);
- // grace over
- const after = at("2027-01-08T00:00:00Z");
+ expect(entitled("sso", at("2027-01-08T00:00:00Z"))).toBe(true);
+ expect(entitled("sso", at("2027-01-14T23:59:59.999Z"))).toBe(true);
+ // grace over: 14 days after the expiry instant, to the millisecond
+ const after = at("2027-01-15T00:00:00Z");
expect(entitled("sso", after)).toBe(false);
const lapsed = editionStatus(after);
expect(lapsed.edition).toBe("oss");
@@ -187,7 +189,7 @@ describe("enterprise hook point", () => {
it("tells the operator when the layer is present but no key is configured", async () => {
const dir = fakeLayer(`export function register() { return { customer: "x", features: [], expiresAt: null }; }`);
const status = await loadEnterpriseLayer({ dir, licenseKey: undefined });
- expect(status).toEqual({ edition: "oss", features: [], notice: "enterprise layer present but OMB_LICENSE_KEY is not set" });
+ expect(status).toEqual({ edition: "oss", features: [], notice: "enterprise layer present but there is no licence: neither license.key nor OMB_LICENSE_KEY is set" });
});
it("refuses a layer that does not honour the contract", async () => {
diff --git a/server/enterprise.ts b/server/enterprise.ts
index 198e2509da..87da48c7a2 100644
--- a/server/enterprise.ts
+++ b/server/enterprise.ts
@@ -1,5 +1,7 @@
// Hook point for the source-available enterprise layer (enterprise/, under its own licence), loaded only when present:
-// core never imports it statically. Its one obligation is `register()`, turning OMB_LICENSE_KEY into entitlements.
+// 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 { existsSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -8,6 +10,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import type { RequestAuth } from "./request-auth.ts";
import type { SessionRegistry } from "./sessions.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";
export interface EditionStatus {
@@ -31,11 +34,20 @@ const layerSchema = z.object({
customer: z.string().min(1),
features: z.array(z.string().min(1)),
expiresAt: z.string().nullable(),
+ seats: z.number().int().positive().optional(),
+ plan: z.string().min(1).optional(),
+ sub: z.string().min(1).optional(),
+ server: z.string().min(1).optional(),
+ /** When the licence was issued (YYYY-MM-DD) and, finer, `iat` (epoch ms): which of two licences is newer. */
+ issued: z.string().optional(),
+ iat: z.number().int().nonnegative().optional(),
});
+type Layer = z.infer<typeof layerSchema>;
/** The layer accepts a key that expired less than the grace period ago. */
export const LICENSE_WARN_DAYS = 30;
-export const LICENSE_GRACE_DAYS = 7;
+/** The one grace period: how long after expiry licensed features keep working. */
+export const LICENSE_GRACE_DAYS = 14;
const DAY_MS = 24 * 60 * 60_000;
/** OMB_ENTERPRISE_DIR alone when set; else beside the server root (a checkout, the npm package), then inside it (the Docker
@@ -51,6 +63,16 @@ function layerEntry(dir: string): string | undefined {
let current: EditionStatus = { edition: "oss", features: [] };
let workspaceAccessFactory: ((options: WorkspaceAccessOptions) => WorkspaceAccess) | undefined;
+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 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. */
+let lastProblem: string | undefined;
+let rereading: Promise<unknown> = Promise.resolve();
export interface WorkspaceAccessOptions {
sessions: SessionRegistry;
@@ -112,46 +134,192 @@ export function createWorkspaceAccess(options: Omit<WorkspaceAccessOptions, "ent
function oss(notice?: string): EditionStatus {
current = notice ? { edition: "oss", features: [], notice } : { edition: "oss", features: [] };
+ held = null;
return current;
}
-const LAYER_WITHOUT_KEY = "enterprise layer present but OMB_LICENSE_KEY is not set";
+const message = (error: unknown) => error instanceof Error ? error.message : String(error);
+
+const LAYER_WITHOUT_KEY = "enterprise layer present but there is no licence: neither license.key nor OMB_LICENSE_KEY is set";
+/** What a notice calls the licence in force: the file a person fixes, or the environment variable. */
+const keyName = () => held && held.source !== "env" ? "license.key" : "OMB_LICENSE_KEY";
/** Never throws: a broken layer or key degrades to the open-source edition with a notice saying what to fix. With no key
- * and no hosted workspace nothing of the layer can be used, so it is not loaded. */
+ * and no hosted workspace nothing of the layer can be used, so it is not loaded. `dataDir`: where license.key and
+ * license.last-good are; server/index.ts leaves it out on a desktop, a Cloud home and a hosted workspace, which read
+ * OMB_LICENSE_KEY alone. */
export async function loadEnterpriseLayer(
- options: { dir?: string; licenseKey?: string; env?: NodeJS.ProcessEnv; serverRoot?: string } = {},
+ options: { dir?: string; licenseKey?: string; env?: NodeJS.ProcessEnv; serverRoot?: string; dataDir?: string; serverInstall?: boolean } = {},
): Promise<EditionStatus> {
workspaceAccessFactory = undefined;
+ lastProblem = undefined;
+ lastChangeLog = Number.NEGATIVE_INFINITY;
const dirs = options.dir ? [options.dir] : enterpriseLayerDirs(options.env, options.serverRoot);
- const licenseKey = options.licenseKey ?? process.env.OMB_LICENSE_KEY;
+ const envKey = options.licenseKey ?? process.env.OMB_LICENSE_KEY;
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);
+ loaded = { entry, dataDir: options.dataDir, envKey, keyAtStart: keyGiven || options.serverInstall === true };
if (!entry) {
- return oss(
- licenseKey ? `OMB_LICENSE_KEY is set but no enterprise layer exists at ${dirs.join(" or ")}` : undefined,
- );
+ const named = reads.file.state !== "absent" ? `${licenseFilePath(options.dataDir!)} holds a licence` : "OMB_LICENSE_KEY is set";
+ return oss(keyGiven ? `${named} but no enterprise layer exists at ${dirs.join(" or ")}` : undefined);
}
- if (!licenseKey && !hostedWorkspaceConfigured(options.env)) return oss(LAYER_WITHOUT_KEY);
+ if (!keyGiven && !hostedWorkspaceConfigured(options.env)) return oss(LAYER_WITHOUT_KEY);
try {
- const loaded: unknown = await import(pathToFileURL(entry).href);
- const access: unknown = Reflect.get(Object(loaded), "createWorkspaceAccess");
- if (typeof access === "function") workspaceAccessFactory = access as (options: WorkspaceAccessOptions) => WorkspaceAccess;
- const register: unknown = Reflect.get(Object(loaded), "register");
- if (typeof register !== "function") throw new Error(`${entry} does not export register()`);
- if (!licenseKey) return oss(LAYER_WITHOUT_KEY);
- // A layer that ignores graceDays refuses an expired key at startup.
- const registered: unknown = await register({ licenseKey, graceDays: LICENSE_GRACE_DAYS });
- const layer = layerSchema.parse(registered);
- current = {
- edition: "enterprise",
- customer: layer.customer,
- features: [...new Set(layer.features)].sort(),
- expiresAt: layer.expiresAt,
- };
- return current;
+ loaded.register = await importLayer(entry);
} catch (error) {
- return oss(`enterprise layer disabled: ${error instanceof Error ? error.message : String(error)}`);
+ return oss(`enterprise layer disabled: ${message(error)}`);
+ }
+ if (!keyGiven) return oss(LAYER_WITHOUT_KEY);
+ return grant(reads, false, (line) => console.warn(line));
+}
+
+/** Whether server/index.ts starts the re-read: a layer, a data folder, and either a licence at start (file, environment
+ * or kept copy) or a server install (license-source.ts licensePlace), whose first licence may arrive after it starts. */
+export function licenseRefreshWanted(): boolean {
+ return Boolean(loaded?.entry && loaded.dataDir && loaded.keyAtStart);
+}
+
+async function readSources(dataDir: string | undefined): Promise<{ file: LicenseFileRead; lastGood: LicenseFileRead }> {
+ if (!dataDir) return { file: { state: "absent" }, lastGood: { state: "absent" } };
+ const [file, lastGood] = await Promise.all([readLicenseFile(dataDir), readLicenseFile(dataDir, LAST_GOOD_FILE)]);
+ return { file, lastGood };
+}
+
+async function importLayer(entry: string): Promise<Register> {
+ const imported: unknown = await import(pathToFileURL(entry).href);
+ const access: unknown = Reflect.get(Object(imported), "createWorkspaceAccess");
+ if (typeof access === "function") workspaceAccessFactory = access as (options: WorkspaceAccessOptions) => WorkspaceAccess;
+ const register: unknown = Reflect.get(Object(imported), "register");
+ if (typeof register !== "function") throw new Error(`${entry} does not export register()`);
+ return register as Register;
+}
+
+function note(problem: string, log: (line: string) => void) {
+ if (problem !== lastProblem) log(problem);
+ lastProblem = problem;
+}
+
+/** Where a licence came from, as a person would look for it. */
+function sourceName(source: LicenseSource): string {
+ return source === "env" ? "OMB_LICENSE_KEY" : source === "file" ? "license.key" : "license.last-good";
+}
+
+/** Positive when `a` was issued after `b`: the issue date, then `iat` when both carry it, then the later expiry. Equal
+ * (0) when none of those tell them apart: the same day's reissue without `iat` is not refused. */
+export function issuedOrder(a: LicenseOrder, b: LicenseOrder): number {
+ const issuedA = a.issued ?? "";
+ const issuedB = b.issued ?? "";
+ if (issuedA !== issuedB) return issuedA < issuedB ? -1 : 1;
+ if (a.iat !== undefined && b.iat !== undefined && a.iat !== b.iat) return a.iat < b.iat ? -1 : 1;
+ const ends = (expires: string | null) => expires === null ? Number.POSITIVE_INFINITY : Date.parse(expires);
+ const endA = ends(a.expiresAt);
+ const endB = ends(b.expiresAt);
+ return endA === endB || (Number.isNaN(endA) && Number.isNaN(endB)) ? 0 : endA < endB ? -1 : 1;
+}
+export type LicenseOrder = Pick<Layer, "issued" | "iat" | "expiresAt">;
+
+/** Off: a licence's `server` claim is carried, not checked. When it is switched on, a licence is refused only when this
+ * server knows its own id and the licence names a different one; a licence that names none, or a server that does not
+ * know its id, is never refused for it. */
+const ENFORCE_LICENSE_SERVER = false;
+export function licenseServerRefusal(licensed: string | undefined, own: string | undefined, enforce: boolean = ENFORCE_LICENSE_SERVER): string | null {
+ if (!enforce || !licensed || !own || licensed === own) return null;
+ return `the licence was issued for server ${licensed}, not this one`;
+}
+
+/** Every licence on offer (license.key, OMB_LICENSE_KEY, the kept copy), each verified by the layer; the one issued last
+ * wins, and on a tie the file, then the environment. On a re-read (`keep`) a licence in force is never replaced by one
+ * issued before it, nor dropped for a broken or missing file: it stays until its grace ends. */
+async function grant(reads: { file: LicenseFileRead; lastGood: LicenseFileRead }, keep: boolean, log: (line: string) => void): Promise<EditionStatus> {
+ const { dataDir, envKey, register } = loaded!;
+ const now = Date.now();
+ const active = keep && current.edition === "enterprise" && !expired(now) && held !== null;
+ 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 === "present") offered.push({ key: read.key, source });
+ else if (read.state === "unreadable") problems.push(read.error);
}
+ const accepted: { key: string; source: LicenseSource; layer: Layer }[] = [];
+ for (const candidate of offered) {
+ try {
+ // A layer that ignores graceDays refuses an expired key at startup.
+ const layer = layerSchema.parse(await register!({ licenseKey: candidate.key, graceDays: LICENSE_GRACE_DAYS }));
+ const refusal = licenseServerRefusal(layer.server, undefined);
+ if (refusal) throw new Error(refusal);
+ accepted.push({ ...candidate, layer });
+ } catch (error) {
+ 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 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 };
+ 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);
+ else lastProblem = undefined;
+ warnClock(layer, now, log);
+ if (dataDir) await writeLastGood(dataDir, best.key).catch((error: unknown) => note(`could not keep a copy of the licence: ${message(error)}`, log));
+ return current;
+ }
+ if (active) {
+ 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);
+ return current;
+ }
+ if (!problems.length) return current;
+ if (keep) note(`enterprise layer disabled: ${problems[0]}`, log);
+ return oss(`enterprise layer disabled: ${problems[0]}`);
+}
+
+/** Once per licence: a clock more than a day before the issue date makes every expiry check wrong. */
+function warnClock(layer: Layer, now: number, log: (line: string) => void) {
+ if (!layer.issued || now >= Date.parse(layer.issued) - DAY_MS || clockWarned === layer.issued) return;
+ clockWarned = layer.issued;
+ log(`this server's clock says ${new Date(now).toISOString()}, before the licence was issued (${layer.issued}): set the clock right, or the licence's dates are judged wrongly`);
+}
+
+/** A re-read that has not finished after this long no longer holds up the next one. */
+const REREAD_DEADLINE_MS = 30_000;
+/** At most one "licence changed" line in this long. */
+const CHANGE_LOG_GAP_MS = 10 * 60_000;
+
+/** Reads the licence again (license-source.ts calls this hourly and when the file changes) and switches licensed
+ * features on or off without a restart. Never throws; one re-read runs at a time, and a hung one stops blocking the
+ * next after REREAD_DEADLINE_MS. */
+export function refreshLicense(log: (line: string) => void = (line) => console.warn(line)): Promise<EditionStatus> {
+ const run = async (): Promise<EditionStatus> => {
+ if (!loaded?.entry) return current;
+ const reads = await readSources(loaded.dataDir);
+ if (reads.file.state === "absent" && reads.lastGood.state === "absent" && !loaded.envKey && !(current.edition === "enterprise" && held)) return current;
+ if (!loaded.register) {
+ try {
+ loaded.register = await importLayer(loaded.entry);
+ } catch (error) {
+ note(`enterprise layer disabled: ${message(error)}`, log);
+ return current;
+ }
+ }
+ // Which licence is in force, not where it was read from: the same licence kept or read again is no change.
+ const before = JSON.stringify([current, held?.layer]);
+ const status = await grant(reads, true, log);
+ const now = Date.now();
+ if (JSON.stringify([current, held?.layer]) !== before && status.edition === "enterprise" && now - lastChangeLog >= CHANGE_LOG_GAP_MS) {
+ lastChangeLog = now;
+ log(`licence changed: ${describeEdition(status)}`);
+ }
+ return status;
+ };
+ const next = rereading.then(run, run);
+ rereading = Promise.race([next.catch(() => undefined), new Promise<void>((done) => setTimeout(done, REREAD_DEADLINE_MS).unref?.())]);
+ return next.catch((error: unknown) => { log(`licence re-read failed: ${message(error)}`); return current; });
}
function expiryAt(): number | null {
@@ -173,7 +341,7 @@ export function editionStatus(now: number = Date.now()): EditionStatus {
return {
edition: "oss",
features: [],
- notice: `enterprise layer disabled: OMB_LICENSE_KEY expired on ${current.expiresAt}; renew it to keep enterprise features`,
+ notice: `enterprise layer disabled: ${keyName()} expired on ${current.expiresAt}; renew it to keep enterprise features`,
};
}
const expiresInDays = Math.ceil((at - now) / DAY_MS);
@@ -183,7 +351,44 @@ export function editionStatus(now: number = Date.now()): EditionStatus {
...current,
expiresInDays,
graceEndsAt,
- notice: `OMB_LICENSE_KEY expired on ${current.expiresAt}; enterprise features keep working until ${graceEndsAt} while it is renewed`,
+ notice: `${keyName()} expired on ${current.expiresAt}; enterprise features keep working until ${graceEndsAt} while it is renewed`,
+ };
+}
+
+/** The licence as the owner's Settings shows it (GET /api/license): never the key itself. `valid` while licensed features
+ * work, grace included. `graceEndsAt` whenever the licence expires; `graceDaysLeft` only once it has expired: whole days
+ * until the features stop, 0 after. `source`, `plan` and `seats` describe the last licence accepted, even once lapsed. */
+export interface LicenseState {
+ valid: boolean;
+ source: LicenseSource | null;
+ customer: string | null;
+ plan: string | null;
+ seats: number | null;
+ features: string[];
+ expiresAt: string | null;
+ expiresInDays: number | null;
+ graceEndsAt: string | null;
+ graceDaysLeft: number | null;
+ notice: string | null;
+}
+
+export function licenseState(now: number = Date.now()): LicenseState {
+ const status = editionStatus(now);
+ const licensed = current.edition === "enterprise";
+ const at = expiryAt();
+ const graceEnd = at === null ? null : at + LICENSE_GRACE_DAYS * DAY_MS;
+ return {
+ valid: status.edition === "enterprise",
+ source: licensed ? held?.source ?? null : null,
+ customer: licensed ? current.customer ?? null : null,
+ plan: licensed ? held?.layer.plan ?? null : null,
+ seats: licensed ? held?.layer.seats ?? null : null,
+ features: status.features,
+ expiresAt: licensed ? current.expiresAt ?? null : null,
+ expiresInDays: at === null ? null : Math.ceil((at - now) / DAY_MS),
+ graceEndsAt: graceEnd === null ? null : new Date(graceEnd).toISOString().slice(0, 10),
+ graceDaysLeft: at === null || graceEnd === null || now < at ? null : Math.max(0, Math.ceil((graceEnd - now) / DAY_MS)),
+ notice: status.notice ?? null,
};
}
@@ -201,11 +406,11 @@ export function entitled(feature: string, now: number = Date.now()): boolean {
export function licenseWarning(status: EditionStatus): string | null {
if (status.edition !== "enterprise" || !status.expiresAt || status.expiresInDays === undefined) return null;
if (status.graceEndsAt) {
- return `OMB_LICENSE_KEY expired on ${status.expiresAt}; enterprise features keep working until ${status.graceEndsAt} — renew the key before then`;
+ return `${keyName()} expired on ${status.expiresAt}; enterprise features keep working until ${status.graceEndsAt} — renew the key before then`;
}
if (status.expiresInDays > LICENSE_WARN_DAYS) return null;
const days = status.expiresInDays === 1 ? "1 day" : `${status.expiresInDays} days`;
- return `OMB_LICENSE_KEY expires on ${status.expiresAt} (in ${days}); renew it before then to keep enterprise features`;
+ return `${keyName()} expires on ${status.expiresAt} (in ${days}); renew it before then to keep enterprise features`;
}
export function describeEdition(status: EditionStatus): string {
diff --git a/server/hosted-access.test.ts b/server/hosted-access.test.ts
index b6c02f5776..3579b5e824 100644
--- a/server/hosted-access.test.ts
+++ b/server/hosted-access.test.ts
@@ -328,8 +328,8 @@ describe("hosted bridge in the full server", () => {
await refuseFullTask();
}, 25_000);
it("withdraws hosted readiness the moment the running server's license grace period ends", async () => {
- // Expired a week ago less eight seconds: inside the 7-day grace, which ends mid-test.
- state("admin", false, { expiresAt: new Date(Date.now() + 8_000 - 7 * 24 * 60 * 60_000).toISOString() });
+ // Expired 14 days ago less eight seconds: inside the 14-day grace, which ends mid-test.
+ state("admin", false, { expiresAt: new Date(Date.now() + 8_000 - 14 * 24 * 60 * 60_000).toISOString() });
await restart({ OMB_ADMIN_MEMBERSHIP: "portal", OMB_SHARED_WORKSPACE_FULL_ACCESS: "1" });
expect((await call("/api/health/hosted")).status).toBe(200);
await policyHealth(true);
diff --git a/server/index.ts b/server/index.ts
index ab9743f755..5cd95d677d 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -514,7 +514,7 @@ import {
} from "./turn-dispatch-guard.ts";
import { createGracefulShutdown } from "./graceful-shutdown.ts";
import { acquireDataDirLeaseForProcess, releaseOnceAtExit } from "./data-dir-lease.ts"; import { markEngineRunClean, startEngineRecords } from "./engine-records.ts";
-import { createWorkspaceAccess, describeEdition, editionForSettings, editionStatus, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer, workspaceMembership, type WorkspaceAccess } from "./enterprise.ts";
+import { createWorkspaceAccess, describeEdition, editionForSettings, editionStatus, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, licenseRefreshWanted, loadEnterpriseLayer, refreshLicense, workspaceMembership, type WorkspaceAccess } from "./enterprise.ts"; import { licensePlace, startLicenseRefresh } from "./license-source.ts";
import { environmentDescriptor, loadEnvironmentId, OWNER_LENDING, serverVersion } from "./environment.ts"; import { dataFormatAtStart } from "./data-format.ts"; import { doctorAtStart } from "./doctor/start.ts";
import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";
import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl, releaseDataForBackup } from "./workspace-backup-http.ts";
@@ -15042,8 +15042,8 @@ upgrades.attach(server, handleRequest);
moveFreeze.hold(() => calendarCalls.start(), () => calendarCalls.stop());
-// Resolve the edition before accepting requests so /api/edition is never a guess.
-console.log(describeEdition(await loadEnterpriseLayer()));
+// Resolve the edition before accepting requests so /api/edition is never a guess. A desktop, a Cloud home and a hosted workspace (licensed by its operator's environment) read OMB_LICENSE_KEY alone, as before: no licence files, no timers.
+const LICENSE_PLACE = licensePlace({ desktopManaged: DESKTOP_MANAGED, cloudHome: Boolean(CLOUD_HOME), hostedWorkspace: HOSTED_WORKSPACE }); console.log(describeEdition(await loadEnterpriseLayer(LICENSE_PLACE === "none" ? {} : { dataDir: DATA_DIR, serverInstall: LICENSE_PLACE === "server" }))); if (licenseRefreshWanted()) startLicenseRefresh({ dataDir: DATA_DIR, refresh: () => refreshLicense() });
const startupLicenseWarning = licenseWarning(editionStatus());
if (startupLicenseWarning) console.warn(startupLicenseWarning);
console.log(LOOPBACK.trust === "service"
diff --git a/server/license-expiry-api.test.ts b/server/license-expiry-api.test.ts
index 73a6610389..608a0bacea 100644
--- a/server/license-expiry-api.test.ts
+++ b/server/license-expiry-api.test.ts
@@ -61,7 +61,7 @@ describe("license expiry through the running server", () => {
it("keeps the features working through the grace period and says until when", async () => {
const expiresAt = day(-2);
// From the expiry date itself, not the clock again: a run that crosses midnight UTC would otherwise expect a day too many.
- const graceEndsAt = new Date(Date.parse(expiresAt) + 7 * DAY_MS).toISOString().slice(0, 10);
+ const graceEndsAt = new Date(Date.parse(expiresAt) + 14 * DAY_MS).toISOString().slice(0, 10);
const server = await boot(expiresAt);
const edition = await server.edition();
expect(edition).toMatchObject({ edition: "enterprise", features: ["budgets"], expiresAt, graceEndsAt });
diff --git a/server/license-refresh.test.ts b/server/license-refresh.test.ts
new file mode 100644
index 0000000000..d91a5c86ea
--- /dev/null
+++ b/server/license-refresh.test.ts
@@ -0,0 +1,353 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, truncateSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { editionStatus, entitled, issuedOrder, licenseRefreshWanted, licenseServerRefusal, licenseState, loadEnterpriseLayer, refreshLicense } from "./enterprise.ts";
+import { LICENSE_CHECK_MS, LICENSE_MIN_GAP_MS, LICENSE_REREAD_MS, licensePlace, startLicenseRefresh } from "./license-source.ts";
+
+const dirs: string[] = [];
+const temp = (prefix: string) => {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ dirs.push(dir);
+ return dir;
+};
+
+/** A stand-in layer: a key is `lic:` and the licence as JSON; anything else is refused the way a forged key is, and a
+ * licence past its grace the way the real layer refuses it. */
+function fakeLayer(): string {
+ const dir = temp("omb-license-layer-");
+ mkdirSync(join(dir, "server"));
+ writeFileSync(join(dir, "server", "index.js"), `export function register({ licenseKey, graceDays }) {
+ if (!licenseKey.startsWith("lic:")) throw new Error("OMB_LICENSE_KEY signature does not match any OpenMausBot signing key");
+ const claims = JSON.parse(licenseKey.slice(4));
+ if (claims.expiresAt && Date.now() >= Date.parse(claims.expiresAt) + graceDays * 86400000) throw new Error("OMB_LICENSE_KEY expired on " + claims.expiresAt);
+ return claims;
+ }`);
+ return dir;
+}
+
+const licence = (customer: string, extra: Record<string, unknown> = {}) =>
+ `lic:${JSON.stringify({ customer, features: ["budgets"], expiresAt: "2027-01-01", issued: "2026-11-01", ...extra })}`;
+const at = (iso: string) => new Date(iso).getTime();
+const DAY_MS = 24 * 60 * 60_000;
+
+let layer: string;
+let data: string;
+const log = vi.fn<(line: string) => void>();
+const keyFile = () => join(data, "license.key");
+/** The minute check's view of license.key, without real file timestamps. */
+const contents = async () => { try { return readFileSync(keyFile(), "utf8"); } catch { return "absent"; } };
+const lastGood = () => join(data, "license.last-good");
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] });
+ vi.setSystemTime(at("2026-12-01T00:00:00Z"));
+ layer = fakeLayer();
+ data = temp("omb-license-data-");
+ log.mockReset();
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ await loadEnterpriseLayer({ dir: join(tmpdir(), "omb-enterprise-absent"), licenseKey: undefined });
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("where the licence is read from", () => {
+ it("reads <data>/license.key and OMB_LICENSE_KEY, the file winning a tie, and keeps a copy of the one accepted", async () => {
+ writeFileSync(keyFile(), `${licence("From file", { seats: 20, plan: "business-server" })}\r\n`);
+ const status = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: licence("From env") });
+ expect(status).toEqual({ edition: "enterprise", customer: "From file", features: ["budgets"], expiresAt: "2027-01-01" });
+ expect(licenseState()).toMatchObject({ valid: true, source: "file", customer: "From file", plan: "business-server", seats: 20 });
+ expect(readFileSync(lastGood(), "utf8").trim()).toBe(licence("From file", { seats: 20, plan: "business-server" }));
+ if (process.platform !== "win32") expect(statSync(lastGood()).mode & 0o777).toBe(0o600);
+
+ rmSync(keyFile());
+ rmSync(lastGood());
+ expect((await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: licence("From env") })).customer).toBe("From env");
+ expect(licenseState()).toMatchObject({ valid: true, source: "env", plan: null, seats: null });
+ });
+
+ it("at start, a broken file falls back to the environment's key and says so in one line", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ writeFileSync(keyFile(), "pasted the wrong thing");
+ const status = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: licence("From env") });
+ expect(status.customer).toBe("From env");
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0][0])).toBe(
+ `the licence in ${keyFile()} was refused: OMB_LICENSE_KEY signature does not match any OpenMausBot signing key; using OMB_LICENSE_KEY instead`,
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("at start, a broken file with nothing else is the open-source edition with a notice, never a crash", async () => {
+ writeFileSync(keyFile(), "omb1.forged.key");
+ const status = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ expect(status.edition).toBe("oss");
+ expect(status.notice).toBe(`enterprise layer disabled: the licence in ${keyFile()} was refused: OMB_LICENSE_KEY signature does not match any OpenMausBot signing key`);
+ expect(licenseState()).toMatchObject({ valid: false, source: null, plan: null, notice: status.notice });
+ });
+
+ it("at start, the licence issued last wins: a file in its grace never beats a newer environment key", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ vi.setSystemTime(at("2027-01-05T00:00:00Z"));
+ writeFileSync(keyFile(), licence("Old file", { issued: "2026-10-01", expiresAt: "2027-01-01" }));
+ const status = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: licence("New env", { issued: "2026-12-01", expiresAt: "2027-02-01" }) });
+ expect(status.customer).toBe("New env");
+ expect(licenseState()).toMatchObject({ valid: true, source: "env", graceDaysLeft: null });
+ expect(String(warn.mock.calls[0]?.[0])).toBe(`the licence in ${keyFile()} was issued before the one in OMB_LICENSE_KEY; using OMB_LICENSE_KEY instead`);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
+describe("the kept copy: a restart keeps a licence still in its paid period", () => {
+ it("keeps the licence through a restart with a truncated file", async () => {
+ writeFileSync(keyFile(), licence("Paid", { seats: 20 }));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ truncateSync(keyFile(), 9);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const restarted = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ expect(restarted).toMatchObject({ edition: "enterprise", customer: "Paid" });
+ expect(licenseState()).toMatchObject({ valid: true, source: "last-good", seats: 20 });
+ expect(String(warn.mock.calls[0]?.[0])).toMatch(/license\.key was refused: .*; using license\.last-good instead$/);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("keeps the licence through a restart with the file deleted, even when the install's environment key went stale", async () => {
+ writeFileSync(keyFile(), licence("Renewed", { issued: "2026-11-28", expiresAt: "2027-01-01" }));
+ const stale = licence("Install key", { issued: "2026-10-01", expiresAt: "2026-11-15" });
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: stale });
+ rmSync(keyFile());
+ expect(await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: stale })).toMatchObject({ edition: "enterprise", customer: "Renewed" });
+ expect(licenseState().source).toBe("last-good");
+ expect(licenseRefreshWanted()).toBe(true);
+ });
+
+ it("gains nothing from a forged kept copy", async () => {
+ writeFileSync(lastGood(), "omb1.forged.copy\n");
+ const status = await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ expect(status.edition).toBe("oss");
+ expect(status.notice).toContain(`the licence in ${lastGood()} was refused`);
+ expect(entitled("budgets")).toBe(false);
+ });
+});
+
+describe("reading the licence again while the server runs", () => {
+ it("is started only with a layer, a data folder and a licence at start", async () => {
+ expect((await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined })).notice)
+ .toBe("enterprise layer present but there is no licence: neither license.key nor OMB_LICENSE_KEY is set");
+ expect(licenseRefreshWanted()).toBe(false);
+ await loadEnterpriseLayer({ dir: layer, licenseKey: licence("Desktop") });
+ expect(licenseRefreshWanted()).toBe(false); // no data folder: a desktop or a Cloud home
+ await loadEnterpriseLayer({ dir: join(data, "no-layer"), dataDir: data, licenseKey: licence("No layer") });
+ expect(licenseRefreshWanted()).toBe(false);
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: licence("Env") });
+ expect(licenseRefreshWanted()).toBe(true);
+ });
+
+ it("on a server install that started with no licence, loads one written later without a restart", async () => {
+ // The bought server's real order: installed first, enrolled, and only then does the connector write the licence.
+ expect(await loadEnterpriseLayer({ dir: layer, dataDir: data, serverInstall: true, licenseKey: undefined }))
+ .toMatchObject({ edition: "oss" });
+ expect(licenseRefreshWanted()).toBe(true);
+ let last: Promise<unknown> = Promise.resolve();
+ const refresh = startLicenseRefresh({ dataDir: data, refresh: () => (last = refreshLicense(log)), stamp: contents });
+ try {
+ await vi.advanceTimersByTimeAsync(LICENSE_CHECK_MS * 2);
+ expect(entitled("budgets")).toBe(false);
+ writeFileSync(keyFile(), licence("Bought", { seats: 20, plan: "business-server" }));
+ await vi.advanceTimersByTimeAsync(LICENSE_CHECK_MS + LICENSE_MIN_GAP_MS);
+ await last;
+ expect(entitled("budgets")).toBe(true);
+ expect(licenseState()).toMatchObject({ valid: true, source: "file", customer: "Bought", seats: 20 });
+ } finally {
+ refresh.stop();
+ }
+ });
+
+ it("uses licence files on a server install and any other server, never on a desktop, a Cloud home or a hosted workspace", () => {
+ const docker = (path: string) => path === "/.dockerenv";
+ const nothing = () => false;
+ const base = { desktopManaged: false, cloudHome: false, hostedWorkspace: false, serverRoot: join(data, "dist-server"), env: {} };
+ expect(licensePlace({ ...base, exists: docker })).toBe("server");
+ expect(licensePlace({ ...base, exists: nothing, env: { OMB_PODMAN_SERVICE: "1" } })).toBe("server");
+ expect(licensePlace({ ...base, exists: (path) => path === "/run/.containerenv" })).toBe("server");
+ expect(licensePlace({ ...base, exists: nothing })).toBe("files");
+ for (const where of [{ desktopManaged: true }, { cloudHome: true }, { hostedWorkspace: true }]) {
+ expect(licensePlace({ ...base, ...where, exists: docker }), JSON.stringify(where)).toBe("none");
+ }
+ });
+
+ it("does nothing on a desktop or a Cloud home: no files read or kept, no re-read started", async () => {
+ // server/index.ts passes no data folder there (licensePlace "none"), so only OMB_LICENSE_KEY counts, as before.
+ writeFileSync(keyFile(), licence("Ignored file"));
+ const status = await loadEnterpriseLayer({ dir: layer, licenseKey: licence("Desktop env") });
+ expect(status.customer).toBe("Desktop env");
+ expect(licenseRefreshWanted()).toBe(false);
+ expect(() => readFileSync(lastGood())).toThrow();
+ await loadEnterpriseLayer({ dir: layer, licenseKey: undefined });
+ expect(licenseRefreshWanted()).toBe(false);
+ });
+
+ it("takes a renewed file on the next minute check, and reads hourly besides", async () => {
+ writeFileSync(keyFile(), licence("First", { seats: 20 }));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ const refreshed = vi.fn<() => Promise<unknown>>();
+ let last: Promise<unknown> = Promise.resolve();
+ refreshed.mockImplementation(() => (last = refreshLicense(log)));
+ const refresh = startLicenseRefresh({ dataDir: data, refresh: refreshed, stamp: contents });
+ try {
+ await vi.advanceTimersByTimeAsync(LICENSE_CHECK_MS * 3);
+ expect(refreshed).not.toHaveBeenCalled(); // an unchanged file is not read
+ writeFileSync(keyFile(), licence("First", { seats: 25, issued: "2026-11-30", expiresAt: "2027-02-01" }));
+ await vi.advanceTimersByTimeAsync(LICENSE_CHECK_MS);
+ await last;
+ expect(refreshed).toHaveBeenCalledTimes(1);
+ expect(licenseState()).toMatchObject({ valid: true, seats: 25, expiresAt: "2027-02-01" });
+ expect(log).toHaveBeenCalledWith("licence changed: openmausbot enterprise edition for First until 2027-02-01: budgets");
+ await vi.advanceTimersByTimeAsync(LICENSE_REREAD_MS);
+ expect(refreshed).toHaveBeenCalledTimes(2);
+ } finally {
+ refresh.stop();
+ }
+ });
+
+ it("never reads twice within the minimum gap, however often the file changes", async () => {
+ writeFileSync(keyFile(), licence("Busy"));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ const refreshed = vi.fn<() => Promise<unknown>>().mockResolvedValue(undefined);
+ const refresh = startLicenseRefresh({ dataDir: data, refresh: refreshed, checkMs: 5_000, minGapMs: 30_000, stamp: contents });
+ try {
+ await vi.advanceTimersByTimeAsync(1);
+ for (let round = 0; round < 12; round += 1) {
+ writeFileSync(keyFile(), licence("Busy", { seats: round + 1 }));
+ await vi.advanceTimersByTimeAsync(5_000);
+ }
+ // 60 s of changes every 5 s: a read at the first change, one 30 s later, one at 60 s.
+ expect(refreshed.mock.calls.length).toBeLessThanOrEqual(3);
+ expect(refreshed.mock.calls.length).toBeGreaterThanOrEqual(2);
+ } finally {
+ refresh.stop();
+ }
+ });
+
+ it("never replaces the licence in force with one issued before it, and logs the refusal once", async () => {
+ writeFileSync(keyFile(), licence("Acme", { seats: 30, issued: "2026-11-20" }));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ const older = licence("Acme", { seats: 100, issued: "2026-10-20", expiresAt: "2027-06-01" });
+ writeFileSync(keyFile(), older);
+ await refreshLicense(log);
+ await refreshLicense(log);
+ expect(licenseState()).toMatchObject({ seats: 30 });
+ expect(log).toHaveBeenCalledTimes(1);
+ expect(log.mock.calls[0][0]).toBe(`the licence in ${keyFile()} was issued before the one in license.last-good; using license.last-good instead`);
+ // Without the kept copy the older file is the only licence on offer, and still does not replace the one in force.
+ rmSync(lastGood());
+ await refreshLicense(log);
+ expect(licenseState()).toMatchObject({ seats: 30 });
+ expect(log).toHaveBeenLastCalledWith(`the licence in ${keyFile()} was issued before the one in force; keeping the licence in force until it expires`);
+ // Once the licence in force is past its grace, an older licence still valid is better than none.
+ vi.setSystemTime(at("2027-01-01T00:00:00Z") + 14 * DAY_MS);
+ await refreshLicense(log);
+ expect(licenseState()).toMatchObject({ valid: true, seats: 100 });
+ });
+
+ it("orders the same day's licences by iat when both carry it, else takes the reissue (expiry breaks a tie)", async () => {
+ writeFileSync(keyFile(), licence("Acme", { seats: 20, issued: "2026-11-27", iat: 2_000 }));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ writeFileSync(keyFile(), licence("Acme", { seats: 10, issued: "2026-11-27", iat: 1_000 }));
+ await refreshLicense(log);
+ expect(licenseState().seats).toBe(20);
+ writeFileSync(keyFile(), licence("Acme", { seats: 25, issued: "2026-11-27", iat: 3_000 }));
+ await refreshLicense(log);
+ expect(licenseState().seats).toBe(25);
+ writeFileSync(keyFile(), licence("Acme", { seats: 30, issued: "2026-11-27" }));
+ await refreshLicense(log);
+ expect(licenseState().seats).toBe(30);
+ expect(issuedOrder({ issued: "2026-11-27", expiresAt: "2027-01-01" }, { issued: "2026-11-27", expiresAt: "2026-12-30" })).toBe(1);
+ expect(issuedOrder({ issued: "2026-11-27", expiresAt: null }, { issued: "2026-11-27", expiresAt: "2099-01-01" })).toBe(1);
+ expect(issuedOrder({ issued: "2026-11-27", iat: 5, expiresAt: "2026-12-01" }, { issued: "2026-11-27", iat: 9, expiresAt: "2027-12-01" })).toBe(-1);
+ expect(issuedOrder({ issued: "2026-11-28", expiresAt: "2026-12-01" }, { issued: "2026-11-27", expiresAt: "2027-12-01" })).toBe(1);
+ });
+
+ it("never drops the licence in force for a broken or missing file, logs it once, and keeps it until its grace ends", async () => {
+ writeFileSync(keyFile(), licence("Good"));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ writeFileSync(keyFile(), "half a licence");
+ await refreshLicense(log);
+ await refreshLicense(log);
+ expect(editionStatus()).toMatchObject({ edition: "enterprise", customer: "Good" });
+ expect(entitled("budgets")).toBe(true);
+ expect(log).toHaveBeenCalledTimes(1);
+ expect(log.mock.calls[0][0]).toBe(
+ `the licence in ${keyFile()} was refused: OMB_LICENSE_KEY signature does not match any OpenMausBot signing key; using license.last-good instead`,
+ );
+ rmSync(keyFile());
+ rmSync(lastGood());
+ await refreshLicense(log);
+ expect(editionStatus().customer).toBe("Good");
+ expect(log).toHaveBeenLastCalledWith(`no licence in ${keyFile()} any more; keeping the licence in force until it expires`);
+ // Past its grace the kept licence stops on its own.
+ vi.setSystemTime(at("2027-01-01T00:00:00Z") + 14 * DAY_MS);
+ expect(entitled("budgets")).toBe(false);
+ expect(editionStatus().edition).toBe("oss");
+ });
+
+ it("logs once when the server's clock is more than a day before the licence's issue date", async () => {
+ vi.setSystemTime(at("2026-10-01T00:00:00Z"));
+ writeFileSync(keyFile(), licence("Future", { issued: "2026-11-01" }));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ await refreshLicense(log);
+ const lines = [...warn.mock.calls, ...log.mock.calls].map((call) => String(call[0])).filter((line) => line.includes("clock"));
+ expect(lines).toEqual(["this server's clock says 2026-10-01T00:00:00.000Z, before the licence was issued (2026-11-01): set the clock right, or the licence's dates are judged wrongly"]);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("carries a licence's server id without checking it; the check, when switched on, refuses only a real mismatch", () => {
+ expect(licenseServerRefusal("srv_1", "srv_2")).toBeNull();
+ expect(licenseServerRefusal("srv_1", "srv_2", true)).toBe("the licence was issued for server srv_1, not this one");
+ expect(licenseServerRefusal("srv_1", "srv_1", true)).toBeNull();
+ expect(licenseServerRefusal(undefined, "srv_2", true)).toBeNull();
+ expect(licenseServerRefusal("srv_1", undefined, true)).toBeNull();
+ });
+});
+
+describe("the licence state the owner's Settings reads", () => {
+ it("counts the 14 days of grace to the millisecond with an injected clock, and holds no key material", async () => {
+ writeFileSync(keyFile(), licence("Acme", { seats: 20, plan: "business-server", sub: "sub_1", server: "srv_1" }));
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+ const expiry = at("2027-01-01T00:00:00Z");
+ const before = licenseState(expiry - 1);
+ expect(before).toEqual({
+ valid: true, source: "file", customer: "Acme", plan: "business-server", seats: 20, features: ["budgets"],
+ expiresAt: "2027-01-01", expiresInDays: 1, graceEndsAt: "2027-01-15", graceDaysLeft: null, notice: null,
+ });
+ expect(licenseState(expiry)).toMatchObject({ valid: true, graceDaysLeft: 14 });
+ const lastMoment = licenseState(expiry + 14 * DAY_MS - 1);
+ expect(lastMoment).toMatchObject({ valid: true, features: ["budgets"], graceDaysLeft: 1 });
+ expect(lastMoment.notice).toBe("license.key expired on 2027-01-01; enterprise features keep working until 2027-01-15 while it is renewed");
+ const over = licenseState(expiry + 14 * DAY_MS);
+ expect(over).toMatchObject({ valid: false, source: "file", expiresAt: "2027-01-01", features: [], graceDaysLeft: 0 });
+ expect(over.notice).toBe("enterprise layer disabled: license.key expired on 2027-01-01; renew it to keep enterprise features");
+ for (const state of [before, over]) {
+ const text = JSON.stringify(state);
+ expect(text).not.toContain("lic:");
+ expect(text).not.toContain("sub_1");
+ expect(text).not.toContain("srv_1");
+ }
+ });
+});
diff --git a/server/license-source.test.ts b/server/license-source.test.ts
new file mode 100644
index 0000000000..896a1c89b8
--- /dev/null
+++ b/server/license-source.test.ts
@@ -0,0 +1,103 @@
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { LICENSE_REREAD_MS, licenseFilePath, readLicenseFile, startLicenseRefresh, writeLastGood } from "./license-source.ts";
+
+const dirs: string[] = [];
+const temp = () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-license-source-"));
+ dirs.push(dir);
+ return dir;
+};
+const posix = process.platform !== "win32";
+
+afterEach(() => {
+ vi.useRealTimers();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("reading license.key", () => {
+ it("reads the key trimmed, treats a missing or empty file as none, and never throws", async () => {
+ const data = temp();
+ expect(licenseFilePath(data)).toBe(join(data, "license.key"));
+ expect(await readLicenseFile(data)).toEqual({ state: "absent" });
+ expect(await readLicenseFile(join(data, "no-such-folder"))).toEqual({ state: "absent" });
+ writeFileSync(join(data, "license.key"), " \r\n");
+ expect(await readLicenseFile(data)).toEqual({ state: "absent" });
+ writeFileSync(join(data, "license.key"), "omb1.claims.signature\r\n");
+ expect(await readLicenseFile(data)).toEqual({ state: "present", key: "omb1.claims.signature" });
+ });
+
+ it("refuses to read what cannot be a licence: a folder, or a large file", async () => {
+ const data = temp();
+ mkdirSync(join(data, "license.key"));
+ expect(await readLicenseFile(data)).toEqual({ state: "unreadable", error: `${join(data, "license.key")} is not a file` });
+ const other = temp();
+ writeFileSync(join(other, "license.key"), "x".repeat(64 * 1024 + 1));
+ expect(await readLicenseFile(other)).toEqual({ state: "unreadable", error: `${join(other, "license.key")} is too large to be a licence` });
+ });
+
+ it.skipIf(!posix)("never waits on a pipe and never follows a link", async () => {
+ const data = temp();
+ const made = spawnSync("mkfifo", [join(data, "license.key")]);
+ if (made.status === 0) {
+ // A read that waited on the pipe would never settle; this one answers at once.
+ expect(await readLicenseFile(data)).toEqual({ state: "unreadable", error: `${join(data, "license.key")} is not a file` });
+ rmSync(join(data, "license.key"));
+ }
+ writeFileSync(join(data, "elsewhere"), "omb1.claims.signature");
+ symlinkSync(join(data, "elsewhere"), join(data, "license.key"));
+ expect(await readLicenseFile(data)).toEqual({ state: "unreadable", error: `${join(data, "license.key")} is a link; put the licence itself there` });
+ });
+});
+
+describe("the kept copy of the last good licence", () => {
+ it("is written in one step, readable by this user only, and not rewritten when unchanged", async () => {
+ const data = temp();
+ await writeLastGood(data, "omb1.first.key");
+ const path = join(data, "license.last-good");
+ expect(readFileSync(path, "utf8")).toBe("omb1.first.key\n");
+ if (posix) expect(statSync(path).mode & 0o777).toBe(0o600);
+ const written = statSync(path).mtimeMs;
+ await writeLastGood(data, "omb1.first.key");
+ expect(statSync(path).mtimeMs).toBe(written);
+ await writeLastGood(data, "omb1.second.key");
+ expect(readFileSync(path, "utf8")).toBe("omb1.second.key\n");
+ expect(readdirSync(data)).toEqual(["license.last-good"]); // no temporary file left behind
+ });
+});
+
+describe("re-reading it", () => {
+ it("reads hourly, keeps going after a failed read, and stops", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] });
+ const log = vi.fn<(line: string) => void>();
+ const refresh = vi.fn<() => Promise<unknown>>().mockRejectedValueOnce(new Error("disk gone")).mockResolvedValue(undefined);
+ const running = startLicenseRefresh({ dataDir: temp(), refresh, log });
+ await vi.advanceTimersByTimeAsync(LICENSE_REREAD_MS);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ expect(log).toHaveBeenCalledWith("licence re-read failed: disk gone");
+ await vi.advanceTimersByTimeAsync(LICENSE_REREAD_MS);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ running.stop();
+ await vi.advanceTimersByTimeAsync(3 * LICENSE_REREAD_MS);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it("never keeps the process alive", () => {
+ const data = temp();
+ writeFileSync(join(data, "license.key"), "omb1.claims.signature");
+ const source = pathToFileURL(join(import.meta.dirname, "license-source.ts")).href;
+ const program = `import { startLicenseRefresh } from ${JSON.stringify(source)};
+ startLicenseRefresh({ dataDir: ${JSON.stringify(data)}, refresh: async () => {} });
+ console.log("started");`;
+ const child = spawnSync(process.execPath, ["--input-type=module", "-e", program], { encoding: "utf8", timeout: 30_000 });
+ expect(child.error).toBeUndefined();
+ expect(child.signal).toBeNull();
+ expect(child.stdout.trim()).toBe("started");
+ expect(child.status, child.stderr).toBe(0);
+ });
+});
diff --git a/server/license-source.ts b/server/license-source.ts
new file mode 100644
index 0000000000..6790e4809e
--- /dev/null
+++ b/server/license-source.ts
@@ -0,0 +1,173 @@
+// Where the enterprise licence comes from: `<data>/license.key`, OMB_LICENSE_KEY, and `<data>/license.last-good` (the
+// last licence this server accepted, so a restart with a broken or missing file keeps a licence still in its paid period).
+// A pasted licence and one the MausBot connector refreshes land in license.key and take effect without a restart: on a
+// server install the file is checked once a minute (size, change time, inode; never its folder, where the databases
+// write constantly) and read every hour. Reading never throws or hangs; which licence wins is decided in enterprise.ts.
+import { constants } from "node:fs";
+import { open, rename, stat, unlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { SERVER_ROOT } from "./proxy-paths.ts";
+import { installKind } from "./update-check.ts";
+
+export const LICENSE_FILE = "license.key";
+export const LAST_GOOD_FILE = "license.last-good";
+export const LICENSE_REREAD_MS = 60 * 60_000;
+/** How often the file's size, change time and inode are compared: one stat a minute. */
+export const LICENSE_CHECK_MS = 60_000;
+/** Never two reads closer than this, however often the file changes. */
+export const LICENSE_MIN_GAP_MS = 30_000;
+/** A licence is well under 1 KB; anything bigger than this is not one, and is not read past it. */
+export const MAX_LICENSE_BYTES = 64 * 1024;
+
+/** Where licence files are used. `none`: a desktop, a Cloud home or a hosted workspace, which read OMB_LICENSE_KEY alone,
+ * as before licence files existed. `server`: the Docker image or the rootless Podman service, as the installer sets a
+ * server up (installKind, the same marker the Update server button goes by): the minute check runs even before any
+ * licence exists, because a bought server's first licence arrives through the connector after it is installed. `files`:
+ * any other server (a checkout, npm): the files are read, and the minute check runs only when there was a licence at
+ * start. */
+export type LicensePlace = "none" | "files" | "server";
+export function licensePlace(input: {
+ desktopManaged: boolean;
+ cloudHome: boolean;
+ hostedWorkspace: boolean;
+ serverRoot?: string;
+ exists?: (path: string) => boolean;
+ env?: NodeJS.ProcessEnv;
+}): LicensePlace {
+ if (input.desktopManaged || input.cloudHome || input.hostedWorkspace) return "none";
+ const kind = installKind({ desktopManaged: false, managed: false, serverRoot: input.serverRoot ?? SERVER_ROOT, exists: input.exists, env: input.env });
+ return kind === "docker" || kind === "podman" || kind === "podman-service" ? "server" : "files";
+}
+
+/** `last-good`: the copy this server keeps of the last licence it accepted. */
+export type LicenseSource = "file" | "env" | "last-good";
+export type LicenseFileRead =
+ | { state: "absent" }
+ | { state: "present"; key: string }
+ | { state: "unreadable"; error: string };
+
+export function licenseFilePath(dataDir: string, name: string = LICENSE_FILE): string {
+ return join(dataDir, name);
+}
+
+// No following a link (a link could point anywhere) and no waiting on a pipe: a FIFO opens at once, is seen not to be a
+// file, and is never read. Neither flag exists on Windows, where neither case blocks either.
+const OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
+
+/** Opens the file once and reads at most MAX_LICENSE_BYTES + 1 bytes from that handle, so a file swapped for a huge
+ * one between checks is never read whole. An empty file counts as none. */
+export async function readLicenseFile(dataDir: string, name: string = LICENSE_FILE): Promise<LicenseFileRead> {
+ const path = licenseFilePath(dataDir, name);
+ let handle;
+ try {
+ handle = await open(path, OPEN_FLAGS);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === "ENOENT" || code === "ENOTDIR") return { state: "absent" };
+ if (code === "ELOOP") return { state: "unreadable", error: `${path} is a link; put the licence itself there` };
+ if (code === "EISDIR") return { state: "unreadable", error: `${path} is not a file` };
+ return { state: "unreadable", error: `${path} could not be read (${code ?? (error instanceof Error ? error.message : String(error))})` };
+ }
+ try {
+ const info = await handle.stat();
+ if (!info.isFile()) return { state: "unreadable", error: `${path} is not a file` };
+ if (info.size > MAX_LICENSE_BYTES) return { state: "unreadable", error: `${path} is too large to be a licence` };
+ const buffer = Buffer.alloc(MAX_LICENSE_BYTES + 1);
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > MAX_LICENSE_BYTES) return { state: "unreadable", error: `${path} is too large to be a licence` };
+ const key = buffer.subarray(0, bytesRead).toString("utf8").trim();
+ return key ? { state: "present", key } : { state: "absent" };
+ } catch (error) {
+ return { state: "unreadable", error: `${path} could not be read (${(error as NodeJS.ErrnoException).code ?? String(error)})` };
+ } finally {
+ await handle.close().catch(() => {});
+ }
+}
+
+/** Keeps the licence just accepted, replaced in one step (a temporary file, then a rename), readable by this user only. */
+export async function writeLastGood(dataDir: string, key: string): Promise<void> {
+ const path = licenseFilePath(dataDir, LAST_GOOD_FILE);
+ const kept = await readLicenseFile(dataDir, LAST_GOOD_FILE);
+ if (kept.state === "present" && kept.key === key) return;
+ const temporary = `${path}.${process.pid}.tmp`;
+ try {
+ await writeFile(temporary, `${key}\n`, { mode: 0o600 });
+ await rename(temporary, path);
+ } catch (error) {
+ await unlink(temporary).catch(() => {});
+ throw error;
+ }
+}
+
+/** Size, change time and inode of license.key, or "absent": what the minute check compares. */
+export async function licenseFileStamp(dataDir: string): Promise<string> {
+ try {
+ const info = await stat(licenseFilePath(dataDir));
+ return `${info.size}:${info.mtimeMs}:${info.ctimeMs}:${info.ino}`;
+ } catch {
+ return "absent";
+ }
+}
+
+export interface LicenseRefreshOptions {
+ dataDir: string;
+ refresh(): Promise<unknown>;
+ log?(line: string): void;
+ intervalMs?: number;
+ checkMs?: number;
+ minGapMs?: number;
+ now?(): number;
+ /** What the minute check compares; licenseFileStamp by default. */
+ stamp?(): Promise<string>;
+}
+
+/** Reads hourly, and after the minute check sees license.key change, never twice within LICENSE_MIN_GAP_MS. Started
+ * only on a server install that has or had a licence (server/index.ts); its timers never keep the process alive. */
+export function startLicenseRefresh(options: LicenseRefreshOptions): { stop(): void } {
+ const log = options.log ?? ((line: string) => console.warn(line));
+ const now = options.now ?? Date.now;
+ const minGap = options.minGapMs ?? LICENSE_MIN_GAP_MS;
+ let lastRun = Number.NEGATIVE_INFINITY;
+ let deferred: ReturnType<typeof setTimeout> | null = null;
+ let stopped = false;
+ const run = () => {
+ if (stopped) return;
+ const wait = lastRun + minGap - now();
+ if (wait > 0) {
+ if (!deferred) {
+ deferred = setTimeout(() => { deferred = null; run(); }, wait);
+ deferred.unref?.();
+ }
+ return;
+ }
+ lastRun = now();
+ void options.refresh().catch((error: unknown) => log(`licence re-read failed: ${error instanceof Error ? error.message : String(error)}`));
+ };
+ let stamp: string | null = null;
+ let checking = false;
+ const check = async () => {
+ if (checking || stopped) return;
+ checking = true;
+ try {
+ const next = await (options.stamp ? options.stamp() : licenseFileStamp(options.dataDir));
+ if (stamp !== null && next !== stamp) run();
+ stamp = next;
+ } finally {
+ checking = false;
+ }
+ };
+ void check();
+ const hourly = setInterval(run, options.intervalMs ?? LICENSE_REREAD_MS);
+ hourly.unref?.();
+ const minute = setInterval(() => { void check(); }, options.checkMs ?? LICENSE_CHECK_MS);
+ minute.unref?.();
+ return {
+ stop() {
+ stopped = true;
+ clearInterval(hourly);
+ clearInterval(minute);
+ if (deferred) clearTimeout(deferred);
+ },
+ };
+}
diff --git a/server/routes/license.test.ts b/server/routes/license.test.ts
new file mode 100644
index 0000000000..f5bf34ce82
--- /dev/null
+++ b/server/routes/license.test.ts
@@ -0,0 +1,88 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+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 { dispatchRoutes, ROUTES } from "./table.ts";
+
+const servers: Server[] = [];
+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 });
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+async function serve(auth: RequestAuth): Promise<string> {
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const handled = await dispatchRoutes(ROUTES, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (!handled) json(res, 404, {});
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+const session = (scopes: ("admin" | "client")[]): RequestAuth =>
+ ({ kind: "session", via: "bearer", scopes, session: {} as never });
+
+describe("GET /api/license", () => {
+ it("is listed with the other routes, needs the admin scope, and is never open to a bot shell", () => {
+ expect(ROUTES).toContain(licenseRoutes);
+ expect(requiredScope("GET", LICENSE_PATH)).toBe("admin");
+ expect(serviceAllowed("GET", LICENSE_PATH)).toBe(false);
+ });
+
+ it("tells the owner the licence state, and never the key", async () => {
+ 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({ licenseKey }) { return { customer: "Acme", features: ["budgets"], expiresAt: "2099-01-01", seats: 20, plan: "business-server", sub: "sub_secret_id", server: licenseKey.slice(0, 4) }; }`);
+ const key = "omb1.eyJjbGFpbXMiOnRydWV9.c2lnbmF0dXJl";
+ writeFileSync(join(data, "license.key"), key);
+ await loadEnterpriseLayer({ dir: layer, dataDir: data, licenseKey: undefined });
+
+ const base = await serve({ kind: "loopback", scopes: ["admin", "client"] });
+ const response = await fetch(`${base}/api/license`);
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ const text = await response.text();
+ expect(JSON.parse(text)).toMatchObject({
+ valid: true, source: "file", customer: "Acme", plan: "business-server", seats: 20, features: ["budgets"],
+ expiresAt: "2099-01-01", graceEndsAt: "2099-01-15", graceDaysLeft: null, notice: null,
+ });
+ expect(text).not.toContain("omb1");
+ expect(text).not.toContain("c2lnbmF0dXJl");
+ expect(text).not.toContain("sub_secret_id");
+ expect((await fetch(`${base}/api/license`, { method: "POST" })).status).toBe(405);
+
+ const admin = await serve(session(["admin", "client"]));
+ expect((await fetch(`${admin}/api/license`)).status).toBe(200);
+ });
+
+ it("answers an unlicensed server too: not valid, nothing held", async () => {
+ const base = await serve({ kind: "loopback", scopes: ["admin", "client"] });
+ 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,
+ });
+ });
+
+ it("refuses a bot shell on a shared server and a chat-only session", async () => {
+ for (const auth of [{ kind: "loopback", scopes: ["client"], trust: "service" } as RequestAuth, session(["client"])]) {
+ const base = await serve(auth);
+ const response = await fetch(`${base}/api/license`);
+ expect(response.status).toBe(403);
+ expect(await response.text()).not.toContain("valid");
+ }
+ });
+});
diff --git a/server/routes/license.ts b/server/routes/license.ts
new file mode 100644
index 0000000000..64add68032
--- /dev/null
+++ b/server/routes/license.ts
@@ -0,0 +1,17 @@
+// 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";
+import { ownerOrAdmin } from "../request-auth.ts";
+import { PASS, type RouteContext } from "./table.ts";
+
+export const LICENSE_PATH = "/api/license";
+
+// 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> {
+ 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." });
+ res.setHeader("cache-control", "no-store");
+ return json(res, 200, licenseState());
+}
diff --git a/server/routes/table.ts b/server/routes/table.ts
index a587fa2607..c38c1898ae 100644
--- a/server/routes/table.ts
+++ b/server/routes/table.ts
@@ -4,6 +4,7 @@ import type { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
import { announcementRoutes } from "./announcements.ts";
import { cloudSyncRoutes } from "./cloud-sync.ts";
+import { licenseRoutes } from "./license.ts";
import { ownMcpHttpRoutes } from "./own-mcp-http.ts";
import { webPanelRoutes } from "./web-panels.ts";
@@ -24,7 +25,7 @@ export interface RouteContext {
export type RouteHandler = (ctx: RouteContext) => Promise<typeof PASS | void>;
/** Modules with no wiring from index.ts are listed here; index.ts pushes the rest. */
-export const ROUTES: RouteHandler[] = [cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes, announcementRoutes];
+export const ROUTES: RouteHandler[] = [cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes, announcementRoutes, licenseRoutes];
/** True means stop routing. A handler that wrote a response but returned PASS still counts as answered. */
export async function dispatchRoutes(routes: readonly RouteHandler[], ctx: RouteContext): Promise<boolean> {