@dharma-ai-labs/agent-fabric-relay-client 0.2.31 → 0.2.32

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,7 +1,9 @@
1
1
  import { createHash, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto';
2
2
  import { mkdir, open, readFile, rename, rm } from 'node:fs/promises';
3
- import { dirname } from 'node:path';
4
- import { canonicalize, refreshActionDecisionAcknowledgement, validateActionDecisionAcknowledgementContract, verifyInitialServerSigningKeyset, verifyServerSigningKeysetUpdate, } from '@dharma-ai-labs/agent-fabric-contracts';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { userInfo } from 'node:os';
5
+ import { acquireEnrollmentAnchorLock } from './enrollmentAnchorLock.js';
6
+ import { canonicalize, refreshActionDecisionAcknowledgement, validateActionDecisionAcknowledgementContract, verifyInitialServerSigningKeyset, verifyServerSigningKeysetUpdate, validateDeviceConfigContract, validateDeviceConnectionPreferenceContract, } from '@dharma-ai-labs/agent-fabric-contracts';
5
7
  import { createSystemSecureStore } from '@dharma-ai-labs/agent-fabric-secure-store';
6
8
  import { HostOperationFence } from './hostOperationScope.js';
7
9
  export { claimSetupReference, setupClaimSourceRegistration } from './setupClaim.js';
@@ -170,26 +172,120 @@ function enrollmentAnchorHasBaseIdentity(anchor, config) {
170
172
  && anchor.enrolledAt === config.enrolledAt
171
173
  && Number.isFinite(Date.parse(anchor.enrolledAt));
172
174
  }
175
+ // The namespace follows the OS user and protected legacy account, rather than
176
+ // DHARMA_HOME/configPath. Different configured homes share the same anchor lock.
177
+ async function withEnrollmentAnchorLock(config, fence, operation) {
178
+ const identity = userInfo();
179
+ const user = createHash('sha256').update(identity.homedir + ':' + identity.username).digest('hex').slice(0, 32);
180
+ const account = legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId);
181
+ // Use a stable OS-user path even when callers override HOME, TMPDIR or DHARMA_HOME.
182
+ const temporaryRoot = process.platform === 'win32' ? resolve(identity.homedir, 'AppData', 'Local', 'Temp') : '/tmp';
183
+ const path = resolve(temporaryRoot, `dharma-enrollment-locks-${user}`, `${account}.lock`);
184
+ let release;
185
+ try {
186
+ release = await acquireEnrollmentAnchorLock(path, fence);
187
+ return fence ? await fence.step(operation) : await operation();
188
+ }
189
+ finally {
190
+ await release?.();
191
+ }
192
+ }
193
+ async function freshAnchorValue(store, account) {
194
+ return (store.getFresh ?? store.get).call(store, account);
195
+ }
196
+ async function writeEnrollmentAnchor(store, config, secret, expectedCurrent, expectedLegacy) {
197
+ const account = enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId);
198
+ if (store.backend === 'windows-credential-manager') {
199
+ if (!store.compareAndPutEnrollmentAnchor)
200
+ throw Error('connection_anchor_store_unavailable');
201
+ const written = await store.compareAndPutEnrollmentAnchor({ account, secret, expectedCurrent, expectedLegacy,
202
+ legacyAccount: legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId) });
203
+ if (!written)
204
+ throw Error('connection_existing_anchor_requires_recovery');
205
+ }
206
+ else {
207
+ await store.put(account, secret);
208
+ }
209
+ }
210
+ /** Missing-anchor recovery must prove both current and historical slots absent. */
211
+ export async function assertDeviceEnrollmentAnchorAbsent(input) {
212
+ const config = input.config;
213
+ let values;
214
+ try {
215
+ const store = await protectedStore(input.store, input.hostScope);
216
+ const get = (account) => store.getFresh ? store.getFresh(account) : store.get(account);
217
+ values = await Promise.all([
218
+ get(enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId)),
219
+ get(legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId)),
220
+ ]);
221
+ }
222
+ catch {
223
+ throw new Error('connection_anchor_store_unavailable');
224
+ }
225
+ if (values.some(value => value !== null))
226
+ throw new Error('connection_existing_anchor_requires_recovery');
227
+ }
173
228
  export async function saveDeviceEnrollmentAnchor(input) {
174
- const anchor = enrollmentAnchorFromConfig(input.hostScope ? structuredClone(input.config) : input.config);
229
+ const config = structuredClone(input.config);
230
+ const fence = input.hostScope ? new HostOperationFence(input.hostScope) : undefined;
231
+ return withEnrollmentAnchorLock(config, fence, () => saveEnrollmentAnchorLocked({ ...input, config }));
232
+ }
233
+ async function saveEnrollmentAnchorLocked(input) {
234
+ const anchor = enrollmentAnchorFromConfig(input.config);
175
235
  const serialized = JSON.stringify(anchor);
176
236
  const account = enrollmentAnchorAccountFor(anchor.hqUrl, anchor.organizationId, anchor.deviceId);
177
237
  const store = await protectedStore(input.store, input.hostScope);
178
- await store.put(account, serialized);
179
- if (await store.get(account) !== serialized)
238
+ let previous, legacy;
239
+ try {
240
+ previous = await freshAnchorValue(store, account);
241
+ legacy = input.requireAbsent || store.backend === 'windows-credential-manager'
242
+ ? await freshAnchorValue(store, legacyEnrollmentAnchorAccountFor(anchor.hqUrl, anchor.organizationId)) : null;
243
+ }
244
+ catch (error) {
245
+ if (input.requireAbsent)
246
+ throw Error('connection_anchor_store_unavailable');
247
+ throw error;
248
+ }
249
+ if (input.requireAbsent) {
250
+ if (previous !== null || legacy !== null)
251
+ throw Error('connection_existing_anchor_requires_recovery');
252
+ }
253
+ else {
254
+ if (previous !== null) {
255
+ const existing = parseProtectedAnchor(previous, input.hostScope, 'Protected enrollment anchor is corrupt.');
256
+ if (!enrollmentAnchorHasBaseIdentity(existing, input.config)) {
257
+ throw new Error('connection_existing_anchor_requires_recovery');
258
+ }
259
+ if (canonicalize(existing.serverSigningKeyset ?? null) !== canonicalize(anchor.serverSigningKeyset ?? null)) {
260
+ if (!anchor.serverSigningKeyset
261
+ || !verifyKeysetTransition(input.config, existing.serverSigningKeyset, anchor.serverSigningKeyset, input.now ?? new Date()).ok) {
262
+ throw new Error('connection_existing_anchor_requires_recovery');
263
+ }
264
+ }
265
+ }
266
+ }
267
+ await writeEnrollmentAnchor(store, input.config, serialized, previous, legacy);
268
+ if (await freshAnchorValue(store, account) !== serialized)
180
269
  throw new Error('Secure store did not confirm the enrollment anchor write.');
181
270
  return anchor;
182
271
  }
