@tinycloud/node-sdk 2.6.0-beta.0 → 2.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISigner, Bytes, IWasmBindings, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CallbackStrategy, CanonicalAddress, CanonicalDecryptRequest, CanonicalJson, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncodedShareData, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IEncryptionService, IHooksService, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InlineEncryptedEnvelope, InvokeFunction, JWK, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedNetworkId, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SignedReceiverKeyInput, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, VersionCheckError, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, addressStorageKey, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, buildSpaceUri, canonicalHashHex, canonicalSignedResponse, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeEncryptionJson, canonicalizeNetworkId, canonicalizeSecretScope, checkDecryptInvocationInput, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, decryptEnvelopeWithKey, defaultSpaceCreationHandler, deriveSignedReceiverKey, didCacheKey, didEquals, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, encryptionBase64Decode, encryptionBase64Encode, encryptionError, encryptionUtf8Decode, encryptionUtf8Encode, ensureNetworkUsableForDecrypt, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, isNetworkId, loadManifest, makePkhSpaceId, makePublicSpaceId, networkDiscoveryKey, openWrappedKey, parseCanonicalNetworkId, parseExpiry, parseNetworkId, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-ojeY-wet.cjs';
3
+ export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-Cr-zD1lk.cjs';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, generateHostSIWEMessage, siweToDelegationHeaders, protocolVersion, vault_encrypt, vault_decrypt, vault_derive_key, vault_x25519_from_seed, vault_x25519_dh, vault_random_bytes, vault_sha256 } from '@tinycloud/node-sdk-wasm';
5
5
  import 'events';
6
6
  import '@tinycloud/sdk-services';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISigner, Bytes, IWasmBindings, ISessionManager } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CallbackStrategy, CanonicalAddress, CanonicalDecryptRequest, CanonicalJson, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncodedShareData, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IEncryptionService, IHooksService, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InlineEncryptedEnvelope, InvokeFunction, JWK, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedNetworkId, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiveOptions, ReceiverKeyPair, ReceiverKeySigner, ResolvedCapabilities, ResolvedDelegate, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SignedReceiverKeyInput, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, VersionCheckError, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, addressStorageKey, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, buildSpaceUri, canonicalHashHex, canonicalSignedResponse, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeEncryptionJson, canonicalizeNetworkId, canonicalizeSecretScope, checkDecryptInvocationInput, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, decryptEnvelopeWithKey, defaultSpaceCreationHandler, deriveSignedReceiverKey, didCacheKey, didEquals, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, encryptionBase64Decode, encryptionBase64Encode, encryptionError, encryptionUtf8Decode, encryptionUtf8Encode, ensureNetworkUsableForDecrypt, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, isNetworkId, loadManifest, makePkhSpaceId, makePublicSpaceId, networkDiscoveryKey, openWrappedKey, parseCanonicalNetworkId, parseExpiry, parseNetworkId, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateEnvelope, validateManifest, verifyDecryptResponse } from '@tinycloud/sdk-core';
3
- export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-ojeY-wet.js';
3
+ export { A as AuthDelegationArtifact, a as AuthRequestArtifact, D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, d as DelegationAuthority, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, R as RestorableSession, g as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, W as WasmKeyProvider, i as WasmKeyProviderConfig, j as createWasmKeyProvider, k as defaultSignStrategy, l as deserializeDelegation, m as grantAuthRequest, s as serializeDelegation } from './core-Cr-zD1lk.js';
4
4
  import { invoke, invokeAny, computeCid, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, parseRecapFromSiwe, generateHostSIWEMessage, siweToDelegationHeaders, protocolVersion, vault_encrypt, vault_decrypt, vault_derive_key, vault_x25519_from_seed, vault_x25519_dh, vault_random_bytes, vault_sha256 } from '@tinycloud/node-sdk-wasm';
5
5
  import 'events';
6
6
  import '@tinycloud/sdk-services';
