borgmcp-server 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +70 -22
  2. package/THIRD_PARTY_NOTICES.md +1 -0
  3. package/dist/cli.js +62 -11
  4. package/dist/cli.js.map +1 -1
  5. package/dist/coordination-api.d.ts +3 -1
  6. package/dist/coordination-api.js +476 -78
  7. package/dist/coordination-api.js.map +1 -1
  8. package/dist/credentials.d.ts +13 -7
  9. package/dist/credentials.js +77 -15
  10. package/dist/credentials.js.map +1 -1
  11. package/dist/debug-log.d.ts +76 -0
  12. package/dist/debug-log.js +124 -0
  13. package/dist/debug-log.js.map +1 -0
  14. package/dist/enrollment.d.ts +3 -11
  15. package/dist/enrollment.js +21 -60
  16. package/dist/enrollment.js.map +1 -1
  17. package/dist/https-server.d.ts +5 -20
  18. package/dist/https-server.js +108 -50
  19. package/dist/https-server.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/message-taxonomy.d.ts +38 -0
  22. package/dist/message-taxonomy.js +218 -0
  23. package/dist/message-taxonomy.js.map +1 -0
  24. package/dist/migrations.d.ts +4 -0
  25. package/dist/migrations.js +99 -0
  26. package/dist/migrations.js.map +1 -1
  27. package/dist/operator-error.d.ts +2 -1
  28. package/dist/operator-error.js +23 -5
  29. package/dist/operator-error.js.map +1 -1
  30. package/dist/role-section.d.ts +14 -0
  31. package/dist/role-section.js +87 -0
  32. package/dist/role-section.js.map +1 -0
  33. package/dist/service.d.ts +14 -4
  34. package/dist/service.js +243 -25
  35. package/dist/service.js.map +1 -1
  36. package/dist/start-options.d.ts +5 -1
  37. package/dist/start-options.js +17 -3
  38. package/dist/start-options.js.map +1 -1
  39. package/dist/store.d.ts +106 -8
  40. package/dist/store.js +772 -120
  41. package/dist/store.js.map +1 -1
  42. package/npm-shrinkwrap.json +6 -7
  43. package/package.json +2 -2
  44. package/src/cli.ts +61 -11
  45. package/src/coordination-api.ts +490 -72
  46. package/src/credentials.ts +103 -19
  47. package/src/debug-log.ts +165 -0
  48. package/src/enrollment.ts +32 -78
  49. package/src/https-server.ts +113 -78
  50. package/src/index.ts +1 -1
  51. package/src/message-taxonomy.ts +284 -0
  52. package/src/migrations.ts +102 -0
  53. package/src/operator-error.ts +40 -6
  54. package/src/role-section.ts +108 -0
  55. package/src/service.ts +268 -27
  56. package/src/start-options.ts +21 -4
  57. package/src/store.ts +887 -142
  58. package/dist/protocol-draft.d.ts +0 -2
  59. package/dist/protocol-draft.js +0 -31
  60. package/dist/protocol-draft.js.map +0 -1
  61. package/src/protocol-draft.ts +0 -32
package/src/migrations.ts CHANGED
@@ -7,6 +7,13 @@ export interface Migration {
7
7
  readonly sql: string;
8
8
  }
9
9
 