183
272
  export async function loadDeviceEnrollmentAnchor(input) {
273
+ if (input.readOnly)
274
+ return loadEnrollmentAnchorLocked(input);
275
+ const config = structuredClone(input.config);
276
+ const fence = input.hostScope ? new HostOperationFence(input.hostScope) : undefined;
277
+ return withEnrollmentAnchorLock(config, fence, () => loadEnrollmentAnchorLocked({ ...input, config }));
278
+ }
279
+ async function loadEnrollmentAnchorLocked(input) {
184
280
  const { hostScope, store: suppliedStore } = input;
185
281
  const config = hostScope ? structuredClone(input.config) : input.config;
186
282
  const account = enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId);
187
283
  const store = await protectedStore(suppliedStore, hostScope);
188
- let serialized = await store.get(account);
284
+ let serialized = await freshAnchorValue(store, account);
189
285
  let migratedLegacy = false;
190
- if (!serialized) {
191
- serialized = await store.get(legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId));
192
- migratedLegacy = Boolean(serialized);
286
+ if (serialized === null) {
287
+ serialized = await freshAnchorValue(store, legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId));
288
+ migratedLegacy = serialized !== null;
193
289
  }
194
290
  if (!serialized)
195
291
  throw new Error('Device enrollment is not anchored in secure storage. Run dharma login again.');