package/dist/index.js CHANGED
@@ -19136,6 +19136,10 @@ var _TinyCloudNode = class _TinyCloudNode {
19136
19136
  await this.tc.signIn(options);
19137
19137
  this.syncResolvedHostFromAuth();
19138
19138
  this.initializeServices();
19139
+ const primarySession = this.currentTinyCloudSession();
19140
+ if (primarySession) {
19141
+ this.registerPrimarySessionGrant(primarySession);
19142
+ }
19139
19143
  const bootstrapped = await this.bootstrapAccountIfNeeded();
19140
19144
  await this.ensureRequestedEncryptionNetworks();
19141
19145
  if (!bootstrapped && this.config.manifest === void 0 && this.config.capabilityRequest === void 0) {
@@ -19379,7 +19383,107 @@ var _TinyCloudNode = class _TinyCloudNode {
19379
19383
  host: this.config.host
19380
19384
  },
19381
19385
  operations,
19382
- expiresAt
19386
+ expiresAt,
19387
+ provenance: "bootstrap"
19388
+ });
19389
+ }
19390
+ /**
19391
+ * Map the base session's OWN recap into runtime permission operations.
19392
+ *
19393
+ * Uses the RAW `parseRecapFromSiwe` binding — NOT `parseRecapCapabilities`,
19394
+ * whose `normalizeSpace` collapses `tinycloud:pkh:...:<owner>:<space>` to a
19395
+ * bare short name and would conflate two owners' identically-named spaces.
19396
+ * We must keep the full owner-scoped URI so a synthetic primary grant can
19397
+ * never cover an operation on a different owner's space.
19398
+ *
19399
+ * Mirrors {@link operationsFromDelegation}'s op shape: encryption network
19400
+ * entries (`urn:tinycloud:encryption:` paths) become `resource` ops; every
19401
+ * other entry becomes a `spaceId` op carrying the raw recap `space` URI.
19402
+ * One op per action.
19403
+ *
19404
+ * Returns `[]` for session-only / restored-without-siwe modes and for any
19405
+ * unparseable SIWE — the primary grant is simply not registered in that case.
19406
+ */
19407
+ recapOperationsFromSession(session) {
19408
+ const siwe = session.siwe;
19409
+ if (!siwe) {
19410
+ return [];
19411
+ }
19412
+ if (this._recapOperationsCache?.siwe === siwe) {
19413
+ return this._recapOperationsCache.operations;
19414
+ }
19415
+ let operations = [];
19416
+ try {
19417
+ const entries = this.wasmBindings.parseRecapFromSiwe(siwe);
19418
+ if (Array.isArray(entries)) {
19419
+ operations = entries.flatMap((entry) => {
19420
+ const service = this.invocationServiceName(entry.service);
19421
+ return entry.actions.map((action) => ({
19422
+ ...this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space },
19423
+ service,
19424
+ path: entry.path,
19425
+ action
19426
+ }));
19427
+ });
19428
+ }
19429
+ } catch {
19430
+ operations = [];
19431
+ }
19432
+ this._recapOperationsCache = { siwe, operations };
19433
+ return operations;
19434
+ }
19435
+ /**
19436
+ * Register the base (primary) session's own recap as a synthetic runtime
19437
+ * grant tagged `provenance: "primary"` so it always out-ranks other covering
19438
+ * grants in {@link findGrantForOperations}. This closes the selection-design
19439
+ * hazard where a broad — possibly broken — bootstrap/delegated grant could
19440
+ * hijack an operation the primary session itself already authorized (TC-111).
19441
+ *
19442
+ * Two safety exclusions:
19443
+ * - Ops whose space is in `lastActivationSkippedSpaceIds` are dropped: the
19444
+ * node refused to activate those spaces this sign-in even though the recap
19445
+ * claims them. Including them would let the synthetic primary out-rank a
19446
+ * working grant and 401 (the "skipped-activation inverted hijack").
19447
+ * - Encryption `resource` ops are kept as-is (space-independent).
19448
+ *
19449
+ * No-ops when nothing remains after exclusion. Callers (`signIn`,
19450
+ * `restoreSession`) clear `runtimePermissionGrants` first, so no dupes.
19451
+ */
19452
+ registerPrimarySessionGrant(session) {
19453
+ const skipped = this.auth ? this.auth.lastActivationSkippedSpaceIds ?? [] : [];
19454
+ const operations = this.recapOperationsFromSession(session).filter(
19455
+ (operation) => operation.spaceId === void 0 || !skipped.some((spaceId) => this.spaceIdsEqual(spaceId, operation.spaceId))
19456
+ );
19457
+ if (operations.length === 0) {
19458
+ return;
19459
+ }
19460
+ const expiresAt = extractSiweExpiration(session.siwe) ?? this.getSessionExpiry();
19461
+ const actions = [...new Set(operations.map((operation) => operation.action))];
19462
+ this.runtimePermissionGrants.push({
19463
+ session: {
19464
+ delegationHeader: session.delegationHeader,
19465
+ delegationCid: session.delegationCid,
19466
+ spaceId: session.spaceId,
19467
+ verificationMethod: session.verificationMethod,
19468
+ jwk: session.jwk
19469
+ },
19470
+ delegation: {
19471
+ cid: session.delegationCid,
19472
+ delegationHeader: session.delegationHeader,
19473
+ delegateDID: session.verificationMethod,
19474
+ delegatorDID: this.did,
19475
+ spaceId: session.spaceId,
19476
+ path: "",
19477
+ actions,
19478
+ expiry: expiresAt,
19479
+ allowSubDelegation: true,
19480
+ ownerAddress: session.address,
19481
+ chainId: session.chainId,
19482
+ host: this.config.host
19483
+ },
19484
+ operations,
19485
+ expiresAt,
19486
+ provenance: "primary"
19383
19487
  });
19384
19488
  }
