@dharma-ai-labs/agent-fabric-relay-client 0.2.28 → 0.2.30

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.
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto';
2
- import { mkdir, open, readFile, rename } from 'node:fs/promises';
2
+ import { mkdir, open, readFile, rename, rm } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
4
  import { canonicalize, refreshActionDecisionAcknowledgement, validateActionDecisionAcknowledgementContract, verifyInitialServerSigningKeyset, verifyServerSigningKeysetUpdate, } from '@dharma-ai-labs/agent-fabric-contracts';
5
5
  import { createSystemSecureStore } from '@dharma-ai-labs/agent-fabric-secure-store';
6
+ import { HostOperationFence } from './hostOperationScope.js';
6
7
  export { claimSetupReference, setupClaimSourceRegistration } from './setupClaim.js';
7
8
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
8
9
  function isRecoveredTaskCompletion(value) {
@@ -102,19 +103,41 @@ function organizationApiTokenAccountFor(hqUrl, organizationId, installationId) {
102
103
  : `${normalizeHqUrl(hqUrl)}:${organizationId}`;
103
104
  return `organization-api-${sha256(scope).slice(0, 32)}`;
104
105
  }
106
+ async function protectedStore(store, scope) {
107
+ if (scope === undefined)
108
+ return store ?? await createSystemSecureStore();
109
+ const fence = new HostOperationFence(scope);
110
+ const raw = await fence.step(async () => store ?? await createSystemSecureStore());
111
+ return fence.store(raw);
112
+ }
113
+ function parseProtectedAnchor(serialized, scope, message) {
114
+ try {
115
+ const parsed = JSON.parse(serialized);
116
+ if (scope && (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)))
117
+ throw new Error();
118
+ return parsed;
119
+ }
120
+ catch (error) {
121
+ if (scope)
122
+ throw new Error(message);
123
+ throw error;
124
+ }
125
+ }
105
126
  export async function saveOrganizationApiToken(input) {
106
- if (!/^dharma_org_[A-Za-z0-9_-]{40,120}$/.test(input.token)) {
127
+ const { hqUrl, organizationId, installationId, token, store: suppliedStore, hostScope } = input;
128
+ if (!/^dharma_org_[A-Za-z0-9_-]{40,120}$/.test(token)) {
107
129
  throw new Error('Organization API token is invalid.');
108
130
  }
109
- const store = input.store ?? await createSystemSecureStore();
110
- const account = organizationApiTokenAccountFor(input.hqUrl, input.organizationId, input.installationId);
111
- await store.put(account, input.token);
112
- if (await store.get(account) !== input.token)
131
+ const account = organizationApiTokenAccountFor(hqUrl, organizationId, installationId);
132
+ const store = await protectedStore(suppliedStore, hostScope);
133
+ await store.put(account, token);
134
+ if (await store.get(account) !== token)
113
135
  throw new Error('Secure store did not confirm the organization API token write.');
114
136
  }
115
137
  export async function loadOrganizationApiToken(input) {
116
- const store = input.store ?? await createSystemSecureStore();
117
- const token = await store.get(organizationApiTokenAccountFor(input.hqUrl, input.organizationId, input.installationId));
138
+ const account = organizationApiTokenAccountFor(input.hqUrl, input.organizationId, input.installationId);
139
+ const store = await protectedStore(input.store, input.hostScope);
140
+ const token = await store.get(account);
118
141
  if (token && !/^dharma_org_[A-Za-z0-9_-]{40,120}$/.test(token)) {
119
142
  throw new Error('Organization API token in the secure store is corrupt.');
120
143
  }
@@ -148,29 +171,31 @@ function enrollmentAnchorHasBaseIdentity(anchor, config) {
148
171
  && Number.isFinite(Date.parse(anchor.enrolledAt));
149
172
  }
150
173
  export async function saveDeviceEnrollmentAnchor(input) {
151
- const store = input.store ?? await createSystemSecureStore();
152
- const anchor = enrollmentAnchorFromConfig(input.config);
174
+ const anchor = enrollmentAnchorFromConfig(input.hostScope ? structuredClone(input.config) : input.config);
153
175
  const serialized = JSON.stringify(anchor);
154
176
  const account = enrollmentAnchorAccountFor(anchor.hqUrl, anchor.organizationId, anchor.deviceId);
177
+ const store = await protectedStore(input.store, input.hostScope);
155
178
  await store.put(account, serialized);
156
179
  if (await store.get(account) !== serialized)
157
180
  throw new Error('Secure store did not confirm the enrollment anchor write.');
158
181
  return anchor;
159
182
  }
160
183
  export async function loadDeviceEnrollmentAnchor(input) {
161
- const store = input.store ?? await createSystemSecureStore();
162
- const account = enrollmentAnchorAccountFor(input.config.hqUrl, input.config.organizationId, input.config.deviceId);
184
+ const { hostScope, store: suppliedStore } = input;
185
+ const config = hostScope ? structuredClone(input.config) : input.config;
186
+ const account = enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId);
187
+ const store = await protectedStore(suppliedStore, hostScope);
163
188
  let serialized = await store.get(account);
164
189
  let migratedLegacy = false;
165
190
  if (!serialized) {
166
- serialized = await store.get(legacyEnrollmentAnchorAccountFor(input.config.hqUrl, input.config.organizationId));
191
+ serialized = await store.get(legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId));
167
192
  migratedLegacy = Boolean(serialized);
168
193
  }
169
194
  if (!serialized)
170
195
  throw new Error('Device enrollment is not anchored in secure storage. Run dharma login again.');
171
- const anchor = JSON.parse(serialized);
172
- if (!enrollmentAnchorHasBaseIdentity(anchor, input.config)
173
- || JSON.stringify(anchor.serverSigningKeyset ?? null) !== JSON.stringify(input.config.serverSigningKeyset ?? null)) {
196
+ const anchor = parseProtectedAnchor(serialized, hostScope, 'Protected enrollment anchor is corrupt.');
197
+ if (!enrollmentAnchorHasBaseIdentity(anchor, config)
198
+ || JSON.stringify(anchor.serverSigningKeyset ?? null) !== JSON.stringify(config.serverSigningKeyset ?? null)) {
174
199
  throw new Error('Device configuration does not match the secure enrollment anchor. Run dharma login again.');
175
200
  }
176
201
  if (migratedLegacy) {
@@ -187,7 +212,6 @@ export async function saveActiveSkillAuthorizationAnchor(input) {
187
212
  || (input.expiresAt !== null && !Number.isFinite(Date.parse(input.expiresAt)))) {
188
213
  throw new Error('Active skill authorization anchor is invalid.');
189
214
  }
190
- const store = input.store ?? await createSystemSecureStore();
191
215
  const anchor = {
192
216
  schema: 'dharma.active-skill-authorization-anchor/v1',
193
217
  organizationId: input.config.organizationId,
@@ -202,25 +226,28 @@ export async function saveActiveSkillAuthorizationAnchor(input) {
202
226
  };
203
227
  const serialized = JSON.stringify(anchor);
204
228
  const account = activeSkillAnchorAccountFor(input.config, input.workspaceId, input.provider);
229
+ const store = await protectedStore(input.store, input.hostScope);
205
230
  await store.put(account, serialized);
206
231
  if (await store.get(account) !== serialized)
207
232
  throw new Error('Secure store did not confirm the active skill anchor write.');
208
233
  return anchor;
209
234
  }
210
235
  export async function loadActiveSkillAuthorizationAnchor(input) {
211
- const store = input.store ?? await createSystemSecureStore();
212
- const account = activeSkillAnchorAccountFor(input.config, input.workspaceId, input.provider);
213
- const serialized = input.fresh && store.getFresh
236
+ const { workspaceId, organizationAgentId, provider, fresh, hostScope, store: suppliedStore } = input;
237
+ const config = { ...input.config };
238
+ const account = activeSkillAnchorAccountFor(config, workspaceId, provider);
239
+ const store = await protectedStore(suppliedStore, hostScope);
240
+ const serialized = fresh && store.getFresh
214
241
  ? await store.getFresh(account)
215
242
  : await store.get(account);
216
243
  if (!serialized)
217
244
  return null;
218
- const anchor = JSON.parse(serialized);
245
+ const anchor = parseProtectedAnchor(serialized, hostScope, 'Protected active skill authorization anchor is corrupt.');
219
246
  if (anchor.schema !== 'dharma.active-skill-authorization-anchor/v1'
220
- || anchor.organizationId !== input.config.organizationId || anchor.deviceId !== input.config.deviceId
221
- || anchor.organizationAgentId !== input.organizationAgentId
247
+ || anchor.organizationId !== config.organizationId || anchor.deviceId !== config.deviceId
248
+ || anchor.organizationAgentId !== organizationAgentId
222
249
  || !/^[0-9a-f-]{36}$/i.test(anchor.organizationAgentId)
223
- || anchor.workspaceId !== input.workspaceId || anchor.provider !== input.provider
250
+ || anchor.workspaceId !== workspaceId || anchor.provider !== provider
224
251
  || !/^[0-9a-f-]{36}$/i.test(anchor.bundleId) || !/^sha256:[a-f0-9]{64}$/i.test(anchor.receiptHash)
225
252
  || !Number.isFinite(Date.parse(anchor.activatedAt))
226
253
  || (anchor.expiresAt !== null && !Number.isFinite(Date.parse(anchor.expiresAt)))) {
@@ -229,18 +256,20 @@ export async function loadActiveSkillAuthorizationAnchor(input) {
229
256
  return anchor;
230
257
  }
231
258
  export async function deleteActiveSkillAuthorizationAnchor(input) {
232
- const store = input.store ?? await createSystemSecureStore();
233
259
  const account = activeSkillAnchorAccountFor(input.config, input.workspaceId, input.provider);
260
+ const store = await protectedStore(input.store, input.hostScope);
234
261
  await store.delete(account);
235
262
  if (await store.get(account) !== null)
236
263
  throw new Error('Secure store did not confirm the active skill anchor deletion.');
237
264
  }
238
265
  export async function loadEvidenceQuotaAnchor(input) {
239
- const store = input.store ?? await createSystemSecureStore();
240
- const value = await store.get(evidenceQuotaAccountFor(input.config.hqUrl, input.config.organizationId, input.config.deviceId));
266
+ const { hostScope, store: suppliedStore } = input;
267
+ const account = evidenceQuotaAccountFor(input.config.hqUrl, input.config.organizationId, input.config.deviceId);
268
+ const store = await protectedStore(suppliedStore, hostScope);
269
+ const value = await store.get(account);
241
270
  if (!value)
242
271
  return null;
243
- const anchor = JSON.parse(value);
272
+ const anchor = parseProtectedAnchor(value, hostScope, 'Protected evidence quota anchor is corrupt.');
244
273
  if (anchor.schema !== 'dharma.evidence-quota-anchor/v1'
245
274
  || !/^\d{4}-\d{2}-\d{2}$/.test(anchor.day)
246
275
  || !Number.isSafeInteger(anchor.totalBytes) || anchor.totalBytes < 0
@@ -251,15 +280,55 @@ export async function loadEvidenceQuotaAnchor(input) {
251
280
  return anchor;
252
281
  }
253
282
  export async function saveEvidenceQuotaAnchor(input) {
254
- const store = input.store ?? await createSystemSecureStore();
255
283
  const account = evidenceQuotaAccountFor(input.config.hqUrl, input.config.organizationId, input.config.deviceId);
256
- await store.put(account, JSON.stringify(input.anchor));
284
+ const serialized = JSON.stringify(input.anchor);
285
+ const store = await protectedStore(input.store, input.hostScope);
286
+ await store.put(account, serialized);
257
287
  const confirmed = await store.get(account);
258
- if (confirmed !== JSON.stringify(input.anchor)) {
288
+ if (confirmed !== serialized) {
259
289
  throw new Error('Secure store did not confirm the evidence quota anchor write.');
260
290
  }
261
291
  }
262
- async function atomicJson(path, value) {
292
+ async function atomicJson(path, value, fence) {
293
+ if (fence) {
294
+ await fence.step(() => mkdir(dirname(path), { recursive: true, mode: 0o700 }));
295
+ const temporary = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
296
+ let handle;
297
+ let owned = false;
298
+ try {
299
+ await fence.assert();
300
+ handle = await open(temporary, 'wx', 0o600);
301
+ owned = true;
302
+ await fence.assert();
303
+ await fence.step(() => handle.writeFile(`${JSON.stringify(value, null, 2)}\n`));
304
+ await fence.step(() => handle.sync());
305
+ await handle.close();
306
+ handle = undefined;
307
+ await fence.step(() => rename(temporary, path));
308
+ let directory;
309
+ try {
310
+ await fence.assert();
311
+ directory = await open(dirname(path), 'r');
312
+ await fence.assert();
313
+ await fence.step(() => directory.sync());
314
+ }
315
+ catch {
316
+ // Unsupported directory fsync is not permission to swallow withdrawal.
317
+ await fence.assert();
318
+ }
319
+ finally {
320
+ await directory?.close();
321
+ }
322
+ }
323
+ finally {
324
+ await handle?.close();
325
+ // Cleanup only this successfully created, random temporary. Never undo a
326
+ // committed state rename or remove another actor's file after withdrawal.
327
+ if (owned)
328
+ await rm(temporary, { force: true });
329
+ }
330
+ return;
331
+ }
263
332
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
264
333
  const temporary = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
265
334
  const handle = await open(temporary, 'wx', 0o600);
@@ -284,6 +353,43 @@ async function atomicJson(path, value) {
284
353
  // Directory fsync is unavailable on some supported hosts.
285
354
  }
286
355
  }
356
+ async function scopedResponseJson(response, fence) {
357
+ const invalid = () => new Error('relay_host_transport_response_invalid');
358
+ if (!response.body || Number(response.headers.get('content-length')) > 5_000_000)
359
+ throw invalid();
360
+ await fence.assert();
361
+ const reader = response.body.getReader();
362
+ const cancel = () => { void reader.cancel().catch(() => undefined); };
363
+ fence.signal.addEventListener('abort', cancel, { once: true });
364
+ const chunks = [];
365
+ let size = 0;
366
+ try {
367
+ await fence.assert();
368
+ while (true) {
369
+ const next = await fence.step(() => reader.read());
370
+ if (next.done)
371
+ break;
372
+ size += next.value.byteLength;
373
+ if (size > 5_000_000)
374
+ throw invalid();
375
+ chunks.push(next.value);
376
+ }
377
+ await fence.assert();
378
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
379
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
380
+ throw invalid();
381
+ return parsed;
382
+ }
383
+ catch {
384
+ await fence.assert();
385
+ throw invalid();
386
+ }
387
+ finally {
388
+ fence.signal.removeEventListener('abort', cancel);
389
+ await reader.cancel().catch(() => undefined);
390
+ reader.releaseLock();
391
+ }
392
+ }
287
393
  function errorMessage(body, status) {
288
394
  if (body && typeof body === 'object') {
289
395
  const record = body;
@@ -325,6 +431,32 @@ export async function loadOrCreateDeviceIdentity(input) {
325
431
  }
326
432
  return { account, privateJwk, publicKeyEd25519: privateJwk.x };
327
433
  }
434
+ async function existingHostDeviceIdentity(config, store) {
435
+ const account = accountFor(config.hqUrl, config.organizationId, config.installationId);
436
+ const current = await store.get(account);
437
+ const unavailable = () => new Error('relay_host_device_identity_unavailable');
438
+ if (!current)
439
+ throw unavailable();
440
+ try {
441
+ const privateJwk = JSON.parse(current);
442
+ if (privateJwk.kty !== 'OKP' || privateJwk.crv !== 'Ed25519'
443
+ || !/^[A-Za-z0-9_-]{43}$/.test(privateJwk.x ?? '') || !/^[A-Za-z0-9_-]{43}$/.test(privateJwk.d ?? ''))
444
+ throw unavailable();
445
+ return { account, privateJwk, publicKeyEd25519: privateJwk.x };
446
+ }
447
+ catch {
448
+ throw unavailable();
449
+ }
450
+ }
451
+ /** Read the accepted identity; never repair a missing key by generating one. */
452
+ export async function loadDeviceIdentity(input) {
453
+ const config = { ...input.config };
454
+ const store = await protectedStore(input.store, input.hostScope);
455
+ const identity = await existingHostDeviceIdentity(config, store);
456
+ if (identity.publicKeyEd25519 !== config.publicKeyEd25519)
457
+ throw new Error('relay_host_device_identity_unavailable');
458
+ return identity;
459
+ }
328
460
  export async function beginEnrollment(input) {
329
461
  const response = await (input.fetcher || fetch)(`${normalizeHqUrl(input.hqUrl)}/api/v1/agent-fabric/enrollments`, {
330
462
  method: 'POST', headers: { 'content-type': 'application/json', 'idempotency-key': input.idempotencyKey || randomUUID() },
@@ -466,8 +598,9 @@ export async function pollEnrollment(input) {
466
598
  throw new Error(errorMessage(body, response.status));
467
599
  return body;
468
600
  }
469
- export async function saveDeviceConfig(path, config) {
470
- await atomicJson(path, { ...config, hqUrl: normalizeHqUrl(config.hqUrl), relayUrl: normalizeRelayUrl(config.relayUrl) });
601
+ export async function saveDeviceConfig(path, config, hostScope) {
602
+ const fence = hostScope === undefined ? undefined : new HostOperationFence(hostScope);
603
+ await atomicJson(path, { ...config, hqUrl: normalizeHqUrl(config.hqUrl), relayUrl: normalizeRelayUrl(config.relayUrl) }, fence);
471
604
  }
472
605
  function verifyKeysetTransition(config, current, candidate, now) {
473
606
  return current
@@ -475,8 +608,15 @@ function verifyKeysetTransition(config, current, candidate, now) {
475
608
  : verifyInitialServerSigningKeyset(candidate, createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: config.serverPublicKeyEd25519 }, format: 'jwk' }), config.organizationId, now);
476
609
  }
477
610
  export async function recoverDeviceEnrollmentConsistency(input) {
478
- const config = await loadDeviceConfig(input.configPath);
479
- const store = input.store ?? await createSystemSecureStore();
611
+ return recoverEnrollmentWithFence({ ...input,
612
+ hostFence: input.hostScope === undefined ? undefined : new HostOperationFence(input.hostScope) });
613
+ }
614
+ async function recoverEnrollmentWithFence(input) {
615
+ const config = input.hostFence ? await input.hostFence.step(() => loadDeviceConfig(input.configPath))
616
+ : await loadDeviceConfig(input.configPath);
617
+ const rawStore = input.hostFence ? await input.hostFence.step(async () => input.store ?? await createSystemSecureStore())
618
+ : input.store ?? await createSystemSecureStore();
619
+ const store = input.hostFence ? input.hostFence.store(rawStore) : rawStore;
480
620
  const account = enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId);
481
621
  let serialized = await store.get(account);
482
622
  let migratedLegacy = false;
@@ -503,7 +643,7 @@ export async function recoverDeviceEnrollmentConsistency(input) {
503
643
  const verification = verifyKeysetTransition(config, config.serverSigningKeyset, anchor.serverSigningKeyset, now);
504
644
  if (verification.ok) {
505
645
  const recovered = { ...config, serverSigningKeyset: anchor.serverSigningKeyset };
506
- await saveDeviceConfig(input.configPath, recovered);
646
+ await atomicJson(input.configPath, recovered, input.hostFence);
507
647
  return recovered;
508
648
  }
509
649
  }
@@ -517,8 +657,14 @@ export async function recoverDeviceEnrollmentConsistency(input) {
517
657
  throw new Error('Interrupted server signing keyset installation could not be verified. Run dharma login again.');
518
658
  }
519
659
  export async function installTrustedServerSigningKeyset(input) {
520
- const store = input.store ?? await createSystemSecureStore();
521
- const config = await recoverDeviceEnrollmentConsistency({ configPath: input.configPath, store, now: input.now });
660
+ return installKeysetWithFence({ ...input,
661
+ hostFence: input.hostScope === undefined ? undefined : new HostOperationFence(input.hostScope) });
662
+ }
663
+ async function installKeysetWithFence(input) {
664
+ const rawStore = input.hostFence ? await input.hostFence.step(async () => input.store ?? await createSystemSecureStore())
665
+ : input.store ?? await createSystemSecureStore();
666
+ const store = input.hostFence ? input.hostFence.store(rawStore) : rawStore;
667
+ const config = await recoverEnrollmentWithFence({ configPath: input.configPath, store, now: input.now, hostFence: input.hostFence });
522
668
  const now = input.now ?? new Date();
523
669
  if (canonicalize(config.serverSigningKeyset ?? null) === canonicalize(input.candidate))
524
670
  return config;
@@ -529,7 +675,7 @@ export async function installTrustedServerSigningKeyset(input) {
529
675
  // The protected anchor is the write-ahead record. If the process stops before
530
676
  // the disk configuration is replaced, startup verifies and completes it.
531
677
  await saveDeviceEnrollmentAnchor({ config: next, store });
532
- await saveDeviceConfig(input.configPath, next);
678
+ await atomicJson(input.configPath, next, input.hostFence);
533
679
  return next;
534
680
  }
535
681
  export async function loadDeviceConfig(path) {
@@ -548,6 +694,8 @@ export class AgentFabricClient {
548
694
  #store;
549
695
  #fetcher;
550
696
  #directTransport;
697
+ #hostFence;
698
+ #hostBinding;
551
699
  #state;
552
700
  #serial = Promise.resolve();
553
701
  constructor(input) {
@@ -559,11 +707,35 @@ export class AgentFabricClient {
559
707
  this.#state = input.state;
560
708
  this.#fetcher = input.fetcher || fetch;
561
709
  this.#directTransport = Boolean(input.fetcher);
710
+ this.#hostFence = input.hostFence;
711
+ this.#hostBinding = this.#binding();
712
+ }
713
+ #binding() {
714
+ const { schema, organizationId, deviceId, installationId, hqUrl, relayUrl, publicKeyEd25519, serverPublicKeyEd25519, enrolledAt, platform, setupClaimReference, setupClaimRepositoryFingerprint } = this.config;
715
+ return canonicalize({ organizationId, deviceId, installationId: installationId ?? null, hqUrl, relayUrl,
716
+ publicKeyEd25519, serverPublicKeyEd25519, enrolledAt, platform, schema,
717
+ setupClaimReference: setupClaimReference ?? null, setupClaimRepositoryFingerprint: setupClaimRepositoryFingerprint ?? null });
718
+ }
719
+ async #assertHostScope() {
720
+ if (!this.#hostFence)
721
+ return;
722
+ try {
723
+ if (this.#binding() !== this.#hostBinding)
724
+ this.#hostFence.withdraw();
725
+ }
726
+ catch {
727
+ this.#hostFence.withdraw();
728
+ }
729
+ await this.#hostFence.assert();
562
730
  }
563
731
  static async open(input) {
564
- const store = input.store ?? await createSystemSecureStore();
565
- const config = await recoverDeviceEnrollmentConsistency({ configPath: input.configPath, store });
566
- const identity = await loadOrCreateDeviceIdentity({
732
+ const { configPath, statePath, store: suppliedStore, fetcher, hostScope } = input;
733
+ const fence = hostScope === undefined ? undefined : new HostOperationFence(hostScope);
734
+ const rawStore = fence ? await fence.step(async () => suppliedStore ?? await createSystemSecureStore())
735
+ : suppliedStore ?? await createSystemSecureStore();
736
+ const store = fence ? fence.store(rawStore) : rawStore;
737
+ const config = await recoverEnrollmentWithFence({ configPath, store, hostFence: fence });
738
+ const identity = fence ? await existingHostDeviceIdentity(config, store) : await loadOrCreateDeviceIdentity({
567
739
  hqUrl: config.hqUrl,
568
740
  organizationId: config.organizationId,
569
741
  installationId: config.installationId,
@@ -584,22 +756,27 @@ export class AgentFabricClient {
584
756
  recoveredTaskCompletions: [],
585
757
  };
586
758
  try {
587
- const parsed = JSON.parse(await readFile(input.statePath, 'utf8'));
759
+ const bytes = fence ? await fence.step(() => readFile(statePath, 'utf8')) : await readFile(statePath, 'utf8');
760
+ const parsed = JSON.parse(bytes);
588
761
  assertProtocolState(parsed);
589
762
  state = parsed;
590
763
  }
591
764
  catch (error) {
592
765
  if (error.code !== 'ENOENT') {
766
+ if (fence)
767
+ await fence.assert();
593
768
  throw new Error('Relay protocol state is invalid; preserve the file for recovery and re-enroll if necessary.', { cause: error });
594
769
  }
595
770
  }
596
771
  state.recoveredTaskCompletions ??= [];
772
+ await fence?.assert();
597
773
  return new AgentFabricClient({
598
- config, privateJwk: identity.privateJwk, configPath: input.configPath,
599
- statePath: input.statePath, state, store, fetcher: input.fetcher,
774
+ config, privateJwk: identity.privateJwk, configPath,
775
+ statePath, state, store, fetcher, hostFence: fence,
600
776
  });
601
777
  }
602
778
  async openSession(relayVersion = '0.1.0') {
779
+ await this.#assertHostScope();
603
780
  if (this.#state.pending && isExplicitlyRebuiltPath(this.#state.pending.pathname)) {
604
781
  // Content-bearing requests require refreshed consent. Repository connect
605
782
  // requests depend on current workspace registration. Both are rebuilt by
@@ -622,10 +799,11 @@ export class AgentFabricClient {
622
799
  async registerWorkspace(body) {
623
800
  const response = await this.signedPost('/agent-fabric/workspaces', body);
624
801
  if (response.serverSigningKeyset !== undefined) {
625
- const next = await installTrustedServerSigningKeyset({
802
+ const next = await installKeysetWithFence({
626
803
  configPath: this.#configPath,
627
804
  candidate: response.serverSigningKeyset,
628
805
  store: this.#store,
806
+ hostFence: this.#hostFence,
629
807
  });
630
808
  Object.assign(this.config, next);
631
809
  }
@@ -659,6 +837,7 @@ export class AgentFabricClient {
659
837
  }
660
838
  acknowledgeRecoveredTaskCompletion(taskId, receiptHash) {
661
839
  const operation = this.#serial.then(async () => {
840
+ await this.#assertHostScope();
662
841
  const current = this.#state.recoveredTaskCompletions || [];
663
842
  const matching = current.find((item) => item.taskId === taskId);
664
843
  if (!matching)
@@ -701,6 +880,7 @@ export class AgentFabricClient {
701
880
  return operation;
702
881
  }
703
882
  async #signedRequestNow(method, route, body) {
883
+ await this.#assertHostScope();
704
884
  if (!this.#state.sessionId)
705
885
  throw new Error('Relay session is not open.');
706
886
  const pathname = `/api/v1/orgs/${encodeURIComponent(this.config.organizationId)}${route}`;
@@ -724,6 +904,7 @@ export class AgentFabricClient {
724
904
  return recovered;
725
905
  }
726
906
  const timestamp = new Date().toISOString();
907
+ await this.#assertHostScope();
727
908
  const messageId = randomUUID();
728
909
  const nonce = randomBytes(24).toString('base64url');
729
910
  const sequence = this.#state.nextSequence;
@@ -752,6 +933,7 @@ export class AgentFabricClient {
752
933
  return this.#sendPending();
753
934
  }
754
935
  async #sendPending() {
936
+ await this.#assertHostScope();
755
937
  const pending = this.#state.pending;
756
938
  if (!pending)
757
939
  throw new Error('No pending protocol request.');
@@ -829,16 +1011,34 @@ export class AgentFabricClient {
829
1011
  let status;
830
1012
  let body;
831
1013
  if (this.#directTransport) {
832
- const response = await this.#fetcher(`${this.config.hqUrl.replace(/\/$/, '')}${pending.pathname}`, {
833
- method: pending.method,
834
- headers: pending.headers,
835
- body: pending.method === 'GET' ? undefined : pending.body,
836
- });
837
- status = response.status;
838
- body = await response.json();
1014
+ await this.#assertHostScope();
1015
+ const url = `${this.config.hqUrl.replace(/\/$/, '')}${pending.pathname}`;
1016
+ let response;
1017
+ try {
1018
+ response = await this.#fetcher(url, {
1019
+ method: pending.method, headers: pending.headers,
1020
+ body: pending.method === 'GET' ? undefined : pending.body,
1021
+ ...(this.#hostFence ? { signal: this.#hostFence.signal, redirect: 'error' } : {}),
1022
+ });
1023
+ await this.#assertHostScope();
1024
+ if (this.#hostFence && (response.redirected || response.url && response.url !== url)) {
1025
+ throw new Error('relay_host_transport_response_invalid');
1026
+ }
1027
+ status = response.status;
1028
+ body = this.#hostFence ? await scopedResponseJson(response, this.#hostFence)
1029
+ : await response.json();
1030
+ }
1031
+ catch (error) {
1032
+ if (this.#hostFence) {
1033
+ await response?.body?.cancel().catch(() => undefined);
1034
+ await this.#assertHostScope();
1035
+ }
1036
+ throw error;
1037
+ }
839
1038
  }
840
1039
  else {
841
1040
  const response = await this.#sendViaRelay(pending);
1041
+ await this.#assertHostScope();
842
1042
  status = response.status;
843
1043
  try {
844
1044
  body = JSON.parse(response.body);
@@ -847,6 +1047,7 @@ export class AgentFabricClient {
847
1047
  body = { ok: false, error: { code: 'invalid_relay_response', message: 'Relay returned invalid JSON.' } };
848
1048
  }
849
1049
  }
1050
+ await this.#assertHostScope();
850
1051
  if (status < 200 || status >= 300) {
851
1052
  // A deterministic client rejection is an acknowledgement, not an unknown
852
1053
  // delivery outcome. Retaining it would permanently block the device
@@ -933,7 +1134,8 @@ export class AgentFabricClient {
933
1134
  throw new Error('Recovered task completion queue is full; acknowledge stored completions before sending another completion.');
934
1135
  }
935
1136
  }
936
- #sendViaRelay(pending) {
1137
+ async #sendViaRelay(pending) {
1138
+ await this.#assertHostScope();
937
1139
  return new Promise((accept, reject) => {
938
1140
  const relay = new URL(normalizeRelayUrl(this.config.relayUrl));
939
1141
  relay.pathname = '/v1/connect';
@@ -945,16 +1147,32 @@ export class AgentFabricClient {
945
1147
  return;
946
1148
  settled = true;
947
1149
  clearTimeout(timeout);
1150
+ this.#hostFence?.signal.removeEventListener('abort', abort);
948
1151
  callback();
949
1152
  if (closeSocket && socket.readyState < WebSocket.CLOSING)
950
1153
  socket.close(1000);
951
1154
  };
952
1155
  const timeout = setTimeout(() => finish(() => reject(new Error('Relay response timed out.'))), RELAY_ACKNOWLEDGEMENT_TIMEOUT_MS);
953
- socket.addEventListener('open', () => socket.send(JSON.stringify({
954
- requestId: pending.headers['x-dharma-message-id'], method: pending.method,
955
- pathname: pending.pathname, headers: pending.headers, body: pending.body,
956
- })));
1156
+ const abort = () => finish(() => reject(new Error('relay_host_scope_unavailable')));
1157
+ this.#hostFence?.signal.addEventListener('abort', abort, { once: true });
1158
+ if (this.#hostFence?.signal.aborted)
1159
+ abort();
1160
+ socket.addEventListener('open', () => {
1161
+ const send = () => {
1162
+ if (!settled)
1163
+ socket.send(JSON.stringify({
1164
+ requestId: pending.headers['x-dharma-message-id'], method: pending.method,
1165
+ pathname: pending.pathname, headers: pending.headers, body: pending.body,
1166
+ }));
1167
+ };
1168
+ if (!this.#hostFence)
1169
+ send();
1170
+ else
1171
+ void this.#assertHostScope().then(send).catch(error => finish(() => reject(error)));
1172
+ });
957
1173
  socket.addEventListener('message', (event) => {
1174
+ if (settled)
1175
+ return;
958
1176
  try {
959
1177
  const response = JSON.parse(String(event.data));
960
1178
  if (response.requestId !== pending.headers['x-dharma-message-id'])
@@ -971,14 +1189,15 @@ export class AgentFabricClient {
971
1189
  });
972
1190
  });
973
1191
  }
974
- #persist() {
1192
+ async #persist() {
1193
+ await this.#assertHostScope();
975
1194
  // Authorized content and state-dependent repository connects are rebuilt
976
1195
  // from their governed source. Do not retain them as an automatic replay
977
1196
  // that can outlive consent or the workspace registration they depend on.
978
1197
  const durableState = this.#state.pending && isExplicitlyRebuiltPath(this.#state.pending.pathname)
979
1198
  ? { ...this.#state, nextSequence: this.#state.nextSequence + 1, pending: null }
980
1199
  : this.#state;
981
- return atomicJson(this.#statePath, durableState);
1200
+ return atomicJson(this.#statePath, durableState, this.#hostFence);
982
1201
  }
983
1202
  }
984
1203
  export const RELAY_ACKNOWLEDGEMENT_TIMEOUT_MS = 90_000;