@tinycloud/node-sdk 3.0.0-beta.9 → 3.0.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/core.d.cts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, CaveatedDelegationUnsupportedError, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, EncodedShareData, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InvokeFunction, JWK, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedSecretCatalogKey, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, RegisterBatchSuccess, RegisterPolicyV3Input, RegisterPolicyV3Receipt, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretCatalogEntry, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, disableTinyCloudDebug, enableTinyCloudDebug, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, getTinyCloudDebugLogs, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateManifest } from '@tinycloud/sdk-core';
2
- export { e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, m as RuntimePermissionGrantOptions, S as SecretPermissionHint, n as SecretReadInput, o as SecretReadResult, p as SignStrategy, T as TinyCloudNode, q as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, r as UnifiedOwnerRootReceipt, s as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, t as WasmKeyProviderConfig, u as activateCompactRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, G as serializeDelegation } from './core-BTuD37zN.cjs';
2
+ export { e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, I as InvalidRestoredSessionError, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, m as RuntimePermissionGrantOptions, S as SecretPermissionHint, n as SecretReadInput, o as SecretReadResult, p as SignStrategy, T as TinyCloudNode, q as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, r as UnifiedOwnerRootReceipt, s as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, t as WasmKeyProviderConfig, u as activateCompactRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, G as serializeDelegation } from './core-DufYfxi-.cjs';
3
3
  import 'events';
4
4
  import '@tinycloud/sdk-services';
package/dist/core.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, CaveatedDelegationUnsupportedError, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, EncodedShareData, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InvokeFunction, JWK, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedSecretCatalogKey, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, RegisterBatchSuccess, RegisterPolicyV3Input, RegisterPolicyV3Receipt, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretCatalogEntry, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, disableTinyCloudDebug, enableTinyCloudDebug, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, getTinyCloudDebugLogs, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateManifest } from '@tinycloud/sdk-core';
2
- export { e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, m as RuntimePermissionGrantOptions, S as SecretPermissionHint, n as SecretReadInput, o as SecretReadResult, p as SignStrategy, T as TinyCloudNode, q as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, r as UnifiedOwnerRootReceipt, s as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, t as WasmKeyProviderConfig, u as activateCompactRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, G as serializeDelegation } from './core-BTuD37zN.js';
2
+ export { e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, I as InvalidRestoredSessionError, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, m as RuntimePermissionGrantOptions, S as SecretPermissionHint, n as SecretReadInput, o as SecretReadResult, p as SignStrategy, T as TinyCloudNode, q as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, r as UnifiedOwnerRootReceipt, s as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, t as WasmKeyProviderConfig, u as activateCompactRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, G as serializeDelegation } from './core-DufYfxi-.js';
3
3
  import 'events';
4
4
  import '@tinycloud/sdk-services';
package/dist/core.js CHANGED
@@ -2289,6 +2289,22 @@ function cloneRecapCaveats(caveats) {
2289
2289
  throw new Error("Verified persisted session ReCap contains invalid caveats.");
2290
2290
  }
2291
2291
  }
