{"version":3,"sources":["../src/core.ts","../src/storage/MemorySessionStorage.ts","../src/storage/FileSessionStorage.ts","../src/authorization/NodeUserAuthorization.ts","../src/authorization/strategies.ts","../src/TinyCloudNode.ts","../src/account/AccountService.ts","../src/DelegatedAccess.ts","../src/keys/WasmKeyProvider.ts","../src/delegateToHelpers.ts","../src/NodeSecretsService.ts","../src/delegation.ts"],"sourcesContent":["/**\n * @tinycloud/node-sdk/core\n *\n * Platform-agnostic entry point for TinyCloud node-sdk.\n *\n * This entry point excludes Node.js-specific modules that depend on\n * @tinycloud/node-sdk-wasm (PrivateKeySigner, NodeWasmBindings), making it\n * safe to import in browser builds without webpack aliases or shims.\n *\n * Browser consumers (e.g., @tinycloud/web-sdk) should import from this\n * entry point instead of the root \"@tinycloud/node-sdk\".\n *\n * @packageDocumentation\n */\n\n// Re-export core values\nexport { TinyCloud } from \"@tinycloud/sdk-core\";\n\n// Re-export core types\nexport type {\n  TinyCloudConfig,\n  ISigner,\n  ISessionStorage,\n  IUserAuthorization,\n  ClientSession,\n  Extension,\n  SignInOptions,\n  PersistedSessionData,\n  TinyCloudSession,\n  INotificationHandler,\n  IENSResolver,\n  IWasmBindings,\n  ISessionManager,\n  ISpaceCreationHandler,\n  SpaceCreationContext,\n  CanonicalAddress,\n  CanonicalParsedNetworkId,\n  DidCacheKeyOptions,\n  DidEqualsOptions,\n  PkhDidParts,\n  TinyCloudDebugEvent,\n  TinyCloudDebugLevel,\n  TinyCloudDebugEnableOptions,\n  TinyCloudDebugTimer,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export core values for extensibility\nexport {\n  SilentNotificationHandler,\n  AutoApproveSpaceCreationHandler,\n  defaultSpaceCreationHandler,\n  IdentityParseError,\n  addressStorageKey,\n  canonicalizeAddress,\n  canonicalizeDid,\n  canonicalizeDidUrl,\n  canonicalizeNetworkId,\n  didCacheKey,\n  didEquals,\n  isEvmAddress,\n  makePkhSpaceId,\n  parsePkhDid,\n  pkhDid,\n  principalDid,\n  principalDidEquals,\n  parseCanonicalNetworkId,\n  TinyCloudDebugLogger,\n  tinyCloudDebugLogger,\n  enableTinyCloudDebug,\n  disableTinyCloudDebug,\n  getTinyCloudDebugLogs,\n  clearTinyCloudDebugLogs,\n  installTinyCloudDebugGlobals,\n} from \"@tinycloud/sdk-core\";\n\n// Storage implementations\nexport { MemorySessionStorage } from \"./storage/MemorySessionStorage\";\nexport { FileSessionStorage } from \"./storage/FileSessionStorage\";\n\n// Authorization\nexport {\n  NodeUserAuthorization,\n  type NodeUserAuthorizationConfig,\n} from \"./authorization/NodeUserAuthorization\";\n\n// Sign strategies — value exports\nexport {\n  createOpenKeyCallbackSigningStrategy,\n  defaultSignStrategy,\n} from \"./authorization/strategies\";\n\n// Sign strategies — type exports (re-exported from sdk-core + Node.js-specific types)\nexport type {\n  SignRequest,\n  SignResponse,\n  SignCallback,\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n  OpenKeySigningStrategyOptions,\n  OpenKeySigningRequestBody,\n  OpenKeySigningResponseBody,\n  OpenKeyCallbackStrategy,\n  NodeEventEmitterStrategy,\n  SignStrategy,\n} from \"./authorization/strategies\";\n\n// High-level API\nexport {\n  TinyCloudNode,\n  type TinyCloudNodeConfig,\n  type DelegateToOptions,\n  type DelegateToResult,\n  type RuntimePermissionGrantOptions,\n} from \"./TinyCloudNode\";\n\nexport { AccountService } from \"./account/AccountService\";\nexport type {\n  AccountApplication,\n  AccountApplicationListOptions,\n  AccountDelegation,\n  AccountDelegationListOptions,\n  AccountDelegationRevokeOptions,\n  AccountIndexEnsureResult,\n  AccountIndexRebuildResult,\n  AccountIndexStatus,\n  AccountIndexedReadOptions,\n  AccountServiceConfig,\n  AccountSpace,\n  AccountSpaceListOptions,\n  AccountStatus,\n} from \"./account/AccountService\";\n\n// Capability-chain primitives (spec: .claude/specs/capability-chain.md).\n// Re-exported here so TinyCloudWeb and other consumers can pass\n// `PermissionEntry[]` to `delegateTo` and catch the error classes without\n// also importing from `@tinycloud/sdk-core`.\nexport {\n  type PermissionEntry,\n  type Manifest,\n  type ManifestDefaults,\n  type ManifestSecretActions,\n  type ComposeManifestOptions,\n  type ComposedManifestRequest,\n  type ManifestRegistryRecord,\n  type ResolvedCapabilities,\n  type ResolvedDelegate,\n  type ResourceCapability,\n  type SpaceAbilitiesMap,\n  ACCOUNT_REGISTRY_PATH,\n  ACCOUNT_REGISTRY_SPACE,\n  DEFAULT_MANIFEST_SPACE,\n  DEFAULT_MANIFEST_VERSION,\n  VAULT_PERMISSION_SERVICE,\n  PermissionNotInManifestError,\n  SessionExpiredError,\n  ManifestValidationError,\n  composeManifestRequest,\n  resolveManifest,\n  validateManifest,\n  loadManifest,\n  isCapabilitySubset,\n  expandActionShortNames,\n  expandPermissionEntries,\n  expandPermissionEntry,\n  parseExpiry,\n  resourceCapabilitiesToSpaceAbilitiesMap,\n} from \"@tinycloud/sdk-core\";\n\n// Delegation\nexport { DelegatedAccess } from \"./DelegatedAccess\";\nexport { serializeDelegation, deserializeDelegation } from \"./delegation\";\nexport type { PortableDelegation } from \"./delegation\";\n\n// Re-export KV service values\nexport {\n  DEFAULT_SIGNED_READ_URL_EXPIRY_MS,\n  KVService,\n  PrefixedKVService,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export KV service types\nexport type {\n  IKVService,\n  KVServiceConfig,\n  KVCreateSignedReadUrlOptions,\n  KVResponse,\n  KVSignedReadUrlResponse,\n  IPrefixedKVService,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SQL service values\nexport { SQLService, SQLAction, DatabaseHandle } from \"@tinycloud/sdk-core\";\n\n// Re-export SQL service types\nexport type {\n  ISQLService,\n  IDatabaseHandle,\n  SQLServiceConfig,\n  SqlValue,\n  SqlStatement,\n  QueryOptions,\n  ExecuteOptions,\n  BatchOptions,\n  QueryResponse,\n  ExecuteResponse,\n  BatchResponse,\n  SQLActionType,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export DuckDB service values\nexport {\n  DuckDbService,\n  DuckDbDatabaseHandle,\n  DuckDbAction,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export DuckDB service types\nexport type {\n  IDuckDbService,\n  IDuckDbDatabaseHandle,\n  DuckDbServiceConfig,\n  DuckDbQueryOptions,\n  DuckDbExecuteOptions,\n  DuckDbBatchOptions,\n  DuckDbOptions,\n  DuckDbValue,\n  DuckDbStatement,\n  DuckDbQueryResponse,\n  DuckDbExecuteResponse,\n  DuckDbBatchResponse,\n  DuckDbActionType,\n  SchemaInfo,\n  TableInfo,\n  ColumnInfo,\n  ViewInfo,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export Vault and Secrets service values\nexport {\n  DataVaultService,\n  VaultHeaders,\n  VaultPublicSpaceKVActions,\n  createVaultCrypto,\n  SecretsService,\n  SECRET_NAME_RE,\n  canonicalizeSecretScope,\n  resolveSecretListPrefix,\n  resolveSecretPath,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export Vault and Secrets service types\nexport type {\n  IDataVaultService,\n  VaultCrypto,\n  WasmVaultFunctions,\n  DataVaultConfig,\n  VaultPutOptions,\n  VaultGetOptions,\n  VaultListOptions,\n  VaultGrantOptions,\n  VaultEntry,\n  VaultError,\n  ISecretsService,\n  SecretPayload,\n  SecretsError,\n  ResolvedSecretPath,\n  SecretScopeOptions,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export v2 Delegation service values\nexport {\n  DelegationManager,\n  SharingService,\n  createSharingService,\n  DelegationErrorCodes,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export v2 Delegation types\nexport type {\n  DelegationManagerConfig,\n  ISharingService,\n  SharingServiceConfig,\n  EncodedShareData,\n  ReceiveOptions,\n  ShareAccess,\n  Delegation,\n  CreateDelegationParams,\n  DelegationResult,\n  DelegationError,\n  DelegationErrorCode,\n  JWK,\n  KeyType,\n  KeyInfo,\n  CapabilityEntry,\n  DelegationRecord,\n  SpaceOwnership,\n  SpaceInfo,\n  ShareSchema,\n  ShareLink,\n  ShareLinkData,\n  IngestOptions,\n  GenerateShareParams,\n  DelegationChain,\n  DelegationChainV2,\n  DelegationDirection,\n  DelegationFilters,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export CapabilityKeyRegistry values (v2)\nexport {\n  CapabilityKeyRegistry,\n  createCapabilityKeyRegistry,\n  CapabilityKeyRegistryErrorCodes,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export CapabilityKeyRegistry types (v2)\nexport type {\n  ICapabilityKeyRegistry,\n  StoredDelegationChain,\n  CapabilityKeyRegistryErrorCode,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SpaceService values (v2)\nexport {\n  SpaceService,\n  SpaceErrorCodes,\n  createSpaceService,\n  parseSpaceUri,\n  buildSpaceUri,\n  makePublicSpaceId,\n  Space,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SpaceService types (v2)\nexport type {\n  ISpaceService,\n  SpaceServiceConfig,\n  SpaceErrorCode,\n  ISpace,\n  SpaceConfig,\n  ISpaceScopedDelegations,\n  ISpaceScopedSharing,\n} from \"@tinycloud/sdk-core\";\n\n// Protocol version checking\nexport {\n  ProtocolMismatchError,\n  VersionCheckError,\n  UnsupportedFeatureError,\n  checkNodeInfo,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export ServiceContext value for advanced usage\nexport { ServiceContext } from \"@tinycloud/sdk-core\";\n\n// Re-export ServiceContext types for advanced usage\nexport type {\n  ServiceContextConfig,\n  ServiceSession,\n  InvokeFunction,\n  FetchFunction,\n  TelemetryConfig,\n  TelemetryEventHandler,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export KeyProvider interface from sdk-core\nexport type { KeyProvider } from \"@tinycloud/sdk-core\";\n\n// Key management for node-sdk\nexport {\n  WasmKeyProvider,\n  type WasmKeyProviderConfig,\n  createWasmKeyProvider,\n} from \"./keys/WasmKeyProvider\";\n","import { ISessionStorage, PersistedSessionData } from \"@tinycloud/sdk-core\";\n\n/**\n * In-memory session storage for Node.js.\n *\n * Sessions are stored in memory and lost when the process exits.\n * Suitable for:\n * - Development and testing\n * - Stateless server deployments\n * - Short-lived processes\n *\n * @example\n * ```typescript\n * const storage = new MemorySessionStorage();\n * await storage.save(\"0x123...\", sessionData);\n * const session = await storage.load(\"0x123...\");\n * ```\n */\nexport class MemorySessionStorage implements ISessionStorage {\n  private sessions: Map<string, PersistedSessionData> = new Map();\n\n  /**\n   * Save a session for an address.\n   */\n  async save(address: string, session: PersistedSessionData): Promise<void> {\n    const normalizedAddress = address.toLowerCase();\n    this.sessions.set(normalizedAddress, session);\n  }\n\n  /**\n   * Load a session for an address.\n   */\n  async load(address: string): Promise<PersistedSessionData | null> {\n    const normalizedAddress = address.toLowerCase();\n    const session = this.sessions.get(normalizedAddress);\n\n    if (!session) {\n      return null;\n    }\n\n    // Check if session is expired\n    const expiresAt = new Date(session.expiresAt);\n    if (expiresAt < new Date()) {\n      this.sessions.delete(normalizedAddress);\n      return null;\n    }\n\n    return session;\n  }\n\n  /**\n   * Clear a session for an address.\n   */\n  async clear(address: string): Promise<void> {\n    const normalizedAddress = address.toLowerCase();\n    this.sessions.delete(normalizedAddress);\n  }\n\n  /**\n   * Check if a session exists for an address.\n   */\n  exists(address: string): boolean {\n    const normalizedAddress = address.toLowerCase();\n    const session = this.sessions.get(normalizedAddress);\n\n    if (!session) {\n      return false;\n    }\n\n    // Check if session is expired\n    const expiresAt = new Date(session.expiresAt);\n    if (expiresAt < new Date()) {\n      this.sessions.delete(normalizedAddress);\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Memory storage is always available.\n   */\n  isAvailable(): boolean {\n    return true;\n  }\n\n  /**\n   * Clear all sessions.\n   */\n  clearAll(): void {\n    this.sessions.clear();\n  }\n\n  /**\n   * Get the number of stored sessions.\n   */\n  size(): number {\n    return this.sessions.size;\n  }\n}\n","import { ISessionStorage, PersistedSessionData, validatePersistedSessionData } from \"@tinycloud/sdk-core\";\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\n/**\n * File-based session storage for Node.js.\n *\n * Sessions are persisted to the file system and survive process restarts.\n * Suitable for:\n * - CLI applications\n * - Long-running server processes\n * - Development environments\n *\n * @example\n * ```typescript\n * const storage = new FileSessionStorage(\"/tmp/tinycloud-sessions\");\n * await storage.save(\"0x123...\", sessionData);\n * // Session persists across process restarts\n * ```\n */\nexport class FileSessionStorage implements ISessionStorage {\n  private readonly baseDir: string;\n\n  /**\n   * Create a new FileSessionStorage.\n   *\n   * @param baseDir - Directory to store session files (default: ~/.tinycloud/sessions)\n   */\n  constructor(baseDir?: string) {\n    this.baseDir = baseDir || this.getDefaultDir();\n    this.ensureDirectoryExists();\n  }\n\n  /**\n   * Get the default session storage directory.\n   */\n  private getDefaultDir(): string {\n    const home = process.env.HOME || process.env.USERPROFILE || \"/tmp\";\n    return join(home, \".tinycloud\", \"sessions\");\n  }\n\n  /**\n   * Ensure the storage directory exists.\n   */\n  private ensureDirectoryExists(): void {\n    if (!existsSync(this.baseDir)) {\n      mkdirSync(this.baseDir, { recursive: true });\n    }\n  }\n\n  /**\n   * Get the file path for an address.\n   */\n  private getFilePath(address: string): string {\n    const normalizedAddress = address.toLowerCase();\n    // Use a hash of the address to avoid filesystem issues\n    const filename = `${normalizedAddress.replace(\"0x\", \"\")}.json`;\n    return join(this.baseDir, filename);\n  }\n\n  /**\n   * Save a session for an address.\n   */\n  async save(address: string, session: PersistedSessionData): Promise<void> {\n    const filePath = this.getFilePath(address);\n    const data = JSON.stringify(session, null, 2);\n    writeFileSync(filePath, data, \"utf-8\");\n  }\n\n  /**\n   * Load a session for an address.\n   */\n  async load(address: string): Promise<PersistedSessionData | null> {\n    const filePath = this.getFilePath(address);\n\n    if (!existsSync(filePath)) {\n      return null;\n    }\n\n    try {\n      const data = readFileSync(filePath, \"utf-8\");\n      const parsed = JSON.parse(data);\n\n      // Validate loaded data against schema\n      const validation = validatePersistedSessionData(parsed);\n      if (!validation.ok) {\n        console.warn(`Invalid session data for ${address}:`, validation.error.message);\n        // Clean up invalid session\n        unlinkSync(filePath);\n        return null;\n      }\n\n      const session = validation.data;\n\n      // Check if session is expired\n      const expiresAt = new Date(session.expiresAt);\n      if (expiresAt < new Date()) {\n        // Clean up expired session\n        unlinkSync(filePath);\n        return null;\n      }\n\n      return session;\n    } catch (error) {\n      // Invalid JSON or read error - remove the file\n      try {\n        unlinkSync(filePath);\n      } catch {\n        // Ignore cleanup errors\n      }\n      return null;\n    }\n  }\n\n  /**\n   * Clear a session for an address.\n   */\n  async clear(address: string): Promise<void> {\n    const filePath = this.getFilePath(address);\n    if (existsSync(filePath)) {\n      unlinkSync(filePath);\n    }\n  }\n\n  /**\n   * Check if a session exists for an address.\n   */\n  exists(address: string): boolean {\n    const filePath = this.getFilePath(address);\n    if (!existsSync(filePath)) {\n      return false;\n    }\n\n    try {\n      const data = readFileSync(filePath, \"utf-8\");\n      const session: PersistedSessionData = JSON.parse(data);\n\n      // Check if session is expired\n      const expiresAt = new Date(session.expiresAt);\n      if (expiresAt < new Date()) {\n        // Clean up expired session\n        unlinkSync(filePath);\n        return false;\n      }\n\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Check if file system storage is available.\n   */\n  isAvailable(): boolean {\n    try {\n      this.ensureDirectoryExists();\n      return existsSync(this.baseDir);\n    } catch {\n      return false;\n    }\n  }\n}\n","import { EventEmitter } from \"events\";\nimport {\n  IUserAuthorization,\n  ISigner,\n  ISessionStorage,\n  ClientSession,\n  Extension,\n  PersistedSessionData,\n  TinyCloudSession,\n  SiweConfig,\n  SignInOptions,\n  SpaceHostResult,\n  fetchPeerId,\n  submitHostDelegation,\n  activateSessionWithHost,\n  checkNodeInfo,\n  ISpaceCreationHandler,\n  AutoApproveSpaceCreationHandler,\n  IWasmBindings,\n  ISessionManager,\n  Manifest,\n  ComposedManifestRequest,\n  AbilitiesMap,\n  DEFAULT_MANIFEST_SPACE,\n  ENCRYPTION_PERMISSION_SERVICE,\n  composeManifestRequest,\n  parseNetworkId,\n  principalDidEquals,\n  resourceCapabilitiesToAbilitiesMap,\n  resourceCapabilitiesToSpaceAbilitiesMap,\n  resolveTinyCloudHosts,\n  EXPIRY,\n  canonicalizeAddress,\n  makePkhSpaceId,\n  pkhDid,\n} from \"@tinycloud/sdk-core\";\nimport {\n  SignStrategy,\n  SignRequest,\n  SignResponse,\n  defaultSignStrategy,\n} from \"./strategies\";\nimport { MemorySessionStorage } from \"../storage/MemorySessionStorage\";\n\nconst DECRYPT_ACTION = \"tinycloud.encryption/decrypt\";\nconst NETWORK_CREATE_ACTION = \"tinycloud.encryption/network.create\";\n\nfunction didPrincipalMatches(actual: string, expected: string): boolean {\n  try {\n    return principalDidEquals(actual, expected);\n  } catch {\n    return actual === expected;\n  }\n}\n\nfunction addRawAbility(\n  rawAbilities: Record<string, string[]>,\n  resource: string,\n  action: string,\n): void {\n  const actions = rawAbilities[resource];\n  if (actions === undefined) {\n    rawAbilities[resource] = [action];\n    return;\n  }\n  if (!actions.includes(action)) {\n    actions.push(action);\n  }\n}\n\n/**\n * Configuration for NodeUserAuthorization.\n */\nexport interface NodeUserAuthorizationConfig {\n  /** The signer used for signing messages */\n  signer: ISigner;\n  /** Sign strategy for handling sign requests */\n  signStrategy?: SignStrategy;\n  /** Session storage implementation */\n  sessionStorage?: ISessionStorage;\n  /** Domain for SIWE messages */\n  domain: string;\n  /** URI for SIWE messages (default: domain) */\n  uri?: string;\n  /** Statement included in SIWE messages */\n  statement?: string;\n  /** Space prefix for new sessions */\n  spacePrefix?: string;\n  /** Default actions for sessions */\n  defaultActions?: Record<string, Record<string, string[]>>;\n  /** Session expiration time in milliseconds (default: 1 hour) */\n  sessionExpirationMs?: number;\n  /** Automatically create space if it doesn't exist (default: false) */\n  autoCreateSpace?: boolean;\n  /** Custom space creation handler. If provided, takes precedence over autoCreateSpace. */\n  spaceCreationHandler?: ISpaceCreationHandler;\n  /** Explicit TinyCloud server endpoints. When omitted, signIn resolves the user's host. */\n  tinycloudHosts?: string[];\n  /** TinyCloud location registry URL. Default: https://registry.tinycloud.xyz. */\n  tinycloudRegistryUrl?: string | null;\n  /** Fallback TinyCloud hosts. Default: hosted TinyCloud node. */\n  tinycloudFallbackHosts?: string[] | null;\n  /** Whether to include public space capabilities in the session (default: true) */\n  enablePublicSpace?: boolean;\n  /** WASM bindings for cryptographic operations. Required. */\n  wasmBindings: IWasmBindings;\n  /**\n   * SIWE nonce override. If omitted, the WASM layer generates a random nonce.\n   * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.\n   */\n  nonce?: string;\n  /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */\n  siweConfig?: SiweConfig;\n  /**\n   * App manifest used to drive the SIWE recap at sign-in.\n   *\n   * When set, `signIn` resolves the manifest (via\n   * {@link resolveManifest}), unions the app's own permissions with\n   * every `delegations[*].permissions` list, converts to the WASM\n   * abilities shape, and uses that map as the session's granted\n   * capabilities — *instead* of `defaultActions`.\n   *\n   * This is what makes manifest-declared pre-delegations usable: the\n   * session key's recap covers both the app's runtime needs and the\n   * downstream delegation targets, so `delegateTo` can issue the\n   * sub-delegation via the session-key UCAN path without a wallet\n   * prompt.\n   *\n   * When omitted, `signIn` falls back to `defaultActions` for\n   * backwards compatibility.\n   */\n  manifest?: Manifest | Manifest[];\n  /** Pre-composed manifest request. Takes precedence over `manifest`. */\n  capabilityRequest?: ComposedManifestRequest;\n  /** Include implicit account registry permissions when composing `manifest`. Default true. */\n  includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface CreateBootstrapSessionOptions {\n  spaceId: string;\n  capabilityRequest: ComposedManifestRequest;\n  rawAbilities?: Record<string, string[]>;\n}\n\n/**\n * Node.js implementation of IUserAuthorization.\n *\n * Supports multiple sign strategies for different use cases:\n * - auto-sign: Automatically approve all sign requests (trusted backends)\n * - auto-reject: Reject all sign requests (read-only mode)\n * - callback: Delegate to a custom callback function (CLI prompts)\n * - event-emitter: Emit sign requests as events (async workflows)\n *\n * @example\n * ```typescript\n * // Auto-sign for backend services\n * const auth = new NodeUserAuthorization({\n *   signer: new PrivateKeySigner(process.env.PRIVATE_KEY),\n *   signStrategy: { type: 'auto-sign' },\n *   domain: 'api.myapp.com',\n * });\n *\n * // Callback for CLI prompts\n * const auth = new NodeUserAuthorization({\n *   signer,\n *   signStrategy: {\n *     type: 'callback',\n *     handler: async (req) => {\n *       const approved = await promptUser(`Sign for ${req.address}?`);\n *       return { approved };\n *     }\n *   },\n *   domain: 'cli.myapp.com',\n * });\n * ```\n */\nexport class NodeUserAuthorization implements IUserAuthorization {\n  private readonly signer: ISigner;\n  private readonly signStrategy: SignStrategy;\n  private readonly sessionStorage: ISessionStorage;\n  private readonly domain: string;\n  private readonly uri: string;\n  private readonly statement?: string;\n  private readonly spacePrefix: string;\n  private readonly defaultActions: Record<string, Record<string, string[]>>;\n  private readonly sessionExpirationMs: number;\n  private readonly autoCreateSpace: boolean;\n  private readonly spaceCreationHandler?: ISpaceCreationHandler;\n  private tinycloudHosts?: string[];\n  private readonly tinycloudRegistryUrl?: string | null;\n  private readonly tinycloudFallbackHosts?: string[] | null;\n  private readonly enablePublicSpace: boolean;\n  private readonly nonce?: string;\n  private readonly siweConfig?: SiweConfig;\n  private readonly wasm: IWasmBindings;\n  /**\n   * Stored manifest, if one was provided at construction time. Used by\n   * {@link signIn} to derive the session's granted capabilities instead\n   * of falling back to {@link defaultActions}.\n   */\n  private _manifest?: Manifest | Manifest[];\n  private _capabilityRequest?: ComposedManifestRequest;\n  private readonly includeAccountRegistryPermissions: boolean;\n\n  private sessionManager: ISessionManager;\n  private extensions: Extension[] = [];\n  private _session?: ClientSession;\n  private _tinyCloudSession?: TinyCloudSession;\n  private _address?: string;\n  private _chainId?: number;\n  private _nodeFeatures: string[] = [];\n  private _lastActivationSkippedSpaceIds: string[] = [];\n\n  constructor(config: NodeUserAuthorizationConfig) {\n    this.wasm = config.wasmBindings;\n\n    this.signer = config.signer;\n    this.signStrategy = config.signStrategy ?? defaultSignStrategy;\n    this.sessionStorage = config.sessionStorage ?? new MemorySessionStorage();\n    this.domain = config.domain;\n    this.uri = config.uri ?? `https://${config.domain}`;\n    this.statement = config.statement;\n    this.spacePrefix = config.spacePrefix ?? \"default\";\n    this.defaultActions = config.defaultActions ?? {\n      kv: {\n        \"\": [\n          \"tinycloud.kv/put\",\n          \"tinycloud.kv/get\",\n          \"tinycloud.kv/del\",\n          \"tinycloud.kv/list\",\n          \"tinycloud.kv/metadata\",\n        ],\n      },\n      sql: {\n        \"\": [\n          \"tinycloud.sql/read\",\n          \"tinycloud.sql/write\",\n          \"tinycloud.sql/schema\",\n          \"tinycloud.sql/admin\",\n          \"tinycloud.sql/export\",\n        ],\n      },\n      duckdb: {\n        \"\": [\n          \"tinycloud.duckdb/read\",\n          \"tinycloud.duckdb/write\",\n          \"tinycloud.duckdb/admin\",\n          \"tinycloud.duckdb/describe\",\n          \"tinycloud.duckdb/export\",\n          \"tinycloud.duckdb/import\",\n          \"tinycloud.duckdb/execute\",\n        ],\n      },\n      capabilities: {\n        \"\": [\"tinycloud.capabilities/read\"],\n      },\n      hooks: {\n        \"\": [\n          \"tinycloud.hooks/subscribe\",\n          \"tinycloud.hooks/register\",\n          \"tinycloud.hooks/list\",\n          \"tinycloud.hooks/unregister\",\n        ],\n      },\n    };\n    this.sessionExpirationMs = config.sessionExpirationMs ?? EXPIRY.SESSION_MS;\n    this.autoCreateSpace = config.autoCreateSpace ?? false;\n    this.spaceCreationHandler = config.spaceCreationHandler;\n    this.tinycloudHosts = config.tinycloudHosts;\n    this.tinycloudRegistryUrl = config.tinycloudRegistryUrl;\n    this.tinycloudFallbackHosts = config.tinycloudFallbackHosts;\n    this.enablePublicSpace = config.enablePublicSpace ?? true;\n    this.nonce = config.nonce;\n    this.siweConfig = config.siweConfig;\n    this.includeAccountRegistryPermissions =\n      config.includeAccountRegistryPermissions ?? true;\n    this._manifest = config.manifest;\n    this._capabilityRequest = config.capabilityRequest;\n\n    // Initialize session manager via WASM bindings\n    this.sessionManager = this.wasm.createSessionManager();\n  }\n\n  /**\n   * Return the manifest currently driving sign-in behavior, or\n   * `undefined` if none is set. Used by TinyCloudWeb/TinyCloudNode\n   * internals to surface the manifest for requestPermissions flows\n   * without forcing the caller to track it separately.\n   */\n  get manifest(): Manifest | Manifest[] | undefined {\n    return this._manifest;\n  }\n\n  get capabilityRequest(): ComposedManifestRequest | undefined {\n    return this.getCapabilityRequest();\n  }\n\n  get hosts(): string[] {\n    return this.tinycloudHosts ? [...this.tinycloudHosts] : [];\n  }\n\n  /**\n   * Install or replace the stored manifest. Takes effect on the next\n   * `signIn()` call — the current session (if any) is not touched.\n   */\n  setManifest(manifest: Manifest | Manifest[] | undefined): void {\n    this._manifest = manifest;\n    this._capabilityRequest = undefined;\n  }\n\n  setCapabilityRequest(request: ComposedManifestRequest | undefined): void {\n    this._capabilityRequest = request;\n  }\n\n  /**\n   * The current active session (web-core compatible).\n   */\n  get session(): ClientSession | undefined {\n    return this._session;\n  }\n\n  /**\n   * The current TinyCloud session with full delegation data.\n   * Includes spaceId, delegationHeader, and delegationCid.\n   */\n  get tinyCloudSession(): TinyCloudSession | undefined {\n    return this._tinyCloudSession;\n  }\n\n  /**\n   * Rehydrate the auth-layer session from previously-persisted delegation\n   * data. Used by {@link TinyCloudNode.restoreSession} so that downstream\n   * surfaces that read from `tinyCloudSession` (notably\n   * `grantRuntimePermissions`, which extracts the SIWE expiry from it) work\n   * without re-running the full sign-in flow.\n   *\n   * Caller must supply the same fields that `signIn` would have written —\n   * `siwe` is the load-bearing one because `extractSiweExpiration` returns\n   * undefined for missing SIWEs and the SDK then treats the session as\n   * expired-at-epoch-zero.\n   *\n   * @param hosts - The TinyCloud hosts this session was created against,\n   *   as persisted in {@link PersistedSessionData.tinycloudHosts}. When\n   *   present (and non-empty) they are adopted directly so the restored\n   *   session resolves to the same node as the original sign-in without\n   *   re-running registry/fallback resolution. When absent (old session)\n   *   hosts are resolved lazily on the first host-needing call via\n   *   {@link ensureTinyCloudHosts}.\n   */\n  setRestoredTinyCloudSession(\n    session: TinyCloudSession,\n    hosts?: string[],\n  ): void {\n    const address = canonicalizeAddress(session.address);\n    this._tinyCloudSession = { ...session, address };\n    this._address = address;\n    this._chainId = session.chainId;\n    // Don't overwrite an explicitly-configured host (e.g. local dev) with a\n    // possibly-stale persisted value: only adopt persisted hosts when none\n    // are already set.\n    if (\n      (!this.tinycloudHosts || this.tinycloudHosts.length === 0) &&\n      hosts &&\n      hosts.length > 0\n    ) {\n      this.tinycloudHosts = [...hosts];\n    }\n  }\n\n  /**\n   * Ensure `tinycloudHosts` are resolved before a host-needing call.\n   *\n   * Fresh sign-in resolves hosts up front; a restored session may not have\n   * (old persisted sessions predate {@link PersistedSessionData.tinycloudHosts}).\n   * This guard makes a restored session resolve the node exactly like a fresh\n   * sign-in — persisted hosts are preferred (already set by\n   * {@link setRestoredTinyCloudSession}), otherwise the registry/fallback\n   * resolution runs lazily here. Idempotent: {@link resolveTinyCloudHostsForSignIn}\n   * early-returns when hosts are already set.\n   *\n   * Throws if hosts are unset and the restored session has no address/chainId\n   * to resolve from — a real failure that must surface, not be masked.\n   */\n  async ensureTinyCloudHosts(): Promise<void> {\n    if (this.tinycloudHosts && this.tinycloudHosts.length > 0) {\n      return;\n    }\n    if (this._address === undefined || this._chainId === undefined) {\n      throw new Error(\n        \"Cannot resolve TinyCloud hosts: no address/chainId available. \" +\n          \"Sign in or restore a session first.\",\n      );\n    }\n    await this.resolveTinyCloudHostsForSignIn(this._address, this._chainId);\n  }\n\n  private async resolveTinyCloudHostsForSignIn(\n    address: string,\n    chainId: number,\n  ): Promise<void> {\n    if (this.tinycloudHosts && this.tinycloudHosts.length > 0) {\n      return;\n    }\n\n    const subject = pkhDid(address, chainId);\n    const resolved = await resolveTinyCloudHosts(subject, {\n      registryUrl: this.tinycloudRegistryUrl,\n      fallbackHosts: this.tinycloudFallbackHosts,\n    });\n    this.tinycloudHosts = resolved.hosts;\n  }\n\n  private requireTinyCloudHosts(): string[] {\n    if (!this.tinycloudHosts || this.tinycloudHosts.length === 0) {\n      throw new Error(\"TinyCloud hosts have not been resolved. Call signIn() first.\");\n    }\n    return this.tinycloudHosts;\n  }\n\n  private get primaryTinyCloudHost(): string {\n    return this.requireTinyCloudHosts()[0];\n  }\n\n  get nodeFeatures(): string[] {\n    return this._nodeFeatures;\n  }\n\n  get lastActivationSkippedSpaceIds(): string[] {\n    return [...this._lastActivationSkippedSpaceIds];\n  }\n\n  /**\n   * Compute the `abilities` map the WASM `prepareSession` call should\n   * see at sign-in time.\n   *\n   * When a manifest is installed, we resolve it and union together:\n   * - the app's own `resources` (what it needs at runtime)\n   * - every `additionalDelegates[*].permissions` list (what it will\n   *   re-delegate to other DIDs post sign-in)\n   *\n   * into the short-service / path / full-URN-actions shape the WASM\n   * layer expects. This is the key invariant that lets\n   * {@link TinyCloudNode.delegateTo} issue manifest-declared\n   * delegations via the session key (no wallet prompt): the session's\n   * own recap already covers every action those delegations need.\n   *\n   * When no manifest is installed, we fall back to the\n   * {@link defaultActions} table so existing callers see no change.\n   *\n   * This is a pure function of `this._manifest` + `this.defaultActions`\n   * — the manifest resolution performs no I/O and throws a\n   * {@link ManifestValidationError} on structural problems (missing\n   * id/name, unparseable expiry, etc), which will surface at sign-in\n   * rather than being silently swallowed.\n   *\n   * @internal\n   */\n  private getCapabilityRequest(): ComposedManifestRequest | undefined {\n    if (this._capabilityRequest !== undefined) {\n      return this._capabilityRequest;\n    }\n    if (this._manifest === undefined) {\n      return undefined;\n    }\n    this._capabilityRequest = composeManifestRequest(\n      Array.isArray(this._manifest) ? this._manifest : [this._manifest],\n      {\n        includeAccountRegistryPermissions:\n          this.includeAccountRegistryPermissions,\n      }\n    );\n    return this._capabilityRequest;\n  }\n\n  private resolveSpaceName(space: string, address: string, chainId: number): string {\n    if (space.startsWith(\"tinycloud:\")) {\n      return space;\n    }\n    return makePkhSpaceId(address, chainId, space);\n  }\n\n  private defaultEncryptionNetworkId(address: string, chainId: number): string {\n    return `urn:tinycloud:encryption:${pkhDid(address, chainId)}:default`;\n  }\n\n  private resolveSignInCapabilities(\n    address: string,\n    chainId: number,\n  ): {\n    abilities: AbilitiesMap;\n    spaceId: string;\n    spaceAbilities?: Record<string, AbilitiesMap>;\n    rawAbilities?: Record<string, string[]>;\n  } {\n    const request = this.getCapabilityRequest();\n    if (request === undefined) {\n      const defaultNetworkId = this.defaultEncryptionNetworkId(address, chainId);\n      const primarySpaceId = makePkhSpaceId(address, chainId, this.spacePrefix);\n      const secretsSpaceId = makePkhSpaceId(address, chainId, \"secrets\");\n      return {\n        abilities: this.defaultActions,\n        spaceId: primarySpaceId,\n        spaceAbilities: {\n          [primarySpaceId]: this.defaultActions,\n          [secretsSpaceId]: {\n            kv: {\n              \"vault/secrets/\": [\n                \"tinycloud.kv/get\",\n                \"tinycloud.kv/put\",\n                \"tinycloud.kv/del\",\n                \"tinycloud.kv/list\",\n                \"tinycloud.kv/metadata\",\n              ],\n            },\n          },\n        },\n        rawAbilities: {\n          [defaultNetworkId]: [\n            \"tinycloud.encryption/decrypt\",\n            \"tinycloud.encryption/network.create\",\n          ],\n        },\n      };\n    }\n\n    const rawAbilities: Record<string, string[]> = {};\n    const currentDid = pkhDid(address, chainId);\n    const spaceResources = request.resources.filter((entry) => {\n      if (entry.service !== ENCRYPTION_PERMISSION_SERVICE) {\n        return true;\n      }\n      for (const action of entry.actions) {\n        addRawAbility(rawAbilities, entry.path, action);\n      }\n      if (entry.actions.includes(DECRYPT_ACTION)) {\n        const parsed = parseNetworkId(entry.path);\n        if (didPrincipalMatches(parsed.ownerDid, currentDid)) {\n          addRawAbility(rawAbilities, entry.path, NETWORK_CREATE_ACTION);\n        }\n      }\n      return false;\n    });\n\n    const primarySpaceName =\n      spaceResources.find((entry) => entry.space !== \"account\")?.space ??\n      DEFAULT_MANIFEST_SPACE;\n    const primarySpaceId = this.resolveSpaceName(\n      primarySpaceName,\n      address,\n      chainId,\n    );\n\n    const bySpace = resourceCapabilitiesToSpaceAbilitiesMap(spaceResources);\n    const spaceAbilities: Record<string, AbilitiesMap> = {};\n    for (const [space, abilities] of Object.entries(bySpace)) {\n      spaceAbilities[this.resolveSpaceName(space, address, chainId)] = abilities;\n    }\n\n    return {\n      abilities:\n        spaceAbilities[primarySpaceId] ??\n        resourceCapabilitiesToAbilitiesMap([]),\n      spaceId: primarySpaceId,\n      spaceAbilities,\n      rawAbilities:\n        Object.keys(rawAbilities).length > 0 ? rawAbilities : undefined,\n    };\n  }\n\n  /**\n   * Build SIWE overrides from the top-level nonce and siweConfig.\n   * - Top-level `nonce` is seeded first so `siweConfig.nonce` wins if both are set.\n   * - statement is prepended to the default statement\n   * - resources are appended to the default resources\n   * - uri triggers a warning (overwriting delegation target)\n   * - all other fields override directly\n   * - per-call nonce overrides siweConfig.nonce when provided\n   */\n  private buildSiweOverrides(options?: SignInOptions): Record<string, unknown> {\n    const base: Record<string, unknown> = { uri: this.uri };\n    if (this.nonce !== undefined) {\n      base.nonce = this.nonce;\n    }\n\n    if (!this.siweConfig && !options?.nonce) {\n      return base;\n    }\n\n    const { statement, resources, uri, ...rest } = this.siweConfig ?? {};\n    const overrides: Record<string, unknown> = { ...base, ...rest };\n\n    if (statement) {\n      overrides.statement = this.statement\n        ? `${statement} ${this.statement}`\n        : statement;\n    }\n\n    if (resources && resources.length > 0) {\n      overrides.resources = resources;\n    }\n\n    if (uri) {\n      console.warn(\n        \"[tinycloud] siweConfig.uri is overwriting the delegation target URI. \" +\n          \"This may break delegation chain validation if the URI does not match the session key DID.\",\n      );\n      overrides.uri = uri;\n    }\n\n    if (options?.nonce) {\n      overrides.nonce = options.nonce;\n    }\n\n    return overrides;\n  }\n\n  /**\n   * Add an extension to the authorization flow.\n   */\n  extend(extension: Extension): void {\n    this.extensions.push(extension);\n  }\n\n  /**\n   * Get the space ID for the current session.\n   */\n  getSpaceId(): string | undefined {\n    return this._tinyCloudSession?.spaceId;\n  }\n\n  /**\n   * Create the space on the TinyCloud server (host delegation).\n   * This registers the user as the owner of the space.\n   */\n  private async hostSpace(targetSpaceId?: string): Promise<boolean> {\n    if (!this._tinyCloudSession || !this._address || !this._chainId) {\n      throw new Error(\"Must be signed in to host space\");\n    }\n\n    await this.ensureTinyCloudHosts();\n    const host = this.primaryTinyCloudHost;\n    const spaceId = targetSpaceId ?? this._tinyCloudSession.spaceId;\n\n    // Get peer ID from TinyCloud server\n    const peerId = await fetchPeerId(host, spaceId);\n\n    // Generate host SIWE message\n    const siwe = this.wasm.generateHostSIWEMessage({\n      address: this._address,\n      chainId: this._chainId,\n      domain: this.domain,\n      issuedAt: new Date().toISOString(),\n      spaceId,\n      peerId,\n    });\n\n    // Sign the message\n    const signature = await this.signMessage(siwe);\n\n    // Convert to delegation headers and submit\n    const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });\n    const result = await submitHostDelegation(host, headers);\n\n    return result.success;\n  }\n\n  /**\n   * Create a specific space on the server via host delegation.\n   * Used for lazy creation of additional spaces (e.g., public).\n   */\n  async hostPublicSpace(spaceId: string): Promise<boolean> {\n    return this.hostSpace(spaceId);\n  }\n\n  /**\n   * Create a specific owned space on the server via host delegation.\n   * Used by manifest registry setup for the account space.\n   */\n  async hostOwnedSpace(spaceId: string): Promise<boolean> {\n    return this.hostSpace(spaceId);\n  }\n\n  /**\n   * Ensure the user's space exists on the TinyCloud server.\n   * Creates the space if it doesn't exist and autoCreateSpace is enabled.\n   * If autoCreateSpace is false and space doesn't exist, silently returns\n   * (user may be using delegations to access other spaces).\n   *\n   * @throws Error if space creation fails\n   */\n  async ensureSpaceExists(): Promise<void> {\n    if (!this._tinyCloudSession) {\n      throw new Error(\"Must be signed in to ensure space exists\");\n    }\n\n    await this.ensureTinyCloudHosts();\n    const host = this.primaryTinyCloudHost;\n    const primarySpaceId = this._tinyCloudSession.spaceId;\n\n    // Try to activate the session\n    const result = await activateSessionWithHost(\n      host,\n      this._tinyCloudSession.delegationHeader,\n    );\n    this.recordActivationSkippedSpaces(result, primarySpaceId);\n\n    // Determine the effective space creation handler:\n    // 1. Explicit spaceCreationHandler takes precedence\n    // 2. autoCreateSpace: true uses AutoApproveSpaceCreationHandler\n    // 3. Otherwise, no handler (space creation skipped silently)\n    const handler: ISpaceCreationHandler | undefined =\n      this.spaceCreationHandler ??\n      (this.autoCreateSpace\n        ? new AutoApproveSpaceCreationHandler()\n        : undefined);\n\n    const creationContext = {\n      spaceId: primarySpaceId,\n      address: this._address!,\n      chainId: this._chainId!,\n      host,\n    };\n\n    if (result.success) {\n      // Check if primary space was actually activated or just skipped\n      const primarySkipped = result.skipped?.includes(primarySpaceId);\n\n      if (!primarySkipped) {\n        // Primary space exists and session is activated\n        return;\n      }\n\n      // Primary space was skipped (doesn't exist yet)\n      if (!handler) {\n        return;\n      }\n\n      const confirmed = await handler.confirmSpaceCreation(creationContext);\n      if (!confirmed) {\n        return;\n      }\n\n      // Create the primary space\n      try {\n        const created = await this.hostSpace();\n        if (!created) {\n          const err = new Error(`Failed to create space: ${primarySpaceId}`);\n          handler.onSpaceCreationFailed?.(creationContext, err);\n          throw err;\n        }\n      } catch (error) {\n        handler.onSpaceCreationFailed?.(\n          creationContext,\n          error instanceof Error ? error : new Error(String(error)),\n        );\n        throw error;\n      }\n\n      // Small delay to allow space creation to propagate\n      await new Promise((resolve) => setTimeout(resolve, 100));\n\n      // Retry activation\n      const retryResult = await activateSessionWithHost(\n        host,\n        this._tinyCloudSession.delegationHeader,\n      );\n\n      if (!retryResult.success) {\n        const err = new Error(\n          `Failed to activate session after creating space: ${retryResult.error}`,\n        );\n        handler.onSpaceCreationFailed?.(creationContext, err);\n        throw err;\n      }\n\n      handler.onSpaceCreated?.(creationContext);\n      return;\n    }\n\n    // Handle 404 (backwards compat with older servers)\n    if (result.status === 404) {\n      if (!handler) {\n        return;\n      }\n\n      const confirmed = await handler.confirmSpaceCreation(creationContext);\n      if (!confirmed) {\n        return;\n      }\n\n      try {\n        const created = await this.hostSpace();\n        if (!created) {\n          const err = new Error(`Failed to create space: ${primarySpaceId}`);\n          handler.onSpaceCreationFailed?.(creationContext, err);\n          throw err;\n        }\n      } catch (error) {\n        handler.onSpaceCreationFailed?.(\n          creationContext,\n          error instanceof Error ? error : new Error(String(error)),\n        );\n        throw error;\n      }\n\n      await new Promise((resolve) => setTimeout(resolve, 100));\n\n      const retryResult = await activateSessionWithHost(\n        host,\n        this._tinyCloudSession.delegationHeader,\n      );\n\n      if (!retryResult.success) {\n        const err = new Error(\n          `Failed to activate session after creating space: ${retryResult.error}`,\n        );\n        handler.onSpaceCreationFailed?.(creationContext, err);\n        throw err;\n      }\n\n      handler.onSpaceCreated?.(creationContext);\n      return;\n    }\n\n    throw new Error(`Failed to activate session: ${result.error}`);\n  }\n\n  private recordActivationSkippedSpaces(\n    result: SpaceHostResult,\n    primarySpaceId: string,\n  ): void {\n    if (result.success) {\n      this._lastActivationSkippedSpaceIds = result.skipped ?? [];\n      return;\n    }\n    this._lastActivationSkippedSpaceIds = result.status === 404\n      ? [primarySpaceId]\n      : [];\n  }\n\n  async createBootstrapSession(\n    options: CreateBootstrapSessionOptions,\n  ): Promise<TinyCloudSession> {\n    if (!this._address || !this._chainId) {\n      throw new Error(\"Must be signed in before creating bootstrap sessions\");\n    }\n\n    const address = this._address;\n    const chainId = this._chainId;\n    const keyId = `bootstrap-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n    this.sessionManager.createSessionKey(keyId);\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create bootstrap session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n    const abilities = resourceCapabilitiesToAbilitiesMap(\n      options.capabilityRequest.resources,\n    );\n    const prepared = this.wasm.prepareSession({\n      abilities,\n      ...(options.rawAbilities !== undefined\n        ? { rawAbilities: options.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: options.spaceId,\n      jwk,\n      ...this.buildSiweOverrides(),\n    });\n    const signature = await this.requestSignature({\n      address,\n      chainId,\n      message: prepared.siwe,\n      type: \"siwe\",\n    });\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    return {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId: options.spaceId,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n  }\n\n  /**\n   * Sign in and create a new session.\n   *\n   * This follows the correct SIWE-ReCap flow:\n   * 1. Create session key and get JWK\n   * 2. Call prepareSession() which generates the SIWE with ReCap capabilities\n   * 3. Sign the SIWE string from prepareSession\n   * 4. Call completeSessionSetup() with the prepared session + signature\n   *\n   * @param options - Optional per-call SIWE overrides for this sign-in only\n   */\n  async signIn(options?: SignInOptions): Promise<ClientSession> {\n    // Get signer address and chain ID\n    this._address = canonicalizeAddress(await this.signer.getAddress());\n    this._chainId = await this.signer.getChainId();\n\n    const address = this._address;\n    const chainId = this._chainId;\n\n    await this.resolveTinyCloudHostsForSignIn(address, chainId);\n\n    // Create a session key\n    const keyId = `session-${Date.now()}`;\n    this.sessionManager.renameSessionKeyId(\"default\", keyId);\n\n    // Get JWK for session key\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n\n    const capabilityPlan = this.resolveSignInCapabilities(address, chainId);\n    const spaceId = capabilityPlan.spaceId;\n\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n\n    // Prepare session - this creates the SIWE message with ReCap capabilities.\n    //\n    // When a manifest is installed, `resolveSignInAbilities()` returns\n    // the union of app permissions + every manifest-declared\n    // delegation's permissions in the shape `prepareSession` accepts.\n    // Otherwise it returns `defaultActions` unchanged (legacy path).\n    const prepared = this.wasm.prepareSession({\n      abilities: capabilityPlan.abilities,\n      ...(capabilityPlan.spaceAbilities !== undefined\n        ? { spaceAbilities: capabilityPlan.spaceAbilities }\n        : {}),\n      ...(capabilityPlan.rawAbilities !== undefined\n        ? { rawAbilities: capabilityPlan.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId,\n      jwk,\n      ...this.buildSiweOverrides(options),\n    });\n\n    // Sign the SIWE message from prepareSession (NOT a separately generated SIWE)\n    const signature = await this.requestSignature({\n      address,\n      chainId,\n      message: prepared.siwe,\n      type: \"siwe\",\n    });\n\n    // Complete session setup with the prepared session + signature\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Create client session (web-core compatible)\n    const clientSession: ClientSession = {\n      address,\n      walletAddress: address,\n      chainId,\n      sessionKey: keyId,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Compute additional spaces as metadata (not in the delegation itself).\n    // The public space delegation is created lazily via ensurePublicSpace(),\n    // not at signIn time, to avoid creating spaces the user may never use.\n    const spacesMetadata: Record<string, string> | undefined = this\n      .enablePublicSpace\n      ? { public: makePkhSpaceId(address, chainId, \"public\") }\n      : undefined;\n\n    // Create TinyCloud session with full delegation data\n    // Use sessionManager.getDID(keyId) for verificationMethod to get properly formatted DID URL\n    // The prepared.verificationMethod from Rust WASM has a bug that doubles the DID fragment\n    const tinyCloudSession: TinyCloudSession = {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId,\n      spaces: spacesMetadata,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Persist session with TinyCloud-specific data\n    const persistedData: PersistedSessionData = {\n      address,\n      chainId,\n      sessionKey: JSON.stringify(jwk),\n      siwe: prepared.siwe,\n      signature,\n      tinycloudSession: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId,\n        spaces: spacesMetadata,\n        verificationMethod: this.sessionManager.getDID(keyId),\n      },\n      expiresAt: expirationTime.toISOString(),\n      createdAt: now.toISOString(),\n      version: \"1.0\",\n      tinycloudHosts: this.tinycloudHosts,\n    };\n    await this.sessionStorage.save(address, persistedData);\n\n    // Set current session\n    this._session = clientSession;\n    this._tinyCloudSession = tinyCloudSession;\n    this._address = address;\n    this._chainId = chainId;\n\n    // Verify SDK-node protocol compatibility and discover supported features\n    const nodeInfo = await checkNodeInfo(\n      this.primaryTinyCloudHost,\n      this.wasm.protocolVersion(),\n    );\n    this._nodeFeatures = nodeInfo.features;\n\n    // Call extension hooks\n    for (const ext of this.extensions) {\n      if (ext.afterSignIn) {\n        await ext.afterSignIn(clientSession);\n      }\n    }\n\n    // Ensure space exists (creates if needed when autoCreateSpace is true)\n    await this.ensureSpaceExists();\n\n    return clientSession;\n  }\n\n  /**\n   * Sign out and clear the current session.\n   */\n  async signOut(): Promise<void> {\n    if (this._address) {\n      await this.clearPersistedSession(this._address);\n    }\n    this._session = undefined;\n  }\n\n  /**\n   * Get the current wallet/signer address.\n   */\n  address(): string | undefined {\n    return this._address;\n  }\n\n  /**\n   * Get the current chain ID.\n   */\n  chainId(): number | undefined {\n    return this._chainId;\n  }\n\n  /**\n   * Sign a message with the connected signer.\n   */\n  async signMessage(message: string): Promise<string> {\n    if (!this._address) {\n      this._address = canonicalizeAddress(await this.signer.getAddress());\n    }\n    if (!this._chainId) {\n      this._chainId = await this.signer.getChainId();\n    }\n\n    return this.requestSignature({\n      address: this._address,\n      chainId: this._chainId,\n      message,\n      type: \"message\",\n    });\n  }\n\n  /**\n   * Prepare a session for external signing.\n   *\n   * Use this method when you need to sign the SIWE message externally (e.g., via\n   * a hardware wallet, multi-sig, or external service). After obtaining the signature,\n   * call `signInWithPreparedSession()` to complete the sign-in.\n   *\n   * @example\n   * ```typescript\n   * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();\n   * const signature = await externalSigner.signMessage(prepared.siwe);\n   * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);\n   * ```\n   */\n  async prepareSessionForSigning(): Promise<{\n    prepared: {\n      siwe: string;\n      jwk: Record<string, unknown>;\n      spaceId: string;\n      verificationMethod: string;\n    };\n    keyId: string;\n    jwk: Record<string, unknown>;\n    address: string;\n    chainId: number;\n  }> {\n    const address = canonicalizeAddress(await this.signer.getAddress());\n    const chainId = await this.signer.getChainId();\n\n    // Create a session key\n    const keyId = `session-${Date.now()}`;\n    this.sessionManager.renameSessionKeyId(\"default\", keyId);\n\n    // Get JWK for session key\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n\n    const capabilityPlan = this.resolveSignInCapabilities(address, chainId);\n    const spaceId = capabilityPlan.spaceId;\n\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n\n    // Prepare session - this creates the SIWE message with ReCap capabilities.\n    //\n    // When a manifest is installed, `resolveSignInAbilities()` returns\n    // the union of app permissions + every manifest-declared\n    // delegation's permissions in the shape `prepareSession` accepts.\n    // Otherwise it returns `defaultActions` unchanged (legacy path).\n    const prepared = this.wasm.prepareSession({\n      abilities: capabilityPlan.abilities,\n      ...(capabilityPlan.spaceAbilities !== undefined\n        ? { spaceAbilities: capabilityPlan.spaceAbilities }\n        : {}),\n      ...(capabilityPlan.rawAbilities !== undefined\n        ? { rawAbilities: capabilityPlan.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId,\n      jwk,\n      ...this.buildSiweOverrides(),\n    });\n\n    return {\n      prepared,\n      keyId,\n      jwk,\n      address,\n      chainId,\n    };\n  }\n\n  /**\n   * Complete sign-in with a prepared session and signature.\n   *\n   * Use this method after obtaining a signature for the SIWE message from\n   * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.\n   *\n   * @param prepared - The prepared session from `prepareSessionForSigning()`\n   * @param signature - The signature over `prepared.siwe`\n   * @param keyId - The session key ID from `prepareSessionForSigning()`\n   * @param jwk - The JWK from `prepareSessionForSigning()`\n   */\n  async signInWithPreparedSession(\n    prepared: {\n      siwe: string;\n      jwk: Record<string, unknown>;\n      spaceId: string;\n      verificationMethod: string;\n    },\n    signature: string,\n    keyId: string,\n    jwk: Record<string, unknown>,\n  ): Promise<ClientSession> {\n    // Complete session setup with the prepared session + signature\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Parse address and chainId from the prepared session\n    // The SIWE message contains this info, but we need to extract it\n    // For now, we'll get it from the signer since it should match\n    const address = canonicalizeAddress(await this.signer.getAddress());\n    const chainId = await this.signer.getChainId();\n\n    await this.resolveTinyCloudHostsForSignIn(address, chainId);\n\n    // Create client session (web-core compatible)\n    const clientSession: ClientSession = {\n      address,\n      walletAddress: address,\n      chainId,\n      sessionKey: keyId,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Compute additional spaces as metadata (not in the delegation itself).\n    const spacesMetadata: Record<string, string> | undefined = this\n      .enablePublicSpace\n      ? { public: makePkhSpaceId(address, chainId, \"public\") }\n      : undefined;\n\n    // Create TinyCloud session with full delegation data\n    // Use sessionManager.getDID(keyId) for properly formatted DID URL\n    const tinyCloudSession: TinyCloudSession = {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId: prepared.spaceId,\n      spaces: spacesMetadata,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Extract expiration from SIWE message (parse the string)\n    const expirationMatch = prepared.siwe.match(/Expiration Time: (.+)/);\n    const issuedAtMatch = prepared.siwe.match(/Issued At: (.+)/);\n    const expiresAt =\n      expirationMatch?.[1] ??\n      new Date(Date.now() + this.sessionExpirationMs).toISOString();\n    const createdAt = issuedAtMatch?.[1] ?? new Date().toISOString();\n\n    // Persist session with TinyCloud-specific data\n    const persistedData: PersistedSessionData = {\n      address,\n      chainId,\n      sessionKey: JSON.stringify(jwk),\n      siwe: prepared.siwe,\n      signature,\n      tinycloudSession: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: prepared.spaceId,\n        spaces: spacesMetadata,\n        verificationMethod: this.sessionManager.getDID(keyId),\n      },\n      expiresAt,\n      createdAt,\n      version: \"1.0\",\n      tinycloudHosts: this.tinycloudHosts,\n    };\n    await this.sessionStorage.save(address, persistedData);\n\n    // Set current session\n    this._session = clientSession;\n    this._tinyCloudSession = tinyCloudSession;\n    this._address = address;\n    this._chainId = chainId;\n\n    // Verify SDK-node protocol compatibility and discover supported features\n    const nodeInfo = await checkNodeInfo(\n      this.primaryTinyCloudHost,\n      this.wasm.protocolVersion(),\n    );\n    this._nodeFeatures = nodeInfo.features;\n\n    // Call extension hooks\n    for (const ext of this.extensions) {\n      if (ext.afterSignIn) {\n        await ext.afterSignIn(clientSession);\n      }\n    }\n\n    // Ensure space exists (creates if needed when autoCreateSpace is true)\n    await this.ensureSpaceExists();\n\n    return clientSession;\n  }\n\n  /**\n   * Clear persisted session data.\n   */\n  async clearPersistedSession(address?: string): Promise<void> {\n    const targetAddress = address ?? this._address;\n    if (targetAddress) {\n      await this.sessionStorage.clear(targetAddress);\n    }\n  }\n\n  /**\n   * Check if a session is persisted for an address.\n   */\n  isSessionPersisted(address: string): boolean {\n    return this.sessionStorage.exists(address);\n  }\n\n  /**\n   * Request a signature based on the configured strategy.\n   */\n  private async requestSignature(request: SignRequest): Promise<string> {\n    switch (this.signStrategy.type) {\n      case \"auto-sign\":\n        return this.signer.signMessage(request.message);\n\n      case \"auto-reject\":\n        throw new Error(\"Sign request rejected by auto-reject strategy\");\n\n      case \"callback\": {\n        const response = await this.signStrategy.handler(request);\n        if (!response.approved) {\n          throw new Error(\n            response.reason ?? \"Sign request rejected by callback\",\n          );\n        }\n        // If callback provides signature, use it; otherwise sign with signer\n        return (\n          response.signature ?? (await this.signer.signMessage(request.message))\n        );\n      }\n\n      case \"event-emitter\": {\n        return this.requestSignatureViaEmitter(\n          request,\n          this.signStrategy.emitter,\n          this.signStrategy.timeout ?? 60000,\n        );\n      }\n\n      default:\n        throw new Error(\n          `Unknown sign strategy: ${(this.signStrategy as any).type}`,\n        );\n    }\n  }\n\n  /**\n   * Request signature via event emitter with timeout.\n   */\n  private requestSignatureViaEmitter(\n    request: SignRequest,\n    emitter: EventEmitter,\n    timeout: number,\n  ): Promise<string> {\n    return new Promise((resolve, reject) => {\n      const timeoutId = setTimeout(() => {\n        reject(new Error(\"Sign request timed out\"));\n      }, timeout);\n\n      const respond = async (response: SignResponse) => {\n        clearTimeout(timeoutId);\n        if (!response.approved) {\n          reject(\n            new Error(response.reason ?? \"Sign request rejected via emitter\"),\n          );\n        } else {\n          // If response provides signature, use it; otherwise sign with signer\n          const signature =\n            response.signature ??\n            (await this.signer.signMessage(request.message));\n          resolve(signature);\n        }\n      };\n\n      emitter.emit(\"sign-request\", request, respond);\n    });\n  }\n}\n","/**\n * Node.js-specific SignStrategy types for TinyCloud authorization.\n *\n * This module re-exports common types from sdk-core and provides\n * Node.js-specific implementations (e.g., NodeEventEmitterStrategy\n * using Node's EventEmitter instead of browser EventTarget).\n *\n * @packageDocumentation\n */\n\nimport { EventEmitter } from \"events\";\n\n// Import types for local use in SignStrategy union\nimport type {\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export common types from sdk-core (type-only — erased at runtime in sdk-core dist)\nexport type {\n  SignRequest,\n  SignResponse,\n  SignCallback,\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n  OpenKeySigningStrategyOptions,\n  OpenKeySigningRequestBody,\n  OpenKeySigningResponseBody,\n  OpenKeyCallbackStrategy,\n} from \"@tinycloud/sdk-core\";\n\nexport { createOpenKeyCallbackSigningStrategy } from \"@tinycloud/sdk-core\";\n\n/**\n * Node.js event emitter strategy: emits sign requests as events.\n *\n * Uses Node.js EventEmitter for compatibility with Node.js applications.\n * For browser environments, use the EventEmitterStrategy from sdk-core\n * which uses EventTarget.\n *\n * Events emitted:\n * - 'sign-request': When a sign request is received\n *\n * Use cases:\n * - Async approval workflows in Node.js\n * - External signing services\n * - Multi-step authorization flows\n *\n * @example\n * ```typescript\n * const emitter = new EventEmitter();\n * const strategy: NodeEventEmitterStrategy = { type: 'event-emitter', emitter };\n *\n * emitter.on('sign-request', async (req, respond) => {\n *   const approved = await externalApprovalService.check(req);\n *   respond({ approved, signature: approved ? await sign(req.message) : undefined });\n * });\n * ```\n */\nexport interface NodeEventEmitterStrategy {\n  type: \"event-emitter\";\n  emitter: EventEmitter;\n  /** Timeout in milliseconds for waiting on event response (default: 60000) */\n  timeout?: number;\n}\n\n/**\n * Node.js sign strategy union type.\n *\n * Determines how sign requests are handled in NodeUserAuthorization.\n * Uses Node.js EventEmitter for the event-emitter strategy.\n */\nexport type SignStrategy =\n  | AutoSignStrategy\n  | AutoRejectStrategy\n  | CallbackStrategy\n  | NodeEventEmitterStrategy;\n\n/**\n * Default sign strategy is auto-sign for convenience.\n * This is the Node.js-specific version typed with SignStrategy.\n */\nexport const defaultSignStrategy: SignStrategy = { type: \"auto-sign\" };\n","/**\n * TinyCloudNode - High-level API for Node.js users.\n *\n * Each user has their own TinyCloudNode instance with their own key.\n * This class provides a simplified interface for:\n * - Signing in and managing sessions\n * - Key-value storage operations on own space\n * - Creating and using delegations\n *\n * @example\n * ```typescript\n * const alice = new TinyCloudNode({\n *   privateKey: process.env.ALICE_PRIVATE_KEY,\n *   host: \"https://node.tinycloud.xyz\",\n *   prefix: \"myapp\",\n * });\n *\n * await alice.signIn();\n * await alice.kv.put(\"greeting\", \"Hello, world!\");\n *\n * // Delegate access to Bob\n * const delegation = await alice.createDelegation({\n *   path: \"shared/\",\n *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n *   delegateDID: bob.did,\n * });\n *\n * // Bob uses the delegation\n * const access = await bob.useDelegation(delegation);\n * const data = await access.kv.get(\"shared/data\");\n * ```\n */\n\nimport {\n  TinyCloud,\n  TinyCloudSession,\n  activateSessionWithHost,\n  KVService,\n  IKVService,\n  SQLService,\n  ISQLService,\n  DuckDbService,\n  IDuckDbService,\n  HooksService,\n  DataVaultService,\n  IDataVaultService,\n  EncryptionService,\n  SecretsService,\n  ISecretsService,\n  IEncryptionService,\n  IHooksService,\n  createVaultCrypto,\n  ServiceSession,\n  ServiceContext,\n  type TelemetryConfig,\n  ISessionStorage,\n  ISigner,\n  type InvokeAnyFunction,\n  type InvokeFunction,\n  INotificationHandler,\n  SilentNotificationHandler,\n  IENSResolver,\n  IWasmBindings,\n  ISessionManager,\n  ISpaceCreationHandler,\n  SignInOptions,\n  // v2 services\n  DelegationManager,\n  SpaceService,\n  ISpaceService,\n  ISpace,\n  CapabilityKeyRegistry,\n  ICapabilityKeyRegistry,\n  SharingService,\n  ISharingService,\n  // v2 types\n  SiweConfig,\n  Delegation,\n  CreateDelegationParams,\n  KeyInfo,\n  JWK,\n  DelegationResult,\n  CreateDelegationWasmParams,\n  CreateDelegationWasmResult,\n  type DelegatedResource,\n  UnsupportedFeatureError,\n  makePublicSpaceId,\n  ACCOUNT_REGISTRY_SPACE,\n  BOOTSTRAP_SESSION_REQUESTS,\n  SECRET_RECORDS_SCHEMA,\n  SECRETS_SPACE,\n  TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,\n  bootstrapSteps,\n  type BootstrapSpaceName,\n  type BootstrapStep,\n  type ComposedManifestRequest,\n  type ResolvedDelegate,\n  // Capability-chain delegation\n  type PermissionEntry,\n  ENCRYPTION_PERMISSION_SERVICE,\n  PermissionNotInManifestError,\n  SessionExpiredError,\n  expandPermissionEntries as expandPermissionEntriesCore,\n  isCapabilitySubset,\n  parseRecapCapabilities,\n  // Manifest-driven sign-in\n  type Manifest,\n  type AbilitiesMap,\n  resourceCapabilitiesToAbilitiesMap,\n  SERVICE_LONG_TO_SHORT,\n  EXPIRY,\n  canonicalHashHex,\n  canonicalizeEncryptionJson,\n  verifyDidKeyEd25519Signature,\n  canonicalizeAddress,\n  pkhDid,\n  resolveTinyCloudHosts,\n  principalDidEquals,\n  parseNetworkId,\n  type BuildDecryptInvocationInput,\n  type BuiltDecryptInvocation,\n  type CanonicalJson,\n  type DecryptResponseBody,\n  type DecryptTransport,\n  type EncryptionCrypto,\n  type NetworkDescriptor,\n} from \"@tinycloud/sdk-core\";\nimport { NodeUserAuthorization } from \"./authorization/NodeUserAuthorization\";\nimport type { SignStrategy } from \"./authorization/strategies\";\nimport { AccountService } from \"./account/AccountService\";\nimport { FileSessionStorage } from \"./storage/FileSessionStorage\";\nimport { MemorySessionStorage } from \"./storage/MemorySessionStorage\";\nimport { PortableDelegation } from \"./delegation\";\nimport { DelegatedAccess } from \"./DelegatedAccess\";\nimport { WasmKeyProvider } from \"./keys/WasmKeyProvider\";\nimport {\n  legacyParamsToPermissionEntries,\n  resolveExpiryMs,\n  extractSiweExpiration,\n} from \"./delegateToHelpers\";\nimport { NodeSecretsService } from \"./NodeSecretsService\";\n\n/** Default TinyCloud host */\nconst DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nconst DEFAULT_ENCRYPTION_NETWORK_NAME = \"default\";\nconst NETWORK_CREATE_ACTION = \"tinycloud.encryption/network.create\";\nconst DECRYPT_ACTION = \"tinycloud.encryption/decrypt\";\nconst NETWORK_ADMIN_TYPE = \"tinycloud.encryption.network-admin/v1\";\n\n/**\n * Default lifetime of a SIWE session when {@link TinyCloudNodeConfig.sessionExpirationMs}\n * is not set. Sourced from the shared SESSION tier so all sign-in code\n * paths land on the same number — see `@tinycloud/sdk-core/expiry.ts`\n * for the tier rationale.\n */\nconst DEFAULT_SESSION_EXPIRATION_MS = EXPIRY.SESSION_MS;\n\nfunction isOpenKeyAutoSignStrategy(strategy: SignStrategy | undefined): boolean {\n  return (strategy as { openKeyAutoSign?: unknown } | undefined)?.openKeyAutoSign === true;\n}\n\nfunction didPrincipalMatches(actual: string, expected: string): boolean {\n  try {\n    return principalDidEquals(actual, expected);\n  } catch {\n    return actual === expected;\n  }\n}\n\n/**\n * Configuration for TinyCloudNode.\n * All fields are optional - TinyCloudNode can work with zero configuration.\n */\nexport interface TinyCloudNodeConfig {\n  /** Hex-encoded private key (with or without 0x prefix). Optional - only needed for wallet mode and signIn() */\n  privateKey?: string;\n  /** Custom signer implementation. If provided, takes precedence over privateKey. */\n  signer?: ISigner;\n  /** Strategy for root signature requests. Defaults to auto-sign for local keys. */\n  signStrategy?: SignStrategy;\n  /** Explicit TinyCloud server URL. When omitted, signIn resolves the user's host. */\n  host?: string;\n  /** TinyCloud location registry URL. Default: https://registry.tinycloud.xyz. */\n  tinycloudRegistryUrl?: string | null;\n  /** Fallback TinyCloud hosts. Default: hosted TinyCloud node. */\n  tinycloudFallbackHosts?: string[] | null;\n  /** Space prefix for this user's space. Optional - only needed for signIn() */\n  prefix?: string;\n  /** Domain for SIWE messages (default: derived from host) */\n  domain?: string;\n  /** Session expiration time in milliseconds (default: 1 hour) */\n  sessionExpirationMs?: number;\n  /** Whether to automatically create space if it doesn't exist (default: false) */\n  autoCreateSpace?: boolean;\n  /** Custom session storage implementation (default: MemorySessionStorage) */\n  sessionStorage?: ISessionStorage;\n  /** Whether to include public space capabilities in the session (default: true).\n   * When true, signIn() automatically includes capabilities for the user's public space,\n   * accessible via spaces.get('public').kv */\n  enablePublicSpace?: boolean;\n  /** Custom WASM bindings (default: @tinycloud/node-sdk-wasm). Used by browser wrapper. */\n  wasmBindings?: IWasmBindings;\n  /** Notification handler for sign-in/sign-out/error events (default: SilentNotificationHandler) */\n  notificationHandler?: INotificationHandler;\n  /** ENS resolver for resolving .eth names in delegation methods */\n  ensResolver?: IENSResolver;\n  /** Custom space creation handler (default: auto-approve when autoCreateSpace is true) */\n  spaceCreationHandler?: ISpaceCreationHandler;\n  /**\n   * SIWE nonce override. If omitted, the WASM layer generates a random nonce.\n   * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.\n   */\n  nonce?: string;\n  /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */\n  siweConfig?: SiweConfig;\n  /**\n   * App manifest driving the SIWE recap at sign-in.\n   *\n   * When set, `signIn()` resolves the manifest, unions the app's own\n   * permissions with every manifest-declared delegation's permissions,\n   * and uses that union as the session's granted capabilities — NOT\n   * the legacy `defaultActions` table. This is what makes\n   * `delegateTo(manifestDeclaredDid, permissions)` work without a\n   * wallet prompt: the session key's recap already covers the\n   * delegation target's needs at sign-in time.\n   *\n   * When omitted, `signIn()` falls back to `defaultActions` for\n   * backwards compatibility with callers that pre-date the manifest\n   * flow.\n   */\n  manifest?: Manifest | Manifest[];\n  /** Pre-composed manifest request. Takes precedence over `manifest`. */\n  capabilityRequest?: ComposedManifestRequest;\n  /** Include implicit account registry permissions when composing `manifest`. Default true. */\n  includeAccountRegistryPermissions?: boolean;\n  /** Run canonical first-account bootstrap when fresh account state is detected. Default true. */\n  autoBootstrapAccount?: boolean;\n  /** Default-off service telemetry. */\n  telemetry?: TelemetryConfig;\n}\n\n/**\n * Options for {@link TinyCloudNode.delegateTo}.\n *\n * `expiry` accepts either an ms-format duration string (e.g. `\"7d\"`, `\"1h\"`)\n * or a raw number of milliseconds. When omitted, the default is 1 hour.\n *\n * `forceWalletSign` bypasses the derivability check and sends the\n * delegation through the legacy wallet-signed SIWE path, which always\n * triggers a wallet prompt. Used for testing, for explicit wallet\n * confirmation flows, and by the legacy `createDelegation` fallback.\n */\nexport interface DelegateToOptions {\n  /** Override expiry. ms-format string (\"7d\", \"1h\") or raw milliseconds. */\n  expiry?: string | number;\n  /** Force the wallet-signed SIWE path even if the caps are derivable. Default false. */\n  forceWalletSign?: boolean;\n}\n\n/**\n * Result of {@link TinyCloudNode.delegateTo}.\n *\n * `prompted` indicates whether a wallet prompt was shown — `true` for the\n * legacy wallet path (always), `false` for the session-key UCAN path (never).\n * Callers wiring single-prompt sign-in flows use this to assert that their\n * capability chain was derivable.\n */\nexport interface DelegateToResult {\n  delegation: PortableDelegation;\n  prompted: boolean;\n}\n\n/**\n * Options for runtime permission escalation.\n */\nexport interface RuntimePermissionGrantOptions {\n  /** Override expiry. ms-format string (\"7d\", \"1h\") or raw milliseconds. */\n  expiry?: string | number;\n}\n\ninterface RuntimePermissionOperation {\n  spaceId?: string;\n  resource?: string;\n  service: string;\n  path: string;\n  action: string;\n}\n\ninterface RuntimePermissionGrant {\n  session: ServiceSession;\n  delegation: PortableDelegation;\n  operations: RuntimePermissionOperation[];\n  expiresAt: Date;\n}\n\ntype CanonicalizableEncryptionJson = CanonicalJson;\ntype NetworkInvocationFact = object;\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n  const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n  let output = \"\";\n  for (let i = 0; i < bytes.length; i += 3) {\n    const a = bytes[i];\n    const b = bytes[i + 1];\n    const c = bytes[i + 2];\n    const triplet = (a << 16) | ((b ?? 0) << 8) | (c ?? 0);\n    output += alphabet[(triplet >> 18) & 63];\n    output += alphabet[(triplet >> 12) & 63];\n    if (i + 1 < bytes.length) output += alphabet[(triplet >> 6) & 63];\n    if (i + 2 < bytes.length) output += alphabet[triplet & 63];\n  }\n  return output;\n}\n\nfunction base64UrlDecode(value: string): Uint8Array {\n  const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n  const bytes: number[] = [];\n  let buffer = 0;\n  let bits = 0;\n  for (const char of value) {\n    const index = alphabet.indexOf(char);\n    if (index < 0) {\n      throw new Error(\"invalid base64url input\");\n    }\n    buffer = (buffer << 6) | index;\n    bits += 6;\n    if (bits >= 8) {\n      bits -= 8;\n      bytes.push((buffer >> bits) & 0xff);\n    }\n  }\n  return new Uint8Array(bytes);\n}\n\nasync function signJwtInputWithJwk(\n  signingInput: string,\n  jwk: object,\n): Promise<Uint8Array> {\n  const bytes = new TextEncoder().encode(signingInput);\n  try {\n    const subtle = globalThis.crypto?.subtle;\n    if (!subtle) {\n      throw new Error(\"WebCrypto subtle API is unavailable\");\n    }\n    const key = await subtle.importKey(\n      \"jwk\",\n      jwk as any,\n      { name: \"Ed25519\" },\n      false,\n      [\"sign\"],\n    );\n    return new Uint8Array(await subtle.sign({ name: \"Ed25519\" }, key, bytes));\n  } catch {\n    const nodeCrypto = await import(\"node:crypto\");\n    const key = nodeCrypto.createPrivateKey({ key: jwk as any, format: \"jwk\" });\n    return new Uint8Array(nodeCrypto.sign(null, Buffer.from(bytes), key));\n  }\n}\n\nasync function rewriteInvocationAudience(\n  authorization: string,\n  audience: string,\n  jwk: object,\n): Promise<string> {\n  const [headerPart, payloadPart] = authorization.split(\".\");\n  if (!headerPart || !payloadPart) {\n    throw new Error(\"invalid invocation authorization\");\n  }\n  const header = JSON.parse(new TextDecoder().decode(base64UrlDecode(headerPart)));\n  const payload = JSON.parse(new TextDecoder().decode(base64UrlDecode(payloadPart)));\n  payload.aud = audience;\n  const signingInput = `${base64UrlEncode(\n    new TextEncoder().encode(JSON.stringify(header)),\n  )}.${base64UrlEncode(new TextEncoder().encode(JSON.stringify(payload)))}`;\n  const signature = await signJwtInputWithJwk(signingInput, jwk);\n  return `${signingInput}.${base64UrlEncode(signature)}`;\n}\n\nfunction authorizationHeader(headers: Record<string, string> | [string, string][]): string {\n  if (Array.isArray(headers)) {\n    const entry = headers.find(([name]) => name.toLowerCase() === \"authorization\");\n    if (!entry) {\n      throw new Error(\"network invocation did not include an Authorization header\");\n    }\n    return entry[1];\n  }\n  const value = headers.Authorization ?? headers.authorization;\n  if (!value) {\n    throw new Error(\"network invocation did not include an Authorization header\");\n  }\n  return value;\n}\n\n/**\n * High-level TinyCloud API for Node.js environments.\n *\n * Each user creates their own TinyCloudNode instance with their private key.\n * The instance manages the user's session and provides access to their space.\n */\n/** @internal */\nexport interface NodeDefaults {\n  createWasmBindings: () => IWasmBindings;\n  createSigner: (privateKey: string, chainId?: number) => ISigner;\n}\n\nexport class TinyCloudNode {\n  /** @internal Registered by importing @tinycloud/node-sdk (not /core) */\n  private static nodeDefaults?: NodeDefaults;\n\n  /** @internal Register Node.js-specific defaults (NodeWasmBindings, PrivateKeySigner) */\n  static registerNodeDefaults(defaults: NodeDefaults): void {\n    TinyCloudNode.nodeDefaults = defaults;\n  }\n\n  private config: TinyCloudNodeConfig;\n  private readonly explicitHost?: string;\n  private signer: ISigner | null = null;\n  private auth: NodeUserAuthorization | null = null;\n  private tc: TinyCloud | null = null;\n  private _address?: string;\n  private _chainId: number = 1;\n  private wasmBindings: IWasmBindings;\n  private sessionManager: ISessionManager;\n  private _serviceContext?: ServiceContext;\n  private _kv?: KVService;\n  private _sql?: SQLService;\n  private _duckdb?: DuckDbService;\n  private _hooks?: HooksService;\n  private _vault?: DataVaultService;\n  private _encryption?: EncryptionService;\n  private _baseSecrets?: ISecretsService;\n  private _secrets?: ISecretsService;\n  private _account?: AccountService;\n  /** Cached public KV with proper delegation (set by ensurePublicSpace) */\n  private _publicKV?: KVService;\n\n  /** Session key ID - always available */\n  private sessionKeyId: string;\n  /** Session key JWK as object - always available */\n  private sessionKeyJwk: object;\n\n  /** Notification handler for user-facing events */\n  private notificationHandler: INotificationHandler;\n\n  // v2 services (initialized in constructor)\n  private _capabilityRegistry: CapabilityKeyRegistry;\n  private _keyProvider: WasmKeyProvider;\n  private _sharingService: SharingService;\n  // These are initialized after signIn()\n  private _delegationManager?: DelegationManager;\n  private _spaceService?: SpaceService;\n  private runtimePermissionGrants: RuntimePermissionGrant[] = [];\n\n  /**\n   * TinyCloudSession captured by {@link restoreSession} when there's no\n   * auth-layer signer available (session-only mode used by OpenKey-backed\n   * CLI restores, public-space replays, …). Read by\n   * {@link currentTinyCloudSession} as a fallback for `auth.tinyCloudSession`.\n   */\n  private _restoredTcSession?: TinyCloudSession;\n\n  private get nodeFeatures(): string[] {\n    return this.auth?.nodeFeatures ?? [];\n  }\n\n  /** SIWE domain — uses config override or defaults to app.tinycloud.xyz */\n  private get siweDomain(): string {\n    return this.config.domain ?? 'app.tinycloud.xyz';\n  }\n\n  private readonly invokeWithRuntimePermissions: InvokeFunction = (\n    session,\n    service,\n    path,\n    action,\n    facts,\n  ) => {\n    return this.wasmBindings.invoke(\n      this.selectInvocationSession(session, service, path, action),\n      service,\n      path,\n      action,\n      facts,\n    );\n  };\n\n  private readonly invokeAnyWithRuntimePermissions: InvokeAnyFunction = (\n    session,\n    entries,\n    facts,\n  ) => {\n    if (!this.wasmBindings.invokeAny) {\n      throw new Error(\"WASM binding does not support invokeAny\");\n    }\n    const grant = this.findGrantForOperations(\n      entries.flatMap((entry) => {\n        const operation = this.operationFromInvokeAnyEntry(entry);\n        return operation ? [operation] : [];\n      }),\n    );\n    return this.wasmBindings.invokeAny(grant?.session ?? session, entries, facts);\n  };\n\n  /**\n   * Create a new TinyCloudNode instance.\n   *\n   * All configuration is optional. Without a privateKey, the instance operates\n   * in \"session-only\" mode where it can receive delegations but cannot create\n   * its own space via signIn().\n   *\n   * @param config - Configuration options (all optional)\n   *\n   * @example\n   * ```typescript\n   * // Session-only mode - can receive delegations\n   * const bob = new TinyCloudNode();\n   * console.log(bob.did); // did:key:z6Mk... - available immediately\n   *\n   * // Wallet mode - can create own space\n   * const alice = new TinyCloudNode({\n   *   privateKey: process.env.ALICE_PRIVATE_KEY,\n   *   prefix: \"myapp\",\n   * });\n   * await alice.signIn();\n   * ```\n   */\n  constructor(config: TinyCloudNodeConfig = {}) {\n    this.explicitHost = config.host;\n\n    // Store config with default host\n    this.config = {\n      ...config,\n      host: config.host ?? DEFAULT_HOST,\n    };\n\n    // Initialize WASM bindings (uses registered Node defaults if not provided)\n    if (config.wasmBindings) {\n      this.wasmBindings = config.wasmBindings;\n    } else if (TinyCloudNode.nodeDefaults) {\n      this.wasmBindings = TinyCloudNode.nodeDefaults.createWasmBindings();\n    } else {\n      throw new Error(\n        \"wasmBindings must be provided in config. \" +\n        \"Import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n      );\n    }\n\n    // Always create session manager and session key immediately\n    this.sessionManager = this.wasmBindings.createSessionManager();\n\n    // Try to use \"default\" key, create if it doesn't exist\n    const defaultKeyId = \"default\";\n    let jwkStr = this.sessionManager.jwk(defaultKeyId);\n    if (jwkStr) {\n      // Key already exists, reuse it\n      this.sessionKeyId = defaultKeyId;\n    } else {\n      // Create new key\n      this.sessionKeyId = this.sessionManager.createSessionKey(defaultKeyId);\n      jwkStr = this.sessionManager.jwk(this.sessionKeyId);\n    }\n\n    if (!jwkStr) {\n      throw new Error(\"Failed to get session key JWK\");\n    }\n    this.sessionKeyJwk = JSON.parse(jwkStr);\n\n    // Initialize capability registry for all users (needed for tracking received delegations)\n    this._capabilityRegistry = new CapabilityKeyRegistry();\n\n    // Initialize KeyProvider for SharingService\n    this._keyProvider = new WasmKeyProvider({\n      sessionManager: this.sessionManager,\n    });\n\n    // Initialize notification handler\n    this.notificationHandler = config.notificationHandler ?? new SilentNotificationHandler();\n\n    // Initialize SharingService for receive-only access (no session required)\n    // This allows session-only users to receive sharing links without signIn()\n    // Full capabilities (generate) are added after signIn()\n    this._sharingService = new SharingService({\n      hosts: [this.config.host!],\n      // session: undefined - not needed for receive()\n      invoke: this.invokeWithRuntimePermissions,\n      fetch: globalThis.fetch.bind(globalThis),\n      keyProvider: this._keyProvider,\n      registry: this._capabilityRegistry,\n      // delegationManager: undefined - not needed for receive()\n      createKVService: (config) => {\n        // Use pathPrefix as the KV service prefix for sharing links\n        // Strip trailing slash to match DelegatedAccess behavior\n        const prefix = config.pathPrefix?.replace(/\\/$/, '');\n        const kvService = new KVService({ prefix });\n        // Create a new service context for the KV service\n        const kvContext = new ServiceContext({\n          invoke: config.invoke,\n          fetch: config.fetch ?? globalThis.fetch.bind(globalThis),\n          hosts: config.hosts,\n          telemetry: this.config.telemetry,\n        });\n        kvContext.setSession(config.session);\n        kvService.initialize(kvContext);\n        return kvService;\n      },\n    });\n\n    // Set up wallet/auth if signer or privateKey is provided\n    if (config.signer) {\n      this.signer = config.signer;\n      this.setupAuth(config);\n    } else if (config.privateKey) {\n      if (!TinyCloudNode.nodeDefaults) {\n        throw new Error(\n          \"privateKey requires PrivateKeySigner. Either provide a signer in config, \" +\n          \"or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n        );\n      }\n      this.signer = TinyCloudNode.nodeDefaults.createSigner(config.privateKey, this._chainId);\n      this.setupAuth(config);\n    }\n  }\n\n  /**\n   * Set up authorization handler and TinyCloud instance.\n   * @internal\n   */\n  private setupAuth(config: TinyCloudNodeConfig): void {\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(config);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer!,\n      signStrategy: config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionStorage: config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: config.prefix,\n      sessionExpirationMs: config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: config.tinycloudFallbackHosts,\n      autoCreateSpace: useBootstrapSignInRequest ? false : config.autoCreateSpace,\n      enablePublicSpace: config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : config.spaceCreationHandler,\n      nonce: config.nonce,\n      siweConfig: config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : config.includeAccountRegistryPermissions,\n    });\n\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: config.telemetry,\n    });\n  }\n\n  private shouldUseBootstrapSignInRequest(config: TinyCloudNodeConfig): boolean {\n    return config.autoBootstrapAccount !== false &&\n      config.manifest === undefined &&\n      config.capabilityRequest === undefined &&\n      (config.prefix ?? \"default\") === \"default\" &&\n      isOpenKeyAutoSignStrategy(config.signStrategy);\n  }\n\n  private syncResolvedHostFromAuth(): void {\n    const host = this.auth?.hosts[0];\n    if (host) {\n      this.config.host = host;\n    }\n  }\n\n  /**\n   * Install or replace the manifest that drives the SIWE recap at\n   * sign-in. Takes effect on the next `signIn()` call — the current\n   * session (if any) is not touched. Wire this up from a higher\n   * layer (e.g. TinyCloudWeb.setManifest) so the manifest is kept\n   * in sync across the stack.\n   */\n  setManifest(manifest: Manifest | Manifest[] | undefined): void {\n    if (!this.auth) {\n      // Session-only mode has no auth handler, so there's nothing to\n      // update. The caller almost certainly wanted wallet mode — fail\n      // loudly rather than silently dropping the manifest.\n      throw new Error(\n        \"setManifest requires wallet mode. Provide a signer or privateKey in the TinyCloudNode config.\",\n      );\n    }\n    this.config.manifest = manifest;\n    this.config.capabilityRequest = undefined;\n    this.auth.setManifest(manifest);\n  }\n\n  setCapabilityRequest(request: ComposedManifestRequest | undefined): void {\n    if (!this.auth) {\n      throw new Error(\n        \"setCapabilityRequest requires wallet mode. Provide a signer or privateKey in the TinyCloudNode config.\",\n      );\n    }\n    this.config.capabilityRequest = request;\n    this.config.manifest = request?.manifests;\n    this.auth.setCapabilityRequest(request);\n  }\n\n  /**\n   * Return the manifest currently installed on the auth handler,\n   * or `undefined` if none is set.\n   */\n  get manifest(): Manifest | Manifest[] | undefined {\n    return this.auth?.manifest;\n  }\n\n  get capabilityRequest(): ComposedManifestRequest | undefined {\n    return this.auth?.capabilityRequest;\n  }\n\n  get hosts(): string[] {\n    const authHosts = this.auth?.hosts ?? [];\n    return authHosts.length > 0 ? authHosts : [this.config.host!];\n  }\n\n  /**\n   * Get the primary identity DID for this user.\n   * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})\n   * - If session-only mode: returns session key DID (did:key:z6Mk...)\n   *\n   * Use this for delegations - it always returns the appropriate identity.\n   */\n  get did(): string {\n    // If wallet is connected and signed in, return PKH (persistent identity)\n    if (this._address) {\n      return pkhDid(this._address, this._chainId);\n    }\n    // Session-only mode: return session key DID (ephemeral identity)\n    return this.sessionManager.getDID(this.sessionKeyId);\n  }\n\n  /**\n   * Get the session key DID. Always available.\n   * Format: did:key:z6Mk...#z6Mk...\n   *\n   * Use this when you specifically need the session key, not the user identity.\n   */\n  get sessionDid(): string {\n    return this.sessionManager.getDID(this.sessionKeyId);\n  }\n\n  /**\n   * Get the Ethereum address for this user.\n   */\n  get address(): string | undefined {\n    return this.auth?.address() ?? this._address;\n  }\n\n  /**\n   * Check if this instance is in session-only mode (no wallet).\n   * In session-only mode, the instance can receive delegations but cannot\n   * create its own space via signIn().\n   */\n  get isSessionOnly(): boolean {\n    return this.signer === null;\n  }\n\n  /**\n   * Get the space ID for this user.\n   * Available after signIn().\n   */\n  get spaceId(): string | undefined {\n    return this.auth?.tinyCloudSession?.spaceId;\n  }\n\n  /**\n   * Get the account space ID for this wallet identity.\n   * Available after wallet-backed sign-in or a restored session with address metadata.\n   */\n  get accountSpaceId(): string | undefined {\n    if (!this._address) {\n      return undefined;\n    }\n    return this.wasmBindings.makeSpaceId(this._address, this._chainId, ACCOUNT_REGISTRY_SPACE);\n  }\n\n  /**\n   * Account-level application and delegation helpers.\n   */\n  get account(): AccountService {\n    if (!this._account) {\n      this._account = new AccountService({\n        getDid: () => this.did,\n        getHost: () => this.hosts[0] ?? this.config.host!,\n        getPrimarySpaceId: () => this.spaceId,\n        getAccountSpaceId: () => this.accountSpaceId,\n        getSpaces: () => this.spaces,\n        getAccountDb: () =>\n          this.accountSpaceId\n            ? this.sqlForSpace(this.accountSpaceId).db(\"account\")\n            : undefined,\n        ensureAccountSpaceHosted: async () => {\n          if (this.accountSpaceId && this.auth) {\n            await this.ensureOwnedSpaceHostedById(this.accountSpaceId);\n          }\n        },\n      });\n    }\n    return this._account;\n  }\n\n  /**\n   * Get the current TinyCloud session.\n   * Available after signIn().\n   */\n  get session(): TinyCloudSession | undefined {\n    return this.auth?.tinyCloudSession;\n  }\n\n  /**\n   * Sign in and create a new session.\n   * This creates the user's space if it doesn't exist.\n   * Requires wallet mode (privateKey in config).\n   *\n   * @param options - Optional per-call SIWE overrides for this sign-in only\n   */\n  async signIn(options?: SignInOptions): Promise<void> {\n    if (!this.signer || !this.tc) {\n      throw new Error(\n        \"Cannot signIn() in session-only mode. Provide a privateKey in config to create your own space.\"\n      );\n    }\n\n    // Ensure WASM is ready (critical for browser where WASM loads asynchronously)\n    await this.wasmBindings.ensureInitialized?.();\n\n    this._address = canonicalizeAddress(await this.signer.getAddress());\n    this._chainId = await this.signer.getChainId();\n\n    // Reset services so they get recreated with new session\n    this._kv = undefined;\n    this._sql = undefined;\n    this._duckdb = undefined;\n    this._hooks = undefined;\n    this._vault = undefined;\n    this._encryption = undefined;\n    this._baseSecrets = undefined;\n    this._secrets = undefined;\n    this._spaceService = undefined;\n    this._serviceContext = undefined;\n    this.runtimePermissionGrants = [];\n\n    await this.tc.signIn(options);\n    this.syncResolvedHostFromAuth();\n\n    // Initialize service context with session\n    this.initializeServices();\n\n    const bootstrapped = await this.bootstrapAccountIfNeeded();\n\n    await this.ensureRequestedEncryptionNetworks();\n\n    if (\n      !bootstrapped &&\n      this.config.manifest === undefined &&\n      this.config.capabilityRequest === undefined\n    ) {\n      await this.ensureOwnedSpaceHostedById(this.ownedSpaceId(SECRETS_SPACE));\n    }\n\n    if (!bootstrapped) {\n      this.scheduleAccountRegistrySync();\n    }\n\n    this.notificationHandler.success(\"Successfully signed in\");\n  }\n\n  private ownedSpaceId(name: string): string {\n    if (!this._address) {\n      throw new Error(\"Cannot resolve owned space before sign-in\");\n    }\n    return this.wasmBindings.makeSpaceId(this._address, this._chainId, name);\n  }\n\n  private async bootstrapAccountIfNeeded(): Promise<boolean> {\n    if (this.config.autoBootstrapAccount === false) {\n      return false;\n    }\n    if (!this.auth || !this._address) {\n      return false;\n    }\n\n    const steps = bootstrapSteps(this._address, this._chainId);\n    if (!(await this.isFreshBootstrapAccount(steps))) {\n      return false;\n    }\n\n    await this.runAccountBootstrap(steps);\n    return true;\n  }\n\n  private async isFreshBootstrapAccount(steps: BootstrapStep[]): Promise<boolean> {\n    const enshrinedSpaceIds = new Set<string>();\n    for (const step of steps) {\n      if (step.kind === \"session\") {\n        enshrinedSpaceIds.add(step.spaceId);\n      }\n    }\n    const skipped = (this.auth as NodeUserAuthorization).lastActivationSkippedSpaceIds;\n    if (skipped.some((spaceId) => enshrinedSpaceIds.has(spaceId))) {\n      return true;\n    }\n\n    try {\n      const indexed = await this.account.index.spaces.list();\n      if (indexed.ok && indexed.data.length === 0) {\n        return true;\n      }\n    } catch {\n      // A missing account index is expected before bootstrap; fall through to KV.\n    }\n\n    try {\n      const spaces = await this.account.spaces.list();\n      return spaces.ok && spaces.data.length === 0;\n    } catch {\n      return false;\n    }\n  }\n\n  private async runAccountBootstrap(steps: BootstrapStep[]): Promise<void> {\n    if (!this.auth || !this._address) {\n      throw new Error(\"Account bootstrap requires an active wallet session\");\n    }\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Account bootstrap requires a TinyCloud host\");\n    }\n\n    const auth = this.auth as NodeUserAuthorization;\n    const sessions = new Map<BootstrapSpaceName, TinyCloudSession>();\n    const rawAbilitiesBySpace = new Map<BootstrapSpaceName, Record<string, string[]>>();\n    const primarySession = auth.tinyCloudSession;\n    const defaultSpaceId = this.ownedSpaceId(\"default\");\n    const canReusePrimaryBootstrapSession =\n      primarySession?.spaceId === defaultSpaceId &&\n      auth.capabilityRequest === BOOTSTRAP_SESSION_REQUESTS.default;\n\n    for (const step of steps) {\n      if (step.kind !== \"session\") continue;\n      if (step.space === \"default\" && canReusePrimaryBootstrapSession && primarySession) {\n        sessions.set(step.space, primarySession);\n        continue;\n      }\n      const rawAbilities = step.rawAbilities;\n      if (rawAbilities) {\n        rawAbilitiesBySpace.set(step.space, rawAbilities);\n      }\n      const session = await auth.createBootstrapSession({\n        spaceId: step.spaceId,\n        capabilityRequest: step.request ?? BOOTSTRAP_SESSION_REQUESTS[step.space],\n        rawAbilities,\n      });\n      sessions.set(step.space, session);\n    }\n\n    for (const step of steps) {\n      if (step.kind !== \"host\") continue;\n      const hosted = await auth.hostOwnedSpace(step.spaceId);\n      if (!hosted) {\n        throw new Error(`Failed to host bootstrap space: ${step.spaceId}`);\n      }\n    }\n\n    await new Promise((resolve) => setTimeout(resolve, 100));\n\n    for (const step of steps) {\n      if (step.kind !== \"activate\") continue;\n      const session = sessions.get(step.space);\n      if (!session) {\n        throw new Error(`Missing bootstrap session for ${step.space}`);\n      }\n      const activated = await activateSessionWithHost(host, session.delegationHeader);\n      if (!activated.success || activated.skipped?.includes(step.spaceId)) {\n        throw new Error(\n          `Failed to activate bootstrap session for ${step.spaceId}: ${\n            activated.error ?? \"space was skipped\"\n          }`,\n        );\n      }\n      this.registerBootstrapRuntimeGrant(\n        session,\n        BOOTSTRAP_SESSION_REQUESTS[step.space],\n        rawAbilitiesBySpace.get(step.space),\n      );\n    }\n\n    for (const step of steps) {\n      if (step.kind === \"account-index-schema\") {\n        const ensured = await this.account.index.ensure();\n        if (!ensured.ok) {\n          throw new Error(`Failed to create account index schema: ${ensured.error.message}`);\n        }\n      }\n\n      if (step.kind === \"seed-spaces\") {\n        for (const space of step.spaces) {\n          const registered = await this.account.spaces.register({\n            spaceId: space.spaceId,\n            name: space.name,\n            ownerDid: this.did,\n            type: \"owned\",\n            permissions: [\"*\"],\n            status: \"active\",\n          });\n          if (!registered.ok) {\n            throw new Error(\n              `Failed to seed account space ${space.spaceId}: ${registered.error.message}`,\n            );\n          }\n        }\n      }\n\n      if (step.kind === \"seed-applications\") {\n        const registered = await this.account.applications.register(\n          step.manifests.length > 0\n            ? [...step.manifests]\n            : TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,\n        );\n        if (!registered.ok) {\n          throw new Error(`Failed to seed bootstrap applications: ${registered.error.message}`);\n        }\n      }\n\n      if (step.kind === \"encryption-network-create\") {\n        await this.ensureEncryptionNetwork(step.networkId);\n      }\n\n      if (step.kind === \"secret-records-schema\") {\n        const db = this.sqlForSpace(step.spaceId).db(step.database);\n        const migrated = await db.migrations.apply({\n          namespace: \"tinycloud.secrets.records\",\n          migrations: [\n            {\n              id: \"001_initial\",\n              sql: [...SECRET_RECORDS_SCHEMA],\n            },\n          ],\n        });\n        if (!migrated.ok) {\n          throw new Error(\n            `Failed to create secret_records schema: ${migrated.error.message}`,\n          );\n        }\n      }\n    }\n  }\n\n  private registerBootstrapRuntimeGrant(\n    session: TinyCloudSession,\n    request: { resources: readonly { service: string; space: string; path: string; actions: readonly string[] }[] },\n    rawAbilities?: Record<string, string[]>,\n  ): void {\n    const operations: RuntimePermissionOperation[] = [];\n    for (const resource of request.resources) {\n      const service = resource.service.startsWith(\"tinycloud.\")\n        ? this.shortServiceName(resource.service)\n        : resource.service;\n      const spaceId = resource.space.startsWith(\"tinycloud:\")\n        ? resource.space\n        : this.ownedSpaceId(resource.space);\n      for (const action of resource.actions) {\n        operations.push({\n          spaceId,\n          service,\n          path: resource.path,\n          action,\n        });\n      }\n    }\n    for (const [resource, actions] of Object.entries(rawAbilities ?? {})) {\n      for (const action of actions) {\n        operations.push({\n          resource,\n          service: \"encryption\",\n          path: resource,\n          action,\n        });\n      }\n    }\n\n    const expiresAt = extractSiweExpiration(session.siwe) ?? this.getSessionExpiry();\n    const actions = [...new Set(operations.map((operation) => operation.action))];\n    this.runtimePermissionGrants.push({\n      session: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: session.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      delegation: {\n        cid: session.delegationCid,\n        delegationHeader: session.delegationHeader,\n        delegateDID: session.verificationMethod,\n        delegatorDID: this.did,\n        spaceId: session.spaceId,\n        path: \"\",\n        actions,\n        expiry: expiresAt,\n        allowSubDelegation: true,\n        ownerAddress: session.address,\n        chainId: session.chainId,\n        host: this.config.host,\n      },\n      operations,\n      expiresAt,\n    });\n  }\n\n  private async writeManifestRegistryRecords(): Promise<void> {\n    const request = this.capabilityRequest;\n    if (!request || request.registryRecords.length === 0) {\n      return;\n    }\n    if (!this.auth || !this.signer) {\n      throw new Error(\"Manifest registry write requires wallet mode\");\n    }\n\n    const accountSpaceId = this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE);\n    await this.ensureOwnedSpaceHostedById(accountSpaceId);\n\n    const result = await this.account.applications.register(request.manifests);\n    if (!result.ok) {\n      throw new Error(\n        `Failed to write manifest registry records: ${result.error.message}`,\n      );\n    }\n  }\n\n  private scheduleAccountRegistrySync(): void {\n    void this.withAccountRegistryRetry(async () => {\n      void this.account.index.ensure();\n      await this.writeManifestRegistryRecords();\n      const spaces = await this.account.spaces.syncAccessible();\n      if (!spaces.ok) {\n        throw new Error(`Failed to sync account spaces: ${spaces.error.message}`);\n      }\n    });\n  }\n\n  private async withAccountRegistryRetry(task: () => Promise<void>): Promise<void> {\n    const delays = [250, 1_000, 3_000];\n    let lastError: unknown;\n    for (let attempt = 0; attempt < delays.length; attempt += 1) {\n      try {\n        await task();\n        return;\n      } catch (error) {\n        lastError = error;\n        if (attempt < delays.length - 1) {\n          await new Promise((resolve) => setTimeout(resolve, delays[attempt]));\n        }\n      }\n    }\n\n    console.warn(\n      \"TinyCloud account registry sync failed after retries\",\n      lastError,\n    );\n  }\n\n  private requestedEncryptionNetworkIds(): string[] {\n    const request = this.capabilityRequest;\n    if (!request) {\n      return [];\n    }\n\n    const networkIds = new Set<string>();\n    for (const resource of request.resources) {\n      if (\n        resource.service === ENCRYPTION_PERMISSION_SERVICE &&\n        resource.path.startsWith(\"urn:tinycloud:encryption:\") &&\n        resource.actions.includes(DECRYPT_ACTION)\n      ) {\n        networkIds.add(resource.path);\n      }\n    }\n    return [...networkIds];\n  }\n\n  private async ensureRequestedEncryptionNetworks(): Promise<void> {\n    if (!this.signer || !this.auth) {\n      return;\n    }\n\n    for (const networkId of this.requestedEncryptionNetworkIds()) {\n      const parsed = parseNetworkId(networkId);\n      if (!didPrincipalMatches(parsed.ownerDid, this.did)) {\n        continue;\n      }\n      await this.ensureEncryptionNetwork(networkId);\n    }\n  }\n\n  private async ensureOwnedSpaceHostedById(spaceId: string): Promise<void> {\n    if (!this.auth) {\n      throw new Error(\"Owned space hosting requires wallet mode\");\n    }\n\n    const session = this.auth.tinyCloudSession;\n    if (!session) {\n      throw new Error(\"Owned space hosting requires an active session\");\n    }\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Owned space hosting requires a TinyCloud host\");\n    }\n\n    const activation = await activateSessionWithHost(host, session.delegationHeader);\n    if (activation.success && !activation.skipped?.includes(spaceId)) {\n      return;\n    }\n\n    if (!activation.success && activation.status !== 404) {\n      throw new Error(\n        `Failed to check owned space ${spaceId}: ${activation.error ?? activation.status}`,\n      );\n    }\n\n    const created = await (this.auth as NodeUserAuthorization).hostOwnedSpace(spaceId);\n    if (!created) {\n      throw new Error(`Failed to create owned space: ${spaceId}`);\n    }\n\n    await new Promise((resolve) => setTimeout(resolve, 100));\n\n    const retry = await activateSessionWithHost(host, session.delegationHeader);\n    if (!retry.success || retry.skipped?.includes(spaceId)) {\n      throw new Error(\n        `Failed to activate session after creating owned space ${spaceId}: ${\n          retry.error ?? \"space was skipped\"\n        }`,\n      );\n    }\n  }\n\n  /**\n   * Host one of this user's owned spaces by name (e.g. `\"applications\"`).\n   *\n   * Resolves the name to the owned space URI\n   * (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`) and registers it on the\n   * server via the host-SIWE delegation flow, so subsequent KV/SQL writes to\n   * that space succeed instead of returning `404 - Space not found`. The\n   * caller is the root authority of their own owned spaces, so no additional\n   * delegation is required.\n   *\n   * Unlike {@link ensureOwnedSpaceHostedById}, this always submits the host\n   * delegation rather than inferring hosting from session activation: a space\n   * the current session has never referenced is reported neither as\n   * `activated` nor `skipped`, so activation-based detection would wrongly\n   * skip the host. The host SIWE is idempotent server-side, so re-hosting an\n   * existing space is a safe no-op. Must be called after {@link signIn}.\n   *\n   * @param name - The owned space name (e.g. `\"applications\"`).\n   * @returns The hosted space URI.\n   */\n  async hostOwnedSpace(name: string): Promise<string> {\n    if (!this.auth || !this.auth.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const spaceId = this.ownedSpaceId(name);\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Owned space hosting requires a TinyCloud host\");\n    }\n\n    const hosted = await (this.auth as NodeUserAuthorization).hostOwnedSpace(\n      spaceId,\n    );\n    if (!hosted) {\n      throw new Error(`Failed to host owned space: ${spaceId}`);\n    }\n\n    // Re-activate the session so it covers the newly hosted space, and prove\n    // the session can actually use it before reporting success: a successful\n    // /delegate that still lists the space under `skipped` means it is not\n    // hosted for this session.\n    const activation = await activateSessionWithHost(\n      host,\n      this.auth.tinyCloudSession.delegationHeader,\n    );\n    if (!activation.success || activation.skipped?.includes(spaceId)) {\n      throw new Error(\n        `Failed to activate session for owned space ${spaceId}: ${\n          activation.error ?? \"space was skipped\"\n        }`,\n      );\n    }\n\n    void this.account.spaces\n      .register({\n        spaceId,\n        name,\n        ownerDid: this.did,\n        type: \"owned\",\n        permissions: [\"*\"],\n        status: \"active\",\n      })\n      .catch(() => {});\n\n    return spaceId;\n  }\n\n  /**\n   * Ensure one of this user's owned spaces (e.g. `\"secrets\"`) is hosted on the\n   * server.\n   *\n   * At sign-in, a full-authority session auto-hosts the owner's `secrets`\n   * space, but a session created with a manifest / capabilityRequest does not.\n   * Such a session can therefore hold valid `tinycloud.kv/*` capabilities for\n   * the owned `secrets` space yet still fail its first scoped\n   * `secrets.put(...)` with `404 Space not found`, because the space was never\n   * registered on the node.\n   *\n   * Calling this resolves `name` to the owner's owned-space URI\n   * (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`). It first consults the\n   * account-space spaces registry (`account/spaces/{space_id}`, the canonical\n   * KV source of truth, fronted by a best-effort SQLite index): if the space is\n   * already registered/hosted it returns the URI WITHOUT submitting a host\n   * delegation, avoiding a redundant host-SIWE signature prompt for owners who\n   * already use the space. Only when the space is absent — or the registry\n   * check fails for any reason (e.g. a cold SQLite index reporting\n   * `no such table: spaces`) — does it fall through to {@link hostOwnedSpace}.\n   *\n   * The registry check is purely an optimization: any failure falls back to\n   * hosting, and the host SIWE is idempotent server-side, so re-hosting an\n   * existing space remains a safe no-op. Must be called after {@link signIn}.\n   *\n   * @param name - The owned space name (e.g. `\"secrets\"`).\n   * @returns The hosted owned-space URI.\n   */\n  async ensureOwnedSpaceHosted(name: string): Promise<string> {\n    if (!this.auth || !this.auth.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const spaceId = this.ownedSpaceId(name);\n\n    if (await this.isOwnedSpaceRegistered(spaceId)) {\n      return spaceId;\n    }\n\n    const hosted = await this.hostOwnedSpace(name);\n\n    // hostOwnedSpace registers best-effort and fire-and-forget; await an\n    // explicit registry write here so the canonical `account/spaces/{id}`\n    // record is durably present and a subsequent ensure short-circuits on the\n    // registry instead of re-hosting. The host already succeeded, so a failed\n    // registry write must not fail this call.\n    try {\n      await this.account.spaces.register({\n        spaceId,\n        name,\n        ownerDid: this.did,\n        type: \"owned\",\n        permissions: [\"*\"],\n        status: \"active\",\n      });\n    } catch {\n      // Registry write is best-effort; the space is hosted regardless.\n    }\n\n    return hosted;\n  }\n\n  /**\n   * Check whether an owned space is already registered/hosted by consulting the\n   * account spaces registry.\n   *\n   * Source of truth is the canonical KV registry record\n   * `account/spaces/{space_id}`, read here via `account.spaces.get(spaceId)`.\n   * The KV path is used (rather than `syncAccessible()`) because it works under\n   * a manifest/recap session with NO extra prompt: the composed manifest recap\n   * already grants `tinycloud.kv get/list` on the account space `spaces/`\n   * prefix, whereas `syncAccessible()` depends on `tinycloud.space/list`, which\n   * a recap session does not hold. Before reading, it consults the fast SQLite\n   * index (`account.index.spaces.list()`) as a best-effort short-circuit; on a\n   * cold index (`no such table: spaces`) or any other index failure it falls\n   * back to the canonical KV read.\n   *\n   * This is a best-effort optimization. ANY failure of the check path (missing\n   * table, KV error, missing record, thrown exception) resolves to `false` so\n   * the caller falls through to hosting — per the directive, \"if it fails in any\n   * way then create the space\".\n   */\n  private async isOwnedSpaceRegistered(spaceId: string): Promise<boolean> {\n    // Best-effort fast path: the SQLite index. Only trust a positive hit; treat\n    // misses/empties/errors/throws (e.g. a cold `no such table: spaces`) as\n    // inconclusive and fall through to the canonical KV read.\n    try {\n      const indexed = await this.account.index.spaces.list();\n      if (indexed.ok && indexed.data.some((space) => space.spaceId === spaceId)) {\n        return true;\n      }\n    } catch {\n      // Cache miss/error — fall back to canonical below.\n    }\n\n    // Canonical: the `account/spaces/{space_id}` KV record. This is the registry\n    // source of truth and is recap-readable. Any failure here (missing record,\n    // KV error, throw) resolves to \"not registered\" so the caller hosts.\n    try {\n      const record = await this.account.spaces.get(spaceId);\n      return record.ok;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Restore a previously established session from stored delegation data.\n   *\n   * This is used by the CLI to restore a session that was created via the\n   * browser-based delegation flow (OpenKey `/delegate` page). Instead of\n   * signing in with a private key, it injects the delegation data directly.\n   *\n   * @param sessionData - The stored delegation data from the browser flow\n   */\n  async restoreSession(sessionData: {\n    delegationHeader: { Authorization: string };\n    delegationCid: string;\n    spaceId: string;\n    jwk: object;\n    verificationMethod: string;\n    address?: string;\n    chainId?: number;\n    /**\n     * The SIWE message that authorized this session. Required for\n     * downstream operations that need the session's expiry (e.g.\n     * {@link grantRuntimePermissions}). When omitted the SDK can still\n     * invoke services with the existing delegation, but anything that\n     * reads `auth.tinyCloudSession.siwe` will treat the session as\n     * expired-at-epoch-zero.\n     */\n    siwe?: string;\n    /**\n     * The wallet/OpenKey signature over `siwe`. Optional because the\n     * runtime doesn't re-verify it — it's persisted alongside the SIWE\n     * for callers that need to round-trip the full session shape.\n     */\n    signature?: string;\n    /**\n     * The TinyCloud hosts this session was created against (from\n     * {@link PersistedSessionData.tinycloudHosts}). When present they are\n     * adopted so the restored session targets the same node as the\n     * original sign-in — without this, service calls fall back to the\n     * default host and the auth layer throws \"TinyCloud hosts have not\n     * been resolved\". When absent (old persisted session) hosts resolve\n     * lazily via the registry/fallback on the first host-needing call.\n     */\n    tinycloudHosts?: string[];\n  }): Promise<void> {\n    // Ensure WASM is ready (critical for browser where WASM loads asynchronously)\n    await this.wasmBindings.ensureInitialized?.();\n\n    // Reset services so they get recreated with new session\n    this._kv = undefined;\n    this._sql = undefined;\n    this._duckdb = undefined;\n    this._hooks = undefined;\n    this._vault = undefined;\n    this._encryption = undefined;\n    this._baseSecrets = undefined;\n    this._secrets = undefined;\n    this._spaceService = undefined;\n    this._serviceContext = undefined;\n    this.runtimePermissionGrants = [];\n\n    const restoredAddress = sessionData.address\n      ? canonicalizeAddress(sessionData.address)\n      : undefined;\n    if (restoredAddress) {\n      this._address = restoredAddress;\n    }\n    if (sessionData.chainId) {\n      this._chainId = sessionData.chainId;\n    }\n\n    // Resolve the host the restored session should target, mirroring what a\n    // fresh signIn() would have done. Priority:\n    //   1. explicitHost   — local dev / pinned node, never override\n    //   2. persisted hosts — the node this session was created against\n    //   3. registry/fallback resolution — old sessions that predate the\n    //      persisted tinycloudHosts field\n    // Without this, the ServiceContext below (and every service call) would\n    // silently target the default host instead of the user's actual node.\n    const resolvedHost = await this.resolveRestoredHost(\n      sessionData.tinycloudHosts,\n      restoredAddress,\n      sessionData.chainId,\n    );\n    if (resolvedHost) {\n      this.config.host = resolvedHost;\n    }\n\n    // Create service context\n    this._serviceContext = new ServiceContext({\n      invoke: this.invokeWithRuntimePermissions,\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      fetch: globalThis.fetch.bind(globalThis),\n      hosts: [this.config.host!],\n      telemetry: this.config.telemetry,\n    });\n\n    // Create and register KV service\n    this._kv = new KVService({});\n    this._kv.initialize(this._serviceContext);\n    this._serviceContext.registerService('kv', this._kv);\n\n    // Create and register SQL service\n    this._sql = new SQLService({});\n    this._sql.initialize(this._serviceContext);\n    this._serviceContext.registerService('sql', this._sql);\n\n    // Create and register DuckDB service\n    this._duckdb = new DuckDbService({});\n    this._duckdb.initialize(this._serviceContext);\n    this._serviceContext.registerService('duckdb', this._duckdb);\n\n    this._hooks = new HooksService({});\n    this._hooks.initialize(this._serviceContext);\n    this._serviceContext.registerService('hooks', this._hooks);\n\n    // Set session on context\n    const serviceSession: ServiceSession = {\n      delegationHeader: sessionData.delegationHeader,\n      delegationCid: sessionData.delegationCid,\n      spaceId: sessionData.spaceId,\n      verificationMethod: sessionData.verificationMethod,\n      jwk: sessionData.jwk,\n    };\n    this._serviceContext.setSession(serviceSession);\n\n    // Create and register Vault service (matches initializeServices behavior)\n    this._vault = this.createVaultService(sessionData.spaceId, this._kv!);\n    this._vault.initialize(this._serviceContext);\n    this._serviceContext.registerService('vault', this._vault);\n\n    // Initialize v2 services\n    this.initializeV2Services(serviceSession);\n\n    // Rehydrate a TinyCloudSession on whatever surface is available. In\n    // wallet mode the auth layer holds it; in session-only mode (OpenKey,\n    // public-space restore, …) `this.auth` is null and we fall back to\n    // `_restoredTcSession` on the node itself. Both surfaces are read by\n    // {@link currentTinyCloudSession} so callers don't have to care.\n    //\n    // Required for `useRuntimeDelegation` / `hasRuntimePermissions` /\n    // `getRuntimePermissionDelegations` to work after a session restore —\n    // without this they bail with `SessionExpiredError(new Date(0))`.\n    if (sessionData.siwe && restoredAddress && sessionData.chainId) {\n      const tcSession: TinyCloudSession = {\n        address: restoredAddress,\n        chainId: sessionData.chainId,\n        sessionKey: JSON.stringify(sessionData.jwk),\n        spaceId: sessionData.spaceId,\n        delegationCid: sessionData.delegationCid,\n        delegationHeader: sessionData.delegationHeader,\n        verificationMethod: sessionData.verificationMethod,\n        jwk: sessionData.jwk as { [k: string]: unknown },\n        siwe: sessionData.siwe,\n        signature: sessionData.signature ?? \"\",\n      };\n      if (this.auth) {\n        // Pass the now-resolved host so the auth layer's host-needing\n        // methods (ensureSpaceExists/hostSpace) don't throw \"hosts have\n        // not been resolved\" on a restored session.\n        this.auth.setRestoredTinyCloudSession(\n          tcSession,\n          this.config.host ? [this.config.host] : undefined,\n        );\n      } else {\n        this._restoredTcSession = tcSession;\n      }\n    }\n  }\n\n  /**\n   * Resolve the host a restored session should target.\n   *\n   * Mirrors fresh sign-in host resolution but for the restore path:\n   * an explicit/pinned host always wins, then the hosts the session was\n   * persisted with, then a lazy registry/fallback resolution for sessions\n   * that predate the persisted `tinycloudHosts` field. Returns `undefined`\n   * only when there's nothing to resolve from (no explicit host, no\n   * persisted hosts, and no address/chainId) — in which case the existing\n   * `config.host` (default) is left in place.\n   *\n   * Resolution failures are surfaced, not swallowed: a genuinely broken\n   * registry lookup throws rather than silently falling back to a wrong host.\n   */\n  private async resolveRestoredHost(\n    persistedHosts: string[] | undefined,\n    address: string | undefined,\n    chainId: number | undefined,\n  ): Promise<string | undefined> {\n    if (this.explicitHost) {\n      return this.explicitHost;\n    }\n    if (persistedHosts && persistedHosts.length > 0) {\n      return persistedHosts[0];\n    }\n    if (address === undefined || chainId === undefined) {\n      return undefined;\n    }\n    const resolved = await resolveTinyCloudHosts(pkhDid(address, chainId), {\n      registryUrl: this.config.tinycloudRegistryUrl,\n      fallbackHosts: this.config.tinycloudFallbackHosts,\n    });\n    return resolved.hosts[0];\n  }\n\n  /**\n   * Resolve the currently-active TinyCloudSession, preferring the auth\n   * layer's value (wallet mode) and falling back to the node-level\n   * rehydration set by {@link restoreSession} (session-only mode).\n   */\n  private currentTinyCloudSession(): TinyCloudSession | undefined {\n    return this.auth?.tinyCloudSession ?? this._restoredTcSession;\n  }\n\n  /**\n   * Connect a wallet to upgrade from session-only mode to wallet mode.\n   *\n   * This allows a user who started in session-only mode to later connect\n   * a wallet and gain the ability to create their own space.\n   *\n   * Note: This does NOT automatically sign in. Call signIn() after connecting\n   * the wallet to create your space.\n   *\n   * @param privateKey - The Ethereum private key (hex string, no 0x prefix)\n   * @param options - Optional configuration\n   * @param options.prefix - Space name prefix (defaults to \"default\")\n   *\n   * @example\n   * ```typescript\n   * // Start in session-only mode\n   * const node = new TinyCloudNode({ host: \"https://node.tinycloud.xyz\" });\n   * console.log(node.did); // did:key:z6Mk... (session key)\n   *\n   * // Later, connect a wallet\n   * node.connectWallet(privateKey);\n   * await node.signIn();\n   * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)\n   * ```\n   */\n  connectWallet(privateKey: string, options?: { prefix?: string; sessionStorage?: ISessionStorage }): void {\n    if (this.signer) {\n      throw new Error(\"Wallet already connected. Cannot connect another wallet.\");\n    }\n\n    const prefix = options?.prefix ?? \"default\";\n\n    // Create signer from private key\n    if (!TinyCloudNode.nodeDefaults) {\n      throw new Error(\n        \"connectWallet() requires PrivateKeySigner. Use connectSigner() instead, \" +\n        \"or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n      );\n    }\n    this.signer = TinyCloudNode.nodeDefaults.createSigner(privateKey);\n\n    // Create authorization handler\n    const authConfig = { ...this.config, prefix };\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(authConfig);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer,\n      signStrategy: this.config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: prefix,\n      sessionExpirationMs: this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: this.config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: this.config.tinycloudFallbackHosts,\n      autoCreateSpace: useBootstrapSignInRequest ? false : this.config.autoCreateSpace,\n      enablePublicSpace: this.config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : this.config.spaceCreationHandler,\n      nonce: this.config.nonce,\n      siweConfig: this.config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : this.config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : this.config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : this.config.includeAccountRegistryPermissions,\n    });\n\n    // Create TinyCloud instance\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: this.config.telemetry,\n    });\n\n    // Update config with prefix\n    this.config.prefix = prefix;\n  }\n\n  /**\n   * Connect any ISigner to upgrade from session-only mode to wallet mode.\n   *\n   * Same as connectWallet() but accepts any ISigner implementation instead\n   * of a raw private key string. Use this for browser wallets, hardware wallets,\n   * or custom signing backends.\n   *\n   * Note: This does NOT automatically sign in. Call signIn() after connecting.\n   *\n   * @param signer - Any ISigner implementation\n   * @param options - Optional configuration\n   * @param options.prefix - Space name prefix (defaults to \"default\")\n   */\n  connectSigner(signer: ISigner, options?: { prefix?: string; sessionStorage?: ISessionStorage }): void {\n    if (this.signer) {\n      throw new Error(\"Signer already connected. Cannot connect another signer.\");\n    }\n\n    const prefix = options?.prefix ?? \"default\";\n\n    this.signer = signer;\n\n    const authConfig = { ...this.config, prefix };\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(authConfig);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer,\n      signStrategy: this.config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: prefix,\n      sessionExpirationMs: this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: this.config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: this.config.tinycloudFallbackHosts,\n      autoCreateSpace: useBootstrapSignInRequest ? false : this.config.autoCreateSpace,\n      enablePublicSpace: this.config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : this.config.spaceCreationHandler,\n      nonce: this.config.nonce,\n      siweConfig: this.config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : this.config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : this.config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : this.config.includeAccountRegistryPermissions,\n    });\n\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: this.config.telemetry,\n    });\n    this.config.prefix = prefix;\n  }\n\n  /**\n   * Initialize the service context and KV service after sign-in.\n   * @internal\n   */\n  private initializeServices(): void {\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      return;\n    }\n\n    // Initialize TinyCloud core services (needed for publicKV, ensurePublicSpace)\n    this.tc!.initializeServices(this.invokeWithRuntimePermissions, [this.config.host!]);\n\n    // Create service context\n    this._serviceContext = new ServiceContext({\n      invoke: this.invokeWithRuntimePermissions,\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      fetch: globalThis.fetch.bind(globalThis),\n      hosts: [this.config.host!],\n      telemetry: this.config.telemetry,\n    });\n\n    // Create and register KV service\n    this._kv = new KVService({});\n    this._kv.initialize(this._serviceContext);\n    this._serviceContext.registerService('kv', this._kv);\n\n    // Create and register SQL service (if supported)\n    const features = this.nodeFeatures;\n    if (features.length === 0 || features.includes(\"sql\")) {\n      this._sql = new SQLService({});\n      this._sql.initialize(this._serviceContext);\n      this._serviceContext.registerService('sql', this._sql);\n    }\n\n    // Create and register DuckDB service (if supported)\n    if (features.length === 0 || features.includes(\"duckdb\")) {\n      this._duckdb = new DuckDbService({});\n      this._duckdb.initialize(this._serviceContext);\n      this._serviceContext.registerService('duckdb', this._duckdb);\n    }\n\n    this._hooks = new HooksService({});\n    this._hooks.initialize(this._serviceContext);\n    this._serviceContext.registerService('hooks', this._hooks);\n\n    // Set session on context\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      spaceId: session.spaceId,\n      verificationMethod: session.verificationMethod,\n      jwk: session.jwk,\n    };\n    this._serviceContext.setSession(serviceSession);\n    (this.tc!.serviceContext as ServiceContext).setSession(serviceSession);\n\n    // Create and register Vault service\n    this._vault = this.createVaultService(session.spaceId, this._kv!);\n    this._vault.initialize(this._serviceContext);\n    this._serviceContext.registerService('vault', this._vault);\n\n    // Initialize v2 services\n    this.initializeV2Services(serviceSession);\n  }\n\n  private createSpaceScopedKVService(spaceId: string): KVService {\n    const kvService = new KVService({});\n    if (this._serviceContext) {\n      const spaceScopedContext = new ServiceContext({\n        invoke: this._serviceContext.invoke,\n        fetch: this._serviceContext.fetch,\n        hosts: this._serviceContext.hosts,\n        telemetry: this.config.telemetry,\n      });\n      const session = this._serviceContext.session;\n      if (session) {\n        spaceScopedContext.setSession({ ...session, spaceId });\n      }\n      kvService.initialize(spaceScopedContext);\n    }\n    return kvService;\n  }\n\n  getDefaultEncryptionNetworkId(name = DEFAULT_ENCRYPTION_NETWORK_NAME): string {\n    return `urn:tinycloud:encryption:${this.did}:${name}`;\n  }\n\n  private requireServiceSession(): ServiceSession {\n    const session = this._serviceContext?.session;\n    if (!session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return session;\n  }\n\n  private createEncryptionCrypto(): EncryptionCrypto {\n    const wasm = this.wasmBindings;\n    const columnEncrypt = (key: Uint8Array, plaintext: Uint8Array): Uint8Array => {\n      const encrypted = wasm.vault_encrypt(key, plaintext);\n      const out = new Uint8Array(1 + encrypted.length);\n      out[0] = 0x01;\n      out.set(encrypted, 1);\n      return out;\n    };\n    const columnDecrypt = (key: Uint8Array, blob: Uint8Array): Uint8Array => {\n      if (blob[0] !== 0x01) {\n        return blob;\n      }\n      return wasm.vault_decrypt(key, blob.slice(1));\n    };\n    return {\n      sha256: (data) => wasm.vault_sha256(data),\n      randomBytes: (length) => wasm.vault_random_bytes(length),\n      x25519FromSeed: (seed) => wasm.vault_x25519_from_seed(seed),\n      x25519Dh: (privateKey, publicKey) =>\n        wasm.vault_x25519_dh(privateKey, publicKey),\n      authEncrypt: (key, plaintext) => wasm.vault_encrypt(key, plaintext),\n      authDecrypt: (key, ciphertext) => wasm.vault_decrypt(key, ciphertext),\n      sealToNetworkKey: (networkPublicKey, symmetricKey) => {\n        const seed = wasm.vault_random_bytes(32);\n        const ephemeral = wasm.vault_x25519_from_seed(seed);\n        const shared = wasm.vault_x25519_dh(\n          ephemeral.privateKey,\n          networkPublicKey,\n        );\n        const encrypted = columnEncrypt(shared, symmetricKey);\n        const out = new Uint8Array(ephemeral.publicKey.length + encrypted.length);\n        out.set(ephemeral.publicKey, 0);\n        out.set(encrypted, ephemeral.publicKey.length);\n        return out;\n      },\n      openWithReceiverKey: (receiverPrivateKey, wrappedKey) => {\n        const peerPublic = wrappedKey.slice(0, 32);\n        const ciphertext = wrappedKey.slice(32);\n        const shared = wasm.vault_x25519_dh(receiverPrivateKey, peerPublic);\n        return columnDecrypt(shared, ciphertext);\n      },\n      verifyNodeSignature: (nodeId, message, signature) =>\n        verifyDidKeyEd25519Signature(nodeId, message, signature),\n    };\n  }\n\n  private async fetchNodeId(): Promise<string> {\n    const response = await fetch(`${this.config.host}/info`);\n    if (!response.ok) {\n      throw new Error(`Failed to fetch node info: HTTP ${response.status}`);\n    }\n    const info = (await response.json()) as { nodeId?: unknown };\n    if (typeof info.nodeId !== \"string\" || info.nodeId.length === 0) {\n      throw new Error(\"Node /info response did not include nodeId\");\n    }\n    return info.nodeId;\n  }\n\n  private async signRawNetworkAuthorization(input: {\n    targetNode: string;\n    networkId: string;\n    action: string;\n    facts: NetworkInvocationFact;\n  }): Promise<{ authorization: string; invocationCid: string }> {\n    if (!this.wasmBindings.invokeAny) {\n      throw new Error(\"WASM binding does not support raw-resource invokeAny\");\n    }\n    if (!this.wasmBindings.computeCid) {\n      throw new Error(\"WASM binding does not support invocation CID computation\");\n    }\n    const session = this.requireServiceSession();\n    const headers = this.invokeAnyWithRuntimePermissions(\n      session,\n      [\n        {\n          resource: input.networkId,\n          service: \"encryption\",\n          path: input.networkId,\n          action: input.action,\n        },\n      ],\n      [input.facts as Record<string, unknown>],\n    );\n    const authorization = authorizationHeader(headers);\n    const audienceBound = await rewriteInvocationAudience(\n      authorization,\n      input.targetNode,\n      session.jwk,\n    );\n    return {\n      authorization: audienceBound,\n      invocationCid: this.wasmBindings.computeCid(\n        new TextEncoder().encode(audienceBound),\n        0x55n,\n      ),\n    };\n  }\n\n  private createEncryptionService(): EncryptionService {\n    const crypto = this.createEncryptionCrypto();\n    const transport: DecryptTransport = {\n      postDecrypt: async ({ networkId, authorization, canonicalBody }) => {\n        const response = await fetch(\n          `${this.config.host}/encryption/networks/${encodeURIComponent(networkId)}/decrypt`,\n          {\n            method: \"POST\",\n            headers: {\n              Authorization: authorization,\n              \"Content-Type\": \"application/json\",\n            },\n            body: canonicalBody,\n          },\n        );\n        if (!response.ok) {\n          throw new Error(\n            `decrypt failed ${response.status}: ${await response.text()}`,\n          );\n        }\n        return (await response.json()) as DecryptResponseBody;\n      },\n    };\n    return new EncryptionService({\n      crypto,\n      signer: {\n        signDecryptInvocation: async (\n          input: BuildDecryptInvocationInput,\n        ): Promise<BuiltDecryptInvocation> => {\n          const signed = await this.signRawNetworkAuthorization({\n            targetNode: input.targetNode,\n            networkId: input.networkId,\n            action: DECRYPT_ACTION,\n            facts: input.facts,\n          });\n          return {\n            ...signed,\n            canonicalBody: canonicalizeEncryptionJson(\n              input.body as unknown as CanonicalizableEncryptionJson,\n            ),\n          };\n        },\n      },\n      transport,\n      node: {\n        fetchByNetworkId: (networkId) => this.getEncryptionNetwork(networkId),\n      },\n      wellKnown: {\n        fetchWellKnown: async (principal, discoveryKey) => {\n          if (!this._address || !didPrincipalMatches(principal, this.did)) {\n            return null;\n          }\n          if (!this.config.host) {\n            return null;\n          }\n          const publicSpaceId = makePublicSpaceId(this._address, this._chainId);\n          const result = await TinyCloud.readPublicSpace<\n            NetworkDescriptor | { descriptor?: NetworkDescriptor }\n          >(this.config.host, publicSpaceId, discoveryKey);\n          if (!result.ok) {\n            return null;\n          }\n          const body = result.data as\n            | NetworkDescriptor\n            | { descriptor?: NetworkDescriptor };\n          return \"descriptor\" in body && body.descriptor\n            ? body.descriptor\n            : (body as NetworkDescriptor);\n        },\n      },\n    });\n  }\n\n  private getEncryptionService(): EncryptionService {\n    if (!this._serviceContext) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    if (!this._encryption) {\n      this._encryption = this.createEncryptionService();\n      this._encryption.initialize(this._serviceContext);\n      this._serviceContext.registerService(\"encryption\", this._encryption);\n    }\n    return this._encryption;\n  }\n\n  private createVaultService(spaceId: string, kv: IKVService): DataVaultService {\n    const wasm = this.wasmBindings;\n    const vaultCrypto = createVaultCrypto({\n      vault_encrypt: wasm.vault_encrypt, vault_decrypt: wasm.vault_decrypt, vault_derive_key: wasm.vault_derive_key,\n      vault_x25519_from_seed: wasm.vault_x25519_from_seed, vault_x25519_dh: wasm.vault_x25519_dh,\n      vault_random_bytes: wasm.vault_random_bytes, vault_sha256: wasm.vault_sha256,\n    });\n    const self = this;\n    return new DataVaultService({\n      spaceId,\n      crypto: vaultCrypto,\n      encryption: {\n        networkId: this.getDefaultEncryptionNetworkId(),\n        service: this.getEncryptionService(),\n        decryptCapabilityProof: () => ({\n          proofs: [this.requireServiceSession().delegationCid],\n        }),\n      },\n      tc: {\n        kv,\n        ensurePublicSpace: async () => {\n          try {\n            await self.ensurePublicSpace();\n            return { ok: true as const, data: undefined };\n          } catch (error) {\n            return { ok: false as const, error: { code: \"STORAGE_ERROR\", message: error instanceof Error ? error.message : String(error), service: \"vault\" } };\n          }\n        },\n        get publicKV() { return self._publicKV ?? self.tc!.publicKV; },\n        readPublicSpace: <T>(host: string, targetSpaceId: string, key: string) =>\n          TinyCloud.readPublicSpace<T>(host, targetSpaceId, key),\n        makePublicSpaceId: TinyCloud.makePublicSpaceId,\n        did: this.did,\n        address: this._address ?? \"\",\n        chainId: this._chainId,\n        hosts: [this.config.host!],\n      },\n    });\n  }\n\n  /**\n   * Initialize the v2 delegation system services.\n   * @internal\n   */\n  private initializeV2Services(serviceSession: ServiceSession): void {\n    // Initialize CapabilityKeyRegistry\n    this._capabilityRegistry = new CapabilityKeyRegistry();\n\n    const tcSession = this.auth?.tinyCloudSession;\n    // Register the session key with its capabilities\n    if (tcSession && this._address) {\n      const sessionKey: KeyInfo = {\n        id: tcSession.sessionKey,\n        did: tcSession.verificationMethod,\n        type: \"session\",\n        // Cast jwk from generic object to JWK - we know it has the required structure\n        jwk: tcSession.jwk as JWK,\n        priority: 0, // Session keys have highest priority\n      };\n\n      // Create root delegation for the session\n      const rootDelegation: Delegation = {\n        cid: tcSession.delegationCid,\n        delegateDID: tcSession.verificationMethod,\n        spaceId: tcSession.spaceId,\n        path: \"\", // Root access\n        actions: [\n          \"tinycloud.kv/put\",\n          \"tinycloud.kv/get\",\n          \"tinycloud.kv/del\",\n          \"tinycloud.kv/list\",\n          \"tinycloud.kv/metadata\",\n          \"tinycloud.sql/read\",\n          \"tinycloud.sql/write\",\n          \"tinycloud.sql/admin\",\n          \"tinycloud.sql/*\",\n          \"tinycloud.duckdb/read\",\n          \"tinycloud.duckdb/write\",\n          \"tinycloud.duckdb/admin\",\n          \"tinycloud.duckdb/describe\",\n          \"tinycloud.duckdb/export\",\n          \"tinycloud.duckdb/import\",\n          \"tinycloud.duckdb/*\",\n        ],\n        expiry: this.getSessionExpiry(),\n        isRevoked: false,\n        allowSubDelegation: true,\n      };\n\n      // Register root delegations\n      const delegations = [rootDelegation];\n\n      // If session includes additional spaces (e.g., public), register delegations for those too\n      if (tcSession.spaces) {\n        for (const [spaceName, spaceId] of Object.entries(tcSession.spaces)) {\n          delegations.push({\n            cid: tcSession.delegationCid,\n            delegateDID: tcSession.verificationMethod,\n            spaceId,\n            path: \"\",\n            actions: [\n              \"tinycloud.kv/put\",\n              \"tinycloud.kv/get\",\n              \"tinycloud.kv/del\",\n              \"tinycloud.kv/list\",\n              \"tinycloud.kv/metadata\",\n              \"tinycloud.sql/read\",\n              \"tinycloud.sql/write\",\n              \"tinycloud.sql/admin\",\n              \"tinycloud.sql/*\",\n              \"tinycloud.duckdb/read\",\n              \"tinycloud.duckdb/write\",\n              \"tinycloud.duckdb/admin\",\n              \"tinycloud.duckdb/describe\",\n              \"tinycloud.duckdb/export\",\n              \"tinycloud.duckdb/import\",\n              \"tinycloud.duckdb/*\",\n            ],\n            expiry: this.getSessionExpiry(),\n            isRevoked: false,\n            allowSubDelegation: true,\n          });\n        }\n      }\n\n      this._capabilityRegistry.registerKey(sessionKey, delegations);\n    }\n\n    // Initialize DelegationManager\n    this._delegationManager = new DelegationManager({\n      hosts: [this.config.host!],\n      session: serviceSession,\n      invoke: this.invokeWithRuntimePermissions,\n      fetch: globalThis.fetch.bind(globalThis),\n    });\n\n    // Initialize SpaceService\n    this._spaceService = new SpaceService({\n      hosts: [this.config.host!],\n      session: serviceSession,\n      invoke: this.wasmBindings.invoke,\n      fetch: globalThis.fetch.bind(globalThis),\n      capabilityRegistry: this._capabilityRegistry,\n      userDid: this.did,\n      createKVService: (spaceId: string) => {\n        return this.createSpaceScopedKVService(spaceId);\n      },\n      createVaultService: (spaceId: string) => {\n        const kvService = this.createSpaceScopedKVService(spaceId);\n        const vaultService = this.createVaultService(spaceId, kvService);\n        if (this._serviceContext) {\n          vaultService.initialize(this._serviceContext);\n        }\n        return vaultService;\n      },\n      // Enable space.delegations.create() via SIWE-based delegation\n      createDelegation: async (params) => {\n        try {\n          // Use the existing createDelegation method which calls /delegate with SIWE\n          const portableDelegation = await this.createDelegation({\n            delegateDID: params.delegateDID,\n            path: params.path,\n            actions: params.actions,\n            disableSubDelegation: params.disableSubDelegation,\n            expiryMs: params.expiry\n              ? params.expiry.getTime() - Date.now()\n              : undefined,\n          });\n\n          // Convert PortableDelegation to Delegation type for Space API\n          const delegation: Delegation = {\n            cid: portableDelegation.cid,\n            delegateDID: portableDelegation.delegateDID,\n            delegatorDID: this.did,\n            spaceId: portableDelegation.spaceId,\n            path: portableDelegation.path,\n            actions: portableDelegation.actions,\n            expiry: portableDelegation.expiry,\n            isRevoked: false,\n            allowSubDelegation: !portableDelegation.disableSubDelegation,\n            createdAt: new Date(),\n            authHeader: portableDelegation.delegationHeader.Authorization,\n          };\n\n          return { ok: true, data: delegation };\n        } catch (error) {\n          return {\n            ok: false,\n            error: {\n              code: \"CREATION_FAILED\",\n              message: error instanceof Error ? error.message : String(error),\n              service: \"delegation\",\n            },\n          };\n        }\n      },\n      onSpaceRegistered: async (space) => {\n        await this.account.spaces.register(space);\n      },\n    });\n\n    // Update SharingService with full capabilities (session + createDelegation)\n    // SharingService was initialized in constructor for receive-only access\n    this._sharingService.updateConfig({\n      session: serviceSession,\n      delegationManager: this._delegationManager,\n      sessionExpiry: this.getSessionExpiry(),\n      // WASM-based delegation creation (preferred - no server roundtrip)\n      createDelegationWasm: (params) => this.createDelegationWrapper(params),\n      // Root delegation for long-lived share links (bypasses session expiry)\n      // In node-sdk we have direct signer access, so no popup needed\n      onRootDelegationNeeded: this.signer\n        ? async (params) => this.createRootDelegationForSharing(params)\n        : undefined,\n    });\n\n    // Wire up SharingService to SpaceService for space.sharing.generate()\n    this._spaceService.updateConfig({\n      sharingService: this._sharingService,\n    });\n  }\n\n  /**\n   * Get the session expiry time.\n   * @internal\n   */\n  private getSessionExpiry(): Date {\n    // Default to 1 hour from now if not explicitly set\n    const expirationMs = this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS;\n    return new Date(Date.now() + expirationMs);\n  }\n\n  /**\n   * Wrapper for the WASM createDelegation function.\n   *\n   * The WASM call now takes a multi-resource `abilities` map\n   * (matching `prepareSession`'s shape) and emits ONE UCAN that\n   * covers every `(service, path, actions)` entry. We mirror the raw\n   * result back through `CreateDelegationWasmResult`, converting the\n   * seconds-since-epoch `expiry` to a Date and normalizing the\n   * `delegateDid` → `delegateDID` case.\n   *\n   * Both SharingService (single-entry) and\n   * {@link TinyCloudNode.delegateTo} (multi-entry) drive this through\n   * the same code path so there's exactly one place that touches the\n   * WASM boundary.\n   *\n   * @internal\n   */\n  private createDelegationWrapper(params: CreateDelegationWasmParams): CreateDelegationWasmResult {\n    // Convert ServiceSession to the format WASM expects\n    const wasmSession = {\n      delegationHeader: params.session.delegationHeader,\n      delegationCid: params.session.delegationCid,\n      jwk: params.session.jwk,\n      spaceId: params.session.spaceId,\n      verificationMethod: params.session.verificationMethod,\n    };\n\n    const result = this.wasmBindings.createDelegation(\n      wasmSession,\n      params.delegateDID,\n      params.spaceId,\n      params.abilities,\n      params.expirationSecs,\n      params.notBeforeSecs\n    );\n\n    return {\n      delegation: result.delegation,\n      cid: result.cid,\n      // Rust serde `rename_all = \"camelCase\"` emits `delegateDid`\n      // (lowercase d); the TypeScript interface uses `delegateDID`\n      // (historical, matches Delegation.delegateDID). Normalize here.\n      delegateDID: result.delegateDid ?? result.delegateDID,\n      expiry: new Date(result.expiry * 1000),\n      resources: result.resources,\n    };\n  }\n\n  /**\n   * Create a direct root delegation from the wallet to a share key.\n   * This bypasses the session delegation chain, allowing share links\n   * with expiry longer than the current session.\n   * @internal\n   */\n  private async createRootDelegationForSharing(params: {\n    shareKeyDID: string;\n    spaceId: string;\n    path: string;\n    actions: string[];\n    requestedExpiry: Date;\n  }): Promise<Delegation | undefined> {\n    if (!this.signer) {\n      return undefined;\n    }\n\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      return undefined;\n    }\n\n    try {\n      const host = this.config.host!;\n      const now = new Date();\n\n      // Build abilities for the share key\n      const abilities: Record<string, Record<string, string[]>> = {\n        kv: {\n          [params.path]: params.actions,\n        },\n      };\n\n      // Prepare a direct delegation to the share key (no parents = root delegation)\n      const prepared = this.wasmBindings.prepareSession({\n        abilities,\n        address: this.wasmBindings.ensureEip55(session.address),\n        chainId: session.chainId,\n        domain: this.siweDomain,\n        issuedAt: now.toISOString(),\n        expirationTime: params.requestedExpiry.toISOString(),\n        spaceId: params.spaceId,\n        delegateUri: params.shareKeyDID,\n      });\n\n      // Sign with the signer (no popup in node-sdk)\n      const signature = await this.signer.signMessage(prepared.siwe);\n\n      const delegationSession = this.wasmBindings.completeSessionSetup({\n        ...prepared,\n        signature,\n      });\n\n      // Activate the delegation with the server\n      const activateResult = await activateSessionWithHost(\n        host,\n        delegationSession.delegationHeader\n      );\n\n      if (!activateResult.success) {\n        return undefined;\n      }\n\n      return {\n        cid: delegationSession.delegationCid,\n        delegateDID: params.shareKeyDID,\n        delegatorDID: pkhDid(session.address, session.chainId),\n        spaceId: params.spaceId,\n        path: params.path,\n        actions: params.actions,\n        expiry: params.requestedExpiry,\n        isRevoked: false,\n        allowSubDelegation: true,\n        createdAt: now,\n        authHeader: delegationSession.delegationHeader.Authorization,\n      };\n    } catch {\n      return undefined;\n    }\n  }\n\n  /**\n   * Track a received delegation in the capability registry.\n   * @internal\n   */\n  private trackReceivedDelegation(delegation: PortableDelegation, jwk: JWK): void {\n    if (!this._capabilityRegistry) {\n      return;\n    }\n\n    const keyInfo: KeyInfo = {\n      id: `received:${delegation.cid}`,\n      did: this.sessionDid,\n      type: \"ingested\",\n      jwk,\n      priority: 2,\n    };\n\n    // Convert PortableDelegation to Delegation type\n    const delegationRecord: Delegation = {\n      cid: delegation.cid,\n      delegateDID: delegation.delegateDID,\n      spaceId: delegation.spaceId,\n      path: delegation.path,\n      actions: delegation.actions,\n      expiry: delegation.expiry,\n      isRevoked: false,\n      allowSubDelegation: !delegation.disableSubDelegation,\n    };\n\n    this._capabilityRegistry.ingestKey(keyInfo, delegationRecord);\n  }\n\n  /**\n   * Key-value storage operations on this user's space.\n   */\n  get kv(): IKVService {\n    if (!this._kv) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._kv;\n  }\n\n  /**\n   * SQL database operations on this user's space.\n   */\n  get sql(): ISQLService {\n    if (!this._sql) {\n      const features = this.nodeFeatures;\n      if (features.length > 0 && !features.includes(\"sql\")) {\n        throw new UnsupportedFeatureError(\"sql\", this.config.host!, features);\n      }\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._sql;\n  }\n\n  /**\n   * Get an SQL service scoped to a specific space.\n   *\n   * Mirrors {@link SpaceService}'s per-space KV factory: clones the active\n   * service context and overrides its session's spaceId so that subsequent\n   * `sql/<dbName>/<action>` invocations route to that space. Useful when\n   * the caller already holds a delegation covering the target space (e.g.\n   * via {@link grantRuntimePermissions} or {@link useRuntimeDelegation})\n   * but the SDK's per-space SQL surface isn't otherwise exposed.\n   *\n   * Does NOT auto-create the space.\n   *\n   * @param spaceId - Full space URI (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`).\n   */\n  sqlForSpace(spaceId: string): ISQLService {\n    if (!this._serviceContext || !this._serviceContext.session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const sql = new SQLService({});\n    const spaceScopedContext = new ServiceContext({\n      invoke: this._serviceContext.invoke,\n      fetch: this._serviceContext.fetch,\n      hosts: this._serviceContext.hosts,\n      telemetry: this.config.telemetry,\n    });\n    spaceScopedContext.setSession({ ...this._serviceContext.session, spaceId });\n    sql.initialize(spaceScopedContext);\n    return sql;\n  }\n\n  /**\n   * Get a KV service scoped to a specific space.\n   *\n   * The KV counterpart to {@link sqlForSpace}: clones the active service\n   * context and overrides its session's spaceId so that subsequent\n   * `kv/<action>` invocations route to that space. Useful for reading data\n   * that a manifest app stores outside the primary space (e.g. transcripts a\n   * `defaults: true` app keeps under the owner's `applications` space), when\n   * the caller already holds a delegation covering the target space.\n   *\n   * Does NOT auto-create the space.\n   *\n   * @param spaceId - Full space URI (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`).\n   */\n  kvForSpace(spaceId: string): IKVService {\n    if (!this._serviceContext || !this._serviceContext.session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const kv = new KVService({});\n    const spaceScopedContext = new ServiceContext({\n      invoke: this._serviceContext.invoke,\n      fetch: this._serviceContext.fetch,\n      hosts: this._serviceContext.hosts,\n    });\n    spaceScopedContext.setSession({ ...this._serviceContext.session, spaceId });\n    kv.initialize(spaceScopedContext);\n    return kv;\n  }\n\n  /**\n   * DuckDB database operations on this user's space.\n   */\n  get duckdb(): IDuckDbService {\n    if (!this._duckdb) {\n      const features = this.nodeFeatures;\n      if (features.length > 0 && !features.includes(\"duckdb\")) {\n        throw new UnsupportedFeatureError(\"duckdb\", this.config.host!, features);\n      }\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._duckdb;\n  }\n\n  /**\n   * Data Vault operations - client-side encrypted KV storage.\n   * Call `vault.unlock(signer)` after signIn() to derive encryption keys.\n   */\n  get vault(): IDataVaultService {\n    if (!this._vault) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._vault;\n  }\n\n  /**\n   * Network-scoped encryption/decrypt service.\n   */\n  get encryption(): IEncryptionService {\n    return this.getEncryptionService();\n  }\n\n  async getEncryptionNetwork(\n    nameOrNetworkId = this.getDefaultEncryptionNetworkId(),\n  ): Promise<NetworkDescriptor | null> {\n    const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n      ? nameOrNetworkId\n      : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n    const response = await fetch(\n      `${this.config.host}/encryption/networks/${encodeURIComponent(networkId)}`,\n    );\n    if (response.status === 404) {\n      return null;\n    }\n    if (!response.ok) {\n      throw new Error(\n        `Failed to fetch encryption network ${networkId}: HTTP ${response.status} ${await response.text()}`,\n      );\n    }\n    const body = (await response.json()) as {\n      descriptor?: NetworkDescriptor;\n    } | NetworkDescriptor;\n    return \"descriptor\" in body && body.descriptor ? body.descriptor : body as NetworkDescriptor;\n  }\n\n  async createEncryptionNetwork(\n    name = DEFAULT_ENCRYPTION_NETWORK_NAME,\n  ): Promise<NetworkDescriptor> {\n    const targetNode = await this.fetchNodeId();\n    const ownerDid = this.did;\n    const networkId = this.getDefaultEncryptionNetworkId(name);\n    const body = {\n      name,\n      ownerDid,\n      threshold: { n: 1, t: 1 },\n    };\n    const crypto = this.createEncryptionCrypto();\n    const facts = {\n      type: NETWORK_ADMIN_TYPE,\n      targetNode,\n      networkId,\n      bodyHash: canonicalHashHex(\n        crypto.sha256,\n        body as unknown as CanonicalizableEncryptionJson,\n      ),\n      action: NETWORK_CREATE_ACTION,\n    };\n    const signed = await this.signRawNetworkAuthorization({\n      targetNode,\n      networkId,\n      action: NETWORK_CREATE_ACTION,\n      facts,\n    });\n    const response = await fetch(`${this.config.host}/encryption/networks`, {\n      method: \"POST\",\n      headers: {\n        Authorization: signed.authorization,\n        \"Content-Type\": \"application/json\",\n      },\n      body: canonicalizeEncryptionJson(\n        body as unknown as CanonicalizableEncryptionJson,\n      ),\n    });\n    if (!response.ok) {\n      throw new Error(\n        `Failed to create encryption network ${networkId}: HTTP ${response.status} ${await response.text()}`,\n      );\n    }\n    const created = (await response.json()) as { descriptor: NetworkDescriptor };\n    return created.descriptor;\n  }\n\n  async ensureEncryptionNetwork(\n    nameOrNetworkId = DEFAULT_ENCRYPTION_NETWORK_NAME,\n  ): Promise<NetworkDescriptor> {\n    const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n      ? nameOrNetworkId\n      : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n    const existing = await this.getEncryptionNetwork(networkId);\n    if (existing) {\n      return existing;\n    }\n    const parsed = parseNetworkId(networkId);\n    if (!didPrincipalMatches(parsed.ownerDid, this.did)) {\n      throw new Error(\n        `Cannot create encryption network ${networkId}: owner ${parsed.ownerDid} does not match signed-in DID ${this.did}`,\n      );\n    }\n    return this.createEncryptionNetwork(parsed.name);\n  }\n\n  /**\n   * App-facing secrets API backed by the `secrets` space vault.\n   */\n  get secrets(): ISecretsService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    if (!this._secrets) {\n      this._secrets = new NodeSecretsService({\n        getService: () => this.getBaseSecrets(),\n        getManifest: () => this.manifest,\n        hasPermissions: (permissions) => this.hasRuntimePermissions(permissions),\n        grantPermissions: (additional) => this.grantRuntimePermissions(additional),\n        canEscalate: () => this.signer !== undefined && this.tc !== undefined,\n        getEncryptionNetworkId: () => this.getDefaultEncryptionNetworkId(),\n        getUnlockSigner: () => this.signer ?? undefined,\n      });\n    }\n    return this._secrets;\n  }\n\n  private getBaseSecrets(): ISecretsService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    if (!this._baseSecrets) {\n      this._baseSecrets = new SecretsService(() => this.space(\"secrets\").vault);\n    }\n    return this._baseSecrets;\n  }\n\n  /**\n   * Hooks write stream subscription API.\n   */\n  get hooks(): IHooksService {\n    if (!this._hooks) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._hooks;\n  }\n\n  // ===========================================================================\n  // v2 Service Accessors\n  // ===========================================================================\n\n  /**\n   * Get the CapabilityKeyRegistry for managing keys and their capabilities.\n   *\n   * The registry tracks keys (session, main, ingested) and their associated\n   * delegations, enabling automatic key selection for operations.\n   *\n   * @example\n   * ```typescript\n   * const registry = alice.capabilityRegistry;\n   *\n   * // Get the best key for an operation\n   * const key = registry.getKeyForCapability(\n   *   \"tinycloud://my-space/kv/data\",\n   *   \"tinycloud.kv/get\"\n   * );\n   *\n   * // List all capabilities\n   * const capabilities = registry.getAllCapabilities();\n   * ```\n   */\n  get capabilityRegistry(): ICapabilityKeyRegistry {\n    if (!this._capabilityRegistry) {\n      throw new Error(\"CapabilityKeyRegistry not initialized.\");\n    }\n    return this._capabilityRegistry;\n  }\n\n  /**\n   * Access received delegations (recipient view).\n   *\n   * Use this to see what delegations have been received via useDelegation().\n   *\n   * @example\n   * ```typescript\n   * // List all received delegations\n   * const received = bob.delegations.list();\n   * console.log(\"I have access to:\", received.length, \"spaces\");\n   *\n   * // Get a specific delegation by CID\n   * const delegation = bob.delegations.get(cid);\n   * ```\n   */\n  get delegations(): {\n    /** List all received delegations */\n    list: () => Delegation[];\n    /** Get a delegation by CID */\n    get: (cid: string) => Delegation | undefined;\n  } {\n    const registry = this._capabilityRegistry;\n    if (!registry) {\n      return {\n        list: () => [],\n        get: () => undefined,\n      };\n    }\n\n    return {\n      list: () => registry.getAllCapabilities().map((entry) => entry.delegation),\n      get: (cid: string) => {\n        const capabilities = registry.getAllCapabilities();\n        const entry = capabilities.find((e) => e.delegation.cid === cid);\n        return entry?.delegation;\n      },\n    };\n  }\n\n  /**\n   * Check whether the current session or an approved runtime delegation covers\n   * every requested permission.\n   */\n  hasRuntimePermissions(permissions: PermissionEntry[]): boolean {\n    const session = this.currentTinyCloudSession();\n    if (!session || !Array.isArray(permissions) || permissions.length === 0) {\n      return false;\n    }\n\n    const expanded = this.expandPermissionEntries(permissions);\n    if (this.sessionCoversPermissionEntries(session, expanded)) {\n      return true;\n    }\n\n    return this.findRuntimeGrantsForPermissionEntries(expanded, session).length > 0;\n  }\n\n  /**\n   * Return installed runtime permission delegations. When `permissions` is\n   * provided, only delegations currently covering those permissions are\n   * returned. Base-session manifest permissions are not represented here.\n   */\n  getRuntimePermissionDelegations(\n    permissions?: PermissionEntry[],\n  ): PortableDelegation[] {\n    this.pruneExpiredRuntimePermissionGrants();\n    if (permissions === undefined) {\n      return this.runtimePermissionGrants.map((grant) => grant.delegation);\n    }\n\n    const session = this.currentTinyCloudSession();\n    if (!session || !Array.isArray(permissions) || permissions.length === 0) {\n      return [];\n    }\n    const expanded = this.expandPermissionEntries(permissions);\n    return this.findRuntimeGrantsForPermissionEntries(expanded, session).map(\n      (grant) => grant.delegation,\n    );\n  }\n\n  /**\n   * Install a portable runtime permission delegation into this SDK instance so\n   * matching service calls and downstream `delegateTo()` calls can use it.\n   */\n  async useRuntimeDelegation(delegation: PortableDelegation): Promise<void> {\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n    if (delegation.expiry.getTime() <= Date.now()) {\n      throw new SessionExpiredError(delegation.expiry);\n    }\n\n    const expectedDids = [session.verificationMethod, this.sessionDid];\n    if (!expectedDids.some((did) => didPrincipalMatches(delegation.delegateDID, did))) {\n      throw new Error(\n        `Runtime delegation targets ${delegation.delegateDID} but this session key is ${session.verificationMethod}.`,\n      );\n    }\n\n    const targetHost = delegation.host ?? this.config.host!;\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      delegation.delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate runtime permission delegation: ${activateResult.error}`,\n      );\n    }\n\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) => grant.delegation.cid !== delegation.cid,\n    );\n    this.runtimePermissionGrants.push(\n      this.runtimeGrantFromDelegation(delegation, session),\n    );\n  }\n\n  /**\n   * Store additional permissions as narrow delegations to the current session\n   * key. Future service invocations automatically use a stored delegation when\n   * its `(space, service, path, action)` covers the request.\n   */\n  async grantRuntimePermissions(\n    permissions: PermissionEntry[],\n    options?: RuntimePermissionGrantOptions,\n  ): Promise<PortableDelegation[]> {\n    if (!Array.isArray(permissions) || permissions.length === 0) {\n      throw new Error(\"grantRuntimePermissions requires a non-empty permissions array\");\n    }\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n\n    const sessionExpiry = extractSiweExpiration(session.siwe);\n    if (sessionExpiry !== undefined) {\n      const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n      if (sessionExpiry.getTime() <= Date.now() + marginMs) {\n        throw new SessionExpiredError(sessionExpiry);\n      }\n    }\n\n    const expanded = this.expandPermissionEntries(permissions);\n    if (this.sessionCoversPermissionEntries(session, expanded)) {\n      return [];\n    }\n\n    const existingGrants = this.findRuntimeGrantsForPermissionEntries(expanded, session);\n    if (existingGrants.length > 0) {\n      return existingGrants.map((grant) => grant.delegation);\n    }\n    if (!this.signer) {\n      throw new Error(\n        \"grantRuntimePermissions requires wallet mode with a signer or privateKey.\",\n      );\n    }\n\n    const rawEntries = expanded.filter((entry) =>\n      this.isEncryptionPermissionEntry(entry)\n    );\n    const spaceEntries = expanded.filter((entry) =>\n      !this.isEncryptionPermissionEntry(entry)\n    );\n\n    const bySpace = new Map<string, PermissionEntry[]>();\n    for (const entry of spaceEntries) {\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      const current = bySpace.get(spaceId) ?? [];\n      current.push(entry);\n      bySpace.set(spaceId, current);\n    }\n    if (bySpace.size === 0 && rawEntries.length > 0) {\n      bySpace.set(session.spaceId, []);\n    }\n\n    const now = new Date();\n    const requestedExpiryMs = resolveExpiryMs(options?.expiry);\n    let expiresAt = new Date(now.getTime() + requestedExpiryMs);\n    if (sessionExpiry !== undefined && sessionExpiry < expiresAt) {\n      expiresAt = sessionExpiry;\n    }\n\n    const delegations: PortableDelegation[] = [];\n    let rawEntriesAttached = false;\n    for (const [spaceId, entries] of bySpace) {\n      const rawForDelegation = !rawEntriesAttached ? rawEntries : [];\n      if (rawForDelegation.length > 0) {\n        rawEntriesAttached = true;\n      }\n      const delegatedEntries = [...entries, ...rawForDelegation];\n      const abilities = this.permissionsToAbilities(entries);\n      const prepared = this.wasmBindings.prepareSession({\n        abilities,\n        ...(rawForDelegation.length > 0\n          ? { rawAbilities: this.permissionsToRawAbilities(rawForDelegation) }\n          : {}),\n        address: this.wasmBindings.ensureEip55(session.address),\n        chainId: session.chainId,\n        domain: this.siweDomain,\n        issuedAt: now.toISOString(),\n        expirationTime: expiresAt.toISOString(),\n        spaceId,\n        jwk: session.jwk,\n      });\n\n      const signature = await this.signer.signMessage(prepared.siwe);\n      const delegatedSession = this.wasmBindings.completeSessionSetup({\n        ...prepared,\n        signature,\n      });\n\n      const activateResult = await activateSessionWithHost(\n        this.config.host!,\n        delegatedSession.delegationHeader,\n      );\n      if (!activateResult.success) {\n        throw new Error(\n          `Failed to activate runtime permission delegation: ${activateResult.error}`,\n        );\n      }\n\n      const delegation = this.runtimeDelegationFromSession(\n        delegatedSession,\n        delegatedEntries,\n        spaceId,\n        session,\n        expiresAt,\n      );\n      this.runtimePermissionGrants.push({\n        session: {\n          delegationHeader: delegatedSession.delegationHeader,\n          delegationCid: delegatedSession.delegationCid,\n          spaceId,\n          verificationMethod: session.verificationMethod,\n          jwk: session.jwk,\n        },\n        delegation,\n        operations: this.permissionOperations(delegatedEntries, spaceId),\n        expiresAt,\n      });\n      delegations.push(delegation);\n    }\n\n    return delegations;\n  }\n\n  /**\n   * Get the DelegationManager for delegation CRUD operations.\n   *\n   * This is the v2 delegation service providing a cleaner API than\n   * the legacy createDelegation/useDelegation methods.\n   *\n   * @example\n   * ```typescript\n   * const delegations = alice.delegationManager;\n   *\n   * // Create a delegation\n   * const result = await delegations.create({\n   *   delegateDID: bob.did,\n   *   path: \"shared/\",\n   *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours\n   * });\n   *\n   * // List delegations\n   * const listResult = await delegations.list();\n   *\n   * // Revoke a delegation\n   * await delegations.revoke(delegationCid);\n   * ```\n   */\n  get delegationManager(): DelegationManager {\n    if (!this._delegationManager) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._delegationManager;\n  }\n\n  /**\n   * Get the SpaceService for managing spaces.\n   *\n   * The SpaceService provides access to owned and delegated spaces,\n   * including space creation, listing, and scoped operations.\n   *\n   * @example\n   * ```typescript\n   * const spaces = alice.spaces;\n   *\n   * // List all accessible spaces\n   * const result = await spaces.list();\n   *\n   * // Create a new space\n   * const createResult = await spaces.create('photos');\n   *\n   * // Get a space object for operations\n   * const mySpace = spaces.get('default');\n   * await mySpace.kv.put('key', 'value');\n   *\n   * // Check if a space exists\n   * const exists = await spaces.exists('photos');\n   * ```\n   */\n  get spaces(): ISpaceService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._spaceService;\n  }\n\n  /**\n   * Alias for `spaces` - get the SpaceService.\n   * @see spaces\n   */\n  get spaceService(): ISpaceService {\n    return this.spaces;\n  }\n\n  /**\n   * Get a Space object by short name or full URI.\n   */\n  space(nameOrUri: string): ISpace {\n    return this.spaces.get(nameOrUri);\n  }\n\n  /**\n   * Get the SharingService for creating and receiving v2 sharing links.\n   *\n   * The SharingService creates sharing links with embedded private keys,\n   * allowing recipients to exercise delegations without prior session setup.\n   *\n   * @example\n   * ```typescript\n   * const sharing = alice.sharing;\n   *\n   * // Generate a sharing link\n   * const result = await sharing.generate({\n   *   path: \"/kv/documents/report.pdf\",\n   *   actions: [\"tinycloud.kv/get\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),\n   * });\n   *\n   * if (result.ok) {\n   *   console.log(\"Share URL:\", result.data.url);\n   *   // Send the URL to the recipient\n   * }\n   *\n   * // Receive a sharing link\n   * const receiveResult = await sharing.receive(shareUrl);\n   * if (receiveResult.ok) {\n   *   // Use the pre-configured KV service\n   *   const data = await receiveResult.data.kv.get(\"report.pdf\");\n   * }\n   * ```\n   */\n  get sharing(): ISharingService {\n    // SharingService is initialized in constructor for receive-only access\n    // Full capabilities (generate) are added after signIn()\n    return this._sharingService;\n  }\n\n  /**\n   * Alias for `sharing` - get the SharingService.\n   * @see sharing\n   */\n  get sharingService(): ISharingService {\n    return this.sharing;\n  }\n\n  // ===========================================================================\n  // Public Space Methods\n  // ===========================================================================\n\n  /**\n   * Ensure the user's public space exists and is accessible.\n   * Creates the space and activates a session delegation for it.\n   * This is the trigger for lazy public space creation — call it\n   * before writing to spaces.get('public').kv.\n   */\n  async ensurePublicSpace() {\n    if (!this.auth || !this.session || !this.signer) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const publicSpaceId = this.session.spaces?.public;\n    if (!publicSpaceId) {\n      throw new Error(\"Public space not enabled. Set enablePublicSpace: true in config.\");\n    }\n\n    // Create the public space on the server (host SIWE)\n    await (this.auth as NodeUserAuthorization).hostPublicSpace(publicSpaceId);\n\n    // Create a session delegation for the public space using the session key JWK.\n    // This mirrors the primary session flow (prepareSession with jwk), ensuring\n    // the delegation targets the session key — not the PKH DID — so that\n    // invoke() requests signed by the session key are properly authorized.\n    const kvActions = [\n      \"tinycloud.kv/put\",\n      \"tinycloud.kv/get\",\n      \"tinycloud.kv/del\",\n      \"tinycloud.kv/list\",\n      \"tinycloud.kv/metadata\",\n    ];\n    const abilities = { kv: { \"\": kvActions } };\n    const now = new Date();\n    // EPHEMERAL tier — this sub-delegation is auto-derived from the\n    // session and re-issued whenever the SDK touches the public space,\n    // so a short lifetime bounds replay without forcing user re-prompts.\n    const expiryMs = EXPIRY.EPHEMERAL_MS;\n    const expirationTime = new Date(now.getTime() + expiryMs);\n\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(this.session.address),\n      chainId: this.session.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: publicSpaceId,\n      jwk: this.session.jwk,\n      parents: [this.session.delegationCid],\n    });\n\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    const delegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate public space delegation: ${activateResult.error}`);\n    }\n\n    // Register the delegation in the capability registry so\n    // spaces.get('public').kv operations are authorized\n    if (this._capabilityRegistry && this.session) {\n      const sessionKey: KeyInfo = {\n        id: this.session.sessionKey,\n        did: this.session.verificationMethod,\n        type: \"session\",\n        jwk: this.session.jwk as JWK,\n        priority: 0,\n      };\n      this._capabilityRegistry.registerKey(sessionKey, [{\n        cid: delegationSession.delegationCid,\n        delegateDID: this.session.verificationMethod,\n        spaceId: publicSpaceId,\n        path: \"\",\n        actions: kvActions,\n        expiry: expirationTime,\n        isRevoked: false,\n        allowSubDelegation: true,\n      }]);\n    }\n\n    // Cache a properly authorized public KV service using the new delegation\n    if (this._serviceContext) {\n      const publicKV = new KVService({ prefix: \"\" });\n      const publicContext = new ServiceContext({\n        invoke: this.invokeWithRuntimePermissions,\n        fetch: this._serviceContext.fetch,\n        hosts: this._serviceContext.hosts,\n        telemetry: this.config.telemetry,\n      });\n      publicContext.setSession({\n        delegationHeader: delegationSession.delegationHeader,\n        delegationCid: delegationSession.delegationCid,\n        spaceId: publicSpaceId,\n        verificationMethod: this.session.verificationMethod,\n        jwk: this.session.jwk,\n      });\n      publicKV.initialize(publicContext);\n      this._publicKV = publicKV;\n    }\n  }\n\n  /**\n   * Get a KVService scoped to the user's own public space.\n   * Writes require authentication (owner/delegate).\n   */\n  get publicKV(): IKVService {\n    if (this._publicKV) {\n      return this._publicKV;\n    }\n    if (!this.tc) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this.tc.publicKV;\n  }\n\n  // ===========================================================================\n  // v2 Delegation Convenience Methods\n  // ===========================================================================\n\n  /**\n   * Create a delegation using the v2 DelegationManager.\n   *\n   * This is a convenience method that wraps DelegationManager.create().\n   * For more control, use `this.delegationManager` directly.\n   *\n   * @param params - Delegation parameters\n   * @returns Result containing the created Delegation\n   *\n   * @example\n   * ```typescript\n   * const result = await alice.delegate({\n   *   delegateDID: bob.did,\n   *   path: \"shared/\",\n   *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),\n   * });\n   *\n   * if (result.ok) {\n   *   console.log(\"Delegation created:\", result.data.cid);\n   * }\n   * ```\n   */\n  async delegate(params: CreateDelegationParams): Promise<DelegationResult<Delegation>> {\n    return this.delegationManager.create(params);\n  }\n\n  /**\n   * Revoke a delegation using the v2 DelegationManager.\n   *\n   * @param cid - The CID of the delegation to revoke\n   * @returns Result indicating success or failure\n   */\n  async revokeDelegation(cid: string): Promise<DelegationResult<void>> {\n    return this.delegationManager.revoke(cid);\n  }\n\n  /**\n   * List all delegations for the current session's space.\n   *\n   * @returns Result containing an array of Delegations\n   */\n  async listDelegations(): Promise<DelegationResult<Delegation[]>> {\n    return this.delegationManager.list();\n  }\n\n  /**\n   * Check if the current session has permission for a path and action.\n   *\n   * @param path - The resource path to check\n   * @param action - The action to check (e.g., \"tinycloud.kv/get\")\n   * @returns Result containing boolean permission status\n   */\n  async checkPermission(path: string, action: string): Promise<DelegationResult<boolean>> {\n    return this.delegationManager.checkPermission(path, action);\n  }\n\n  // ===========================================================================\n  // Capability-chain delegation (spec: .claude/specs/capability-chain.md)\n  // ===========================================================================\n\n  /**\n   * Safety margin before the session's own expiry at which {@link delegateTo}\n   * will refuse to issue a derived delegation. Prevents issuing sub-delegations\n   * that would be invalid by the time the recipient used them. Spec: 60 seconds.\n   *\n   * @internal\n   */\n  private static readonly SESSION_EXPIRY_SAFETY_MARGIN_MS = 60_000;\n\n  /**\n   * Issue a delegation using the capability-chain flow.\n   *\n   * When every requested permission is a subset of the current\n   * session's recap, or of one installed runtime permission delegation,\n   * the delegation is signed by the session key via WASM — no wallet\n   * prompt. When at least one is NOT derivable, a\n   * {@link PermissionNotInManifestError} is raised (carrying the\n   * missing entries) so the caller can trigger an escalation flow\n   * (e.g. `TinyCloudWeb.requestPermissions`). Passing\n   * `forceWalletSign: true` bypasses the derivability check and\n   * always uses the wallet-signed SIWE path — used by the legacy\n   * `createDelegation` fallback and by callers that want explicit\n   * wallet confirmation.\n   *\n   * Multi-entry delegations are now emitted as **one** signed UCAN:\n   * the underlying WASM `createDelegation` takes a full\n   * `HashMap<Service, HashMap<Path, Vec<Ability>>>` abilities map\n   * and produces a single attenuation carrying every\n   * `(service, path, actions)` entry. The returned\n   * {@link DelegateToResult.delegation} is that single blob, and\n   * apps can POST it to their backend exactly like a single-entry\n   * delegation (the server verifies all granted resources from one\n   * UCAN).\n   *\n   * For single-entry requests the `PortableDelegation.path` and\n   * `.actions` fields mirror the one granted entry. For\n   * multi-entry requests they mirror the **first** entry (stable\n   * lexicographic order from the Rust side); consumers that need\n   * the full picture read `PortableDelegation.resources`.\n   *\n   * @throws {@link SessionExpiredError} when there is no session or\n   *   the current session has expired (or will within the 60s\n   *   safety margin).\n   * @throws {@link PermissionNotInManifestError} when any requested\n   *   entry is not a subset of the granted session capabilities and\n   *   `forceWalletSign` is not set.\n   */\n  async delegateTo(\n    did: string,\n    permissions: PermissionEntry[],\n    options?: DelegateToOptions,\n  ): Promise<DelegateToResult> {\n    // 1. Session validity check — fail fast with a clear error class so\n    //    callers can catch and trigger a fresh sign-in.\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n    const sessionExpiry = extractSiweExpiration(session.siwe);\n    if (sessionExpiry !== undefined) {\n      const now = Date.now();\n      const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n      if (sessionExpiry.getTime() <= now + marginMs) {\n        throw new SessionExpiredError(sessionExpiry);\n      }\n    }\n\n    // 2. Input validation. Empty arrays and non-arrays both fail here so\n    //    downstream code can safely assume at least one entry.\n    if (!Array.isArray(permissions) || permissions.length === 0) {\n      throw new Error(\n        \"delegateTo requires a non-empty permissions array\",\n      );\n    }\n\n    // 3. Defensively expand any short-form action names into full URNs\n    //    for every entry so the subset check and downstream WASM call\n    //    both see canonical form. This also deep-copies the entries so\n    //    we don't mutate caller-owned data.\n    const expandedEntries = this.expandPermissionEntries(permissions);\n\n    // 4. Compute expiration. `options.expiry` overrides the default 1h.\n    //    ms-format (\"7d\") or raw millisecond count both accepted. Cap\n    //    at the session's own expiry so we never emit a UCAN whose\n    //    validity exceeds the parent chain.\n    const now = new Date();\n    const expiryMs = resolveExpiryMs(options?.expiry);\n    const expirationTime = new Date(now.getTime() + expiryMs);\n    let effectiveExpiration = expirationTime;\n    if (sessionExpiry !== undefined && sessionExpiry < expirationTime) {\n      effectiveExpiration = sessionExpiry;\n    }\n\n    // 5. forceWalletSign short-circuit → always legacy path. The\n    //    legacy wallet path currently handles one `(space, path)` at\n    //    a time, so we only support single-entry when forced. Callers\n    //    that need multi-entry wallet-signed delegations should issue\n    //    them via the legacy `createDelegation` which loops internally\n    //    (or just not pass `forceWalletSign: true`).\n    if (options?.forceWalletSign) {\n      if (expandedEntries.length > 1) {\n        throw new Error(\n          \"delegateTo with forceWalletSign=true supports at most one \" +\n            \"PermissionEntry. Multi-entry requests must go through the \" +\n            \"session-key UCAN path (drop forceWalletSign) or the legacy \" +\n            \"createDelegation method.\",\n        );\n      }\n      const delegation = await this.createDelegationLegacyWalletPath(\n        did,\n        expandedEntries[0],\n        effectiveExpiration,\n      );\n      return { delegation, prompted: true };\n    }\n\n    // 6. Derivability check across ALL entries. If any entry is not a\n    //    subset of the granted session capabilities, the whole call\n    //    fails with a typed error carrying the missing entries — we do\n    //    NOT partially issue and drop the failing ones, because that\n    //    would produce a delegation the caller didn't ask for.\n    //\n    //    `parseRecapCapabilities` is a thin wrapper around the\n    //    injected WASM binding; the binding is required because\n    //    `IWasmBindings` declares `parseRecapFromSiwe` as mandatory.\n    //    If the runtime binding hasn't been updated, this call will\n    //    surface a clear TypeError rather than silently falling\n    //    through.\n    const granted = parseRecapCapabilities(\n      (siwe: string) => this.wasmBindings.parseRecapFromSiwe(siwe),\n      session.siwe,\n    );\n    const { subset, missing } = isCapabilitySubset(expandedEntries, granted);\n\n    if (!subset) {\n      const runtimeGrant = this.findGrantForOperations(\n        this.permissionEntriesToOperations(expandedEntries, session),\n      );\n      if (runtimeGrant) {\n        const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n        if (runtimeGrant.expiresAt.getTime() <= Date.now() + marginMs) {\n          throw new SessionExpiredError(runtimeGrant.expiresAt);\n        }\n        const runtimeExpiration =\n          runtimeGrant.expiresAt < effectiveExpiration\n            ? runtimeGrant.expiresAt\n            : effectiveExpiration;\n        const delegation = await this.createDelegationViaRuntimeGrant(\n          did,\n          expandedEntries,\n          runtimeExpiration,\n          runtimeGrant,\n        );\n        return { delegation, prompted: false };\n      }\n      throw new PermissionNotInManifestError(missing, granted);\n    }\n\n    // 7. Subset path — sign ONE sub-delegation with the session key\n    //    via WASM that carries every requested entry. No wallet\n    //    prompt. `createDelegationViaWasmPath` builds the\n    //    multi-resource abilities map and returns a single\n    //    PortableDelegation whose `.resources` field lists every\n    //    granted entry.\n    const delegation = await this.createDelegationViaWasmPath(\n      did,\n      expandedEntries,\n      effectiveExpiration,\n      session,\n    );\n    return { delegation, prompted: false };\n  }\n\n  /**\n   * Materialize one manifest-declared delegation using the current session key.\n   * Delivery is intentionally out of band; callers decide how to transmit the\n   * returned UCAN to the delegate.\n   */\n  async materializeDelegation(\n    did: string,\n    request: ComposedManifestRequest | undefined = this.capabilityRequest,\n  ): Promise<DelegateToResult & { target: ResolvedDelegate }> {\n    if (!request) {\n      throw new Error(\n        \"materializeDelegation requires a composed manifest request\",\n      );\n    }\n    const target = request.delegationTargets.find((entry) =>\n      didPrincipalMatches(entry.did, did),\n    );\n    if (!target) {\n      throw new Error(`No manifest delegation target found for DID ${did}`);\n    }\n    const result = await this.delegateTo(target.did, target.permissions, {\n      expiry: target.expiryMs,\n    });\n    return { ...result, target };\n  }\n\n  /**\n   * Materialize every delegation target declared by the composed manifest\n   * request. This does not deliver the delegations anywhere.\n   */\n  async materializeDelegations(\n    request: ComposedManifestRequest | undefined = this.capabilityRequest,\n  ): Promise<Array<DelegateToResult & { target: ResolvedDelegate }>> {\n    if (!request) {\n      throw new Error(\n        \"materializeDelegations requires a composed manifest request\",\n      );\n    }\n    const out: Array<DelegateToResult & { target: ResolvedDelegate }> = [];\n    for (const target of request.delegationTargets) {\n      out.push(await this.materializeDelegation(target.did, request));\n    }\n    return out;\n  }\n\n  /**\n   * Issue a delegation via the session-key UCAN WASM path.\n   *\n   * The caller has already verified every entry is derivable from\n   * the current session; we build one multi-resource abilities map\n   * and emit one signed UCAN covering them all.\n   *\n   * Non-encryption entries must share the same target space. Encryption\n   * entries are raw network URNs and do not participate in space grouping.\n   *\n   * @internal\n   */\n  private async createDelegationViaWasmPath(\n    did: string,\n    entries: PermissionEntry[],\n    expirationTime: Date,\n    session: TinyCloudSession,\n  ): Promise<PortableDelegation> {\n    if (entries.length === 0) {\n      throw new Error(\n        \"createDelegationViaWasmPath requires a non-empty entries array\",\n      );\n    }\n\n    // Translate non-raw manifest `space` fields into the server-side\n    // spaceId. Encryption entries target raw network URNs, not spaces.\n    const resolvedSpaces = new Set<string>();\n    for (const entry of entries) {\n      if (this.isEncryptionPermissionEntry(entry)) {\n        continue;\n      }\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      resolvedSpaces.add(spaceId);\n    }\n    if (resolvedSpaces.size > 1) {\n      throw new Error(\n        `delegateTo: all permission entries must target the same space, got ${resolvedSpaces.size}: ${JSON.stringify([...resolvedSpaces])}`,\n      );\n    }\n    const spaceId = resolvedSpaces.size === 1\n      ? [...resolvedSpaces][0]\n      : session.spaceId;\n\n    // Convert entries to the WASM abilities shape. Each entry's\n    // `service` is the long form (e.g. \"tinycloud.kv\") which we\n    // translate to the short form keyed by the abilities map. Raw\n    // encryption network entries stay in this map because the Rust\n    // create_delegation boundary special-cases network URNs into raw\n    // resources while preserving the legacy spaceId parameter.\n    // Multiple entries on the same (service, path) merge and dedupe\n    // their action lists — unusual in practice (the subset check\n    // should have pruned dupes already) but cheap and safe.\n    const abilities: AbilitiesMap = {};\n    for (const entry of entries) {\n      const shortService = SERVICE_LONG_TO_SHORT[entry.service];\n      if (shortService === undefined) {\n        throw new Error(\n          `delegateTo: unknown service '${entry.service}' — no short-form mapping`,\n        );\n      }\n      if (abilities[shortService] === undefined) {\n        abilities[shortService] = {};\n      }\n      const pathsMap = abilities[shortService];\n      const existing = pathsMap[entry.path];\n      if (existing === undefined) {\n        pathsMap[entry.path] = [...entry.actions];\n      } else {\n        const seen = new Set(existing);\n        for (const action of entry.actions) {\n          if (!seen.has(action)) {\n            existing.push(action);\n            seen.add(action);\n          }\n        }\n      }\n    }\n\n    // Build ServiceSession from TinyCloudSession. This mirrors how\n    // SharingService hands sessions to createDelegationWrapper.\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      jwk: session.jwk,\n      spaceId,\n      verificationMethod: session.verificationMethod,\n    };\n\n    const expirationSecs = Math.floor(expirationTime.getTime() / 1000);\n    const result = this.createDelegationWrapper({\n      session: serviceSession,\n      delegateDID: did,\n      spaceId,\n      abilities,\n      expirationSecs,\n    });\n\n    // Translate the WASM result into a PortableDelegation. We don't\n    // have a structured delegation header from the WASM path, so we\n    // synthesize one from the serialized delegation (the recipient\n    // decodes it via `deserializeDelegation`).\n    //\n    // The flat `.path` and `.actions` fields mirror the first\n    // resource — stable because the Rust side sorts by\n    // (service, path) before signing. Consumers that need the full\n    // multi-resource picture read `.resources`.\n    const primary = result.resources[0];\n    // Use the raw JWT without a \"Bearer \" prefix. The host's HeaderEncode\n    // decoder passes the header value directly to Ucan::decode(), which\n    // expects a bare JWT string. The wallet-signed CACAO path also uses\n    // raw base64 without any prefix. Adding \"Bearer \" causes a parse\n    // failure that surfaces as a 401 from the host.\n    const delegationHeader = { Authorization: result.delegation };\n\n    // Activate the delegation with the host so downstream consumers (e.g.\n    // a backend calling useDelegation) can find it by CID when building\n    // their invoker SIWE. The host validates the UCAN's parent chain\n    // (session key → wallet SIWE) to confirm authority.\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate delegation with host: ${activateResult.error}`,\n      );\n    }\n\n    return {\n      cid: result.cid,\n      delegationHeader,\n      spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources: result.resources,\n      disableSubDelegation: false,\n      expiry: result.expiry,\n      delegateDID: did,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n  }\n\n  private async createDelegationViaRuntimeGrant(\n    did: string,\n    entries: PermissionEntry[],\n    expirationTime: Date,\n    grant: RuntimePermissionGrant,\n  ): Promise<PortableDelegation> {\n    const result = this.createDelegationWrapper({\n      session: grant.session,\n      delegateDID: did,\n      spaceId: grant.session.spaceId,\n      abilities: this.permissionsToAbilities(entries),\n      expirationSecs: Math.floor(expirationTime.getTime() / 1000),\n    });\n\n    const primary = result.resources[0];\n    const delegationHeader = { Authorization: result.delegation };\n    const targetHost = grant.delegation.host ?? this.config.host!;\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate delegation with host: ${activateResult.error}`,\n      );\n    }\n\n    return {\n      cid: result.cid,\n      delegationHeader,\n      spaceId: grant.session.spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources: result.resources,\n      disableSubDelegation: false,\n      expiry: result.expiry,\n      delegateDID: did,\n      ownerAddress: grant.delegation.ownerAddress,\n      chainId: grant.delegation.chainId,\n      host: targetHost,\n    };\n  }\n\n  private resolvePermissionSpace(\n    space: string | undefined,\n    session: TinyCloudSession,\n  ): string {\n    if (space === undefined) {\n      return this.wasmBindings.makeSpaceId(\n        session.address,\n        session.chainId,\n        \"applications\",\n      );\n    }\n    if (space === \"default\") {\n      return session.spaceId;\n    }\n    if (space.startsWith(\"tinycloud:\")) {\n      return space;\n    }\n    return this.wasmBindings.makeSpaceId(session.address, session.chainId, space);\n  }\n\n  private expandPermissionEntries(\n    permissions: PermissionEntry[],\n  ): PermissionEntry[] {\n    return expandPermissionEntriesCore(permissions);\n  }\n\n  private shortServiceName(service: string): string {\n    const short = SERVICE_LONG_TO_SHORT[service];\n    if (short === undefined) {\n      throw new Error(\n        `unknown service '${service}' — no short-form mapping`,\n      );\n    }\n    return short;\n  }\n\n  private permissionsToAbilities(entries: PermissionEntry[]): AbilitiesMap {\n    const abilities: AbilitiesMap = {};\n    for (const entry of entries) {\n      const service = this.shortServiceName(entry.service);\n      abilities[service] ??= {};\n      const existing = abilities[service][entry.path] ?? [];\n      const seen = new Set(existing);\n      for (const action of entry.actions) {\n        if (!seen.has(action)) {\n          existing.push(action);\n          seen.add(action);\n        }\n      }\n      abilities[service][entry.path] = existing;\n    }\n    return abilities;\n  }\n\n  private isEncryptionPermissionEntry(entry: PermissionEntry): boolean {\n    return entry.service === ENCRYPTION_PERMISSION_SERVICE &&\n      entry.path.startsWith(\"urn:tinycloud:encryption:\");\n  }\n\n  private permissionsToRawAbilities(\n    entries: PermissionEntry[],\n  ): Record<string, string[]> {\n    const rawAbilities: Record<string, string[]> = {};\n    for (const entry of entries) {\n      if (!this.isEncryptionPermissionEntry(entry)) {\n        continue;\n      }\n      const existing = rawAbilities[entry.path] ?? [];\n      const seen = new Set(existing);\n      for (const action of entry.actions) {\n        if (!seen.has(action)) {\n          existing.push(action);\n          seen.add(action);\n        }\n      }\n      rawAbilities[entry.path] = existing;\n    }\n    return rawAbilities;\n  }\n\n  private permissionOperations(\n    entries: PermissionEntry[],\n    spaceId: string,\n  ): RuntimePermissionOperation[] {\n    return entries.flatMap((entry) => {\n      const service = this.shortServiceName(entry.service);\n      return entry.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, entry.path)\n          ? { resource: entry.path }\n          : { spaceId }),\n        service,\n        path: entry.path,\n        action,\n      }));\n    });\n  }\n\n  private sessionCoversPermissionEntries(\n    session: TinyCloudSession,\n    entries: PermissionEntry[],\n  ): boolean {\n    try {\n      const granted = parseRecapCapabilities(\n        (siwe: string) => this.wasmBindings.parseRecapFromSiwe(siwe),\n        session.siwe,\n      );\n      return isCapabilitySubset(entries, granted).subset;\n    } catch {\n      return false;\n    }\n  }\n\n  private permissionEntriesToOperations(\n    entries: PermissionEntry[],\n    session: TinyCloudSession,\n  ): RuntimePermissionOperation[] {\n    return entries.flatMap((entry) => {\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      const service = this.shortServiceName(entry.service);\n      return entry.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, entry.path)\n          ? { resource: entry.path }\n          : { spaceId }),\n        service,\n        path: entry.path,\n        action,\n      }));\n    });\n  }\n\n  private findRuntimeGrantsForPermissionEntries(\n    entries: PermissionEntry[],\n    session: TinyCloudSession,\n  ): RuntimePermissionGrant[] {\n    const grants: RuntimePermissionGrant[] = [];\n    const operations = this.permissionEntriesToOperations(entries, session);\n    if (operations.length === 0) {\n      return grants;\n    }\n\n    for (const operation of operations) {\n      const grant = this.findGrantForOperation(operation);\n      if (!grant) {\n        return [];\n      }\n      if (!grants.includes(grant)) {\n        grants.push(grant);\n      }\n    }\n    return grants;\n  }\n\n  private runtimeDelegationFromSession(\n    delegatedSession: {\n      delegationHeader: { Authorization: string };\n      delegationCid: string;\n    },\n    entries: PermissionEntry[],\n    spaceId: string,\n    session: TinyCloudSession,\n    expiresAt: Date,\n  ): PortableDelegation {\n    const resources = this.delegatedResourcesForEntries(entries, spaceId);\n    const primary = resources[0];\n    return {\n      cid: delegatedSession.delegationCid,\n      delegationHeader: delegatedSession.delegationHeader,\n      spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources,\n      disableSubDelegation: false,\n      expiry: expiresAt,\n      delegateDID: session.verificationMethod,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n  }\n\n  private runtimeGrantFromDelegation(\n    delegation: PortableDelegation,\n    session: TinyCloudSession,\n  ): RuntimePermissionGrant {\n    const operations = this.operationsFromDelegation(delegation);\n    return {\n      session: {\n        delegationHeader: delegation.delegationHeader,\n        delegationCid: delegation.cid,\n        spaceId: delegation.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      delegation,\n      operations,\n      expiresAt: delegation.expiry,\n    };\n  }\n\n  private installRuntimeGrantFromServiceSession(\n    delegation: PortableDelegation,\n    session: ServiceSession,\n    expiresAt: Date,\n  ): void {\n    const operations = this.operationsFromDelegation(delegation);\n    if (operations.length === 0) {\n      return;\n    }\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) =>\n        grant.delegation.cid !== delegation.cid &&\n        grant.session.delegationCid !== session.delegationCid,\n    );\n    this.runtimePermissionGrants.push({\n      session,\n      delegation,\n      operations,\n      expiresAt,\n    });\n  }\n\n  private delegatedResourcesForEntries(\n    entries: PermissionEntry[],\n    spaceId: string,\n  ): DelegatedResource[] {\n    return entries.map((entry) => ({\n      service: this.shortServiceName(entry.service),\n      space: this.isEncryptionPermissionEntry(entry) ? \"encryption\" : spaceId,\n      path: entry.path,\n      actions: [...entry.actions],\n    }));\n  }\n\n  private operationsFromDelegation(\n    delegation: PortableDelegation,\n  ): RuntimePermissionOperation[] {\n    const resources =\n      delegation.resources !== undefined && delegation.resources.length > 0\n        ? delegation.resources\n        : this.flatDelegationResources(delegation);\n\n    return resources.flatMap((resource) => {\n      const service = this.invocationServiceName(resource.service);\n      return resource.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, resource.path)\n          ? { resource: resource.path }\n          : { spaceId: resource.space }),\n        service,\n        path: resource.path,\n        action,\n      }));\n    });\n  }\n\n  private flatDelegationResources(\n    delegation: PortableDelegation,\n  ): DelegatedResource[] {\n    const byService = new Map<string, string[]>();\n    for (const action of delegation.actions) {\n      const service = this.shortServiceName(action.split(\"/\")[0]);\n      const actions = byService.get(service) ?? [];\n      actions.push(action);\n      byService.set(service, actions);\n    }\n    return [...byService.entries()].map(([service, actions]) => ({\n      service,\n      space: delegation.spaceId,\n      path: delegation.path,\n      actions,\n    }));\n  }\n\n  /**\n   * Build the abilities/rawAbilities maps for a wallet-mode activation\n   * sub-delegation from the FULL resource set of a received delegation.\n   *\n   * Each entry in `delegation.resources[]` is one `(service, space, path,\n   * actions)` grant; the flat top-level `path`/`actions` mirror only the\n   * first resource. We must reconstruct every grant so the activated\n   * session carries all of them (e.g. both `tinycloud.kv/get` and\n   * `tinycloud.encryption/decrypt`) — not just the primary one.\n   *\n   * Encryption resources are raw network URNs (space-independent) and go\n   * into `rawAbilities`. All other resources are space-scoped and go into\n   * `abilities` keyed by short service name. The activation `prepareSession`\n   * call uses a single `spaceId` (`delegation.spaceId`), so every\n   * non-encryption resource must target that same space — which is exactly\n   * what the multi-resource issuance path enforces. A resource targeting a\n   * different space cannot be activated in one call, so we fail loudly\n   * rather than silently dropping it.\n   *\n   * @internal\n   */\n  private buildActivationAbilities(delegation: PortableDelegation): {\n    abilities: Record<string, Record<string, string[]>>;\n    rawAbilities: Record<string, string[]>;\n  } {\n    const resources =\n      delegation.resources !== undefined && delegation.resources.length > 0\n        ? delegation.resources\n        : this.flatDelegationResources(delegation);\n\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const rawAbilities: Record<string, string[]> = {};\n\n    const addActions = (target: string[], actions: string[]): void => {\n      const seen = new Set(target);\n      for (const action of actions) {\n        if (!seen.has(action)) {\n          target.push(action);\n          seen.add(action);\n        }\n      }\n    };\n\n    for (const resource of resources) {\n      const service = this.invocationServiceName(resource.service);\n      if (this.isEncryptionNetworkOperation(service, resource.path)) {\n        rawAbilities[resource.path] ??= [];\n        addActions(rawAbilities[resource.path], resource.actions);\n        continue;\n      }\n\n      if (resource.space !== delegation.spaceId) {\n        throw new Error(\n          `useDelegation: resource targets space '${resource.space}' but the ` +\n            `delegation activates space '${delegation.spaceId}'. Multi-space ` +\n            `delegations cannot be activated in a single useDelegation call.`,\n        );\n      }\n\n      abilities[service] ??= {};\n      abilities[service][resource.path] ??= [];\n      addActions(abilities[service][resource.path], resource.actions);\n    }\n\n    return { abilities, rawAbilities };\n  }\n\n  private selectInvocationSession(\n    fallback: ServiceSession,\n    service: string,\n    path: string,\n    action: string,\n  ): ServiceSession {\n    const grant = this.findGrantForOperation({\n      spaceId: fallback.spaceId,\n      service: this.invocationServiceName(service),\n      path,\n      action,\n    });\n    return grant?.session ?? fallback;\n  }\n\n  private findGrantForOperations(\n    operations: RuntimePermissionOperation[],\n  ): RuntimePermissionGrant | undefined {\n    if (operations.length === 0) {\n      return undefined;\n    }\n    this.pruneExpiredRuntimePermissionGrants();\n    return this.runtimePermissionGrants.find((grant) => {\n      return operations.every((operation) =>\n        grant.operations.some((granted) =>\n          this.operationCovers(granted, operation),\n        ),\n      );\n    });\n  }\n\n  private findGrantForOperation(\n    operation: RuntimePermissionOperation,\n  ): RuntimePermissionGrant | undefined {\n    return this.findGrantForOperations([operation]);\n  }\n\n  private pruneExpiredRuntimePermissionGrants(): void {\n    const now = Date.now();\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) => grant.expiresAt.getTime() > now,\n    );\n  }\n\n  private operationCovers(\n    granted: RuntimePermissionOperation,\n    requested: RuntimePermissionOperation,\n  ): boolean {\n    if (granted.service !== requested.service ||\n      !this.actionContains(granted.action, requested.action)\n    ) {\n      return false;\n    }\n\n    if (granted.resource !== undefined || requested.resource !== undefined) {\n      return granted.resource !== undefined &&\n        requested.resource !== undefined &&\n        granted.resource === requested.resource &&\n        this.pathContains(granted.path, requested.path);\n    }\n\n    return granted.spaceId !== undefined &&\n      requested.spaceId !== undefined &&\n      this.spaceIdsEqual(granted.spaceId, requested.spaceId) &&\n      this.pathContains(granted.path, requested.path);\n  }\n\n  // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. The embedded\n  // EIP-155 address is case-insensitive, but the CLI canonicalizes it to\n  // lowercase when building a space URI while stored runtime delegations keep\n  // the EIP-55 checksummed form — so a byte-for-byte compare spuriously rejects\n  // an otherwise-valid grant. Lowercase ONLY the `eip155:<chain>:0x<addr>`\n  // segment and leave everything else (crucially the case-sensitive space NAME)\n  // byte-exact. Mirrors the CLI's `normalizeSpaceForCompare` (OPENKEY_SCOPE_MISMATCH fix).\n  private spaceIdsEqual(a: string, b: string): boolean {\n    return this.normalizeSpaceAddress(a) === this.normalizeSpaceAddress(b);\n  }\n\n  private normalizeSpaceAddress(space: string): string {\n    return space.replace(\n      /(eip155:\\d+:)(0x[0-9a-fA-F]{40})/,\n      (_match, prefix: string, addr: string) => prefix + addr.toLowerCase(),\n    );\n  }\n\n  private actionContains(grantedAction: string, requestedAction: string): boolean {\n    if (grantedAction === requestedAction) {\n      return true;\n    }\n    if (grantedAction.endsWith(\"/*\")) {\n      const prefix = grantedAction.slice(0, -2);\n      return requestedAction.startsWith(`${prefix}/`);\n    }\n    return false;\n  }\n\n  private invocationServiceName(service: string): string {\n    return service.startsWith(\"tinycloud.\")\n      ? this.shortServiceName(service)\n      : service;\n  }\n\n  private isEncryptionNetworkOperation(service: string, path: string): boolean {\n    return service === \"encryption\" &&\n      path.startsWith(\"urn:tinycloud:encryption:\");\n  }\n\n  private operationFromInvokeAnyEntry(entry: {\n    spaceId?: string;\n    resource?: string;\n    service: string;\n    path: string;\n    action: string;\n  }): RuntimePermissionOperation | undefined {\n    const service = this.invocationServiceName(entry.service);\n    if (typeof entry.resource === \"string\") {\n      return {\n        resource: entry.resource,\n        service,\n        path: entry.path,\n        action: entry.action,\n      };\n    }\n    if (this.isEncryptionNetworkOperation(service, entry.path)) {\n      return {\n        resource: entry.path,\n        service,\n        path: entry.path,\n        action: entry.action,\n      };\n    }\n    if (typeof entry.spaceId === \"string\") {\n      return {\n        spaceId: entry.spaceId,\n        service,\n        path: entry.path,\n        action: entry.action,\n      };\n    }\n    return undefined;\n  }\n\n  private pathContains(grantedPath: string, requestedPath: string): boolean {\n    if (grantedPath === \"\" || grantedPath === \"/\") {\n      return true;\n    }\n    if (grantedPath.endsWith(\"/**\")) {\n      return requestedPath.startsWith(grantedPath.slice(0, -3));\n    }\n    if (grantedPath.endsWith(\"/*\")) {\n      const prefix = grantedPath.slice(0, -2);\n      if (!requestedPath.startsWith(prefix)) {\n        return false;\n      }\n      const remainder = requestedPath.slice(prefix.length);\n      return !remainder.includes(\"/\") || remainder === \"/\";\n    }\n    if (grantedPath.endsWith(\"/\")) {\n      return requestedPath.startsWith(grantedPath);\n    }\n    return grantedPath === requestedPath;\n  }\n\n  /**\n   * Issue a delegation via the legacy wallet-signed SIWE path for a single\n   * {@link PermissionEntry}. Shares the implementation with the public\n   * `createDelegation` method via {@link createDelegationWalletPath} so\n   * both entry points hit exactly the same SIWE / signer / public-space\n   * logic without mutual recursion.\n   *\n   * @internal\n   */\n  private async createDelegationLegacyWalletPath(\n    delegateDID: string,\n    entry: PermissionEntry,\n    expirationTime: Date,\n  ): Promise<PortableDelegation> {\n    const session = this.auth?.tinyCloudSession;\n    const spaceIdOverride =\n      session === undefined || entry.space === \"default\"\n        ? undefined\n        : this.resolvePermissionSpace(entry.space, session);\n    return this.createDelegationWalletPath({\n      path: entry.path,\n      actions: entry.actions,\n      delegateDID,\n      includePublicSpace: true,\n      expiryMs: Math.max(0, expirationTime.getTime() - Date.now()),\n      spaceIdOverride,\n    });\n  }\n\n  /**\n   * Create a delegation from this user to another user.\n   *\n   * The delegation grants the recipient access to a specific path and actions\n   * within this user's space.\n   *\n   * @param params - Delegation parameters\n   * @returns A portable delegation that can be sent to the recipient\n   */\n  async createDelegation(params: {\n    /** Path within the space to delegate access to */\n    path: string;\n    /** Actions to allow (e.g., [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]) */\n    actions: string[];\n    /** DID of the recipient (from their TinyCloudNode.did) */\n    delegateDID: string;\n    /** Whether to prevent the recipient from creating sub-delegations (default: false) */\n    disableSubDelegation?: boolean;\n    /** Expiration time in milliseconds from now (default: 1 hour) */\n    expiryMs?: number;\n    /** Override space ID (for creating delegations to non-primary spaces like public) */\n    spaceIdOverride?: string;\n    /** Include a companion delegation for the user's public space (default: true) */\n    includePublicSpace?: boolean;\n  }): Promise<PortableDelegation> {\n    // Legacy compatibility shim.\n    //\n    // Route through delegateTo so that callers whose requested capabilities\n    // are a subset of their current session get the session-key UCAN path\n    // (no wallet prompt). Fall back to the legacy wallet-sign path on\n    // PermissionNotInManifestError, preserving today's behaviour for\n    // callers that request scope outside their session.\n    //\n    // SessionExpiredError propagates — an expired session can't be fixed\n    // by re-signing the SIWE, the caller needs to run signIn() again.\n    if (!this.signer) {\n      throw new Error(\"Cannot createDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    if (!this.auth?.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Resolve ENS names to PKH DIDs up front so both paths see the resolved\n    // DID. The wallet path mutates params further below; we do it here so\n    // the fast path (delegateTo) also picks up the resolved DID.\n    let resolvedDelegateDID = params.delegateDID;\n    if (resolvedDelegateDID.endsWith('.eth') && this.config.ensResolver) {\n      const address = await this.config.ensResolver.resolveAddress(resolvedDelegateDID);\n      if (!address) throw new Error(`Could not resolve ENS name: ${resolvedDelegateDID}`);\n      resolvedDelegateDID = pkhDid(address, 1);\n    }\n\n    // Legacy params lump multiple services' actions under one path. We\n    // now emit ONE multi-resource UCAN for any number of entries via\n    // the fast path, so there's no longer a \"single-entry only\" gate\n    // here — the fast path handles N entries and returns a single\n    // PortableDelegation whose `.resources` describes the full set.\n    //\n    // Fall back to the wallet path when the capabilities aren't\n    // derivable from the current session (PermissionNotInManifestError)\n    // so legacy callers requesting scope outside their session continue\n    // to see a wallet prompt, matching today's behaviour.\n    const entries = legacyParamsToPermissionEntries(\n      params.actions,\n      params.path,\n      params.spaceIdOverride,\n    );\n    try {\n      const result = await this.delegateTo(\n        resolvedDelegateDID,\n        entries,\n        params.expiryMs !== undefined ? { expiry: params.expiryMs } : undefined,\n      );\n      return result.delegation;\n    } catch (err) {\n      if (err instanceof PermissionNotInManifestError) {\n        // Expected — fall through to the wallet path below. Legacy\n        // callers that request scope outside their current session\n        // continue to see a wallet prompt, matching today's behaviour.\n      } else {\n        // SessionExpiredError and any other error class must propagate.\n        // An expired session can't be rescued by re-signing the SIWE\n        // here — the caller needs to run signIn() again.\n        throw err;\n      }\n    }\n\n    // Legacy wallet-signed SIWE path — same implementation as before the\n    // delegateTo refactor. Callers that request scope outside their\n    // current session land here and see the familiar wallet prompt.\n    return this.createDelegationWalletPath({\n      ...params,\n      delegateDID: resolvedDelegateDID,\n    });\n  }\n\n  /**\n   * Legacy wallet-signed SIWE delegation path. Lifted from the original\n   * `createDelegation` body verbatim so both the legacy public method and\n   * `delegateTo({ forceWalletSign: true })` hit the same code.\n   *\n   * @internal\n   */\n  private async createDelegationWalletPath(params: {\n    path: string;\n    actions: string[];\n    delegateDID: string;\n    disableSubDelegation?: boolean;\n    expiryMs?: number;\n    spaceIdOverride?: string;\n    includePublicSpace?: boolean;\n  }): Promise<PortableDelegation> {\n    if (!this.signer) {\n      throw new Error(\"Cannot createDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    const session = this.auth?.tinyCloudSession;\n    if (!session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Build abilities for the delegation\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const kvActions = params.actions.filter(a => a.startsWith(\"tinycloud.kv/\"));\n    const sqlActions = params.actions.filter(a => a.startsWith(\"tinycloud.sql/\"));\n    const duckdbActions = params.actions.filter(a => a.startsWith(\"tinycloud.duckdb/\"));\n    if (kvActions.length > 0) {\n      abilities.kv = { [params.path]: kvActions };\n    }\n    if (sqlActions.length > 0) {\n      abilities.sql = { [params.path]: sqlActions };\n    }\n    if (duckdbActions.length > 0) {\n      abilities.duckdb = { [params.path]: duckdbActions };\n    }\n\n    const now = new Date();\n    const expiryMs = params.expiryMs ?? 60 * 60 * 1000; // Default 1 hour\n    const expirationTime = new Date(now.getTime() + expiryMs);\n\n    // Prepare the delegation session with:\n    // - delegateUri: target the recipient's DID directly (for user-to-user delegation)\n    // - parents: reference our session CID for chain validation\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(session.address),\n      chainId: session.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: params.spaceIdOverride ?? session.spaceId,\n      delegateUri: params.delegateDID,\n      parents: [session.delegationCid],\n    });\n\n    // Sign the SIWE message with this user's signer\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const delegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate the delegation with the server\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate delegation: ${activateResult.error}`);\n    }\n\n    const result: PortableDelegation = {\n      cid: delegationSession.delegationCid,\n      delegationHeader: delegationSession.delegationHeader,\n      spaceId: params.spaceIdOverride ?? session.spaceId,\n      path: params.path,\n      actions: params.actions,\n      disableSubDelegation: params.disableSubDelegation ?? false,\n      expiry: expirationTime,\n      delegateDID: params.delegateDID,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n\n    // Auto-create public-space delegation for vault key publishing\n    const hasKvActions = params.actions.some(a => a.startsWith(\"tinycloud.kv/\"));\n    if (hasKvActions && params.includePublicSpace !== false) {\n      const publicSpaceId = makePublicSpaceId(\n        this.wasmBindings.ensureEip55(session.address), session.chainId\n      );\n      const publicAbilities: Record<string, Record<string, string[]>> = {\n        kv: { \"\": [\"tinycloud.kv/get\", \"tinycloud.kv/put\", \"tinycloud.kv/metadata\"] },\n      };\n      const publicPrepared = this.wasmBindings.prepareSession({\n        abilities: publicAbilities,\n        address: this.wasmBindings.ensureEip55(session.address),\n        chainId: session.chainId,\n        domain: this.siweDomain,\n        issuedAt: now.toISOString(),\n        expirationTime: expirationTime.toISOString(),\n        spaceId: publicSpaceId,\n        delegateUri: params.delegateDID,\n        parents: [session.delegationCid],\n      });\n      const publicSignature = await this.signer.signMessage(publicPrepared.siwe);\n      const publicSession = this.wasmBindings.completeSessionSetup({\n        ...publicPrepared,\n        signature: publicSignature,\n      });\n\n      const publicActivateResult = await activateSessionWithHost(\n        this.config.host!,\n        publicSession.delegationHeader\n      );\n\n      if (publicActivateResult.success) {\n        result.publicDelegation = {\n          cid: publicSession.delegationCid,\n          delegationHeader: publicSession.delegationHeader,\n          spaceId: publicSpaceId,\n          path: \"\",\n          actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\", \"tinycloud.kv/metadata\"],\n          disableSubDelegation: params.disableSubDelegation ?? false,\n          expiry: expirationTime,\n          delegateDID: params.delegateDID,\n          ownerAddress: session.address,\n          chainId: session.chainId,\n          host: this.config.host,\n        };\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Use a delegation received from another user.\n   *\n   * This creates a new session key for this user that chains from the\n   * received delegation, allowing operations on the delegator's space.\n   *\n   * Works in both modes:\n   * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key\n   * - **Session-only mode**: Uses the delegation directly (must target session key DID)\n   *\n   * @param delegation - The PortableDelegation to use (from createDelegation or transport)\n   * @returns A DelegatedAccess instance for performing operations\n   */\n  async useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess> {\n    const delegationHeader = delegation.delegationHeader;\n\n    // Use the host from the delegation if provided, otherwise fall back to config\n    const targetHost = delegation.host ?? this.config.host!;\n\n    // Session-only mode: use the delegation directly\n    // The delegation must target this user's session key DID\n    if (this.isSessionOnly) {\n      // Verify the delegation targets our session key DID\n      const myDid = this.did; // In session-only mode, this is the session key DID\n      if (!didPrincipalMatches(delegation.delegateDID, myDid)) {\n        throw new Error(\n          `Delegation targets ${delegation.delegateDID} but this user's DID is ${myDid}. ` +\n          `The delegation must target this user's DID.`\n        );\n      }\n\n      // Create a session using the delegation directly\n      // In session-only mode, we use the received delegation as-is\n      const session: TinyCloudSession = {\n        address: delegation.ownerAddress,\n        chainId: delegation.chainId,\n        sessionKey: JSON.stringify(this.sessionKeyJwk),\n        spaceId: delegation.spaceId,\n        delegationCid: delegation.cid,\n        delegationHeader,\n        verificationMethod: this.sessionDid,\n        jwk: this.sessionKeyJwk as unknown as JWK,\n        siwe: \"\", // Not used in session-only mode\n        signature: \"\", // Not used in session-only mode\n      };\n\n      // Track received delegation in registry\n      this.trackReceivedDelegation(delegation, this.sessionKeyJwk as unknown as JWK);\n      this.installRuntimeGrantFromServiceSession(\n        delegation,\n        {\n          delegationHeader: session.delegationHeader,\n          delegationCid: session.delegationCid,\n          spaceId: session.spaceId,\n          verificationMethod: session.verificationMethod,\n          jwk: session.jwk,\n        },\n        delegation.expiry,\n      );\n\n      return new DelegatedAccess(\n        session,\n        delegation,\n        targetHost,\n        this.wasmBindings.invoke,\n        this.wasmBindings.invokeAny,\n        this.config.telemetry,\n      );\n    }\n\n    // Wallet mode: create a SIWE sub-delegation\n    const mySession = this.auth?.tinyCloudSession;\n    if (!mySession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Use our existing session key - the delegation targets our DID from signIn\n    // We must use the same key that the delegation was created for\n    const jwk = mySession.jwk;\n\n    // Build the activation abilities from the FULL resource set, not just\n    // the flat top-level path/actions. A multi-resource delegation (e.g.\n    // [{kv get vault/secrets/X}, {encryption decrypt <networkId>}]) carries\n    // every grant in `delegation.resources[]`; the flat `path`/`actions`\n    // mirror only the first resource. Building from the flat fields alone\n    // silently drops every other resource from the activated session.\n    const { abilities, rawAbilities } = this.buildActivationAbilities(delegation);\n\n    const now = new Date();\n    // Use delegation expiry or 1 hour, whichever is sooner\n    const maxExpiry = new Date(now.getTime() + 60 * 60 * 1000);\n    const expirationTime = delegation.expiry < maxExpiry ? delegation.expiry : maxExpiry;\n\n    // Prepare the session with:\n    // - THIS user's address (we are the invoker)\n    // - The delegation owner's space (where we're accessing data)\n    // - Our existing session key (must match the DID the delegation targets)\n    // - Parent reference to the received delegation\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(mySession.address),\n      chainId: mySession.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: delegation.spaceId,\n      jwk,\n      parents: [delegation.cid],\n      ...(Object.keys(rawAbilities).length > 0 ? { rawAbilities } : {}),\n    });\n\n    // Sign with THIS user's signer\n    const signature = await this.signer!.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const invokerSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate with server\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      invokerSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate delegated session: ${activateResult.error}`);\n    }\n\n    // Create TinyCloudSession for the delegated access\n    const session: TinyCloudSession = {\n      address: mySession.address,\n      chainId: mySession.chainId,\n      sessionKey: mySession.sessionKey,\n      spaceId: delegation.spaceId,\n      delegationCid: invokerSession.delegationCid,\n      delegationHeader: invokerSession.delegationHeader,\n      verificationMethod: mySession.verificationMethod,\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Track received delegation in registry\n    this.trackReceivedDelegation(delegation, jwk as unknown as JWK);\n    this.installRuntimeGrantFromServiceSession(\n      delegation,\n      {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: session.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      expirationTime,\n    );\n\n    return new DelegatedAccess(\n      session,\n      delegation,\n      targetHost,\n      this.wasmBindings.invoke,\n      this.wasmBindings.invokeAny,\n      this.config.telemetry,\n    );\n  }\n\n  /**\n   * Create a sub-delegation from a received delegation.\n   *\n   * This allows further delegating access that was received from another user,\n   * if the original delegation allows sub-delegation.\n   *\n   * @param parentDelegation - The delegation received from another user\n   * @param params - Sub-delegation parameters (must be within parent's scope)\n   * @returns A portable delegation for the sub-delegate\n   */\n  async createSubDelegation(\n    parentDelegation: PortableDelegation,\n    params: {\n      /** Path within the delegated path to sub-delegate */\n      path: string;\n      /** Actions to allow (must be subset of parent's actions) */\n      actions: string[];\n      /** DID of the recipient */\n      delegateDID: string;\n      /** Whether to prevent the recipient from creating further sub-delegations */\n      disableSubDelegation?: boolean;\n      /** Expiration time in milliseconds from now (must be before parent's expiry) */\n      expiryMs?: number;\n    }\n  ): Promise<PortableDelegation> {\n    if (!this.signer) {\n      throw new Error(\"Cannot createSubDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    if (!this._address) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Validate sub-delegation is allowed\n    if (parentDelegation.disableSubDelegation) {\n      throw new Error(\"Parent delegation does not allow sub-delegation\");\n    }\n\n    // Validate path is within parent's path\n    if (!params.path.startsWith(parentDelegation.path)) {\n      throw new Error(\n        `Sub-delegation path \"${params.path}\" must be within parent path \"${parentDelegation.path}\"`\n      );\n    }\n\n    // Validate actions are subset of parent's actions\n    const parentActions = new Set(parentDelegation.actions);\n    for (const action of params.actions) {\n      if (!parentActions.has(action)) {\n        throw new Error(\n          `Sub-delegation action \"${action}\" is not in parent's actions: ${parentDelegation.actions.join(\", \")}`\n        );\n      }\n    }\n\n    // Calculate expiry - cap at parent's expiry\n    const now = new Date();\n    const expiryMs = params.expiryMs ?? 60 * 60 * 1000;\n    const requestedExpiry = new Date(now.getTime() + expiryMs);\n    // Sub-delegation cannot outlive parent, so cap at parent's expiry\n    const actualExpiry =\n      requestedExpiry > parentDelegation.expiry ? parentDelegation.expiry : requestedExpiry;\n\n    // Build abilities for the sub-delegation\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const kvActions = params.actions.filter(a => a.startsWith(\"tinycloud.kv/\"));\n    const sqlActions = params.actions.filter(a => a.startsWith(\"tinycloud.sql/\"));\n    const duckdbActions = params.actions.filter(a => a.startsWith(\"tinycloud.duckdb/\"));\n    if (kvActions.length > 0) {\n      abilities.kv = { [params.path]: kvActions };\n    }\n    if (sqlActions.length > 0) {\n      abilities.sql = { [params.path]: sqlActions };\n    }\n    if (duckdbActions.length > 0) {\n      abilities.duckdb = { [params.path]: duckdbActions };\n    }\n\n    // Use parent's host or fall back to config\n    const targetHost = parentDelegation.host ?? this.config.host!;\n\n    // Prepare the sub-delegation session\n    // Uses THIS user's address (who received the delegation and is now sub-delegating)\n    // Targets the recipient's PKH DID (delegateUri)\n    // References the parent delegation as the chain\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(this._address),\n      chainId: this._chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: actualExpiry.toISOString(),\n      spaceId: parentDelegation.spaceId,\n      delegateUri: params.delegateDID,\n      parents: [parentDelegation.cid],\n    });\n\n    // Sign with THIS user's signer\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const subDelegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate the sub-delegation with the server\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      subDelegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate sub-delegation: ${activateResult.error}`);\n    }\n\n    // Return the portable sub-delegation\n    return {\n      cid: subDelegationSession.delegationCid,\n      delegationHeader: subDelegationSession.delegationHeader,\n      spaceId: parentDelegation.spaceId,\n      path: params.path,\n      actions: params.actions,\n      disableSubDelegation: params.disableSubDelegation ?? false,\n      expiry: actualExpiry,\n      delegateDID: params.delegateDID,\n      ownerAddress: parentDelegation.ownerAddress!,\n      chainId: parentDelegation.chainId!,\n      host: targetHost,\n    };\n  }\n}\n","export { AccountService } from \"@tinycloud/sdk-core\";\nexport type {\n  AccountApplication,\n  AccountApplicationListOptions,\n  AccountDelegation,\n  AccountDelegationListOptions,\n  AccountDelegationRevokeOptions,\n  AccountIndexEnsureResult,\n  AccountIndexRebuildResult,\n  AccountIndexStatus,\n  AccountIndexedReadOptions,\n  AccountServiceConfig,\n  AccountSpace,\n  AccountSpaceListOptions,\n  AccountStatus,\n} from \"@tinycloud/sdk-core\";\n","import {\n  TinyCloudSession,\n  KVService,\n  IKVService,\n  HooksService,\n  IHooksService,\n  SQLService,\n  ISQLService,\n  DuckDbService,\n  IDuckDbService,\n  ServiceSession,\n  ServiceContext,\n  type TelemetryConfig,\n} from \"@tinycloud/sdk-core\";\nimport type { InvokeFunction, InvokeAnyFunction } from \"@tinycloud/sdk-services\";\nimport { PortableDelegation } from \"./delegation\";\n\n/**\n * The handles needed to rehydrate this delegation activation in a fresh\n * `TinyCloudNode` via `TinyCloudNode.restoreSession(...)` in another process\n * or after a restart.\n *\n * In wallet mode, `delegationHeader` and `delegationCid` are bound to the\n * session key that ran `useDelegation`. They are NOT intrinsic to the\n * portable delegation — they expire with the server-side session (typically\n * ~1h). To keep a restored node alive longer, re-run `useDelegation` with\n * the original portable delegation and call `restoreSession` again with the\n * fresh `RestorableSession`.\n */\nexport interface RestorableSession {\n  delegationHeader: { Authorization: string };\n  delegationCid: string;\n  spaceId: string;\n  jwk: object;\n  verificationMethod: string;\n  address: string;\n  chainId: number;\n}\n\n/**\n * Provides access to a space via a received delegation.\n *\n * This is returned by TinyCloudNode.useDelegation() and provides\n * KV operations on the delegated space.\n */\nexport class DelegatedAccess {\n  private session: TinyCloudSession;\n  private _delegation: PortableDelegation;\n  private host: string;\n  private _serviceContext: ServiceContext;\n  private _kv: KVService;\n  private _sql: SQLService;\n  private _duckdb: DuckDbService;\n  private _hooks: HooksService;\n\n  constructor(\n    session: TinyCloudSession,\n    delegation: PortableDelegation,\n    host: string,\n    invoke: InvokeFunction,\n    invokeAny?: InvokeAnyFunction,\n    telemetry?: TelemetryConfig,\n  ) {\n    this.session = session;\n    this._delegation = delegation;\n    this.host = host;\n\n    // Create service context. invokeAny is required for SQL operations whose\n    // statements span multiple actions in a single invocation (e.g. the\n    // migration runner batches a CREATE TABLE (ddl) with the tracking-row\n    // INSERT (write)); without it those calls throw \"multi-resource\n    // invocations\" not supported.\n    this._serviceContext = new ServiceContext({\n      invoke,\n      invokeAny,\n      fetch: globalThis.fetch.bind(globalThis),\n      hosts: [host],\n      telemetry,\n    });\n\n    // Create and initialize KV service with path prefix from delegation\n    // Strip trailing slash to avoid double-slash in paths\n    const prefix = this._delegation.path.replace(/\\/$/, '');\n    this._kv = new KVService({ prefix });\n    this._kv.initialize(this._serviceContext);\n    this._serviceContext.registerService('kv', this._kv);\n\n    // Create and initialize SQL service with same delegation context\n    this._sql = new SQLService({});\n    this._sql.initialize(this._serviceContext);\n    this._serviceContext.registerService('sql', this._sql);\n\n    // Create and initialize DuckDB service with same delegation context\n    this._duckdb = new DuckDbService({});\n    this._duckdb.initialize(this._serviceContext);\n    this._serviceContext.registerService('duckdb', this._duckdb);\n\n    // Create and initialize Hooks service with same delegation context\n    this._hooks = new HooksService({});\n    this._hooks.initialize(this._serviceContext);\n    this._serviceContext.registerService('hooks', this._hooks);\n\n    // Set session on context\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      spaceId: session.spaceId,\n      verificationMethod: session.verificationMethod,\n      jwk: session.jwk,\n    };\n    this._serviceContext.setSession(serviceSession);\n  }\n\n  /**\n   * Get the delegation this access was created from.\n   */\n  get delegation(): PortableDelegation {\n    return this._delegation;\n  }\n\n  /**\n   * The space ID this access is for.\n   */\n  get spaceId(): string {\n    return this._delegation.spaceId;\n  }\n\n  /**\n   * The path this access is scoped to.\n   */\n  get path(): string {\n    return this._delegation.path;\n  }\n\n  /**\n   * KV operations on the delegated space.\n   */\n  get kv(): IKVService {\n    return this._kv;\n  }\n\n  /**\n   * SQL operations on the delegated space.\n   */\n  get sql(): ISQLService {\n    return this._sql;\n  }\n\n  /**\n   * DuckDB operations on the delegated space.\n   */\n  get duckdb(): IDuckDbService {\n    return this._duckdb;\n  }\n\n  /**\n   * Hooks write-stream subscriptions on the delegated space.\n   */\n  get hooks(): IHooksService {\n    return this._hooks;\n  }\n\n  /**\n   * Export the handles needed to rehydrate this activated delegation via\n   * `TinyCloudNode.restoreSession(...)` in another process or after a\n   * restart.\n   *\n   * See `RestorableSession` for lifetime caveats.\n   */\n  get restorable(): RestorableSession {\n    return {\n      delegationHeader: this.session.delegationHeader,\n      delegationCid: this.session.delegationCid,\n      spaceId: this.session.spaceId,\n      jwk: this.session.jwk,\n      verificationMethod: this.session.verificationMethod,\n      address: this.session.address,\n      chainId: this.session.chainId,\n    };\n  }\n}\n","/**\n * WasmKeyProvider - KeyProvider implementation using WASM session manager.\n *\n * This provider wraps the SessionManager from node-sdk-wasm to provide\n * cryptographic key operations required by the SharingService.\n *\n * @packageDocumentation\n */\n\nimport type { KeyProvider, JWK, ISessionManager } from \"@tinycloud/sdk-core\";\n\n/**\n * Extended session manager with optional key listing support.\n * The base ISessionManager doesn't include listSessionKeys(),\n * but concrete implementations (e.g., TCWSessionManager) may provide it.\n */\ninterface SessionManagerWithListing extends ISessionManager {\n  listSessionKeys?(): string[];\n}\n\n/**\n * Configuration for WasmKeyProvider.\n */\nexport interface WasmKeyProviderConfig {\n  /**\n   * The WASM session manager instance.\n   * Must be created before constructing the KeyProvider.\n   */\n  sessionManager: SessionManagerWithListing;\n}\n\n/**\n * KeyProvider implementation that wraps the WASM session manager.\n *\n * This allows the SharingService to create new session keys for sharing links\n * using the same cryptographic operations as the main session management.\n *\n * @example\n * ```typescript\n * // sessionManager from wasmBindings.createSessionManager()\n * import { WasmKeyProvider } from \"@tinycloud/node-sdk\";\n *\n * const sessionManager = new SessionManager();\n * const keyProvider = new WasmKeyProvider({ sessionManager });\n *\n * // Create a session key for a sharing link\n * const keyId = await keyProvider.createSessionKey(\"share:abc123\");\n * const jwk = keyProvider.getJWK(keyId);\n * const did = await keyProvider.getDID(keyId);\n * ```\n */\nexport class WasmKeyProvider implements KeyProvider {\n  private sessionManager: SessionManagerWithListing;\n\n  /**\n   * Create a new WasmKeyProvider.\n   *\n   * @param config - Configuration with the WASM session manager\n   */\n  constructor(config: WasmKeyProviderConfig) {\n    this.sessionManager = config.sessionManager;\n  }\n\n  /**\n   * Generate a new session key with the given name.\n   *\n   * This creates a new Ed25519 key pair in the WASM session manager.\n   * The key can then be used for signing delegations in sharing links.\n   *\n   * @param name - A unique name/ID for the key (e.g., \"share:timestamp:random\")\n   * @returns The key ID (same as the name provided)\n   */\n  async createSessionKey(name: string): Promise<string> {\n    // The WASM session manager's createSessionKey returns the key_id\n    // and stores the key internally\n    return this.sessionManager.createSessionKey(name);\n  }\n\n  /**\n   * Get the JWK (JSON Web Key) for a key.\n   *\n   * Returns the full JWK including the private key (d parameter),\n   * which is required for signing and for embedding in sharing links.\n   *\n   * @param keyId - The key ID to retrieve\n   * @returns The JWK object with public and private key components\n   * @throws Error if the key is not found\n   */\n  getJWK(keyId: string): JWK {\n    // The WASM session manager returns the JWK as a JSON string\n    const jwkJson = this.sessionManager.jwk(keyId);\n    if (!jwkJson) {\n      throw new Error(`Key not found: ${keyId}`);\n    }\n    // Parse the JSON string to get the JWK object\n    return JSON.parse(jwkJson) as JWK;\n  }\n\n  /**\n   * Get the DID (Decentralized Identifier) for a key.\n   *\n   * Returns the did:key format DID derived from the key's public key.\n   * This DID can be used as the delegatee in delegations.\n   *\n   * @param keyId - The key ID to retrieve\n   * @returns The DID in did:key format (e.g., \"did:key:z6Mk...\")\n   */\n  async getDID(keyId: string): Promise<string> {\n    // The WASM session manager has a synchronous getDID method\n    return this.sessionManager.getDID(keyId);\n  }\n\n  /**\n   * List all session keys currently held by the provider.\n   *\n   * @returns Array of key IDs\n   */\n  listKeys(): string[] {\n    const keys = this.sessionManager.listSessionKeys?.();\n    return Array.isArray(keys) ? keys : [];\n  }\n\n  /**\n   * Check if a key exists in the provider.\n   *\n   * @param keyId - The key ID to check\n   * @returns True if the key exists\n   */\n  hasKey(keyId: string): boolean {\n    const jwk = this.sessionManager.jwk(keyId);\n    return jwk !== undefined;\n  }\n}\n\n/**\n * Create a new WasmKeyProvider instance.\n *\n * @param sessionManager - The WASM session manager\n * @returns A new WasmKeyProvider instance\n */\nexport function createWasmKeyProvider(sessionManager: SessionManagerWithListing): WasmKeyProvider {\n  return new WasmKeyProvider({ sessionManager });\n}\n","/**\n * Internal helpers for TinyCloudNode.delegateTo and the legacy\n * createDelegation compatibility shim. Exported from their own module so\n * they are easy to unit-test without spinning up a full TinyCloudNode.\n *\n * None of these are part of the public API — the module path is not\n * re-exported from `@tinycloud/node-sdk` or `@tinycloud/node-sdk/core`.\n *\n * @packageDocumentation\n */\n\nimport {\n  type PermissionEntry,\n  parseExpiry,\n  SiweMessage,\n  EXPIRY,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * Convert legacy `createDelegation` params into one {@link PermissionEntry}\n * per service. Groups action URNs by their `tinycloud.<service>` prefix and\n * emits one entry per group. Actions whose prefix is not `tinycloud.*` are\n * dropped (preserving the wallet-path behaviour, which also ignores\n * unrecognised URN prefixes).\n *\n * Used by the legacy compatibility shim in `createDelegation` to hand off\n * to `delegateTo` on the fast (subset) path.\n */\nexport function legacyParamsToPermissionEntries(\n  actions: readonly string[],\n  path: string,\n  spaceIdOverride: string | undefined,\n): PermissionEntry[] {\n  const byService = new Map<string, string[]>();\n  for (const a of actions) {\n    // Action URNs look like `tinycloud.kv/get`, `tinycloud.sql/read`, etc.\n    // Split on the first `/` to get the service namespace.\n    const slashIdx = a.indexOf(\"/\");\n    if (slashIdx === -1) {\n      continue;\n    }\n    const service = a.slice(0, slashIdx);\n    if (!service.startsWith(\"tinycloud.\")) {\n      continue;\n    }\n    const list = byService.get(service);\n    if (list === undefined) {\n      byService.set(service, [a]);\n    } else {\n      list.push(a);\n    }\n  }\n  const space = spaceIdOverride ?? \"default\";\n  const entries: PermissionEntry[] = [];\n  for (const [service, actionList] of byService) {\n    entries.push({\n      service,\n      space,\n      path,\n      actions: actionList,\n    });\n  }\n  return entries;\n}\n\n/**\n * Default lifetime for a delegation when no explicit expiry is provided.\n * Sourced from the SESSION tier — runtime grants are always capped at the\n * parent session's expiry, so they can't usefully be longer than SESSION\n * even if a caller asks. See `@tinycloud/sdk-core/expiry.ts`.\n */\nexport const DEFAULT_DELEGATION_EXPIRY_MS = EXPIRY.SESSION_MS;\n\n/**\n * Resolve the `expiry` option of {@link DelegateToOptions} into a concrete\n * millisecond duration from now. Default is {@link DEFAULT_DELEGATION_EXPIRY_MS}\n * (7 days).\n *\n * Accepts:\n *  - `undefined` → {@link DEFAULT_DELEGATION_EXPIRY_MS}\n *  - `number` → raw milliseconds (must be positive + finite)\n *  - `string` → parsed via {@link parseExpiry} (ms-format, e.g. `\"7d\"`)\n */\nexport function resolveExpiryMs(expiry: string | number | undefined): number {\n  if (expiry === undefined) {\n    return DEFAULT_DELEGATION_EXPIRY_MS;\n  }\n  if (typeof expiry === \"number\") {\n    if (!Number.isFinite(expiry) || expiry <= 0) {\n      throw new Error(\n        `delegateTo expiry must be a positive finite number (got ${expiry})`,\n      );\n    }\n    return expiry;\n  }\n  // string — parseExpiry throws ManifestValidationError on bad input.\n  return parseExpiry(expiry);\n}\n\n/**\n * Extract the `expirationTime` field of a signed SIWE message as a `Date`.\n *\n * Returns `undefined` only when the SIWE genuinely has no `Expiration Time`\n * line (RFC-4501 permits it). Propagates parse errors — the SDK always\n * produces signed SIWEs during sign-in, so an unparseable `session.siwe`\n * means something is actively wrong and we do not want to silently skip\n * the expiry check.\n */\nexport function extractSiweExpiration(siwe: string): Date | undefined {\n  const parsed = new SiweMessage(siwe);\n  if (parsed.expirationTime === undefined || parsed.expirationTime === null) {\n    return undefined;\n  }\n  const d = new Date(parsed.expirationTime);\n  if (Number.isNaN(d.getTime())) {\n    throw new Error(\n      `Session SIWE has unparseable expirationTime: ${parsed.expirationTime}`,\n    );\n  }\n  return d;\n}\n","import {\n  ErrorCodes,\n  resolveSecretListPrefix,\n  resolveSecretPath,\n  expandPermissionEntries,\n  resolveManifest,\n  type IDataVaultService,\n  type ISecretsService,\n  type Manifest,\n  type PermissionEntry,\n  type Result,\n  type SecretScopeOptions,\n  type ServiceError,\n  type VaultError,\n} from \"@tinycloud/sdk-core\";\n\nconst SECRETS_SPACE = \"secrets\";\ntype SecretAction = \"get\" | \"put\" | \"del\" | \"list\";\n\nfunction ok(): Result<void, ServiceError> {\n  return { ok: true, data: undefined };\n}\n\nfunction secretsError(\n  code: string,\n  message: string,\n  cause?: Error,\n): Result<never, ServiceError> {\n  return {\n    ok: false,\n    error: {\n      code,\n      service: \"secrets\",\n      message,\n      ...(cause ? { cause } : {}),\n    },\n  };\n}\n\nfunction displayActionUrn(action: SecretAction): string {\n  switch (action) {\n    case \"get\":\n      return \"tinycloud.kv/get\";\n    case \"put\":\n      return \"tinycloud.kv/put\";\n    case \"del\":\n      return \"tinycloud.kv/del\";\n    case \"list\":\n      return \"tinycloud.kv/list\";\n  }\n}\n\nfunction secretActionName(action: SecretAction): \"get\" | \"put\" | \"del\" | \"list\" {\n  return action;\n}\n\nfunction secretPermissionEntries(\n  name: string,\n  options: SecretScopeOptions | undefined,\n  action: SecretAction,\n  encryptionNetworkId?: string,\n): PermissionEntry[] {\n  const entries: PermissionEntry[] = [];\n  const path =\n    action === \"list\"\n      ? resolveSecretListPrefix(options)\n      : resolveSecretPath(name, options).permissionPaths.vault;\n\n  entries.push({\n    service: \"tinycloud.kv\",\n    space: SECRETS_SPACE,\n    path,\n    actions: [secretActionName(action)],\n    skipPrefix: true,\n  });\n\n  if (action === \"get\" && encryptionNetworkId !== undefined) {\n    entries.push({\n      service: \"tinycloud.encryption\",\n      path: encryptionNetworkId,\n      actions: [\"decrypt\"],\n      skipPrefix: true,\n    });\n  }\n\n  return entries;\n}\n\nexport interface NodeSecretsServiceConfig {\n  getService: () => ISecretsService;\n  getManifest: () => Manifest | Manifest[] | undefined;\n  hasPermissions?: (permissions: PermissionEntry[]) => boolean;\n  grantPermissions: (additional: PermissionEntry[]) => Promise<unknown>;\n  canEscalate: () => boolean;\n  getEncryptionNetworkId?: () => string;\n  getUnlockSigner?: () => unknown;\n}\n\nexport class NodeSecretsService implements ISecretsService {\n  private unlockSigner?: unknown;\n  private shouldRestoreUnlock = false;\n\n  constructor(private readonly config: NodeSecretsServiceConfig) {}\n\n  get vault(): IDataVaultService {\n    return this.service.vault;\n  }\n\n  get isUnlocked(): boolean {\n    return this.service.isUnlocked;\n  }\n\n  async unlock(signer?: unknown): Promise<Result<void, VaultError>> {\n    const effectiveSigner = signer ?? this.config.getUnlockSigner?.();\n    if (effectiveSigner !== undefined) {\n      this.unlockSigner = effectiveSigner;\n    }\n    const result = await this.service.unlock(effectiveSigner);\n    if (result.ok) {\n      this.shouldRestoreUnlock = true;\n    }\n    return result;\n  }\n\n  lock(): void {\n    this.shouldRestoreUnlock = false;\n    this.service.lock();\n  }\n\n  async get(name: string, options?: SecretScopeOptions): ReturnType<ISecretsService[\"get\"]> {\n    const permission = await this.ensurePermission(name, options, \"get\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.get(name)\n      : this.service.get(name, options);\n  }\n\n  async put(\n    name: string,\n    value: string,\n    options?: SecretScopeOptions,\n  ): ReturnType<ISecretsService[\"put\"]> {\n    const permission = await this.ensurePermission(name, options, \"put\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.put(name, value)\n      : this.service.put(name, value, options);\n  }\n\n  async delete(\n    name: string,\n    options?: SecretScopeOptions,\n  ): ReturnType<ISecretsService[\"delete\"]> {\n    const permission = await this.ensurePermission(name, options, \"del\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.delete(name)\n      : this.service.delete(name, options);\n  }\n\n  async list(options?: SecretScopeOptions): ReturnType<ISecretsService[\"list\"]> {\n    const permission = await this.ensurePermission(\"\", options, \"list\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.list()\n      : this.service.list(options);\n  }\n\n  private get service(): ISecretsService {\n    return this.config.getService();\n  }\n\n  private async ensurePermission(\n    name: string,\n    options: SecretScopeOptions | undefined,\n    action: SecretAction,\n  ): Promise<Result<void, ServiceError | VaultError>> {\n    const target = name || \"secrets\";\n    let permissionEntries: PermissionEntry[];\n    try {\n      permissionEntries = secretPermissionEntries(\n        name,\n        options,\n        action,\n        action === \"get\" ? this.config.getEncryptionNetworkId?.() : undefined,\n      );\n    } catch (error) {\n      return secretsError(\n        ErrorCodes.INVALID_INPUT,\n        error instanceof Error ? error.message : String(error),\n        error instanceof Error ? error : undefined,\n      );\n    }\n\n    if (this.hasPermission(permissionEntries)) {\n      return ok();\n    }\n\n    if (!this.config.canEscalate()) {\n      return secretsError(\n        ErrorCodes.PERMISSION_DENIED,\n        `Cannot autosign ${displayActionUrn(action)} for ${target}; TinyCloudNode needs wallet mode with a signer or privateKey.`,\n      );\n    }\n\n    try {\n      await this.config.grantPermissions(permissionEntries);\n      return this.restoreUnlockAfterEscalation();\n    } catch (error) {\n      return secretsError(\n        ErrorCodes.PERMISSION_DENIED,\n        error instanceof Error\n          ? error.message\n          : `Autosign escalation for ${displayActionUrn(action)} on ${target} failed.`,\n        error instanceof Error ? error : undefined,\n      );\n    }\n  }\n\n  private async restoreUnlockAfterEscalation(): Promise<\n    Result<void, ServiceError | VaultError>\n  > {\n    if (!this.shouldRestoreUnlock) {\n      return ok();\n    }\n    return this.service.unlock(this.unlockSigner);\n  }\n\n  private hasPermission(\n    permissionEntries: PermissionEntry[],\n  ): boolean {\n    if (this.config.hasPermissions?.(permissionEntries)) {\n      return true;\n    }\n\n    const manifest = this.config.getManifest();\n    if (manifest === undefined) {\n      return false;\n    }\n\n    const manifests = Array.isArray(manifest) ? manifest : [manifest];\n    const requestedEntries = expandPermissionEntries(permissionEntries);\n    return requestedEntries.every((entry) =>\n      manifests.some((candidate) => {\n        const resolved = resolveManifest(candidate);\n        return resolved.resources.some(\n          (resource) =>\n            resource.service === entry.service &&\n            resource.space === entry.space &&\n            resource.path === entry.path &&\n            entry.actions.every((action) => resource.actions.includes(action)),\n        );\n      }),\n    );\n  }\n\n}\n","import { Delegation, DelegatedResource, PermissionEntry } from \"@tinycloud/sdk-core\";\n\n/**\n * A portable delegation that can be transported between users.\n * Extends the base Delegation type with fields required for transport.\n *\n * @remarks\n * PortableDelegation adds transport fields to Delegation:\n * - `delegationHeader`: Structured authorization header for API calls\n * - `ownerAddress`: Space owner's address for session creation\n * - `chainId`: Chain ID for session creation\n * - `host`: Optional server URL\n * - `resources`: Multi-resource grant breakdown (present when the\n *   delegation was issued via the multi-resource WASM path, i.e. one\n *   UCAN covering multiple `(service, path, actions)` entries). The\n *   flat `path` + `actions` fields mirror the first entry for\n *   single-resource callers; consumers that need the full picture\n *   read `resources`.\n */\nexport interface PortableDelegation extends Omit<Delegation, \"isRevoked\"> {\n  /** The authorization header for this delegation (structured format) */\n  delegationHeader: { Authorization: string };\n\n  /** The address of the space owner */\n  ownerAddress: string;\n\n  /** The chain ID */\n  chainId: number;\n\n  /** TinyCloud server URL where this delegation was created */\n  host?: string;\n\n  /** Whether the recipient is prevented from creating sub-delegations */\n  disableSubDelegation?: boolean;\n\n  /** Companion delegation for the user's public space (auto-created when includePublicSpace is true) */\n  publicDelegation?: PortableDelegation;\n\n  /**\n   * Full multi-resource grant breakdown. Present when the delegation\n   * was issued via the multi-resource WASM path; each entry describes\n   * one `(service, space, path, actions)` grant carried by the single\n   * underlying UCAN. When absent, only the flat `path` + `actions`\n   * fields are authoritative (legacy single-resource shape).\n   */\n  resources?: DelegatedResource[];\n}\n\n/**\n * The transport shape `tc auth request --emit` produces and that an owner\n * grants to its requester. Only the fields the grant logic needs are declared;\n * the CLI artifact carries more (posture, captured command, ...) and remains a\n * structural superset of this interface.\n */\nexport interface AuthRequestArtifact {\n  kind: \"tinycloud.auth.request\";\n  version: 1;\n  requestId: string;\n  /** The requester's session DID — the audience the grant is issued to. */\n  sessionDid: string;\n  /** The capabilities the requester is asking the owner to delegate. */\n  requested: PermissionEntry[];\n  /** Optional lifetime override carried from the request. */\n  requestedExpiry?: string | number;\n}\n\n/**\n * The transport shape returned by {@link grantAuthRequest} (and written by\n * `tc auth grant`). `tc auth import` accepts this artifact directly.\n */\nexport interface AuthDelegationArtifact {\n  kind: \"tinycloud.auth.delegation\";\n  version: 1;\n  requestId: string;\n  delegationCid: string;\n  delegation: PortableDelegation;\n  permissions: PermissionEntry[];\n  expiry: string;\n  /** Whether issuing the delegation triggered a wallet prompt. */\n  prompted: boolean;\n}\n\n/**\n * Minimal owner-side capability {@link grantAuthRequest} needs: the signed\n * `delegateTo` primitive. `TinyCloudNode` satisfies this directly; web/SDK\n * contexts can supply any object that exposes the same method.\n */\nexport interface DelegationAuthority {\n  delegateTo(\n    did: string,\n    permissions: PermissionEntry[],\n    options?: { expiry?: string | number; forceWalletSign?: boolean },\n  ): Promise<{ delegation: PortableDelegation; prompted: boolean }>;\n}\n\n/**\n * Turn a delegation REQUEST into a signed GRANT.\n *\n * Lifts the body of `tc auth grant` into the SDK so the request→grant\n * handshake is callable programmatically (future SDK/web owner tooling and the\n * KV delegation inbox), with the CLI verb reduced to a thin wrapper. The owner\n * `authority` (a `TinyCloudNode`) signs a delegation scoped to exactly the\n * requested caps, audienced to the requester's `sessionDid`, honoring the\n * request's expiry. The returned artifact round-trips through `tc auth import`.\n *\n * Authorization is enforced cryptographically by `delegateTo`: caps that are\n * not derivable from the owner's own session capability chain are rejected\n * (it throws), so this never widens authority the owner doesn't hold.\n */\nexport async function grantAuthRequest(\n  authority: DelegationAuthority,\n  request: AuthRequestArtifact,\n  options?: { expiry?: string | number },\n): Promise<AuthDelegationArtifact> {\n  if (request.kind !== \"tinycloud.auth.request\") {\n    throw new Error(\n      `grantAuthRequest expects a tinycloud.auth.request artifact, got \"${request.kind}\".`,\n    );\n  }\n  if (!Array.isArray(request.requested) || request.requested.length === 0) {\n    throw new Error(\"grantAuthRequest request has no requested capabilities.\");\n  }\n\n  const expiry = options?.expiry ?? request.requestedExpiry;\n  const result = await authority.delegateTo(\n    request.sessionDid,\n    request.requested,\n    expiry !== undefined ? { expiry } : undefined,\n  );\n\n  return {\n    kind: \"tinycloud.auth.delegation\",\n    version: 1,\n    requestId: request.requestId,\n    delegationCid: result.delegation.cid,\n    delegation: result.delegation,\n    permissions: request.requested,\n    expiry: result.delegation.expiry.toISOString(),\n    prompted: result.prompted,\n  };\n}\n\n/**\n * Serialize a PortableDelegation for transport (e.g., over network).\n */\nexport function serializeDelegation(delegation: PortableDelegation): string {\n  return JSON.stringify({\n    ...delegation,\n    expiry: delegation.expiry.toISOString(),\n  });\n}\n\n/**\n * Deserialize a PortableDelegation from transport.\n */\nexport function deserializeDelegation(data: string): PortableDelegation {\n  const parsed = JSON.parse(data);\n  return {\n    ...parsed,\n    cid: parsed.cid,\n    expiry: new Date(parsed.expiry),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,IAAAA,mBAA0B;AA+B1B,IAAAA,oBA0BO;;;ACvDA,IAAM,uBAAN,MAAsD;AAAA,EAAtD;AACL,SAAQ,WAA8C,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9D,MAAM,KAAK,SAAiB,SAA8C;AACxE,UAAM,oBAAoB,QAAQ,YAAY;AAC9C,SAAK,SAAS,IAAI,mBAAmB,OAAO;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,KAAK,SAAuD;AAChE,UAAM,oBAAoB,QAAQ,YAAY;AAC9C,UAAM,UAAU,KAAK,SAAS,IAAI,iBAAiB;AAEnD,QAAI,CAAC,SAAS;AACZ,aAAO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kB,qBAAqB;AAAA,MACvC,SAAS,iBAAiB;AAAA,MAC1B,MAAM,OAAO;AAAA,MACb,SAAS,OAAO;AAAA,MAChB,sBAAsB,OAAO,wBAAwB;AAAA,MACrD,QAAQ;AAAA,MACR,aAAa,OAAO;AAAA,MACpB,cAAc,iBAAiB;AAAA,MAC/B,SAAS,iBAAiB;AAAA,MAC1B,MAAM;AAAA,IACR;AAAA,EACF;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AApwIa,eA20Fa,kCAAkC;AA30FrD,IAAM,gBAAN;;;AL5QP,IAAAC,oBA8BO;;;AWtBA,SAAS,oBAAoB,YAAwC;AAC1E,SAAO,KAAK,UAAU;AAAA,IACpB,GAAG;AAAA,IACH,QAAQ,WAAW,OAAO,YAAY;AAAA,EACxC,CAAC;AACH;AAKO,SAAS,sBAAsB,MAAkC;AACtE,QAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,SAAO;AAAA,IACL,GAAG;AAAA,IACH,KAAK,OAAO;AAAA,IACZ,QAAQ,IAAI,KAAK,OAAO,MAAM;AAAA,EAChC;AACF;;;AXaA,IAAAC,oBAIO;AAaP,IAAAA,oBAAsD;AAmBtD,IAAAA,oBAIO;AAwBP,IAAAA,oBAUO;AAsBP,IAAAA,oBAKO;AAkCP,IAAAA,oBAIO;AAUP,IAAAA,oBAQO;AAcP,IAAAA,oBAKO;AAGP,IAAAA,oBAA+B;","names":["import_sdk_core","import_sdk_core","import_sdk_core","primarySpaceId","import_sdk_core","import_sdk_core","import_sdk_core","import_sdk_core","import_sdk_core","NETWORK_CREATE_ACTION","DECRYPT_ACTION","didPrincipalMatches","config","actions","now","delegation","spaceId","expandPermissionEntriesCore","session","import_sdk_core","import_sdk_core"]}