@phnx-labs/agents-cli 1.23.16 → 1.23.18

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 (205) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +140 -165
  3. package/dist/bootstrap.js +10 -16
  4. package/dist/cli/command-registry.d.ts +1 -2
  5. package/dist/cli/command-registry.js +1 -10
  6. package/dist/commands/accounts.js +7 -7
  7. package/dist/commands/cloud-transcripts.d.ts +0 -1
  8. package/dist/commands/cloud-transcripts.js +2 -2
  9. package/dist/commands/cloud.js +1 -1
  10. package/dist/commands/config.js +0 -4
  11. package/dist/commands/cost.js +1 -1
  12. package/dist/commands/daemon-index.js +0 -1
  13. package/dist/commands/detach.d.ts +1 -1
  14. package/dist/commands/detach.js +5 -5
  15. package/dist/commands/exec.js +10 -22
  16. package/dist/commands/feed.d.ts +1 -1
  17. package/dist/commands/feed.js +3 -3
  18. package/dist/commands/focus.d.ts +1 -4
  19. package/dist/commands/focus.js +12 -13
  20. package/dist/commands/fork.d.ts +0 -1
  21. package/dist/commands/fork.js +7 -16
  22. package/dist/commands/harness-wizard.js +1 -1
  23. package/dist/commands/harness.js +1 -1
  24. package/dist/commands/insights.d.ts +0 -1
  25. package/dist/commands/insights.js +3 -7
  26. package/dist/commands/open.js +1 -1
  27. package/dist/commands/output.js +1 -1
  28. package/dist/commands/profiles.d.ts +1 -1
  29. package/dist/commands/profiles.js +2 -2
  30. package/dist/commands/projects.js +1 -1
  31. package/dist/commands/prune.js +1 -1
  32. package/dist/commands/ps.d.ts +0 -1
  33. package/dist/commands/ps.js +63 -18
  34. package/dist/commands/routines.js +1 -1
  35. package/dist/commands/send.js +1 -1
  36. package/dist/commands/sessions-backfill.d.ts +0 -1
  37. package/dist/commands/sessions-backfill.js +3 -6
  38. package/dist/commands/sessions-browser.d.ts +0 -10
  39. package/dist/commands/sessions-browser.js +19 -25
  40. package/dist/commands/sessions-migrate.d.ts +2 -2
  41. package/dist/commands/sessions-migrate.js +13 -13
  42. package/dist/commands/sessions-optimize.d.ts +0 -1
  43. package/dist/commands/sessions-optimize.js +0 -3
  44. package/dist/commands/sessions-picker.js +11 -11
  45. package/dist/commands/sessions-resume.d.ts +16 -15
  46. package/dist/commands/sessions-resume.js +101 -269
  47. package/dist/commands/sessions-stats.d.ts +0 -1
  48. package/dist/commands/sessions-stats.js +5 -8
  49. package/dist/commands/sessions-stop.d.ts +1 -1
  50. package/dist/commands/sessions-stop.js +6 -6
  51. package/dist/commands/sessions-trace.d.ts +1 -1
  52. package/dist/commands/sessions-trace.js +40 -17
  53. package/dist/commands/sessions-watch.js +2 -2
  54. package/dist/commands/sessions.test-fixture.d.ts +1 -0
  55. package/dist/commands/sessions.test-fixture.js +14 -0
  56. package/dist/commands/setup-browser.js +4 -4
  57. package/dist/commands/setup-computer.js +4 -4
  58. package/dist/commands/setup-fleet.js +1 -1
  59. package/dist/commands/setup-preferences.js +1 -1
  60. package/dist/commands/{sessions-backup-setup.d.ts → setup-session-backup.d.ts} +2 -2
  61. package/dist/commands/{sessions-backup-setup.js → setup-session-backup.js} +8 -8
  62. package/dist/commands/setup.js +3 -1
  63. package/dist/commands/ssh.js +4 -5
  64. package/dist/commands/sync.js +1 -1
  65. package/dist/commands/teams.js +2 -2
  66. package/dist/commands/utils.d.ts +0 -1
  67. package/dist/commands/utils.js +0 -10
  68. package/dist/index.js +0 -71
  69. package/dist/lib/accounting/rotate.js +1 -1
  70. package/dist/lib/analytics/mix-commands.js +1 -1
  71. package/dist/lib/auth-mint.js +2 -2
  72. package/dist/lib/browser-client.d.ts +0 -1
  73. package/dist/lib/browser-client.js +0 -3
  74. package/dist/lib/cloud/antigravity.js +1 -1
  75. package/dist/lib/cloud/cursor.js +3 -3
  76. package/dist/lib/cloudflare/creds.js +2 -2
  77. package/dist/lib/computer/context.d.ts +4 -21
  78. package/dist/lib/computer/context.js +3 -24
  79. package/dist/lib/computer/policy.d.ts +0 -10
  80. package/dist/lib/computer/policy.js +0 -28
  81. package/dist/lib/computer-client.d.ts +0 -44
  82. package/dist/lib/computer-client.js +17 -121
  83. package/dist/lib/config-keys.d.ts +1 -1
  84. package/dist/lib/config-keys.js +0 -3
  85. package/dist/lib/crabbox/cli.js +1 -1
  86. package/dist/lib/device-config.js +5 -28
  87. package/dist/lib/devices/connect.d.ts +1 -1
  88. package/dist/lib/devices/connect.js +3 -6
  89. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  90. package/dist/lib/devices/doctor-findings.js +4 -4
  91. package/dist/lib/exec.js +1 -1
  92. package/dist/lib/feed/activity.js +1 -1
  93. package/dist/lib/fleet/apply.js +1 -1
  94. package/dist/lib/help.d.ts +0 -1
  95. package/dist/lib/help.js +2 -10
  96. package/dist/lib/hosts/option.js +1 -1
  97. package/dist/lib/hosts/passthrough.d.ts +0 -1
  98. package/dist/lib/hosts/passthrough.js +2 -26
  99. package/dist/lib/hosts/reconnect.js +5 -5
  100. package/dist/lib/hosts/remote-cmd.d.ts +3 -5
  101. package/dist/lib/hosts/remote-cmd.js +15 -20
  102. package/dist/lib/hosts/remote-session-id.js +1 -1
  103. package/dist/lib/installations/active-check.js +1 -1
  104. package/dist/lib/installations/migrate.js +4 -15
  105. package/dist/lib/installations/versions.js +1 -1
  106. package/dist/lib/launch-log.js +3 -6
  107. package/dist/lib/owner-notify.d.ts +1 -6
  108. package/dist/lib/owner-notify.js +0 -2
  109. package/dist/lib/paths.d.ts +0 -1
  110. package/dist/lib/paths.js +0 -8
  111. package/dist/lib/permissions.js +1 -1
  112. package/dist/lib/redact.d.ts +0 -1
  113. package/dist/lib/redact.js +0 -4
  114. package/dist/lib/remote-agents-json.d.ts +3 -1
  115. package/dist/lib/remote-agents-json.js +8 -6
  116. package/dist/lib/reserved-stores.js +1 -1
  117. package/dist/lib/scheduling/routines.d.ts +0 -1
  118. package/dist/lib/scheduling/routines.js +1 -1
  119. package/dist/lib/session/active.d.ts +1 -1
  120. package/dist/lib/session/db.js +3 -3
  121. package/dist/lib/session/detached.d.ts +0 -1
  122. package/dist/lib/session/detached.js +0 -23
  123. package/dist/lib/session/discover.d.ts +2 -2
  124. package/dist/lib/session/presentation.d.ts +0 -7
  125. package/dist/lib/session/presentation.js +4 -4
  126. package/dist/lib/session/projection.js +1 -1
  127. package/dist/lib/session/remote/remote-list.d.ts +2 -0
  128. package/dist/lib/session/remote/remote-list.js +3 -2
  129. package/dist/lib/session/remote/watch.js +4 -5
  130. package/dist/lib/session/remote-active.js +1 -1
  131. package/dist/lib/session/resume-command.d.ts +0 -1
  132. package/dist/lib/session/resume-command.js +1 -4
  133. package/dist/lib/session/resume-owner.d.ts +0 -2
  134. package/dist/lib/session/resume-owner.js +0 -6
  135. package/dist/lib/session/selection.d.ts +4 -5
  136. package/dist/lib/session/selection.js +2 -2
  137. package/dist/lib/session/sync/config.d.ts +0 -25
  138. package/dist/lib/session/sync/config.js +0 -62
  139. package/dist/lib/session/sync/managed-config.d.ts +0 -1
  140. package/dist/lib/session/sync/managed-config.js +0 -3
  141. package/dist/lib/session/sync/worker-template.js +1 -1
  142. package/dist/lib/sessions-client.d.ts +0 -16
  143. package/dist/lib/sessions-client.js +1 -187
  144. package/dist/lib/startup/command-registry.d.ts +2 -0
  145. package/dist/lib/startup/command-registry.js +36 -3
  146. package/dist/lib/startup/root-command.d.ts +0 -1
  147. package/dist/lib/startup/root-command.js +0 -21
  148. package/dist/lib/sync-umbrella.js +1 -1
  149. package/dist/lib/terminal/resolve.js +1 -1
  150. package/dist/lib/watchdog/rotate.js +1 -1
  151. package/dist/lib/watchdog/watchdog.d.ts +1 -1
  152. package/dist/lib/watchdog/watchdog.js +2 -2
  153. package/package.json +1 -1
  154. package/dist/commands/browser.d.ts +0 -7
  155. package/dist/commands/browser.js +0 -139
  156. package/dist/commands/computer.d.ts +0 -48
  157. package/dist/commands/computer.js +0 -244
  158. package/dist/commands/resume.d.ts +0 -23
  159. package/dist/commands/resume.js +0 -158
  160. package/dist/commands/secrets-passthrough.d.ts +0 -3
  161. package/dist/commands/secrets-passthrough.js +0 -52
  162. package/dist/commands/sessions-bookmark.d.ts +0 -2
  163. package/dist/commands/sessions-bookmark.js +0 -92
  164. package/dist/commands/sessions-export.d.ts +0 -31
  165. package/dist/commands/sessions-export.js +0 -409
  166. package/dist/commands/sessions-import.d.ts +0 -6
  167. package/dist/commands/sessions-import.js +0 -343
  168. package/dist/commands/sessions-inject.d.ts +0 -14
  169. package/dist/commands/sessions-inject.js +0 -143
  170. package/dist/commands/sessions-picker-factory.d.ts +0 -24
  171. package/dist/commands/sessions-picker-factory.js +0 -59
  172. package/dist/commands/sessions-render.d.ts +0 -11
  173. package/dist/commands/sessions-render.js +0 -119
  174. package/dist/commands/sessions-share.d.ts +0 -15
  175. package/dist/commands/sessions-share.js +0 -171
  176. package/dist/commands/sessions.d.ts +0 -122
  177. package/dist/commands/sessions.js +0 -1760
  178. package/dist/lib/address.d.ts +0 -39
  179. package/dist/lib/address.js +0 -128
  180. package/dist/lib/computer/record.d.ts +0 -6
  181. package/dist/lib/computer/record.js +0 -25
  182. package/dist/lib/openclaw-keychain.d.ts +0 -43
  183. package/dist/lib/openclaw-keychain.js +0 -227
  184. package/dist/lib/session/bundle.d.ts +0 -76
  185. package/dist/lib/session/bundle.js +0 -146
  186. package/dist/lib/session/remote/remote-bundle.d.ts +0 -7
  187. package/dist/lib/session/remote/remote-bundle.js +0 -40
  188. package/dist/lib/session/remote/remote.d.ts +0 -35
  189. package/dist/lib/session/remote/remote.js +0 -198
  190. package/dist/lib/session/remote-bundle.d.ts +0 -1
  191. package/dist/lib/session/remote-bundle.js +0 -1
  192. package/dist/lib/session/remote.d.ts +0 -1
  193. package/dist/lib/session/remote.js +0 -1
  194. package/dist/lib/session/sync/agents.d.ts +0 -24
  195. package/dist/lib/session/sync/agents.js +0 -0
  196. package/dist/lib/session/sync/backend.d.ts +0 -22
  197. package/dist/lib/session/sync/backend.js +0 -44
  198. package/dist/lib/session/sync/managed-key.d.ts +0 -5
  199. package/dist/lib/session/sync/managed-key.js +0 -87
  200. package/dist/lib/session/sync/net-client.d.ts +0 -29
  201. package/dist/lib/session/sync/net-client.js +0 -87
  202. package/dist/lib/session/sync/r2.d.ts +0 -20
  203. package/dist/lib/session/sync/r2.js +0 -103
  204. package/dist/lib/session/sync/transcript-crypto.d.ts +0 -41
  205. package/dist/lib/session/sync/transcript-crypto.js +0 -115