2292
+ function jsonFromVerifier(value) {
2293
+ if (value === void 0) return null;
2294
+ if (Array.isArray(value)) return value.map(jsonFromVerifier);
2295
+ if (value instanceof Map) {
2296
+ const entries = [...value.entries()];
2297
+ if (!entries.every(([key]) => typeof key === "string")) return value;
2298
+ return Object.fromEntries(entries.map(([key, nested]) => [key, jsonFromVerifier(nested)]));
2299
+ }
2300
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
2301
+ return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, jsonFromVerifier(nested)]));
2302
+ }
2303
+ return value;
2304
+ }
2305
+ function verifierRecapEntries(entries) {
2306
+ return entries.map((entry) => Array.isArray(entry.caveats) ? { ...entry, caveats: entry.caveats.map((caveat) => jsonFromVerifier(caveat)) } : entry);
2307
+ }
2292
2308
  var ServiceGraphLifetime = class {
2293
2309
  constructor(invokeFn, invokeAnyFn, fetchFn) {
2294
2310
  this.invokeFn = invokeFn;
@@ -2361,18 +2377,23 @@ var UnsupportedSessionRestoreError = class extends Error {
2361
2377
  this.name = "UnsupportedSessionRestoreError";
2362
2378
  }
2363
2379
  };
2380
+ var InvalidRestoredSessionError = class extends Error {
2381
+ constructor(message = "Persisted session authority is invalid or expired.") {
2382
+ super(message);
2383
+ this.code = "AUTH_EXPIRED";
2384
+ this.name = "InvalidRestoredSessionError";
2385
+ }
2386
+ };
2364
2387
  function canonicalRestoredVerificationMethod(canonicalVerificationMethod, persistedVerificationMethod) {
2365
2388
  if (typeof persistedVerificationMethod !== "string") return void 0;
2366
2389
  const principal = canonicalVerificationMethod.split("#", 1)[0];
2367
2390
  return persistedVerificationMethod === principal || persistedVerificationMethod === canonicalVerificationMethod ? canonicalVerificationMethod : void 0;
2368
2391
  }
2369
2392
  function persistedExpiry(value) {
2370
- if (typeof value !== "string") {
2371
- throw new Error("Persisted session without a SIWE expiration must include expiresAt.");
2372
- }
2393
+ if (typeof value !== "string") throw new InvalidRestoredSessionError("Persisted session must include expiresAt.");
2373
2394
  const expiry = new Date(value);
2374
2395
  if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {
2375
- throw new Error("Persisted session expiry is invalid or expired.");
2396
+ throw new InvalidRestoredSessionError();
2376
2397
  }
2377
2398
  return expiry;
2378
2399
  }
@@ -2915,16 +2936,26 @@ var _TinyCloudNode = class _TinyCloudNode {
2915
2936
  */
2916
2937
  getVerifiedSessionCapabilities() {
2917
2938
  const session = this.currentTinyCloudSession();
2918
- if (!session || !session.siwe) return [];
2919
- return parseRecapCapabilities(
2920
- (siwe) => this.parseRecapWithCaveats(siwe),
2921
- session.siwe
2922
- ).map((entry) => entry.service === "tinycloud.encryption" ? {
2923
- service: entry.service,
2924
- path: entry.path,
2925
- actions: [...entry.actions],
2926
- ...entry.caveats === void 0 ? {} : { caveats: entry.caveats }
2927
- } : entry);
2939
+ return session?.siwe ? this.projectSignedRecapCapabilities(session.siwe) : [];
2940
+ }
2941
+ /** Normalize signed capabilities without collapsing nested encryption into raw authority. */
2942
+ projectSignedRecapCapabilities(siwe) {
2943
+ const projected = this.parseRecapWithCaveats(siwe).map((entry) => {
2944
+ const normalized = parseRecapCapabilities(() => [entry], siwe)[0];
2945
+ if (normalized.service !== "tinycloud.encryption") return normalized;
2946
+ if (!this.isEncryptionNetworkOperation("encryption", entry.path, entry.space)) {
2947
+ return { ...normalized, space: entry.space };
2948
+ }
2949
+ return {
2950
+ service: normalized.service,
2951
+ path: normalized.path,
2952
+ actions: normalized.actions,
2953
+ ...normalized.caveats === void 0 ? {} : { caveats: normalized.caveats }
2954
+ };
2955
+ });
2956
+ return projected.sort(
2957
+ (left, right) => (left.space ?? "").localeCompare(right.space ?? "") || left.service.localeCompare(right.service) || left.path.localeCompare(right.path)
2958
+ );
2928
2959
  }
2929
2960
  /**
2930
2961
  * Get the Ethereum address for this user.
@@ -3379,9 +3410,9 @@ var _TinyCloudNode = class _TinyCloudNode {
3379
3410
  * We must keep the full owner-scoped URI so a synthetic primary grant can
3380
3411
  * never cover an operation on a different owner's space.
3381
3412
  *
3382
- * Mirrors {@link operationsFromDelegation}'s op shape: encryption network
3383
- * entries (`urn:tinycloud:encryption:` paths) become `resource` ops; every
3384
- * other entry becomes a `spaceId` op carrying the raw recap `space` URI.
3413
+ * Only top-level encryption network entries (`space: "encryption"` or
3414
+ * absent) become `resource` ops. A network-shaped path nested under a
3415
+ * data space remains a `spaceId` op, not raw network authority.
3385
3416
  * One op per action.
3386
3417
  *
3387
3418
  * Returns `[]` for session-only / restored-without-siwe modes and for any
@@ -3402,7 +3433,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3402
3433
  operations = entries.flatMap((entry) => {
3403
3434
  const service = this.invocationServiceName(entry.service);
3404
3435
  return entry.actions.map((action) => ({
3405
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space },
3436
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space },
3406
3437
  service,
3407
3438
  path: entry.path,
3408
3439
  action,
@@ -3564,7 +3595,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3564
3595
  return;
3565
3596
  } catch (error) {
3566
3597
  const message = error instanceof Error ? error.message : String(error);
3567
- if (/Unauthorized Action|\b401\b/.test(message)) {
3598
+ if (/Unauthorized Action|\b(?:401|403)\b/.test(message)) {
3568
3599
  console.warn(
3569
3600
  "TinyCloud account registry sync stopped: authorization verdict is not retryable",
3570
3601
  error
@@ -3814,9 +3845,14 @@ var _TinyCloudNode = class _TinyCloudNode {
3814
3845
  */
3815
3846
  async restoreSession(sessionData) {
3816
3847
  await this.wasmBindings.ensureInitialized?.();
3817
- const restoredJwk = clonePersistedSessionJwk(sessionData.jwk);
3848
+ let restoredJwk;
3849
+ try {
3850
+ restoredJwk = clonePersistedSessionJwk(sessionData.jwk);
3851
+ } catch {
3852
+ throw new InvalidRestoredSessionError("Persisted session has an invalid private Ed25519 session key.");
3853
+ }
3818
3854
  if (sessionData.chainId !== void 0 && (!Number.isSafeInteger(sessionData.chainId) || sessionData.chainId <= 0)) {
3819
- throw new Error("Persisted session chain ID must be a positive safe integer.");
3855
+ throw new InvalidRestoredSessionError("Persisted session chain ID must be a positive safe integer.");
3820
3856
  }
3821
3857
  const stagedManager = this.wasmBindings.createSessionManager();
3822
3858
  const stagedReplace = stagedManager.replaceSessionKey;
@@ -3828,32 +3864,31 @@ var _TinyCloudNode = class _TinyCloudNode {
3828
3864
  let stagedKeyId;
3829
3865
  let stagedJwk;
3830
3866
  let canonicalVerificationMethod;
3867
+ const keyIds = liveKeys.call(this.sessionManager);
3868
+ if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === "string")) {
3869
+ throw new UnsupportedSessionRestoreError("it cannot reliably enumerate every live session signer");
3870
+ }
3871
+ for (const keyId of keyIds) {
3872
+ if (keyId === this.sessionKeyId) continue;
3873
+ const jwk = this.sessionManager.jwk(keyId);
3874
+ if (!jwk) throw new Error("missing live session key");
3875
+ stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);
3876
+ }
3831
3877
  try {
3832
- const keyIds = liveKeys.call(this.sessionManager);
3833
- if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === "string")) {
3834
- throw new UnsupportedSessionRestoreError("it cannot reliably enumerate every live session signer");
3835
- }
3836
- for (const keyId of keyIds) {
3837
- if (keyId === this.sessionKeyId) continue;
3838
- const jwk = this.sessionManager.jwk(keyId);
3839
- if (!jwk) throw new Error("missing live session key");
3840
- stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);
3841
- }
3842
3878
  stagedKeyId = stagedReplace.call(stagedManager, restoredJwk, this.sessionKeyId);
