@tinycloud/node-sdk 3.11.0 → 3.12.0-beta.1

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 (37) hide show
  1. package/dist/NodeUserAuthorization-BtoDI9in.d.cts +900 -0
  2. package/dist/NodeUserAuthorization-BtoDI9in.d.ts +900 -0
  3. package/dist/{TinyCloudNode-BlNcvo1c.d.ts → TinyCloudNode-C24728N_.d.cts} +30 -874
  4. package/dist/{TinyCloudNode-CnVaWnAX.d.cts → TinyCloudNode-DLrINr98.d.ts} +30 -874
  5. package/dist/{WasmKeyProvider-BKCPRC-c.d.cts → WasmKeyProvider-OA0LqmTg.d.cts} +2 -0
  6. package/dist/{WasmKeyProvider-BKCPRC-c.d.ts → WasmKeyProvider-OA0LqmTg.d.ts} +2 -0
  7. package/dist/{authority-DHIk5QvV.d.ts → authority-BQN2Z3st.d.ts} +1 -1
  8. package/dist/{authority-B2SLx27M.d.cts → authority-DDdheOL6.d.cts} +1 -1
  9. package/dist/core.cjs +179 -100
  10. package/dist/core.cjs.map +1 -1
  11. package/dist/core.d.cts +6 -5
  12. package/dist/core.d.ts +6 -5
  13. package/dist/core.js +180 -101
  14. package/dist/core.js.map +1 -1
  15. package/dist/credentials-core.d.cts +1 -1
  16. package/dist/credentials-core.d.ts +1 -1
  17. package/dist/credentials.d.cts +1 -1
  18. package/dist/credentials.d.ts +1 -1
  19. package/dist/{delegation-Ckc3UETl.d.cts → delegation-BQbAuKad.d.cts} +1 -1
  20. package/dist/{delegation-Ckc3UETl.d.ts → delegation-BQbAuKad.d.ts} +1 -1
  21. package/dist/encryption-keys.d.cts +3 -2
  22. package/dist/encryption-keys.d.ts +3 -2
  23. package/dist/index.cjs +179 -100
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +5 -4
  26. package/dist/index.d.ts +5 -4
  27. package/dist/index.js +180 -101
  28. package/dist/index.js.map +1 -1
  29. package/dist/replication/authority.d.cts +4 -3
  30. package/dist/replication/authority.d.ts +4 -3
  31. package/dist/space-hosting.cjs +141 -0
  32. package/dist/space-hosting.cjs.map +1 -0
  33. package/dist/space-hosting.d.cts +69 -0
  34. package/dist/space-hosting.d.ts +69 -0
  35. package/dist/space-hosting.js +115 -0
  36. package/dist/space-hosting.js.map +1 -0
  37. package/package.json +11 -1
@@ -1,5 +1,5 @@
1
1
  import { CredentialFlowDescriptor, CredentialRequirement, CredentialHolderBinding, IssuedCredentialEnvelope, CredentialIssuerMetadata, ClientSession, IKVService, StoredCredentialRecord, VerifiedCredential, CredentialProgressEvent, CredentialStorageReceipt, UnifiedPolicyV2, UnifiedPolicyCapability, PolicyCredentialAdmissionV3 } from '@tinycloud/sdk-core';
2
- import { V as ValidatedRuntimeDelegation } from './delegation-Ckc3UETl.cjs';
2
+ import { V as ValidatedRuntimeDelegation } from './delegation-BQbAuKad.cjs';
3
3
 