10
+ export class MigrationCompatibilityError extends Error {
11
+ constructor() {
12
+ super("Database migrations do not exactly match this server version.");
13
+ this.name = "MigrationCompatibilityError";
14
+ }
15
+ }
16
+
10
17
  export const STORE_MIGRATIONS: readonly Migration[] = Object.freeze([
11
18
  {
12
19
  version: 1,
@@ -303,6 +310,74 @@ export const STORE_MIGRATIONS: readonly Migration[] = Object.freeze([
303
310
  ON seat_attach_bindings (drone_id, client_id, cube_id);
304
311
  `,
305
312
  },
313
+ {
314
+ version: 7,
315
+ name: "role_management_foundation",
316
+ sql: `
317
+ ALTER TABLE roles ADD COLUMN is_mandatory INTEGER NOT NULL DEFAULT 0
318
+ CHECK (is_mandatory IN (0, 1));
319
+ ALTER TABLE roles ADD COLUMN can_broadcast INTEGER NOT NULL DEFAULT 0
320
+ CHECK (can_broadcast IN (0, 1));
321
+ ALTER TABLE roles ADD COLUMN receives_all_direct INTEGER NOT NULL DEFAULT 0
322
+ CHECK (receives_all_direct IN (0, 1));
323
+
324
+ CREATE UNIQUE INDEX roles_one_default_per_cube_idx
325
+ ON roles (cube_id) WHERE is_default = 1;
326
+ `,
327
+ },
328
+ {
329
+ version: 8,
330
+ name: "cube_scoped_invitations",
331
+ sql: `
332
+ ALTER TABLE enrollment_invitations ADD COLUMN cube_id TEXT;
333
+ ALTER TABLE enrollment_invitations ADD COLUMN access TEXT
334
+ CHECK (access IS NULL OR access IN ('read', 'write', 'manage'));
335
+
336
+ CREATE TRIGGER enrollment_invitations_scope_insert
337
+ BEFORE INSERT ON enrollment_invitations
338
+ WHEN (NEW.cube_id IS NULL) <> (NEW.access IS NULL)
339
+ OR (NEW.cube_id IS NOT NULL AND NEW.purpose <> 'client')
340
+ BEGIN
341
+ SELECT RAISE(ABORT, 'invalid invitation cube scope');
342
+ END;
343
+
344
+ CREATE TRIGGER enrollment_invitations_scope_update
345
+ BEFORE UPDATE OF cube_id, access, purpose ON enrollment_invitations
346
+ WHEN (NEW.cube_id IS NULL) <> (NEW.access IS NULL)
347
+ OR (NEW.cube_id IS NOT NULL AND NEW.purpose <> 'client')
348
+ BEGIN
349
+ SELECT RAISE(ABORT, 'invalid invitation cube scope');
350
+ END;
351
+ `,
352
+ },
353
+ {
354
+ version: 9,
355
+ name: "digest_correlated_seat_attach",
356
+ sql: `
357
+ DROP TABLE seat_attach_bindings;
358
+ DROP INDEX drones_client_retry_key_idx;
359
+ ALTER TABLE drones DROP COLUMN retry_key;
360
+ ALTER TABLE drones DROP COLUMN attach_generation;
361
+ `,
362
+ },
363
+ {
364
+ version: 10,
365
+ name: "cube_message_taxonomy",
366
+ sql: "ALTER TABLE cubes ADD COLUMN message_taxonomy TEXT;",
367
+ },
368
+ {
369
+ version: 11,
370
+ name: "fleet_liveness",
371
+ sql: `
372
+ CREATE INDEX activity_log_drone_post_idx
373
+ ON activity_log (cube_id, drone_id, created_at, id) WHERE drone_id IS NOT NULL;
374
+ CREATE TABLE silent_seat_ping_state (
375
+ drone_id TEXT PRIMARY KEY REFERENCES drones(id) ON DELETE CASCADE,
376
+ attempts INTEGER NOT NULL CHECK (attempts BETWEEN 1 AND 3),
377
+ last_ping_at TEXT NOT NULL
378
+ ) STRICT;
379
+ `,
380
+ },
306
381
  ]);
307
382
 
308
383
  interface AppliedMigrationRow {
@@ -366,6 +441,33 @@ export function applyMigrations(
366
441
  }
367
442
  }
368
443
 
444
+ export function assertMigrationsCurrent(
445
+ database: DatabaseSync,
446
+ migrations: readonly Migration[] = STORE_MIGRATIONS,
447
+ ): void {
448
+ validateMigrationOrder(migrations);
449
+ let rows: Record<string, unknown>[];
450
+ try {
451
+ rows = database.prepare(
452
+ "SELECT version, name, checksum FROM schema_migrations ORDER BY version",
453
+ ).all();
454
+ } catch {
455
+ throw new MigrationCompatibilityError();
456
+ }
457
+ if (rows.length !== migrations.length) throw new MigrationCompatibilityError();
458
+ for (let index = 0; index < migrations.length; index += 1) {
459
+ let applied: AppliedMigrationRow;
460
+ try {
461
+ applied = appliedMigrationRow(rows[index]!);
462
+ } catch {
463
+ throw new MigrationCompatibilityError();
464
+ }
465
+ const expected = migrations[index]!;
466
+ if (applied.version !== expected.version || applied.name !== expected.name ||
467
+ applied.checksum !== checksum(expected)) throw new MigrationCompatibilityError();
468
+ }
469
+ }
470
+
369
471
  function validateMigrationOrder(migrations: readonly Migration[]): void {
370
472
  migrations.forEach((migration, index) => {
371
473
  if (migration.version !== index + 1 || migration.name.length === 0 || migration.sql.length === 0) {
@@ -5,6 +5,9 @@ export type OperatorErrorCode =
5
5
  | "START_HOST_MISSING"
6
6
  | "START_PORT_MISSING"
7
7
  | "START_PORT_INVALID"
8
+ | "START_LOG_LEVEL_DUPLICATE"
9
+ | "START_LOG_LEVEL_MISSING"
10
+ | "START_LOG_LEVEL_INVALID"
8
11
  | "START_OPTION_UNKNOWN"
9
12
  | "BIND_PORT_INVALID"
10
13
  | "BIND_HOST_INVALID"
@@ -13,6 +16,7 @@ export type OperatorErrorCode =
13
16
  | "BIND_LAN_CONSENT"
14
17
  | "SERVER_FILES_MISSING"
15
18
  | "DATA_PATH_SYMLINK"
19
+ | "INSTALLATION_EXISTS"
16
20
  | "LAN_CA_KEY_ONLINE"
17
21
  | "RUNTIME_ACTIVE"
18
22
  | "RUNTIME_LOCK_UNSAFE"
@@ -23,7 +27,13 @@ export type OperatorErrorCode =
23
27
  | "DISK_RESERVE_INVALID"
24
28
  | "CLIENT_NOT_FOUND"
25
29
  | "GRANT_NOT_FOUND"
26
- | "RECOVERY_INVALID";
30
+ | "RECOVERY_INVALID"
31
+ | "INVITATION_BUSY"
32
+ | "INVITATION_CONTENTION"
33
+ | "INVITATION_SCHEMA_MISMATCH"
34
+ | "INVITATION_CUBE_NOT_FOUND"
35
+ | "INVITATION_CUBE_SELECTOR_INVALID"
36
+ | "INVITATION_CUBE_AMBIGUOUS";
27
37
 
28
38
  const publicMessages: Readonly<Record<OperatorErrorCode, string>> = Object.freeze({
29
39
  START_LAN_DUPLICATE: "Provide --lan only once.",
@@ -32,6 +42,9 @@ const publicMessages: Readonly<Record<OperatorErrorCode, string>> = Object.freez
32
42
  START_HOST_MISSING: "Provide an IP address after --host.",
33
43
  START_PORT_MISSING: "Provide a port number after --port.",
34
44
  START_PORT_INVALID: "Provide --port as an integer from 0 to 65535.",
45
+ START_LOG_LEVEL_DUPLICATE: "Provide --log-level only once.",
46
+ START_LOG_LEVEL_MISSING: "Provide debug after --log-level.",
47
+ START_LOG_LEVEL_INVALID: "Use --log-level debug or omit the option.",
35
48
  START_OPTION_UNKNOWN: "Use only documented start options; run borg-mcp-server help.",
36
49
  BIND_PORT_INVALID: "Configure the listen port as an integer from 0 to 65535.",
37
50
  BIND_HOST_INVALID: "Configure --host as an explicit IP address.",
@@ -40,8 +53,9 @@ const publicMessages: Readonly<Record<OperatorErrorCode, string>> = Object.freez
40
53
  BIND_LAN_CONSENT: "Add --lan to consent to this private-LAN start.",
41
54
  SERVER_FILES_MISSING: "Configure BORG_SERVER_DATA_DIR or the required TLS file variables.",
42
55
  DATA_PATH_SYMLINK: "Choose a BORG_SERVER_DATA_DIR path that contains no symbolic links.",
56
+ INSTALLATION_EXISTS: "An installation already exists in BORG_SERVER_DATA_DIR. To destroy and recreate it, stop the server and run borg-mcp-server setup --reinitialize.",
43
57
  LAN_CA_KEY_ONLINE: "Move ca.key out of the runtime data directory before private-LAN startup.",
44
- RUNTIME_ACTIVE: "Stop the server before running offline client administration.",
58
+ RUNTIME_ACTIVE: "Stop the server before running setup or offline administration.",
45
59
  RUNTIME_LOCK_UNSAFE: "Ensure runtime.lock is a private regular file before retrying.",
46
60
  RUNTIME_LOCK_INVALID: "Confirm the server is stopped, then remove the invalid runtime.lock.",
47
61
  RUNTIME_LOCK_STALE: "Confirm the recorded server process is stopped, then remove runtime.lock.",
@@ -51,22 +65,30 @@ const publicMessages: Readonly<Record<OperatorErrorCode, string>> = Object.freez
51
65
  CLIENT_NOT_FOUND: "Provide an existing active client ID.",
52
66
  GRANT_NOT_FOUND: "Provide an existing client cube grant.",
53
67
  RECOVERY_INVALID: "Provide the active recovery credential through the private prompt.",
68
+ INVITATION_BUSY: "Confirm no invitation or offline administration command is running, then remove invitation-mint.lock.",
69
+ INVITATION_CONTENTION: "Retry invitation minting after the current server database write completes.",
70
+ INVITATION_SCHEMA_MISMATCH: "Invitation minting is unavailable while a server with an incompatible schema is running. Stop the server and rerun this command, or use the CLI version that matches the running server.",
71
+ INVITATION_CUBE_NOT_FOUND: "Provide an existing cube name or full cube ID.",
72
+ INVITATION_CUBE_SELECTOR_INVALID: "Provide a full canonical cube UUID or an exact case-sensitive cube name.",
73
+ INVITATION_CUBE_AMBIGUOUS: "Cube name is ambiguous. Rerun with the full cube ID.",
54
74
  });
55
75
 
56
76
  const operatorErrorCodes = new WeakMap<object, OperatorErrorCode>();
77
+ const operatorErrorMessages = new WeakMap<object, string>();
57
78
  const operatorErrorCapability = Object.freeze({});
58
79
 
59
80
  class OperatorError extends Error {
60
81
  readonly #operatorCode: OperatorErrorCode;
61
82
 
62
- constructor(capability: object, code: OperatorErrorCode) {
63
- super(Object.hasOwn(publicMessages, code) ? publicMessages[code] : "Operator error rejected.");
83
+ constructor(capability: object, code: OperatorErrorCode, publicMessage?: string) {
84
+ super(publicMessage ?? (Object.hasOwn(publicMessages, code) ? publicMessages[code] : "Operator error rejected."));
64
85
  if (capability !== operatorErrorCapability || !Object.hasOwn(publicMessages, code)) {
65
86
  throw new Error("Operator error construction is unavailable.");
66
87
  }
67
88
  this.name = "OperatorError";
68
89
  this.#operatorCode = code;
69
90
  operatorErrorCodes.set(this, code);
91
+ operatorErrorMessages.set(this, this.message);
70
92
  Object.freeze(this);
71
93
  }
72
94
 
@@ -75,7 +97,7 @@ class OperatorError extends Error {
75
97
  }
76
98
 
77
99
  get publicMessage(): string {
78
- return publicMessages[this.#operatorCode];
100
+ return operatorErrorMessages.get(this) ?? publicMessages[this.#operatorCode];
79
101
  }
80
102
  }
81
103
 
@@ -93,5 +115,17 @@ export function operatorPublicMessage(error: unknown): string | null {
93
115
  const code = operatorErrorCodes.get(error);
94
116
  if (code === undefined) return null;
95
117
  if (Object.getPrototypeOf(error) !== OperatorError.prototype || !Object.isFrozen(error)) return null;
96
- return publicMessages[code];
118
+ return operatorErrorMessages.get(error) ?? publicMessages[code];
119
+ }
120
+
121
+ export function invitationCubeAmbiguousError(candidateIds: readonly string[]): Error {
122
+ if (candidateIds.length < 2 || candidateIds.some((id) =>
123
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(id))) {
124
+ throw new Error("Ambiguous cube candidates must contain canonical cube IDs.");
125
+ }
126
+ return new OperatorError(
127
+ operatorErrorCapability,
128
+ "INVITATION_CUBE_AMBIGUOUS",
129
+ `Cube name is ambiguous. Rerun with the full cube ID. Candidate cube IDs: ${candidateIds.join(", ")}`,
130
+ );
97
131
  }
@@ -0,0 +1,108 @@
1
+ export type RoleSectionPatchOp =
2
+ | { readonly action: "replace"; readonly heading: string; readonly body: string }
3
+ | {
4
+ readonly action: "insert";
5
+ readonly heading: string;
6
+ readonly body: string;
7
+ readonly after?: string | null;
8
+ }
9
+ | { readonly action: "delete"; readonly heading: string };
10
+
11
+ interface RoleSection {
12
+ readonly heading: string | null;
13
+ readonly body: string;
14
+ }
15
+
16
+ export function patchRoleSectionText(text: string, operation: RoleSectionPatchOp): string {
17
+ validateHeading(operation.heading);
18
+ const sections = parseSections(text);
19
+ const target = normalizedHeading(operation.heading);
20
+ const index = sections.findIndex((section) =>
21
+ section.heading !== null && normalizedHeading(section.heading) === target
22
+ );
23
+
24
+ if (operation.action === "replace") {
25
+ if (index === -1) throw new Error("Role section not found.");
26
+ sections[index] = renderedSection(operation.heading, operation.body);
27
+ return serializeSections(sections);
28
+ }
29
+ if (operation.action === "delete") {
30
+ if (index === -1) throw new Error("Role section not found.");
31
+ sections.splice(index, 1);
32
+ return serializeSections(sections);
33
+ }
34
+ if (index !== -1) throw new Error("Role section already exists.");
35
+
36
+ const section = renderedSection(operation.heading, operation.body);
37
+ if (operation.after == null) {
38
+ ensureTrailingNewline(sections, sections.length - 1);
39
+ sections.push(section);
40
+ return serializeSections(sections);
41
+ }
42
+ validateHeading(operation.after);
43
+ const after = normalizedHeading(operation.after);
44
+ const afterIndex = sections.findIndex((candidate) =>
45
+ candidate.heading !== null && normalizedHeading(candidate.heading) === after
46
+ );
47
+ if (afterIndex === -1) throw new Error("Role section insertion point does not exist.");
48
+ ensureTrailingNewline(sections, afterIndex);
49
+ sections.splice(afterIndex + 1, 0, section);
50
+ return serializeSections(sections);
51
+ }
52
+
53
+ function parseSections(text: string): RoleSection[] {
54
+ const sections: RoleSection[] = [];
55
+ const lines = text.split("\n");
56
+ let heading: string | null = null;
57
+ let body = "";
58
+ for (let index = 0; index < lines.length; index += 1) {
59
+ const line = lines[index]!;
60
+ const sourceLine = index < lines.length - 1 ? `${line}\n` : line;
61
+ if (isLabelLine(line)) {
62
+ sections.push({ heading, body });
63
+ heading = line.slice(0, -1).trim();
64
+ body = sourceLine;
65
+ } else {
66
+ body += sourceLine;
67
+ }
68
+ }
69
+ sections.push({ heading, body });
70
+ return sections;
71
+ }
72
+
73
+ function isLabelLine(line: string): boolean {
74
+ if (/^\s/u.test(line) || !line.endsWith(":")) return false;
75
+ const label = line.slice(0, -1);
76
+ return label.length > 0 && label.length <= 60 && !label.includes(":") &&
77
+ !/^[*\-#>`]/u.test(label);
78
+ }
79
+
80
+ function renderedSection(heading: string, body: string): RoleSection {
81
+ const normalizedBody = body === "" || body.endsWith("\n") ? body : `${body}\n`;
82
+ return {
83
+ heading: heading.trim(),
84
+ body: `${heading.trim()}:\n${normalizedBody}`,
85
+ };
86
+ }
87
+
88
+ function ensureTrailingNewline(sections: RoleSection[], index: number): void {
89
+ const section = sections[index];
90
+ if (section !== undefined && section.body !== "" && !section.body.endsWith("\n")) {
91
+ sections[index] = { ...section, body: `${section.body}\n` };
92
+ }
93
+ }
94
+
95
+ function serializeSections(sections: readonly RoleSection[]): string {
96
+ return sections.map((section) => section.body).join("");
97
+ }
98
+
99
+ function normalizedHeading(heading: string): string {
100
+ return heading.trim().toLowerCase();
101
+ }
102
+
103
+ function validateHeading(heading: string): void {
104
+ if (typeof heading !== "string" || /[\r\n]/u.test(heading) ||
105
+ !isLabelLine(`${heading.trim()}:`)) {
106
+ throw new TypeError("Role section heading is invalid.");
107
+ }
108
+ }