@tinycloud/node-sdk 3.1.0-beta.7 → 3.1.0-beta.8

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, 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-BWvBTn9l.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, p as RuntimePermissionGrantOptions, S as SecretPermissionHint, q as SecretReadInput, r as SecretReadResult, t as SignStrategy, T as TinyCloudNode, u as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, v as UnifiedOwnerRootReceipt, w as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, y as WasmKeyProviderConfig, z as activateCompactRuntimeDelegation, H as createWasmKeyProvider, J as defaultSignStrategy, K as deserializeDelegation, Q as serializeDelegation } from './core-CC7uDKZP.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, 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-BWvBTn9l.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, p as RuntimePermissionGrantOptions, S as SecretPermissionHint, q as SecretReadInput, r as SecretReadResult, t as SignStrategy, T as TinyCloudNode, u as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, v as UnifiedOwnerRootReceipt, w as UnsupportedSessionRestoreError, V as ValidatedRuntimeDelegation, W as WasmKeyProvider, y as WasmKeyProviderConfig, z as activateCompactRuntimeDelegation, H as createWasmKeyProvider, J as defaultSignStrategy, K as deserializeDelegation, Q as serializeDelegation } from './core-CC7uDKZP.js';
3
3
  import 'events';
4
4
  import '@tinycloud/sdk-services';
