@tinycloud/node-sdk 3.0.0-beta.9 → 3.0.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, CapabilityPresentationEnvelopeV1, IWasmBindings, PersistedSessionProof, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, AccountDelegationRecord, AccountDelegationResource, 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, CaveatedDelegationUnsupportedError, 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, DecryptTransportResponseError, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DelegationRevocationReceipt, 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, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, OwnerDelegationPermission, ParsedNetworkId, ParsedSecretCatalogKey, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, 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, 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, VaultNetworkReadResult, 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, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as ACCEPTED_MARKER_VERSIONS, a as AuthDelegationArtifact, b as AuthRequestArtifact, B as BOOTSTRAP_COMPLETION_MARKER_KEY, c as BOOTSTRAP_COMPLETION_MARKER_VERSION, d as BootstrapCompletionMarker, e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, i as DelegationAuthority, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, R as RestorableSession, l as RuntimeDelegationActivator, 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, v as activateValidatedRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, z as grantAuthRequest, G as serializeDelegation } from './core-BTuD37zN.cjs';
3
+ export { A as ACCEPTED_MARKER_VERSIONS, a as AuthDelegationArtifact, b as AuthRequestArtifact, B as BOOTSTRAP_COMPLETION_MARKER_KEY, c as BOOTSTRAP_COMPLETION_MARKER_VERSION, d as BootstrapCompletionMarker, e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, i as DelegationAuthority, 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, R as RestorableSession, l as RuntimeDelegationActivator, 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, v as activateValidatedRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, z as grantAuthRequest, G as serializeDelegation } from './core-DufYfxi-.cjs';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, parseVerifiedRecapFromSiwe, 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';
@@ -133,6 +133,28 @@ type NodeUserAuthorizationAuthorizeFn = (input: OpenKeyBridgeInput) => Promise<{
133
133
  */
134
134
  declare function wireOpenKeyAuthorize(openkey: OpenKeyAuthorizeTinyCloud): NodeUserAuthorizationAuthorizeFn;
135
135
 
136
+ /**
137
+ * Internal helpers for TinyCloudNode.delegateTo and the legacy
138
+ * createDelegation compatibility shim. Exported from their own module so
139
+ * they are easy to unit-test without spinning up a full TinyCloudNode.
140
+ *
141
+ * None of these are part of the public API — the module path is not
142
+ * re-exported from `@tinycloud/node-sdk` or `@tinycloud/node-sdk/core`.
143
+ *
144
+ * @packageDocumentation
145
+ */
146
+
147
+ /**
148
+ * Extract the `expirationTime` field of a signed SIWE message as a `Date`.
149
+ *
150
+ * Returns `undefined` only when the SIWE genuinely has no `Expiration Time`
151
+ * line (RFC-4501 permits it). Propagates parse errors — the SDK always
152
+ * produces signed SIWEs during sign-in, so an unparseable `session.siwe`
153
+ * means something is actively wrong and we do not want to silently skip
154
+ * the expiry check.
155
+ */
156
+ declare function extractSiweExpiration(siwe: string): Date | undefined;
157
+
136
158
  /**
137
159
  * NodeWasmBindings - Default IWasmBindings implementation for Node.js.
138
160
  *
@@ -175,4 +197,4 @@ declare class NodeWasmBindings implements IWasmBindings {
175
197
  createSessionManager(): ISessionManager;
176
198
  }
177
199
 
178
- export { type NodeUserAuthorizationAuthorizeFn, NodeWasmBindings, type OpenKeyAuthorizeTinyCloud, type OpenKeyBridgeInput, PrivateKeySigner, wireOpenKeyAuthorize };
200
+ export { type NodeUserAuthorizationAuthorizeFn, NodeWasmBindings, type OpenKeyAuthorizeTinyCloud, type OpenKeyBridgeInput, PrivateKeySigner, extractSiweExpiration, wireOpenKeyAuthorize };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISigner, Bytes, CapabilityPresentationEnvelopeV1, IWasmBindings, PersistedSessionProof, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, AccountDelegationRecord, AccountDelegationResource, 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, CaveatedDelegationUnsupportedError, 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, DecryptTransportResponseError, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DelegationRevocationReceipt, 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, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, OwnerDelegationPermission, ParsedNetworkId, ParsedSecretCatalogKey, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, 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, 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, VaultNetworkReadResult, 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, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as ACCEPTED_MARKER_VERSIONS, a as AuthDelegationArtifact, b as AuthRequestArtifact, B as BOOTSTRAP_COMPLETION_MARKER_KEY, c as BOOTSTRAP_COMPLETION_MARKER_VERSION, d as BootstrapCompletionMarker, e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, i as DelegationAuthority, E as EnsureEncryptionNetworkOptions, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, j as NodeUserAuthorization, k as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, P as PortableDelegation, R as RestorableSession, l as RuntimeDelegationActivator, 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, v as activateValidatedRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, z as grantAuthRequest, G as serializeDelegation } from './core-BTuD37zN.js';
3
+ export { A as ACCEPTED_MARKER_VERSIONS, a as AuthDelegationArtifact, b as AuthRequestArtifact, B as BOOTSTRAP_COMPLETION_MARKER_KEY, c as BOOTSTRAP_COMPLETION_MARKER_VERSION, d as BootstrapCompletionMarker, e as BootstrapWarning, C as CompactRuntimeDelegationInput, f as CreateOwnerDelegationParams, D as DelegateToOptions, g as DelegateToResult, h as DelegatedAccess, i as DelegationAuthority, 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, R as RestorableSession, l as RuntimeDelegationActivator, 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, v as activateValidatedRuntimeDelegation, w as createWasmKeyProvider, x as defaultSignStrategy, y as deserializeDelegation, z as grantAuthRequest, G as serializeDelegation } from './core-DufYfxi-.js';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, parseVerifiedRecapFromSiwe, 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';
@@ -133,6 +133,28 @@ type NodeUserAuthorizationAuthorizeFn = (input: OpenKeyBridgeInput) => Promise<{
133
133
  */
134
134
  declare function wireOpenKeyAuthorize(openkey: OpenKeyAuthorizeTinyCloud): NodeUserAuthorizationAuthorizeFn;
135
135
 
136
+ /**
137
+ * Internal helpers for TinyCloudNode.delegateTo and the legacy
138
+ * createDelegation compatibility shim. Exported from their own module so
139
+ * they are easy to unit-test without spinning up a full TinyCloudNode.
140
+ *
141
+ * None of these are part of the public API — the module path is not
142
+ * re-exported from `@tinycloud/node-sdk` or `@tinycloud/node-sdk/core`.
143
+ *
144
+ * @packageDocumentation
145
+ */
146
+
147
+ /**
148
+ * Extract the `expirationTime` field of a signed SIWE message as a `Date`.
149
+ *
150
+ * Returns `undefined` only when the SIWE genuinely has no `Expiration Time`
151
+ * line (RFC-4501 permits it). Propagates parse errors — the SDK always
152
+ * produces signed SIWEs during sign-in, so an unparseable `session.siwe`
153
+ * means something is actively wrong and we do not want to silently skip
154
+ * the expiry check.
155
+ */
156
+ declare function extractSiweExpiration(siwe: string): Date | undefined;
157
+
136
158
  /**
137
159
  * NodeWasmBindings - Default IWasmBindings implementation for Node.js.
138
160
  *
@@ -175,4 +197,4 @@ declare class NodeWasmBindings implements IWasmBindings {
175
197
  createSessionManager(): ISessionManager;
176
198
  }
177
199
 
178
- export { type NodeUserAuthorizationAuthorizeFn, NodeWasmBindings, type OpenKeyAuthorizeTinyCloud, type OpenKeyBridgeInput, PrivateKeySigner, wireOpenKeyAuthorize };
200
+ export { type NodeUserAuthorizationAuthorizeFn, NodeWasmBindings, type OpenKeyAuthorizeTinyCloud, type OpenKeyBridgeInput, PrivateKeySigner, extractSiweExpiration, wireOpenKeyAuthorize };
package/dist/index.js CHANGED
@@ -19299,6 +19299,22 @@ function cloneRecapCaveats(caveats) {
19299
19299
  throw new Error("Verified persisted session ReCap contains invalid caveats.");
19300
19300
  }
19301
19301
  }
19302
+ function jsonFromVerifier(value) {
19303
+ if (value === void 0) return null;
19304
+ if (Array.isArray(value)) return value.map(jsonFromVerifier);
19305
+ if (value instanceof Map) {
19306
+ const entries = [...value.entries()];
19307
+ if (!entries.every(([key2]) => typeof key2 === "string")) return value;
19308
+ return Object.fromEntries(entries.map(([key2, nested]) => [key2, jsonFromVerifier(nested)]));
19309
+ }
19310
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
19311
+ return Object.fromEntries(Object.entries(value).map(([key2, nested]) => [key2, jsonFromVerifier(nested)]));
19312
+ }
19313
+ return value;
19314
+ }
19315
+ function verifierRecapEntries(entries) {
19316
+ return entries.map((entry) => Array.isArray(entry.caveats) ? { ...entry, caveats: entry.caveats.map((caveat) => jsonFromVerifier(caveat)) } : entry);
19317
+ }
19302
19318
  var ServiceGraphLifetime = class {
19303
19319
  constructor(invokeFn, invokeAnyFn, fetchFn) {
19304
19320
  this.invokeFn = invokeFn;
@@ -19371,18 +19387,23 @@ var UnsupportedSessionRestoreError = class extends Error {
19371
19387
  this.name = "UnsupportedSessionRestoreError";
19372
19388
  }
19373
19389
  };
19390
+ var InvalidRestoredSessionError = class extends Error {
19391
+ constructor(message = "Persisted session authority is invalid or expired.") {
19392
+ super(message);
19393
+ this.code = "AUTH_EXPIRED";
19394
+ this.name = "InvalidRestoredSessionError";
19395
+ }
19396
+ };
19374
19397
  function canonicalRestoredVerificationMethod(canonicalVerificationMethod, persistedVerificationMethod) {
19375
19398
  if (typeof persistedVerificationMethod !== "string") return void 0;
19376
19399
  const principal = canonicalVerificationMethod.split("#", 1)[0];
19377
19400
  return persistedVerificationMethod === principal || persistedVerificationMethod === canonicalVerificationMethod ? canonicalVerificationMethod : void 0;
19378
19401
  }
19379
19402
  function persistedExpiry(value) {
19380
- if (typeof value !== "string") {
19381
- throw new Error("Persisted session without a SIWE expiration must include expiresAt.");
19382
- }
19403
+ if (typeof value !== "string") throw new InvalidRestoredSessionError("Persisted session must include expiresAt.");
19383
19404
  const expiry = new Date(value);
19384
19405
  if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {
19385
- throw new Error("Persisted session expiry is invalid or expired.");
19406
+ throw new InvalidRestoredSessionError();
19386
19407
  }
19387
19408
  return expiry;
19388
19409
  }
@@ -19925,16 +19946,26 @@ var _TinyCloudNode = class _TinyCloudNode {
19925
19946
  */
19926
19947
  getVerifiedSessionCapabilities() {
19927
19948
  const session = this.currentTinyCloudSession();
19928
- if (!session || !session.siwe) return [];
19929
- return parseRecapCapabilities(
19930
- (siwe) => this.parseRecapWithCaveats(siwe),
19931
- session.siwe
19932
- ).map((entry) => entry.service === "tinycloud.encryption" ? {
19933
- service: entry.service,
19934
- path: entry.path,
19935
- actions: [...entry.actions],
19936
- ...entry.caveats === void 0 ? {} : { caveats: entry.caveats }
19937
- } : entry);
19949
+ return session?.siwe ? this.projectSignedRecapCapabilities(session.siwe) : [];
19950
+ }
19951
+ /** Normalize signed capabilities without collapsing nested encryption into raw authority. */
19952
+ projectSignedRecapCapabilities(siwe) {
19953
+ const projected = this.parseRecapWithCaveats(siwe).map((entry) => {
19954
+ const normalized = parseRecapCapabilities(() => [entry], siwe)[0];
19955
+ if (normalized.service !== "tinycloud.encryption") return normalized;
19956
+ if (!this.isEncryptionNetworkOperation("encryption", entry.path, entry.space)) {
19957
+ return { ...normalized, space: entry.space };
19958
+ }
19959
+ return {
19960
+ service: normalized.service,
19961
+ path: normalized.path,
19962
+ actions: normalized.actions,
19963
+ ...normalized.caveats === void 0 ? {} : { caveats: normalized.caveats }
19964
+ };
19965
+ });
19966
+ return projected.sort(
19967
+ (left, right) => (left.space ?? "").localeCompare(right.space ?? "") || left.service.localeCompare(right.service) || left.path.localeCompare(right.path)
19968
+ );
19938
19969
  }
19939
19970
  /**
19940
19971
  * Get the Ethereum address for this user.
@@ -20389,9 +20420,9 @@ var _TinyCloudNode = class _TinyCloudNode {
20389
20420
  * We must keep the full owner-scoped URI so a synthetic primary grant can
20390
20421
  * never cover an operation on a different owner's space.
20391
20422
  *
20392
- * Mirrors {@link operationsFromDelegation}'s op shape: encryption network
20393
- * entries (`urn:tinycloud:encryption:` paths) become `resource` ops; every
20394
- * other entry becomes a `spaceId` op carrying the raw recap `space` URI.
20423
+ * Only top-level encryption network entries (`space: "encryption"` or
20424
+ * absent) become `resource` ops. A network-shaped path nested under a
20425
+ * data space remains a `spaceId` op, not raw network authority.
20395
20426
  * One op per action.
20396
20427
  *
20397
20428
  * Returns `[]` for session-only / restored-without-siwe modes and for any
@@ -20412,7 +20443,7 @@ var _TinyCloudNode = class _TinyCloudNode {
20412
20443
  operations = entries.flatMap((entry) => {
20413
20444
  const service = this.invocationServiceName(entry.service);
20414
20445
  return entry.actions.map((action) => ({
20415
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space },
20446
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space },
20416
20447
  service,
20417
20448
  path: entry.path,
20418
20449
  action,
@@ -20574,7 +20605,7 @@ var _TinyCloudNode = class _TinyCloudNode {
20574
20605
  return;
20575
20606
  } catch (error) {
20576
20607
  const message = error instanceof Error ? error.message : String(error);
20577
- if (/Unauthorized Action|\b401\b/.test(message)) {
20608
+ if (/Unauthorized Action|\b(?:401|403)\b/.test(message)) {
20578
20609
  console.warn(
20579
20610
  "TinyCloud account registry sync stopped: authorization verdict is not retryable",
20580
20611
  error
@@ -20824,9 +20855,14 @@ var _TinyCloudNode = class _TinyCloudNode {
20824
20855
  */
20825
20856
  async restoreSession(sessionData) {
20826
20857
  await this.wasmBindings.ensureInitialized?.();
20827
- const restoredJwk = clonePersistedSessionJwk(sessionData.jwk);
20858
+ let restoredJwk;
20859
+ try {
20860
+ restoredJwk = clonePersistedSessionJwk(sessionData.jwk);
20861
+ } catch {
20862
+ throw new InvalidRestoredSessionError("Persisted session has an invalid private Ed25519 session key.");
20863
+ }
20828
20864
  if (sessionData.chainId !== void 0 && (!Number.isSafeInteger(sessionData.chainId) || sessionData.chainId <= 0)) {
20829
- throw new Error("Persisted session chain ID must be a positive safe integer.");
20865
+ throw new InvalidRestoredSessionError("Persisted session chain ID must be a positive safe integer.");
20830
20866
  }
20831
20867
  const stagedManager = this.wasmBindings.createSessionManager();
20832
20868
  const stagedReplace = stagedManager.replaceSessionKey;
@@ -20838,32 +20874,31 @@ var _TinyCloudNode = class _TinyCloudNode {
20838
20874
  let stagedKeyId;
20839
20875
  let stagedJwk;
20840
20876
  let canonicalVerificationMethod;
20877
+ const keyIds = liveKeys.call(this.sessionManager);
20878
+ if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === "string")) {
20879
+ throw new UnsupportedSessionRestoreError("it cannot reliably enumerate every live session signer");
20880
+ }
20881
+ for (const keyId of keyIds) {
20882
+ if (keyId === this.sessionKeyId) continue;
20883
+ const jwk = this.sessionManager.jwk(keyId);
20884
+ if (!jwk) throw new Error("missing live session key");
20885
+ stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);
20886
+ }
20841
20887
  try {
20842
- const keyIds = liveKeys.call(this.sessionManager);
20843
- if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === "string")) {
20844
- throw new UnsupportedSessionRestoreError("it cannot reliably enumerate every live session signer");
20845
- }
20846
- for (const keyId of keyIds) {
20847
- if (keyId === this.sessionKeyId) continue;
20848
- const jwk = this.sessionManager.jwk(keyId);
20849
- if (!jwk) throw new Error("missing live session key");
20850
- stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);
20851
- }
20852
20888
  stagedKeyId = stagedReplace.call(stagedManager, restoredJwk, this.sessionKeyId);
