@tinycloud/node-sdk 2.4.0-beta.1 → 2.4.0-beta.10

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
- export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, 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, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, 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, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, composeManifestRequest, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, validateManifest } from '@tinycloud/sdk-core';
2
- export { D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, P as PortableDelegation, e as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, f as TinyCloudNodeConfig, W as WasmKeyProvider, g as WasmKeyProviderConfig, h as createWasmKeyProvider, i as defaultSignStrategy, j as deserializeDelegation, s as serializeDelegation } from './core-Dbzm1kA_.cjs';
1
+ export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, 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, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, 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, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, composeManifestRequest, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, validateManifest } from '@tinycloud/sdk-core';
2
+ export { D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, 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, s as serializeDelegation } from './core-DiVEwp2P.cjs';
3
3
  import 'events';
4
4
  import '@tinycloud/sdk-services';
package/dist/core.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, 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, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, 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, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, composeManifestRequest, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, validateManifest } from '@tinycloud/sdk-core';
2
- export { D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, P as PortableDelegation, e as RuntimePermissionGrantOptions, S as SignStrategy, T as TinyCloudNode, f as TinyCloudNodeConfig, W as WasmKeyProvider, g as WasmKeyProviderConfig, h as createWasmKeyProvider, i as defaultSignStrategy, j as deserializeDelegation, s as serializeDelegation } from './core-Dbzm1kA_.js';
1
+ export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, 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, KVCreateSignedReadUrlOptions, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PkhDidParts, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, 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, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, composeManifestRequest, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, validateManifest } from '@tinycloud/sdk-core';
2
+ export { D as DelegateToOptions, b as DelegateToResult, c as DelegatedAccess, F as FileSessionStorage, M as MemorySessionStorage, N as NodeEventEmitterStrategy, e as NodeUserAuthorization, f as NodeUserAuthorizationConfig, P as PortableDelegation, 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, s as serializeDelegation } from './core-DiVEwp2P.js';
3
3
  import 'events';
4
4
  import '@tinycloud/sdk-services';
package/dist/core.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  parsePkhDid,
18
18
  pkhDid as pkhDid3,
19
19
  principalDid,
20
- principalDidEquals as principalDidEquals2,
20
+ principalDidEquals as principalDidEquals3,
21
21
  parseCanonicalNetworkId
22
22
  } from "@tinycloud/sdk-core";
23
23
 