@@ -198,9 +294,9 @@ export async function loadDeviceEnrollmentAnchor(input) {
198
294
  || JSON.stringify(anchor.serverSigningKeyset ?? null) !== JSON.stringify(config.serverSigningKeyset ?? null)) {
199
295
  throw new Error('Device configuration does not match the secure enrollment anchor. Run dharma login again.');
200
296
  }
201
- if (migratedLegacy) {
202
- await store.put(account, serialized);
203
- if (await store.get(account) !== serialized)
297
+ if (migratedLegacy && !input.readOnly) {
298
+ await writeEnrollmentAnchor(store, config, serialized, null, serialized);
299
+ if (await freshAnchorValue(store, account) !== serialized)
204
300
  throw new Error('Secure store did not confirm the enrollment anchor migration.');
205
301
  }
206
302
  return anchor;
@@ -614,15 +710,23 @@ export async function recoverDeviceEnrollmentConsistency(input) {
614
710
  async function recoverEnrollmentWithFence(input) {
615
711
  const config = input.hostFence ? await input.hostFence.step(() => loadDeviceConfig(input.configPath))
616
712
  : await loadDeviceConfig(input.configPath);
713
+ return withEnrollmentAnchorLock(config, input.hostFence, () => recoverEnrollmentLocked({ ...input, lockedConfig: config }));
714
+ }
715
+ async function recoverEnrollmentLocked(input) {
716
+ const config = input.hostFence ? await input.hostFence.step(() => loadDeviceConfig(input.configPath))
717
+ : await loadDeviceConfig(input.configPath);
718
+ if (!enrollmentAnchorHasBaseIdentity(enrollmentAnchorFromConfig(input.lockedConfig), config)) {
719
+ throw new Error('connection_enrollment_changed');
720
+ }
617
721
  const rawStore = input.hostFence ? await input.hostFence.step(async () => input.store ?? await createSystemSecureStore())
618
722
  : input.store ?? await createSystemSecureStore();
619
723
  const store = input.hostFence ? input.hostFence.store(rawStore) : rawStore;
620
724
  const account = enrollmentAnchorAccountFor(config.hqUrl, config.organizationId, config.deviceId);
621
- let serialized = await store.get(account);
725
+ let serialized = await freshAnchorValue(store, account);
622
726
  let migratedLegacy = false;
623
- if (!serialized) {
624
- serialized = await store.get(legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId));
625
- migratedLegacy = Boolean(serialized);
727
+ if (serialized === null) {
728
+ serialized = await freshAnchorValue(store, legacyEnrollmentAnchorAccountFor(config.hqUrl, config.organizationId));
729
+ migratedLegacy = serialized !== null;
626
730
  }
627
731
  if (!serialized)
628
732
  return config;
@@ -631,8 +735,8 @@ async function recoverEnrollmentWithFence(input) {
631
735
  throw new Error('Device configuration does not match the secure enrollment anchor. Run dharma login again.');
632
736
  }
633
737
  if (migratedLegacy) {
634
- await store.put(account, serialized);
635
- if (await store.get(account) !== serialized)
738
+ await writeEnrollmentAnchor(store, config, serialized, null, serialized);
739
+ if (await freshAnchorValue(store, account) !== serialized)
636
740
  throw new Error('Secure store did not confirm the enrollment anchor migration.');
637
741
  }
638
742
  if (canonicalize(anchor.serverSigningKeyset ?? null) === canonicalize(config.serverSigningKeyset ?? null)) {
@@ -650,7 +754,7 @@ async function recoverEnrollmentWithFence(input) {
650
754
  if (config.serverSigningKeyset) {
651
755
  const verification = verifyKeysetTransition(config, anchor.serverSigningKeyset, config.serverSigningKeyset, now);
652
756
  if (verification.ok) {
653
- await saveDeviceEnrollmentAnchor({ config, store });
757
+ await saveEnrollmentAnchorLocked({ config, store, now });
654
758
  return config;
655
759
  }
656
760
  }
@@ -661,10 +765,16 @@ export async function installTrustedServerSigningKeyset(input) {
661
765
  hostFence: input.hostScope === undefined ? undefined : new HostOperationFence(input.hostScope) });
662
766
  }
663
767
  async function installKeysetWithFence(input) {
768
+ const config = input.hostFence ? await input.hostFence.step(() => loadDeviceConfig(input.configPath))
769
+ : await loadDeviceConfig(input.configPath);
770
+ return withEnrollmentAnchorLock(config, input.hostFence, () => installKeysetLocked({ ...input, lockedConfig: config }));
771
+ }
772
+ async function installKeysetLocked(input) {
664
773
  const rawStore = input.hostFence ? await input.hostFence.step(async () => input.store ?? await createSystemSecureStore())
665
774
  : input.store ?? await createSystemSecureStore();
666
775
  const store = input.hostFence ? input.hostFence.store(rawStore) : rawStore;
667
- const config = await recoverEnrollmentWithFence({ configPath: input.configPath, store, now: input.now, hostFence: input.hostFence });
776
+ const config = await recoverEnrollmentLocked({ configPath: input.configPath, store, now: input.now,
777
+ hostFence: input.hostFence, lockedConfig: input.lockedConfig });
668
778
  const now = input.now ?? new Date();
669
779
  if (canonicalize(config.serverSigningKeyset ?? null) === canonicalize(input.candidate))
670
780
  return config;
@@ -674,17 +784,83 @@ async function installKeysetWithFence(input) {
674
784
  const next = { ...config, serverSigningKeyset: input.candidate };
675
785
  // The protected anchor is the write-ahead record. If the process stops before
676
786
  // the disk configuration is replaced, startup verifies and completes it.
677
- await saveDeviceEnrollmentAnchor({ config: next, store });
787
+ await saveEnrollmentAnchorLocked({ config: next, store, now });
678
788
  await atomicJson(input.configPath, next, input.hostFence);
679
789
  return next;
680
790
  }
791
+ export function parseDeviceConfig(bytes) {
792
+ let value;
793
+ try {
794
+ value = JSON.parse(bytes);
795
+ }
796
+ catch {
797
+ throw new Error('connection_config_corrupt');
798
+ }
799
+ if (!validateDeviceConfigContract(value))
800
+ throw new Error('connection_config_invalid');
801
+ const config = value;
802
+ try {
803
+ assertInstallationId(config.installationId);
804
+ return { ...config, hqUrl: normalizeHqUrl(config.hqUrl), relayUrl: normalizeRelayUrl(config.relayUrl) };
805
+ }
806
+ catch {
807
+ throw new Error('connection_config_invalid');
808
+ }
809
+ }
681
810
  export async function loadDeviceConfig(path) {
682
- const config = JSON.parse(await readFile(path, 'utf8'));
683
- if (config.schema !== 'dharma.device-config/v1' || !config.deviceId || !config.organizationId || !config.hqUrl) {
684
- throw new Error('Device is not enrolled. Run dharma login.');
811
+ let bytes;
812
+ try {
813
+ bytes = await readFile(path, 'utf8');
685
814
  }
686
- assertInstallationId(config.installationId);
687
- return { ...config, hqUrl: normalizeHqUrl(config.hqUrl), relayUrl: normalizeRelayUrl(config.relayUrl) };
815
+ catch (error) {
816
+ if (error.code === 'ENOENT')
817
+ throw error;
818
+ throw new Error('connection_config_unreadable');
819
+ }
820
+ return readDeviceConnectionPreference(path, parseDeviceConfig(bytes));
821
+ }
822
+ function connectionPreferenceBinding(config) {
823
+ const { schema, hqUrl, organizationId, installationId, deviceId, publicKeyEd25519, serverPublicKeyEd25519, relayUrl, enrolledAt } = config;
824
+ return sha256(canonicalize({ schema, hqUrl, organizationId, installationId: installationId ?? null,
825
+ deviceId, publicKeyEd25519, serverPublicKeyEd25519, relayUrl, enrolledAt }));
826
+ }
827
+ /** Separate local preference from trust snapshots so a delayed keyset write cannot overwrite opt-out. */
828
+ export async function readDeviceConnectionPreference(path, config) {
829
+ const binding = connectionPreferenceBinding(config);
830
+ let bytes;
831
+ try {
832
+ bytes = await readFile(`${path}.connection.json`, 'utf8');
833
+ }
834
+ catch (error) {
835
+ if (error.code === 'ENOENT')
836
+ return config;
837
+ throw new Error('connection_preference_unreadable');
838
+ }
839
+ let value;
840
+ try {
841
+ value = JSON.parse(bytes);
842
+ }
843
+ catch {
844
+ throw new Error('connection_preference_corrupt');
845
+ }
846
+ if (!validateDeviceConnectionPreferenceContract(value))
847
+ throw new Error('connection_preference_invalid');
848
+ // A changed scope cannot inherit consent or resurrect an older inline opt-in.
849
+ if (value.binding !== binding)
850
+ return { ...config, connectionMode: 'manual' };
851
+ return { ...config, connectionMode: value.connectionMode };
852
+ }
853
+ export async function saveDeviceConnectionPreference(input) {
854
+ if (input.connectionMode !== 'manual' && input.connectionMode !== 'resume')
855
+ throw new Error('connection_preference_invalid');
856
+ const fence = input.hostScope === undefined ? undefined : new HostOperationFence(input.hostScope);
857
+ const binding = connectionPreferenceBinding(input.config);
858
+ const current = fence ? await fence.step(() => loadDeviceConfig(input.configPath)) : await loadDeviceConfig(input.configPath);
859
+ if (connectionPreferenceBinding(current) !== binding)
860
+ throw new Error('connection_state_changed');
861
+ const preference = { schema: 'dharma.device-connection-preference/v1',
862
+ binding, connectionMode: input.connectionMode };
863
+ await atomicJson(`${input.configPath}.connection.json`, preference, fence);
688
864
  }
689
865
  export class AgentFabricClient {
690
866
  config;
@@ -697,6 +873,7 @@ export class AgentFabricClient {
697
873
  #hostFence;
698
874
  #hostBinding;
699
875
  #readOnly;
876
+ #isolatedSession;
700
877
  #readSessionAdmissionUsed = false;
701
878
  #state;
702
879
  #serial = Promise.resolve();
@@ -712,6 +889,7 @@ export class AgentFabricClient {
712
889
  this.#hostFence = input.hostFence;
713
890
  this.#hostBinding = this.#binding();
714
891
  this.#readOnly = input.readOnly === true;
892
+ this.#isolatedSession = input.isolatedSession === true;
715
893
  }
716
894
  #binding() {
717
895
  const { schema, organizationId, deviceId, installationId, hqUrl, relayUrl, publicKeyEd25519, serverPublicKeyEd25519, enrolledAt, platform, setupClaimReference, setupClaimRepositoryFingerprint } = this.config;
@@ -732,9 +910,11 @@ export class AgentFabricClient {
732
910
  await this.#hostFence.assert();
733
911
  }
734
912
  static async open(input) {
735
- const { configPath, statePath, store: suppliedStore, fetcher, hostScope, readOnly } = input;
913
+ const { configPath, statePath, store: suppliedStore, fetcher, hostScope, readOnly, isolatedSession } = input;
736
914
  if (readOnly !== undefined && typeof readOnly !== 'boolean')
737
915
  throw new Error('relay_read_only_option_invalid');
916
+ if (isolatedSession !== undefined && typeof isolatedSession !== 'boolean')
917
+ throw new Error('relay_isolated_session_option_invalid');
738
918
  const fence = hostScope === undefined ? undefined : new HostOperationFence(hostScope);
739
919
  const rawStore = fence ? await fence.step(async () => suppliedStore ?? await createSystemSecureStore())
740
920
  : suppliedStore ?? await createSystemSecureStore();
@@ -743,18 +923,13 @@ export class AgentFabricClient {
743
923
  put: async () => { throw new Error('relay_read_only_secure_store_write_denied'); },
744
924
  delete: async () => { throw new Error('relay_read_only_secure_store_write_denied'); } } : rawStore;
745
925
  const store = fence ? fence.store(safeStore) : safeStore;
746
- const config = readOnly ? (fence ? await fence.step(() => loadDeviceConfig(configPath)) : await loadDeviceConfig(configPath))
926
+ const config = readOnly || isolatedSession ? (fence ? await fence.step(() => loadDeviceConfig(configPath)) : await loadDeviceConfig(configPath))
747
927
  : await recoverEnrollmentWithFence({ configPath, store, hostFence: fence });
748
- const identity = fence || readOnly ? await existingHostDeviceIdentity(config, store) : await loadOrCreateDeviceIdentity({
749
- hqUrl: config.hqUrl,
750
- organizationId: config.organizationId,
751
- installationId: config.installationId,
752
- store,
753
- });
928
+ const identity = await existingHostDeviceIdentity(config, store);
754
929
  if (identity.publicKeyEd25519 !== config.publicKeyEd25519)
755
930
  throw new Error('Enrolled device identity does not match the secure store.');
756
931
  try {
757
- await loadDeviceEnrollmentAnchor({ config, store });
932
+ await loadDeviceEnrollmentAnchor({ config, store, readOnly: readOnly || isolatedSession });
758
933
  }
759
934
  catch (error) {
760
935
  if (!(error instanceof Error) || !error.message.includes('not anchored in secure storage'))
@@ -765,7 +940,7 @@ export class AgentFabricClient {
765
940
  schema: 'dharma.protocol-state/v1', sessionId: null, nextSequence: 1, pending: null,
766
941
  recoveredTaskCompletions: [],
767
942
  };
768
- if (!readOnly)
943
+ if (!readOnly && !isolatedSession)
769
944
  try {
770
945
  const bytes = fence ? await fence.step(() => readFile(statePath, 'utf8')) : await readFile(statePath, 'utf8');
771
946
  const parsed = JSON.parse(bytes);
@@ -783,7 +958,7 @@ export class AgentFabricClient {
783
958
  await fence?.assert();
784
959
  return new AgentFabricClient({
785
960
  config, privateJwk: identity.privateJwk, configPath,
786
- statePath, state, store, fetcher, hostFence: fence, readOnly,
961
+ statePath, state, store, fetcher, hostFence: fence, readOnly, isolatedSession,
787
962
  });
788
963
  }
789
964
  async openSession(relayVersion = '0.1.0') {
@@ -1216,7 +1391,7 @@ export class AgentFabricClient {
1216
1391
  });
1217
1392
  }
1218
1393
  async #persist() {
1219
- if (this.#readOnly) {
1394
+ if (this.#readOnly || this.#isolatedSession) {
1220
1395
  await this.#assertHostScope();
1221
1396
  return;
1222
1397
  }