20853
- const stagedJwkJson = stagedManager.jwk(stagedKeyId);
20854
- if (!stagedJwkJson) throw new Error("missing restored session key");
20855
- stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));
20856
- canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);
20857
- } catch (error) {
20858
- if (error instanceof UnsupportedSessionRestoreError) throw error;
20859
- throw new Error("Persisted session has an invalid private Ed25519 session key.");
20889
+ } catch {
20890
+ throw new InvalidRestoredSessionError("Persisted session has an invalid private Ed25519 session key.");
20860
20891
  }
20892
+ const stagedJwkJson = stagedManager.jwk(stagedKeyId);
20893
+ if (!stagedJwkJson) throw new Error("missing restored session key");
20894
+ stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));
20895
+ canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);
20861
20896
  const restoredVerificationMethod = canonicalRestoredVerificationMethod(
20862
20897
  canonicalVerificationMethod,
20863
20898
  sessionData.verificationMethod
20864
20899
  );
20865
20900
  if (!restoredVerificationMethod) {
20866
- throw new Error(
20901
+ throw new InvalidRestoredSessionError(
20867
20902
  "Persisted session verification method does not match its private Ed25519 session key."
20868
20903
  );
20869
20904
  }
@@ -20875,26 +20910,37 @@ var _TinyCloudNode = class _TinyCloudNode {
20875
20910
  ];
20876
20911
  const hasPersistedProof = proofValues.every((value) => value !== void 0);
20877
20912
  if (!hasPersistedProof && (proofValues.some((value) => value !== void 0) || sessionData.expiresAt !== void 0)) {
20878
- throw new Error("Persisted session authority metadata is incomplete.");
20913
+ throw new InvalidRestoredSessionError("Persisted session authority metadata is incomplete.");
20914
+ }
20915
+ let restoredAddress;
20916
+ try {
20917
+ restoredAddress = hasPersistedProof ? canonicalizeAddress2(sessionData.address) : void 0;
20918
+ } catch {
20919
+ throw new InvalidRestoredSessionError("Persisted session has an invalid wallet address.");
20879
20920
  }
20880
- const restoredAddress = hasPersistedProof ? canonicalizeAddress2(sessionData.address) : void 0;
20881
20921
  let stagedSessionExpiry = /* @__PURE__ */ new Date(0);
20882
20922
  let stagedRecap = [];
20883
20923
  if (hasPersistedProof) {
20884
20924
  if (typeof this.wasmBindings.validatePersistedSession !== "function") {
20885
20925
  throw new UnsupportedSessionRestoreError("it cannot verify persisted SIWE authority");
20886
20926
  }
20887
- const verified = this.wasmBindings.validatePersistedSession({
20888
- delegationHeader: sessionData.delegationHeader,
20889
- delegationCid: sessionData.delegationCid,
20890
- spaceId: sessionData.spaceId,
20891
- jwk: stagedJwk,
20892
- address: restoredAddress,
20893
- chainId: sessionData.chainId,
20894
- siwe: sessionData.siwe,
20895
- signature: sessionData.signature
20896
- });
20897
- const exactRecap = verified.verifiedRecap;
20927
+ const verified = (() => {
20928
+ try {
20929
+ return this.wasmBindings.validatePersistedSession({
20930
+ delegationHeader: sessionData.delegationHeader,
20931
+ delegationCid: sessionData.delegationCid,
20932
+ spaceId: sessionData.spaceId,
20933
+ jwk: stagedJwk,
20934
+ address: restoredAddress,
20935
+ chainId: sessionData.chainId,
20936
+ siwe: sessionData.siwe,
20937
+ signature: sessionData.signature
20938
+ });
20939
+ } catch (error) {
20940
+ throw new InvalidRestoredSessionError(error instanceof Error ? error.message : String(error));
20941
+ }
20942
+ })();
20943
+ const exactRecap = Array.isArray(verified.verifiedRecap) ? verifierRecapEntries(verified.verifiedRecap) : verified.verifiedRecap;
20898
20944
  if (!Array.isArray(exactRecap) || !exactRecap.every(
20899
20945
  (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(
20900
20946
  (caveat) => caveat !== null && typeof caveat === "object" && !Array.isArray(caveat)
@@ -20914,7 +20960,7 @@ var _TinyCloudNode = class _TinyCloudNode {
20914
20960
  const signedExpiry = verified.expiresAt === void 0 ? void 0 : persistedExpiry(verified.expiresAt);
20915
20961
  const persistedPolicyExpiry = sessionData.expiresAt === void 0 ? void 0 : persistedExpiry(sessionData.expiresAt);
20916
20962
  if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {
20917
- throw new Error("Persisted session expiry does not match its signed SIWE authority.");
20963
+ throw new InvalidRestoredSessionError("Persisted session expiry does not match its signed SIWE authority.");
20918
20964
  }
20919
20965
  stagedSessionExpiry = signedExpiry ?? persistedPolicyExpiry ?? persistedExpiry(void 0);
20920
20966
  }
@@ -21011,7 +21057,7 @@ var _TinyCloudNode = class _TinyCloudNode {
21011
21057
  operations = recap.flatMap((entry) => {
21012
21058
  const service = this.invocationServiceName(entry.service);
21013
21059
  return entry.actions.map((action) => ({
21014
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space },
21060
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space },
21015
21061
  service,
21016
21062
  path: entry.path,
21017
21063
  action,
@@ -21107,7 +21153,7 @@ var _TinyCloudNode = class _TinyCloudNode {
21107
21153
  const delegations = input.recap.map((entry) => ({
21108
21154
  cid: session.delegationCid,
21109
21155
  delegateDID: session.verificationMethod,
21110
- spaceId: entry.space,
21156
+ spaceId: this.spaceIdsEqual(entry.space, session.spaceId) ? session.spaceId : entry.space,
21111
21157
  path: entry.path,
21112
21158
  actions: [...entry.actions],
21113
21159
  caveats: cloneRecapCaveats(entry.caveats),
@@ -21797,16 +21843,11 @@ var _TinyCloudNode = class _TinyCloudNode {
21797
21843
  );
21798
21844
  graph.assertActive();
21799
21845
  if (!response.ok) {
21800
- let permissionHint;
21801
- if (response.status === 401 || response.status === 403) {
21802
- try {
21803
- const body = await response.json();
21804
- const record = typeof body === "object" && body !== null ? body : void 0;
21805
- const nested = typeof record?.error === "object" && record.error !== null ? record.error : void 0;
21806
- permissionHint = parsePermissionHint(record?.permissionHint) ?? parsePermissionHint(nested?.permissionHint);
21807
- } catch {
21808
- }
21809
- }
21846
+ const permissionHint = response.status === 401 || response.status === 403 ? parsePermissionHint({
21847
+ service: "tinycloud.encryption",
21848
+ path: networkId,
21849
+ actions: ["tinycloud.encryption/decrypt"]
21850
+ }) : void 0;
21810
21851
  throw new DecryptTransportResponseError(response.status, permissionHint);
21811
21852
  }
21812
21853
  return await response.json();
@@ -22245,13 +22286,20 @@ var _TinyCloudNode = class _TinyCloudNode {
22245
22286
  const session = this.currentTinyCloudSession();
22246
22287
  const serviceSession = this._serviceContext?.session;
22247
22288
  if (!session || !serviceSession) throw new Error("Share delivery requires an authenticated session");
22289
+ const idempotencyBytes = new TextEncoder().encode(input.idempotencyKey);
22290
+ if (idempotencyBytes.byteLength === 0 || idempotencyBytes.byteLength > 512) {
22291
+ throw new Error("Share delivery idempotency key is invalid");
22292
+ }
22293
+ const jtiDigest = new Uint8Array(await crypto.subtle.digest("SHA-256", idempotencyBytes));
22248
22294
  const body = {
22249
22295
  envelope: input.envelope,
22296
+ sealedEnvelope: input.sealedEnvelope,
22297
+ envelopeKey: input.envelopeKey,
22250
22298
  shareCid: input.shareCid,
22251
22299
  recipientEmail: input.recipientEmail,
22252
22300
  shareUrl: input.shareUrl,
22253
22301
  documentName: input.documentName,
22254
- jti: base64UrlEncode(crypto.getRandomValues(new Uint8Array(16))),
22302
+ jti: base64UrlEncode(jtiDigest.slice(0, 16)),
22255
22303
  expiresAt: new Date(input.expiresAt).toISOString().replace(/\.\d{3}Z$/, "Z")
22256
22304
  };
22257
22305
  const requestBodyDigest = base64UrlEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalizeEncryptionJson(body)))));
@@ -22734,7 +22782,7 @@ var _TinyCloudNode = class _TinyCloudNode {
22734
22782
  continue;
22735
22783
  }
22736
22784
  let space;
22737
- if (service !== "tinycloud.encryption") {
22785
+ if (service !== "tinycloud.encryption" || operation.resource === void 0) {
22738
22786
  if (typeof operation.spaceId !== "string") continue;
22739
22787
  try {
22740
22788
  space = this.resolvePermissionSpace(operation.spaceId, session);
@@ -23279,11 +23327,8 @@ var _TinyCloudNode = class _TinyCloudNode {
23279
23327
  );
23280
23328
  return { delegation: delegation2, prompted: true };
23281
23329
  }
23282
- const granted = parseRecapCapabilities(
23283
- (siwe) => this.parseRecapWithCaveats(siwe),
23284
- session.siwe
23285
- );
23286
- const { subset, missing } = isCapabilitySubset(expandedEntries, granted);
23330
+ const granted = this.projectSignedRecapCapabilities(session.siwe);
23331
+ const { subset, missing } = this.signedCapabilitySubset(expandedEntries, granted);
23287
23332
  if (!subset) {
23288
23333
  const runtimeOperations = this.permissionEntriesToOperations(expandedEntries, session);
23289
23334
  const runtimeGrant = this.findGrantForOperations(
@@ -23603,7 +23648,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23603
23648
  return abilities;
23604
23649
  }
23605
23650
  isEncryptionPermissionEntry(entry) {
23606
- return entry.service === ENCRYPTION_PERMISSION_SERVICE2 && entry.path.startsWith("urn:tinycloud:encryption:");
23651
+ return entry.service === ENCRYPTION_PERMISSION_SERVICE2 && this.isEncryptionNetworkOperation("encryption", entry.path, entry.space);
23607
23652
  }
23608
23653
  permissionsToRawAbilities(entries) {
23609
23654
  const rawAbilities = {};
@@ -23627,7 +23672,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23627
23672
  return entries.flatMap((entry) => {
23628
23673
  const service = this.shortServiceName(entry.service);
23629
23674
  return entry.actions.map((action) => ({
23630
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId },
23675
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId },
23631
23676
  service,
23632
23677
  path: entry.path,
23633
23678
  action,
@@ -23635,13 +23680,21 @@ var _TinyCloudNode = class _TinyCloudNode {
23635
23680
  }));
23636
23681
  });
23637
23682
  }
23683
+ /** Raw network authority cannot be covered by a nested encryption space. */
23684
+ signedCapabilitySubset(requested, granted) {
23685
+ const rawGranted = granted.filter((entry) => this.isEncryptionPermissionEntry(entry)).map((entry) => ({ ...entry, space: "encryption" }));
23686
+ const spaceGranted = granted.filter((entry) => !this.isEncryptionPermissionEntry(entry));
23687
+ const missing = requested.filter((entry) => {
23688
+ const raw = this.isEncryptionPermissionEntry(entry);
23689
+ const comparable = raw ? { ...entry, space: "encryption" } : entry;
23690
+ return !isCapabilitySubset([comparable], raw ? rawGranted : spaceGranted).subset;
23691
+ });
23692
+ return { subset: missing.length === 0, missing };
23693
+ }
23638
23694
  sessionCoversPermissionEntries(session, entries) {
23639
23695
  try {
23640
- const granted = parseRecapCapabilities(
23641
- (siwe) => this.parseRecapWithCaveats(siwe),
23642
- session.siwe
23643
- );
23644
- return isCapabilitySubset(entries, granted).subset;
23696
+ const granted = this.projectSignedRecapCapabilities(session.siwe);
23697
+ return this.signedCapabilitySubset(entries, granted).subset;
23645
23698
  } catch {
23646
23699
  return false;
23647
23700
  }
@@ -23651,7 +23704,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23651
23704
  const spaceId = this.resolvePermissionSpace(entry.space, session);
23652
23705
  const service = this.shortServiceName(entry.service);
23653
23706
  return entry.actions.map((action) => ({
23654
- ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId },
23707
+ ...this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId },
23655
23708
  service,
23656
23709
  path: entry.path,
23657
23710
  action,
@@ -23740,7 +23793,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23740
23793
  return resources.flatMap((resource) => {
23741
23794
  const service = this.invocationServiceName(resource.service);
23742
23795
  return resource.actions.map((action) => ({
23743
- ...this.isEncryptionNetworkOperation(service, resource.path) ? { resource: resource.path } : { spaceId: resource.space },
23796
+ ...this.isEncryptionNetworkOperation(service, resource.path, resource.space) ? { resource: resource.path } : { spaceId: resource.space },
23744
23797
  service,
23745
23798
  path: resource.path,
23746
23799
  action,
@@ -23801,7 +23854,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23801
23854
  };
23802
23855
  for (const resource of resources) {
23803
23856
  const service = this.invocationServiceName(resource.service);
23804
- if (this.isEncryptionNetworkOperation(service, resource.path)) {
23857
+ if (this.isEncryptionNetworkOperation(service, resource.path, resource.space)) {
23805
23858
  rawAbilities[_a = resource.path] ?? (rawAbilities[_a] = []);
23806
23859
  addActions(rawAbilities[resource.path], resource.actions);
23807
23860
  continue;
@@ -23870,21 +23923,15 @@ var _TinyCloudNode = class _TinyCloudNode {
23870
23923
  }
23871
23924
  return granted.spaceId !== void 0 && requested.spaceId !== void 0 && this.spaceIdsEqual(granted.spaceId, requested.spaceId) && this.pathContains(granted.path, requested.path);
23872
23925
  }
23873
- // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. The embedded
23874
- // EIP-155 address is case-insensitive, but the CLI canonicalizes it to
23875
- // lowercase when building a space URI while stored runtime delegations keep
23876
- // the EIP-55 checksummed form — so a byte-for-byte compare spuriously rejects
23877
- // an otherwise-valid grant. Lowercase ONLY the `eip155:<chain>:0x<addr>`
23878
- // segment and leave everything else (crucially the case-sensitive space NAME)
23879
- // byte-exact. Mirrors the CLI's `normalizeSpaceForCompare` (OPENKEY_SCOPE_MISMATCH fix).
23926
+ // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. Compare
23927
+ // only the embedded EIP-155 address without case sensitivity; chain, name,
23928
+ // and all non-PKH space identifiers remain byte-exact.
23880
23929
  spaceIdsEqual(a, b) {
23881
23930
  return this.normalizeSpaceAddress(a) === this.normalizeSpaceAddress(b);
23882
23931
  }
23883
23932
  normalizeSpaceAddress(space) {
23884
- return space.replace(
23885
- /(eip155:\d+:)(0x[0-9a-fA-F]{40})/,
23886
- (_match, prefix, addr) => prefix + addr.toLowerCase()
23887
- );
23933
+ const match = /^(tinycloud:pkh:eip155:\d+:)(0x[0-9a-fA-F]{40})(:.+)$/.exec(space);
23934
+ return match === null ? space : `${match[1]}${match[2].toLowerCase()}${match[3]}`;
23888
23935
  }
23889
23936
  actionContains(grantedAction, requestedAction) {
23890
23937
  if (grantedAction === requestedAction) {
@@ -23901,10 +23948,11 @@ var _TinyCloudNode = class _TinyCloudNode {
23901
23948
  }
23902
23949
  /** Prefer the v2 caveat-preserving parser while retaining old custom WASM. */
23903
23950
  parseRecapWithCaveats(siwe) {
23904
- return this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe) ?? this.wasmBindings.parseRecapFromSiwe(siwe);
23951
+ const verified = this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe);
23952
+ return verified == null ? this.wasmBindings.parseRecapFromSiwe(siwe) : verifierRecapEntries(verified);
23905
23953
  }
23906
- isEncryptionNetworkOperation(service, path) {
23907
- return service === "encryption" && path.startsWith("urn:tinycloud:encryption:");
23954
+ isEncryptionNetworkOperation(service, path, space) {
23955
+ return service === "encryption" && (space === void 0 || space === "encryption") && path.startsWith("urn:tinycloud:encryption:");
23908
23956
  }
23909
23957
  operationFromInvokeAnyEntry(entry) {
23910
23958
  const service = this.invocationServiceName(entry.service);
@@ -23917,7 +23965,7 @@ var _TinyCloudNode = class _TinyCloudNode {
23917
23965
  ...entry.caveats === void 0 ? {} : { caveats: cloneRecapCaveats(entry.caveats) }
23918
23966
  };
23919
23967
  }
23920
- if (this.isEncryptionNetworkOperation(service, entry.path)) {
23968
+ if (entry.spaceId === void 0 && this.isEncryptionNetworkOperation(service, entry.path)) {
23921
23969
  return {
23922
23970
  resource: entry.path,
23923
23971
  service,
@@ -24202,8 +24250,7 @@ var _TinyCloudNode = class _TinyCloudNode {
24202
24250
  const jwk = mySession.jwk;
24203
24251
  const { abilities, rawAbilities } = this.buildActivationAbilities(delegation);
24204
24252
  const now = /* @__PURE__ */ new Date();
24205
- const maxExpiry = new Date(now.getTime() + 60 * 60 * 1e3);
24206
- const expirationTime = delegation.expiry < maxExpiry ? delegation.expiry : maxExpiry;
24253
+ const expirationTime = delegation.expiry;
24207
24254
  const prepared = this.wasmBindings.prepareSession({
24208
24255
  abilities,
24209
24256
  address: this.wasmBindings.ensureEip55(mySession.address),
@@ -24307,8 +24354,7 @@ var _TinyCloudNode = class _TinyCloudNode {
24307
24354
  );
24308
24355
  }
24309
24356
  const now = /* @__PURE__ */ new Date();
24310
- const expiryMs = params.expiryMs ?? 60 * 60 * 1e3;
24311
- const requestedExpiry = new Date(now.getTime() + expiryMs);
24357
+ const requestedExpiry = params.expiryMs === void 0 ? parentDelegation.expiry : new Date(now.getTime() + params.expiryMs);
24312
24358
  const actualExpiry = requestedExpiry > parentDelegation.expiry ? parentDelegation.expiry : requestedExpiry;
24313
24359
  const abilities = {};
24314
24360
  const rawAbilities = {};
@@ -25113,6 +25159,7 @@ export {
25113
25159
  FileSessionStorage,
25114
25160
  HooksService3 as HooksService,
25115
25161
  IdentityParseError,
25162
+ InvalidRestoredSessionError,
25116
25163
  KVService3 as KVService,
25117
25164
  ManifestValidationError,
25118
25165
  MemorySessionStorage,
@@ -25192,6 +25239,7 @@ export {
25192
25239
  expandActionShortNames,
25193
25240
  expandPermissionEntries2 as expandPermissionEntries,
25194
25241
  expandPermissionEntry,
25242
+ extractSiweExpiration,
25195
25243
  generateRandomReceiverKey,
25196
25244
  getTinyCloudDebugLogs,
25197
25245
  grantAuthRequest,