package/dist/core.js CHANGED
@@ -1658,14 +1658,14 @@ var NodeUserAuthorization = class {
1658
1658
  * Request signature via event emitter with timeout.
1659
1659
  */
1660
1660
  requestSignatureViaEmitter(request, emitter, timeout) {
1661
- return new Promise((resolve, reject) => {
1661
+ return new Promise((resolve, reject2) => {
1662
1662
  const timeoutId = setTimeout(() => {
1663
- reject(new Error("Sign request timed out"));
1663
+ reject2(new Error("Sign request timed out"));
1664
1664
  }, timeout);
1665
1665
  const respond = async (response) => {
1666
1666
  clearTimeout(timeoutId);
1667
1667
  if (!response.approved) {
1668
- reject(
1668
+ reject2(
1669
1669
  new Error(response.reason ?? "Sign request rejected via emitter")
1670
1670
  );
1671
1671
  } else {
@@ -2330,6 +2330,25 @@ function jsonFromVerifier(value) {
2330
2330
  function verifierRecapEntries(entries) {
2331
2331
  return entries.map((entry) => Array.isArray(entry.caveats) ? { ...entry, caveats: entry.caveats.map((caveat) => jsonFromVerifier(caveat)) } : entry);
2332
2332
  }
2333
+ function exactVerifiedRecap(verified) {
2334
+ const exactRecap = Array.isArray(verified.verifiedRecap) ? verifierRecapEntries(verified.verifiedRecap) : verified.verifiedRecap;
2335
+ if (!Array.isArray(exactRecap) || !exactRecap.every(
2336
+ (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(
2337
+ (caveat) => caveat !== null && typeof caveat === "object" && !Array.isArray(caveat)
2338
+ )
2339
+ )) {
2340
+ throw new UnsupportedSessionRestoreError(
2341
+ "it cannot reconstruct caveat-preserving persisted ReCap authority"
2342
+ );
2343
+ }
2344
+ return exactRecap.map((entry) => ({
2345
+ service: entry.service,
2346
+ space: entry.space,
2347
+ path: entry.path,
2348
+ actions: [...entry.actions],
2349
+ caveats: cloneRecapCaveats(entry.caveats)
2350
+ }));
2351
+ }
2333
2352
  var ServiceGraphLifetime = class {
2334
2353
  constructor(invokeFn, invokeAnyFn, fetchFn) {
2335
2354
  this.invokeFn = invokeFn;
@@ -3994,23 +4013,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3994
4013
  throw new InvalidRestoredSessionError(error instanceof Error ? error.message : String(error));
3995
4014
  }
3996
4015
  })();
3997
- const exactRecap = Array.isArray(verified.verifiedRecap) ? verifierRecapEntries(verified.verifiedRecap) : verified.verifiedRecap;
3998
- if (!Array.isArray(exactRecap) || !exactRecap.every(
3999
- (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(
4000
- (caveat) => caveat !== null && typeof caveat === "object" && !Array.isArray(caveat)
4001
- )
4002
- )) {
4003
- throw new UnsupportedSessionRestoreError(
4004
- "it cannot reconstruct caveat-preserving persisted ReCap authority"
4005
- );
4006
- }
4007
- stagedRecap = exactRecap.map((entry) => ({
4008
- service: entry.service,
4009
- space: entry.space,
4010
- path: entry.path,
4011
- actions: [...entry.actions],
4012
- caveats: cloneRecapCaveats(entry.caveats)
4013
- }));
4016
+ stagedRecap = exactVerifiedRecap(verified);
4014
4017
  const signedExpiry = verified.expiresAt === void 0 ? void 0 : persistedExpiry(verified.expiresAt);
4015
4018
  const persistedPolicyExpiry = sessionData.expiresAt === void 0 ? void 0 : persistedExpiry(sessionData.expiresAt);
4016
4019
  if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {
@@ -5871,6 +5874,42 @@ var _TinyCloudNode = class _TinyCloudNode {
5871
5874
  (left, right) => left.service.localeCompare(right.service) || (left.space ?? "").localeCompare(right.space ?? "") || left.path.localeCompare(right.path) || left.actions.join("\0").localeCompare(right.actions.join("\0"))
5872
5875
  );
5873
5876
  }
5877
+ /**
5878
+ * Verify a wallet-signed session grant (a CACAO built from a SIWE and its
5879
+ * EIP-191 signature) issued to this instance's live session key. The
5880
+ * verifier rebuilds the CACAO from `siwe` and `signature`, so the grant is
5881
+ * accepted only when its authorization bytes and CID are exactly that CACAO,
5882
+ * its signer is `address`, its audience is this session key, it is valid
5883
+ * now, and its ReCap covers `spaceId` or names only raw encryption networks
5884
+ * (a decrypt-only grant has no space). Returns the signed ReCap and expiry.
5885
+ * Bindings without `validateSessionGrant` fall back to the session verifier,
5886
+ * which also refuses decrypt-only grants.
5887
+ */
5888
+ verifySessionGrant(grant) {
5889
+ const bindings = this.wasmBindings;
5890
+ const validate = typeof bindings.validateSessionGrant === "function" ? bindings.validateSessionGrant.bind(bindings) : bindings.validatePersistedSession?.bind(bindings);
5891
+ if (validate === void 0) {
5892
+ throw new UnsupportedSessionRestoreError("it cannot verify persisted SIWE authority");
5893
+ }
5894
+ const verified = validate({
5895
+ delegationHeader: { Authorization: grant.delegationHeader.Authorization },
5896
+ delegationCid: grant.delegationCid,
5897
+ spaceId: grant.spaceId,
5898
+ jwk: this.sessionKeyJwk,
5899
+ address: canonicalizeAddress2(grant.address),
5900
+ chainId: grant.chainId,
5901
+ siwe: grant.siwe,
5902
+ signature: grant.signature
5903
+ });
5904
+ if (typeof verified.expiresAt !== "string") {
5905
+ throw new Error("Session grant has no signed expiry.");
5906
+ }
5907
+ const expiresAt = new Date(verified.expiresAt);
5908
+ if (!Number.isFinite(expiresAt.getTime())) {
5909
+ throw new Error("Session grant has an invalid signed expiry.");
5910
+ }
5911
+ return { recap: exactVerifiedRecap(verified), expiresAt };
5912
+ }
5874
5913
  /**
5875
5914
  * Install a portable runtime permission delegation into this SDK instance so
5876
5915
  * matching service calls and downstream `delegateTo()` calls can use it.
@@ -6003,7 +6042,8 @@ var _TinyCloudNode = class _TinyCloudNode {
6003
6042
  delegatedEntries,
6004
6043
  spaceId,
6005
6044
  session,
6006
- expiresAt
6045
+ expiresAt,
6046
+ { siwe: prepared.siwe, signature }
6007
6047
  );
6008
6048
  this.runtimePermissionGrants.push({
6009
6049
  session: {
@@ -6789,7 +6829,7 @@ var _TinyCloudNode = class _TinyCloudNode {
6789
6829
  }
6790
6830
  return grants;
6791
6831
  }
6792
- runtimeDelegationFromSession(delegatedSession, entries, spaceId, session, expiresAt) {
6832
+ runtimeDelegationFromSession(delegatedSession, entries, spaceId, session, expiresAt, siweProof) {
6793
6833
  const resources = this.delegatedResourcesForEntries(entries, spaceId);
6794
6834
  const primary = resources[0];
6795
6835
  return {
@@ -6804,7 +6844,8 @@ var _TinyCloudNode = class _TinyCloudNode {
6804
6844
  delegateDID: session.verificationMethod,
6805
6845
  ownerAddress: session.address,
6806
6846
  chainId: session.chainId,
6807
- host: this.config.host
6847
+ host: this.config.host,
6848
+ siweProof
6808
6849
  };
6809
6850
  }
6810
6851
  runtimeGrantFromDelegation(delegation, session) {
@@ -7524,6 +7565,16 @@ import {
7524
7565
  decodeBase64Url,
7525
7566
  principalDidEquals as principalDidEquals3
7526
7567
  } from "@tinycloud/sdk-core";
7568
+ var RuntimeDelegationRejectedError = class extends Error {
7569
+ constructor(reason, message) {
7570
+ super(message);
7571
+ this.name = "RuntimeDelegationRejectedError";
7572
+ this.reason = reason;
7573
+ }
7574
+ };
7575
+ function reject(reason, message) {
7576
+ throw new RuntimeDelegationRejectedError(reason, message);
7577
+ }
7527
7578
  var SERVICE_BY_SHORT_NAME = {
7528
7579
  kv: "tinycloud.kv",
7529
7580
  sql: "tinycloud.sql",
@@ -7670,6 +7721,15 @@ function signedAuthorityFromCompactUcan(authorization) {
7670
7721
  abilities
7671
7722
  ));
7672
7723
  }
7724
+ return canonicalSignedAuthority({
7725
+ issuer: payload.iss,
7726
+ audience: payload.aud,
7727
+ expiry,
7728
+ proofs: [...payload.prf],
7729
+ ...remainingRedelegationDepth === void 0 ? {} : { remainingRedelegationDepth }
7730
+ }, permissions);
7731
+ }
7732
+ function canonicalSignedAuthority(signed, permissions) {
7673
7733
  if (permissions.length === 0) {
7674
7734
  throw new Error("Validated runtime delegation has no signed capabilities.");
7675
7735
  }
@@ -7681,15 +7741,84 @@ function signedAuthorityFromCompactUcan(authorization) {
7681
7741
  actions: [...permission.actions],
7682
7742
  ...permission.caveats === void 0 ? {} : { caveats: permission.caveats }
7683
7743
  }));
7684
- return {
7685
- issuer: payload.iss,
7686
- audience: payload.aud,
7687
- expiry,
7688
- proofs: [...payload.prf],
7689
- ...remainingRedelegationDepth === void 0 ? {} : { remainingRedelegationDepth },
7690
- permissions: canonicalPermissions,
7691
- resources: canonicalResources
7692
- };
7744
+ return { ...signed, permissions: canonicalPermissions, resources: canonicalResources };
7745
+ }
7746
+ var RAW_ENCRYPTION_PREFIX = "urn:tinycloud:encryption:";
7747
+ var PKH_SPACE = /^tinycloud:pkh:eip155:(\d+):(0x[0-9a-fA-F]{40}):(.+)$/;
7748
+ function comparableSpace(space) {
7749
+ const match = PKH_SPACE.exec(space);
7750
+ return match ? `tinycloud:pkh:eip155:${match[1]}:${match[2].toLowerCase()}:${match[3]}` : space;
7751
+ }
7752
+ function signedAuthorityFromSessionGrant(node, delegation, authorization, cid) {
7753
+ const proof = delegation.siweProof;
7754
+ if (proof === void 0 || proof === null || typeof proof !== "object" || typeof proof.siwe !== "string" || typeof proof.signature !== "string") {
7755
+ reject(
7756
+ "proof_missing",
7757
+ "Runtime delegation is a wallet-signed session grant stored without its signed SIWE proof, so its authority cannot be verified."
7758
+ );
7759
+ }
7760
+ if (typeof node.verifySessionGrant !== "function") {
7761
+ reject("unsupported", "This runtime cannot verify wallet-signed session grants.");
7762
+ }
7763
+ const owner = `did:pkh:eip155:${delegation.chainId}:${delegation.ownerAddress}`;
7764
+ if (typeof node.did !== "string" || !didPrincipalsMatch(owner, node.did)) {
7765
+ reject("owner_mismatch", "Runtime delegation is not signed by this session's owner.");
7766
+ }
7767
+ let verified;
7768
+ try {
7769
+ verified = node.verifySessionGrant({
7770
+ delegationHeader: { Authorization: authorization },
7771
+ delegationCid: cid,
7772
+ spaceId: delegation.spaceId,
7773
+ address: delegation.ownerAddress,
7774
+ chainId: delegation.chainId,
7775
+ siwe: proof.siwe,
7776
+ signature: proof.signature
7777
+ });
7778
+ } catch (error) {
7779
+ reject("proof_invalid", error instanceof Error ? error.message : String(error));
7780
+ }
7781
+ const space = comparableSpace(delegation.spaceId);
7782
+ const spaceOwner = PKH_SPACE.exec(delegation.spaceId);
7783
+ if (!spaceOwner || !didPrincipalsMatch(`did:pkh:eip155:${spaceOwner[1]}:${spaceOwner[2]}`, owner)) {
7784
+ reject("authority_invalid", "Runtime delegation space is not owned by its signer.");
7785
+ }
7786
+ const groups = /* @__PURE__ */ new Map();
7787
+ for (const entry of verified.recap) {
7788
+ const service = entry.service.startsWith("tinycloud.") ? entry.service : `tinycloud.${entry.service}`;
7789
+ const raw = entry.space === "encryption";
7790
+ if (raw) {
7791
+ if (service !== "tinycloud.encryption" || !entry.path.startsWith(RAW_ENCRYPTION_PREFIX)) {
7792
+ reject("authority_invalid", "Runtime delegation has an unsupported signed raw resource.");
7793
+ }
7794
+ const networkOwner = entry.path.slice(RAW_ENCRYPTION_PREFIX.length, entry.path.lastIndexOf(":"));
7795
+ if (!didPrincipalsMatch(networkOwner, owner)) {
7796
+ reject("authority_invalid", "Runtime delegation names an encryption network its signer does not own.");
7797
+ }
7798
+ } else if (service === "tinycloud.encryption" || comparableSpace(entry.space) !== space) {
7799
+ reject("authority_invalid", "Runtime delegation has signed authority outside its space.");
7800
+ }
7801
+ const caveats = signedCaveats(entry.caveats ?? []);
7802
+ const key = JSON.stringify([service, raw ? "" : entry.space, entry.path, canonicalizeRecapCaveats2(caveats)]);
7803
+ const group = groups.get(key) ?? {
7804
+ service,
7805
+ ...raw ? {} : { space: entry.space },
7806
+ path: entry.path,
7807
+ actions: [],
7808
+ ...caveats === void 0 ? {} : { caveats }
7809
+ };
7810
+ for (const action of entry.actions) {
7811
+ if (!group.actions.includes(action)) group.actions.push(action);
7812
+ }
7813
+ groups.set(key, group);
7814
+ }
7815
+ return canonicalSignedAuthority({
7816
+ issuer: owner,
7817
+ // The verifier bound the SIWE audience to this runtime's own session key.
7818
+ audience: node.sessionDid,
7819
+ expiry: verified.expiresAt,
7820
+ proofs: []
7821
+ }, [...groups.values()]);
7693
7822
  }
7694
7823
  function canonicalResourcesFromPortableDelegation(delegation) {
7695
7824
  if (delegation.resources !== void 0 && delegation.resources.length > 0) {
@@ -7725,49 +7854,58 @@ function resourcesMatch(actual, expected) {
7725
7854
  async function activateValidatedRuntimeDelegation(node, delegation, options) {
7726
7855
  const host = normalizedHost(options.host);
7727
7856
  if (delegation.host !== void 0 && normalizedHost(delegation.host) !== host) {
7728
- throw new Error(
7857
+ reject(
7858
+ "host_mismatch",
7729
7859
  `Runtime delegation host '${delegation.host}' does not match expected host '${options.host}'.`
7730
7860
  );
7731
7861
  }
7732
7862
  if (!(delegation.expiry instanceof Date) || Number.isNaN(delegation.expiry.getTime())) {
7733
- throw new Error("Runtime delegation has an invalid expiry.");
7863
+ reject("authority_invalid", "Runtime delegation has an invalid expiry.");
7734
7864
  }
7735
7865
  if (delegation.expiry.getTime() <= Date.now()) {
7736
- throw new Error("Runtime delegation is expired.");
7866
+ reject("expired", "Runtime delegation is expired.");
7737
7867
  }
7738
7868
  const authorization = delegation.delegationHeader?.Authorization;
7739
7869
  if (typeof authorization !== "string" || authorization.length === 0) {
7740
- throw new Error("Runtime delegation is missing authorization bytes.");
7870
+ reject("authority_invalid", "Runtime delegation is missing authorization bytes.");
7741
7871
  }
7742
7872
  const cid = node.computeDelegationCid(authorization);
7743
7873
  if (cid !== delegation.cid) {
7744
- throw new Error("Runtime delegation CID does not match authorization bytes.");
7874
+ reject("cid_mismatch", "Runtime delegation CID does not match authorization bytes.");
7875
+ }
7876
+ const compact = authorizationWithoutBearer(authorization).split(".").length === 3;
7877
+ let signed;
7878
+ try {
7879
+ signed = compact ? signedAuthorityFromCompactUcan(authorization) : signedAuthorityFromSessionGrant(node, delegation, authorization, cid);
7880
+ } catch (error) {
7881
+ if (error instanceof RuntimeDelegationRejectedError) throw error;
7882
+ reject("authority_invalid", error instanceof Error ? error.message : String(error));
7745
7883
  }
7746
- const signed = signedAuthorityFromCompactUcan(authorization);
7747
7884
  if (signed.expiry.getTime() <= Date.now()) {
7748
- throw new Error("Runtime delegation is expired.");
7885
+ reject("expired", "Runtime delegation is expired.");
7749
7886
  }
7750
7887
  if (delegation.expiry.getTime() !== signed.expiry.getTime()) {
7751
- throw new Error("Runtime delegation expiry does not match signed authority.");
7888
+ reject("authority_invalid", "Runtime delegation expiry does not match signed authority.");
7752
7889
  }
7753
7890
  if (!didPrincipalsMatch(signed.audience, node.sessionDid)) {
7754
- throw new Error(
7891
+ reject(
7892
+ "audience_mismatch",
7755
7893
  `Runtime delegation targets ${signed.audience} but this session is ${node.sessionDid}.`
7756
7894
  );
7757
7895
  }
7758
7896
  if (!didPrincipalsMatch(delegation.delegateDID, signed.audience)) {
7759
- throw new Error("Runtime delegation audience does not match signed authority.");
7897
+ reject("audience_mismatch", "Runtime delegation audience does not match signed authority.");
7760
7898
  }
7761
- const declaredResources = canonicalResourcesFromPortableDelegation(delegation);
7762
- if (!resourcesMatch(declaredResources, signed.resources)) {
7763
- throw new Error("Runtime delegation resources do not match signed authority.");
7899
+ if (compact && !resourcesMatch(canonicalResourcesFromPortableDelegation(delegation), signed.resources)) {
7900
+ reject("resources_mismatch", "Runtime delegation resources do not match signed authority.");
7764
7901
  }
7765
7902
  if (options.authorize !== void 0 && !options.authorize(signed.permissions)) {
7766
7903
  throw new Error("Runtime delegation is not authorized for this runtime.");
7767
7904
  }
7768
7905
  const previouslyInstalled = node.getRuntimePermissionDelegations().find((candidate) => candidate.cid === cid);
7769
7906
  if (previouslyInstalled !== void 0 && previouslyInstalled.delegationHeader.Authorization !== authorization) {
7770
- throw new Error(
7907
+ reject(
7908
+ "cid_mismatch",
7771
7909
  "A different authorization is already installed for this runtime delegation CID."
7772
7910
  );
7773
7911
  }
@@ -7797,22 +7935,28 @@ async function activateValidatedRuntimeDelegation(node, delegation, options) {
7797
7935
  })),
7798
7936
  expiry: new Date(signed.expiry),
7799
7937
  delegateDID: signed.audience,
7800
- host
7938
+ host,
7939
+ ...compact ? {} : { siweProof: delegation.siweProof }
7801
7940
  };
7802
- if (node.isSessionOnly === true && typeof node.did === "string" && principalDidEquals3(node.did, node.sessionDid) && typeof node.useDelegation === "function") {
7803
- await node.useDelegation(installedCandidate);
7804
- } else {
7805
- await node.useRuntimeDelegation(installedCandidate);
7941
+ try {
7942
+ if (node.isSessionOnly === true && typeof node.did === "string" && principalDidEquals3(node.did, node.sessionDid) && typeof node.useDelegation === "function") {
7943
+ await node.useDelegation(installedCandidate);
7944
+ } else {
7945
+ await node.useRuntimeDelegation(installedCandidate);
7946
+ }
7947
+ } catch (error) {
7948
+ reject("activation_rejected", error instanceof Error ? error.message : String(error));
7806
7949
  }
7807
7950
  const installed = node.getRuntimePermissionDelegations().find((candidate) => candidate.cid === cid);
7808
7951
  if (!installed) {
7809
- throw new Error("Runtime delegation activation did not install the validated authority.");
7952
+ reject("activation_rejected", "Runtime delegation activation did not install the validated authority.");
7810
7953
  }
7811
7954
  if (installed.delegationHeader.Authorization !== authorization || !didPrincipalsMatch(installed.delegateDID, signed.audience) || installed.expiry.getTime() !== signed.expiry.getTime() || !resourcesMatch(
7812
7955
  canonicalResourcesFromPortableDelegation(installed),
7813
7956
  signed.resources
7814
7957
  ) || normalizedHost(installed.host ?? "") !== host) {
7815
- throw new Error(
7958
+ reject(
7959
+ "activation_rejected",
7816
7960
  "Runtime delegation activation installed authority that differs from the validated authority."
7817
7961
  );
7818
7962
  }