3843
- const stagedJwkJson = stagedManager.jwk(stagedKeyId);
3844
- if (!stagedJwkJson) throw new Error("missing restored session key");
3845
- stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));
3846
- canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);
3847
- } catch (error) {
3848
- if (error instanceof UnsupportedSessionRestoreError) throw error;
3849
- throw new Error("Persisted session has an invalid private Ed25519 session key.");
3879
+ } catch {
3880
+ throw new InvalidRestoredSessionError("Persisted session has an invalid private Ed25519 session key.");
3850
3881
  }
3882
+ const stagedJwkJson = stagedManager.jwk(stagedKeyId);
3883
+ if (!stagedJwkJson) throw new Error("missing restored session key");
3884
+ stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));
3885
+ canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);
3851
3886
  const restoredVerificationMethod = canonicalRestoredVerificationMethod(
3852
3887
  canonicalVerificationMethod,
3853
3888
  sessionData.verificationMethod
3854
3889
  );
3855
3890
  if (!restoredVerificationMethod) {
3856
- throw new Error(
3891
+ throw new InvalidRestoredSessionError(
3857
3892
  "Persisted session verification method does not match its private Ed25519 session key."
3858
3893
  );
3859
3894
  }
@@ -3865,26 +3900,37 @@ var _TinyCloudNode = class _TinyCloudNode {
3865
3900
  ];
3866
3901
  const hasPersistedProof = proofValues.every((value) => value !== void 0);
3867
3902
  if (!hasPersistedProof && (proofValues.some((value) => value !== void 0) || sessionData.expiresAt !== void 0)) {
3868
- throw new Error("Persisted session authority metadata is incomplete.");
3903
+ throw new InvalidRestoredSessionError("Persisted session authority metadata is incomplete.");
3904
+ }
3905
+ let restoredAddress;
3906
+ try {
3907
+ restoredAddress = hasPersistedProof ? canonicalizeAddress2(sessionData.address) : void 0;
3908
+ } catch {
3909
+ throw new InvalidRestoredSessionError("Persisted session has an invalid wallet address.");
3869
3910
  }
3870
- const restoredAddress = hasPersistedProof ? canonicalizeAddress2(sessionData.address) : void 0;
3871
3911
  let stagedSessionExpiry = /* @__PURE__ */ new Date(0);
3872
3912
  let stagedRecap = [];
3873
3913
  if (hasPersistedProof) {
3874
3914
  if (typeof this.wasmBindings.validatePersistedSession !== "function") {
3875
3915
  throw new UnsupportedSessionRestoreError("it cannot verify persisted SIWE authority");
3876
3916
  }
3877
- const verified = this.wasmBindings.validatePersistedSession({
3878
- delegationHeader: sessionData.delegationHeader,
3879
- delegationCid: sessionData.delegationCid,
3880
- spaceId: sessionData.spaceId,
3881
- jwk: stagedJwk,
3882
- address: restoredAddress,
3883
- chainId: sessionData.chainId,
3884
- siwe: sessionData.siwe,
3885
- signature: sessionData.signature
3886
- });
3887
- const exactRecap = verified.verifiedRecap;
3917
+ const verified = (() => {
3918
+ try {
3919
+ return this.wasmBindings.validatePersistedSession({
3920
+ delegationHeader: sessionData.delegationHeader,
3921
+ delegationCid: sessionData.delegationCid,
3922
+ spaceId: sessionData.spaceId,
3923
+ jwk: stagedJwk,
3924
+ address: restoredAddress,
3925
+ chainId: sessionData.chainId,
3926
+ siwe: sessionData.siwe,
3927
+ signature: sessionData.signature
3928
+ });
3929
+ } catch (error) {
3930
+ throw new InvalidRestoredSessionError(error instanceof Error ? error.message : String(error));
3931
+ }
3932
+ })();
3933
+ const exactRecap = Array.isArray(verified.verifiedRecap) ? verifierRecapEntries(verified.verifiedRecap) : verified.verifiedRecap;
3888
3934
  if (!Array.isArray(exactRecap) || !exactRecap.every(
3889
3935
  (entry) => entry !== null && typeof entry === "object" && typeof entry.service === "string" && typeof entry.space === "string" && typeof entry.path === "string" && Array.isArray(entry.actions) && entry.actions.every((action) => typeof action === "string") && Array.isArray(entry.caveats) && entry.caveats.every(
3890
3936
  (caveat) => caveat !== null && typeof caveat === "object" && !Array.isArray(caveat)
@@ -3904,7 +3950,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3904
3950
  const signedExpiry = verified.expiresAt === void 0 ? void 0 : persistedExpiry(verified.expiresAt);
3905
3951
  const persistedPolicyExpiry = sessionData.expiresAt === void 0 ? void 0 : persistedExpiry(sessionData.expiresAt);
3906
3952
  if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {
3907
- throw new Error("Persisted session expiry does not match its signed SIWE authority.");
3953
+ throw new InvalidRestoredSessionError("Persisted session expiry does not match its signed SIWE authority.");
3908
3954
  }
3909
3955
  stagedSessionExpiry = signedExpiry ?? persistedPolicyExpiry ?? persistedExpiry(void 0);
3910
3956
  }
@@ -4001,7 +4047,7 @@ var _TinyCloudNode = class _TinyCloudNode {
4001
4047
  operations = recap.flatMap((entry) => {
4002
4048
  const service = this.invocationServiceName(entry.service);
4003
4049
  return entry.actions.map((action) => ({
4004
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space },
4050
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space },
4005
4051
  service,
4006
4052
  path: entry.path,
4007
4053
  action,
@@ -4097,7 +4143,7 @@ var _TinyCloudNode = class _TinyCloudNode {
4097
4143
  const delegations = input.recap.map((entry) => ({
4098
4144
  cid: session.delegationCid,
4099
4145
  delegateDID: session.verificationMethod,
4100
- spaceId: entry.space,
4146
+ spaceId: this.spaceIdsEqual(entry.space, session.spaceId) ? session.spaceId : entry.space,
4101
4147
  path: entry.path,
4102
4148
  actions: [...entry.actions],
4103
4149
  caveats: cloneRecapCaveats(entry.caveats),
@@ -4787,16 +4833,11 @@ var _TinyCloudNode = class _TinyCloudNode {
4787
4833
  );
4788
4834
  graph.assertActive();
4789
4835
  if (!response.ok) {
4790
- let permissionHint;
4791
- if (response.status === 401 || response.status === 403) {
4792
- try {
4793
- const body = await response.json();
4794
- const record = typeof body === "object" && body !== null ? body : void 0;
4795
- const nested = typeof record?.error === "object" && record.error !== null ? record.error : void 0;
4796
- permissionHint = parsePermissionHint(record?.permissionHint) ?? parsePermissionHint(nested?.permissionHint);
4797
- } catch {
4798
- }
4799
- }
4836
+ const permissionHint = response.status === 401 || response.status === 403 ? parsePermissionHint({
4837
+ service: "tinycloud.encryption",
4838
+ path: networkId,
4839
+ actions: ["tinycloud.encryption/decrypt"]
4840
+ }) : void 0;
4800
4841
  throw new DecryptTransportResponseError(response.status, permissionHint);
4801
4842
  }
4802
4843
  return await response.json();
@@ -5235,13 +5276,20 @@ var _TinyCloudNode = class _TinyCloudNode {
5235
5276
  const session = this.currentTinyCloudSession();
5236
5277
  const serviceSession = this._serviceContext?.session;
5237
5278
  if (!session || !serviceSession) throw new Error("Share delivery requires an authenticated session");
5279
+ const idempotencyBytes = new TextEncoder().encode(input.idempotencyKey);
5280
+ if (idempotencyBytes.byteLength === 0 || idempotencyBytes.byteLength > 512) {
5281
+ throw new Error("Share delivery idempotency key is invalid");
5282
+ }
5283
+ const jtiDigest = new Uint8Array(await crypto.subtle.digest("SHA-256", idempotencyBytes));
5238
5284
  const body = {
5239
5285
  envelope: input.envelope,
5286
+ sealedEnvelope: input.sealedEnvelope,
5287
+ envelopeKey: input.envelopeKey,
5240
5288
  shareCid: input.shareCid,
5241
5289
  recipientEmail: input.recipientEmail,
5242
5290
  shareUrl: input.shareUrl,
5243
5291
  documentName: input.documentName,
5244
- jti: base64UrlEncode(crypto.getRandomValues(new Uint8Array(16))),
5292
+ jti: base64UrlEncode(jtiDigest.slice(0, 16)),
5245
5293
  expiresAt: new Date(input.expiresAt).toISOString().replace(/\.\d{3}Z$/, "Z")
5246
5294
  };
5247
5295
  const requestBodyDigest = base64UrlEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalizeEncryptionJson(body)))));
@@ -5724,7 +5772,7 @@ var _TinyCloudNode = class _TinyCloudNode {
5724
5772
  continue;
5725
5773
  }
5726
5774
  let space;
5727
- if (service !== "tinycloud.encryption") {
5775
+ if (service !== "tinycloud.encryption" || operation.resource === void 0) {
5728
5776
  if (typeof operation.spaceId !== "string") continue;
5729
5777
  try {
5730
5778
  space = this.resolvePermissionSpace(operation.spaceId, session);
@@ -6269,11 +6317,8 @@ var _TinyCloudNode = class _TinyCloudNode {
6269
6317
  );
6270
6318
  return { delegation: delegation2, prompted: true };
6271
6319
  }
6272
- const granted = parseRecapCapabilities(
6273
- (siwe) => this.parseRecapWithCaveats(siwe),
6274
- session.siwe
6275
- );
6276
- const { subset, missing } = isCapabilitySubset(expandedEntries, granted);
6320
+ const granted = this.projectSignedRecapCapabilities(session.siwe);
6321
+ const { subset, missing } = this.signedCapabilitySubset(expandedEntries, granted);
6277
6322
  if (!subset) {
6278
6323
  const runtimeOperations = this.permissionEntriesToOperations(expandedEntries, session);
6279
6324
  const runtimeGrant = this.findGrantForOperations(
@@ -6593,7 +6638,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6593
6638
  return abilities;
6594
6639
  }
6595
6640
  isEncryptionPermissionEntry(entry) {
6596
- return entry.service === ENCRYPTION_PERMISSION_SERVICE2 && entry.path.startsWith("urn:tinycloud:encryption:");
6641
+ return entry.service === ENCRYPTION_PERMISSION_SERVICE2 && this.isEncryptionNetworkOperation("encryption", entry.path, entry.space);
6597
6642
  }
6598
6643
  permissionsToRawAbilities(entries) {
6599
6644
  const rawAbilities = {};
@@ -6617,7 +6662,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6617
6662
  return entries.flatMap((entry) => {
6618
6663
  const service = this.shortServiceName(entry.service);
6619
6664
  return entry.actions.map((action) => ({
6620
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId },
6665
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId },
6621
6666
  service,
6622
6667
  path: entry.path,
6623
6668
  action,
@@ -6625,13 +6670,21 @@ var _TinyCloudNode = class _TinyCloudNode {
6625
6670
  }));
6626
6671
  });
6627
6672
  }
6673
+ /** Raw network authority cannot be covered by a nested encryption space. */
6674
+ signedCapabilitySubset(requested, granted) {
6675
+ const rawGranted = granted.filter((entry) => this.isEncryptionPermissionEntry(entry)).map((entry) => ({ ...entry, space: "encryption" }));
6676
+ const spaceGranted = granted.filter((entry) => !this.isEncryptionPermissionEntry(entry));
6677
+ const missing = requested.filter((entry) => {
6678
+ const raw = this.isEncryptionPermissionEntry(entry);
6679
+ const comparable = raw ? { ...entry, space: "encryption" } : entry;
6680
+ return !isCapabilitySubset([comparable], raw ? rawGranted : spaceGranted).subset;
6681
+ });
6682
+ return { subset: missing.length === 0, missing };
6683
+ }
6628
6684
  sessionCoversPermissionEntries(session, entries) {
6629
6685
  try {
6630
- const granted = parseRecapCapabilities(
6631
- (siwe) => this.parseRecapWithCaveats(siwe),
6632
- session.siwe
6633
- );
6634
- return isCapabilitySubset(entries, granted).subset;
6686
+ const granted = this.projectSignedRecapCapabilities(session.siwe);
6687
+ return this.signedCapabilitySubset(entries, granted).subset;
6635
6688
  } catch {
6636
6689
  return false;
6637
6690
  }
@@ -6641,7 +6694,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6641
6694
  const spaceId = this.resolvePermissionSpace(entry.space, session);
6642
6695
  const service = this.shortServiceName(entry.service);
6643
6696
  return entry.actions.map((action) => ({
6644
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId },
6697
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId },
6645
6698
  service,
6646
6699
  path: entry.path,
6647
6700
  action,
@@ -6730,7 +6783,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6730
6783
  return resources.flatMap((resource) => {
6731
6784
  const service = this.invocationServiceName(resource.service);
6732
6785
  return resource.actions.map((action) => ({
6733
- ...this.isEncryptionNetworkOperation(service, resource.path) ? { resource: resource.path } : { spaceId: resource.space },
6786
+ ...this.isEncryptionNetworkOperation(service, resource.path, resource.space) ? { resource: resource.path } : { spaceId: resource.space },
6734
6787
  service,
6735
6788
  path: resource.path,
6736
6789
  action,
@@ -6791,7 +6844,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6791
6844
  };
6792
6845
  for (const resource of resources) {
6793
6846
  const service = this.invocationServiceName(resource.service);
6794
- if (this.isEncryptionNetworkOperation(service, resource.path)) {
6847
+ if (this.isEncryptionNetworkOperation(service, resource.path, resource.space)) {
6795
6848
  rawAbilities[_a = resource.path] ?? (rawAbilities[_a] = []);
6796
6849
  addActions(rawAbilities[resource.path], resource.actions);
6797
6850
  continue;
@@ -6860,21 +6913,15 @@ var _TinyCloudNode = class _TinyCloudNode {
6860
6913
  }
6861
6914
  return granted.spaceId !== void 0 && requested.spaceId !== void 0 && this.spaceIdsEqual(granted.spaceId, requested.spaceId) && this.pathContains(granted.path, requested.path);
6862
6915
  }
6863
- // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. The embedded
6864
- // EIP-155 address is case-insensitive, but the CLI canonicalizes it to
6865
- // lowercase when building a space URI while stored runtime delegations keep
6866
- // the EIP-55 checksummed form — so a byte-for-byte compare spuriously rejects
6867
- // an otherwise-valid grant. Lowercase ONLY the `eip155:<chain>:0x<addr>`
6868
- // segment and leave everything else (crucially the case-sensitive space NAME)
6869
- // byte-exact. Mirrors the CLI's `normalizeSpaceForCompare` (OPENKEY_SCOPE_MISMATCH fix).
6916
+ // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. Compare
6917
+ // only the embedded EIP-155 address without case sensitivity; chain, name,
6918
+ // and all non-PKH space identifiers remain byte-exact.
6870
6919
  spaceIdsEqual(a, b) {
6871
6920
  return this.normalizeSpaceAddress(a) === this.normalizeSpaceAddress(b);
6872
6921
  }
6873
6922
  normalizeSpaceAddress(space) {
6874
- return space.replace(
6875
- /(eip155:\d+:)(0x[0-9a-fA-F]{40})/,
6876
- (_match, prefix, addr) => prefix + addr.toLowerCase()
6877
- );
6923
+ const match = /^(tinycloud:pkh:eip155:\d+:)(0x[0-9a-fA-F]{40})(:.+)$/.exec(space);
6924
+ return match === null ? space : `${match[1]}${match[2].toLowerCase()}${match[3]}`;
6878
6925
  }
6879
6926
  actionContains(grantedAction, requestedAction) {
6880
6927
  if (grantedAction === requestedAction) {
@@ -6891,10 +6938,11 @@ var _TinyCloudNode = class _TinyCloudNode {
6891
6938
  }
6892
6939
  /** Prefer the v2 caveat-preserving parser while retaining old custom WASM. */
6893
6940
  parseRecapWithCaveats(siwe) {
6894
- return this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe) ?? this.wasmBindings.parseRecapFromSiwe(siwe);
6941
+ const verified = this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe);
6942
+ return verified == null ? this.wasmBindings.parseRecapFromSiwe(siwe) : verifierRecapEntries(verified);
6895
6943
  }
6896
- isEncryptionNetworkOperation(service, path) {
6897
- return service === "encryption" && path.startsWith("urn:tinycloud:encryption:");
6944
+ isEncryptionNetworkOperation(service, path, space) {
6945
+ return service === "encryption" && (space === void 0 || space === "encryption") && path.startsWith("urn:tinycloud:encryption:");
6898
6946
  }
6899
6947
  operationFromInvokeAnyEntry(entry) {
6900
6948
  const service = this.invocationServiceName(entry.service);
@@ -6907,7 +6955,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6907
6955
  ...entry.caveats === void 0 ? {} : { caveats: cloneRecapCaveats(entry.caveats) }
6908
6956
  };
6909
6957
  }
6910
- if (this.isEncryptionNetworkOperation(service, entry.path)) {
6958
+ if (entry.spaceId === void 0 && this.isEncryptionNetworkOperation(service, entry.path)) {
6911
6959
  return {
6912
6960
  resource: entry.path,
6913
6961
  service,
@@ -7192,8 +7240,7 @@ var _TinyCloudNode = class _TinyCloudNode {
7192
7240
  const jwk = mySession.jwk;
7193
7241
  const { abilities, rawAbilities } = this.buildActivationAbilities(delegation);
7194
7242
  const now = /* @__PURE__ */ new Date();
7195
- const maxExpiry = new Date(now.getTime() + 60 * 60 * 1e3);
7196
- const expirationTime = delegation.expiry < maxExpiry ? delegation.expiry : maxExpiry;
7243
+ const expirationTime = delegation.expiry;
7197
7244
  const prepared = this.wasmBindings.prepareSession({
7198
7245
  abilities,
7199
7246
  address: this.wasmBindings.ensureEip55(mySession.address),
@@ -7297,8 +7344,7 @@ var _TinyCloudNode = class _TinyCloudNode {
7297
7344
  );
7298
7345
  }
7299
7346
  const now = /* @__PURE__ */ new Date();
7300
- const expiryMs = params.expiryMs ?? 60 * 60 * 1e3;
7301
- const requestedExpiry = new Date(now.getTime() + expiryMs);
7347
+ const requestedExpiry = params.expiryMs === void 0 ? parentDelegation.expiry : new Date(now.getTime() + params.expiryMs);
7302
7348
  const actualExpiry = requestedExpiry > parentDelegation.expiry ? parentDelegation.expiry : requestedExpiry;
7303
7349
  const abilities = {};
7304
7350
  const rawAbilities = {};
@@ -7818,6 +7864,7 @@ export {
7818
7864
  DuckDbService3 as DuckDbService,
7819
7865
  FileSessionStorage,
7820
7866
  IdentityParseError,
7867
+ InvalidRestoredSessionError,
7821
7868
  KVService3 as KVService,
7822
7869
  ManifestValidationError,
7823
7870
  MemorySessionStorage,