19385
19489
  async writeManifestRegistryRecords() {
@@ -19715,6 +19819,7 @@ var _TinyCloudNode = class _TinyCloudNode {
19715
19819
  } else {
19716
19820
  this._restoredTcSession = tcSession;
19717
19821
  }
19822
+ this.registerPrimarySessionGrant(tcSession);
19718
19823
  }
19719
19824
  }
19720
19825
  /**
@@ -20753,7 +20858,7 @@ var _TinyCloudNode = class _TinyCloudNode {
20753
20858
  getRuntimePermissionDelegations(permissions) {
20754
20859
  this.pruneExpiredRuntimePermissionGrants();
20755
20860
  if (permissions === void 0) {
20756
- return this.runtimePermissionGrants.map((grant) => grant.delegation);
20861
+ return this.runtimePermissionGrants.filter((grant) => grant.provenance !== "primary").map((grant) => grant.delegation);
20757
20862
  }
20758
20863
  const session = this.currentTinyCloudSession();
20759
20864
  if (!session || !Array.isArray(permissions) || permissions.length === 0) {
@@ -20905,7 +21010,8 @@ var _TinyCloudNode = class _TinyCloudNode {
20905
21010
  },
20906
21011
  delegation,
20907
21012
  operations: this.permissionOperations(delegatedEntries, spaceId),
20908
- expiresAt
21013
+ expiresAt,
21014
+ provenance: "runtime"
20909
21015
  });
20910
21016
  delegations.push(delegation);
20911
21017
  }
@@ -21566,7 +21672,7 @@ var _TinyCloudNode = class _TinyCloudNode {
21566
21672
  return grants;
21567
21673
  }
21568
21674
  for (const operation of operations) {
21569
- const grant = this.findGrantForOperation(operation);
21675
+ const grant = this.findGrantForOperation(operation, { excludePrimary: true });
21570
21676
  if (!grant) {
21571
21677
  return [];
21572
21678
  }
@@ -21606,7 +21712,8 @@ var _TinyCloudNode = class _TinyCloudNode {
21606
21712
  },
21607
21713
  delegation,
21608
21714
  operations,
21609
- expiresAt: delegation.expiry
21715
+ expiresAt: delegation.expiry,
21716
+ provenance: "delegated"
21610
21717
  };
21611
21718
  }
21612
21719
  installRuntimeGrantFromServiceSession(delegation, session, expiresAt) {
@@ -21621,7 +21728,8 @@ var _TinyCloudNode = class _TinyCloudNode {
21621
21728
  session,
21622
21729
  delegation,
21623
21730
  operations,
21624
- expiresAt
21731
+ expiresAt,
21732
+ provenance: "delegated"
21625
21733
  });
21626
21734
  }
21627
21735
  delegatedResourcesForEntries(entries, spaceId) {
@@ -21721,21 +21829,28 @@ var _TinyCloudNode = class _TinyCloudNode {
21721
21829
  });
21722
21830
  return grant?.session ?? fallback;
21723
21831
  }
21724
- findGrantForOperations(operations) {
21832
+ findGrantForOperations(operations, options) {
21725
21833
  if (operations.length === 0) {
21726
21834
  return void 0;
21727
21835
  }
21728
21836
  this.pruneExpiredRuntimePermissionGrants();
21729
- return this.runtimePermissionGrants.find((grant) => {
21837
+ const covering = this.runtimePermissionGrants.filter((grant) => {
21838
+ if (options?.excludePrimary && grant.provenance === "primary") {
21839
+ return false;
21840
+ }
21730
21841
  return operations.every(
21731
21842
  (operation) => grant.operations.some(
21732
21843
  (granted) => this.operationCovers(granted, operation)
21733
21844
  )
21734
21845
  );
21735
21846
  });
21847
+ if (covering.length === 0) {
21848
+ return void 0;
21849
+ }
21850
+ return covering.find((grant) => grant.provenance === "primary") ?? covering[0];
21736
21851
  }
21737
- findGrantForOperation(operation) {
21738
- return this.findGrantForOperations([operation]);
21852
+ findGrantForOperation(operation, options) {
21853
+ return this.findGrantForOperations([operation], options);
21739
21854
  }
21740
21855
  pruneExpiredRuntimePermissionGrants() {
21741
21856
  const now = Date.now();