@tinycloud/node-sdk 2.4.0 → 2.4.1-beta.0

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.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISigner, Bytes, IWasmBindings, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CallbackStrategy, CanonicalAddress, CanonicalDecryptRequest, CanonicalJson, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncodedShareData, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IEncryptionService, IHooksService, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InlineEncryptedEnvelope, InvokeFunction, JWK, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedNetworkId, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SignedReceiverKeyInput, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, VersionCheckError, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, addressStorageKey, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, buildSpaceUri, canonicalHashHex, canonicalSignedResponse, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeEncryptionJson, canonicalizeNetworkId, canonicalizeSecretScope, checkDecryptInvocationInput, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, decryptEnvelopeWithKey, defaultSpaceCreationHandler, deriveSignedReceiverKey, didCacheKey, didEquals, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, encryptionBase64Decode, encryptionBase64Encode, encryptionError, encryptionUtf8Decode, encryptionUtf8Encode, ensureNetworkUsableForDecrypt, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, isNetworkId, loadManifest, makePkhSpaceId, makePublicSpaceId, networkDiscoveryKey, openWrappedKey, parseCanonicalNetworkId, parseExpiry, parseNetworkId, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-DfE4s_Rg.cjs';
3
+ export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-D01sn2vf.cjs';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, generateHostSIWEMessage, siweToDelegationHeaders, protocolVersion, vault_encrypt, vault_decrypt, vault_derive_key, vault_x25519_from_seed, vault_x25519_dh, vault_random_bytes, vault_sha256 } from '@tinycloud/node-sdk-wasm';
5
5
  import 'events';
6
6
  import '@tinycloud/sdk-services';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISigner, Bytes, IWasmBindings, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CallbackStrategy, CanonicalAddress, CanonicalDecryptRequest, CanonicalJson, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncodedShareData, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IEncryptionService, IHooksService, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InlineEncryptedEnvelope, InvokeFunction, JWK, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedNetworkId, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SignedReceiverKeyInput, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, VersionCheckError, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, addressStorageKey, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, buildSpaceUri, canonicalHashHex, canonicalSignedResponse, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeEncryptionJson, canonicalizeNetworkId, canonicalizeSecretScope, checkDecryptInvocationInput, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, decryptEnvelopeWithKey, defaultSpaceCreationHandler, deriveSignedReceiverKey, didCacheKey, didEquals, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, encryptionBase64Decode, encryptionBase64Encode, encryptionError, encryptionUtf8Decode, encryptionUtf8Encode, ensureNetworkUsableForDecrypt, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, isNetworkId, loadManifest, makePkhSpaceId, makePublicSpaceId, networkDiscoveryKey, openWrappedKey, parseCanonicalNetworkId, parseExpiry, parseNetworkId, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-DfE4s_Rg.js';
3
+ export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-D01sn2vf.js';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, generateHostSIWEMessage, siweToDelegationHeaders, protocolVersion, vault_encrypt, vault_decrypt, vault_derive_key, vault_x25519_from_seed, vault_x25519_dh, vault_random_bytes, vault_sha256 } from '@tinycloud/node-sdk-wasm';
5
5
  import 'events';
6
6
  import '@tinycloud/sdk-services';
