From eac575ea0fa98781389e20bc4db4a7a0d28f7f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ant=C3=B4nio=20Miranda?= Date: Mon, 30 Nov 2026 21:51:24 -0300 Subject: [PATCH 1/5] feat(protocol): role grants can list the commands a member key may run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A grant may carry a closed list of command types. The agent then accepts only commands in that list and within the grant's role (role ∩ commands). Old agents reject such grants because the schema is strict, so they fail closed. --- src/agent/jobs.ts | 7 +- src/agent/members.ts | 1 + src/agent/state.ts | 14 ++ src/protocol/command.ts | 9 +- src/protocol/errors.ts | 1 + src/protocol/grant-commands.test.ts | 317 ++++++++++++++++++++++++++++ src/protocol/index.ts | 1 + src/protocol/roles.ts | 74 ++++++- src/protocol/trust.ts | 18 ++ 9 files changed, 436 insertions(+), 6 deletions(-) create mode 100644 src/protocol/grant-commands.test.ts diff --git a/src/agent/jobs.ts b/src/agent/jobs.ts index 3645855..6d7991f 100644 --- a/src/agent/jobs.ts +++ b/src/agent/jobs.ts @@ -191,7 +191,12 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { typeof (body as { server_id: unknown }).server_id === "string" ? (body as { server_id: string }).server_id : "*"; - return roleAtLeast(trust.roleFor(opened.accountId, scope), definition?.minRole ?? "owner"); + return trust.mayRun( + opened.accountId, + scope, + opened.header.type, + definition?.minRole ?? "owner", + ); } function sendSealedEvent(type: string, body: unknown, recipientPublicKey: PublicKey): void { diff --git a/src/agent/members.ts b/src/agent/members.ts index 4d9024c..9ba88ea 100644 --- a/src/agent/members.ts +++ b/src/agent/members.ts @@ -99,6 +99,7 @@ export function applyMembersSet( granted_by: opened.accountId, role: grant.role, servers: grant.servers, + ...(grant.commands !== undefined ? { commands: grant.commands } : {}), issued_at: grant.issued_at, ...(grant.expires_at !== undefined ? { expires_at: grant.expires_at } : {}), }; diff --git a/src/agent/state.ts b/src/agent/state.ts index 191da69..8654950 100644 --- a/src/agent/state.ts +++ b/src/agent/state.ts @@ -796,6 +796,20 @@ export function createFileTrustContext(options: FileTrustContextOptions): FileTr return memberTable().roleFor(account, serverId, clock()); }, + mayRun(account: KeyId, serverId: string, type: string, minRole: Role): boolean { + if (ownerKey(account) !== null) { + return true; + } + return memberTable().commandAllowed(account, serverId, type, minRole, clock()); + }, + + isRestricted(account: KeyId): boolean { + if (ownerKey(account) !== null) { + return false; + } + return memberTable().isRestricted(account, clock()); + }, + listMembers(): readonly MemberEntry[] { return loadMembers(options.stateDir); }, diff --git a/src/protocol/command.ts b/src/protocol/command.ts index 817ac4d..b160f2f 100644 --- a/src/protocol/command.ts +++ b/src/protocol/command.ts @@ -18,7 +18,7 @@ import { import { assertSupportedVersion, concatBytes, DOMAIN_COMMAND, PROTOCOL_VERSION } from "./domains"; import { ProtocolError } from "./errors"; import type { CommandRegistry } from "./registry"; -import { type Role, roleAtLeast } from "./roles"; +import type { Role } from "./roles"; import { type CommandHeader, type KeyId, @@ -295,9 +295,14 @@ export async function openCommand( ? (bodyResult.data as { server_id: string }).server_id : "*"; const role = trust.roleFor(accountId, scope); - if (role === null || !roleAtLeast(role, definition.minRole)) { + if (role === null) { throw new ProtocolError("insufficient_role", "Account role is below the command's minimum"); } + if (!trust.mayRun(accountId, scope, header.type, definition.minRole)) { + throw trust.isRestricted(accountId) + ? new ProtocolError("command_not_granted", "This key may not run this command") + : new ProtocolError("insufficient_role", "Account role is below the command's minimum"); + } return { header, diff --git a/src/protocol/errors.ts b/src/protocol/errors.ts index 0243799..ebd36de 100644 --- a/src/protocol/errors.ts +++ b/src/protocol/errors.ts @@ -21,6 +21,7 @@ export type ProtocolErrorCode = | "account_key_required" | "decrypt_failed" | "insufficient_role" + | "command_not_granted" | "too_many_subscribers" | "role_grant_invalid" | "auth_invalid" diff --git a/src/protocol/grant-commands.test.ts b/src/protocol/grant-commands.test.ts new file mode 100644 index 0000000..26b39f3 --- /dev/null +++ b/src/protocol/grant-commands.test.ts @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { beforeAll, describe, expect, test } from "bun:test"; +import { applyMembersSet } from "../agent/members"; +import { fingerprint, generateSigningKeyPair, ready, toBase64Url } from "../crypto"; +import { + agentMembersSetBodySchema, + createCoreRegistry, + createInMemoryTrustContext, + createSignedCommand, + type MemberEntry, + openCommand, + ProtocolError, + type ProtocolErrorCode, + type Role, + RoleTable, + signRoleGrant, + verifyRoleGrant, +} from "./index"; + +const NOW = 1_700_000_000_000; +const GRANTER = "a".repeat(32); + +beforeAll(async () => { + await ready(); +}); + +function expectThrowCode(fn: () => unknown, code: ProtocolErrorCode): void { + try { + fn(); + } catch (err) { + expect(err).toBeInstanceOf(ProtocolError); + expect((err as ProtocolError).code).toBe(code); + return; + } + throw new Error(`Expected ProtocolError ${code}`); +} + +function memberEntry( + accountKey: string, + account: string, + over: Partial = {}, +): MemberEntry { + return { + account_key: accountKey, + account, + granted_by: GRANTER, + role: "operator", + servers: ["srv-a"], + issued_at: NOW, + ...over, + }; +} + +function setup(commands?: readonly string[]) { + const agent = generateSigningKeyPair(); + const owner = generateSigningKeyPair(); + const account = generateSigningKeyPair(); + const accountId = fingerprint(account.publicKey); + const registry = createCoreRegistry(); + const trust = createInMemoryTrustContext({ + agentKeyPair: agent, + trustedAccountKeys: [owner.publicKey], + members: [ + memberEntry(toBase64Url(account.publicKey), accountId, { + ...(commands !== undefined ? { commands: [...commands] } : {}), + }), + ], + now: () => NOW, + }); + let counter = 0; + + async function run(type: string, body: unknown): Promise<"ok" | ProtocolErrorCode> { + const command = createSignedCommand( + { + type, + body, + agentPublicKey: agent.publicKey, + signer: account, + counter: ++counter, + now: NOW, + }, + registry, + ); + try { + await openCommand(command, trust, registry); + return "ok"; + } catch (err) { + if (err instanceof ProtocolError) { + return err.code; + } + throw err; + } + } + + return { agent, owner, account, accountId, registry, trust, run }; +} + +describe("grants with a command list", () => { + test("only the listed command types run, and only where the role applies", async () => { + const { run } = setup(["server.status", "server.start"]); + + expect(await run("server.start", { server_id: "srv-a" })).toBe("ok"); + expect(await run("server.status", { server_id: "srv-a" })).toBe("ok"); + expect(await run("server.stop", { server_id: "srv-a" })).toBe("command_not_granted"); + expect(await run("server.start", { server_id: "srv-b" })).toBe("insufficient_role"); + expect(await run("server.console.send", { server_id: "srv-a", line: "list" })).toBe( + "command_not_granted", + ); + }); + + test("agent-level commands also follow the list", async () => { + const { run } = setup(["server.list"]); + + expect(await run("server.list", {})).toBe("ok"); + expect(await run("host.info", {})).toBe("command_not_granted"); + }); + + test("a grant without commands keeps the role's whole command set", async () => { + const { run } = setup(); + + expect(await run("server.console.send", { server_id: "srv-a", line: "list" })).toBe("ok"); + expect(await run("server.stop", { server_id: "srv-a" })).toBe("ok"); + }); + + test("owners are never restricted by a command list", () => { + const agent = generateSigningKeyPair(); + const owner = generateSigningKeyPair(); + const account = generateSigningKeyPair(); + const ownerId = fingerprint(owner.publicKey); + const accountId = fingerprint(account.publicKey); + const trust = createInMemoryTrustContext({ + agentKeyPair: agent, + trustedAccountKeys: [owner.publicKey], + members: [ + memberEntry(toBase64Url(account.publicKey), accountId, { commands: ["server.start"] }), + ], + now: () => NOW, + }); + + expect(trust.isRestricted(ownerId)).toBe(false); + expect(trust.mayRun(ownerId, "srv-a", "server.delete", "admin")).toBe(true); + expect(trust.isRestricted(accountId)).toBe(true); + expect(trust.mayRun(accountId, "srv-a", "server.start", "operator")).toBe(true); + expect(trust.mayRun(accountId, "srv-a", "server.stop", "operator")).toBe(false); + }); +}); + +describe("signing grants with commands", () => { + function signedGrant(commands?: readonly string[], over: Record = {}) { + const owner = generateSigningKeyPair(); + const member = generateSigningKeyPair(); + const grant = signRoleGrant({ + granter: owner, + accountPublicKey: member.publicKey, + agent: GRANTER, + servers: ["srv-a"], + role: "operator", + ...(commands !== undefined ? { commands } : {}), + issuedAt: NOW, + ...over, + }); + return { owner, grant }; + } + + test("commands round-trip through the signature", () => { + const { owner, grant } = signedGrant(["server.start", "server.status"]); + const verified = verifyRoleGrant(grant, owner.publicKey, { agent: GRANTER, now: NOW }); + expect(verified.grant.commands).toEqual(["server.start", "server.status"]); + }); + + test("signRoleGrant refuses a duplicate command", () => { + expect(() => signedGrant(["server.start", "server.start"])).toThrow(RangeError); + }); + + test("verifyRoleGrant refuses a forged duplicate command", () => { + const { owner, grant } = signedGrant(["server.start"]); + expectThrowCode( + () => + verifyRoleGrant({ ...grant, commands: ["server.start", "server.start"] }, owner.publicKey, { + agent: GRANTER, + now: NOW, + }), + "role_grant_invalid", + ); + }); + + test("an unknown field is still refused", () => { + const { owner, grant } = signedGrant(["server.start"]); + expectThrowCode( + () => + verifyRoleGrant({ ...grant, extra: true }, owner.publicKey, { agent: GRANTER, now: NOW }), + "role_grant_invalid", + ); + }); + + test("changing the command list after signing breaks the signature", () => { + const { owner, grant } = signedGrant(["server.start"]); + expectThrowCode( + () => + verifyRoleGrant({ ...grant, commands: ["server.stop"] }, owner.publicKey, { + agent: GRANTER, + now: NOW, + }), + "role_grant_invalid", + ); + expectThrowCode( + () => + verifyRoleGrant({ ...grant, commands: ["server.start", "server.stop"] }, owner.publicKey, { + agent: GRANTER, + now: NOW, + }), + "role_grant_invalid", + ); + }); +}); + +describe("RoleTable with command lists", () => { + test("set keeps an open and a restricted grant for the same account and servers", () => { + const account = "b".repeat(32); + const key = toBase64Url(generateSigningKeyPair().publicKey); + const table = new RoleTable(); + table.set(memberEntry(key, account)); + table.set(memberEntry(key, account, { commands: ["server.start"] })); + + const entries = table.entries(); + expect(entries).toHaveLength(2); + expect(entries.filter((entry) => entry.commands === undefined)).toHaveLength(1); + expect(entries.filter((entry) => entry.commands !== undefined)).toHaveLength(1); + }); + + test("commandAllowed intersects the role with the command list", () => { + const account = "b".repeat(32); + const key = toBase64Url(generateSigningKeyPair().publicKey); + const table = new RoleTable([ + memberEntry(key, account, { role: "operator", commands: ["server.start"] }), + ]); + + expect(table.commandAllowed(account, "srv-a", "server.start", "operator", NOW)).toBe(true); + expect(table.commandAllowed(account, "srv-a", "server.stop", "operator", NOW)).toBe(false); + expect(table.commandAllowed(account, "srv-b", "server.start", "operator", NOW)).toBe(false); + expect(table.commandAllowed(account, "*", "server.list", "viewer", NOW)).toBe(false); + expect(table.isRestricted(account, NOW)).toBe(true); + expect(table.isRestricted(account, NOW + 1)).toBe(true); + + const open = new RoleTable([memberEntry(key, account, { role: "viewer" })]); + expect(open.commandAllowed(account, "*", "host.info", "viewer", NOW)).toBe(true); + expect(open.isRestricted(account, NOW)).toBe(false); + + const perServer = new RoleTable([memberEntry(key, account, { servers: ["srv-a"] })]); + expect(perServer.commandAllowed(account, "*", "server.list", "viewer", NOW)).toBe(true); + expect(perServer.commandAllowed(account, "*", "agent.members.set", "admin", NOW)).toBe(false); + }); + + test("an expired grant is neither allowed nor restrictive", () => { + const account = "b".repeat(32); + const key = toBase64Url(generateSigningKeyPair().publicKey); + const table = new RoleTable([ + memberEntry(key, account, { expires_at: NOW + 1000, commands: ["server.start"] }), + ]); + + expect(table.commandAllowed(account, "srv-a", "server.start", "operator", NOW)).toBe(true); + expect(table.isRestricted(account, NOW)).toBe(true); + expect(table.commandAllowed(account, "srv-a", "server.start", "operator", NOW + 1000)).toBe( + false, + ); + expect(table.isRestricted(account, NOW + 1000)).toBe(false); + }); +}); + +describe("members.set", () => { + test("stores the grant's command list in the member entry", async () => { + const agent = generateSigningKeyPair(); + const owner = generateSigningKeyPair(); + const member = generateSigningKeyPair(); + const agentId = fingerprint(agent.publicKey); + const registry = createCoreRegistry(); + const trust = createInMemoryTrustContext({ + agentKeyPair: agent, + trustedAccountKeys: [owner.publicKey], + now: () => NOW, + }); + const grant = signRoleGrant({ + granter: owner, + accountPublicKey: member.publicKey, + agent: agentId, + servers: ["srv-a"], + role: "operator", + commands: ["server.start"], + issuedAt: NOW, + }); + const command = createSignedCommand( + { + type: "agent.members.set", + body: { grant }, + agentPublicKey: agent.publicKey, + signer: owner, + counter: 1, + now: NOW, + }, + registry, + ); + const opened = await openCommand(command, trust, registry); + const body = agentMembersSetBodySchema.parse(opened.body); + const entry = applyMembersSet(opened, body, { trust, store: trust, agentId }, NOW); + + expect(entry.commands).toEqual(["server.start"]); + expect(trust.listMembers()).toHaveLength(1); + expect(trust.listMembers()[0]?.commands).toEqual(["server.start"]); + expect(trust.isRestricted(fingerprint(member.publicKey))).toBe(true); + const minRole: Role = "operator"; + expect(trust.mayRun(fingerprint(member.publicKey), "srv-a", "server.stop", minRole)).toBe( + false, + ); + }); +}); diff --git a/src/protocol/index.ts b/src/protocol/index.ts index a91ff62..14c64ef 100644 --- a/src/protocol/index.ts +++ b/src/protocol/index.ts @@ -373,6 +373,7 @@ export { type GrantableRole, grantableRoleSchema, MAX_GRANT_CLOCK_SKEW_MS, + MAX_GRANT_COMMANDS, MAX_GRANT_SERVERS, MAX_MEMBERS, type MemberEntry, diff --git a/src/protocol/roles.ts b/src/protocol/roles.ts index 77145bb..aff4670 100644 --- a/src/protocol/roles.ts +++ b/src/protocol/roles.ts @@ -50,6 +50,7 @@ export function maxRole(a: T | null, b: T | null): T | null { export const ALL_SERVERS = "*" as const; export const MAX_GRANT_SERVERS = 256; +export const MAX_GRANT_COMMANDS = 32; export const MAX_MEMBERS = 64; const grantServerIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "Invalid server id"); @@ -59,6 +60,10 @@ const grantServersSchema = z.union([ z.array(grantServerIdSchema).min(1).max(MAX_GRANT_SERVERS), ]); +const grantCommandSchema = z.string().regex(/^[a-z][a-z0-9_.]{0,63}$/); + +const grantCommandsSchema = z.array(grantCommandSchema).min(1).max(MAX_GRANT_COMMANDS); + export const roleGrantSchema = z .object({ v: z.literal(PROTOCOL_VERSION), @@ -67,6 +72,7 @@ export const roleGrantSchema = z agent: keyIdSchema, servers: grantServersSchema, role: grantableRoleSchema, + commands: grantCommandsSchema.optional(), issued_at: z.number().int().nonnegative(), expires_at: z.number().int().nonnegative().optional(), sig: base64UrlSchema, @@ -82,6 +88,8 @@ export interface SignRoleGrantParams { readonly agent: KeyId; readonly servers: readonly string[] | typeof ALL_SERVERS; readonly role: GrantableRole; + /** Command types this key may run, on top of the role's own permissions. */ + readonly commands?: readonly string[]; readonly issuedAt: number; readonly expiresAt?: number; } @@ -99,6 +107,9 @@ export function signRoleGrant(params: SignRoleGrantParams): RoleGrant { ) { throw new RangeError("expiresAt must be a safe integer after issuedAt"); } + if (params.commands !== undefined && new Set(params.commands).size !== params.commands.length) { + throw new RangeError("commands must not contain duplicates"); + } const unsigned = { v: PROTOCOL_VERSION, @@ -107,6 +118,7 @@ export function signRoleGrant(params: SignRoleGrantParams): RoleGrant { agent: params.agent, servers: params.servers === ALL_SERVERS ? ALL_SERVERS : [...params.servers], role: params.role, + ...(params.commands !== undefined ? { commands: [...params.commands] } : {}), issued_at: params.issuedAt, ...(params.expiresAt !== undefined ? { expires_at: params.expiresAt } : {}), }; @@ -155,6 +167,9 @@ export function verifyRoleGrant( if (data.servers !== ALL_SERVERS && new Set(data.servers).size !== data.servers.length) { throw new ProtocolError("role_grant_invalid", "Role grant lists a server more than once"); } + if (data.commands !== undefined && new Set(data.commands).size !== data.commands.length) { + throw new ProtocolError("role_grant_invalid", "Role grant lists a command more than once"); + } let accountPublicKey: Uint8Array; let signatureBytes: Uint8Array; @@ -185,16 +200,26 @@ export const memberEntrySchema = z granted_by: keyIdSchema, role: grantableRoleSchema, servers: grantServersSchema, + commands: grantCommandsSchema.optional(), issued_at: z.number().int().nonnegative(), expires_at: z.number().int().nonnegative().optional(), }) .strict(); export type MemberEntry = z.infer; -function scopeKey(servers: MemberEntry["servers"]): string { +function serverScopeKey(servers: MemberEntry["servers"]): string { return servers === ALL_SERVERS ? ALL_SERVERS : [...servers].sort().join(","); } +function commandScopeKey(commands: MemberEntry["commands"]): string { + return commands === undefined ? "" : [...commands].sort().join(","); +} + +/** Entries with the same account, servers and command list replace each other. */ +function scopeKey(entry: MemberEntry): string { + return `${serverScopeKey(entry.servers)}|${commandScopeKey(entry.commands)}`; +} + function isActive(entry: MemberEntry, now: number): boolean { return entry.expires_at === undefined || now < entry.expires_at; } @@ -258,10 +283,53 @@ export class RoleTable { return best; } + /** + * Whether `account` may run a command of `type` on `serverId` at `minRole`. + * A grant that lists `commands` only allows those types, so the answer is the + * intersection of the role's permissions and the grant's command list. + */ + commandAllowed( + account: KeyId, + serverId: string, + type: string, + minRole: Role, + now: number, + ): boolean { + for (const entry of this.#entries) { + if (entry.account !== account || !isActive(entry, now)) { + continue; + } + if (entry.commands !== undefined && !entry.commands.includes(type)) { + continue; + } + const covers = + entry.servers === ALL_SERVERS || + (serverId !== ALL_SERVERS && entry.servers.includes(serverId)); + if (covers && ROLE_LEVEL[entry.role] >= ROLE_LEVEL[minRole]) { + return true; + } + // Same viewer floor that `roleFor` gives at agent level. + if (serverId === ALL_SERVERS && minRole === "viewer") { + return true; + } + } + return false; + } + + /** True when any active grant of `account` lists the commands it may run. */ + isRestricted(account: KeyId, now: number): boolean { + for (const entry of this.#entries) { + if (entry.account === account && isActive(entry, now) && entry.commands !== undefined) { + return true; + } + } + return false; + } + set(entry: MemberEntry): void { - const key = scopeKey(entry.servers); + const key = scopeKey(entry); const next = this.#entries.filter( - (existing) => !(existing.account === entry.account && scopeKey(existing.servers) === key), + (existing) => !(existing.account === entry.account && scopeKey(existing) === key), ); next.push(entry); this.#entries = next; diff --git a/src/protocol/trust.ts b/src/protocol/trust.ts index 0960af9..327c1e4 100644 --- a/src/protocol/trust.ts +++ b/src/protocol/trust.ts @@ -15,6 +15,10 @@ export interface TrustContext { * roles come from accepted role grants. */ roleFor(account: KeyId, serverId: string): Role | null; + /** True when `account` may run `type` on `serverId`. Owners may run everything. */ + mayRun(account: KeyId, serverId: string, type: string, minRole: Role): boolean; + /** True when the account holds a grant that lists its commands. */ + isRestricted(account: KeyId): boolean; now(): number; claimCommand(signer: KeyId, id: string, counter: number): boolean; } @@ -66,6 +70,20 @@ export function createInMemoryTrustContext( return members.roleFor(account, serverId, clock()); }, + mayRun(account: KeyId, serverId: string, type: string, minRole: Role): boolean { + if (trusted.has(account)) { + return true; + } + return members.commandAllowed(account, serverId, type, minRole, clock()); + }, + + isRestricted(account: KeyId): boolean { + if (trusted.has(account)) { + return false; + } + return members.isRestricted(account, clock()); + }, + listMembers(): readonly MemberEntry[] { return members.entries(); }, From 445ec600546b993e7acce77d8e0110d97dc93465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ant=C3=B4nio=20Miranda?= Date: Mon, 30 Nov 2026 21:59:32 -0300 Subject: [PATCH 2/5] feat(agent): limit restricted keys and announce agent features A key whose grant lists its commands may only follow server status and may change a server's state at most 6 times in 10 minutes. host.info now reports the agent's features so clients can tell whether it supports these grants. --- src/agent/flap-limit.test.ts | 61 ++++++++++++ src/agent/flap-limit.ts | 38 +++++++ src/agent/host-info.test.ts | 19 ++++ src/agent/host-info.ts | 2 + src/agent/jobs.ts | 6 ++ src/agent/restricted-key.test.ts | 165 +++++++++++++++++++++++++++++++ src/cli/run.ts | 3 + src/protocol/commands/host.ts | 5 + src/protocol/errors.ts | 1 + src/protocol/index.ts | 1 + src/server/runtime.ts | 24 +++++ 11 files changed, 325 insertions(+) create mode 100644 src/agent/flap-limit.test.ts create mode 100644 src/agent/flap-limit.ts create mode 100644 src/agent/restricted-key.test.ts diff --git a/src/agent/flap-limit.test.ts b/src/agent/flap-limit.test.ts new file mode 100644 index 0000000..caf747a --- /dev/null +++ b/src/agent/flap-limit.test.ts @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { describe, expect, test } from "bun:test"; +import { createFlapLimiter, FLAP_LIMIT_MAX, FLAP_LIMIT_WINDOW_MS } from "./flap-limit"; + +const NOW = 1_700_000_000_000; +const ACCOUNT = "a".repeat(32); +const OTHER_ACCOUNT = "b".repeat(32); + +describe("flap limiter", () => { + test("allows six changes in the window and refuses the seventh", () => { + const limiter = createFlapLimiter(); + + for (let i = 0; i < FLAP_LIMIT_MAX; i++) { + expect(limiter.take(ACCOUNT, "survival", NOW + i)).toBe(true); + } + expect(limiter.take(ACCOUNT, "survival", NOW + FLAP_LIMIT_MAX)).toBe(false); + }); + + test("accepts changes again once the window has passed", () => { + const limiter = createFlapLimiter(); + + for (let i = 0; i < FLAP_LIMIT_MAX; i++) { + expect(limiter.take(ACCOUNT, "survival", NOW)).toBe(true); + } + expect(limiter.take(ACCOUNT, "survival", NOW + FLAP_LIMIT_WINDOW_MS - 1)).toBe(false); + expect(limiter.take(ACCOUNT, "survival", NOW + FLAP_LIMIT_WINDOW_MS)).toBe(true); + }); + + test("a refused change does not consume a slot of the window", () => { + const limiter = createFlapLimiter(); + + for (let i = 0; i < FLAP_LIMIT_MAX; i++) { + expect(limiter.take(ACCOUNT, "survival", NOW)).toBe(true); + } + expect(limiter.take(ACCOUNT, "survival", NOW + 1000)).toBe(false); + // The six original entries still age out at the same instant. + expect(limiter.take(ACCOUNT, "survival", NOW + FLAP_LIMIT_WINDOW_MS)).toBe(true); + }); + + test("accounts and servers have separate windows", () => { + const limiter = createFlapLimiter(); + + for (let i = 0; i < FLAP_LIMIT_MAX; i++) { + expect(limiter.take(ACCOUNT, "survival", NOW)).toBe(true); + } + expect(limiter.take(ACCOUNT, "survival", NOW)).toBe(false); + expect(limiter.take(ACCOUNT, "creative", NOW)).toBe(true); + expect(limiter.take(OTHER_ACCOUNT, "survival", NOW)).toBe(true); + }); + + test("a custom maximum and window are honoured", () => { + const limiter = createFlapLimiter(2, 1000); + + expect(limiter.take(ACCOUNT, "survival", NOW)).toBe(true); + expect(limiter.take(ACCOUNT, "survival", NOW + 1)).toBe(true); + expect(limiter.take(ACCOUNT, "survival", NOW + 2)).toBe(false); + expect(limiter.take(ACCOUNT, "survival", NOW + 1000)).toBe(true); + }); +}); diff --git a/src/agent/flap-limit.ts b/src/agent/flap-limit.ts new file mode 100644 index 0000000..6eecc3f --- /dev/null +++ b/src/agent/flap-limit.ts @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import type { KeyId } from "../protocol"; + +export const FLAP_LIMIT_MAX = 6; +export const FLAP_LIMIT_WINDOW_MS = 10 * 60 * 1000; + +export interface FlapLimiter { + take(account: KeyId, serverId: string, now: number): boolean; +} + +/** + * Sliding window of state changes per account and server, kept in memory only. + * `take` reports whether another change fits in the window and records it when + * it does; a rejected change does not consume a slot. + */ +export function createFlapLimiter( + max: number = FLAP_LIMIT_MAX, + windowMs: number = FLAP_LIMIT_WINDOW_MS, +): FlapLimiter { + const entries = new Map(); + + return { + take(account: KeyId, serverId: string, now: number): boolean { + const key = `${account}\u0000${serverId}`; + const cutoff = now - windowMs; + const recent = (entries.get(key) ?? []).filter((at) => at > cutoff); + if (recent.length >= max) { + entries.set(key, recent); + return false; + } + recent.push(now); + entries.set(key, recent); + return true; + }, + }; +} diff --git a/src/agent/host-info.test.ts b/src/agent/host-info.test.ts index c776a1a..401694a 100644 --- a/src/agent/host-info.test.ts +++ b/src/agent/host-info.test.ts @@ -27,6 +27,7 @@ import { signSessionCertificate, type TransportFrame, } from "../protocol"; +import { AGENT_FEATURES } from "../protocol/commands/host"; import { RESERVED_SYSTEM_MEMORY_MB } from "../server/memory"; import { readAddressesFromFibTrie, readHostAddresses, readHostInfo } from "./host-info"; import { createCommandQueue, type TransportCommandFrame } from "./jobs"; @@ -157,10 +158,27 @@ describe("readHostInfo", () => { cpu_count: 6, reserved_memory_mb: RESERVED_SYSTEM_MEMORY_MB, addresses: [], + features: [...AGENT_FEATURES], }); expect(hostInfoResultSchema.safeParse(info).success).toBe(true); }); + test("announces the agent features that ship with this release", () => { + const dir = makeTempDir(); + const meminfoPath = join(dir, "meminfo"); + writeFileSync(meminfoPath, "MemTotal: 8388608 kB\nMemAvailable: 6291456 kB\n"); + + const info = readHostInfo({ + meminfoPath, + availableParallelismImpl: () => 4, + networkInterfacesImpl: () => ({}), + fibTriePath: join(dir, "no-fib-trie"), + }); + + expect(info.features).toEqual(["grant_commands", "status_players", "audit"]); + expect(hostInfoResultSchema.safeParse(info).success).toBe(true); + }); + test("lists only external IPv4 addresses, once each and without link-local ones", () => { const iface = (address: string, family: "IPv4" | "IPv6", internal = false) => ({ @@ -336,6 +354,7 @@ describe("host.info command handler", () => { cpu_count: 4, reserved_memory_mb: RESERVED_SYSTEM_MEMORY_MB, addresses: [], + features: [...AGENT_FEATURES], }); // Account key cannot decrypt a reply sealed to the session key. diff --git a/src/agent/host-info.ts b/src/agent/host-info.ts index 9993f1a..2a85368 100644 --- a/src/agent/host-info.ts +++ b/src/agent/host-info.ts @@ -4,6 +4,7 @@ import { readFileSync } from "node:fs"; import { availableParallelism, networkInterfaces } from "node:os"; import type { HostInfoResult } from "../protocol"; +import { AGENT_FEATURES } from "../protocol"; import { DEFAULT_MEMINFO_PATH, type Meminfo, @@ -94,5 +95,6 @@ export function readHostInfo(options: ReadHostInfoOptions = {}): HostInfoResult cpu_count: cpuCount, reserved_memory_mb: reservedMemoryMb, addresses, + features: [...AGENT_FEATURES], }; } diff --git a/src/agent/jobs.ts b/src/agent/jobs.ts index 6d7991f..075a63a 100644 --- a/src/agent/jobs.ts +++ b/src/agent/jobs.ts @@ -391,6 +391,12 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { registerHandler("agent.subscribe", (opened, ctx) => { const body = opened.body as AgentSubscribeBody; + if ( + trust.isRestricted(opened.accountId) && + body.topics.some((topic) => topic !== "server.status") + ) { + throw new ProtocolError("command_not_granted", "This key may only follow server status"); + } const key = resolveRecipientKey(opened); if (key === null) { throw new ProtocolError("untrusted_signer", "Subscriber key is not available"); diff --git a/src/agent/restricted-key.test.ts b/src/agent/restricted-key.test.ts new file mode 100644 index 0000000..c39fd0e --- /dev/null +++ b/src/agent/restricted-key.test.ts @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { beforeAll, describe, expect, test } from "bun:test"; +import { + fingerprint, + generateSigningKeyPair, + ready, + type SigningKeyPair, + toBase64Url, +} from "../crypto"; +import { + createCoreRegistry, + createInMemoryTrustContext, + createSignedCommand, + PROTOCOL_VERSION, + type TransportFrame, +} from "../protocol"; +import { registerServerHandlers, type ServerManager } from "../server"; +import { createFlapLimiter, FLAP_LIMIT_MAX } from "./flap-limit"; +import { type CommandQueue, createCommandQueue, type TransportCommandFrame } from "./jobs"; +import { createLogger } from "./logger"; + +const NOW = 1_700_000_000_000; +const SERVER = "survival"; +const silentLogger = createLogger({ level: "error", stdout: () => {}, stderr: () => {} }); + +beforeAll(async () => { + await ready(); +}); + +interface Harness { + readonly agent: SigningKeyPair; + readonly owner: SigningKeyPair; + readonly restricted: SigningKeyPair; + readonly queue: CommandQueue; + readonly sent: TransportFrame[]; + send(type: string, body: unknown, signer: SigningKeyPair): Promise; +} + +function makeManager(): ServerManager { + return { + startServer: async () => undefined, + stopServer: async () => ({ + active_state: "inactive", + sub_state: "dead", + main_pid: null, + memory_current_bytes: null, + }), + restartServer: async () => undefined, + } as unknown as ServerManager; +} + +function makeHarness(commands: readonly string[]): Harness { + const agent = generateSigningKeyPair(); + const owner = generateSigningKeyPair(); + const restricted = generateSigningKeyPair(); + const registry = createCoreRegistry(); + const trust = createInMemoryTrustContext({ + agentKeyPair: agent, + trustedAccountKeys: [owner.publicKey], + members: [ + { + account_key: toBase64Url(restricted.publicKey), + account: fingerprint(restricted.publicKey), + granted_by: fingerprint(owner.publicKey), + role: "operator", + servers: [SERVER], + commands: [...commands], + issued_at: NOW, + }, + ], + now: () => NOW, + }); + + const sent: TransportFrame[] = []; + const queue = createCommandQueue({ + trust, + registry, + sendFrame: (frame) => sent.push(frame), + logger: silentLogger, + }); + registerServerHandlers(queue, makeManager(), { + flapLimiter: createFlapLimiter(), + isRestricted: (accountId) => trust.isRestricted(accountId), + }); + + const counters = new Map(); + + return { + agent, + owner, + restricted, + queue, + sent, + async send(type, body, signer) { + const key = fingerprint(signer.publicKey); + const counter = (counters.get(key) ?? 0) + 1; + counters.set(key, counter); + const command = createSignedCommand( + { + type, + body, + agentPublicKey: agent.publicKey, + signer, + counter, + now: NOW, + }, + registry, + ); + const frame: TransportCommandFrame = { + v: PROTOCOL_VERSION, + kind: "command", + route: { agent: fingerprint(agent.publicKey) }, + body: command, + }; + await queue.enqueue(frame); + }, + }; +} + +function lastAck(sent: readonly TransportFrame[]): { ok: boolean; code?: string } { + for (let i = sent.length - 1; i >= 0; i--) { + const frame = sent[i]; + if (frame?.kind === "ack") { + return frame.body.code !== undefined + ? { ok: frame.body.ok, code: frame.body.code } + : { ok: frame.body.ok }; + } + } + throw new Error("no ack"); +} + +describe("restricted keys", () => { + test("a restricted key may change a server's state six times in the window", async () => { + const h = makeHarness(["server.start", "server.status"]); + + for (let i = 0; i < FLAP_LIMIT_MAX; i++) { + await h.send("server.start", { server_id: SERVER }, h.restricted); + expect(lastAck(h.sent)).toEqual({ ok: true }); + } + + await h.send("server.start", { server_id: SERVER }, h.restricted); + expect(lastAck(h.sent)).toEqual({ ok: false, code: "rate_limited" }); + }); + + test("the owner is not rate limited", async () => { + const h = makeHarness(["server.start"]); + + for (let i = 0; i < FLAP_LIMIT_MAX + 1; i++) { + await h.send("server.start", { server_id: SERVER }, h.owner); + expect(lastAck(h.sent)).toEqual({ ok: true }); + } + }); + + test("a restricted key may only follow server status", async () => { + const h = makeHarness(["agent.subscribe", "server.status"]); + + await h.send("agent.subscribe", { topics: ["server.status", "server.backup"] }, h.restricted); + expect(lastAck(h.sent)).toEqual({ ok: false, code: "command_not_granted" }); + + await h.send("agent.subscribe", { topics: ["server.status"] }, h.restricted); + expect(lastAck(h.sent)).toEqual({ ok: true }); + }); +}); diff --git a/src/cli/run.ts b/src/cli/run.ts index bd088eb..94d1229 100644 --- a/src/cli/run.ts +++ b/src/cli/run.ts @@ -20,6 +20,7 @@ import { type TimerProvider, type WebSocketFactory, } from "../agent"; +import { createFlapLimiter } from "../agent/flap-limit"; import { type BackupManager, createBackupManager, registerBackupHandlers } from "../backup"; import { fingerprint } from "../crypto"; import { FileManager, registerFileCommandHandlers } from "../files"; @@ -181,6 +182,8 @@ export async function createAgentRuntime( void statusWatcher.refresh(serverId); }, onDeleted: (serverId) => statusWatcher.forget(serverId), + flapLimiter: createFlapLimiter(), + isRestricted: (accountId) => trust.isRestricted(accountId), }); const apiClient = createAgentApiClient({ diff --git a/src/protocol/commands/host.ts b/src/protocol/commands/host.ts index f170afd..e762827 100644 --- a/src/protocol/commands/host.ts +++ b/src/protocol/commands/host.ts @@ -7,6 +7,9 @@ import { type CommandRegistry, defineCommand } from "../registry"; export const hostInfoBodySchema = z.object({}).strict(); export type HostInfoBody = z.infer; +/** Capabilities this agent build announces in `host.info`, so clients can adapt. */ +export const AGENT_FEATURES = ["grant_commands", "status_players", "audit"] as const; + export const hostInfoResultSchema = z.object({ memory_total_mb: z.number().int().nonnegative(), memory_available_mb: z.number().int().nonnegative(), @@ -14,6 +17,8 @@ export const hostInfoResultSchema = z.object({ reserved_memory_mb: z.number().int().nonnegative(), /** Non-internal IPv4 addresses of the host, so a player can find the server on the network. */ addresses: z.array(z.string().min(1).max(45)).max(16).optional(), + /** Optional capabilities of this agent build; absent means an older agent. */ + features: z.array(z.string().min(1).max(64)).max(32).optional(), }); export type HostInfoResult = z.infer; diff --git a/src/protocol/errors.ts b/src/protocol/errors.ts index ebd36de..ccf3476 100644 --- a/src/protocol/errors.ts +++ b/src/protocol/errors.ts @@ -22,6 +22,7 @@ export type ProtocolErrorCode = | "decrypt_failed" | "insufficient_role" | "command_not_granted" + | "rate_limited" | "too_many_subscribers" | "role_grant_invalid" | "auth_invalid" diff --git a/src/protocol/index.ts b/src/protocol/index.ts index 14c64ef..b840946 100644 --- a/src/protocol/index.ts +++ b/src/protocol/index.ts @@ -145,6 +145,7 @@ export { sha256HexSchema, } from "./commands/files"; export { + AGENT_FEATURES, HOST_COMMANDS, type HostInfoBody, type HostInfoResult, diff --git a/src/server/runtime.ts b/src/server/runtime.ts index 9d1753e..b4ac39d 100644 --- a/src/server/runtime.ts +++ b/src/server/runtime.ts @@ -3,9 +3,11 @@ import { existsSync, mkdirSync, rmSync } from "node:fs"; import { join } from "node:path"; +import { createFlapLimiter, type FlapLimiter } from "../agent/flap-limit"; import type { CommandQueue } from "../agent/jobs"; import type { Logger } from "../agent/logger"; import { + type KeyId, ProtocolError, roleAtLeast, type ServerChangeRuntimeBody, @@ -641,6 +643,10 @@ export interface ServerHandlerHooks { readonly onStateChanged?: (serverId: string) => void; /** Called after a server was deleted. */ readonly onDeleted?: (serverId: string) => void; + /** Shared limiter for state changes made by restricted keys. */ + readonly flapLimiter?: FlapLimiter; + /** Whether an account may only run the commands its grant lists. */ + readonly isRestricted?: (accountId: KeyId) => boolean; } export function registerServerHandlers( @@ -648,6 +654,21 @@ export function registerServerHandlers( manager: ServerManager, hooks: ServerHandlerHooks = {}, ): void { + const flapLimiter = hooks.flapLimiter ?? createFlapLimiter(); + + function assertNotFlapping( + opened: { readonly accountId: KeyId }, + now: number, + serverId: string, + ): void { + if (!hooks.isRestricted?.(opened.accountId)) { + return; + } + if (!flapLimiter.take(opened.accountId, serverId, now)) { + throw new ProtocolError("rate_limited", "Too many state changes for this server"); + } + } + queue.registerHandler("server.create", async (opened, ctx) => { const body = opened.body as ServerCreateBody; const server = await manager.createServer(body); @@ -662,6 +683,7 @@ export function registerServerHandlers( queue.registerHandler("server.start", async (opened, ctx) => { const body = opened.body as { readonly server_id: string }; + assertNotFlapping(opened, ctx.now(), body.server_id); await manager.startServer(body.server_id); ctx.sendEvent("server.started", { server_id: body.server_id }); hooks.onStateChanged?.(body.server_id); @@ -669,6 +691,7 @@ export function registerServerHandlers( queue.registerHandler("server.stop", async (opened, ctx) => { const body = opened.body as { readonly server_id: string }; + assertNotFlapping(opened, ctx.now(), body.server_id); await manager.stopServer(body.server_id); ctx.sendEvent("server.stopped", { server_id: body.server_id }); hooks.onStateChanged?.(body.server_id); @@ -676,6 +699,7 @@ export function registerServerHandlers( queue.registerHandler("server.restart", async (opened, ctx) => { const body = opened.body as { readonly server_id: string }; + assertNotFlapping(opened, ctx.now(), body.server_id); await manager.restartServer(body.server_id); ctx.sendEvent("server.restarted", { server_id: body.server_id }); hooks.onStateChanged?.(body.server_id); From cde72141dfbc1fb94dcc9cb401bcdb35a370039b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ant=C3=B4nio=20Miranda?= Date: Mon, 30 Nov 2026 22:09:33 -0300 Subject: [PATCH 3/5] feat(server): report players online and MOTD in server status The agent asks its own running servers for their status on localhost (Server List Ping) and adds players online/max and the MOTD to server.status. The status watcher also emits server.status.changed when the player count changes, polling every 30 seconds while someone is subscribed. --- src/cli/run.ts | 9 ++ src/protocol/commands/agent.ts | 8 + src/server/runtime.ts | 32 +++- src/server/slp.test.ts | 211 ++++++++++++++++++++++++ src/server/slp.ts | 283 +++++++++++++++++++++++++++++++++ src/server/status-watcher.ts | 77 ++++++++- 6 files changed, 617 insertions(+), 3 deletions(-) create mode 100644 src/server/slp.test.ts create mode 100644 src/server/slp.ts diff --git a/src/cli/run.ts b/src/cli/run.ts index 94d1229..085cd1f 100644 --- a/src/cli/run.ts +++ b/src/cli/run.ts @@ -41,6 +41,7 @@ import { type ServerManager, type ServerStatusWatcher, } from "../server"; +import { pingLocalServer } from "../server/slp"; import { createModpackInstaller, createStateManager, @@ -161,6 +162,14 @@ export async function createAgentRuntime( const statusWatcher: ServerStatusWatcher = createServerStatusWatcher({ listServerIds: () => serverManager.listServers().map((server) => server.id), getState: (serverId) => serverManager.getServerState(serverId), + readPlayers: async (serverId) => { + const server = serverManager.listServers().find((entry) => entry.id === serverId); + if (server === undefined) { + return null; + } + const slp = await pingLocalServer(server.port); + return slp === null ? null : { online: slp.online, max: slp.max }; + }, emit: (change) => { queue.publish("server.status", "server.status.changed", change, { serverId: change.server_id, diff --git a/src/protocol/commands/agent.ts b/src/protocol/commands/agent.ts index ceb1e53..b13c592 100644 --- a/src/protocol/commands/agent.ts +++ b/src/protocol/commands/agent.ts @@ -19,6 +19,14 @@ export const serverStatusChangedSchema = z.object({ server_id: serverIdSchema, state: serverStateSchema, at: z.number().int().nonnegative(), + players: z + .object({ + online: z.number().int().nonnegative(), + max: z.number().int().nonnegative(), + }) + .nullable() + .optional(), + motd: z.string().max(256).nullable().optional(), }); export type ServerStatusChanged = z.infer; diff --git a/src/server/runtime.ts b/src/server/runtime.ts index b4ac39d..c5a889e 100644 --- a/src/server/runtime.ts +++ b/src/server/runtime.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Antônio Miranda -import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { createFlapLimiter, type FlapLimiter } from "../agent/flap-limit"; import type { CommandQueue } from "../agent/jobs"; @@ -65,11 +65,13 @@ import { isEulaAccepted, listServerMetadata, readServerMetadata, + SERVER_PROPERTIES_FILE, type ServerMetadata, writeEulaFile, writeServerMetadata, writeServerProperties, } from "./registry"; +import { pingLocalServer, stripFormatting } from "./slp"; import { validateJvmArgs, writeStartScript } from "./start-script"; import { createServerStatsCollector } from "./stats"; import { mapUnitState } from "./status-watcher"; @@ -85,6 +87,8 @@ import { export interface ServerStatusReport { readonly server: ServerMetadata; readonly eula_accepted: boolean; + readonly players: { readonly online: number; readonly max: number } | null; + readonly motd: string | null; readonly systemd: { readonly active_state: string; readonly sub_state: string; @@ -93,6 +97,28 @@ export interface ServerStatusReport { }; } +function readMotdFromProperties(serverDir: string): string | null { + let content: string; + try { + content = readFileSync(resolveServerSubpath(serverDir, SERVER_PROPERTIES_FILE), "utf8"); + } catch { + return null; + } + for (const line of content.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith("#") || trimmed.startsWith("!")) { + continue; + } + const match = /^motd\s*[=:]\s*(.*)$/.exec(trimmed); + if (match === null) { + continue; + } + const motd = stripFormatting(match[1] ?? ""); + return motd.length > 0 ? motd : null; + } + return null; +} + export interface ServerManagerOptions { readonly serversDir?: string; readonly runDir?: string; @@ -448,10 +474,14 @@ export function createServerManager(options: ServerManagerOptions = {}): ServerM const server = readServerMetadata(serversDir, validId); const serverDir = resolveServerDir(serversDir, validId); const status = await getUnitStatus(validId, options.runFixedImpl); + const slp = + mapUnitState(status.activeState) === "running" ? await pingLocalServer(server.port) : null; return { server, eula_accepted: isEulaAccepted(serverDir), + players: slp === null ? null : { online: slp.online, max: slp.max }, + motd: slp?.motd ?? readMotdFromProperties(serverDir), systemd: { active_state: status.activeState, sub_state: status.subState, diff --git a/src/server/slp.test.ts b/src/server/slp.test.ts new file mode 100644 index 0000000..4108524 --- /dev/null +++ b/src/server/slp.test.ts @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { afterEach, describe, expect, test } from "bun:test"; +import type { ServerState, ServerStatusChanged } from "../protocol"; +import { motdFromDescription, pingLocalServer, stripFormatting } from "./slp"; +import { createServerStatusWatcher } from "./status-watcher"; + +const servers: Array<{ stop(force?: boolean): void }> = []; + +afterEach(() => { + while (servers.length > 0) { + const server = servers.pop(); + server?.stop(true); + } +}); + +function concatBytes(parts: readonly Uint8Array[]): Uint8Array { + const total = parts.reduce((sum, part) => sum + part.length, 0); + const result = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} + +function encodeVarInt(value: number): Uint8Array { + const bytes: number[] = []; + let remaining = value >>> 0; + do { + let byte = remaining & 0x7f; + remaining >>>= 7; + if (remaining !== 0) { + byte |= 0x80; + } + bytes.push(byte); + } while (remaining !== 0); + return Uint8Array.from(bytes); +} + +function stringField(value: string): Uint8Array { + const bytes = new TextEncoder().encode(value); + return concatBytes([encodeVarInt(bytes.length), bytes]); +} + +function packet(id: number, payload: Uint8Array): Uint8Array { + const body = concatBytes([encodeVarInt(id), payload]); + return concatBytes([encodeVarInt(body.length), body]); +} + +function statusPacket(json: string): Uint8Array { + return packet(0x00, stringField(json)); +} + +/** Starts a loopback server that answers every request with `response`, or stays silent. */ +function listen(response: Uint8Array | null): number { + const server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(socket) { + if (response !== null) { + socket.write(response); + } + }, + }, + }); + servers.push(server); + return server.port; +} + +describe("server list ping", () => { + test("reads online, max, MOTD and version from a status response", async () => { + const port = listen( + statusPacket( + JSON.stringify({ + version: { name: "1.21.4", protocol: 765 }, + players: { online: 3, max: 20 }, + description: { + text: "§aHello ", + extra: [{ text: "§lWorld", extra: [{ text: "!" }] }], + }, + }), + ), + ); + + const result = await pingLocalServer(port, { timeoutMs: 1_000 }); + + expect(result).not.toBeNull(); + expect(result?.online).toBe(3); + expect(result?.max).toBe(20); + expect(result?.motd).toBe("Hello World!"); + expect(result?.version).toBe("1.21.4"); + }); + + test("returns null when the server does not answer within the timeout", async () => { + const port = listen(null); + + const result = await pingLocalServer(port, { timeoutMs: 200 }); + + expect(result).toBeNull(); + }); + + test("returns null when the status response is not valid JSON", async () => { + const port = listen(statusPacket("{not json")); + + const result = await pingLocalServer(port, { timeoutMs: 1_000 }); + + expect(result).toBeNull(); + }); + + test("returns null when the status response is larger than 64 KiB", async () => { + const port = listen( + statusPacket( + JSON.stringify({ + players: { online: 0, max: 20 }, + description: "x".repeat(70_000), + }), + ), + ); + + const result = await pingLocalServer(port, { timeoutMs: 1_000 }); + + expect(result).toBeNull(); + }); + + test("strips formatting codes", () => { + expect(stripFormatting("§aHello §lWorld")).toBe("Hello World"); + }); + + test("flattens nested chat components", () => { + expect( + motdFromDescription({ + text: "a", + extra: [{ text: "b", extra: [{ text: "c" }] }], + }), + ).toBe("abc"); + }); +}); + +describe("status watcher players", () => { + test("emits only when online or max changes", async () => { + let now = 0; + let players = { online: 0, max: 20 }; + const emitted: ServerStatusChanged[] = []; + const watcher = createServerStatusWatcher({ + listServerIds: () => ["a"], + getState: async () => "running", + readPlayers: async () => players, + playersIntervalMs: 30_000, + now: () => now, + emit: (change) => emitted.push(change), + }); + + await watcher.pollOnce(); + expect(emitted).toHaveLength(0); + + now += 30_000; + await watcher.pollOnce(); + expect(emitted).toHaveLength(0); + + players = { online: 1, max: 20 }; + now += 30_000; + await watcher.pollOnce(); + expect(emitted).toEqual([ + { server_id: "a", state: "running", at: 60_000, players: { online: 1, max: 20 } }, + ]); + + // Before the players interval elapses, a new value is not read or emitted. + players = { online: 2, max: 20 }; + now += 15_000; + await watcher.pollOnce(); + expect(emitted).toHaveLength(1); + + now += 15_000; + await watcher.pollOnce(); + expect(emitted).toHaveLength(2); + + // Same values again: no new event. + now += 30_000; + await watcher.pollOnce(); + expect(emitted).toHaveLength(2); + }); + + test("a state change to a non-running state reports null players", async () => { + let state: ServerState = "stopped"; + const emitted: ServerStatusChanged[] = []; + const watcher = createServerStatusWatcher({ + listServerIds: () => ["a"], + getState: async () => state, + readPlayers: async () => ({ online: 0, max: 20 }), + now: () => 1_000, + emit: (change) => emitted.push(change), + }); + + state = "running"; + await watcher.refresh("a"); + expect(emitted).toEqual([ + { server_id: "a", state: "running", at: 1_000, players: { online: 0, max: 20 } }, + ]); + + state = "stopped"; + await watcher.refresh("a"); + expect(emitted).toEqual([ + { server_id: "a", state: "running", at: 1_000, players: { online: 0, max: 20 } }, + { server_id: "a", state: "stopped", at: 1_000, players: null }, + ]); + }); +}); diff --git a/src/server/slp.ts b/src/server/slp.ts new file mode 100644 index 0000000..63cb3bd --- /dev/null +++ b/src/server/slp.ts @@ -0,0 +1,283 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { z } from "zod"; + +/** Protocol sent in the handshake; status replies do not depend on it. */ +const HANDSHAKE_PROTOCOL = 765; +/** A status response only carries players, MOTD and version; refuse anything absurd. */ +const MAX_RESPONSE_BYTES = 64 * 1024; +const DEFAULT_TIMEOUT_MS = 1_500; +const DEFAULT_HOST = "127.0.0.1"; +const CACHE_TTL_MS = 15_000; +const MAX_MOTD_LENGTH = 256; + +export interface SlpResult { + readonly online: number; + readonly max: number; + readonly motd: string; + readonly version: string | null; +} + +const chatComponentSchema: z.ZodType = z.lazy(() => + z + .object({ + text: z.string().optional(), + extra: z.array(chatComponentSchema).optional(), + }) + .passthrough(), +); + +const statusResponseSchema = z.object({ + players: z.object({ + online: z.number().int().nonnegative(), + max: z.number().int().nonnegative(), + }), + description: z.union([z.string(), chatComponentSchema]), + version: z + .object({ + name: z.string().optional(), + }) + .passthrough() + .optional(), +}); + +const FORMATTING_CODE = /§[0-9a-fk-orx]/gi; + +/** Removes Minecraft formatting codes and collapses repeated whitespace. */ +export function stripFormatting(text: string): string { + return text.replace(FORMATTING_CODE, "").replace(/\s+/g, " ").trim().slice(0, MAX_MOTD_LENGTH); +} + +/** Flattens a chat component (string, object or array) to plain text. */ +export function motdFromDescription(description: unknown): string { + if (typeof description === "string") { + return description; + } + if (description === null || description === undefined) { + return ""; + } + if (Array.isArray(description)) { + return description.map(motdFromDescription).join(""); + } + if (typeof description === "object") { + const node = description as { readonly text?: unknown; readonly extra?: unknown }; + const own = typeof node.text === "string" ? node.text : ""; + const extra = Array.isArray(node.extra) ? node.extra.map(motdFromDescription).join("") : ""; + return own + extra; + } + return ""; +} + +function encodeVarInt(value: number): Buffer { + const bytes: number[] = []; + let remaining = value >>> 0; + do { + let byte = remaining & 0x7f; + remaining >>>= 7; + if (remaining !== 0) { + byte |= 0x80; + } + bytes.push(byte); + } while (remaining !== 0); + return Buffer.from(bytes); +} + +function decodeVarInt(buffer: Buffer, offset = 0): { value: number; size: number } | null { + let value = 0; + for (let i = 0; i < 5; i += 1) { + const index = offset + i; + if (index >= buffer.length) { + return null; + } + const byte = buffer[index]; + if (byte === undefined) { + return null; + } + value |= (byte & 0x7f) << (7 * i); + if ((byte & 0x80) === 0) { + return { value: value | 0, size: i + 1 }; + } + } + throw new Error("VarInt is too long"); +} + +function encodeString(value: string): Buffer { + const bytes = Buffer.from(value, "utf8"); + return Buffer.concat([encodeVarInt(bytes.length), bytes]); +} + +function framePacket(packetId: number, payload: Buffer): Buffer { + const body = Buffer.concat([encodeVarInt(packetId), payload]); + return Buffer.concat([encodeVarInt(body.length), body]); +} + +function buildHandshakePacket(host: string, port: number): Buffer { + const portBytes = Buffer.alloc(2); + portBytes.writeUInt16BE(port); + return framePacket( + 0x00, + Buffer.concat([ + encodeVarInt(HANDSHAKE_PROTOCOL), + encodeString(host), + portBytes, + encodeVarInt(1), + ]), + ); +} + +function readPacket(buffer: Buffer): { id: number; data: Buffer; size: number } | null { + const length = decodeVarInt(buffer); + if (length === null) { + return null; + } + if (length.value < 1 || length.value > MAX_RESPONSE_BYTES) { + throw new Error("Invalid packet length"); + } + const end = length.size + length.value; + if (buffer.length < end) { + return null; + } + const id = decodeVarInt(buffer, length.size); + if (id === null) { + throw new Error("Truncated packet id"); + } + const dataStart = length.size + id.size; + if (dataStart > end) { + throw new Error("Invalid packet"); + } + return { id: id.value, data: buffer.subarray(dataStart, end), size: end }; +} + +function readString(data: Buffer): string | null { + const length = decodeVarInt(data); + if (length === null || length.value < 0) { + return null; + } + const start = length.size; + const end = start + length.value; + if (end > data.length) { + return null; + } + return data.subarray(start, end).toString("utf8"); +} + +function parseStatusJson(json: string): SlpResult | null { + let raw: unknown; + try { + raw = JSON.parse(json); + } catch { + return null; + } + const parsed = statusResponseSchema.safeParse(raw); + if (!parsed.success) { + return null; + } + const versionName = parsed.data.version?.name; + return { + online: parsed.data.players.online, + max: parsed.data.players.max, + motd: stripFormatting(motdFromDescription(parsed.data.description)), + version: versionName !== undefined && versionName.length > 0 ? versionName : null, + }; +} + +function pingOnce(host: string, port: number, timeoutMs: number): Promise { + return new Promise((resolve) => { + let buffer = Buffer.alloc(0); + let active: { terminate(): void } | null = null; + let settled = false; + + const finish = (result: SlpResult | null): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + active?.terminate(); + resolve(result); + }; + + const timer = setTimeout(() => finish(null), timeoutMs); + + const handleChunk = (chunk: Uint8Array): void => { + buffer = Buffer.concat([buffer, Buffer.from(chunk)]); + if (buffer.length > MAX_RESPONSE_BYTES) { + finish(null); + return; + } + try { + const packet = readPacket(buffer); + if (packet === null) { + return; + } + if (packet.id !== 0x00) { + finish(null); + return; + } + const json = readString(packet.data); + finish(json === null ? null : parseStatusJson(json)); + } catch { + finish(null); + } + }; + + Bun.connect({ + hostname: host, + port, + socket: { + open(socket) { + if (settled) { + socket.terminate(); + return; + } + active = socket; + socket.write( + Buffer.concat([buildHandshakePacket(host, port), framePacket(0x00, Buffer.alloc(0))]), + ); + }, + data(_socket, chunk) { + handleChunk(chunk); + }, + close() { + finish(null); + }, + error() { + finish(null); + }, + connectError() { + finish(null); + }, + }, + }).then( + (socket) => { + if (settled) { + socket.terminate(); + } + }, + () => finish(null), + ); + }); +} + +const cache = new Map(); + +/** Queries a local Minecraft server's status, or returns null when it cannot answer. */ +export async function pingLocalServer( + port: number, + options: { timeoutMs?: number; host?: string } = {}, +): Promise { + if (!Number.isInteger(port) || port < 1 || port > 65535) { + return null; + } + const host = options.host ?? DEFAULT_HOST; + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const key = `${host}:${port}`; + const cached = cache.get(key); + if (cached !== undefined && cached.expiresAt > Date.now()) { + return cached.result; + } + const result = await pingOnce(host, port, timeoutMs); + cache.set(key, { result, expiresAt: Date.now() + CACHE_TTL_MS }); + return result; +} diff --git a/src/server/status-watcher.ts b/src/server/status-watcher.ts index 6fd5606..cc67b7c 100644 --- a/src/server/status-watcher.ts +++ b/src/server/status-watcher.ts @@ -4,6 +4,7 @@ import type { ServerState, ServerStatusChanged } from "../protocol"; export const DEFAULT_STATUS_POLL_INTERVAL_MS = 3_000; +export const DEFAULT_PLAYERS_POLL_INTERVAL_MS = 30_000; /** Maps a systemd `ActiveState` to the state clients see, or null when it is not meaningful. */ export function mapUnitState(activeState: string): ServerState | null { @@ -35,6 +36,9 @@ export interface StatusWatcherOptions { readonly emit: (change: ServerStatusChanged) => void; /** Polling only runs while this returns true (e.g. while someone is subscribed). */ readonly shouldPoll?: () => boolean; + /** Reads the players online of a running server, or null when unknown. */ + readonly readPlayers?: (serverId: string) => Promise<{ online: number; max: number } | null>; + readonly playersIntervalMs?: number; readonly now?: () => number; readonly intervalMs?: number; readonly timers?: StatusWatcherTimers; @@ -59,10 +63,53 @@ export function createServerStatusWatcher(options: StatusWatcherOptions): Server const now = options.now ?? (() => Date.now()); const timers = options.timers ?? defaultTimers; const intervalMs = options.intervalMs ?? DEFAULT_STATUS_POLL_INTERVAL_MS; + const playersIntervalMs = options.playersIntervalMs ?? DEFAULT_PLAYERS_POLL_INTERVAL_MS; const lastStates = new Map(); + const lastPlayers = new Map(); + const playersReadAt = new Map(); let handle: unknown = null; let polling = false; + async function readPlayers(serverId: string): Promise<{ online: number; max: number } | null> { + if (options.readPlayers === undefined) { + return null; + } + try { + return await options.readPlayers(serverId); + } catch { + return null; + } + } + + /** Reads players while the interval allows and emits when online or max changed. */ + async function pollPlayers(serverId: string, state: ServerState): Promise { + if (state !== "running" || options.readPlayers === undefined) { + return; + } + if (options.shouldPoll !== undefined && !options.shouldPoll()) { + return; + } + const at = now(); + const lastRead = playersReadAt.get(serverId); + if (lastRead !== undefined && at - lastRead < playersIntervalMs) { + return; + } + playersReadAt.set(serverId, at); + const players = await readPlayers(serverId); + if (players === null) { + return; + } + const previous = lastPlayers.get(serverId); + lastPlayers.set(serverId, players); + if (previous === undefined) { + return; + } + if (previous !== null && previous.online === players.online && previous.max === players.max) { + return; + } + options.emit({ server_id: serverId, state, at, players }); + } + async function observe(serverId: string, emitFirst: boolean): Promise { let state: ServerState | null; try { @@ -75,10 +122,30 @@ export function createServerStatusWatcher(options: StatusWatcherOptions): Server } const previous = lastStates.get(serverId); lastStates.set(serverId, state); - if (previous === state || (previous === undefined && !emitFirst)) { + if (previous === state) { + await pollPlayers(serverId, state); + return; + } + if (previous === undefined && !emitFirst) { + // The first poll is a silent baseline; players are recorded below it. + await pollPlayers(serverId, state); + return; + } + const at = now(); + if (options.readPlayers === undefined) { + options.emit({ server_id: serverId, state, at }); + return; + } + if (state === "running") { + const players = await readPlayers(serverId); + lastPlayers.set(serverId, players); + playersReadAt.set(serverId, at); + options.emit({ server_id: serverId, state, at, players }); return; } - options.emit({ server_id: serverId, state, at: now() }); + lastPlayers.set(serverId, null); + playersReadAt.delete(serverId); + options.emit({ server_id: serverId, state, at, players: null }); } async function pollOnce(): Promise { @@ -92,6 +159,8 @@ export function createServerStatusWatcher(options: StatusWatcherOptions): Server for (const id of lastStates.keys()) { if (!known.has(id)) { lastStates.delete(id); + lastPlayers.delete(id); + playersReadAt.delete(id); } } for (const id of ids) { @@ -110,6 +179,8 @@ export function createServerStatusWatcher(options: StatusWatcherOptions): Server handle = timers.setInterval(() => { if (options.shouldPoll !== undefined && !options.shouldPoll()) { lastStates.clear(); + lastPlayers.clear(); + playersReadAt.clear(); return; } void pollOnce(); @@ -129,6 +200,8 @@ export function createServerStatusWatcher(options: StatusWatcherOptions): Server forget(serverId: string): void { lastStates.delete(serverId); + lastPlayers.delete(serverId); + playersReadAt.delete(serverId); }, pollOnce, From c581847d9de2633dda193cdc59e85482c641cfc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ant=C3=B4nio=20Miranda?= Date: Mon, 30 Nov 2026 22:18:20 -0300 Subject: [PATCH 4/5] feat(agent): signed on_behalf_of and a local audit log of state changes A restricted key may say, inside the signed command header, which Discord user it acts for. The agent records server start, stop and restart from any signer in a local audit log (last 5000 entries, 0600) and serves it to admins with agent.audit.list. --- src/agent/audit.test.ts | 362 +++++++++++++++++++++++++++++++++ src/agent/audit.ts | 154 ++++++++++++++ src/agent/jobs.ts | 54 +++++ src/agent/paths.ts | 2 + src/cli/run.ts | 4 + src/protocol/command.ts | 13 ++ src/protocol/commands/agent.ts | 39 +++- src/protocol/index.ts | 9 + src/protocol/phase3.test.ts | 1 + src/protocol/schemas.ts | 11 + 10 files changed, 648 insertions(+), 1 deletion(-) create mode 100644 src/agent/audit.test.ts create mode 100644 src/agent/audit.ts diff --git a/src/agent/audit.test.ts b/src/agent/audit.test.ts new file mode 100644 index 0000000..d76707f --- /dev/null +++ b/src/agent/audit.test.ts @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { beforeAll, describe, expect, test } from "bun:test"; +import { appendFileSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + fingerprint, + generateSigningKeyPair, + ready, + type SigningKeyPair, + toBase64Url, +} from "../crypto"; +import { + createCoreRegistry, + createInMemoryTrustContext, + createSignedCommand, + type GrantableRole, + type MemberEntry, + type OnBehalfOf, + openCommand, + PROTOCOL_VERSION, + ProtocolError, + type SignedCommand, + type TransportFrame, +} from "../protocol"; +import { registerServerHandlers, type ServerManager } from "../server"; +import { type AuditEntry, type AuditLog, createFileAuditLog, createMemoryAuditLog } from "./audit"; +import { type CommandQueue, createCommandQueue, type TransportCommandFrame } from "./jobs"; +import { createLogger } from "./logger"; +import { openTestEvent } from "./test-events"; + +const NOW = 1_700_000_000_000; +const SERVER = "survival"; +const silentLogger = createLogger({ level: "error", stdout: () => {}, stderr: () => {} }); + +const ON_BEHALF: OnBehalfOf = { + via: "discord", + user_id: "123456789012345678", + display_name: "Ana", + guild_id: "987654321098765432", +}; + +beforeAll(async () => { + await ready(); +}); + +function memberEntry( + key: SigningKeyPair, + owner: SigningKeyPair, + role: GrantableRole, + commands?: readonly string[], +): MemberEntry { + return { + account_key: toBase64Url(key.publicKey), + account: fingerprint(key.publicKey), + granted_by: fingerprint(owner.publicKey), + role, + servers: [SERVER, "broken"], + ...(commands !== undefined ? { commands: [...commands] } : {}), + issued_at: NOW, + }; +} + +function makeManager(): ServerManager { + return { + startServer: async (serverId: string) => { + if (serverId === "broken") { + throw new ProtocolError("systemd_error", "Server failed to start"); + } + }, + stopServer: async () => ({ + active_state: "inactive", + sub_state: "dead", + main_pid: null, + memory_current_bytes: null, + }), + restartServer: async () => undefined, + getServerStatus: async () => ({ + active_state: "inactive", + sub_state: "dead", + main_pid: null, + memory_current_bytes: null, + }), + } as unknown as ServerManager; +} + +interface Fixture { + readonly agent: SigningKeyPair; + readonly owner: SigningKeyPair; + readonly restricted: SigningKeyPair; + readonly admin: SigningKeyPair; + readonly operator: SigningKeyPair; + readonly registry: ReturnType; + readonly trust: ReturnType; + readonly queue: CommandQueue; + readonly sent: TransportFrame[]; + readonly audit: AuditLog; + send( + type: string, + body: unknown, + signer: SigningKeyPair, + onBehalfOf?: OnBehalfOf, + ): Promise; +} + +function makeFixture(): Fixture { + const agent = generateSigningKeyPair(); + const owner = generateSigningKeyPair(); + const restricted = generateSigningKeyPair(); + const admin = generateSigningKeyPair(); + const operator = generateSigningKeyPair(); + const registry = createCoreRegistry(); + const trust = createInMemoryTrustContext({ + agentKeyPair: agent, + trustedAccountKeys: [owner.publicKey], + members: [ + memberEntry(restricted, owner, "operator", ["server.start", "server.stop", "server.restart"]), + memberEntry(admin, owner, "admin"), + memberEntry(operator, owner, "operator"), + ], + now: () => NOW, + }); + + const audit = createMemoryAuditLog(); + const sent: TransportFrame[] = []; + const queue = createCommandQueue({ + trust, + registry, + audit, + sendFrame: (frame) => sent.push(frame), + logger: silentLogger, + }); + registerServerHandlers(queue, makeManager()); + + const counters = new Map(); + + return { + agent, + owner, + restricted, + admin, + operator, + registry, + trust, + queue, + sent, + audit, + async send(type, body, signer, onBehalfOf) { + const key = fingerprint(signer.publicKey); + const counter = (counters.get(key) ?? 0) + 1; + counters.set(key, counter); + const command = createSignedCommand( + { + type, + body, + agentPublicKey: agent.publicKey, + signer, + counter, + now: NOW, + ...(onBehalfOf !== undefined ? { onBehalfOf } : {}), + }, + registry, + ); + const frame: TransportCommandFrame = { + v: PROTOCOL_VERSION, + kind: "command", + route: { agent: fingerprint(agent.publicKey) }, + body: command, + }; + await queue.enqueue(frame); + return command; + }, + }; +} + +function lastAck(sent: readonly TransportFrame[]): { ok: boolean; code?: string } { + for (let i = sent.length - 1; i >= 0; i--) { + const frame = sent[i]; + if (frame?.kind === "ack") { + return frame.body.code !== undefined + ? { ok: frame.body.ok, code: frame.body.code } + : { ok: frame.body.ok }; + } + } + throw new Error("no ack"); +} + +async function openError( + promise: Promise, +): Promise<{ code?: string; message?: string } | null> { + try { + await promise; + } catch (err) { + if (err instanceof ProtocolError) { + return { code: err.code, message: err.message }; + } + return { message: err instanceof Error ? err.message : String(err) }; + } + return null; +} + +describe("on_behalf_of", () => { + test("a restricted key may sign it and openCommand exposes it", async () => { + const f = makeFixture(); + const command = createSignedCommand( + { + type: "server.start", + body: { server_id: SERVER }, + agentPublicKey: f.agent.publicKey, + signer: f.restricted, + counter: 1, + now: NOW, + onBehalfOf: ON_BEHALF, + }, + f.registry, + ); + + const opened = await openCommand(command, f.trust, f.registry); + expect(opened.onBehalfOf).toEqual(ON_BEHALF); + }); + + test("the owner key is refused", async () => { + const f = makeFixture(); + const command = createSignedCommand( + { + type: "server.start", + body: { server_id: SERVER }, + agentPublicKey: f.agent.publicKey, + signer: f.owner, + counter: 1, + now: NOW, + onBehalfOf: ON_BEHALF, + }, + f.registry, + ); + + const error = await openError(openCommand(command, f.trust, f.registry)); + expect(error).toEqual({ + code: "invalid_format", + message: "on_behalf_of is only accepted from restricted keys", + }); + }); + + test("altering it after signing is a bad signature", async () => { + const f = makeFixture(); + const command = createSignedCommand( + { + type: "server.start", + body: { server_id: SERVER }, + agentPublicKey: f.agent.publicKey, + signer: f.restricted, + counter: 1, + now: NOW, + onBehalfOf: ON_BEHALF, + }, + f.registry, + ); + command.header.on_behalf_of = { ...ON_BEHALF, display_name: "Mallory" }; + + const error = await openError(openCommand(command, f.trust, f.registry)); + expect(error?.code).toBe("bad_signature"); + }); +}); + +describe("audit log", () => { + test("server.start is recorded with and without on_behalf_of, server.status is not", async () => { + const f = makeFixture(); + + await f.send("server.start", { server_id: SERVER }, f.restricted, ON_BEHALF); + expect(lastAck(f.sent)).toEqual({ ok: true }); + let entries = f.audit.list({ limit: 50 }); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + type: "server.start", + server_id: SERVER, + account: fingerprint(f.restricted.publicKey), + ok: true, + on_behalf_of: ON_BEHALF, + }); + + await f.send("server.start", { server_id: SERVER }, f.owner); + expect(lastAck(f.sent)).toEqual({ ok: true }); + entries = f.audit.list({ limit: 50 }); + expect(entries).toHaveLength(2); + expect(entries[0]?.on_behalf_of).toBeUndefined(); + + await f.send("server.status", { server_id: SERVER }, f.owner); + expect(lastAck(f.sent)).toEqual({ ok: true }); + expect(f.audit.list({ limit: 50 })).toHaveLength(2); + }); + + test("a command error is recorded with its code", async () => { + const f = makeFixture(); + await f.send("server.start", { server_id: "broken" }, f.restricted, ON_BEHALF); + expect(lastAck(f.sent)).toEqual({ ok: false, code: "systemd_error" }); + + const entries = f.audit.list({ limit: 50 }); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + type: "server.start", + server_id: "broken", + ok: false, + error_code: "systemd_error", + on_behalf_of: ON_BEHALF, + }); + }); + + test("file log keeps the newest maxEntries, ignores corrupt lines and is 0600", () => { + const dir = mkdtempSync(join(tmpdir(), "tegrad-audit-")); + const path = join(dir, "audit.jsonl"); + try { + const log = createFileAuditLog(path, { maxEntries: 5000 }); + for (let i = 1; i <= 5600; i++) { + log.record({ + at: i, + type: "server.start", + server_id: SERVER, + account: "a".repeat(32), + ok: true, + }); + } + + const entries = log.list({ limit: 10_000 }); + expect(entries).toHaveLength(5000); + expect(entries[0]?.at).toBe(5600); + expect(entries[entries.length - 1]?.at).toBe(601); + + appendFileSync(path, "{not json\n"); + expect(log.list({ limit: 10_000 })).toHaveLength(5000); + + if (process.platform !== "win32") { + expect(statSync(path).mode & 0o777).toBe(0o600); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("agent.audit.list needs admin and returns entries to an admin", async () => { + const f = makeFixture(); + await f.send("server.start", { server_id: SERVER }, f.owner); + + await f.send("agent.audit.list", { server_id: SERVER, limit: 10 }, f.operator); + expect(lastAck(f.sent)).toEqual({ ok: false, code: "insufficient_role" }); + + const before = f.sent.length; + await f.send("agent.audit.list", { server_id: SERVER }, f.admin); + expect(lastAck(f.sent)).toEqual({ ok: true }); + + const event = f.sent.slice(before).find((frame) => frame.kind === "event"); + expect(event).toBeDefined(); + if (event?.kind === "event") { + const opened = openTestEvent(event.body, f.agent.publicKey, f.admin); + expect(opened.header.type).toBe("agent.audit.list.result"); + const data = opened.body as { entries: AuditEntry[] }; + expect(data.entries).toHaveLength(1); + expect(data.entries[0]?.type).toBe("server.start"); + } + }); +}); diff --git a/src/agent/audit.ts b/src/agent/audit.ts new file mode 100644 index 0000000..38fd90b --- /dev/null +++ b/src/agent/audit.ts @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { + appendFileSync, + chmodSync, + existsSync, + mkdirSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { dirname } from "node:path"; +import { auditEntrySchema, type KeyId, type OnBehalfOf } from "../protocol"; + +export const AUDITED_COMMANDS = ["server.start", "server.stop", "server.restart"] as const; + +export const DEFAULT_AUDIT_MAX_ENTRIES = 5000; +const COMPACT_EVERY_WRITES = 500; + +export interface AuditEntry { + at: number; + type: string; + server_id: string; + account: KeyId; + ok: boolean; + error_code?: string; + on_behalf_of?: OnBehalfOf; +} + +export interface AuditLog { + record(entry: AuditEntry): void; + list(params: { server_id?: string; before?: number; limit: number }): AuditEntry[]; +} + +export function isAuditedCommand(type: string): boolean { + return (AUDITED_COMMANDS as readonly string[]).includes(type); +} + +function selectEntries( + entries: readonly AuditEntry[], + params: { server_id?: string; before?: number; limit: number }, + maxEntries: number, +): AuditEntry[] { + const limit = Math.max(1, Math.min(params.limit, maxEntries)); + const selected: AuditEntry[] = []; + for (let i = entries.length - 1; i >= 0 && selected.length < limit; i--) { + const entry = entries[i]; + if (entry === undefined) { + continue; + } + if (params.server_id !== undefined && entry.server_id !== params.server_id) { + continue; + } + if (params.before !== undefined && entry.at >= params.before) { + continue; + } + selected.push(entry); + } + return selected; +} + +function parseLines(raw: string): AuditEntry[] { + const entries: AuditEntry[] = []; + for (const line of raw.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) { + continue; + } + let value: unknown; + try { + value = JSON.parse(trimmed); + } catch { + continue; + } + const parsed = auditEntrySchema.safeParse(value); + if (parsed.success) { + const entry = parsed.data; + entries.push({ + at: entry.at, + type: entry.type, + server_id: entry.server_id, + account: entry.account, + ok: entry.ok, + ...(entry.error_code !== undefined ? { error_code: entry.error_code } : {}), + ...(entry.on_behalf_of !== undefined ? { on_behalf_of: entry.on_behalf_of } : {}), + }); + } + } + return entries; +} + +export function createMemoryAuditLog(options?: { maxEntries?: number }): AuditLog { + const maxEntries = options?.maxEntries ?? DEFAULT_AUDIT_MAX_ENTRIES; + const entries: AuditEntry[] = []; + return { + record(entry: AuditEntry): void { + entries.push(entry); + if (entries.length > maxEntries) { + entries.splice(0, entries.length - maxEntries); + } + }, + list(params): AuditEntry[] { + return selectEntries(entries, params, maxEntries); + }, + }; +} + +export function createFileAuditLog(path: string, options?: { maxEntries?: number }): AuditLog { + const maxEntries = options?.maxEntries ?? DEFAULT_AUDIT_MAX_ENTRIES; + mkdirSync(dirname(path), { recursive: true }); + if (!existsSync(path)) { + writeFileSync(path, "", { mode: 0o600 }); + } + if (process.platform !== "win32") { + chmodSync(path, 0o600); + } + + let writes = 0; + + function readEntries(): AuditEntry[] { + try { + return parseLines(readFileSync(path, "utf8")); + } catch { + return []; + } + } + + function compact(): void { + const entries = readEntries(); + if (entries.length <= maxEntries) { + return; + } + const kept = entries.slice(-maxEntries); + const body = + kept.length > 0 ? `${kept.map((entry) => JSON.stringify(entry)).join("\n")}\n` : ""; + writeFileSync(path, body, { mode: 0o600 }); + if (process.platform !== "win32") { + chmodSync(path, 0o600); + } + } + + return { + record(entry: AuditEntry): void { + appendFileSync(path, `${JSON.stringify(entry)}\n`); + writes++; + if (writes % COMPACT_EVERY_WRITES === 0) { + compact(); + } + }, + list(params): AuditEntry[] { + return selectEntries(readEntries(), params, maxEntries); + }, + }; +} diff --git a/src/agent/jobs.ts b/src/agent/jobs.ts index 075a63a..28674d4 100644 --- a/src/agent/jobs.ts +++ b/src/agent/jobs.ts @@ -3,6 +3,7 @@ import { fingerprint, type PublicKey } from "../crypto"; import { + type AgentAuditListBody, type AgentMembersRevokeBody, type AgentMembersSetBody, type AgentSubscribeBody, @@ -23,6 +24,7 @@ import { type TrustContext, wrapEventBody, } from "../protocol"; +import { type AuditLog, isAuditedCommand } from "./audit"; import { readHostInfo } from "./host-info"; import type { Logger } from "./logger"; import { applyMembersRevoke, applyMembersSet } from "./members"; @@ -61,6 +63,8 @@ export interface CommandQueueOptions { readonly logger: Logger; readonly maxIdempotencyEntries?: number; readonly readHostInfo?: () => HostInfoResult; + /** Local record of state-changing commands. Absent in code paths that do not need it. */ + readonly audit?: AuditLog; } export interface PublishScope { @@ -310,6 +314,41 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { } } + const audit = options.audit; + + function recordAudit(opened: OpenedCommand, ok: boolean, errorCode?: string): void { + if (audit === undefined || !isAuditedCommand(opened.header.type)) { + return; + } + const body = opened.body; + const serverId = + typeof body === "object" && + body !== null && + "server_id" in body && + typeof (body as { server_id: unknown }).server_id === "string" + ? (body as { server_id: string }).server_id + : null; + if (serverId === null) { + return; + } + try { + audit.record({ + at: trust.now(), + type: opened.header.type, + server_id: serverId, + account: opened.accountId, + ok, + ...(errorCode !== undefined ? { error_code: errorCode } : {}), + ...(opened.onBehalfOf !== undefined ? { on_behalf_of: opened.onBehalfOf } : {}), + }); + } catch (err) { + logger.warn("Failed to write audit entry", { + type: opened.header.type, + errName: err instanceof Error ? err.name : "Error", + }); + } + } + async function runCommand(frame: TransportCommandFrame, opened: OpenedCommand): Promise { const handler = handlers.get(opened.header.type); if (!handler) { @@ -356,6 +395,7 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { code: err.code, reason: err.message, }); + recordAudit(opened, false, err.code); sendFrame(makeAckError(opened.header.id, err.code)); return; } @@ -366,10 +406,12 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { errName: err instanceof Error ? err.name : "Error", errMessage: sanitizeErrorMessage(err), }); + recordAudit(opened, false, "handler_error"); sendFrame(makeAckError(opened.header.id, "handler_error")); return; } + recordAudit(opened, true); const ack = makeAckOk(opened.header.id); recordCompletedAck(opened.header.id, frame.body.sig, ack); sendFrame(ack); @@ -481,6 +523,18 @@ export function createCommandQueue(options: CommandQueueOptions): CommandQueue { }); } + if (audit !== undefined) { + registerHandler("agent.audit.list", (opened, ctx) => { + const body = opened.body as AgentAuditListBody; + const entries = audit.list({ + ...(body.server_id !== undefined ? { server_id: body.server_id } : {}), + ...(body.before !== undefined ? { before: body.before } : {}), + limit: body.limit, + }); + ctx.sendEvent("agent.audit.list.result", { entries }); + }); + } + return { registerHandler, publish, diff --git a/src/agent/paths.ts b/src/agent/paths.ts index dfaae66..08001f1 100644 --- a/src/agent/paths.ts +++ b/src/agent/paths.ts @@ -21,6 +21,7 @@ export interface StatePaths { readonly replayPath: string; readonly networkIsolationPath: string; readonly updateDir: string; + readonly auditPath: string; } export function resolveStateDir( @@ -54,5 +55,6 @@ export function getStatePaths(stateDir: string): StatePaths { replayPath: join(stateDir, "replay.json"), networkIsolationPath: join(stateDir, "network-isolation.json"), updateDir: join(stateDir, "update"), + auditPath: join(stateDir, "audit.jsonl"), }; } diff --git a/src/cli/run.ts b/src/cli/run.ts index 085cd1f..c31a931 100644 --- a/src/cli/run.ts +++ b/src/cli/run.ts @@ -12,6 +12,7 @@ import { createLogger, type FetchLike, type FileTrustContext, + getStatePaths, isInsecureAllowed, type Logger, loadConfig, @@ -20,6 +21,7 @@ import { type TimerProvider, type WebSocketFactory, } from "../agent"; +import { createFileAuditLog } from "../agent/audit"; import { createFlapLimiter } from "../agent/flap-limit"; import { type BackupManager, createBackupManager, registerBackupHandlers } from "../backup"; import { fingerprint } from "../crypto"; @@ -129,10 +131,12 @@ export async function createAgentRuntime( }); let connectionRef: AgentConnection | null = null; + const auditLog = createFileAuditLog(getStatePaths(options.stateDir).auditPath); const queue = createCommandQueue({ trust, registry, logger, + audit: auditLog, sendFrame: (frame: TransportFrame) => { connectionRef?.send(frame); }, diff --git a/src/protocol/command.ts b/src/protocol/command.ts index b160f2f..21999e5 100644 --- a/src/protocol/command.ts +++ b/src/protocol/command.ts @@ -22,6 +22,7 @@ import type { Role } from "./roles"; import { type CommandHeader, type KeyId, + type OnBehalfOf, type SessionCertificate, type SignedCommand, signedCommandSchema, @@ -51,6 +52,11 @@ export interface CreateSignedCommandParams { * Defaults to the account key. A session signer must use its own key. */ readonly replyTo?: PublicKey; + /** + * Who the command was issued for, when a bot acts for a person. It is inside + * the signed header, so the agent can record it without trusting the server. + */ + readonly onBehalfOf?: OnBehalfOf; } export interface OpenedCommand { @@ -65,6 +71,8 @@ export interface OpenedCommand { readonly sessionNotAfter?: number; /** Key from the command's `reply_to`, when present. Replies go here instead of the account key. */ readonly replyTo?: PublicKey; + /** Who the command was issued for, copied from the signed header. */ + readonly onBehalfOf?: OnBehalfOf; /** Role of the signing account on the command's server (`"*"` for agent commands). */ readonly role: Role; } @@ -98,6 +106,7 @@ export function createSignedCommand( expires_at: params.now + ttlMs, counter: params.counter, ...(params.replyTo !== undefined ? { reply_to: toBase64Url(params.replyTo) } : {}), + ...(params.onBehalfOf !== undefined ? { on_behalf_of: params.onBehalfOf } : {}), }; const payloadBytes = sealTo(canonicalize(parsedBody.data), params.agentPublicKey); @@ -303,6 +312,9 @@ export async function openCommand( ? new ProtocolError("command_not_granted", "This key may not run this command") : new ProtocolError("insufficient_role", "Account role is below the command's minimum"); } + if (header.on_behalf_of !== undefined && !trust.isRestricted(accountId)) { + throw new ProtocolError("invalid_format", "on_behalf_of is only accepted from restricted keys"); + } return { header, @@ -314,5 +326,6 @@ export async function openCommand( ...(sessionId !== undefined ? { sessionId } : {}), ...(sessionNotAfter !== undefined ? { sessionNotAfter } : {}), ...(replyToKey !== undefined ? { replyTo: replyToKey } : {}), + ...(header.on_behalf_of !== undefined ? { onBehalfOf: header.on_behalf_of } : {}), }; } diff --git a/src/protocol/commands/agent.ts b/src/protocol/commands/agent.ts index b13c592..3f7341e 100644 --- a/src/protocol/commands/agent.ts +++ b/src/protocol/commands/agent.ts @@ -4,7 +4,7 @@ import { z } from "zod"; import { type CommandRegistry, defineCommand } from "../registry"; import { roleGrantSchema } from "../roles"; -import { keyIdSchema } from "../schemas"; +import { keyIdSchema, onBehalfOfSchema } from "../schemas"; import { serverIdSchema } from "./server"; export const SUBSCRIPTION_TOPICS = ["server.status", "server.backup", "server.modpack"] as const; @@ -52,6 +52,35 @@ export const agentMembersRevokeBodySchema = z .strict(); export type AgentMembersRevokeBody = z.infer; +export const auditEntrySchema = z + .object({ + at: z.number().int().nonnegative(), + type: z.string().min(1), + server_id: serverIdSchema, + account: keyIdSchema, + ok: z.boolean(), + error_code: z.string().min(1).optional(), + on_behalf_of: onBehalfOfSchema.optional(), + }) + .strict(); +export type AuditEntry = z.infer; + +export const agentAuditListBodySchema = z + .object({ + server_id: serverIdSchema.optional(), + before: z.number().int().nonnegative().optional(), + limit: z.number().int().min(1).max(200).default(50), + }) + .strict(); +export type AgentAuditListBody = z.infer; + +export const agentAuditListResultSchema = z + .object({ + entries: z.array(auditEntrySchema), + }) + .strict(); +export type AgentAuditListResult = z.infer; + export const agentSubscribeCommand = defineCommand({ type: "agent.subscribe", level: "session", @@ -80,11 +109,19 @@ export const agentMembersRevokeCommand = defineCommand({ body: agentMembersRevokeBodySchema, }); +export const agentAuditListCommand = defineCommand({ + type: "agent.audit.list", + level: "session", + minRole: "admin", + body: agentAuditListBodySchema, +}); + export const AGENT_COMMANDS = [ agentSubscribeCommand, agentUnsubscribeCommand, agentMembersSetCommand, agentMembersRevokeCommand, + agentAuditListCommand, ] as const; export function registerAgentCommands(registry: CommandRegistry): CommandRegistry { diff --git a/src/protocol/index.ts b/src/protocol/index.ts index b840946..c48a4ba 100644 --- a/src/protocol/index.ts +++ b/src/protocol/index.ts @@ -43,9 +43,15 @@ export { } from "./command"; export { AGENT_COMMANDS, + type AgentAuditListBody, + type AgentAuditListResult, type AgentMembersRevokeBody, type AgentMembersSetBody, type AgentSubscribeBody, + type AuditEntry, + agentAuditListBodySchema, + agentAuditListCommand, + agentAuditListResultSchema, agentMembersRevokeBodySchema, agentMembersRevokeCommand, agentMembersSetBodySchema, @@ -53,6 +59,7 @@ export { agentSubscribeBodySchema, agentSubscribeCommand, agentUnsubscribeCommand, + auditEntrySchema, registerAgentCommands, SERVER_STATES, type ServerState, @@ -406,6 +413,8 @@ export { commandHeaderSchema, type KeyId, keyIdSchema, + type OnBehalfOf, + onBehalfOfSchema, type RevocationList, revocationListSchema, type SessionCertificate, diff --git a/src/protocol/phase3.test.ts b/src/protocol/phase3.test.ts index 160fdd5..ebbb07a 100644 --- a/src/protocol/phase3.test.ts +++ b/src/protocol/phase3.test.ts @@ -694,6 +694,7 @@ const MIN_ROLE: Record = { "server.delete": "admin", "agent.members.set": "admin", "agent.members.revoke": "admin", + "agent.audit.list": "admin", "agent.revocations.set": "admin", }; diff --git a/src/protocol/schemas.ts b/src/protocol/schemas.ts index 1c2cc9b..3955878 100644 --- a/src/protocol/schemas.ts +++ b/src/protocol/schemas.ts @@ -29,6 +29,16 @@ export const sessionCertificateSchema = z.object({ }); export type SessionCertificate = z.infer; +export const onBehalfOfSchema = z + .object({ + via: z.literal("discord"), + user_id: z.string().regex(/^\d{1,32}$/), + display_name: z.string().min(1).max(64), + guild_id: z.string().regex(/^\d{1,32}$/), + }) + .strict(); +export type OnBehalfOf = z.infer; + export const commandHeaderSchema = z.object({ v: z.literal(PROTOCOL_VERSION), id: base64UrlSchema, @@ -39,6 +49,7 @@ export const commandHeaderSchema = z.object({ expires_at: z.number().int().nonnegative(), counter: z.number().int().nonnegative(), reply_to: base64UrlSchema.optional(), + on_behalf_of: onBehalfOfSchema.optional(), }); export type CommandHeader = z.infer; From 23fa8a78627fbed2c990fcff0dce9ed5f991f524 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ant=C3=B4nio=20Miranda?= Date: Mon, 30 Nov 2026 22:18:34 -0300 Subject: [PATCH 5/5] build(lib): rebuild for grant commands, status players and audit --- .../{index-3yjqz9zv.js => index-b83z6s0k.js} | 520 +++++++++++------- lib/protocol/index.js | 16 +- lib/types/protocol/command.d.ts | 11 +- lib/types/protocol/commands/agent.d.ts | 55 ++ lib/types/protocol/commands/host.d.ts | 3 + lib/types/protocol/errors.d.ts | 2 +- lib/types/protocol/index.d.ts | 8 +- lib/types/protocol/roles.d.ts | 13 + lib/types/protocol/schemas.d.ts | 31 ++ lib/types/protocol/trust.d.ts | 4 + lib/vault/index.js | 2 +- 11 files changed, 447 insertions(+), 218 deletions(-) rename lib/chunks/{index-3yjqz9zv.js => index-b83z6s0k.js} (88%) diff --git a/lib/chunks/index-3yjqz9zv.js b/lib/chunks/index-b83z6s0k.js similarity index 88% rename from lib/chunks/index-3yjqz9zv.js rename to lib/chunks/index-b83z6s0k.js index 89424ae..1c63e5e 100644 --- a/lib/chunks/index-3yjqz9zv.js +++ b/lib/chunks/index-b83z6s0k.js @@ -72,6 +72,12 @@ var sessionCertificateSchema = z.object({ scope: z.literal("elevated").optional(), sig: base64UrlSchema }); +var onBehalfOfSchema = z.object({ + via: z.literal("discord"), + user_id: z.string().regex(/^\d{1,32}$/), + display_name: z.string().min(1).max(64), + guild_id: z.string().regex(/^\d{1,32}$/) +}).strict(); var commandHeaderSchema = z.object({ v: z.literal(PROTOCOL_VERSION), id: base64UrlSchema, @@ -81,7 +87,8 @@ var commandHeaderSchema = z.object({ issued_at: z.number().int().nonnegative(), expires_at: z.number().int().nonnegative(), counter: z.number().int().nonnegative(), - reply_to: base64UrlSchema.optional() + reply_to: base64UrlSchema.optional(), + on_behalf_of: onBehalfOfSchema.optional() }); var signedCommandSchema = z.object({ header: commandHeaderSchema, @@ -414,207 +421,6 @@ function openAgentEvent(message, agentPublicKey, recipientKeyPair) { data: parsed.data.data }; } -// src/protocol/roles.ts -import { z as z3 } from "zod"; -var ROLES = ["viewer", "operator", "editor", "admin", "owner"]; -var roleSchema = z3.enum(ROLES); -var GRANTABLE_ROLES = ["viewer", "operator", "editor", "admin"]; -var grantableRoleSchema = z3.enum(GRANTABLE_ROLES); -var ROLE_LEVEL = { - viewer: 1, - operator: 2, - editor: 3, - admin: 4, - owner: 5 -}; -function roleAtLeast(role, minimum) { - return role !== null && role !== undefined && ROLE_LEVEL[role] >= ROLE_LEVEL[minimum]; -} -function maxRole(a, b) { - if (a === null) - return b; - if (b === null) - return a; - return ROLE_LEVEL[a] >= ROLE_LEVEL[b] ? a : b; -} -var ALL_SERVERS = "*"; -var MAX_GRANT_SERVERS = 256; -var MAX_MEMBERS = 64; -var grantServerIdSchema = z3.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "Invalid server id"); -var grantServersSchema = z3.union([ - z3.literal(ALL_SERVERS), - z3.array(grantServerIdSchema).min(1).max(MAX_GRANT_SERVERS) -]); -var roleGrantSchema = z3.object({ - v: z3.literal(PROTOCOL_VERSION), - kind: z3.literal("server-role"), - account_key: base64UrlSchema, - agent: keyIdSchema, - servers: grantServersSchema, - role: grantableRoleSchema, - issued_at: z3.number().int().nonnegative(), - expires_at: z3.number().int().nonnegative().optional(), - sig: base64UrlSchema -}).strict(); -var MAX_GRANT_CLOCK_SKEW_MS = 5 * 60 * 1000; -function signRoleGrant(params) { - if (params.accountPublicKey.length !== SIGNING_PUBLIC_KEY_BYTES) { - throw new RangeError(`Account public key must be ${SIGNING_PUBLIC_KEY_BYTES} bytes`); - } - if (!Number.isSafeInteger(params.issuedAt) || params.issuedAt < 0) { - throw new RangeError("issuedAt must be a non-negative safe integer"); - } - if (params.expiresAt !== undefined && (!Number.isSafeInteger(params.expiresAt) || params.expiresAt <= params.issuedAt)) { - throw new RangeError("expiresAt must be a safe integer after issuedAt"); - } - const unsigned = { - v: PROTOCOL_VERSION, - kind: "server-role", - account_key: toBase64Url(params.accountPublicKey), - agent: params.agent, - servers: params.servers === ALL_SERVERS ? ALL_SERVERS : [...params.servers], - role: params.role, - issued_at: params.issuedAt, - ...params.expiresAt !== undefined ? { expires_at: params.expiresAt } : {} - }; - const signingInput = concatBytes(DOMAIN_ROLE_GRANT, canonicalize(unsigned)); - const signature = sign(signingInput, params.granter.secretKey); - return roleGrantSchema.parse({ ...unsigned, sig: toBase64Url(signature) }); -} -function verifyRoleGrant(grant, granterPublicKey, options) { - assertSupportedVersion(grant); - const parsed = roleGrantSchema.safeParse(grant); - if (!parsed.success) { - throw new ProtocolError("role_grant_invalid", "Malformed role grant"); - } - const data = parsed.data; - if (data.agent !== options.agent) { - throw new ProtocolError("role_grant_invalid", "Role grant is addressed to a different agent"); - } - if (data.issued_at > options.now + MAX_GRANT_CLOCK_SKEW_MS) { - throw new ProtocolError("role_grant_invalid", "Role grant issued_at is in the future"); - } - if (data.expires_at !== undefined && data.expires_at <= data.issued_at) { - throw new ProtocolError("role_grant_invalid", "Role grant expiry is not after issuance"); - } - if (data.expires_at !== undefined && options.now >= data.expires_at) { - throw new ProtocolError("role_grant_invalid", "Role grant has expired"); - } - if (data.servers !== ALL_SERVERS && new Set(data.servers).size !== data.servers.length) { - throw new ProtocolError("role_grant_invalid", "Role grant lists a server more than once"); - } - let accountPublicKey; - let signatureBytes; - try { - accountPublicKey = fromBase64Url(data.account_key); - signatureBytes = fromBase64Url(data.sig); - } catch { - throw new ProtocolError("role_grant_invalid", "Invalid base64url encoding in role grant"); - } - if (accountPublicKey.length !== SIGNING_PUBLIC_KEY_BYTES) { - throw new ProtocolError("role_grant_invalid", "Invalid account key length in role grant"); - } - const { sig: _sig, ...unsigned } = data; - const signingInput = concatBytes(DOMAIN_ROLE_GRANT, canonicalize(unsigned)); - if (!verify(signingInput, signatureBytes, granterPublicKey)) { - throw new ProtocolError("role_grant_invalid", "Invalid role grant signature"); - } - return { grant: data, accountPublicKey, accountId: fingerprint(accountPublicKey) }; -} -var memberEntrySchema = z3.object({ - account_key: base64UrlSchema, - account: keyIdSchema, - granted_by: keyIdSchema, - role: grantableRoleSchema, - servers: grantServersSchema, - issued_at: z3.number().int().nonnegative(), - expires_at: z3.number().int().nonnegative().optional() -}).strict(); -function scopeKey(servers) { - return servers === ALL_SERVERS ? ALL_SERVERS : [...servers].sort().join(","); -} -function isActive(entry, now) { - return entry.expires_at === undefined || now < entry.expires_at; -} - -class RoleTable { - #entries; - constructor(entries = []) { - this.#entries = [...entries]; - } - entries() { - return [...this.#entries]; - } - accountCount() { - return new Set(this.#entries.map((entry) => entry.account)).size; - } - keyFor(account, now) { - for (const entry of this.#entries) { - if (entry.account === account && isActive(entry, now)) { - try { - return fromBase64Url(entry.account_key); - } catch { - return null; - } - } - } - return null; - } - roleFor(account, serverId, now) { - let best = null; - let anyActive = false; - for (const entry of this.#entries) { - if (entry.account !== account || !isActive(entry, now)) { - continue; - } - anyActive = true; - const covers = entry.servers === ALL_SERVERS || serverId !== ALL_SERVERS && entry.servers.includes(serverId); - if (covers) { - best = maxRole(best, entry.role); - } - } - if (best === null && serverId === ALL_SERVERS && anyActive) { - return "viewer"; - } - return best; - } - set(entry) { - const key = scopeKey(entry.servers); - const next = this.#entries.filter((existing) => !(existing.account === entry.account && scopeKey(existing.servers) === key)); - next.push(entry); - this.#entries = next; - } - revoke(account, servers) { - let changed = 0; - const next = []; - for (const entry of this.#entries) { - if (entry.account !== account) { - next.push(entry); - continue; - } - if (servers === undefined) { - changed++; - continue; - } - if (entry.servers === ALL_SERVERS) { - next.push(entry); - continue; - } - const remaining = entry.servers.filter((id) => !servers.includes(id)); - if (remaining.length === entry.servers.length) { - next.push(entry); - continue; - } - changed++; - if (remaining.length > 0) { - next.push({ ...entry, servers: remaining }); - } - } - this.#entries = next; - return changed; - } -} - // src/protocol/session.ts var MAX_ELEVATED_SESSION_MS = 60 * 60 * 1000; function signSessionCertificate(params) { @@ -717,7 +523,8 @@ function createSignedCommand(params, registry) { issued_at: params.now, expires_at: params.now + ttlMs, counter: params.counter, - ...params.replyTo !== undefined ? { reply_to: toBase64Url(params.replyTo) } : {} + ...params.replyTo !== undefined ? { reply_to: toBase64Url(params.replyTo) } : {}, + ...params.onBehalfOf !== undefined ? { on_behalf_of: params.onBehalfOf } : {} }; const payloadBytes = sealTo(canonicalize(parsedBody.data), params.agentPublicKey); const signingInput = concatBytes(DOMAIN_COMMAND, canonicalize(header), payloadBytes); @@ -864,9 +671,15 @@ async function openCommand(command, trust, registry) { } const scope = typeof bodyResult.data === "object" && bodyResult.data !== null && "server_id" in bodyResult.data && typeof bodyResult.data.server_id === "string" ? bodyResult.data.server_id : "*"; const role = trust.roleFor(accountId, scope); - if (role === null || !roleAtLeast(role, definition.minRole)) { + if (role === null) { throw new ProtocolError("insufficient_role", "Account role is below the command's minimum"); } + if (!trust.mayRun(accountId, scope, header.type, definition.minRole)) { + throw trust.isRestricted(accountId) ? new ProtocolError("command_not_granted", "This key may not run this command") : new ProtocolError("insufficient_role", "Account role is below the command's minimum"); + } + if (header.on_behalf_of !== undefined && !trust.isRestricted(accountId)) { + throw new ProtocolError("invalid_format", "on_behalf_of is only accepted from restricted keys"); + } return { header, body: bodyResult.data, @@ -876,7 +689,8 @@ async function openCommand(command, trust, registry) { role, ...sessionId !== undefined ? { sessionId } : {}, ...sessionNotAfter !== undefined ? { sessionNotAfter } : {}, - ...replyToKey !== undefined ? { replyTo: replyToKey } : {} + ...replyToKey !== undefined ? { replyTo: replyToKey } : {}, + ...header.on_behalf_of !== undefined ? { onBehalfOf: header.on_behalf_of } : {} }; } // src/protocol/commands/agent.ts @@ -919,6 +733,251 @@ class CommandRegistry { } } +// src/protocol/roles.ts +import { z as z3 } from "zod"; +var ROLES = ["viewer", "operator", "editor", "admin", "owner"]; +var roleSchema = z3.enum(ROLES); +var GRANTABLE_ROLES = ["viewer", "operator", "editor", "admin"]; +var grantableRoleSchema = z3.enum(GRANTABLE_ROLES); +var ROLE_LEVEL = { + viewer: 1, + operator: 2, + editor: 3, + admin: 4, + owner: 5 +}; +function roleAtLeast(role, minimum) { + return role !== null && role !== undefined && ROLE_LEVEL[role] >= ROLE_LEVEL[minimum]; +} +function maxRole(a, b) { + if (a === null) + return b; + if (b === null) + return a; + return ROLE_LEVEL[a] >= ROLE_LEVEL[b] ? a : b; +} +var ALL_SERVERS = "*"; +var MAX_GRANT_SERVERS = 256; +var MAX_GRANT_COMMANDS = 32; +var MAX_MEMBERS = 64; +var grantServerIdSchema = z3.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "Invalid server id"); +var grantServersSchema = z3.union([ + z3.literal(ALL_SERVERS), + z3.array(grantServerIdSchema).min(1).max(MAX_GRANT_SERVERS) +]); +var grantCommandSchema = z3.string().regex(/^[a-z][a-z0-9_.]{0,63}$/); +var grantCommandsSchema = z3.array(grantCommandSchema).min(1).max(MAX_GRANT_COMMANDS); +var roleGrantSchema = z3.object({ + v: z3.literal(PROTOCOL_VERSION), + kind: z3.literal("server-role"), + account_key: base64UrlSchema, + agent: keyIdSchema, + servers: grantServersSchema, + role: grantableRoleSchema, + commands: grantCommandsSchema.optional(), + issued_at: z3.number().int().nonnegative(), + expires_at: z3.number().int().nonnegative().optional(), + sig: base64UrlSchema +}).strict(); +var MAX_GRANT_CLOCK_SKEW_MS = 5 * 60 * 1000; +function signRoleGrant(params) { + if (params.accountPublicKey.length !== SIGNING_PUBLIC_KEY_BYTES) { + throw new RangeError(`Account public key must be ${SIGNING_PUBLIC_KEY_BYTES} bytes`); + } + if (!Number.isSafeInteger(params.issuedAt) || params.issuedAt < 0) { + throw new RangeError("issuedAt must be a non-negative safe integer"); + } + if (params.expiresAt !== undefined && (!Number.isSafeInteger(params.expiresAt) || params.expiresAt <= params.issuedAt)) { + throw new RangeError("expiresAt must be a safe integer after issuedAt"); + } + if (params.commands !== undefined && new Set(params.commands).size !== params.commands.length) { + throw new RangeError("commands must not contain duplicates"); + } + const unsigned = { + v: PROTOCOL_VERSION, + kind: "server-role", + account_key: toBase64Url(params.accountPublicKey), + agent: params.agent, + servers: params.servers === ALL_SERVERS ? ALL_SERVERS : [...params.servers], + role: params.role, + ...params.commands !== undefined ? { commands: [...params.commands] } : {}, + issued_at: params.issuedAt, + ...params.expiresAt !== undefined ? { expires_at: params.expiresAt } : {} + }; + const signingInput = concatBytes(DOMAIN_ROLE_GRANT, canonicalize(unsigned)); + const signature = sign(signingInput, params.granter.secretKey); + return roleGrantSchema.parse({ ...unsigned, sig: toBase64Url(signature) }); +} +function verifyRoleGrant(grant, granterPublicKey, options) { + assertSupportedVersion(grant); + const parsed = roleGrantSchema.safeParse(grant); + if (!parsed.success) { + throw new ProtocolError("role_grant_invalid", "Malformed role grant"); + } + const data = parsed.data; + if (data.agent !== options.agent) { + throw new ProtocolError("role_grant_invalid", "Role grant is addressed to a different agent"); + } + if (data.issued_at > options.now + MAX_GRANT_CLOCK_SKEW_MS) { + throw new ProtocolError("role_grant_invalid", "Role grant issued_at is in the future"); + } + if (data.expires_at !== undefined && data.expires_at <= data.issued_at) { + throw new ProtocolError("role_grant_invalid", "Role grant expiry is not after issuance"); + } + if (data.expires_at !== undefined && options.now >= data.expires_at) { + throw new ProtocolError("role_grant_invalid", "Role grant has expired"); + } + if (data.servers !== ALL_SERVERS && new Set(data.servers).size !== data.servers.length) { + throw new ProtocolError("role_grant_invalid", "Role grant lists a server more than once"); + } + if (data.commands !== undefined && new Set(data.commands).size !== data.commands.length) { + throw new ProtocolError("role_grant_invalid", "Role grant lists a command more than once"); + } + let accountPublicKey; + let signatureBytes; + try { + accountPublicKey = fromBase64Url(data.account_key); + signatureBytes = fromBase64Url(data.sig); + } catch { + throw new ProtocolError("role_grant_invalid", "Invalid base64url encoding in role grant"); + } + if (accountPublicKey.length !== SIGNING_PUBLIC_KEY_BYTES) { + throw new ProtocolError("role_grant_invalid", "Invalid account key length in role grant"); + } + const { sig: _sig, ...unsigned } = data; + const signingInput = concatBytes(DOMAIN_ROLE_GRANT, canonicalize(unsigned)); + if (!verify(signingInput, signatureBytes, granterPublicKey)) { + throw new ProtocolError("role_grant_invalid", "Invalid role grant signature"); + } + return { grant: data, accountPublicKey, accountId: fingerprint(accountPublicKey) }; +} +var memberEntrySchema = z3.object({ + account_key: base64UrlSchema, + account: keyIdSchema, + granted_by: keyIdSchema, + role: grantableRoleSchema, + servers: grantServersSchema, + commands: grantCommandsSchema.optional(), + issued_at: z3.number().int().nonnegative(), + expires_at: z3.number().int().nonnegative().optional() +}).strict(); +function serverScopeKey(servers) { + return servers === ALL_SERVERS ? ALL_SERVERS : [...servers].sort().join(","); +} +function commandScopeKey(commands) { + return commands === undefined ? "" : [...commands].sort().join(","); +} +function scopeKey(entry) { + return `${serverScopeKey(entry.servers)}|${commandScopeKey(entry.commands)}`; +} +function isActive(entry, now) { + return entry.expires_at === undefined || now < entry.expires_at; +} + +class RoleTable { + #entries; + constructor(entries = []) { + this.#entries = [...entries]; + } + entries() { + return [...this.#entries]; + } + accountCount() { + return new Set(this.#entries.map((entry) => entry.account)).size; + } + keyFor(account, now) { + for (const entry of this.#entries) { + if (entry.account === account && isActive(entry, now)) { + try { + return fromBase64Url(entry.account_key); + } catch { + return null; + } + } + } + return null; + } + roleFor(account, serverId, now) { + let best = null; + let anyActive = false; + for (const entry of this.#entries) { + if (entry.account !== account || !isActive(entry, now)) { + continue; + } + anyActive = true; + const covers = entry.servers === ALL_SERVERS || serverId !== ALL_SERVERS && entry.servers.includes(serverId); + if (covers) { + best = maxRole(best, entry.role); + } + } + if (best === null && serverId === ALL_SERVERS && anyActive) { + return "viewer"; + } + return best; + } + commandAllowed(account, serverId, type, minRole, now) { + for (const entry of this.#entries) { + if (entry.account !== account || !isActive(entry, now)) { + continue; + } + if (entry.commands !== undefined && !entry.commands.includes(type)) { + continue; + } + const covers = entry.servers === ALL_SERVERS || serverId !== ALL_SERVERS && entry.servers.includes(serverId); + if (covers && ROLE_LEVEL[entry.role] >= ROLE_LEVEL[minRole]) { + return true; + } + if (serverId === ALL_SERVERS && minRole === "viewer") { + return true; + } + } + return false; + } + isRestricted(account, now) { + for (const entry of this.#entries) { + if (entry.account === account && isActive(entry, now) && entry.commands !== undefined) { + return true; + } + } + return false; + } + set(entry) { + const key = scopeKey(entry); + const next = this.#entries.filter((existing) => !(existing.account === entry.account && scopeKey(existing) === key)); + next.push(entry); + this.#entries = next; + } + revoke(account, servers) { + let changed = 0; + const next = []; + for (const entry of this.#entries) { + if (entry.account !== account) { + next.push(entry); + continue; + } + if (servers === undefined) { + changed++; + continue; + } + if (entry.servers === ALL_SERVERS) { + next.push(entry); + continue; + } + const remaining = entry.servers.filter((id) => !servers.includes(id)); + if (remaining.length === entry.servers.length) { + next.push(entry); + continue; + } + changed++; + if (remaining.length > 0) { + next.push({ ...entry, servers: remaining }); + } + } + this.#entries = next; + return changed; + } +} + // src/protocol/commands/server.ts import { z as z4 } from "zod"; var SERVER_ID_REGEX = /^[a-z0-9][a-z0-9-]{0,62}$/; @@ -1082,7 +1141,12 @@ var serverStateSchema = z5.enum(SERVER_STATES); var serverStatusChangedSchema = z5.object({ server_id: serverIdSchema, state: serverStateSchema, - at: z5.number().int().nonnegative() + at: z5.number().int().nonnegative(), + players: z5.object({ + online: z5.number().int().nonnegative(), + max: z5.number().int().nonnegative() + }).nullable().optional(), + motd: z5.string().max(256).nullable().optional() }); var agentSubscribeBodySchema = z5.object({ topics: z5.array(subscriptionTopicSchema).min(1).max(SUBSCRIPTION_TOPICS.length) @@ -1094,6 +1158,23 @@ var agentMembersRevokeBodySchema = z5.object({ account: keyIdSchema, servers: z5.array(serverIdSchema).min(1).max(256).optional() }).strict(); +var auditEntrySchema = z5.object({ + at: z5.number().int().nonnegative(), + type: z5.string().min(1), + server_id: serverIdSchema, + account: keyIdSchema, + ok: z5.boolean(), + error_code: z5.string().min(1).optional(), + on_behalf_of: onBehalfOfSchema.optional() +}).strict(); +var agentAuditListBodySchema = z5.object({ + server_id: serverIdSchema.optional(), + before: z5.number().int().nonnegative().optional(), + limit: z5.number().int().min(1).max(200).default(50) +}).strict(); +var agentAuditListResultSchema = z5.object({ + entries: z5.array(auditEntrySchema) +}).strict(); var agentSubscribeCommand = defineCommand({ type: "agent.subscribe", level: "session", @@ -1118,11 +1199,18 @@ var agentMembersRevokeCommand = defineCommand({ minRole: "admin", body: agentMembersRevokeBodySchema }); +var agentAuditListCommand = defineCommand({ + type: "agent.audit.list", + level: "session", + minRole: "admin", + body: agentAuditListBodySchema +}); var AGENT_COMMANDS = [ agentSubscribeCommand, agentUnsubscribeCommand, agentMembersSetCommand, - agentMembersRevokeCommand + agentMembersRevokeCommand, + agentAuditListCommand ]; function registerAgentCommands(registry) { return registry.registerAll(AGENT_COMMANDS); @@ -1490,12 +1578,14 @@ function registerFilesCommands(registry) { // src/protocol/commands/host.ts import { z as z8 } from "zod"; var hostInfoBodySchema = z8.object({}).strict(); +var AGENT_FEATURES = ["grant_commands", "status_players", "audit"]; var hostInfoResultSchema = z8.object({ memory_total_mb: z8.number().int().nonnegative(), memory_available_mb: z8.number().int().nonnegative(), cpu_count: z8.number().int().positive(), reserved_memory_mb: z8.number().int().nonnegative(), - addresses: z8.array(z8.string().min(1).max(45)).max(16).optional() + addresses: z8.array(z8.string().min(1).max(45)).max(16).optional(), + features: z8.array(z8.string().min(1).max(64)).max(32).optional() }); var hostInfoCommand = defineCommand({ type: "host.info", @@ -2327,6 +2417,18 @@ function createInMemoryTrustContext(options) { } return members.roleFor(account, serverId, clock()); }, + mayRun(account, serverId, type, minRole) { + if (trusted.has(account)) { + return true; + } + return members.commandAllowed(account, serverId, type, minRole, clock()); + }, + isRestricted(account) { + if (trusted.has(account)) { + return false; + } + return members.isRestricted(account, clock()); + }, listMembers() { return members.entries(); }, @@ -2362,4 +2464,4 @@ function createInMemoryTrustContext(options) { } }; } -export { ProtocolError, PROTOCOL_VERSION, DOMAIN_COMMAND, DOMAIN_SESSION, DOMAIN_AGENT_MESSAGE, DOMAIN_REVOCATION, DOMAIN_TRUST_GRANT, DOMAIN_PAIRING_PROOF, DOMAIN_AGENT_AUTH, DOMAIN_AGENT_HTTP, DOMAIN_ROLE_GRANT, keyIdSchema, base64UrlSchema, sessionCertificateSchema, commandHeaderSchema, signedCommandSchema, agentMessageHeaderSchema, agentMessageSchema, revocationListSchema, transportCommandFrameSchema, transportEventFrameSchema, transportAckFrameSchema, transportPingFrameSchema, AGENT_NONCE_BYTES, agentNonceSchema, transportHelloFrameSchema, transportAuthFrameSchema, transportFrameSchema, AGENT_AUTH_MAX_SKEW_MS, AGENT_HTTP_MAX_SKEW_MS, AGENT_HTTP_HEADER_AGENT, AGENT_HTTP_HEADER_TS, AGENT_HTTP_HEADER_SIG, generateAgentNonce, createHelloFrame, signAgentAuth, verifyAgentAuth, signAgentRequest, verifyAgentRequest, sealAgentMessage, openAgentMessage, agentEventBodySchema, wrapEventBody, openAgentEvent, ROLES, roleSchema, GRANTABLE_ROLES, grantableRoleSchema, ROLE_LEVEL, roleAtLeast, maxRole, ALL_SERVERS, MAX_GRANT_SERVERS, MAX_MEMBERS, roleGrantSchema, MAX_GRANT_CLOCK_SKEW_MS, signRoleGrant, verifyRoleGrant, memberEntrySchema, RoleTable, MAX_ELEVATED_SESSION_MS, signSessionCertificate, verifySessionCertificate, COMMAND_ID_BYTES, DEFAULT_COMMAND_TTL_MS, MAX_COMMAND_TTL_MS, MAX_CLOCK_SKEW_MS, createSignedCommand, openCommand, defineCommand, CommandRegistry, SERVER_ID_REGEX, DEFAULT_SERVER_PORT, MAX_CONSOLE_LINE_LENGTH, MIN_SERVER_MEMORY_MB, MAX_SERVER_MEMORY_MB, MAX_JVM_ARGS, serverIdSchema, serverLoaderSchema, serverPortSchema, serverStartOnBootSchema, DEFAULT_START_ON_BOOT, serverMemoryMbSchema, consoleLineSchema, minecraftVersionSchema, loaderVersionSchema, serverCreateBodySchema, serverChangeRuntimeBodySchema, serverUpdateSettingsBodySchema, serverConsoleSendBodySchema, serverConsoleSubscribeBodySchema, serverConsoleHistoryBodySchema, serverStatsBodySchema, serverStatsResultSchema, serverCreateCommand, serverChangeRuntimeCommand, serverRestartCommand, serverStatusCommand, serverStatsCommand, serverListCommand, serverUpdateSettingsCommand, serverConsoleSendCommand, serverConsoleSubscribeCommand, serverConsoleHistoryCommand, serverConsoleUnsubscribeCommand, SERVER_COMMANDS, registerServerCommands, SUBSCRIPTION_TOPICS, subscriptionTopicSchema, SERVER_STATES, serverStateSchema, serverStatusChangedSchema, agentSubscribeBodySchema, agentMembersSetBodySchema, agentMembersRevokeBodySchema, agentSubscribeCommand, agentUnsubscribeCommand, agentMembersSetCommand, agentMembersRevokeCommand, AGENT_COMMANDS, registerAgentCommands, BACKUP_ID_REGEX, MIN_BACKUP_INTERVAL_MINUTES, MAX_BACKUP_INTERVAL_MINUTES, MIN_BACKUP_RETENTION_COUNT, MAX_BACKUP_RETENTION_COUNT, backupIdSchema, backupDestinationKindSchema, BACKUP_UPLOAD_STATES, backupUploadStateSchema, serverBackupUploadEventSchema, pendingBackupUploadSchema, backupScheduleConfigSchema, backupLocalConfigSchema, s3BucketSchema, s3RegionSchema, s3PrefixSchema, backupS3ConfigSchema, backupTegraCloudConfigSchema, serverBackupConfigSetBodySchema, serverBackupCreateBodySchema, serverBackupListBodySchema, serverBackupDeleteBodySchema, serverBackupRestoreBodySchema, serverBackupConfigSetCommand, serverBackupConfigGetCommand, serverBackupCreateCommand, serverBackupListCommand, serverBackupDeleteCommand, serverBackupRestoreCommand, BACKUP_COMMANDS, registerBackupCommands, SERVER_ID_PATTERN, SHA256_HEX_PATTERN, fileEncodingSchema, sha256HexSchema, filesListCommand, filesStatCommand, filesReadCommand, filesWriteCommand, filesMkdirCommand, filesRenameCommand, filesCopyCommand, filesDeleteCommand, filesUploadBeginCommand, filesUploadPartCommand, filesUploadCommitCommand, filesUploadAbortCommand, filesDownloadBeginCommand, filesDownloadPartCommand, filesDownloadCloseCommand, filesDownloadCommand, filesZipCommand, filesUnzipCommand, FILES_COMMANDS, registerFilesCommands, hostInfoBodySchema, hostInfoResultSchema, hostInfoCommand, HOST_COMMANDS, registerHostCommands, MODPACK_SOURCES, modpackSourceSchema, MODPACK_INSTALL_PHASES, modpackInstallPhaseSchema, MODPACK_INSTALL_JOB_STATES, modpackInstallJobStateSchema, MODPACK_INSTALL_ERROR_CODES, modpackInstallErrorCodeSchema, modpackInstallSkippedItemSchema, serverInstallModpackBodySchema, serverInstallModpackStatusBodySchema, serverInstallModpackCancelBodySchema, serverInstallModpackAcceptedEventSchema, serverInstallModpackProgressEventSchema, serverInstallModpackResultEventSchema, modpackInstallJobStatusSchema, serverInstallModpackStatusResultSchema, serverInstallModpackCommand, serverInstallModpackStatusCommand, serverInstallModpackCancelCommand, MODPACK_COMMANDS, registerModpackCommands, agentRevocationsSetCommand, PAIRING_COMMANDS, registerPairingCommands, SHA1_HEX_PATTERN, SHA512_HEX_PATTERN, sha1HexSchema, sha512HexSchema, modSourceSchema, modLayerSchema, modFileNameSchema, serverModEntrySchema, serverOriginSchema, serverOriginSyncStateSchema, modEnvironmentInfoSchema, originPlanModInputSchema, originPlanFileInputSchema, serverModsListBodySchema, serverModsInstallBodySchema, serverModsRemoveBodySchema, serverModsToggleBodySchema, serverModsReplaceBodySchema, serverModsIdentifyBodySchema, serverOriginPlanBodySchema, serverOriginApplyBodySchema, serverOriginUnlinkBodySchema, blobKeySchema, WORLD_NAME_REGEX, RESERVED_WORLD_NAMES, worldNameSchema, serverWorldImportBodySchema, serverDeployServerpackBodySchema, serverModsListCommand, serverModsInstallCommand, serverModsRemoveCommand, serverModsToggleCommand, serverModsReplaceCommand, serverModsIdentifyCommand, serverOriginPlanCommand, serverOriginApplyCommand, serverOriginUnlinkCommand, serverDeployServerpackCommand, serverWorldImportCommand, STATE_COMMANDS, registerStateCommands, PLAYIT_SECRET_KEY_REGEX, playitSecretKeySchema, tunnelPlayitSetKeyBodySchema, tunnelPlayitSetKeyCommand, tunnelPlayitStartCommand, tunnelPlayitStopCommand, tunnelPlayitStatusCommand, tunnelPlayitClaimBeginCommand, tunnelPlayitClaimStatusCommand, tunnelPlayitClaimCancelCommand, serverTunnelBodySchema, serverTunnelCreateBodySchema, serverTunnelGetCommand, serverTunnelCreateCommand, TUNNEL_COMMANDS, registerTunnelCommands, agentPingCommand, serverStartCommand, serverStopCommand, serverDeleteCommand, CORE_COMMANDS, registerCoreCommands, createCoreRegistry, PAIRING_CODE_LENGTH, PAIRING_SECRET_BYTES, DEFAULT_TRUST_GRANT_TTL_MS, MAX_TRUST_GRANT_TTL_MS, pairingCodeSchema, trustGrantSchema, generatePairingCode, generatePairingSecret, buildPairingFragment, parsePairingFragment, signTrustGrant, verifyTrustGrant, signRevocationList, verifyRevocationList, createInMemoryTrustContext }; +export { ProtocolError, PROTOCOL_VERSION, DOMAIN_COMMAND, DOMAIN_SESSION, DOMAIN_AGENT_MESSAGE, DOMAIN_REVOCATION, DOMAIN_TRUST_GRANT, DOMAIN_PAIRING_PROOF, DOMAIN_AGENT_AUTH, DOMAIN_AGENT_HTTP, DOMAIN_ROLE_GRANT, keyIdSchema, base64UrlSchema, sessionCertificateSchema, onBehalfOfSchema, commandHeaderSchema, signedCommandSchema, agentMessageHeaderSchema, agentMessageSchema, revocationListSchema, transportCommandFrameSchema, transportEventFrameSchema, transportAckFrameSchema, transportPingFrameSchema, AGENT_NONCE_BYTES, agentNonceSchema, transportHelloFrameSchema, transportAuthFrameSchema, transportFrameSchema, AGENT_AUTH_MAX_SKEW_MS, AGENT_HTTP_MAX_SKEW_MS, AGENT_HTTP_HEADER_AGENT, AGENT_HTTP_HEADER_TS, AGENT_HTTP_HEADER_SIG, generateAgentNonce, createHelloFrame, signAgentAuth, verifyAgentAuth, signAgentRequest, verifyAgentRequest, sealAgentMessage, openAgentMessage, agentEventBodySchema, wrapEventBody, openAgentEvent, MAX_ELEVATED_SESSION_MS, signSessionCertificate, verifySessionCertificate, COMMAND_ID_BYTES, DEFAULT_COMMAND_TTL_MS, MAX_COMMAND_TTL_MS, MAX_CLOCK_SKEW_MS, createSignedCommand, openCommand, defineCommand, CommandRegistry, ROLES, roleSchema, GRANTABLE_ROLES, grantableRoleSchema, ROLE_LEVEL, roleAtLeast, maxRole, ALL_SERVERS, MAX_GRANT_SERVERS, MAX_GRANT_COMMANDS, MAX_MEMBERS, roleGrantSchema, MAX_GRANT_CLOCK_SKEW_MS, signRoleGrant, verifyRoleGrant, memberEntrySchema, RoleTable, SERVER_ID_REGEX, DEFAULT_SERVER_PORT, MAX_CONSOLE_LINE_LENGTH, MIN_SERVER_MEMORY_MB, MAX_SERVER_MEMORY_MB, MAX_JVM_ARGS, serverIdSchema, serverLoaderSchema, serverPortSchema, serverStartOnBootSchema, DEFAULT_START_ON_BOOT, serverMemoryMbSchema, consoleLineSchema, minecraftVersionSchema, loaderVersionSchema, serverCreateBodySchema, serverChangeRuntimeBodySchema, serverUpdateSettingsBodySchema, serverConsoleSendBodySchema, serverConsoleSubscribeBodySchema, serverConsoleHistoryBodySchema, serverStatsBodySchema, serverStatsResultSchema, serverCreateCommand, serverChangeRuntimeCommand, serverRestartCommand, serverStatusCommand, serverStatsCommand, serverListCommand, serverUpdateSettingsCommand, serverConsoleSendCommand, serverConsoleSubscribeCommand, serverConsoleHistoryCommand, serverConsoleUnsubscribeCommand, SERVER_COMMANDS, registerServerCommands, SUBSCRIPTION_TOPICS, subscriptionTopicSchema, SERVER_STATES, serverStateSchema, serverStatusChangedSchema, agentSubscribeBodySchema, agentMembersSetBodySchema, agentMembersRevokeBodySchema, auditEntrySchema, agentAuditListBodySchema, agentAuditListResultSchema, agentSubscribeCommand, agentUnsubscribeCommand, agentMembersSetCommand, agentMembersRevokeCommand, agentAuditListCommand, AGENT_COMMANDS, registerAgentCommands, BACKUP_ID_REGEX, MIN_BACKUP_INTERVAL_MINUTES, MAX_BACKUP_INTERVAL_MINUTES, MIN_BACKUP_RETENTION_COUNT, MAX_BACKUP_RETENTION_COUNT, backupIdSchema, backupDestinationKindSchema, BACKUP_UPLOAD_STATES, backupUploadStateSchema, serverBackupUploadEventSchema, pendingBackupUploadSchema, backupScheduleConfigSchema, backupLocalConfigSchema, s3BucketSchema, s3RegionSchema, s3PrefixSchema, backupS3ConfigSchema, backupTegraCloudConfigSchema, serverBackupConfigSetBodySchema, serverBackupCreateBodySchema, serverBackupListBodySchema, serverBackupDeleteBodySchema, serverBackupRestoreBodySchema, serverBackupConfigSetCommand, serverBackupConfigGetCommand, serverBackupCreateCommand, serverBackupListCommand, serverBackupDeleteCommand, serverBackupRestoreCommand, BACKUP_COMMANDS, registerBackupCommands, SERVER_ID_PATTERN, SHA256_HEX_PATTERN, fileEncodingSchema, sha256HexSchema, filesListCommand, filesStatCommand, filesReadCommand, filesWriteCommand, filesMkdirCommand, filesRenameCommand, filesCopyCommand, filesDeleteCommand, filesUploadBeginCommand, filesUploadPartCommand, filesUploadCommitCommand, filesUploadAbortCommand, filesDownloadBeginCommand, filesDownloadPartCommand, filesDownloadCloseCommand, filesDownloadCommand, filesZipCommand, filesUnzipCommand, FILES_COMMANDS, registerFilesCommands, hostInfoBodySchema, AGENT_FEATURES, hostInfoResultSchema, hostInfoCommand, HOST_COMMANDS, registerHostCommands, MODPACK_SOURCES, modpackSourceSchema, MODPACK_INSTALL_PHASES, modpackInstallPhaseSchema, MODPACK_INSTALL_JOB_STATES, modpackInstallJobStateSchema, MODPACK_INSTALL_ERROR_CODES, modpackInstallErrorCodeSchema, modpackInstallSkippedItemSchema, serverInstallModpackBodySchema, serverInstallModpackStatusBodySchema, serverInstallModpackCancelBodySchema, serverInstallModpackAcceptedEventSchema, serverInstallModpackProgressEventSchema, serverInstallModpackResultEventSchema, modpackInstallJobStatusSchema, serverInstallModpackStatusResultSchema, serverInstallModpackCommand, serverInstallModpackStatusCommand, serverInstallModpackCancelCommand, MODPACK_COMMANDS, registerModpackCommands, agentRevocationsSetCommand, PAIRING_COMMANDS, registerPairingCommands, SHA1_HEX_PATTERN, SHA512_HEX_PATTERN, sha1HexSchema, sha512HexSchema, modSourceSchema, modLayerSchema, modFileNameSchema, serverModEntrySchema, serverOriginSchema, serverOriginSyncStateSchema, modEnvironmentInfoSchema, originPlanModInputSchema, originPlanFileInputSchema, serverModsListBodySchema, serverModsInstallBodySchema, serverModsRemoveBodySchema, serverModsToggleBodySchema, serverModsReplaceBodySchema, serverModsIdentifyBodySchema, serverOriginPlanBodySchema, serverOriginApplyBodySchema, serverOriginUnlinkBodySchema, blobKeySchema, WORLD_NAME_REGEX, RESERVED_WORLD_NAMES, worldNameSchema, serverWorldImportBodySchema, serverDeployServerpackBodySchema, serverModsListCommand, serverModsInstallCommand, serverModsRemoveCommand, serverModsToggleCommand, serverModsReplaceCommand, serverModsIdentifyCommand, serverOriginPlanCommand, serverOriginApplyCommand, serverOriginUnlinkCommand, serverDeployServerpackCommand, serverWorldImportCommand, STATE_COMMANDS, registerStateCommands, PLAYIT_SECRET_KEY_REGEX, playitSecretKeySchema, tunnelPlayitSetKeyBodySchema, tunnelPlayitSetKeyCommand, tunnelPlayitStartCommand, tunnelPlayitStopCommand, tunnelPlayitStatusCommand, tunnelPlayitClaimBeginCommand, tunnelPlayitClaimStatusCommand, tunnelPlayitClaimCancelCommand, serverTunnelBodySchema, serverTunnelCreateBodySchema, serverTunnelGetCommand, serverTunnelCreateCommand, TUNNEL_COMMANDS, registerTunnelCommands, agentPingCommand, serverStartCommand, serverStopCommand, serverDeleteCommand, CORE_COMMANDS, registerCoreCommands, createCoreRegistry, PAIRING_CODE_LENGTH, PAIRING_SECRET_BYTES, DEFAULT_TRUST_GRANT_TTL_MS, MAX_TRUST_GRANT_TTL_MS, pairingCodeSchema, trustGrantSchema, generatePairingCode, generatePairingSecret, buildPairingFragment, parsePairingFragment, signTrustGrant, verifyTrustGrant, signRevocationList, verifyRevocationList, createInMemoryTrustContext }; diff --git a/lib/protocol/index.js b/lib/protocol/index.js index f78548d..3a0abbd 100644 --- a/lib/protocol/index.js +++ b/lib/protocol/index.js @@ -1,6 +1,7 @@ import { AGENT_AUTH_MAX_SKEW_MS, AGENT_COMMANDS, + AGENT_FEATURES, AGENT_HTTP_HEADER_AGENT, AGENT_HTTP_HEADER_SIG, AGENT_HTTP_HEADER_TS, @@ -36,6 +37,7 @@ import { MAX_CONSOLE_LINE_LENGTH, MAX_ELEVATED_SESSION_MS, MAX_GRANT_CLOCK_SKEW_MS, + MAX_GRANT_COMMANDS, MAX_GRANT_SERVERS, MAX_JVM_ARGS, MAX_MEMBERS, @@ -70,6 +72,9 @@ import { SUBSCRIPTION_TOPICS, TUNNEL_COMMANDS, WORLD_NAME_REGEX, + agentAuditListBodySchema, + agentAuditListCommand, + agentAuditListResultSchema, agentEventBodySchema, agentMembersRevokeBodySchema, agentMembersRevokeCommand, @@ -83,6 +88,7 @@ import { agentSubscribeBodySchema, agentSubscribeCommand, agentUnsubscribeCommand, + auditEntrySchema, backupDestinationKindSchema, backupIdSchema, backupLocalConfigSchema, @@ -141,6 +147,7 @@ import { modpackInstallPhaseSchema, modpackInstallSkippedItemSchema, modpackSourceSchema, + onBehalfOfSchema, openAgentEvent, openAgentMessage, openCommand, @@ -284,7 +291,7 @@ import { verifyTrustGrant, worldNameSchema, wrapEventBody -} from "../chunks/index-3yjqz9zv.js"; +} from "../chunks/index-b83z6s0k.js"; import"../chunks/index-g1frygvt.js"; export { wrapEventBody, @@ -430,6 +437,7 @@ export { openCommand, openAgentMessage, openAgentEvent, + onBehalfOfSchema, modpackSourceSchema, modpackInstallSkippedItemSchema, modpackInstallPhaseSchema, @@ -488,6 +496,7 @@ export { backupLocalConfigSchema, backupIdSchema, backupDestinationKindSchema, + auditEntrySchema, agentUnsubscribeCommand, agentSubscribeCommand, agentSubscribeBodySchema, @@ -501,6 +510,9 @@ export { agentMembersRevokeCommand, agentMembersRevokeBodySchema, agentEventBodySchema, + agentAuditListResultSchema, + agentAuditListCommand, + agentAuditListBodySchema, WORLD_NAME_REGEX, TUNNEL_COMMANDS, SUBSCRIPTION_TOPICS, @@ -535,6 +547,7 @@ export { MAX_MEMBERS, MAX_JVM_ARGS, MAX_GRANT_SERVERS, + MAX_GRANT_COMMANDS, MAX_GRANT_CLOCK_SKEW_MS, MAX_ELEVATED_SESSION_MS, MAX_CONSOLE_LINE_LENGTH, @@ -570,6 +583,7 @@ export { AGENT_HTTP_HEADER_TS, AGENT_HTTP_HEADER_SIG, AGENT_HTTP_HEADER_AGENT, + AGENT_FEATURES, AGENT_COMMANDS, AGENT_AUTH_MAX_SKEW_MS }; diff --git a/lib/types/protocol/command.d.ts b/lib/types/protocol/command.d.ts index 684eeda..bb9a189 100644 --- a/lib/types/protocol/command.d.ts +++ b/lib/types/protocol/command.d.ts @@ -1,7 +1,7 @@ import { type PublicKey, type SigningKeyPair } from "../crypto"; import type { CommandRegistry } from "./registry"; -import { type Role } from "./roles"; -import { type CommandHeader, type KeyId, type SessionCertificate, type SignedCommand } from "./schemas"; +import type { Role } from "./roles"; +import { type CommandHeader, type KeyId, type OnBehalfOf, type SessionCertificate, type SignedCommand } from "./schemas"; import type { TrustContext } from "./trust"; export declare const COMMAND_ID_BYTES = 16; export declare const DEFAULT_COMMAND_TTL_MS: number; @@ -22,6 +22,11 @@ export interface CreateSignedCommandParams { * Defaults to the account key. A session signer must use its own key. */ readonly replyTo?: PublicKey; + /** + * Who the command was issued for, when a bot acts for a person. It is inside + * the signed header, so the agent can record it without trusting the server. + */ + readonly onBehalfOf?: OnBehalfOf; } export interface OpenedCommand { readonly header: CommandHeader; @@ -35,6 +40,8 @@ export interface OpenedCommand { readonly sessionNotAfter?: number; /** Key from the command's `reply_to`, when present. Replies go here instead of the account key. */ readonly replyTo?: PublicKey; + /** Who the command was issued for, copied from the signed header. */ + readonly onBehalfOf?: OnBehalfOf; /** Role of the signing account on the command's server (`"*"` for agent commands). */ readonly role: Role; } diff --git a/lib/types/protocol/commands/agent.d.ts b/lib/types/protocol/commands/agent.d.ts index c42bd8c..d16056e 100644 --- a/lib/types/protocol/commands/agent.d.ts +++ b/lib/types/protocol/commands/agent.d.ts @@ -26,6 +26,11 @@ export declare const serverStatusChangedSchema: z.ZodObject<{ stopping: "stopping"; }>; at: z.ZodNumber; + players: z.ZodOptional>>; + motd: z.ZodOptional>; }, z.core.$strip>; export type ServerStatusChanged = z.infer; export declare const agentSubscribeBodySchema: z.ZodObject<{ @@ -49,6 +54,7 @@ export declare const agentMembersSetBodySchema: z.ZodObject<{ operator: "operator"; viewer: "viewer"; }>; + commands: z.ZodOptional>; issued_at: z.ZodNumber; expires_at: z.ZodOptional; sig: z.ZodString; @@ -60,6 +66,44 @@ export declare const agentMembersRevokeBodySchema: z.ZodObject<{ servers: z.ZodOptional>; }, z.core.$strict>; export type AgentMembersRevokeBody = z.infer; +export declare const auditEntrySchema: z.ZodObject<{ + at: z.ZodNumber; + type: z.ZodString; + server_id: z.ZodString; + account: z.ZodString; + ok: z.ZodBoolean; + error_code: z.ZodOptional; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; +}, z.core.$strict>; +export type AuditEntry = z.infer; +export declare const agentAuditListBodySchema: z.ZodObject<{ + server_id: z.ZodOptional; + before: z.ZodOptional; + limit: z.ZodDefault; +}, z.core.$strict>; +export type AgentAuditListBody = z.infer; +export declare const agentAuditListResultSchema: z.ZodObject<{ + entries: z.ZodArray; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; + }, z.core.$strict>>; +}, z.core.$strict>; +export type AgentAuditListResult = z.infer; export declare const agentSubscribeCommand: import("..").CommandDefinition<"agent.subscribe", { topics: ("server.backup" | "server.modpack" | "server.status")[]; }>; @@ -74,6 +118,7 @@ export declare const agentMembersSetCommand: import("..").CommandDefinition<"age agent: string; servers: "*" | string[]; role: "admin" | "editor" | "operator" | "viewer"; + commands?: string[] | undefined; issued_at: number; expires_at?: number | undefined; sig: string; @@ -83,6 +128,11 @@ export declare const agentMembersRevokeCommand: import("..").CommandDefinition<" account: string; servers?: string[] | undefined; }>; +export declare const agentAuditListCommand: import("..").CommandDefinition<"agent.audit.list", { + server_id?: string | undefined; + before?: number | undefined; + limit: number; +}>; export declare const AGENT_COMMANDS: readonly [import("..").CommandDefinition<"agent.subscribe", { topics: ("server.backup" | "server.modpack" | "server.status")[]; }>, import("..").CommandDefinition<"agent.unsubscribe", { @@ -95,6 +145,7 @@ export declare const AGENT_COMMANDS: readonly [import("..").CommandDefinition<"a agent: string; servers: "*" | string[]; role: "admin" | "editor" | "operator" | "viewer"; + commands?: string[] | undefined; issued_at: number; expires_at?: number | undefined; sig: string; @@ -102,5 +153,9 @@ export declare const AGENT_COMMANDS: readonly [import("..").CommandDefinition<"a }>, import("..").CommandDefinition<"agent.members.revoke", { account: string; servers?: string[] | undefined; +}>, import("..").CommandDefinition<"agent.audit.list", { + server_id?: string | undefined; + before?: number | undefined; + limit: number; }>]; export declare function registerAgentCommands(registry: CommandRegistry): CommandRegistry; diff --git a/lib/types/protocol/commands/host.d.ts b/lib/types/protocol/commands/host.d.ts index be63348..5c0a5fd 100644 --- a/lib/types/protocol/commands/host.d.ts +++ b/lib/types/protocol/commands/host.d.ts @@ -2,12 +2,15 @@ import { z } from "zod"; import { type CommandRegistry } from "../registry"; export declare const hostInfoBodySchema: z.ZodObject<{}, z.core.$strict>; export type HostInfoBody = z.infer; +/** Capabilities this agent build announces in `host.info`, so clients can adapt. */ +export declare const AGENT_FEATURES: readonly ["grant_commands", "status_players", "audit"]; export declare const hostInfoResultSchema: z.ZodObject<{ memory_total_mb: z.ZodNumber; memory_available_mb: z.ZodNumber; cpu_count: z.ZodNumber; reserved_memory_mb: z.ZodNumber; addresses: z.ZodOptional>; + features: z.ZodOptional>; }, z.core.$strip>; export type HostInfoResult = z.infer; export declare const hostInfoCommand: import("..").CommandDefinition<"host.info", Record>; diff --git a/lib/types/protocol/errors.d.ts b/lib/types/protocol/errors.d.ts index 5ac30b9..6526c23 100644 --- a/lib/types/protocol/errors.d.ts +++ b/lib/types/protocol/errors.d.ts @@ -1,4 +1,4 @@ -export type ProtocolErrorCode = "invalid_format" | "unsupported_version" | "wrong_agent" | "wrong_recipient" | "expired" | "not_yet_valid" | "ttl_too_long" | "untrusted_signer" | "bad_signature" | "session_invalid" | "session_revoked" | "replayed" | "unknown_command" | "invalid_body" | "elevation_required" | "elevation_invalid" | "account_key_required" | "decrypt_failed" | "insufficient_role" | "too_many_subscribers" | "role_grant_invalid" | "auth_invalid" | "request_invalid" | "grant_invalid" | "grant_wrong_agent" | "grant_expired" | "grant_bad_signature" | "grant_proof_required" | "grant_bad_proof" | "revocation_stale" | "revocation_not_superset" | "insufficient_memory" | "eula_not_accepted" | "server_not_found" | "server_already_exists" | "server_running" | "server_stopped" | "invalid_jvm_args" | "download_failed" | "hash_mismatch" | "systemd_error" | "perms_unavailable" | "origin_locked" | "plan_not_found" | "plan_expired" | "plan_stale" | "mod_not_found" | "mod_conflict" | "mod_already_exists" | "backup_not_found" | "backup_failed" | "backup_config_invalid" | "tunnel_not_configured" | "tunnel_already_running" | "tunnel_not_running" | "tunnel_failed" | "tunnel_not_managed" | "tunnel_api_failed" | "port_in_use" | "pack_unavailable" | "runtime_mismatch" | "host_not_allowed" | "too_large" | "install_in_progress" | "api_unavailable" | "io_error" | "cancelled"; +export type ProtocolErrorCode = "invalid_format" | "unsupported_version" | "wrong_agent" | "wrong_recipient" | "expired" | "not_yet_valid" | "ttl_too_long" | "untrusted_signer" | "bad_signature" | "session_invalid" | "session_revoked" | "replayed" | "unknown_command" | "invalid_body" | "elevation_required" | "elevation_invalid" | "account_key_required" | "decrypt_failed" | "insufficient_role" | "command_not_granted" | "rate_limited" | "too_many_subscribers" | "role_grant_invalid" | "auth_invalid" | "request_invalid" | "grant_invalid" | "grant_wrong_agent" | "grant_expired" | "grant_bad_signature" | "grant_proof_required" | "grant_bad_proof" | "revocation_stale" | "revocation_not_superset" | "insufficient_memory" | "eula_not_accepted" | "server_not_found" | "server_already_exists" | "server_running" | "server_stopped" | "invalid_jvm_args" | "download_failed" | "hash_mismatch" | "systemd_error" | "perms_unavailable" | "origin_locked" | "plan_not_found" | "plan_expired" | "plan_stale" | "mod_not_found" | "mod_conflict" | "mod_already_exists" | "backup_not_found" | "backup_failed" | "backup_config_invalid" | "tunnel_not_configured" | "tunnel_already_running" | "tunnel_not_running" | "tunnel_failed" | "tunnel_not_managed" | "tunnel_api_failed" | "port_in_use" | "pack_unavailable" | "runtime_mismatch" | "host_not_allowed" | "too_large" | "install_in_progress" | "api_unavailable" | "io_error" | "cancelled"; export declare class ProtocolError extends Error { readonly code: ProtocolErrorCode; constructor(code: ProtocolErrorCode, message: string); diff --git a/lib/types/protocol/index.d.ts b/lib/types/protocol/index.d.ts index 1393618..ddd0477 100644 --- a/lib/types/protocol/index.d.ts +++ b/lib/types/protocol/index.d.ts @@ -1,11 +1,11 @@ export { AGENT_AUTH_MAX_SKEW_MS, AGENT_HTTP_HEADER_AGENT, AGENT_HTTP_HEADER_SIG, AGENT_HTTP_HEADER_TS, AGENT_HTTP_MAX_SKEW_MS, type AgentRequestBody, type AuthFrame, createHelloFrame, generateAgentNonce, type HelloFrame, type SignAgentRequestParams, signAgentAuth, signAgentRequest, type VerifyAgentAuthOptions, type VerifyAgentRequestParams, verifyAgentAuth, verifyAgentRequest, } from "./agent-auth"; export { type AgentEventBody, agentEventBodySchema, type OpenedAgentEvent, type OpenedAgentMessage, openAgentEvent, openAgentMessage, type SealAgentMessageParams, sealAgentMessage, wrapEventBody, } from "./agent-message"; export { COMMAND_ID_BYTES, type CreateSignedCommandParams, createSignedCommand, DEFAULT_COMMAND_TTL_MS, MAX_CLOCK_SKEW_MS, MAX_COMMAND_TTL_MS, type OpenedCommand, openCommand, } from "./command"; -export { AGENT_COMMANDS, type AgentMembersRevokeBody, type AgentMembersSetBody, type AgentSubscribeBody, agentMembersRevokeBodySchema, agentMembersRevokeCommand, agentMembersSetBodySchema, agentMembersSetCommand, agentSubscribeBodySchema, agentSubscribeCommand, agentUnsubscribeCommand, registerAgentCommands, SERVER_STATES, type ServerState, type ServerStatusChanged, SUBSCRIPTION_TOPICS, type SubscriptionTopic, serverStateSchema, serverStatusChangedSchema, subscriptionTopicSchema, } from "./commands/agent"; +export { AGENT_COMMANDS, type AgentAuditListBody, type AgentAuditListResult, type AgentMembersRevokeBody, type AgentMembersSetBody, type AgentSubscribeBody, type AuditEntry, agentAuditListBodySchema, agentAuditListCommand, agentAuditListResultSchema, agentMembersRevokeBodySchema, agentMembersRevokeCommand, agentMembersSetBodySchema, agentMembersSetCommand, agentSubscribeBodySchema, agentSubscribeCommand, agentUnsubscribeCommand, auditEntrySchema, registerAgentCommands, SERVER_STATES, type ServerState, type ServerStatusChanged, SUBSCRIPTION_TOPICS, type SubscriptionTopic, serverStateSchema, serverStatusChangedSchema, subscriptionTopicSchema, } from "./commands/agent"; export { BACKUP_COMMANDS, BACKUP_ID_REGEX, BACKUP_UPLOAD_STATES, type BackupDestinationKind, type BackupLocalConfig, type BackupS3ConfigInput, type BackupScheduleConfig, type BackupTegraCloudConfig, type BackupUploadState, backupDestinationKindSchema, backupIdSchema, backupLocalConfigSchema, backupS3ConfigSchema, backupScheduleConfigSchema, backupTegraCloudConfigSchema, backupUploadStateSchema, MAX_BACKUP_INTERVAL_MINUTES, MAX_BACKUP_RETENTION_COUNT, MIN_BACKUP_INTERVAL_MINUTES, MIN_BACKUP_RETENTION_COUNT, type PendingBackupUpload, pendingBackupUploadSchema, registerBackupCommands, type ServerBackupConfigSetBody, type ServerBackupCreateBody, type ServerBackupDeleteBody, type ServerBackupListBody, type ServerBackupRestoreBody, type ServerBackupUploadEvent, s3BucketSchema, s3PrefixSchema, s3RegionSchema, serverBackupConfigGetCommand, serverBackupConfigSetBodySchema, serverBackupConfigSetCommand, serverBackupCreateBodySchema, serverBackupCreateCommand, serverBackupDeleteBodySchema, serverBackupDeleteCommand, serverBackupListBodySchema, serverBackupListCommand, serverBackupRestoreBodySchema, serverBackupRestoreCommand, serverBackupUploadEventSchema, } from "./commands/backup"; export { agentPingCommand, CORE_COMMANDS, createCoreRegistry, registerCoreCommands, serverDeleteCommand, serverStartCommand, serverStopCommand, } from "./commands/core"; export { FILES_COMMANDS, fileEncodingSchema, filesCopyCommand, filesDeleteCommand, filesDownloadBeginCommand, filesDownloadCloseCommand, filesDownloadCommand, filesDownloadPartCommand, filesListCommand, filesMkdirCommand, filesReadCommand, filesRenameCommand, filesStatCommand, filesUnzipCommand, filesUploadAbortCommand, filesUploadBeginCommand, filesUploadCommitCommand, filesUploadPartCommand, filesWriteCommand, filesZipCommand, registerFilesCommands, SERVER_ID_PATTERN, SHA256_HEX_PATTERN, sha256HexSchema, } from "./commands/files"; -export { HOST_COMMANDS, type HostInfoBody, type HostInfoResult, hostInfoBodySchema, hostInfoCommand, hostInfoResultSchema, registerHostCommands, } from "./commands/host"; +export { AGENT_FEATURES, HOST_COMMANDS, type HostInfoBody, type HostInfoResult, hostInfoBodySchema, hostInfoCommand, hostInfoResultSchema, registerHostCommands, } from "./commands/host"; export { MODPACK_COMMANDS, MODPACK_INSTALL_ERROR_CODES, MODPACK_INSTALL_JOB_STATES, MODPACK_INSTALL_PHASES, MODPACK_SOURCES, type ModpackInstallErrorCode, type ModpackInstallJobState, type ModpackInstallJobStatus, type ModpackInstallPhase, type ModpackInstallSkippedItem, type ModpackSource, modpackInstallErrorCodeSchema, modpackInstallJobStateSchema, modpackInstallJobStatusSchema, modpackInstallPhaseSchema, modpackInstallSkippedItemSchema, modpackSourceSchema, registerModpackCommands, type ServerInstallModpackAcceptedEvent, type ServerInstallModpackBody, type ServerInstallModpackCancelBody, type ServerInstallModpackProgressEvent, type ServerInstallModpackResultEvent, type ServerInstallModpackStatusBody, type ServerInstallModpackStatusResult, serverInstallModpackAcceptedEventSchema, serverInstallModpackBodySchema, serverInstallModpackCancelBodySchema, serverInstallModpackCancelCommand, serverInstallModpackCommand, serverInstallModpackProgressEventSchema, serverInstallModpackResultEventSchema, serverInstallModpackStatusBodySchema, serverInstallModpackStatusCommand, serverInstallModpackStatusResultSchema, } from "./commands/modpack"; export { agentRevocationsSetCommand, PAIRING_COMMANDS, registerPairingCommands, } from "./commands/pairing"; export { consoleLineSchema, DEFAULT_SERVER_PORT, DEFAULT_START_ON_BOOT, loaderVersionSchema, MAX_CONSOLE_LINE_LENGTH, MAX_JVM_ARGS, MAX_SERVER_MEMORY_MB, MIN_SERVER_MEMORY_MB, minecraftVersionSchema, registerServerCommands, SERVER_COMMANDS, SERVER_ID_REGEX, type ServerChangeRuntimeBody, type ServerConsoleSendBody, type ServerConsoleSubscribeBody, type ServerCreateBody, type ServerLoader, type ServerStartOnBoot, type ServerStatsBody, type ServerStatsResult, type ServerUpdateSettingsBody, serverChangeRuntimeBodySchema, serverChangeRuntimeCommand, serverConsoleHistoryBodySchema, serverConsoleHistoryCommand, serverConsoleSendBodySchema, serverConsoleSendCommand, serverConsoleSubscribeBodySchema, serverConsoleSubscribeCommand, serverConsoleUnsubscribeCommand, serverCreateBodySchema, serverCreateCommand, serverIdSchema, serverListCommand, serverLoaderSchema, serverMemoryMbSchema, serverPortSchema, serverRestartCommand, serverStartOnBootSchema, serverStatsBodySchema, serverStatsCommand, serverStatsResultSchema, serverStatusCommand, serverUpdateSettingsBodySchema, serverUpdateSettingsCommand, } from "./commands/server"; @@ -16,7 +16,7 @@ export { ProtocolError, type ProtocolErrorCode } from "./errors"; export { type BuildPairingFragmentParams, buildPairingFragment, DEFAULT_TRUST_GRANT_TTL_MS, generatePairingCode, generatePairingSecret, MAX_TRUST_GRANT_TTL_MS, PAIRING_CODE_LENGTH, PAIRING_SECRET_BYTES, type PairingFragment, pairingCodeSchema, parsePairingFragment, type SignTrustGrantParams, signTrustGrant, type TrustGrant, trustGrantSchema, type VerifiedTrustGrant, type VerifyTrustGrantOptions, verifyTrustGrant, } from "./pairing"; export { type CommandDefinition, type CommandLevel, CommandRegistry, defineCommand, } from "./registry"; export { type SignRevocationListParams, signRevocationList, verifyRevocationList, } from "./revocation"; -export { ALL_SERVERS, GRANTABLE_ROLES, type GrantableRole, grantableRoleSchema, MAX_GRANT_CLOCK_SKEW_MS, MAX_GRANT_SERVERS, MAX_MEMBERS, type MemberEntry, maxRole, memberEntrySchema, ROLE_LEVEL, ROLES, type Role, type RoleGrant, RoleTable, roleAtLeast, roleGrantSchema, roleSchema, type SignRoleGrantParams, signRoleGrant, type VerifiedRoleGrant, type VerifyRoleGrantOptions, verifyRoleGrant, } from "./roles"; -export { AGENT_NONCE_BYTES, type AgentMessage, type AgentMessageHeader, agentMessageHeaderSchema, agentMessageSchema, agentNonceSchema, base64UrlSchema, type CommandHeader, commandHeaderSchema, type KeyId, keyIdSchema, type RevocationList, revocationListSchema, type SessionCertificate, type SignedCommand, sessionCertificateSchema, signedCommandSchema, type TransportFrame, transportAckFrameSchema, transportAuthFrameSchema, transportCommandFrameSchema, transportEventFrameSchema, transportFrameSchema, transportHelloFrameSchema, transportPingFrameSchema, } from "./schemas"; +export { ALL_SERVERS, GRANTABLE_ROLES, type GrantableRole, grantableRoleSchema, MAX_GRANT_CLOCK_SKEW_MS, MAX_GRANT_COMMANDS, MAX_GRANT_SERVERS, MAX_MEMBERS, type MemberEntry, maxRole, memberEntrySchema, ROLE_LEVEL, ROLES, type Role, type RoleGrant, RoleTable, roleAtLeast, roleGrantSchema, roleSchema, type SignRoleGrantParams, signRoleGrant, type VerifiedRoleGrant, type VerifyRoleGrantOptions, verifyRoleGrant, } from "./roles"; +export { AGENT_NONCE_BYTES, type AgentMessage, type AgentMessageHeader, agentMessageHeaderSchema, agentMessageSchema, agentNonceSchema, base64UrlSchema, type CommandHeader, commandHeaderSchema, type KeyId, keyIdSchema, type OnBehalfOf, onBehalfOfSchema, type RevocationList, revocationListSchema, type SessionCertificate, type SignedCommand, sessionCertificateSchema, signedCommandSchema, type TransportFrame, transportAckFrameSchema, transportAuthFrameSchema, transportCommandFrameSchema, transportEventFrameSchema, transportFrameSchema, transportHelloFrameSchema, transportPingFrameSchema, } from "./schemas"; export { MAX_ELEVATED_SESSION_MS, type SignSessionCertificateParams, signSessionCertificate, type VerifiedSessionCertificate, verifySessionCertificate, } from "./session"; export { createInMemoryTrustContext, type InMemoryTrustContext, type InMemoryTrustContextOptions, type MemberStore, type TrustContext, } from "./trust"; diff --git a/lib/types/protocol/roles.d.ts b/lib/types/protocol/roles.d.ts index 01d763d..36cd1ea 100644 --- a/lib/types/protocol/roles.d.ts +++ b/lib/types/protocol/roles.d.ts @@ -23,6 +23,7 @@ export declare function roleAtLeast(role: Role | null | undefined, minimum: Role export declare function maxRole(a: T | null, b: T | null): T | null; export declare const ALL_SERVERS: "*"; export declare const MAX_GRANT_SERVERS = 256; +export declare const MAX_GRANT_COMMANDS = 32; export declare const MAX_MEMBERS = 64; export declare const roleGrantSchema: z.ZodObject<{ v: z.ZodLiteral<1>; @@ -36,6 +37,7 @@ export declare const roleGrantSchema: z.ZodObject<{ operator: "operator"; viewer: "viewer"; }>; + commands: z.ZodOptional>; issued_at: z.ZodNumber; expires_at: z.ZodOptional; sig: z.ZodString; @@ -48,6 +50,8 @@ export interface SignRoleGrantParams { readonly agent: KeyId; readonly servers: readonly string[] | typeof ALL_SERVERS; readonly role: GrantableRole; + /** Command types this key may run, on top of the role's own permissions. */ + readonly commands?: readonly string[]; readonly issuedAt: number; readonly expiresAt?: number; } @@ -74,6 +78,7 @@ export declare const memberEntrySchema: z.ZodObject<{ viewer: "viewer"; }>; servers: z.ZodUnion, z.ZodArray]>; + commands: z.ZodOptional>; issued_at: z.ZodNumber; expires_at: z.ZodOptional; }, z.core.$strict>; @@ -95,6 +100,14 @@ export declare class RoleTable { * return is filtered per server). */ roleFor(account: KeyId, serverId: string, now: number): GrantableRole | null; + /** + * Whether `account` may run a command of `type` on `serverId` at `minRole`. + * A grant that lists `commands` only allows those types, so the answer is the + * intersection of the role's permissions and the grant's command list. + */ + commandAllowed(account: KeyId, serverId: string, type: string, minRole: Role, now: number): boolean; + /** True when any active grant of `account` lists the commands it may run. */ + isRestricted(account: KeyId, now: number): boolean; set(entry: MemberEntry): void; /** * Removes grants of `account`. Without `servers`, all of them. With diff --git a/lib/types/protocol/schemas.d.ts b/lib/types/protocol/schemas.d.ts index 4ea3282..88651a4 100644 --- a/lib/types/protocol/schemas.d.ts +++ b/lib/types/protocol/schemas.d.ts @@ -13,6 +13,13 @@ export declare const sessionCertificateSchema: z.ZodObject<{ sig: z.ZodString; }, z.core.$strip>; export type SessionCertificate = z.infer; +export declare const onBehalfOfSchema: z.ZodObject<{ + via: z.ZodLiteral<"discord">; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; +}, z.core.$strict>; +export type OnBehalfOf = z.infer; export declare const commandHeaderSchema: z.ZodObject<{ v: z.ZodLiteral<1>; id: z.ZodString; @@ -23,6 +30,12 @@ export declare const commandHeaderSchema: z.ZodObject<{ expires_at: z.ZodNumber; counter: z.ZodNumber; reply_to: z.ZodOptional; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; }, z.core.$strip>; export type CommandHeader = z.infer; export declare const signedCommandSchema: z.ZodObject<{ @@ -36,6 +49,12 @@ export declare const signedCommandSchema: z.ZodObject<{ expires_at: z.ZodNumber; counter: z.ZodNumber; reply_to: z.ZodOptional; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; }, z.core.$strip>; payload: z.ZodString; session: z.ZodOptional; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; }, z.core.$strip>; payload: z.ZodString; session: z.ZodOptional; + on_behalf_of: z.ZodOptional; + user_id: z.ZodString; + display_name: z.ZodString; + guild_id: z.ZodString; + }, z.core.$strict>>; }, z.core.$strip>; payload: z.ZodString; session: z.ZodOptional