@@ -222,6 +222,8 @@ import {
222
222
  DEFAULT_MANIFEST_SPACE,
223
223
  ENCRYPTION_PERMISSION_SERVICE,
224
224
  composeManifestRequest,
225
+ parseNetworkId,
226
+ principalDidEquals,
225
227
  resourceCapabilitiesToAbilitiesMap,
226
228
  resourceCapabilitiesToSpaceAbilitiesMap,
227
229
  resolveTinyCloudHosts,
@@ -235,6 +237,25 @@ import {
235
237
  var defaultSignStrategy = { type: "auto-sign" };
236
238
 
237
239
  // src/authorization/NodeUserAuthorization.ts
240
+ var DECRYPT_ACTION = "tinycloud.encryption/decrypt";
241
+ var NETWORK_CREATE_ACTION = "tinycloud.encryption/network.create";
242
+ function didPrincipalMatches(actual, expected) {
243
+ try {
244
+ return principalDidEquals(actual, expected);
245
+ } catch {
246
+ return actual === expected;
247
+ }
248
+ }
249
+ function addRawAbility(rawAbilities, resource, action) {
250
+ const actions = rawAbilities[resource];
251
+ if (actions === void 0) {
252
+ rawAbilities[resource] = [action];
253
+ return;
254
+ }
255
+ if (!actions.includes(action)) {
256
+ actions.push(action);
257
+ }
258
+ }
238
259
  var NodeUserAuthorization = class {
239
260
  constructor(config) {
240
261
  this.extensions = [];
@@ -261,6 +282,7 @@ var NodeUserAuthorization = class {
261
282
  "": [
262
283
  "tinycloud.sql/read",
263
284
  "tinycloud.sql/write",
285
+ "tinycloud.sql/ddl",
264
286
  "tinycloud.sql/admin",
265
287
  "tinycloud.sql/export"
266
288
  ]
@@ -464,20 +486,18 @@ var NodeUserAuthorization = class {
464
486
  };
465
487
  }
466
488
  const rawAbilities = {};
489
+ const currentDid = pkhDid(address, chainId);
467
490
  const spaceResources = request.resources.filter((entry) => {
468
491
  if (entry.service !== ENCRYPTION_PERMISSION_SERVICE) {
469
492
  return true;
470
493
  }
471
- const existing = rawAbilities[entry.path];
472
- if (existing === void 0) {
473
- rawAbilities[entry.path] = [...entry.actions];
474
- } else {
475
- const seen = new Set(existing);
476
- for (const action of entry.actions) {
477
- if (!seen.has(action)) {
478
- existing.push(action);
479
- seen.add(action);
480
- }
494
+ for (const action of entry.actions) {
495
+ addRawAbility(rawAbilities, entry.path, action);
496
+ }
497
+ if (entry.actions.includes(DECRYPT_ACTION)) {
498
+ const parsed = parseNetworkId(entry.path);
499
+ if (didPrincipalMatches(parsed.ownerDid, currentDid)) {
500
+ addRawAbility(rawAbilities, entry.path, NETWORK_CREATE_ACTION);
481
501
  }
482
502
  }
483
503
  return false;
@@ -1070,9 +1090,13 @@ import {
1070
1090
  verifyDidKeyEd25519Signature,
1071
1091
  canonicalizeAddress as canonicalizeAddress2,
1072
1092
  pkhDid as pkhDid2,
1073
- principalDidEquals
1093
+ principalDidEquals as principalDidEquals2,
1094
+ parseNetworkId as parseNetworkId2
1074
1095
  } from "@tinycloud/sdk-core";
1075
1096
 
1097
+ // src/account/AccountService.ts
1098
+ import { AccountService } from "@tinycloud/sdk-core";
1099
+
1076
1100
  // src/DelegatedAccess.ts
1077
1101
  import {
1078
1102
  KVService,
@@ -1490,13 +1514,13 @@ var NodeSecretsService = class {
1490
1514
  // src/TinyCloudNode.ts
1491
1515
  var DEFAULT_HOST = "https://node.tinycloud.xyz";
1492
1516
  var DEFAULT_ENCRYPTION_NETWORK_NAME = "default";
1493
- var NETWORK_CREATE_ACTION = "tinycloud.encryption/network.create";
1494
- var DECRYPT_ACTION = "tinycloud.encryption/decrypt";
1517
+ var NETWORK_CREATE_ACTION2 = "tinycloud.encryption/network.create";
1518
+ var DECRYPT_ACTION2 = "tinycloud.encryption/decrypt";
1495
1519
  var NETWORK_ADMIN_TYPE = "tinycloud.encryption.network-admin/v1";
1496
1520
  var DEFAULT_SESSION_EXPIRATION_MS = EXPIRY3.SESSION_MS;
1497
- function didPrincipalMatches(actual, expected) {
1521
+ function didPrincipalMatches2(actual, expected) {
1498
1522
  try {
1499
- return principalDidEquals(actual, expected);
1523
+ return principalDidEquals2(actual, expected);
1500
1524
  } catch {
1501
1525
  return actual === expected;
1502
1526
  }
@@ -1833,6 +1857,37 @@ var _TinyCloudNode = class _TinyCloudNode {
1833
1857
  get spaceId() {
1834
1858
  return this.auth?.tinyCloudSession?.spaceId;
1835
1859
  }
1860
+ /**
1861
+ * Get the account space ID for this wallet identity.
1862
+ * Available after wallet-backed sign-in or a restored session with address metadata.
1863
+ */
1864
+ get accountSpaceId() {
1865
+ if (!this._address) {
1866
+ return void 0;
1867
+ }
1868
+ return this.wasmBindings.makeSpaceId(this._address, this._chainId, ACCOUNT_REGISTRY_SPACE);
1869
+ }
1870
+ /**
1871
+ * Account-level application and delegation helpers.
1872
+ */
1873
+ get account() {
1874
+ if (!this._account) {
1875
+ this._account = new AccountService({
1876
+ getDid: () => this.did,
1877
+ getHost: () => this.hosts[0] ?? this.config.host,
1878
+ getPrimarySpaceId: () => this.spaceId,
1879
+ getAccountSpaceId: () => this.accountSpaceId,
1880
+ getSpaces: () => this.spaces,
1881
+ getAccountDb: () => this.accountSpaceId ? this.sqlForSpace(this.accountSpaceId).db("account") : void 0,
1882
+ ensureAccountSpaceHosted: async () => {
1883
+ if (this.accountSpaceId && this.auth) {
1884
+ await this.ensureOwnedSpaceHostedById(this.accountSpaceId);
1885
+ }
1886
+ }
1887
+ });
1888
+ }
1889
+ return this._account;
1890
+ }
1836
1891
  /**
1837
1892
  * Get the current TinyCloud session.
1838
1893
  * Available after signIn().
@@ -1870,10 +1925,11 @@ var _TinyCloudNode = class _TinyCloudNode {
1870
1925
  await this.tc.signIn(options);
1871
1926
  this.syncResolvedHostFromAuth();
1872
1927
  this.initializeServices();
1928
+ await this.ensureRequestedEncryptionNetworks();
1873
1929
  if (this.config.manifest === void 0 && this.config.capabilityRequest === void 0) {
1874
- await this.ensureOwnedSpaceHosted(this.ownedSpaceId("secrets"));
1930
+ await this.ensureOwnedSpaceHostedById(this.ownedSpaceId("secrets"));
1875
1931
  }
1876
- await this.writeManifestRegistryRecords();
1932
+ this.scheduleAccountRegistrySync();
1877
1933
  this.notificationHandler.success("Successfully signed in");
1878
1934
  }
1879
1935
  ownedSpaceId(name) {
@@ -1891,22 +1947,68 @@ var _TinyCloudNode = class _TinyCloudNode {
1891
1947
  throw new Error("Manifest registry write requires wallet mode");
1892
1948
  }
1893
1949
  const accountSpaceId = this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE);
1894
- await this.ensureOwnedSpaceHosted(accountSpaceId);
1895
- const accountKV = this.spaces.get(accountSpaceId).kv;
1896
- for (const record of request.registryRecords) {
1897
- const result = await accountKV.put(record.key, {
1898
- app_id: record.app_id,
1899
- manifests: record.manifests,
1900
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
1901
- });
1902
- if (!result.ok) {
1903
- throw new Error(
1904
- `Failed to write manifest registry record ${record.key}: ${result.error.message}`
1905
- );
1950
+ await this.ensureOwnedSpaceHostedById(accountSpaceId);
1951
+ const result = await this.account.applications.register(request.manifests);
1952
+ if (!result.ok) {
1953
+ throw new Error(
1954
+ `Failed to write manifest registry records: ${result.error.message}`
1955
+ );
1956
+ }
1957
+ }
1958
+ scheduleAccountRegistrySync() {
1959
+ void this.withAccountRegistryRetry(async () => {
1960
+ await this.writeManifestRegistryRecords();
1961
+ const spaces = await this.account.spaces.syncAccessible();
1962
+ if (!spaces.ok) {
1963
+ throw new Error(`Failed to sync account spaces: ${spaces.error.message}`);
1964
+ }
1965
+ });
1966
+ }
1967
+ async withAccountRegistryRetry(task) {
1968
+ const delays = [250, 1e3, 3e3];
1969
+ let lastError;
1970
+ for (let attempt = 0; attempt < delays.length; attempt += 1) {
1971
+ try {
1972
+ await task();
1973
+ return;
1974
+ } catch (error) {
1975
+ lastError = error;
1976
+ if (attempt < delays.length - 1) {
1977
+ await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
1978
+ }
1979
+ }
1980
+ }
1981
+ console.warn(
1982
+ "TinyCloud account registry sync failed after retries",
1983
+ lastError
1984
+ );
1985
+ }
1986
+ requestedEncryptionNetworkIds() {
1987
+ const request = this.capabilityRequest;
1988
+ if (!request) {
1989
+ return [];
1990
+ }
1991
+ const networkIds = /* @__PURE__ */ new Set();
1992
+ for (const resource of request.resources) {
1993
+ if (resource.service === ENCRYPTION_PERMISSION_SERVICE2 && resource.path.startsWith("urn:tinycloud:encryption:") && resource.actions.includes(DECRYPT_ACTION2)) {
1994
+ networkIds.add(resource.path);
1906
1995
  }
1907
1996
  }
1997
+ return [...networkIds];
1908
1998
  }
1909
- async ensureOwnedSpaceHosted(spaceId) {
1999
+ async ensureRequestedEncryptionNetworks() {
2000
+ if (!this.signer || !this.auth) {
2001
+ return;
2002
+ }
2003
+ for (const networkId of this.requestedEncryptionNetworkIds()) {
2004
+ const parsed = parseNetworkId2(networkId);
2005
+ if (!didPrincipalMatches2(parsed.ownerDid, this.did)) {
2006
+ continue;
2007
+ }
2008
+ await this.ensureEncryptionNetwork(networkId);
2009
+ }
2010
+ }
2011
+ async ensureOwnedSpaceHostedById(spaceId) {
1910
2012
  if (!this.auth) {
1911
2013
  throw new Error("Owned space hosting requires wallet mode");
1912
2014
  }
@@ -1949,7 +2051,7 @@ var _TinyCloudNode = class _TinyCloudNode {
1949
2051
  * caller is the root authority of their own owned spaces, so no additional
1950
2052
  * delegation is required.
1951
2053
  *
1952
- * Unlike {@link ensureOwnedSpaceHosted}, this always submits the host
2054
+ * Unlike {@link ensureOwnedSpaceHostedById}, this always submits the host
1953
2055
  * delegation rather than inferring hosting from session activation: a space
1954
2056
  * the current session has never referenced is reported neither as
1955
2057
  * `activated` nor `skipped`, so activation-based detection would wrongly
@@ -1983,8 +2085,40 @@ var _TinyCloudNode = class _TinyCloudNode {
1983
2085
  `Failed to activate session for owned space ${spaceId}: ${activation.error ?? "space was skipped"}`
1984
2086
  );
1985
2087
  }
2088
+ void this.account.spaces.register({
2089
+ spaceId,
2090
+ name,
2091
+ ownerDid: this.did,
2092
+ type: "owned",
2093
+ permissions: ["*"],
2094
+ status: "active"
2095
+ }).catch(() => {
2096
+ });
1986
2097
  return spaceId;
1987
2098
  }
2099
+ /**
2100
+ * Ensure one of this user's owned spaces (e.g. `"secrets"`) is hosted on the
2101
+ * server.
2102
+ *
2103
+ * At sign-in, a full-authority session auto-hosts the owner's `secrets`
2104
+ * space, but a session created with a manifest / capabilityRequest does not.
2105
+ * Such a session can therefore hold valid `tinycloud.kv/*` capabilities for
2106
+ * the owned `secrets` space yet still fail its first scoped
2107
+ * `secrets.put(...)` with `404 Space not found`, because the space was never
2108
+ * registered on the node.
2109
+ *
2110
+ * Calling this resolves `name` to the owner's owned-space URI
2111
+ * (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`) and hosts it via the
2112
+ * host-SIWE delegation flow. The host SIWE is idempotent server-side, so it
2113
+ * is safe to call whether or not the space already exists; do not gate it on
2114
+ * a prior existence check. Must be called after {@link signIn}.
2115
+ *
2116
+ * @param name - The owned space name (e.g. `"secrets"`).
2117
+ * @returns The hosted owned-space URI.
2118
+ */
2119
+ async ensureOwnedSpaceHosted(name) {
2120
+ return this.hostOwnedSpace(name);
2121
+ }
1988
2122
  /**
1989
2123
  * Restore a previously established session from stored delegation data.
1990
2124
  *
@@ -2374,7 +2508,7 @@ var _TinyCloudNode = class _TinyCloudNode {
2374
2508
  const signed = await this.signRawNetworkAuthorization({
2375
2509
  targetNode: input.targetNode,
2376
2510
  networkId: input.networkId,
2377
- action: DECRYPT_ACTION,
2511
+ action: DECRYPT_ACTION2,
2378
2512
  facts: input.facts
2379
2513
  });
2380
2514
  return {
@@ -2391,7 +2525,7 @@ var _TinyCloudNode = class _TinyCloudNode {
2391
2525
  },
2392
2526
  wellKnown: {
2393
2527
  fetchWellKnown: async (principal, discoveryKey) => {
2394
- if (!this._address || !didPrincipalMatches(principal, this.did)) {
2528
+ if (!this._address || !didPrincipalMatches2(principal, this.did)) {
2395
2529
  return null;
2396
2530
  }
2397
2531
  if (!this.config.host) {
@@ -2600,6 +2734,9 @@ var _TinyCloudNode = class _TinyCloudNode {
2600
2734
  }
2601
2735
  };
2602
2736
  }
2737
+ },
2738
+ onSpaceRegistered: async (space) => {
2739
+ await this.account.spaces.register(space);
2603
2740
  }
2604
2741
  });
2605
2742
  this._sharingService.updateConfig({
@@ -2898,12 +3035,12 @@ var _TinyCloudNode = class _TinyCloudNode {
2898
3035
  crypto.sha256,
2899
3036
  body
2900
3037
  ),
2901
- action: NETWORK_CREATE_ACTION
3038
+ action: NETWORK_CREATE_ACTION2
2902
3039
  };
2903
3040
  const signed = await this.signRawNetworkAuthorization({
2904
3041
  targetNode,
2905
3042
  networkId,
2906
- action: NETWORK_CREATE_ACTION,
3043
+ action: NETWORK_CREATE_ACTION2,
2907
3044
  facts
2908
3045
  });
2909
3046
  const response = await fetch(`${this.config.host}/encryption/networks`, {
@@ -2924,12 +3061,19 @@ var _TinyCloudNode = class _TinyCloudNode {
2924
3061
  const created = await response.json();
2925
3062
  return created.descriptor;
2926
3063
  }
2927
- async ensureEncryptionNetwork(name = DEFAULT_ENCRYPTION_NETWORK_NAME) {
2928
- const existing = await this.getEncryptionNetwork(name);
3064
+ async ensureEncryptionNetwork(nameOrNetworkId = DEFAULT_ENCRYPTION_NETWORK_NAME) {
3065
+ const networkId = nameOrNetworkId.startsWith("urn:tinycloud:encryption:") ? nameOrNetworkId : this.getDefaultEncryptionNetworkId(nameOrNetworkId);
3066
+ const existing = await this.getEncryptionNetwork(networkId);
2929
3067
  if (existing) {
2930
3068
  return existing;
2931
3069
  }
2932
- return this.createEncryptionNetwork(name);
3070
+ const parsed = parseNetworkId2(networkId);
3071
+ if (!didPrincipalMatches2(parsed.ownerDid, this.did)) {
3072
+ throw new Error(
3073
+ `Cannot create encryption network ${networkId}: owner ${parsed.ownerDid} does not match signed-in DID ${this.did}`
3074
+ );
3075
+ }
3076
+ return this.createEncryptionNetwork(parsed.name);
2933
3077
  }
2934
3078
  /**
2935
3079
  * App-facing secrets API backed by the `secrets` space vault.
@@ -3077,7 +3221,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3077
3221
  throw new SessionExpiredError(delegation.expiry);
3078
3222
  }
3079
3223
  const expectedDids = [session.verificationMethod, this.sessionDid];
3080
- if (!expectedDids.some((did) => didPrincipalMatches(delegation.delegateDID, did))) {
3224
+ if (!expectedDids.some((did) => didPrincipalMatches2(delegation.delegateDID, did))) {
3081
3225
  throw new Error(
3082
3226
  `Runtime delegation targets ${delegation.delegateDID} but this session key is ${session.verificationMethod}.`
3083
3227
  );
@@ -3606,7 +3750,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3606
3750
  );
3607
3751
  }
3608
3752
  const target = request.delegationTargets.find(
3609
- (entry) => didPrincipalMatches(entry.did, did)
3753
+ (entry) => didPrincipalMatches2(entry.did, did)
3610
3754
  );
3611
3755
  if (!target) {
3612
3756
  throw new Error(`No manifest delegation target found for DID ${did}`);
@@ -4056,7 +4200,23 @@ var _TinyCloudNode = class _TinyCloudNode {
4056
4200
  if (granted.resource !== void 0 || requested.resource !== void 0) {
4057
4201
  return granted.resource !== void 0 && requested.resource !== void 0 && granted.resource === requested.resource && this.pathContains(granted.path, requested.path);
4058
4202
  }
4059
- return granted.spaceId !== void 0 && requested.spaceId !== void 0 && granted.spaceId === requested.spaceId && this.pathContains(granted.path, requested.path);
4203
+ return granted.spaceId !== void 0 && requested.spaceId !== void 0 && this.spaceIdsEqual(granted.spaceId, requested.spaceId) && this.pathContains(granted.path, requested.path);
4204
+ }
4205
+ // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. The embedded
4206
+ // EIP-155 address is case-insensitive, but the CLI canonicalizes it to
4207
+ // lowercase when building a space URI while stored runtime delegations keep
4208
+ // the EIP-55 checksummed form — so a byte-for-byte compare spuriously rejects
4209
+ // an otherwise-valid grant. Lowercase ONLY the `eip155:<chain>:0x<addr>`
4210
+ // segment and leave everything else (crucially the case-sensitive space NAME)
4211
+ // byte-exact. Mirrors the CLI's `normalizeSpaceForCompare` (OPENKEY_SCOPE_MISMATCH fix).
4212
+ spaceIdsEqual(a, b) {
4213
+ return this.normalizeSpaceAddress(a) === this.normalizeSpaceAddress(b);
4214
+ }
4215
+ normalizeSpaceAddress(space) {
4216
+ return space.replace(
4217
+ /(eip155:\d+:)(0x[0-9a-fA-F]{40})/,
4218
+ (_match, prefix, addr) => prefix + addr.toLowerCase()
4219
+ );
4060
4220
  }
4061
4221
  actionContains(grantedAction, requestedAction) {
4062
4222
  if (grantedAction === requestedAction) {
@@ -4320,7 +4480,7 @@ var _TinyCloudNode = class _TinyCloudNode {
4320
4480
  const targetHost = delegation.host ?? this.config.host;
4321
4481
  if (this.isSessionOnly) {
4322
4482
  const myDid = this.did;
4323
- if (!didPrincipalMatches(delegation.delegateDID, myDid)) {
4483
+ if (!didPrincipalMatches2(delegation.delegateDID, myDid)) {
4324
4484
  throw new Error(
4325
4485
  `Delegation targets ${delegation.delegateDID} but this user's DID is ${myDid}. The delegation must target this user's DID.`
4326
4486
  );
@@ -4617,6 +4777,7 @@ import { ServiceContext as ServiceContext3 } from "@tinycloud/sdk-core";
4617
4777
  export {
4618
4778
  ACCOUNT_REGISTRY_PATH,
4619
4779
  ACCOUNT_REGISTRY_SPACE2 as ACCOUNT_REGISTRY_SPACE,
4780
+ AccountService,
4620
4781
  AutoApproveSpaceCreationHandler2 as AutoApproveSpaceCreationHandler,
4621
4782
  CapabilityKeyRegistry2 as CapabilityKeyRegistry,
4622
4783
  CapabilityKeyRegistryErrorCodes,
@@ -4692,7 +4853,7 @@ export {
4692
4853
  parseSpaceUri,
4693
4854
  pkhDid3 as pkhDid,
4694
4855
  principalDid,
4695
- principalDidEquals2 as principalDidEquals,
4856
+ principalDidEquals3 as principalDidEquals,
4696
4857
  resolveManifest2 as resolveManifest,
4697
4858
  resolveSecretListPrefix2 as resolveSecretListPrefix,
4698
4859
  resolveSecretPath2 as resolveSecretPath,