package/dist/index.js CHANGED
@@ -18502,12 +18502,12 @@ function displayActionUrn(action) {
18502
18502
  function secretActionName(action) {
18503
18503
  return action;
18504
18504
  }
18505
- function secretPermissionEntries(name, options, action, encryptionNetworkId) {
18505
+ function secretPermissionEntries(name, options, action, space, encryptionNetworkId) {
18506
18506
  const entries = [];
18507
18507
  const path = action === "list" ? resolveSecretListPrefix(options) : resolveSecretPath(name, options).permissionPaths.vault;
18508
18508
  entries.push({
18509
18509
  service: "tinycloud.kv",
18510
- space: SECRETS_SPACE,
18510
+ space,
18511
18511
  path,
18512
18512
  actions: [secretActionName(action)],
18513
18513
  skipPrefix: true
@@ -18522,11 +18522,23 @@ function secretPermissionEntries(name, options, action, encryptionNetworkId) {
18522
18522
  }
18523
18523
  return entries;
18524
18524
  }
18525
+ function normalizeSpace(space, resolveSpace) {
18526
+ if (!space) return void 0;
18527
+ if (space.startsWith("tinycloud:")) return space;
18528
+ return resolveSpace?.(space) ?? space;
18529
+ }
18530
+ function spaceMatches(granted, requested, resolveSpace) {
18531
+ if (!granted || !requested) return false;
18532
+ return normalizeSpace(granted, resolveSpace) === normalizeSpace(requested, resolveSpace);
18533
+ }
18525
18534
  var NodeSecretsService = class {
18526
18535
  constructor(config) {
18527
18536
  this.config = config;
18528
18537
  this.shouldRestoreUnlock = false;
18529
18538
  }
18539
+ get space() {
18540
+ return this.config.space ?? SECRETS_SPACE;
18541
+ }
18530
18542
  get vault() {
18531
18543
  return this.service.vault;
18532
18544
  }
@@ -18579,6 +18591,7 @@ var NodeSecretsService = class {
18579
18591
  name,
18580
18592
  options,
18581
18593
  action,
18594
+ this.space,
18582
18595
  action === "get" ? this.config.getEncryptionNetworkId?.() : void 0
18583
18596
  );
18584
18597
  } catch (error) {
@@ -18628,7 +18641,7 @@ var NodeSecretsService = class {
18628
18641
  (entry) => manifests.some((candidate) => {
18629
18642
  const resolved = resolveManifest(candidate);
18630
18643
  return resolved.resources.some(
18631
- (resource) => resource.service === entry.service && resource.space === entry.space && resource.path === entry.path && entry.actions.every((action) => resource.actions.includes(action))
18644
+ (resource) => resource.service === entry.service && spaceMatches(resource.space, entry.space, this.config.resolveSpace) && resource.path === entry.path && entry.actions.every((action) => resource.actions.includes(action))
18632
18645
  );
18633
18646
  })
18634
18647
  );
@@ -18652,6 +18665,20 @@ function didPrincipalMatches2(actual, expected) {
18652
18665
  return actual === expected;
18653
18666
  }
18654
18667
  }
18668
+ function sharingActionsToAbilities(path, actions) {
18669
+ var _a;
18670
+ const abilities = {};
18671
+ for (const action of actions) {
18672
+ const slash = action.indexOf("/");
18673
+ if (slash === -1) return void 0;
18674
+ const shortService = SERVICE_LONG_TO_SHORT[action.slice(0, slash)];
18675
+ if (shortService === void 0) return void 0;
18676
+ abilities[shortService] ?? (abilities[shortService] = {});
18677
+ (_a = abilities[shortService])[path] ?? (_a[path] = []);
18678
+ abilities[shortService][path].push(action);
18679
+ }
18680
+ return Object.keys(abilities).length > 0 ? abilities : void 0;
18681
+ }
18655
18682
  function base64UrlEncode(bytes) {
18656
18683
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
18657
18684
  let output = "";
@@ -18764,6 +18791,8 @@ var _TinyCloudNode = class _TinyCloudNode {
18764
18791
  this.auth = null;
18765
18792
  this.tc = null;
18766
18793
  this._chainId = 1;
18794
+ this._baseSecrets = /* @__PURE__ */ new Map();
18795
+ this._secrets = /* @__PURE__ */ new Map();
18767
18796
  this.runtimePermissionGrants = [];
18768
18797
  this.invokeWithRuntimePermissions = (session, service, path, action, facts) => {
18769
18798
  return this.wasmBindings.invoke(
@@ -19026,6 +19055,13 @@ var _TinyCloudNode = class _TinyCloudNode {
19026
19055
  get session() {
19027
19056
  return this.auth?.tinyCloudSession;
19028
19057
  }
19058
+ /**
19059
+ * Get the currently active session in the shape callers can persist and later
19060
+ * pass back to {@link restoreSession}.
19061
+ */
19062
+ get restorableSession() {
19063
+ return this.currentTinyCloudSession();
19064
+ }
19029
19065
  /**
19030
19066
  * Sign in and create a new session.
19031
19067
  * This creates the user's space if it doesn't exist.
@@ -19048,8 +19084,8 @@ var _TinyCloudNode = class _TinyCloudNode {
19048
19084
  this._hooks = void 0;
19049
19085
  this._vault = void 0;
19050
19086
  this._encryption = void 0;
19051
- this._baseSecrets = void 0;
19052
- this._secrets = void 0;
19087
+ this._baseSecrets.clear();
19088
+ this._secrets.clear();
19053
19089
  this._spaceService = void 0;
19054
19090
  this._serviceContext = void 0;
19055
19091
  this.runtimePermissionGrants = [];
@@ -19535,8 +19571,8 @@ var _TinyCloudNode = class _TinyCloudNode {
19535
19571
  this._hooks = void 0;
19536
19572
  this._vault = void 0;
19537
19573
  this._encryption = void 0;
19538
- this._baseSecrets = void 0;
19539
- this._secrets = void 0;
19574
+ this._baseSecrets.clear();
19575
+ this._secrets.clear();
19540
19576
  this._spaceService = void 0;
19541
19577
  this._serviceContext = void 0;
19542
19578
  this.runtimePermissionGrants = [];
@@ -19826,6 +19862,20 @@ var _TinyCloudNode = class _TinyCloudNode {
19826
19862
  getDefaultEncryptionNetworkId(name = DEFAULT_ENCRYPTION_NETWORK_NAME) {
19827
19863
  return `urn:tinycloud:encryption:${this.did}:${name}`;
19828
19864
  }
19865
+ getEncryptionNetworkIdForSpace(spaceId, name = DEFAULT_ENCRYPTION_NETWORK_NAME) {
19866
+ const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? this.did;
19867
+ return `urn:tinycloud:encryption:${ownerDid}:${name}`;
19868
+ }
19869
+ ownerDidFromSpaceId(spaceId) {
19870
+ if (!spaceId.startsWith("tinycloud:")) return void 0;
19871
+ const body = spaceId.slice("tinycloud:".length);
19872
+ const lastSeparator = body.lastIndexOf(":");
19873
+ if (lastSeparator <= 0) return void 0;
19874
+ const owner = body.slice(0, lastSeparator);
19875
+ if (owner.startsWith("did:")) return owner;
19876
+ if (!owner.includes(":")) return void 0;
19877
+ return `did:${owner}`;
19878
+ }
19829
19879
  requireServiceSession() {
19830
19880
  const session = this._serviceContext?.session;
19831
19881
  if (!session) {
@@ -20013,7 +20063,7 @@ var _TinyCloudNode = class _TinyCloudNode {
20013
20063
  spaceId,
20014
20064
  crypto: vaultCrypto,
20015
20065
  encryption: {
20016
- networkId: this.getDefaultEncryptionNetworkId(),
20066
+ networkId: this.getEncryptionNetworkIdForSpace(spaceId),
20017
20067
  service: this.getEncryptionService(),
20018
20068
  decryptCapabilityProof: () => ({
20019
20069
  proofs: [this.requireServiceSession().delegationCid]
@@ -20144,6 +20194,9 @@ var _TinyCloudNode = class _TinyCloudNode {
20144
20194
  }
20145
20195
  return vaultService;
20146
20196
  },
20197
+ createSecretsService: (spaceId) => {
20198
+ return this.secretsForSpace(spaceId);
20199
+ },
20147
20200
  // Enable space.delegations.create() via SIWE-based delegation
20148
20201
  createDelegation: async (params) => {
20149
20202
  try {
@@ -20266,11 +20319,10 @@ var _TinyCloudNode = class _TinyCloudNode {
20266
20319
  try {
20267
20320
  const host = this.config.host;
20268
20321
  const now = /* @__PURE__ */ new Date();
20269
- const abilities = {
20270
- kv: {
20271
- [params.path]: params.actions
20272
- }
20273
- };
20322
+ const abilities = sharingActionsToAbilities(params.path, params.actions);
20323
+ if (!abilities) {
20324
+ return void 0;
20325
+ }
20274
20326
  const prepared = this.wasmBindings.prepareSession({
20275
20327
  abilities,
20276
20328
  address: this.wasmBindings.ensureEip55(session.address),
@@ -20526,27 +20578,49 @@ var _TinyCloudNode = class _TinyCloudNode {
20526
20578
  if (!this._spaceService) {
20527
20579
  throw new Error("Not signed in. Call signIn() first.");
20528
20580
  }
20529
- if (!this._secrets) {
20530
- this._secrets = new NodeSecretsService({
20531
- getService: () => this.getBaseSecrets(),
20581
+ return this.secretsForSpace("secrets");
20582
+ }
20583
+ /**
20584
+ * App-facing secrets API backed by the requested space's vault.
20585
+ */
20586
+ secretsForSpace(spaceId) {
20587
+ if (!this._spaceService) {
20588
+ throw new Error("Not signed in. Call signIn() first.");
20589
+ }
20590
+ const resolvedSpace = spaceId.startsWith("tinycloud:") ? spaceId : this.ownedSpaceId(spaceId);
20591
+ let secrets = this._secrets.get(resolvedSpace);
20592
+ if (!secrets) {
20593
+ secrets = new NodeSecretsService({
20594
+ getService: () => this.getBaseSecrets(resolvedSpace),
20595
+ space: resolvedSpace,
20532
20596
  getManifest: () => this.manifest,
20533
20597
  hasPermissions: (permissions) => this.hasRuntimePermissions(permissions),
20534
20598
  grantPermissions: (additional) => this.grantRuntimePermissions(additional),
20535
20599
  canEscalate: () => this.signer !== void 0 && this.tc !== void 0,
20536
- getEncryptionNetworkId: () => this.getDefaultEncryptionNetworkId(),
20600
+ getEncryptionNetworkId: () => this.getEncryptionNetworkIdForSpace(resolvedSpace),
20601
+ resolveSpace: (space) => space.startsWith("tinycloud:") ? space : this.ownedSpaceId(space),
20537
20602
  getUnlockSigner: () => this.signer ?? void 0
20538
20603
  });
20604
+ this._secrets.set(resolvedSpace, secrets);
20539
20605
  }
20540
- return this._secrets;
20606
+ return secrets;
20541
20607
  }
20542
- getBaseSecrets() {
20608
+ getBaseSecrets(spaceId) {
20543
20609
  if (!this._spaceService) {
20544
20610
  throw new Error("Not signed in. Call signIn() first.");
20545
20611
  }
20546
- if (!this._baseSecrets) {
20547
- this._baseSecrets = new SecretsService(() => this.space("secrets").vault);
20612
+ const resolvedSpace = spaceId.startsWith("tinycloud:") ? spaceId : this.ownedSpaceId(spaceId);
20613
+ let secrets = this._baseSecrets.get(resolvedSpace);
20614
+ if (!secrets) {
20615
+ const kvService = this.createSpaceScopedKVService(resolvedSpace);
20616
+ const vaultService = this.createVaultService(resolvedSpace, kvService);
20617
+ if (this._serviceContext) {
20618
+ vaultService.initialize(this._serviceContext);
20619
+ }
20620
+ secrets = new SecretsService(() => vaultService);
20621
+ this._baseSecrets.set(resolvedSpace, secrets);
20548
20622
  }
20549
- return this._baseSecrets;
20623
+ return secrets;
20550
20624
  }
20551
20625
  /**
20552
20626
  * Hooks write stream subscription API.