@@ -1,87 +0,0 @@
1
- export class SessionsHttpClient {
2
- kind = 'managed';
3
- base;
4
- userId;
5
- token;
6
- constructor(opts) {
7
- this.base = opts.baseUrl.replace(/\/+$/, '');
8
- this.userId = safeOwnerSegment(opts.userId);
9
- this.token = opts.token;
10
- }
11
- objUrl(key) {
12
- const rel = safeObjectKey(key).map(encodeURIComponent).join('/');
13
- return `${this.base}/${encodeURIComponent(this.userId)}/${rel}`;
14
- }
15
- authHeaders(extra = {}) {
16
- return { authorization: `Bearer ${this.token}`, ...extra };
17
- }
18
- async put(key, body, contentType = 'application/octet-stream') {
19
- const res = await fetch(this.objUrl(key), {
20
- method: 'PUT',
21
- headers: this.authHeaders({ 'content-type': contentType }),
22
- body,
23
- });
24
- if (!res.ok)
25
- throw new Error(`sessions PUT ${key} failed: ${res.status} ${await safeText(res)}`);
26
- }
27
- async putIfAbsent(key, body, contentType = 'application/octet-stream') {
28
- const res = await fetch(this.objUrl(key), {
29
- method: 'PUT',
30
- headers: this.authHeaders({ 'content-type': contentType, 'if-none-match': '*' }),
31
- body,
32
- });
33
- if (res.status === 409)
34
- return false;
35
- if (!res.ok) {
36
- throw new Error(`sessions PUT-IF-ABSENT ${key} failed: ${res.status} ${await safeText(res)}`);
37
- }
38
- return true;
39
- }
40
- async get(key) {
41
- const res = await fetch(this.objUrl(key), { method: 'GET', headers: this.authHeaders() });
42
- if (res.status === 404)
43
- return null;
44
- if (!res.ok)
45
- throw new Error(`sessions GET ${key} failed: ${res.status} ${await safeText(res)}`);
46
- return await res.text();
47
- }
48
- async list(_prefix) {
49
- const url = `${this.base}/${encodeURIComponent(this.userId)}/?list`;
50
- const res = await fetch(url, { method: 'GET', headers: this.authHeaders() });
51
- if (!res.ok)
52
- throw new Error(`sessions LIST failed: ${res.status} ${await safeText(res)}`);
53
- const body = (await res.json());
54
- if (!body || !Array.isArray(body.keys))
55
- return [];
56
- return body.keys.filter((k) => typeof k === 'string');
57
- }
58
- async delete(key) {
59
- const res = await fetch(this.objUrl(key), { method: 'DELETE', headers: this.authHeaders() });
60
- if (!res.ok && res.status !== 404) {
61
- throw new Error(`sessions DELETE ${key} failed: ${res.status} ${await safeText(res)}`);
62
- }
63
- }
64
- }
65
- function safeOwnerSegment(owner) {
66
- const value = owner.trim();
67
- if (!value || value === '.' || value === '..' || value.includes('/')) {
68
- throw new Error(`Invalid managed sessions user id: ${JSON.stringify(owner)}`);
69
- }
70
- return value;
71
- }
72
- function safeObjectKey(key) {
73
- const segments = key.split('/');
74
- if (segments.length === 0 ||
75
- segments.some(segment => !segment || segment === '.' || segment === '..')) {
76
- throw new Error(`Invalid managed sessions object key: ${JSON.stringify(key)}`);
77
- }
78
- return segments;
79
- }
80
- async function safeText(res) {
81
- try {
82
- return (await res.text()).slice(0, 200);
83
- }
84
- catch {
85
- return '';
86
- }
87
- }
@@ -1,20 +0,0 @@
1
- import type { R2Config } from './config.js';
2
- interface HeadResult {
3
- size: number;
4
- etag: string;
5
- }
6
- export declare class R2Client {
7
- readonly kind: "byo";
8
- private aws;
9
- private base;
10
- constructor(cfg: R2Config);
11
- private url;
12
- put(key: string, body: string | Uint8Array, contentType?: string): Promise<void>;
13
- get(key: string): Promise<string | null>;
14
- head(key: string): Promise<HeadResult | null>;
15
- delete(key: string): Promise<void>;
16
- listPrefixes(prefix: string): Promise<string[]>;
17
- list(prefix?: string): Promise<string[]>;
18
- }
19
- export declare function decodeXml(s: string): string;
20
- export {};
@@ -1,103 +0,0 @@
1
- import { AwsClient } from 'aws4fetch';
2
- export class R2Client {
3
- kind = 'byo';
4
- aws;
5
- base;
6
- constructor(cfg) {
7
- this.aws = new AwsClient({
8
- accessKeyId: cfg.accessKeyId,
9
- secretAccessKey: cfg.secretAccessKey,
10
- service: 's3',
11
- region: 'auto',
12
- });
13
- this.base = `${cfg.endpoint}/${encodeURIComponent(cfg.bucket)}`;
14
- }
15
- url(key) {
16
- const encoded = key.split('/').map(encodeURIComponent).join('/');
17
- return `${this.base}/${encoded}`;
18
- }
19
- async put(key, body, contentType = 'application/octet-stream') {
20
- const res = await this.aws.fetch(this.url(key), {
21
- method: 'PUT',
22
- body,
23
- headers: { 'content-type': contentType },
24
- });
25
- if (!res.ok)
26
- throw new Error(`R2 PUT ${key} failed: ${res.status} ${await safeText(res)}`);
27
- }
28
- async get(key) {
29
- const res = await this.aws.fetch(this.url(key), { method: 'GET' });
30
- if (res.status === 404)
31
- return null;
32
- if (!res.ok)
33
- throw new Error(`R2 GET ${key} failed: ${res.status} ${await safeText(res)}`);
34
- return await res.text();
35
- }
36
- async head(key) {
37
- const res = await this.aws.fetch(this.url(key), { method: 'HEAD' });
38
- if (res.status === 404)
39
- return null;
40
- if (!res.ok)
41
- throw new Error(`R2 HEAD ${key} failed: ${res.status}`);
42
- return {
43
- size: Number(res.headers.get('content-length') ?? '0'),
44
- etag: (res.headers.get('etag') ?? '').replace(/"/g, ''),
45
- };
46
- }
47
- async delete(key) {
48
- const res = await this.aws.fetch(this.url(key), { method: 'DELETE' });
49
- if (!res.ok && res.status !== 404) {
50
- throw new Error(`R2 DELETE ${key} failed: ${res.status}`);
51
- }
52
- }
53
- async listPrefixes(prefix) {
54
- const prefixes = [];
55
- let token;
56
- do {
57
- const params = new URLSearchParams({ 'list-type': '2', prefix, delimiter: '/' });
58
- if (token)
59
- params.set('continuation-token', token);
60
- const res = await this.aws.fetch(`${this.base}?${params.toString()}`, { method: 'GET' });
61
- if (!res.ok)
62
- throw new Error(`R2 LIST(prefixes) ${prefix} failed: ${res.status} ${await safeText(res)}`);
63
- const xml = await res.text();
64
- for (const m of xml.matchAll(/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g)) {
65
- prefixes.push(decodeXml(m[1]));
66
- }
67
- const truncated = /<IsTruncated>true<\/IsTruncated>/.test(xml);
68
- token = truncated ? xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1] : undefined;
69
- } while (token);
70
- return prefixes;
71
- }
72
- async list(prefix = '') {
73
- const keys = [];
74
- let token;
75
- do {
76
- const params = new URLSearchParams({ 'list-type': '2', prefix });
77
- if (token)
78
- params.set('continuation-token', token);
79
- const res = await this.aws.fetch(`${this.base}?${params.toString()}`, { method: 'GET' });
80
- if (!res.ok)
81
- throw new Error(`R2 LIST ${prefix} failed: ${res.status} ${await safeText(res)}`);
82
- const xml = await res.text();
83
- for (const m of xml.matchAll(/<Key>([^<]+)<\/Key>/g)) {
84
- keys.push(decodeXml(m[1]));
85
- }
86
- const truncated = /<IsTruncated>true<\/IsTruncated>/.test(xml);
87
- token = truncated ? xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1] : undefined;
88
- } while (token);
89
- return keys;
90
- }
91
- }
92
- const XML_ENTITIES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'" };
93
- export function decodeXml(s) {
94
- return s.replace(/&(?:amp|lt|gt|quot|apos);/g, (entity) => XML_ENTITIES[entity] ?? entity);
95
- }
96
- async function safeText(res) {
97
- try {
98
- return (await res.text()).slice(0, 200);
99
- }
100
- catch {
101
- return '';
102
- }
103
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * Client-side (zero-knowledge) encryption for session transcripts before they
3
- * leave this machine for R2.
4
- *
5
- * R2 encrypts objects at rest server-side (AES-256, Cloudflare default), but
6
- * that key is Cloudflare's — anyone with bucket-read access (or Cloudflare
7
- * itself) can read the plaintext. Transcripts carry secrets, tokens, and
8
- * absolute file paths, so "encrypted at rest by the provider" is not enough. We
9
- * seal each transcript BODY client-side with AES-256-GCM under a key that never
10
- * leaves the machines that share the sync bundle; Cloudflare only ever stores
11
- * ciphertext.
12
- *
13
- * The key is a 32-byte secret (`R2_SYNC_ENC_KEY`) held in the same
14
- * keychain-backed `r2.backups` bundle as the R2 credentials. Every machine in
15
- * the sync fabric shares that bundle, so every machine derives the identical key
16
- * and can decrypt its peers' objects. The key is deliberately SEPARATE from the
17
- * R2 access key so that rotating the R2 token (RUSH-1464) never orphans
18
- * transcripts already encrypted under the old one.
19
- *
20
- * Identity for CRDT merge stays over PLAINTEXT: the manifest hash is computed on
21
- * the cleartext transcript (sync.ts), and pull decrypts before the G-Set union
22
- * (crdt.ts) ever sees the bytes. Ciphertext is non-deterministic (a fresh random
23
- * IV per seal), so it is never usable as an identity — which is exactly why the
24
- * manifest, not the object body, carries the hash.
25
- */
26
- import type { R2Config } from './config.js';
27
- interface TranscriptEnvelope {
28
- v: 1;
29
- alg: 'aes-256-gcm';
30
- iv: string;
31
- ct: string;
32
- tag: string;
33
- }
34
- export declare function resolveSyncEncKey(cfg: Pick<R2Config, 'syncEncKey'>): Buffer | null;
35
- export declare function generateSyncEncKey(): string;
36
- export declare function encryptTranscript(plaintext: string, key: Buffer): string;
37
- export declare function parseEnvelope(body: string): TranscriptEnvelope | null;
38
- export declare function isTranscriptEnvelope(body: string): boolean;
39
- export declare function decryptEnvelope(envelope: TranscriptEnvelope, key: Buffer): string;
40
- export declare function decryptTranscriptBody(body: string, key: Buffer | null): string;
41
- export {};
@@ -1,115 +0,0 @@
1
- /**
2
- * Client-side (zero-knowledge) encryption for session transcripts before they
3
- * leave this machine for R2.
4
- *
5
- * R2 encrypts objects at rest server-side (AES-256, Cloudflare default), but
6
- * that key is Cloudflare's — anyone with bucket-read access (or Cloudflare
7
- * itself) can read the plaintext. Transcripts carry secrets, tokens, and
8
- * absolute file paths, so "encrypted at rest by the provider" is not enough. We
9
- * seal each transcript BODY client-side with AES-256-GCM under a key that never
10
- * leaves the machines that share the sync bundle; Cloudflare only ever stores
11
- * ciphertext.
12
- *
13
- * The key is a 32-byte secret (`R2_SYNC_ENC_KEY`) held in the same
14
- * keychain-backed `r2.backups` bundle as the R2 credentials. Every machine in
15
- * the sync fabric shares that bundle, so every machine derives the identical key
16
- * and can decrypt its peers' objects. The key is deliberately SEPARATE from the
17
- * R2 access key so that rotating the R2 token (RUSH-1464) never orphans
18
- * transcripts already encrypted under the old one.
19
- *
20
- * Identity for CRDT merge stays over PLAINTEXT: the manifest hash is computed on
21
- * the cleartext transcript (sync.ts), and pull decrypts before the G-Set union
22
- * (crdt.ts) ever sees the bytes. Ciphertext is non-deterministic (a fresh random
23
- * IV per seal), so it is never usable as an identity — which is exactly why the
24
- * manifest, not the object body, carries the hash.
25
- */
26
- import * as crypto from 'crypto';
27
- const ALG = 'aes-256-gcm';
28
- const KEY_LEN = 32;
29
- const IV_LEN = 12;
30
- const TAG_LEN = 16;
31
- export function resolveSyncEncKey(cfg) {
32
- const raw = cfg.syncEncKey?.trim();
33
- if (!raw)
34
- return null;
35
- let key;
36
- if (/^[0-9a-f]{64}$/i.test(raw)) {
37
- key = Buffer.from(raw, 'hex');
38
- }
39
- else {
40
- key = Buffer.from(raw, 'base64');
41
- }
42
- if (key.length !== KEY_LEN) {
43
- throw new Error(`R2_SYNC_ENC_KEY must decode to ${KEY_LEN} bytes (got ${key.length}). ` +
44
- `Provide 32 random bytes as hex (64 chars) or base64. ` +
45
- `Generate one with: openssl rand -base64 32`);
46
- }
47
- return key;
48
- }
49
- export function generateSyncEncKey() {
50
- return crypto.randomBytes(KEY_LEN).toString('base64');
51
- }
52
- export function encryptTranscript(plaintext, key) {
53
- const iv = crypto.randomBytes(IV_LEN);
54
- const cipher = crypto.createCipheriv(ALG, key, iv);
55
- const ct = Buffer.concat([cipher.update(plaintext, 'utf-8'), cipher.final()]);
56
- const tag = cipher.getAuthTag();
57
- const envelope = {
58
- v: 1,
59
- alg: ALG,
60
- iv: iv.toString('base64'),
61
- ct: ct.toString('base64'),
62
- tag: tag.toString('base64'),
63
- };
64
- return JSON.stringify(envelope);
65
- }
66
- export function parseEnvelope(body) {
67
- const trimmed = body.trimStart();
68
- if (!trimmed.startsWith('{'))
69
- return null;
70
- let obj;
71
- try {
72
- obj = JSON.parse(body);
73
- }
74
- catch {
75
- return null;
76
- }
77
- if (obj && typeof obj === 'object' &&
78
- obj.v === 1 &&
79
- obj.alg === ALG &&
80
- typeof obj.iv === 'string' &&
81
- typeof obj.ct === 'string' &&
82
- typeof obj.tag === 'string') {
83
- return obj;
84
- }
85
- return null;
86
- }
87
- export function isTranscriptEnvelope(body) {
88
- return parseEnvelope(body) !== null;
89
- }
90
- export function decryptEnvelope(envelope, key) {
91
- const iv = Buffer.from(envelope.iv, 'base64');
92
- const ct = Buffer.from(envelope.ct, 'base64');
93
- const tag = Buffer.from(envelope.tag, 'base64');
94
- if (tag.length !== TAG_LEN) {
95
- throw new Error(`Transcript envelope has a malformed auth tag (${tag.length} bytes).`);
96
- }
97
- const decipher = crypto.createDecipheriv(ALG, key, iv);
98
- decipher.setAuthTag(tag);
99
- try {
100
- return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf-8');
101
- }
102
- catch {
103
- throw new Error('Transcript decryption failed — wrong R2_SYNC_ENC_KEY or corrupt object.');
104
- }
105
- }
106
- export function decryptTranscriptBody(body, key) {
107
- const envelope = parseEnvelope(body);
108
- if (!envelope)
109
- return body;
110
- if (!key) {
111
- throw new Error('Fetched an encrypted transcript but R2_SYNC_ENC_KEY is not set in the r2.backups bundle. ' +
112
- 'Add the shared key so this machine can decrypt peers\' sessions.');
113
- }
114
- return decryptEnvelope(envelope, key);
115
- }