4
4
  interface CredentialClient {
5
5
  readonly sessionDid: string;
@@ -1,5 +1,5 @@
1
1
  import { CredentialFlowDescriptor, CredentialRequirement, CredentialHolderBinding, IssuedCredentialEnvelope, CredentialIssuerMetadata, ClientSession, IKVService, StoredCredentialRecord, VerifiedCredential, CredentialProgressEvent, CredentialStorageReceipt, UnifiedPolicyV2, UnifiedPolicyCapability, PolicyCredentialAdmissionV3 } from '@tinycloud/sdk-core';
2
- import { V as ValidatedRuntimeDelegation } from './delegation-Ckc3UETl.js';
2
+ import { V as ValidatedRuntimeDelegation } from './delegation-BQbAuKad.js';
3
3
 
4
4
  interface CredentialClient {
5
5
  readonly sessionDid: string;
@@ -1,7 +1,7 @@
1
1
  export { CredentialAcquisitionTheme, CredentialAcquisitionTransport, CredentialBrowserInteractionAdapter, CredentialClient, CredentialInlineInteractionAdapter, CredentialInputRequest, CredentialInteractionAdapter, CredentialInteractionKind, CredentialInteractionSurface, CredentialProofSubject, CredentialRedirectResumeState, CredentialRedirectStore, CredentialRequestState, CredentialSigningAdapter, CredentialsAcquireOptions, CredentialsEnsureOptions, CredentialsEnsureResult, CredentialsOperationOptions, CredentialsPolicyAdmissionOptions, CredentialsPolicyAdmissionResult, HolderSignatureKey, InlineCredentialProofHandler, InlineCredentialProofRequest, OpenCredentialsHttpTransport, PrimitiveStepHandler, PrimitiveStepResult, ReceiverCredentialCustody, interpretCredentialFlow, mailboxSubject } from './credentials-core.cjs';
2
2
  export { D as DEFAULT_EMAIL_PROOF_PROFILE, b as EMAIL_PROOF_CREDENTIAL_TYPE, c as EMAIL_PROOF_PENDING_MAX_MS, d as EmailProofAcquireInput, e as EmailProofAcquisition, f as EmailProofError, g as EmailProofErrorCode, h as EmailProofOptions, a as EmailProofPending, E as EmailProofPendingStore, i as EmailProofProfileId, j as EmailProofRequestInput, k as EmailProofResult, l as EmailProofStep, H as HolderAlgorithm, m as HolderSigner, S as StoredEmailProofInput, n as StoredEmailProofRecord, o as acquireEmailProof, p as completeEmailProof, q as createEd25519HolderSigner, r as createMemoryEmailProofPendingStore, s as emailProofRequirement, t as isTicketEmailProofResult, u as requestEmailProofCode, v as verifyStoredEmailProof } from './email-proof-B4DRizIL.cjs';
3
3
  import '@tinycloud/sdk-core';
4
- import './delegation-Ckc3UETl.cjs';
4
+ import './delegation-BQbAuKad.cjs';
5
5
  import '@tinycloud/sdk-core/held-credentials';
6
6
 
7
7
  /** Production pins. Credentials verify only against these values. Tests pin them literally. */
@@ -1,7 +1,7 @@
1
1
  export { CredentialAcquisitionTheme, CredentialAcquisitionTransport, CredentialBrowserInteractionAdapter, CredentialClient, CredentialInlineInteractionAdapter, CredentialInputRequest, CredentialInteractionAdapter, CredentialInteractionKind, CredentialInteractionSurface, CredentialProofSubject, CredentialRedirectResumeState, CredentialRedirectStore, CredentialRequestState, CredentialSigningAdapter, CredentialsAcquireOptions, CredentialsEnsureOptions, CredentialsEnsureResult, CredentialsOperationOptions, CredentialsPolicyAdmissionOptions, CredentialsPolicyAdmissionResult, HolderSignatureKey, InlineCredentialProofHandler, InlineCredentialProofRequest, OpenCredentialsHttpTransport, PrimitiveStepHandler, PrimitiveStepResult, ReceiverCredentialCustody, interpretCredentialFlow, mailboxSubject } from './credentials-core.js';
2
2
  export { D as DEFAULT_EMAIL_PROOF_PROFILE, b as EMAIL_PROOF_CREDENTIAL_TYPE, c as EMAIL_PROOF_PENDING_MAX_MS, d as EmailProofAcquireInput, e as EmailProofAcquisition, f as EmailProofError, g as EmailProofErrorCode, h as EmailProofOptions, a as EmailProofPending, E as EmailProofPendingStore, i as EmailProofProfileId, j as EmailProofRequestInput, k as EmailProofResult, l as EmailProofStep, H as HolderAlgorithm, m as HolderSigner, S as StoredEmailProofInput, n as StoredEmailProofRecord, o as acquireEmailProof, p as completeEmailProof, q as createEd25519HolderSigner, r as createMemoryEmailProofPendingStore, s as emailProofRequirement, t as isTicketEmailProofResult, u as requestEmailProofCode, v as verifyStoredEmailProof } from './email-proof-B4DRizIL.js';
3
3
  import '@tinycloud/sdk-core';
4
- import './delegation-Ckc3UETl.js';
4
+ import './delegation-BQbAuKad.js';
5
5
  import '@tinycloud/sdk-core/held-credentials';
6
6
 
7
7
  /** Production pins. Credentials verify only against these values. Tests pin them literally. */
@@ -248,4 +248,4 @@ declare function serializeDelegation(delegation: PortableDelegation): string;
248
248
  */
249
249
  declare function deserializeDelegation(data: string): PortableDelegation;
250
250
 
251
- export { type AuthDelegationArtifact as A, type CompactRuntimeDelegationInput as C, type DelegationAuthority as D, type PortableDelegation as P, RuntimeDelegationRejectedError as R, type SessionGrantProof as S, type ValidatedRuntimeDelegation as V, type RuntimeDelegationRejection as a, activateCompactRuntimeDelegation as b, activateValidatedRuntimeDelegation as c, deserializeDelegation as d, type AuthRequestArtifact as e, RUNTIME_DELEGATION_REJECTIONS as f, type RuntimeDelegationActivator as g, type VerifiedSessionGrant as h, grantAuthRequest as i, signedCompactUcanExpiry as j, siweRuntimeDelegation as k, serializeDelegation as s };
251
+ export { type AuthDelegationArtifact as A, type CompactRuntimeDelegationInput as C, type DelegationAuthority as D, type PortableDelegation as P, RuntimeDelegationRejectedError as R, type SessionGrantProof as S, type ValidatedRuntimeDelegation as V, type RuntimeDelegationRejection as a, activateCompactRuntimeDelegation as b, activateValidatedRuntimeDelegation as c, deserializeDelegation as d, type VerifiedSessionGrant as e, type AuthRequestArtifact as f, RUNTIME_DELEGATION_REJECTIONS as g, type RuntimeDelegationActivator as h, grantAuthRequest as i, signedCompactUcanExpiry as j, siweRuntimeDelegation as k, serializeDelegation as s };
@@ -248,4 +248,4 @@ declare function serializeDelegation(delegation: PortableDelegation): string;
248
248
  */
249
249
  declare function deserializeDelegation(data: string): PortableDelegation;
250
250
 
251
- export { type AuthDelegationArtifact as A, type CompactRuntimeDelegationInput as C, type DelegationAuthority as D, type PortableDelegation as P, RuntimeDelegationRejectedError as R, type SessionGrantProof as S, type ValidatedRuntimeDelegation as V, type RuntimeDelegationRejection as a, activateCompactRuntimeDelegation as b, activateValidatedRuntimeDelegation as c, deserializeDelegation as d, type AuthRequestArtifact as e, RUNTIME_DELEGATION_REJECTIONS as f, type RuntimeDelegationActivator as g, type VerifiedSessionGrant as h, grantAuthRequest as i, signedCompactUcanExpiry as j, siweRuntimeDelegation as k, serializeDelegation as s };
251
+ export { type AuthDelegationArtifact as A, type CompactRuntimeDelegationInput as C, type DelegationAuthority as D, type PortableDelegation as P, RuntimeDelegationRejectedError as R, type SessionGrantProof as S, type ValidatedRuntimeDelegation as V, type RuntimeDelegationRejection as a, activateCompactRuntimeDelegation as b, activateValidatedRuntimeDelegation as c, deserializeDelegation as d, type VerifiedSessionGrant as e, type AuthRequestArtifact as f, RUNTIME_DELEGATION_REJECTIONS as g, type RuntimeDelegationActivator as h, grantAuthRequest as i, signedCompactUcanExpiry as j, siweRuntimeDelegation as k, serializeDelegation as s };
@@ -1,11 +1,12 @@
1
1
  import { NamedKeyClient } from '@tinycloud/sdk-services/encryption/named-keys';
2
2
  export { DecryptManyResult, KeyCallOptions, KeyDescriptor, KeyEncryptOptions, NamedKeyClient, NamedKeyEnvelope, NamedKeyError, NamedKeyErrorCode, PublicKeyDescriptor, buildKeyAdminFacts, buildKeyDescribeFacts } from '@tinycloud/sdk-services/encryption/named-keys';
3
- import { T as TinyCloudNode } from './TinyCloudNode-CnVaWnAX.cjs';
3
+ import { T as TinyCloudNode } from './TinyCloudNode-C24728N_.cjs';
4
4
  import '@tinycloud/sdk-core';
5
5
  import '@tinycloud/sdk-services/kv/replication';
6
6
  import '@tinycloud/sdk-services';
7
+ import './NodeUserAuthorization-BtoDI9in.cjs';
7
8
  import 'events';
8
- import './delegation-Ckc3UETl.cjs';
9
+ import './delegation-BQbAuKad.cjs';
9
10
 
10
11
  /**
11
12
  * Named encryption keys for a signed-in {@link TinyCloudNode}.
@@ -1,11 +1,12 @@
1
1
  import { NamedKeyClient } from '@tinycloud/sdk-services/encryption/named-keys';
2
2
  export { DecryptManyResult, KeyCallOptions, KeyDescriptor, KeyEncryptOptions, NamedKeyClient, NamedKeyEnvelope, NamedKeyError, NamedKeyErrorCode, PublicKeyDescriptor, buildKeyAdminFacts, buildKeyDescribeFacts } from '@tinycloud/sdk-services/encryption/named-keys';
3
- import { T as TinyCloudNode } from './TinyCloudNode-BlNcvo1c.js';
3
+ import { T as TinyCloudNode } from './TinyCloudNode-DLrINr98.js';
4
4
  import '@tinycloud/sdk-core';
5
5
  import '@tinycloud/sdk-services/kv/replication';
6
6
  import '@tinycloud/sdk-services';
7
+ import './NodeUserAuthorization-BtoDI9in.js';
7
8
  import 'events';
8
- import './delegation-Ckc3UETl.js';
9
+ import './delegation-BQbAuKad.js';
9
10
 
10
11
  /**
11
12
  * Named encryption keys for a signed-in {@link TinyCloudNode}.
package/dist/index.cjs CHANGED
@@ -18968,6 +18968,18 @@ var MemorySessionStorage = class {
18968
18968
  }
18969
18969
  };
18970
18970
 
18971
+ // src/storage/clearPersistedSessionIfOwn.ts
18972
+ async function clearPersistedSessionIfOwn(storage, address, ownSignature) {
18973
+ if (ownSignature !== void 0) {
18974
+ try {
18975
+ const stored = await storage.load(address);
18976
+ if (stored !== null && stored.signature !== ownSignature) return;
18977
+ } catch {
18978
+ }
18979
+ }
18980
+ await storage.clear(address);
18981
+ }
18982
+
18971
18983
  // src/authorization/NodeUserAuthorization.ts
18972
18984
  function assertMaxExpiresAt(value) {
18973
18985
  if (value === void 0 || typeof value === "function") return;
@@ -19061,6 +19073,8 @@ var NodeUserAuthorization = class {
19061
19073
  * delegation lists them: the node answers a repeat with empty lists.
19062
19074
  */
19063
19075
  this._lastActivationActivatedSpaceIds = [];
19076
+ /** See {@link spaceHosting}. Written only from node answers. */
19077
+ this._spaceHosting = "unknown";
19064
19078
  this.wasm = config.wasmBindings;
19065
19079
  this.signer = config.signer;
19066
19080
  this.signStrategy = config.signStrategy ?? defaultSignStrategy;
@@ -19220,6 +19234,7 @@ var NodeUserAuthorization = class {
19220
19234
  this.registryVerdict = void 0;
19221
19235
  this._lastActivationSkippedSpaceIds = [];
19222
19236
  this._lastActivationActivatedSpaceIds = [];
19237
+ this._spaceHosting = "unknown";
19223
19238
  if (!session) {
19224
19239
  this._session = void 0;
19225
19240
  this._tinyCloudSession = void 0;
@@ -19360,6 +19375,18 @@ var NodeUserAuthorization = class {
19360
19375
  get lastActivationActivatedSpaceIds() {
19361
19376
  return [...this._lastActivationActivatedSpaceIds];
19362
19377
  }
19378
+ /**
19379
+ * The node's last answer for whether this session's primary space is hosted:
19380
+ * recorded from the sign-in activation, or by {@link noteSpaceHosting}.
19381
+ * `unknown` until one of them answers, and after a restore.
19382
+ */
19383
+ get spaceHosting() {
19384
+ return this._spaceHosting;
19385
+ }
19386
+ /** @internal Record the hosting probe's answer for the primary space. */
19387
+ noteSpaceHosting(hosting) {
19388
+ this._spaceHosting = hosting;
19389
+ }
19363
19390
  /**
19364
19391
  * Compute the `abilities` map the WASM `prepareSession` call should
19365
19392
  * see at sign-in time.
@@ -19820,103 +19847,55 @@ var NodeUserAuthorization = class {
19820
19847
  this._tinyCloudSession.delegationHeader
19821
19848
  );
19822
19849
  this.recordActivationSkippedSpaces(result, primarySpaceId);
19850
+ if (!result.success && result.status !== 404) {
19851
+ throw Object.assign(
19852
+ new Error(`Failed to activate session: ${describeHostFailure(result)}`),
19853
+ { cause: result }
19854
+ );
19855
+ }
19856
+ await this.ensurePrimarySpaceHosted(this._spaceHosting);
19857
+ }
19858
+ /**
19859
+ * The create step of {@link ensureSpaceExists}: given the node's answer for
19860
+ * the primary space, host it through the space creation handler when it is
19861
+ * `not-hosted`. Any other answer, and a missing handler, change nothing. The
19862
+ * caller supplies the answer (sign-in's activation, or the hosting probe);
19863
+ * an empty activation list is never one.
19864
+ *
19865
+ * @throws Error if the creation handler fails or times out, or hosting fails
19866
+ */
19867
+ async ensurePrimarySpaceHosted(hosting) {
19868
+ if (hosting !== "not-hosted") {
19869
+ return;
19870
+ }
19871
+ const session = this._tinyCloudSession;
19872
+ if (!session) {
19873
+ throw new Error("Must be signed in to host the primary space");
19874
+ }
19823
19875
  const handler = this.spaceCreationHandler ?? (this.autoCreateSpace ? new import_sdk_core5.AutoApproveSpaceCreationHandler() : void 0);
19876
+ if (!handler) {
19877
+ return;
19878
+ }
19879
+ await this.ensureTinyCloudHosts();
19880
+ const host = this.primaryTinyCloudHost;
19881
+ const primarySpaceId = session.spaceId;
19824
19882
  const creationContext = {
19825
19883
  spaceId: primarySpaceId,
19826
19884
  address: this._address,
19827
19885
  chainId: this._chainId,
19828
19886
  host
19829
19887
  };
19830
- if (result.success) {
19831
- const primarySkipped = result.skipped?.includes(primarySpaceId);
19832
- if (!primarySkipped) {
19833
- return;
19834
- }
19835
- if (!handler) {
19836
- return;
19837
- }
19838
- await this.guardSpaceCreation(handler, creationContext);
19839
- const confirmed = await handler.confirmSpaceCreation(creationContext);
19840
- if (!confirmed) {
19841
- return;
19842
- }
19843
- try {
19844
- const created = await this.hostSpace();
19845
- if (!created.success) {
19846
- const err2 = Object.assign(
19847
- new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),
19848
- { cause: created }
19849
- );
19850
- throw err2;
19851
- }
19852
- } catch (error) {
19853
- handler.onSpaceCreationFailed?.(
19854
- creationContext,
19855
- error instanceof Error ? error : new Error(String(error))
19856
- );
19857
- throw error;
19858
- }
19859
- await new Promise((resolve2) => setTimeout(resolve2, 100));
19860
- const retryResult = await (0, import_sdk_core5.activateSessionWithHost)(
19861
- host,
19862
- this._tinyCloudSession.delegationHeader
19863
- );
19864
- if (!retryResult.success) {
19865
- const err2 = Object.assign(
19866
- new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),
19867
- { cause: retryResult }
19868
- );
19869
- handler.onSpaceCreationFailed?.(creationContext, err2);
19870
- throw err2;
19871
- }
19872
- handler.onSpaceCreated?.(creationContext);
19873
- return;
19874
- }
19875
- if (result.status === 404) {
19876
- if (!handler) {
19877
- return;
19878
- }
19879
- await this.guardSpaceCreation(handler, creationContext);
19880
- const confirmed = await handler.confirmSpaceCreation(creationContext);
19881
- if (!confirmed) {
19882
- return;
19883
- }
19884
- try {
19885
- const created = await this.hostSpace();
19886
- if (!created.success) {
19887
- const err2 = Object.assign(
19888
- new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),
19889
- { cause: created }
19890
- );
19891
- throw err2;
19892
- }
19893
- } catch (error) {
19894
- handler.onSpaceCreationFailed?.(
19895
- creationContext,
19896
- error instanceof Error ? error : new Error(String(error))
19897
- );
19898
- throw error;
19899
- }
19900
- await new Promise((resolve2) => setTimeout(resolve2, 100));
19901
- const retryResult = await (0, import_sdk_core5.activateSessionWithHost)(
19902
- host,
19903
- this._tinyCloudSession.delegationHeader
19904
- );
19905
- if (!retryResult.success) {
19906
- const err2 = Object.assign(
19907
- new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),
19908
- { cause: retryResult }
19909
- );
19910
- handler.onSpaceCreationFailed?.(creationContext, err2);
19911
- throw err2;
19912
- }
19913
- handler.onSpaceCreated?.(creationContext);
19914
- return;
19915
- }
19916
- throw Object.assign(
19917
- new Error(`Failed to activate session: ${describeHostFailure(result)}`),
19918
- { cause: result }
19919
- );
19888
+ const { createPrimarySpace } = await import("./space-hosting.cjs");
19889
+ await createPrimarySpace({
19890
+ handler,
19891
+ context: creationContext,
19892
+ guard: () => this.guardSpaceCreation(handler, creationContext),
19893
+ host: () => this.hostSpace(primarySpaceId),
19894
+ onHosted: () => {
19895
+ this._spaceHosting = "hosted";
19896
+ },
19897
+ activate: () => (0, import_sdk_core5.activateSessionWithHost)(host, session.delegationHeader)
19898
+ });
19920
19899
  }
19921
19900
  /** {@link assertMayCreateSpace}, reporting a refusal to the creation handler before rethrowing it. */
19922
19901
  async guardSpaceCreation(handler, context) {
@@ -19932,10 +19911,12 @@ var NodeUserAuthorization = class {
19932
19911
  if (result.success) {
19933
19912
  this._lastActivationSkippedSpaceIds = result.skipped ?? [];
19934
19913
  this._lastActivationActivatedSpaceIds = result.activated ?? [];
19914
+ this._spaceHosting = this._lastActivationSkippedSpaceIds.includes(primarySpaceId) ? "not-hosted" : this._lastActivationActivatedSpaceIds.includes(primarySpaceId) ? "hosted" : "unknown";
19935
19915
  return;
19936
19916
  }
19937
19917
  this._lastActivationActivatedSpaceIds = [];
19938
19918
  this._lastActivationSkippedSpaceIds = result.status === 404 ? [primarySpaceId] : [];
19919
+ this._spaceHosting = result.status === 404 ? "not-hosted" : "unknown";
19939
19920
  }
19940
19921
  async createBootstrapSession(options) {
19941
19922
  refuseCaveated(options.capabilityRequest.manifests);
@@ -20784,12 +20765,13 @@ var NodeUserAuthorization = class {
20784
20765
  };
20785
20766
  }
20786
20767
  /**
20787
- * Clear persisted session data.
20768
+ * Clear persisted session data. With `ownSignature`, a stored session that provably has a different
20769
+ * signature (a newer sign-in for the same address) is left alone.
20788
20770
  */
20789
- async clearPersistedSession(address) {
20771
+ async clearPersistedSession(address, ownSignature) {
20790
20772
  const targetAddress = address ?? this._address;
20791
20773
  if (targetAddress) {
20792
- await this.sessionStorage.clear(targetAddress);
20774
+ await clearPersistedSessionIfOwn(this.sessionStorage, targetAddress, ownSignature);
20793
20775
  }
20794
20776
  }
20795
20777
  /**
@@ -21873,6 +21855,8 @@ var _TinyCloudNode = class _TinyCloudNode {
21873
21855
  * hosting is confirmed against the session that was active at the time.
21874
21856
  */
21875
21857
  this.confirmedHostedSpaceIds = /* @__PURE__ */ new Set();
21858
+ /** The primary space's hosting answer when no authorization layer holds it (a session-only restore). */
21859
+ this._restoredSpaceHosting = "unknown";
21876
21860
  /**
21877
21861
  * Owned space ids known to be hosted for the current session: the sign-in
21878
21862
  * activation listed them as `activated`, or this session hosted them. Unlike
@@ -22211,6 +22195,84 @@ var _TinyCloudNode = class _TinyCloudNode {
22211
22195
  ));
22212
22196
  }
22213
22197
  }
22198
+ /**
22199
+ * Whether the TinyCloud node hosts the primary space (the default) or a named
22200
+ * or full-id space: `"hosted"`, `"not-hosted"`, or `"unknown"` when the node
22201
+ * cannot say.
22202
+ *
22203
+ * Sends one authorized read the session already holds on that space (a kv
22204
+ * list under a granted prefix, else kv metadata, `tinycloud.space/info`, or
22205
+ * a kv get of a key that does not exist), signed for that space. A session
22206
+ * with no such read sends nothing and answers `unknown`. A 401/403 registers
22207
+ * the session delegation with the node once and asks again once. Network
22208
+ * failures, 5xx and a 5 s timeout answer `unknown`; this never throws.
22209
+ *
22210
+ * `hosted` is remembered for the session and `not-hosted` never is. The
22211
+ * answer for the primary space is also what {@link spaceHosting} reports; a
22212
+ * `unknown` answer leaves the previous one in place.
22213
+ */
22214
+ async checkSpaceHosting(space) {
22215
+ try {
22216
+ return await this.probeSpaceHosting(space);
22217
+ } catch {
22218
+ return "unknown";
22219
+ }
22220
+ }
22221
+ /**
22222
+ * The node's last answer for the primary space: recorded at sign-in from the
22223
+ * activation, or by {@link checkSpaceHosting}. `unknown` after a restore until
22224
+ * something asks.
22225
+ */
22226
+ get spaceHosting() {
22227
+ return this.auth ? this.auth.spaceHosting : this._restoredSpaceHosting;
22228
+ }
22229
+ async probeSpaceHosting(space) {
22230
+ const context = this._serviceContext;
22231
+ const session = context?.session;
22232
+ const host = context?.hosts[0];
22233
+ if (!context || !session || !host) {
22234
+ return "unknown";
22235
+ }
22236
+ const spaceId = space === void 0 ? session.spaceId : space.startsWith("tinycloud:") ? space : this.ownedSpaceId(space);
22237
+ const graph = this._serviceGraph;
22238
+ const epoch = this.sessionEpoch;
22239
+ const assertCurrent = () => {
22240
+ graph.assertActive();
22241
+ if (epoch !== this.sessionEpoch || graph !== this._serviceGraph || this._serviceContext !== context) {
22242
+ throw new Error("The session changed during the hosting check.");
22243
+ }
22244
+ };
22245
+ const { askSpaceHosting } = await import("./space-hosting.cjs");
22246
+ assertCurrent();
22247
+ this.pruneExpiredRuntimePermissionGrants();
22248
+ const primary = this.currentTinyCloudSession();
22249
+ const answer = await askSpaceHosting({
22250
+ spaceId,
22251
+ operations: [
22252
+ ...this.runtimePermissionGrants.flatMap((grant) => grant.operations),
22253
+ ...primary ? this.recapOperationsFromSession(primary) : []
22254
+ ],
22255
+ covers: (granted, requested) => this.operationCovers(granted, requested),
22256
+ scope: context,
22257
+ host,
22258
+ fetch: unrecordedFetchOf(context),
22259
+ sign: (entries) => {
22260
+ assertCurrent();
22261
+ return graph.invokeAny({ ...session, spaceId }, entries);
22262
+ },
22263
+ // A session saved but never registered on this node is refused: it registers once.
22264
+ activate: (signal) => {
22265
+ assertCurrent();
22266
+ return (0, import_sdk_core10.activateSessionWithHost)(host, session.delegationHeader, AbortSignal.any([signal, graph.signal]));
22267
+ }
22268
+ });
22269
+ assertCurrent();
22270
+ if (answer !== "unknown" && this.spaceIdsEqual(spaceId, session.spaceId)) {
22271
+ if (this.auth) this.auth.noteSpaceHosting(answer);
22272
+ else this._restoredSpaceHosting = answer;
22273
+ }
22274
+ return answer;
22275
+ }
22214
22276
  get nodeFeatures() {
22215
22277
  return this.auth?.nodeFeatures ?? this._restoredNodeFeatures ?? [];
22216
22278
  }
@@ -22579,6 +22641,7 @@ var _TinyCloudNode = class _TinyCloudNode {
22579
22641
  const leavingChainId = this._chainId;
22580
22642
  const leavingPrincipal = this.replicaSessionPrincipal ?? (leavingAddress ? (0, import_sdk_core10.pkhDid)(leavingAddress, leavingChainId) : void 0);
22581
22643
  const leavingAuth = this.auth;
22644
+ const leavingSignature = leavingAuth?.tinyCloudSession?.signature ?? this._restoredTcSession?.signature;
22582
22645
  const leavingContext = this._serviceContext;
22583
22646
  let denied;
22584
22647
  let erased;
@@ -22595,7 +22658,7 @@ var _TinyCloudNode = class _TinyCloudNode {
22595
22658
  if (denied) erased = await this.eraseReplicaLocalCopy("sign_out", denied.status);
22596
22659
  } finally {
22597
22660
  if (leavingAddress) {
22598
- await (leavingAuth ? leavingAuth.clearPersistedSession(leavingAddress) : this.config.sessionStorage?.clear(leavingAddress));
22661
+ await (leavingAuth ? leavingAuth.clearPersistedSession(leavingAddress, leavingSignature) : this.config.sessionStorage && clearPersistedSessionIfOwn(this.config.sessionStorage, leavingAddress, leavingSignature));
22599
22662
  }
22600
22663
  }
22601
22664
  }
@@ -22701,6 +22764,7 @@ var _TinyCloudNode = class _TinyCloudNode {
22701
22764
  this._spaceService = void 0;
22702
22765
  this.runtimePermissionGrants = [];
22703
22766
  this._recapOperationsCache = void 0;
22767
+ this._restoredSpaceHosting = "unknown";
22704
22768
  this.confirmedHostedSpaceIds.clear();
22705
22769
  this.hostedOwnedSpaceIds.clear();
22706
22770
  this.cancelOwnedSpaceHosts();
@@ -22894,6 +22958,10 @@ var _TinyCloudNode = class _TinyCloudNode {
22894
22958
  const primarySession = this.currentTinyCloudSession();
22895
22959
  if (primarySession) {
22896
22960
  this.registerPrimarySessionGrant(primarySession);
22961
+ if (this.auth?.spaceHosting === "unknown") {
22962
+ await this.checkSpaceHosting();
22963
+ this.assertSessionEpoch(epoch, "Sign-in");
22964
+ }
22897
22965
  }
22898
22966
  const bootstrapped = await this.bootstrapAccountIfNeeded();
22899
22967
  this.assertSessionEpoch(epoch, "Sign-in");
@@ -24273,6 +24341,7 @@ var _TinyCloudNode = class _TinyCloudNode {
24273
24341
  this.tc = stagedGraph.core;
24274
24342
  this._recapOperationsCache = stagedPrimary.cache;
24275
24343
  this.runtimePermissionGrants = stagedPrimary.grants;
24344
+ this._restoredSpaceHosting = "unknown";
24276
24345
  this.confirmedHostedSpaceIds.clear();
24277
24346
  this.hostedOwnedSpaceIds.clear();
24278
24347
  this.cancelOwnedSpaceHosts();
@@ -28341,10 +28410,22 @@ var FileSessionStorage = class {
28341
28410
  async save(address, session) {
28342
28411
  const filePath = this.getFilePath(address);
28343
28412
  const data = JSON.stringify(session, null, 2);
28344
- (0, import_fs.writeFileSync)(filePath, data, "utf-8");
28413
+ const tempPath = `${filePath}.${process.pid}.${process.hrtime.bigint()}.tmp`;
28414
+ try {
28415
+ (0, import_fs.writeFileSync)(tempPath, data, { mode: 384, flag: "wx" });
28416
+ (0, import_fs.renameSync)(tempPath, filePath);
28417
+ } catch (error) {
28418
+ try {
28419
+ (0, import_fs.unlinkSync)(tempPath);
28420
+ } catch {
28421
+ }
28422
+ throw error;
28423
+ }
28345
28424
  }
28346
28425
  /**
28347
28426
  * Load a session for an address.
28427
+ *
28428
+ * Rejects when the file exists but cannot be read or parsed; the file is left in place.
28348
28429
  */
28349
28430
  async load(address) {
28350
28431
  const filePath = this.getFilePath(address);
@@ -28368,11 +28449,9 @@ var FileSessionStorage = class {
28368
28449
  }
28369
28450
  return session;
28370
28451
  } catch (error) {
28371
- try {
28372
- (0, import_fs.unlinkSync)(filePath);
28373
- } catch {
28374
- }
28375
- return null;
28452
+ throw new Error(
28453
+ `Could not read session file ${filePath}: ${error}`
28454
+ );
28376
28455
  }
28377
28456
  }
28378
28457
  /**