@tinycloud/node-sdk 3.1.0-beta.9 → 3.2.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{core-CC7uDKZP.d.cts → core-AEx5vAa8.d.cts} +21 -0
- package/dist/{core-CC7uDKZP.d.ts → core-AEx5vAa8.d.ts} +21 -0
- package/dist/core.cjs +171 -85
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +171 -85
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +171 -85
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +171 -85
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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 UnsupportedSessionRestoreError,\n InvalidRestoredSessionError,\n type TinyCloudNodeConfig,\n type DelegateToOptions,\n type DelegateToResult,\n type RuntimePermissionGrantOptions,\n type EnsureEncryptionNetworkOptions,\n type SecretReadInput,\n type SecretPermissionHint,\n type SecretReadResult,\n type CreateOwnerDelegationParams,\n type OwnerDelegationReceipt,\n type RegisterPolicyV3Input,\n type RegisterPolicyV3Receipt,\n type UnifiedOwnerRootInput,\n type UnifiedOwnerRootReceipt,\n type BootstrapWarning,\n} from \"./TinyCloudNode\";\n\nexport { AccountService } from \"./account/AccountService\";\nexport type {\n AccountApplication,\n AccountApplicationListOptions,\n AccountApplicationRegisterOptions,\n AccountDelegation,\n AccountDelegationListOptions,\n AccountDelegationRevokeOptions,\n AccountIndexEnsureResult,\n AccountIndexRebuildResult,\n AccountIndexStatus,\n AccountIndexedReadOptions,\n AccountServiceConfig,\n AccountSpace,\n AccountSpaceListOptions,\n AccountStatus,\n RegisterBatchSuccess,\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 CaveatedDelegationUnsupportedError,\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 {\n activateCompactRuntimeDelegation,\n serializeDelegation,\n deserializeDelegation,\n} from \"./delegation\";\nexport type {\n CompactRuntimeDelegationInput,\n PortableDelegation,\n ValidatedRuntimeDelegation,\n} 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 KVBatchReadResponse,\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 parseSecretCatalogKey,\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 VaultNetworkReadResult,\n VaultError,\n ISecretsService,\n SecretCatalogEntry,\n SecretPayload,\n SecretsError,\n ResolvedSecretPath,\n ParsedSecretCatalogKey,\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 DelegateReceivedShareParams,\n DelegatedShareAccess,\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 { createHash } from \"node:crypto\";\nimport { SiweMessage } from \"siwe\";\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 type LocalNodeIdentityStore,\n EXPIRY,\n canonicalizeAddress,\n makePkhSpaceId,\n pkhDid,\n extractImmutableSiweFields,\n diffImmutableSiweFields,\n extractRecapAttenuations,\n unauthorizedRecapCapabilities,\n parseCanonicalRecapResource,\n ACCOUNT_REGISTRY_SPACE,\n ACCOUNT_MANIFEST_PERMISSIONS,\n KV,\n SQL,\n DUCKDB,\n CAPABILITIES,\n HOOKS,\n ENCRYPTION,\n type CapabilityPresentationEnvelopeV1,\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 = ENCRYPTION.DECRYPT;\n\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\n\n/** `<status> - <server text>` for a failed host activation. */\nfunction describeHostFailure(result: SpaceHostResult): string {\n const text = result.error?.trim();\n return text ? `${result.status} - ${text}` : `${result.status}`;\n}\n\ntype JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Canonical sorted-key JSON used by the OpenKey manifest-digest protocol.\n * Ordinary JSON semantics are applied first so undefined object fields are\n * omitted identically to a published JSON file.\n */\nexport function canonicalizeOpenKeyManifestJson(value: unknown): string {\n const json = JSON.stringify(value);\n if (json === undefined) {\n throw new TypeError(\"manifest is not JSON-serializable\");\n }\n return canonicalizeJsonValue(JSON.parse(json) as JsonValue);\n}\n\nfunction canonicalizeJsonValue(value: JsonValue): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalizeJsonValue).join(\",\")}]`;\n }\n return `{${Object.keys(value)\n .sort()\n .map(\n (key) =>\n `${JSON.stringify(key)}:${canonicalizeJsonValue(value[key]!)}`,\n )\n .join(\",\")}}`;\n}\n\n/** SHA-256 hex of the canonical JSON form of a published manifest. */\nexport function canonicalOpenKeyManifestSha256Hex(value: unknown): string {\n return createHash(\"sha256\")\n .update(canonicalizeOpenKeyManifestJson(value))\n .digest(\"hex\");\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\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\nfunction cloneAbilitiesMap(actions: AbilitiesMap): AbilitiesMap {\n return Object.fromEntries(\n Object.entries(actions).map(([service, paths]) => [\n service,\n Object.fromEntries(\n Object.entries(paths).map(([path, pathActions]) => [path, [...pathActions]]),\n ),\n ]),\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: 30 days, `EXPIRY.SESSION_MS`) */\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 /** Probe configured/registered local nodes before registry/fallback resolution. Default: true. */\n autoDiscoverLocalNode?: boolean;\n /** Local loopback node URL to probe. Omit to avoid probing loopback. */\n localNodeUrl?: string;\n /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n localLinkName?: string;\n /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n expectedNodeDid?: string;\n /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n localNodeIdentityStore?: LocalNodeIdentityStore;\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 /** Existing session manager to share with a higher-level SDK client. */\n sessionManager?: ISessionManager;\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 canonical account registry read/create-update/list permissions when composing `manifest` and plain sign-in. 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 autoDiscoverLocalNode?: boolean;\n private readonly localNodeUrl?: string;\n private readonly localLinkName?: string;\n private readonly expectedNodeDid?: string;\n private readonly localNodeIdentityStore?: LocalNodeIdentityStore;\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 activeSessionKeyId = \"default\";\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 /**\n * `nodeId` from the `GET /info` performed during sign-in/restore, tagged with\n * the host it came from. Callers that need the node DID (encryption-network\n * admin invocations) reuse this instead of re-fetching `/info`.\n */\n private _nodeInfoIdentity?: { host: string; nodeId: 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 \"\": [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA],\n },\n sql: {\n \"\": [SQL.READ, SQL.WRITE, SQL.SCHEMA, SQL.ADMIN, SQL.EXPORT],\n },\n duckdb: {\n \"\": [\n DUCKDB.READ,\n DUCKDB.WRITE,\n DUCKDB.ADMIN,\n DUCKDB.DESCRIBE,\n DUCKDB.EXPORT,\n DUCKDB.IMPORT,\n DUCKDB.EXECUTE,\n ],\n },\n capabilities: {\n \"\": [CAPABILITIES.READ],\n },\n hooks: {\n \"\": [HOOKS.SUBSCRIBE, HOOKS.REGISTER, HOOKS.LIST, HOOKS.UNREGISTER],\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.autoDiscoverLocalNode = config.autoDiscoverLocalNode;\n this.localNodeUrl = config.localNodeUrl;\n this.localLinkName = config.localLinkName;\n this.expectedNodeDid = config.expectedNodeDid;\n this.localNodeIdentityStore = config.localNodeIdentityStore;\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 // Reuse the caller's manager when authorization is owned by a higher-level\n // client so both layers address the same session keys.\n this.sessionManager = config.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 /** @internal Atomically adopt the state staged by TinyCloudNode.restoreSession. */\n installRestoredSession(\n sessionManager: ISessionManager,\n session: TinyCloudSession | undefined,\n hosts?: string[],\n ): void {\n this.sessionManager = sessionManager;\n // Restore is a complete session replacement, not an additive update. In\n // particular, a second restore may target a different host and must not\n // retain skip decisions from the previous activation.\n this.tinycloudHosts = hosts && hosts.length > 0 ? [...hosts] : undefined;\n this._lastActivationSkippedSpaceIds = [];\n if (!session) {\n this._session = undefined;\n this._tinyCloudSession = undefined;\n this._address = undefined;\n this._chainId = undefined;\n return;\n }\n this._tinyCloudSession = { ...session };\n this._address = session.address;\n this._chainId = session.chainId;\n this._session = {\n address: session.address,\n walletAddress: session.address,\n chainId: session.chainId,\n sessionKey: session.sessionKey,\n siwe: session.siwe,\n signature: session.signature,\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 autoDiscoverLocalNode: this.autoDiscoverLocalNode,\n localNodeUrl: this.localNodeUrl,\n localLinkName: this.localLinkName,\n expectedNodeDid: this.expectedNodeDid,\n localNodeIdentityStore: this.localNodeIdentityStore,\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 /**\n * The node DID reported by `GET /info` for `host`, if the sign-in (or\n * restore) that populated it targeted that same host. Returns `undefined`\n * for any other host, and for nodes whose `/info` omits `nodeId`, so callers\n * fall back to fetching it themselves rather than using a foreign node's DID.\n */\n nodeIdForHost(host: string): string | undefined {\n return this._nodeInfoIdentity?.host === host\n ? this._nodeInfoIdentity.nodeId\n : undefined;\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 const primaryActions =\n this.includeAccountRegistryPermissions && this.spacePrefix === ACCOUNT_REGISTRY_SPACE\n ? cloneAbilitiesMap(this.defaultActions)\n : this.defaultActions;\n const spaceAbilities: Record<string, AbilitiesMap> = {\n [primarySpaceId]: primaryActions,\n [secretsSpaceId]: {\n kv: {\n \"vault/secrets/\": [\n KV.GET,\n KV.PUT,\n KV.DEL,\n KV.LIST,\n KV.METADATA,\n ],\n },\n },\n };\n // Plain sessions receive the canonical account-manifest permissions in\n // the signer-derived account space. Do not duplicate the space object\n // when the primary space itself is `account`; merge into its existing\n // defaultActions map instead.\n if (\n this.includeAccountRegistryPermissions &&\n this.spacePrefix !== ACCOUNT_REGISTRY_SPACE\n ) {\n spaceAbilities[makePkhSpaceId(address, chainId, ACCOUNT_REGISTRY_SPACE)] =\n resourceCapabilitiesToAbilitiesMap(ACCOUNT_MANIFEST_PERMISSIONS);\n } else if (this.includeAccountRegistryPermissions) {\n const accountAbilities = resourceCapabilitiesToAbilitiesMap(\n ACCOUNT_MANIFEST_PERMISSIONS,\n );\n for (const [service, paths] of Object.entries(accountAbilities)) {\n const existingPaths = primaryActions[service] ?? (primaryActions[service] = {});\n for (const [path, actions] of Object.entries(paths)) {\n const existingActions = existingPaths[path] ?? (existingPaths[path] = []);\n for (const action of actions) {\n if (!existingActions.includes(action)) existingActions.push(action);\n }\n }\n }\n }\n return {\n abilities: primaryActions,\n spaceId: primarySpaceId,\n spaceAbilities,\n rawAbilities: {\n [defaultNetworkId]: [DECRYPT_ACTION, NETWORK_CREATE_ACTION],\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(\n targetSpaceId?: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<SpaceHostResult> {\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, purpose);\n\n // Convert to delegation headers and submit\n const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });\n return submitHostDelegation(host, headers);\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 (await this.hostSpace(spaceId)).success;\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(\n spaceId: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<boolean> {\n return (await this.hostOwnedSpaceResult(spaceId, purpose)).success;\n }\n\n /**\n * {@link hostOwnedSpace} with the full host-delegation result, so a failure\n * keeps its HTTP status (e.g. a typed 401/403) instead of collapsing to\n * `false`.\n */\n async hostOwnedSpaceResult(\n spaceId: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<SpaceHostResult> {\n return this.hostSpace(spaceId, purpose);\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.success) {\n const err = Object.assign(\n new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 = Object.assign(\n new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),\n { cause: retryResult },\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.success) {\n const err = Object.assign(\n new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 = Object.assign(\n new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),\n { cause: retryResult },\n );\n handler.onSpaceCreationFailed?.(creationContext, err);\n throw err;\n }\n\n handler.onSpaceCreated?.(creationContext);\n return;\n }\n\n throw Object.assign(\n new Error(`Failed to activate session: ${describeHostFailure(result)}`),\n { cause: result },\n );\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 purpose: \"bootstrap-session\",\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(this.activeSessionKeyId, keyId);\n this.activeSessionKeyId = 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 purpose: \"sign-in\",\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 infoHost = this.primaryTinyCloudHost;\n const nodeInfo = await checkNodeInfo(\n infoHost,\n this.wasm.protocolVersion(),\n );\n this._nodeFeatures = nodeInfo.features;\n // `/info` already told us the node DID. Keep it so encryption-network\n // admin invocations do not re-fetch `/info` just to learn it.\n this._nodeInfoIdentity = nodeInfo.nodeId\n ? { host: infoHost, nodeId: nodeInfo.nodeId }\n : undefined;\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(\n message: string,\n purpose?: SignRequest[\"purpose\"],\n ): 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 ...(purpose ? { purpose } : {}),\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(this.activeSessionKeyId, keyId);\n this.activeSessionKeyId = 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 infoHost = this.primaryTinyCloudHost;\n const nodeInfo = await checkNodeInfo(\n infoHost,\n this.wasm.protocolVersion(),\n );\n this._nodeFeatures = nodeInfo.features;\n // `/info` already told us the node DID. Keep it so encryption-network\n // admin invocations do not re-fetch `/info` just to learn it.\n this._nodeInfoIdentity = nodeInfo.nodeId\n ? { host: infoHost, nodeId: nodeInfo.nodeId }\n : undefined;\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 * End-to-end sign-in via OpenKey `authorizeTinyCloud()` (Sol CRITICAL-4).\n *\n * This is the production entry point that wires\n * {@link prepareSessionForSigning} → OpenKey `authorizeTinyCloud()` →\n * {@link signInWithOpenKeyResult} into one call. Consumers pass in a\n * caller-provided `authorizeFn` (typically a thin wrapper around\n * `openkey.authorizeTinyCloud()`) so this method has no direct\n * dependency on the OpenKey SDK — it works with any transport that\n * conforms to the versioned protocol.\n *\n * The `authorizeFn` MUST:\n * 1. Send the prepared SIWE bytes to OpenKey.\n * 2. Return the exact `TinyCloudAuthorizationResultV1` shape (with\n * `signedMessage` — the bytes the signature actually verifies\n * against — plus `selectedActionKeys` and `permissions`).\n *\n * NodeUserAuthorization then completes the session with `signedMessage`\n * (never the prepared bytes), verifying the signature, the immutable\n * SIWE fields, and every subset invariant enforced by\n * {@link signInWithOpenKeyResult}. This preserves the exact-byte\n * guarantee: if the user did NOT narrow, the returned `signedMessage`\n * equals the prepared SIWE byte-for-byte; if the user narrowed, only\n * the ReCap block differs and every immutable header field survives.\n *\n * Legacy exact-byte {@link signIn} callers are unaffected — this method\n * is opt-in.\n *\n * @param authorizeFn Callback that invokes the versioned OpenKey\n * `authorizeTinyCloud()` protocol and returns the result. Receives\n * the prepared SIWE bytes plus a `host` hint the widget should bind\n * into its /authorize-sign-prepare context.\n * @param options Optional overrides for the OpenKey request.\n */\n async signInWithOpenKey(\n authorizeFn: (input: {\n protocolVersion: 1;\n siwe: string;\n jwk: Record<string, unknown>;\n host?: string;\n /**\n * Sol MAJOR-3: OpenKey key ID (managed or external key) to sign\n * with. When omitted, the OpenKey SDK falls back to the last\n * connected key. Callers who want to bind the flow to a specific\n * OpenKey key can override via options.openkeyKeyId; otherwise the\n * bridge relies on the SDK's connected-key state.\n */\n keyId?: string;\n /**\n * Optional presentation envelope forwarded to the OpenKey widget.\n * Built from this instance's `_manifest` when set. Display-only —\n * the widget/server MUST NOT let it expand authority. The envelope\n * carries `manifests` payloads plus a stable SHA-256 digest so the\n * OpenKey server can origin-bind the browser origin against the\n * app's well-known manifest.\n */\n presentation?: CapabilityPresentationEnvelopeV1;\n }) => Promise<{\n protocolVersion: 1;\n address: string;\n signature: string;\n signedMessage: string;\n selectedActionKeys: string[];\n permissions: Array<{ service: string; space: string; path: string; actions: string[] }>;\n }>,\n options?: {\n host?: string;\n openkeyKeyId?: string;\n /**\n * Optional caller-supplied reason string forwarded in the\n * presentation envelope. Rendered as caller-supplied (never\n * verified) in the widget.\n */\n reason?: string;\n },\n ): Promise<ClientSession> {\n // A per-call host override is the host this session will actually use,\n // not merely a display hint for OpenKey. Install it before preparation so\n // the same value is bound into the authorization context and later used\n // for activation.\n if (options?.host !== undefined) {\n const overrideHost = options.host.trim();\n if (!overrideHost) {\n throw new Error(\"OpenKey authorization host must not be empty\");\n }\n this.tinycloudHosts = [overrideHost];\n }\n\n // OpenKey binds the target host into its authorization context. Resolve\n // the same host activation will use before asking OpenKey to prepare or\n // sign anything; signInWithPreparedSession is intentionally too late.\n const signingAddress = canonicalizeAddress(await this.signer.getAddress());\n const signingChainId = await this.signer.getChainId();\n await this.resolveTinyCloudHostsForSignIn(signingAddress, signingChainId);\n\n // 1. Prepare — this creates a SIWE bound to a fresh session key.\n const { prepared, keyId, jwk } = await this.prepareSessionForSigning();\n\n // 2. Build the presentation envelope from the instance manifest (if\n // any). This is the SUPPORTED production path for surfacing an\n // honest app identity in the OpenKey review UI — we NEVER\n // fabricate manifest fields, and the envelope is display-only.\n const presentation = this.buildPresentationEnvelope(options?.reason);\n\n // 3. Delegate signing to OpenKey via the caller-supplied bridge.\n // We forward the JWK so the OpenKey server can regenerate a\n // narrowed SIWE bound to the same session key when the user\n // edits the review — and never a caller-echoed JWK.\n //\n // We forward the TinyCloud host so the widget can bind it into\n // its authorization context (Sol MAJOR-2). Falls back to the\n // first resolved TinyCloud host when not overridden.\n //\n // Sol MAJOR-3: forward an OpenKey keyId when the caller supplied\n // one so the widget/SDK routes to the specific OpenKey key rather\n // than the SDK's connected-key default.\n const hostHint = this.primaryTinyCloudHost;\n const result = await authorizeFn({\n protocolVersion: 1,\n siwe: prepared.siwe,\n jwk,\n host: hostHint,\n keyId: options?.openkeyKeyId,\n presentation,\n });\n\n // 4. Complete with the EXACT bytes OpenKey signed. Every subset\n // invariant (immutable fields preserved, capabilities ⊆ prepared,\n // selectedActionKeys grounded in signedMessage, permissions\n // consistent) is enforced by signInWithOpenKeyResult before any\n // session state is created.\n return this.signInWithOpenKeyResult(result, prepared, keyId, jwk);\n }\n\n /**\n * Build a `CapabilityPresentationEnvelopeV1` from `this._manifest`. The\n * envelope is display-only — the OpenKey widget renders it under an\n * honest trust label, and the server /authorize-sign-prepare route\n * decides whether to upgrade the label to `origin-bound` by fetching\n * the well-known manifest and comparing its digest to\n * `manifestDigest`.\n *\n * Returns `undefined` when no manifest is set — the widget renders as\n * \"no manifest supplied\" (unsigned).\n *\n * The digest is a deterministic SHA-256 over canonical JSON of the\n * first manifest payload; OpenKey parses the fetched well-known manifest\n * and applies the same canonicalization before comparing digests.\n */\n private buildPresentationEnvelope(\n reason?: string,\n ): CapabilityPresentationEnvelopeV1 | undefined {\n const manifests = Array.isArray(this._manifest)\n ? this._manifest\n : this._manifest\n ? [this._manifest]\n : [];\n if (manifests.length === 0 && !reason) {\n return undefined;\n }\n // Canonical JSON: sort keys so the digest is stable across process\n // invocations and formatting/key-order changes in the published\n // well-known manifest.\n const primary = manifests[0];\n let displayName: string | undefined;\n let manifestId: string | undefined;\n let manifestDigest: string | undefined;\n const envelopeManifests: NonNullable<\n CapabilityPresentationEnvelopeV1[\"manifests\"]\n > = [];\n for (const m of manifests) {\n envelopeManifests.push({\n name: m.name,\n appId: m.app_id,\n // Deep-copy to prevent later mutations from affecting the digest.\n payload: JSON.parse(JSON.stringify(m)) as Record<string, unknown>,\n });\n }\n if (primary) {\n displayName = primary.name;\n manifestId = primary.app_id;\n manifestDigest = canonicalOpenKeyManifestSha256Hex(primary);\n }\n return {\n protocolVersion: 1,\n displayName,\n reason: reason && reason.length > 0 ? reason : undefined,\n manifestId,\n manifestDigest,\n manifests: envelopeManifests.length > 0 ? envelopeManifests : undefined,\n };\n }\n\n /**\n * Complete sign-in with a versioned OpenKey authorization result.\n *\n * Where `signInWithPreparedSession` completes with a signature over the\n * ORIGINAL prepared SIWE, this method completes with the SIWE bytes the\n * OpenKey widget actually presented and signed (`signedMessage`). It\n * exists because the versioned authorizeTinyCloud protocol lets the user\n * narrow capabilities; the returned bytes may differ from the original\n * request and are the only ones the signature actually verifies against.\n *\n * The `result` parameter is validated at the trust boundary via\n * `validateAuthorizationResultV1` (in sdk-core). Callers should validate\n * BEFORE calling this method so unknown/missing fields are rejected\n * before any session state is created.\n *\n * Validation performed here (defence-in-depth: even a \"valid\" v1 payload\n * must clear these checks before any session state is created):\n * 1. `result.address` matches the local signer's address.\n * 2. `result.signature` recovers to `result.address` when verified against\n * `result.signedMessage`.\n * 3. Every immutable SIWE header field (domain, address, URI, version,\n * chainId, nonce, issuedAt) in the original prepared SIWE is preserved\n * byte-for-byte in `result.signedMessage`. `statement` is NOT in this\n * list because the WASM renders it from the ReCap contents; it MUST\n * change when the ReCap is narrowed.\n * 4. Every capability in `result.signedMessage`'s ReCap block was present\n * in the original prepared SIWE — narrowing OK, broadening rejected.\n * 5. Every `result.selectedActionKeys` entry corresponds to a\n * (resource, action) pair in the returned SIWE.\n */\n async signInWithOpenKeyResult(\n result: {\n protocolVersion: 1;\n address: string;\n signature: string;\n signedMessage: string;\n selectedActionKeys: string[];\n permissions: Array<{ service: string; space: string; path: string; actions: string[] }>;\n },\n prepared: {\n /**\n * The ORIGINAL SIWE the SDK produced via {@link prepareSessionForSigning}.\n * Used as the source-of-truth reference for immutable-header and\n * capability-subset comparison against `result.signedMessage`.\n */\n siwe: string;\n jwk: Record<string, unknown>;\n spaceId: string;\n verificationMethod: string;\n },\n keyId: string,\n jwk: Record<string, unknown>,\n ): Promise<ClientSession> {\n if (result.protocolVersion !== 1) {\n throw new Error(`Unsupported OpenKey protocol version ${result.protocolVersion}`);\n }\n if (!result.signedMessage) {\n throw new Error(\"OpenKey result must include signedMessage\");\n }\n if (!prepared.siwe) {\n throw new Error(\n \"signInWithOpenKeyResult requires prepared.siwe (the SDK-generated SIWE the sign-in was proposed with)\",\n );\n }\n // Verify the signer matches what we expect. If the address that signed\n // does not match the address the local signer will present, refuse the\n // session — the widget returned bytes signed by someone else.\n const expectedAddress = canonicalizeAddress(await this.signer.getAddress());\n if (canonicalizeAddress(result.address) !== expectedAddress) {\n throw new Error(\n `OpenKey returned signature from ${result.address} but expected ${expectedAddress}`,\n );\n }\n\n // (2) Recover the signer from the signature over the exact bytes we are\n // about to complete the session with. SiweMessage.verify() calls\n // ethers.verifyMessage(EIP4361Message, signature) internally and matches\n // the recovered address (case-insensitive) against the message's address\n // field. Any mismatch throws, which is exactly the failure mode we want.\n let parsedSignedSiwe: SiweMessage;\n try {\n parsedSignedSiwe = new SiweMessage(result.signedMessage);\n } catch (err) {\n throw new Error(\n `OpenKey signedMessage is not a parseable SIWE: ${(err as Error).message}`,\n );\n }\n const verifyResult = await parsedSignedSiwe.verify(\n { signature: result.signature },\n { suppressExceptions: true },\n );\n if (!verifyResult.success) {\n const errData = verifyResult.error;\n const type =\n errData && typeof errData === \"object\" && \"type\" in errData\n ? (errData as { type?: string }).type\n : undefined;\n const details =\n errData && typeof errData === \"object\" && \"expected\" in errData\n ? ` (expected=${(errData as { expected?: unknown }).expected}, received=${(errData as { received?: unknown }).received})`\n : \"\";\n throw new Error(\n `OpenKey signature verification failed${type ? `: ${type}` : \"\"}${details}`,\n );\n }\n // Belt-and-braces: the SIWE `address` field must match what OpenKey\n // reported and what the local signer will present. verify() checks\n // signature-vs-siwe-address; we additionally cross-check the caller's\n // claim and the local signer.\n if (\n canonicalizeAddress(parsedSignedSiwe.address) !== expectedAddress\n ) {\n throw new Error(\n `OpenKey signedMessage.address (${parsedSignedSiwe.address}) does not match local signer address (${expectedAddress})`,\n );\n }\n\n // (3) Immutable-fields comparison. Any drift on domain/address/URI/version/\n // chainId/nonce/issuedAt/expirationTime/notBefore/requestId/nonRecapResources\n // means the widget is signing a materially different SIWE than we prepared —\n // potentially binding the session to a different relying party or a different\n // session key.\n //\n // Sol final continuation contract requirement 2: pass `originalHasRecap`\n // so `diffImmutableSiweFields` excludes `statement` for ReCap-bearing\n // SIWEs. WASM's `prepareSession` renders the entire statement from the\n // ReCap contents, so narrowing ALWAYS changes the statement — the\n // ReCap subset check below is the authoritative narrowing gate. For\n // plain SIWE flows (no urn:recap: resource) the statement remains\n // byte-immutable.\n const originalHasRecap = /(?:^|\\n)-\\s+urn:recap:/i.test(prepared.siwe);\n const originalFields = extractImmutableSiweFields(prepared.siwe);\n const signedFields = extractImmutableSiweFields(result.signedMessage);\n const changedFields = diffImmutableSiweFields(originalFields, signedFields, {\n originalHasRecap,\n });\n if (changedFields.length > 0) {\n throw new Error(\n `OpenKey signedMessage altered immutable SIWE fields: ${changedFields.join(\", \")}`,\n );\n }\n\n // (4) Capability subset. The widget may narrow the caller's request but\n // MUST NOT introduce (resource, action) pairs the caller never asked for.\n // Both sides are parsed from their `urn:recap:` resources.\n let originalCaps;\n let signedCaps;\n try {\n originalCaps = extractRecapAttenuations(prepared.siwe);\n } catch (err) {\n throw new Error(\n `Failed to decode prepared SIWE recap: ${(err as Error).message}`,\n );\n }\n try {\n signedCaps = extractRecapAttenuations(result.signedMessage);\n } catch (err) {\n throw new Error(\n `Failed to decode OpenKey signedMessage recap: ${(err as Error).message}`,\n );\n }\n const unauthorized = unauthorizedRecapCapabilities(signedCaps, originalCaps);\n if (unauthorized.length > 0) {\n const previewLimit = 5;\n const preview = unauthorized\n .slice(0, previewLimit)\n .map((u) => `${u.resource}::${u.action}`)\n .join(\", \");\n const overflow =\n unauthorized.length > previewLimit\n ? ` (and ${unauthorized.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey signedMessage broadened authorization beyond the original request: ${preview}${overflow}`,\n );\n }\n\n // Structural check: the signed SIWE must reference the expected spaceId.\n // We accept a substring match because the spaceId appears inside the\n // ReCap capability list rather than as a distinct header.\n if (!result.signedMessage.includes(prepared.spaceId)) {\n throw new Error(\n `OpenKey signedMessage does not reference the expected spaceId ${prepared.spaceId}`,\n );\n }\n\n // (5) `selectedActionKeys` and `permissions` must EXACTLY reflect the\n // capabilities in signedMessage — anything less is a trust boundary\n // violation. Two rules:\n //\n // Rule A (selectedActionKeys covers signedCaps):\n // If signedMessage grants capabilities beyond the structurally-required\n // ones (currently `tinycloud.capabilities/read`), then `selectedActionKeys`\n // MUST include a coverage entry for EVERY (resource, action) pair in\n // signedCaps. Otherwise the client has no evidence that the SDK-visible\n // selection matches the ReCap it is about to trust.\n //\n // Rule B (each selectedActionKeys entry is grounded in signedCaps):\n // Every ID the widget returns must correspond to a real (resource, action)\n // pair in signedCaps. Broadening rejected.\n //\n // Sol continuation contract: the CANONICAL OpenKey action ID format is\n // FOUR NUL-separated parts: `service\\0space\\0path\\0ability`. The keys of\n // `signedCaps` are the raw ReCap resource URIs — `space` for whole-space\n // grants, or `space/path` when a path is present. The action key is\n // `ability` (e.g. `tinycloud.kv/get`). We build a canonical index of\n // granted authority keyed by the four-part tuple and REJECT\n // selectedActionKeys that do not conform to it. Legacy 2-part\n // `resource\\0action` IDs are no longer accepted.\n const grantedPairs = new Set<string>();\n // 4-part index: `${service}\\0${space}\\0${path}\\0${ability}` → canonical\n // resource\\0action pair (used to populate the coverage-check set).\n // `service` is derived from the ability's namespace prefix\n // (`tinycloud.kv/get` → `tinycloud.kv`). `space` and `path` are derived\n // from the resource URI by splitting on the first `/` after the\n // `tinycloud:...:name` prefix.\n const grantedFourPartIndex = new Map<string, string>();\n for (const [resource, actions] of Object.entries(signedCaps)) {\n // Sol final continuation contract requirement 1: use the SHARED\n // canonical resource parser so consumer four-part IDs match the\n // producer's IDs byte-for-byte. Prior inline code left the service\n // segment inside `path` (e.g. `path=\"kv\"` for a `<space>/kv`\n // resource), which produced a different ID than OpenKey emits via\n // WASM `parseRecapFromSiwe` (which strips the service segment). The\n // divergence was the actual production round-trip failure Sol cited.\n const { space, path } = parseCanonicalRecapResource(resource);\n for (const action of Object.keys(actions)) {\n // Populate the coverage set with the canonical resource\\0action\n // pair so Rule A can check every non-required capability got\n // covered by a matching selectedActionKeys entry.\n grantedPairs.add(`${resource}\\0${action}`);\n // Canonical four-part index: derive `service` from the ability\n // prefix. Missing prefix (bare action) is refused server-side\n // in OpenKey — we simply skip it here rather than fabricate a\n // half-form 4-part ID.\n const slashIdx = action.indexOf(\"/\");\n const service = slashIdx > 0 ? action.slice(0, slashIdx) : \"\";\n if (service) {\n grantedFourPartIndex.set(\n `${service}\\0${space}\\0${path}\\0${action}`,\n `${resource}\\0${action}`,\n );\n }\n }\n }\n\n // Sol MAJOR-5: rich-result `permissions` MUST equal the signed\n // authority for EVERY resource/action pair, including structurally-\n // required capabilities. Removing required capabilities from the\n // coverage set let a widget silently omit them from the reported\n // grants — which is fine for user consent (the user cannot remove\n // them anyway) but a wire-format drift for the SDK's authoritative\n // return value. Callers that build a UI on top of `permissions` end\n // up under-reporting authority when required pairs are absent.\n // Track both the full set (for rich-result equality) and the\n // non-required set (retained for selectedActionKeys Rule A which\n // legitimately does not surface required pairs in the widget UI).\n const isStructurallyRequired = (action: string) =>\n action === \"tinycloud.capabilities/read\" || action === \"capabilities/read\";\n\n const nonRequiredGrantedPairs = new Set<string>();\n for (const pair of grantedPairs) {\n const idx = pair.indexOf(\"\\0\");\n const action = idx >= 0 ? pair.slice(idx + 1) : pair;\n if (!isStructurallyRequired(action)) {\n nonRequiredGrantedPairs.add(pair);\n }\n }\n // Sol MAJOR-5: the full granted-pair set — including required\n // capabilities — is what `permissions` must equal exactly.\n const allSignedGrantedPairs = new Set<string>(grantedPairs);\n\n // Rule B — validate each returned selectedActionKeys entry.\n // Build a set of grounded pairs so we can also enforce Rule A.\n // Sol MAJOR-4: dedupe using the raw key first — duplicates in the\n // client-supplied selection would let a subset be reported as\n // full coverage. Callers must send each ID exactly once.\n const seenRawKeys = new Set<string>();\n for (const rawKey of result.selectedActionKeys) {\n if (seenRawKeys.has(rawKey)) {\n throw new Error(\n `OpenKey selectedActionKeys contains duplicate entry ${rawKey}`,\n );\n }\n seenRawKeys.add(rawKey);\n }\n const selectedResourceActionPairs = new Set<string>();\n for (const rawKey of result.selectedActionKeys) {\n const parts = rawKey.split(\"\\0\");\n // Sol continuation contract: OpenKey emits ONLY the canonical\n // four-part `service\\0space\\0path\\0ability` shape. Legacy 2-part\n // IDs are no longer accepted — the previous fallback let a\n // malicious widget forward a `resource\\0action` pair that matched\n // by suffix without proving service canonicalization, which\n // silently expanded authority when service short-names collided.\n if (parts.length !== 4) {\n throw new Error(\n `OpenKey selectedActionKeys entry is malformed (expected canonical 4-part service\\\\0space\\\\0path\\\\0ability): ${rawKey}`,\n );\n }\n const canonical = grantedFourPartIndex.get(rawKey);\n if (!canonical) {\n throw new Error(\n `OpenKey selectedActionKeys entry ${rawKey} is not covered by any granted capability`,\n );\n }\n selectedResourceActionPairs.add(canonical);\n }\n\n // Rule A — every non-required granted pair MUST be covered by at least\n // one selectedActionKeys entry. If nonRequiredGrantedPairs is empty\n // (e.g. bootstrap-only session), we do not require selectedActionKeys\n // to be non-empty. If it is non-empty, the widget must have returned\n // selection metadata for every non-required capability the user was\n // shown; anything else is a UI/wire drift.\n if (nonRequiredGrantedPairs.size > 0) {\n const missingPairs: string[] = [];\n for (const pair of nonRequiredGrantedPairs) {\n if (!selectedResourceActionPairs.has(pair)) {\n missingPairs.push(pair);\n }\n }\n if (missingPairs.length > 0) {\n const previewLimit = 5;\n const preview = missingPairs\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n missingPairs.length > previewLimit\n ? ` (and ${missingPairs.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey selectedActionKeys is missing entries for signedMessage capabilities: ${preview}${overflow}`,\n );\n }\n }\n\n // Sol MAJOR-4: rich-result permissions MUST exactly equal the signed\n // authority. Strict rules:\n // 1. If the signed SIWE grants any capabilities, `permissions` MUST\n // cover ALL of them — an empty `permissions` array with a\n // capability-bearing SIWE is a wire-format drift and is rejected.\n // 2. Every permission entry MUST have a non-empty actions[].\n // 3. Every (permission, action) pair MUST resolve to a real\n // (resource, action) pair in signedCaps via a CANONICAL\n // resolution — no substring fallback (which would let a\n // permission on `space` match a resource on `space/leaked/path`\n // and silently expand authority to unintended paths).\n // 4. Permission entries MUST be duplicate-free after canonical\n // normalization; duplicates would let the same authority be\n // reported twice and mask a missing entry.\n // Sol MAJOR-5: reject empty `permissions` for a capability-bearing\n // SIWE regardless of whether the pairs are structurally required.\n // A signed SIWE with any granted authority MUST come back with a\n // matching non-empty permissions[] — otherwise the SDK cannot\n // reconcile local state with what was actually signed.\n if (\n allSignedGrantedPairs.size > 0 &&\n result.permissions.length === 0\n ) {\n throw new Error(\n \"OpenKey permissions is empty but signedMessage carries capabilities — refusing to accept a session without an authoritative grant list\",\n );\n }\n const permissionCanonicalKeys = new Set<string>();\n const permissionPairsCovered = new Set<string>();\n for (const perm of result.permissions) {\n const { service, space, path, actions } = perm;\n if (typeof service !== \"string\" || typeof space !== \"string\" || typeof path !== \"string\") {\n throw new Error(\n `OpenKey permissions entry has non-string service/space/path (service=${service}, space=${space}, path=${path})`,\n );\n }\n if (!Array.isArray(actions) || actions.length === 0) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) has empty actions — a capability-bearing entry must list at least one action`,\n );\n }\n const canonicalKey = `${service}\\0${space}\\0${path}`;\n if (permissionCanonicalKeys.has(canonicalKey)) {\n throw new Error(\n `OpenKey permissions has duplicate entry for (${service} ${space} ${path})`,\n );\n }\n permissionCanonicalKeys.add(canonicalKey);\n\n // Sol final continuation contract requirement 1: canonical\n // resource resolution matches the shared `parseCanonicalRecapResource`\n // used elsewhere. Two distinct on-wire resource shapes exist:\n // (a) `tinycloud:pkh:...` spaces derived from the WASM\n // `prepareSession` `abilities` map. These encode as\n // `<space>/<short-service>[/<sub-path>]` and the canonical\n // parser strips the `<short-service>` segment out of the\n // reported `path`. To match back to the raw ATT resource key\n // we RECONSTRUCT `<space>/<short>[/<path>]`.\n // (b) Non-`tinycloud:` URNs (e.g. `urn:tinycloud:encryption:...`)\n // emitted via `rawAbilities`. Here the resource URI IS the\n // space verbatim — there is no `<short-service>` segment to\n // reconstruct. `parseCanonicalRecapResource` returns\n // `{ space: uri, path: \"\" }` for these; the matched\n // resource is just `space`.\n //\n // We refuse the substring fallback that would let a permission on\n // `space` silently match a `<space>/leaked/path` resource.\n let expectedResource: string;\n if (space.startsWith(\"tinycloud:\")) {\n const shortService = service.startsWith(\"tinycloud.\")\n ? service.slice(\"tinycloud.\".length)\n : service;\n expectedResource = path\n ? `${space}/${shortService}/${path}`\n : `${space}/${shortService}`;\n } else {\n // Raw ability resource: URI is the resource key verbatim.\n // A non-empty `path` on a non-tinycloud URI would be a wire\n // shape drift — reject rather than silently permit.\n if (path) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) carries a path on a non-tinycloud: resource URI, which is not a recognized encoding`,\n );\n }\n expectedResource = space;\n }\n let matchedResource: string;\n if (signedCaps[expectedResource] !== undefined) {\n matchedResource = expectedResource;\n } else {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) claims grants not confirmed in signedMessage capabilities`,\n );\n }\n const grantedActionsForResource = new Set(\n Object.keys(signedCaps[matchedResource]),\n );\n for (const action of actions) {\n if (typeof action !== \"string\" || !action) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) has non-string action ${String(action)}`,\n );\n }\n if (!grantedActionsForResource.has(action)) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) claims action ${action} not present in signedMessage capabilities`,\n );\n }\n permissionPairsCovered.add(`${matchedResource}\\0${action}`);\n }\n }\n // Sol MAJOR-5: EXACT equality between `permissions` coverage and the\n // signed authority — for every resource/action pair, including\n // structurally-required ones. Any missing or extra pair is a\n // wire-format drift and the SDK refuses to build a session state\n // that does not match the signed bytes byte-for-byte.\n if (allSignedGrantedPairs.size > 0) {\n const missingFromPerms: string[] = [];\n for (const pair of allSignedGrantedPairs) {\n if (!permissionPairsCovered.has(pair)) {\n missingFromPerms.push(pair);\n }\n }\n if (missingFromPerms.length > 0) {\n const previewLimit = 5;\n const preview = missingFromPerms\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n missingFromPerms.length > previewLimit\n ? ` (and ${missingFromPerms.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey permissions is missing entries for signedMessage capabilities: ${preview}${overflow}`,\n );\n }\n const extrasInPerms: string[] = [];\n for (const pair of permissionPairsCovered) {\n if (!allSignedGrantedPairs.has(pair)) {\n extrasInPerms.push(pair);\n }\n }\n if (extrasInPerms.length > 0) {\n const previewLimit = 5;\n const preview = extrasInPerms\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n extrasInPerms.length > previewLimit\n ? ` (and ${extrasInPerms.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey permissions contains entries not present in the signed authority: ${preview}${overflow}`,\n );\n }\n }\n // Retain nonRequiredGrantedPairs reference so tsc doesn't drop it.\n void nonRequiredGrantedPairs;\n\n return this.signInWithPreparedSession(\n {\n siwe: result.signedMessage,\n jwk: prepared.jwk,\n spaceId: prepared.spaceId,\n verificationMethod: prepared.verificationMethod,\n },\n result.signature,\n keyId,\n jwk,\n );\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 authorizationVerdictOf,\n httpResponseError,\n type SpaceHostResult,\n KVService,\n IKVService,\n SQLService,\n ISQLService,\n DuckDbService,\n IDuckDbService,\n HooksService,\n DataVaultService,\n IDataVaultService,\n EncryptionService,\n DecryptTransportResponseError,\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 type FetchFunction,\n type SignRequest,\n type SignResponse,\n INotificationHandler,\n SilentNotificationHandler,\n IENSResolver,\n IWasmBindings,\n ISessionManager,\n type WasmRecapEntry,\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 DelegationStatus,\n DelegationRevocationReceipt,\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_DEFAULT_ONLY_SESSION_REQUEST,\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 ErrorCodes,\n ENCRYPTION_PERMISSION_SERVICE,\n CaveatedDelegationUnsupportedError,\n PermissionNotInManifestError,\n SessionExpiredError,\n canonicalizeRecapCaveats,\n recapCaveatsEqual,\n expandPermissionEntries as expandPermissionEntriesCore,\n isCapabilitySubset,\n isExplicitOnlyAction,\n parseRecapCapabilities,\n // Manifest-driven sign-in\n type Manifest,\n type AbilitiesMap,\n resourceCapabilitiesToAbilitiesMap,\n SERVICE_LONG_TO_SHORT,\n SERVICE_SHORT_TO_LONG,\n KV,\n SQL,\n DUCKDB,\n ENCRYPTION,\n EXPIRY,\n canonicalHashHex,\n canonicalizeEncryptionJson,\n verifyDidKeyEd25519Signature,\n canonicalizeAddress,\n pkhDid,\n resolveTinyCloudHosts,\n publishLocationRecord,\n type LocalNodeIdentityStore,\n principalDidEquals,\n parseNetworkId,\n resolveSecretPath,\n type BuildDecryptInvocationInput,\n type BuiltDecryptInvocation,\n type CanonicalJson,\n type DecryptResponseBody,\n type DecryptTransport,\n type EncryptionCrypto,\n type NetworkDescriptor,\n type CreateOwnerDelegationParams as CoreCreateOwnerDelegationParams,\n type OwnerDelegationPermission,\n type OwnerDelegationReceipt as CoreOwnerDelegationReceipt,\n registerPolicyV3,\n type RegisterPolicyV3Input,\n type RegisterPolicyV3Receipt,\n type ShareDeliveryAuthorizationV3Receipt,\n CREDENTIAL_INVITATION_REQUEST_DOMAIN,\n validateShareDeliveryAuthorizationV3Bytes,\n verifyEip191MessageSignature,\n signCompactUcanRootAuthorization,\n type UnifiedPolicyCapability,\n isStorageFullError,\n STORAGE_FULL_MESSAGE,\n STORAGE_WRITE_TOO_LARGE_MESSAGE,\n} from \"@tinycloud/sdk-core\";\nimport {\n parsePermissionHint,\n} from \"@tinycloud/sdk-services\";\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 type { PortableDelegation, SessionGrantProof, VerifiedSessionGrant } 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\nexport type {\n RegisterPolicyV3Input,\n RegisterPolicyV3Receipt,\n ShareDeliveryAuthorizationV3Receipt,\n} from \"@tinycloud/sdk-core\";\n\n/** Default TinyCloud host */\nconst DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nconst DEFAULT_ENCRYPTION_NETWORK_NAME = \"default\";\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\nconst DECRYPT_ACTION = ENCRYPTION.DECRYPT;\nexport const BOOTSTRAP_COMPLETION_MARKER_KEY = \"system/bootstrap/complete\";\nexport const BOOTSTRAP_COMPLETION_MARKER_VERSION = 1;\nexport const ACCEPTED_MARKER_VERSIONS: readonly number[] = [BOOTSTRAP_COMPLETION_MARKER_VERSION];\nconst NETWORK_ADMIN_TYPE = \"tinycloud.encryption.network-admin/v1\";\n\n/** Input for {@link TinyCloudNode.readSecret}. The target space is required. */\nexport interface SecretReadInput {\n /** Explicit full space URI or an owned-space name. */\n space: string;\n /** Env-style secret name. */\n name: string;\n /** Optional logical secret scope. */\n scope?: string;\n}\n\n/** Safe, validated capability hint returned when the node denies one read phase. */\nexport interface SecretPermissionHint {\n readonly service: \"tinycloud.kv\" | \"tinycloud.encryption\";\n readonly space?: string;\n readonly path: string;\n readonly actions: readonly string[];\n}\n\n/**\n * Safe classified result for an explicit-space secret read.\n *\n * Failure variants contain no raw node response, envelope, plaintext, keys,\n * tokens, or delegation data.\n */\nexport type SecretReadResult =\n | { status: \"ok\"; value: string }\n | { status: \"not_found\" }\n | { status: \"permission_required\"; hint: SecretPermissionHint }\n | { status: \"node_unreachable\" }\n | { status: \"read_failed\" }\n | { status: \"corrupt_envelope\" }\n | { status: \"decrypt_failed\" }\n | { status: \"invalid_payload\" };\n\nfunction isSecretPayload(\n value: unknown,\n): value is { value: string; createdAt: string; updatedAt: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"value\" in value &&\n typeof (value as { value?: unknown }).value === \"string\" &&\n \"createdAt\" in value &&\n typeof (value as { createdAt?: unknown }).createdAt === \"string\" &&\n \"updatedAt\" in value &&\n typeof (value as { updatedAt?: unknown }).updatedAt === \"string\"\n );\n}\n\n/**\n * Full actions the session key's root delegation grants over a space. Used for\n * both the primary space and any additional (e.g. public) spaces registered in\n * {@link TinyCloudNode.initializeV2Services}. URNs come from the canonical\n * capability registry in `@tinycloud/bootstrap` (TC-112).\n */\nconst ROOT_DELEGATION_ACTIONS: string[] = [\n KV.PUT,\n KV.GET,\n KV.DEL,\n KV.LIST,\n KV.METADATA,\n SQL.READ,\n SQL.WRITE,\n SQL.ADMIN,\n SQL.ALL,\n DUCKDB.READ,\n DUCKDB.WRITE,\n DUCKDB.ADMIN,\n DUCKDB.DESCRIBE,\n DUCKDB.EXPORT,\n DUCKDB.IMPORT,\n DUCKDB.ALL,\n];\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\nexport type CreateOwnerDelegationParams = CoreCreateOwnerDelegationParams;\n\nexport interface UnifiedOwnerRootInput {\n readonly ownerDid: string;\n readonly role: \"policy-authority\" | \"policy-enforcement\";\n readonly audienceDid: string;\n readonly policyId: string;\n readonly policyDigestHex: string;\n readonly policyCid: string;\n readonly contentSourceDigestHex: string;\n readonly capabilityCeilingHashHex: string;\n readonly nativeProjectionHashHex: string;\n readonly notBefore: Date;\n readonly expiresAt: Date;\n readonly nodeAudience: string;\n readonly capabilities: readonly UnifiedPolicyCapability[];\n}\n\nexport interface UnifiedOwnerRootReceipt {\n readonly cid: string;\n readonly delegationHeader: { readonly Authorization: string };\n readonly delegateDID: string;\n readonly spaceId: string;\n readonly path: string;\n readonly actions: readonly string[];\n readonly expiry: Date;\n}\n\nfunction unifiedRootAttenuation(\n capabilities: readonly UnifiedPolicyCapability[],\n): Record<string, Record<string, readonly Record<string, unknown>[]>> {\n const attenuation: Record<string, Record<string, readonly Record<string, unknown>[]>> = {};\n for (const capability of capabilities) {\n if (attenuation[capability.resource] !== undefined) throw new Error(\"unified owner root contains a duplicate resource\");\n attenuation[capability.resource] = capability.kind === \"encryption\"\n ? { [capability.action]: [{}] }\n : Object.fromEntries(capability.actions.map((action) => [action, [{\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n }]]));\n }\n return attenuation;\n}\n\nexport function decodeAuthorizationBytes(authorization: string): Uint8Array {\n const encoded = authorization.replace(/^Bearer /i, \"\");\n const match = /^([A-Za-z0-9_-]+)(={1,2})?$/.exec(encoded);\n const unpadded = match?.[1];\n const paddingLength = match?.[2]?.length ?? 0;\n const remainder = unpadded === undefined ? 1 : unpadded.length % 4;\n const expectedPaddingLength = remainder === 2 ? 2 : remainder === 3 ? 1 : 0;\n if (\n unpadded === undefined ||\n remainder === 1 ||\n (paddingLength !== 0 && paddingLength !== expectedPaddingLength)\n ) {\n throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n }\n const decoded = base64UrlDecode(unpadded);\n if (base64UrlEncode(decoded) !== unpadded) {\n throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n }\n return decoded;\n}\n\nexport interface OwnerDelegationReceipt extends CoreOwnerDelegationReceipt {\n readonly delegation: Delegation;\n readonly nodeReceipt: {\n /** Raw /delegate response CID: a commit-event id, not delegation identity. */\n readonly commitEventCid?: string;\n readonly activated: readonly string[];\n readonly skipped: readonly string[];\n };\n}\n\nfunction isOpenKeyAutoSignStrategy(strategy: SignStrategy | undefined): boolean {\n return (strategy as { openKeyAutoSign?: unknown } | undefined)?.openKeyAutoSign === true;\n}\n\nfunction openKeyApproval(\n strategy: SignStrategy | undefined,\n): ((request: SignRequest) => Promise<SignResponse>) | undefined {\n return (strategy as { openKeyRequestApproval?: unknown } | undefined)\n ?.openKeyRequestApproval as ((request: SignRequest) => Promise<SignResponse>) | undefined;\n}\n\n/**\n * Returns true when the signer is an external/interactive signer (browser\n * wallet, EIP-1193 provider, etc.) that will open a UI prompt for every\n * `signMessage()` call.\n *\n * Detection: the config provides a `signer` but NOT a `privateKey`, and the\n * `signStrategy` is neither the OpenKey auto-sign callback nor the auto-sign\n * strategy backed by a local key. In practice:\n * - `privateKey` present → local PrivateKeySigner → non-interactive\n * - `signStrategy.openKeyAutoSign === true` → OpenKey /api/delegate/sign → non-interactive\n * - `signer` only, no `privateKey`, no OpenKey strategy → interactive (browser wallet)\n */\nfunction isInteractiveSigner(config: TinyCloudNodeConfig): boolean {\n if (config.privateKey) {\n // Local key: always non-interactive.\n return false;\n }\n if (isOpenKeyAutoSignStrategy(config.signStrategy)) {\n // OpenKey auto-sign path: non-interactive.\n return false;\n }\n // External signer with no auto-sign strategy. Treat as interactive.\n return config.signer !== undefined;\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\nfunction clonePersistedSessionJwk(jwk: unknown): object {\n if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) {\n throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n\n try {\n const serialized = JSON.stringify(jwk);\n const cloned = serialized === undefined ? undefined : JSON.parse(serialized);\n if (cloned === null || typeof cloned !== \"object\" || Array.isArray(cloned)) {\n throw new Error(\"invalid JWK object\");\n }\n return cloned;\n } catch {\n throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n}\n\nfunction cloneRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): Record<string, unknown>[] {\n if (!caveats) return [];\n const cloneJson = (value: unknown): unknown => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return value.map(cloneJson);\n if (typeof value === \"object\") {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n const copy: Record<string, unknown> = Object.create(null);\n for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n copy[key] = cloneJson(nested);\n }\n return copy;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n try {\n return JSON.parse(JSON.stringify(caveats.map(cloneJson))) as Record<string, unknown>[];\n } catch {\n throw new Error(\"Verified persisted session ReCap contains invalid caveats.\");\n }\n}\n\n/**\n * The WASM verifier serializes ReCap caveats with serde-wasm-bindgen, which\n * returns JSON objects as `Map`s and JSON `null` as `undefined`. Convert\n * exactly those back to JSON: string-keyed `Map`s to plain objects and\n * `undefined` to `null`, recursively. Anything else is passed through for\n * cloneRecapCaveats to accept or reject.\n */\nfunction jsonFromVerifier(value: unknown): unknown {\n if (value === undefined) return null;\n if (Array.isArray(value)) return value.map(jsonFromVerifier);\n if (value instanceof Map) {\n const entries = [...value.entries()];\n if (!entries.every(([key]) => typeof key === \"string\")) return value;\n return Object.fromEntries(entries.map(([key, nested]) => [key, jsonFromVerifier(nested)]));\n }\n if (value !== null && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, jsonFromVerifier(nested)]));\n }\n return value;\n}\n\n/** Verifier ReCap entries with their caveats converted by jsonFromVerifier. */\nfunction verifierRecapEntries<T extends { caveats?: Record<string, unknown>[] }>(entries: T[]): T[] {\n return entries.map((entry) => Array.isArray(entry.caveats)\n ? { ...entry, caveats: entry.caveats.map((caveat) => jsonFromVerifier(caveat) as Record<string, unknown>) }\n : entry);\n}\n\n/**\n * The caveat-preserving ReCap a persisted-session verifier returned, as plain\n * JSON. A binding without the v2 witness cannot reconstruct signed authority.\n */\nfunction exactVerifiedRecap(verified: { verifiedRecap?: unknown }): WasmRecapEntry[] {\n // Caveats are verifier output (Maps, undefined for null): convert them\n // before the strict JSON checks below.\n const exactRecap = Array.isArray(verified.verifiedRecap)\n ? verifierRecapEntries(verified.verifiedRecap as WasmRecapEntry[])\n : verified.verifiedRecap;\n if (!Array.isArray(exactRecap) || !exactRecap.every((entry) =>\n entry !== null && typeof entry === \"object\" &&\n typeof entry.service === \"string\" &&\n typeof entry.space === \"string\" &&\n typeof entry.path === \"string\" &&\n Array.isArray(entry.actions) && entry.actions.every((action: unknown) => typeof action === \"string\") &&\n Array.isArray(entry.caveats) && entry.caveats.every((caveat: unknown) =>\n caveat !== null && typeof caveat === \"object\" && !Array.isArray(caveat)\n )\n )) {\n throw new UnsupportedSessionRestoreError(\n \"it cannot reconstruct caveat-preserving persisted ReCap authority\",\n );\n }\n return exactRecap.map((entry: WasmRecapEntry) => ({\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n}\n\n/** One replaceable set of services bound to a single host/session authority. */\nclass ServiceGraphLifetime {\n private readonly abortController = new AbortController();\n private readonly contexts = new Set<ServiceContext>();\n private retired = false;\n\n constructor(\n private readonly invokeFn: InvokeFunction,\n private readonly invokeAnyFn: InvokeAnyFunction,\n private readonly fetchFn: FetchFunction,\n ) {}\n\n readonly invoke: InvokeFunction = (session, service, path, action, facts) => {\n this.assertActive();\n return this.invokeFn(session, service, path, action, facts);\n };\n\n readonly invokeAny: InvokeAnyFunction = (session, entries, facts) => {\n this.assertActive();\n return this.invokeAnyFn(session, entries, facts);\n };\n\n readonly fetch: FetchFunction = (url, init) => {\n this.assertActive();\n return this.fetchFn(url, {\n ...init,\n signal: this.combineSignals(init?.signal),\n });\n };\n\n track(context: ServiceContext): ServiceContext {\n this.assertActive();\n this.contexts.add(context);\n return context;\n }\n\n retire(): void {\n if (this.retired) return;\n this.retired = true;\n this.abortController.abort();\n try {\n for (const context of this.contexts) {\n try {\n const retire = (context as ServiceContext & { retire?: () => void }).retire;\n if (retire) retire.call(context);\n else context.abort();\n } catch (error) {\n // Graph replacement is committed before retirement. A custom\n // service's best-effort cleanup must not roll that replacement back\n // or leave later contexts active.\n console.error(\"Error retiring service graph context:\", error);\n }\n }\n } finally {\n this.contexts.clear();\n }\n }\n\n assertActive(): void {\n if (this.retired) {\n throw new Error(\"Service graph has been retired by session replacement.\");\n }\n }\n\n private combineSignals(signal?: AbortSignal): AbortSignal {\n if (!signal) return this.abortController.signal;\n const combined = new AbortController();\n const abort = () => combined.abort();\n if (signal.aborted || this.abortController.signal.aborted) {\n abort();\n } else {\n signal.addEventListener(\"abort\", abort, { once: true });\n this.abortController.signal.addEventListener(\"abort\", abort, { once: true });\n }\n return combined.signal;\n }\n}\n\nexport class UnsupportedSessionRestoreError extends Error {\n readonly code = \"RESTORE_SESSION_KEY_REPLACEMENT_UNSUPPORTED\" as const;\n\n constructor(reason = \"it cannot replace and enumerate every live session signer\") {\n super(`Persisted session restore is unsupported by this WASM binding because ${reason}.`);\n this.name = \"UnsupportedSessionRestoreError\";\n }\n}\nexport class InvalidRestoredSessionError extends Error {\n readonly code = \"AUTH_EXPIRED\" as const;\n\n constructor(message = \"Persisted session authority is invalid or expired.\") {\n super(message);\n this.name = \"InvalidRestoredSessionError\";\n }\n}\n\nfunction canonicalRestoredVerificationMethod(\n canonicalVerificationMethod: string,\n persistedVerificationMethod: unknown,\n): string | undefined {\n if (typeof persistedVerificationMethod !== \"string\") return undefined;\n const principal = canonicalVerificationMethod.split(\"#\", 1)[0];\n return persistedVerificationMethod === principal ||\n persistedVerificationMethod === canonicalVerificationMethod\n ? canonicalVerificationMethod\n : undefined;\n}\n\nfunction persistedExpiry(value: unknown): Date {\n if (typeof value !== \"string\") throw new InvalidRestoredSessionError(\"Persisted session must include expiresAt.\");\n const expiry = new Date(value);\n if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {\n throw new InvalidRestoredSessionError();\n }\n return expiry;\n}\n\nfunction sameInstant(left: Date, right: Date): boolean {\n return left.getTime() === right.getTime();\n}\n\n/** `<status> - <server text>` for a failed host/activation request; never drops the status. */\nfunction describeHostFailure(result: SpaceHostResult): string {\n const text = result.error?.trim();\n return text ? `${result.status} - ${text}` : `${result.status}`;\n}\n\nfunction ownerDelegationPermissions(\n params: CreateOwnerDelegationParams,\n): OwnerDelegationPermission[] {\n const hasPermissions = Object.prototype.hasOwnProperty.call(params, \"permissions\");\n const hasLegacy = Object.prototype.hasOwnProperty.call(params, \"path\")\n || Object.prototype.hasOwnProperty.call(params, \"actions\");\n if (hasPermissions === hasLegacy) {\n throw new Error(\"Owner delegation requires exactly one authority shape: path/actions or permissions\");\n }\n\n const permissions: OwnerDelegationPermission[] = [];\n if (hasPermissions) {\n if (!Array.isArray(params.permissions)) {\n throw new Error(\"Owner delegation permissions are invalid\");\n }\n permissions.push(...params.permissions.map((permission) => ({\n service: permission.service,\n path: permission.path,\n actions: [...permission.actions],\n })));\n } else {\n if (typeof params.path !== \"string\" || !Array.isArray(params.actions)) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const byService = new Map<string, string[]>();\n for (const action of params.actions) {\n if (typeof action !== \"string\") {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n const slash = action.indexOf(\"/\");\n const service = slash === -1 ? \"\" : action.slice(0, slash);\n if (SERVICE_LONG_TO_SHORT[service] === undefined) {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n const actions = byService.get(service) ?? [];\n actions.push(action);\n byService.set(service, actions);\n }\n for (const [service, actions] of byService) {\n permissions.push({ service, path: params.path, actions });\n }\n }\n\n if (permissions.length === 0 || permissions.length > 16) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const resources = new Set<string>();\n for (const permission of permissions) {\n if (\n typeof permission.service !== \"string\"\n || SERVICE_LONG_TO_SHORT[permission.service] === undefined\n || typeof permission.path !== \"string\"\n || permission.path.length === 0\n || permission.path.trim() !== permission.path\n || /[\\u0000-\\u001f\\u007f\\\\*]/.test(permission.path)\n || !Array.isArray(permission.actions)\n || permission.actions.length === 0\n || permission.actions.length > 32\n ) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const resourceKey = `${permission.service}\\0${permission.path}`;\n if (resources.has(resourceKey)) {\n throw new Error(\"Owner delegation permissions contain duplicate resources\");\n }\n resources.add(resourceKey);\n const actions = new Set<string>();\n for (const action of permission.actions) {\n if (\n typeof action !== \"string\"\n || !action.startsWith(`${permission.service}/`)\n || action.length === permission.service.length + 1\n || actions.has(action)\n ) {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n actions.add(action);\n }\n if (permission.service === ENCRYPTION_PERMISSION_SERVICE) {\n try {\n parseNetworkId(permission.path);\n } catch {\n throw new Error(\"Owner delegation encryption permission requires a canonical network URN\");\n }\n }\n }\n return permissions;\n}\n\nfunction ownerPermissionsToAbilities(\n permissions: readonly OwnerDelegationPermission[],\n): { readonly abilities: AbilitiesMap; readonly rawAbilities: Record<string, string[]> } {\n const abilities: AbilitiesMap = {};\n const rawAbilities: Record<string, string[]> = {};\n for (const permission of permissions) {\n if (permission.service === ENCRYPTION_PERMISSION_SERVICE) {\n rawAbilities[permission.path] = [...permission.actions];\n continue;\n }\n const shortService = SERVICE_LONG_TO_SHORT[permission.service]!;\n abilities[shortService] ??= {};\n abilities[shortService][permission.path] = [...permission.actions];\n }\n return { abilities, rawAbilities };\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 /** Probe configured/registered local nodes before registry/fallback resolution. Default: true. */\n autoDiscoverLocalNode?: boolean;\n /** Local loopback node URL to probe. Omit to avoid probing loopback. */\n localNodeUrl?: string;\n /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n localLinkName?: string;\n /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n expectedNodeDid?: string;\n /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n localNodeIdentityStore?: LocalNodeIdentityStore;\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: 30 days, `EXPIRY.SESSION_MS`) */\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 account bootstrap support in plain sessions and implicit manifest permissions. 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\n * `EXPIRY.SESSION_MS` (30 days), still capped at the session's own expiry.\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\nexport interface EnsureEncryptionNetworkOptions {\n /**\n * Skip the `GET /encryption/networks/{id}` existence probe and go straight\n * to the create.\n *\n * The probe pays for itself only when the network already exists. On a\n * freshly bootstrapped account it is a guaranteed 404, so it costs a round\n * trip on the cold sign-in path and saves nothing. Creating without it is\n * safe: the server answers `409 Conflict` if the network is already there,\n * which {@link TinyCloudNode.createEncryptionNetwork} resolves by reading the\n * existing descriptor. Set this only when the caller knows the account was\n * just provisioned.\n */\n assumeMissing?: boolean;\n}\n\ninterface RuntimePermissionOperation {\n spaceId?: string;\n resource?: string;\n service: string;\n path: string;\n action: string;\n /** Exact signed ReCap attenuation for this action, if any. */\n caveats?: Record<string, unknown>[];\n}\n\ninterface RuntimePermissionGrant {\n session: ServiceSession;\n delegation: PortableDelegation;\n operations: RuntimePermissionOperation[];\n expiresAt: Date;\n /**\n * Where this grant came from. Drives precedence in\n * {@link TinyCloudNode.findGrantForOperations} (a `\"primary\"` grant — the\n * synthetic representation of the base session's own recap — always\n * out-ranks other covering grants) and gates the public-surface guardrails\n * that must never surface the synthetic primary grant. Optional so existing\n * test constructors and older call sites remain valid.\n */\n provenance?: \"primary\" | \"bootstrap\" | \"delegated\" | \"runtime\";\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 return signBytesWithJwk(new TextEncoder().encode(signingInput), jwk);\n}\n\nasync function signBytesWithJwk(bytes: Uint8Array, jwk: object): Promise<Uint8Array> {\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\n/**\n * A bootstrap step that COMPLETED but did so in a degraded way — e.g. a KV\n * batch write that failed ambiguously and was recovered by per-space\n * reconciliation. Structured (not prose) so callers can branch on `kind` and\n * `code` without parsing messages (TC-361).\n */\nexport interface BootstrapWarning {\n /** The BootstrapStep.id that degraded, e.g. \"account:seed-spaces\"\n * (BootstrapStepBase.id — packages/bootstrap/src/index.ts:642-645). */\n stepId: string;\n /** What kind of degradation. Additive union; one member today. */\n kind: \"batch-write-reconciled\";\n /** ServiceError.code of the underlying failure that was recovered from. */\n code: string;\n /** Human-readable detail. Diagnostics only — never parse this. */\n message: string;\n}\n\n/** Durable attestation that the canonical account bootstrap ceremony completed. */\nexport interface BootstrapCompletionMarker {\n v: number;\n stepIds: string[];\n completedAt: string;\n}\n\ntype BootstrapDecision =\n | { action: \"skip\" }\n | { action: \"run\"; mode: \"fresh\" | \"repair\" };\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 _serviceGraph!: ServiceGraphLifetime;\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 _baseVaults = new Map<string, DataVaultService>();\n private _baseSecrets = new Map<string, ISecretsService>();\n private _secrets = new Map<string, 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 * Memoized `recapOperationsFromSession` result, keyed by the exact SIWE it\n * was parsed from. The primary session is stable for the life of a sign-in,\n * so this avoids re-parsing the recap on every registration.\n */\n private _recapOperationsCache?: { siwe: string; operations: RuntimePermissionOperation[] };\n\n /**\n * Owned space ids this sign-in has already confirmed are hosted. Consulted by\n * {@link ensureOwnedSpaceHostedById}; cleared on every {@link signIn} because\n * hosting is confirmed against the session that was active at the time.\n */\n private readonly confirmedHostedSpaceIds = new Set<string>();\n\n /** Serializes account-registry writes for the active node instance. */\n private accountRegistryTail: Promise<void> = Promise.resolve();\n private pendingAccountRegistrySync?: {\n session: TinyCloudSession;\n promise: Promise<void>;\n };\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 private _activeServiceSession?: ServiceSession;\n\n /**\n * True when the last signIn() detected an interactive signer and skipped\n * client-side bootstrap. Apps can read this to know whether bootstrap was\n * deferred to the server (OpenKey) or requires a separate user action.\n */\n private _bootstrapSkipped = false;\n\n /**\n * Outcome of the last signIn()'s account-bootstrap attempt. `skipped` is\n * true when bootstrap did not complete in this invocation (interactive signer,\n * auto-bootstrap disabled, already provisioned, or a decision/provisioning\n * step failed). `already-provisioned` means the bootstrap was not run here;\n * it does not mean a prior provisioning attempt failed to complete.\n * `reason` carries the cause so apps can surface a \"finish account setup\"\n * call-to-action. `warnings` is\n * present when bootstrap completed, but one or more steps recovered from\n * an ambiguous failure (e.g. a KV batch write reconciled via per-space\n * fallback) — clean vs. recovered runs are otherwise byte-identical.\n */\n private _bootstrapStatus: { skipped: boolean; reason?: string; warnings?: BootstrapWarning[] } = {\n skipped: false,\n };\n\n /** Whether the last signIn() skipped client-side bootstrap because the\n * signer is interactive (browser wallet / EIP-1193 provider). */\n get bootstrapSkipped(): boolean {\n return this._bootstrapSkipped;\n }\n\n /** Outcome of the last signIn()'s account-bootstrap attempt. */\n get bootstrapStatus(): { skipped: boolean; reason?: string; warnings?: BootstrapWarning[] } {\n return this._bootstrapStatus;\n }\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 const operation: RuntimePermissionOperation = {\n spaceId: session.spaceId,\n service: this.invocationServiceName(service),\n path,\n action,\n };\n const grant = this.findGrantForOperation(operation);\n const grantedOperation = grant?.operations.find((candidate) =>\n this.operationCovers(candidate, operation),\n );\n const invocationSession = !grant || grant.provenance === \"primary\"\n ? session\n : grant.session;\n\n // The legacy single-capability binding has no caveat parameter. Calling\n // it for a restored caveated grant would silently broaden the authority,\n // so mint the equivalent one-entry aggregate invocation instead.\n if ((grantedOperation?.caveats?.length ?? 0) > 0) {\n if (!this.wasmBindings.invokeAny) {\n throw new Error(\"WASM binding does not support caveat-preserving invocation\");\n }\n return this.wasmBindings.invokeAny(invocationSession, [{\n spaceId: invocationSession.spaceId,\n service,\n path,\n action,\n caveats: cloneRecapCaveats(grantedOperation!.caveats),\n }], facts);\n }\n\n return this.wasmBindings.invoke(invocationSession, service, path, action, facts);\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 operations = entries.flatMap((entry) => {\n const operation = this.operationFromInvokeAnyEntry(entry);\n return operation ? [operation] : [];\n });\n const grant = this.findGrantForOperations(operations);\n // When the primary grant wins, invoke with the PASSED session (its scoped\n // target `spaceId`), not the stored primary `ServiceSession` — see\n // `selectInvocationSession` for the wrong-space rationale (TC-111 follow-up).\n const invocationSession =\n !grant || grant.provenance === \"primary\" ? session : grant.session;\n const caveatPreservingEntries = grant\n ? entries.map((entry) => {\n const requested = this.operationFromInvokeAnyEntry(entry);\n const granted = requested && grant.operations.find((candidate) =>\n this.operationCovers(candidate, requested),\n );\n if (!granted?.caveats?.length) {\n return entry;\n }\n if (entry.caveats !== undefined &&\n !recapCaveatsEqual(entry.caveats, granted.caveats)) {\n throw new Error(\"Invocation caveats do not match signed ReCap authority.\");\n }\n return { ...entry, caveats: cloneRecapCaveats(granted.caveats) };\n })\n : entries;\n return this.wasmBindings.invokeAny(invocationSession, caveatPreservingEntries, 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 this._serviceGraph = this.createServiceGraphLifetime();\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 const receiveOnlyGraph = this._serviceGraph;\n this._sharingService = new SharingService({\n hosts: [this.config.host!],\n // session: undefined - not needed for receive()\n invoke: receiveOnlyGraph.invoke,\n fetch: receiveOnlyGraph.fetch,\n assertActive: () => receiveOnlyGraph.assertActive(),\n keyProvider: this._keyProvider,\n registry: this._capabilityRegistry,\n createDelegationWasm: (params) => this.createDelegationWrapper(params),\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\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 = receiveOnlyGraph.track(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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: config.autoDiscoverLocalNode,\n localNodeUrl: config.localNodeUrl,\n localLinkName: config.localLinkName,\n expectedNodeDid: config.expectedNodeDid,\n localNodeIdentityStore: config.localNodeIdentityStore,\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 ? config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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 createServiceGraphLifetime(): ServiceGraphLifetime {\n return new ServiceGraphLifetime(\n this.invokeWithRuntimePermissions,\n this.invokeAnyWithRuntimePermissions,\n // Resolve fetch at request time. This keeps the graph-owned lifetime\n // signal while preserving the SDK's existing injectable global fetch\n // behavior (including adapters that install it after construction).\n (url, init) => globalThis.fetch(url, init),\n );\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 /** The registry-resolved Node endpoint and the identity returned by that exact Node. */\n async activeNodeIdentity(): Promise<{ readonly origin: string; readonly nodeDid: string }> {\n const host = this.hosts[0];\n if (host === undefined) throw new Error(\"TinyCloud node host has not been resolved\");\n const parsed = new URL(host);\n if ((parsed.protocol !== \"https:\" && !(parsed.protocol === \"http:\" && (parsed.hostname === \"127.0.0.1\" || parsed.hostname === \"localhost\"))) || parsed.origin !== host) {\n throw new Error(\"TinyCloud node host is not a canonical origin\");\n }\n const nodeDid = await this.fetchNodeId();\n if (!nodeDid.startsWith(\"did:key:z\")) throw new Error(\"TinyCloud node identity is not a did:key\");\n return Object.freeze({ origin: parsed.origin, nodeDid });\n }\n\n /** Publish the active owner Node as a session-signed registry record. */\n async publishActiveNodeLocation(\n registryUrl: string,\n fetchFn: typeof fetch = globalThis.fetch.bind(globalThis),\n ) {\n const node = await this.activeNodeIdentity();\n return publishLocationRecord({\n registryUrl,\n subject: this.credentialHolderDid,\n nodeOrigin: node.origin,\n signer: { type: \"did:key\", signBytes: (bytes) => this.signSessionBytes(bytes) },\n fetch: fetchFn,\n });\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 /** Bare did:key principal used as the credential subject and holder binding. */\n get credentialHolderDid(): string {\n return this.sessionDid.split(\"#\", 1)[0];\n }\n\n /** Canonical verification method for the active credential holder key. */\n get credentialHolderKid(): string {\n const holder = this.credentialHolderDid;\n return `${holder}#${holder.slice(\"did:key:\".length)}`;\n }\n\n /**\n * Return the current session's signed ReCap capabilities after the session\n * has been authenticated or restored. This is intentionally distinct from\n * installed runtime delegations: it reports base-session authority only.\n *\n * Invalid or unparseable signed ReCap material throws so callers fail closed\n * rather than treating a malformed session as unrestricted authority.\n */\n getVerifiedSessionCapabilities(): PermissionEntry[] {\n const session = this.currentTinyCloudSession();\n return session?.siwe ? this.projectSignedRecapCapabilities(session.siwe) : [];\n }\n\n /** Normalize signed capabilities without collapsing nested encryption into raw authority. */\n private projectSignedRecapCapabilities(siwe: string): PermissionEntry[] {\n const projected = this.parseRecapWithCaveats(siwe).map((entry) => {\n const normalized = parseRecapCapabilities(() => [entry], siwe)[0]!;\n if (normalized.service !== \"tinycloud.encryption\") return normalized;\n if (!this.isEncryptionNetworkOperation(\"encryption\", entry.path, entry.space)) {\n return { ...normalized, space: entry.space };\n }\n return {\n service: normalized.service,\n path: normalized.path,\n actions: normalized.actions,\n ...(normalized.caveats === undefined ? {} : { caveats: normalized.caveats }),\n };\n });\n return projected.sort((left, right) =>\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.service.localeCompare(right.service) ||\n left.path.localeCompare(right.path)\n );\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 getDelegationManager: () => this.delegationManager,\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 * Get the currently active session in the shape callers can persist and later\n * pass back to {@link restoreSession}.\n */\n get restorableSession(): TinyCloudSession | undefined {\n return this.currentTinyCloudSession();\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 // Do not replace the active session while its best-effort registry sync is\n // still issuing writes with that session's authority.\n await this.accountRegistryTail;\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._baseVaults.clear();\n this._baseSecrets.clear();\n this._secrets.clear();\n this._spaceService = undefined;\n this._serviceContext = undefined;\n this.runtimePermissionGrants = [];\n this.confirmedHostedSpaceIds.clear();\n\n await this.tc.signIn(options);\n this.syncResolvedHostFromAuth();\n\n // Bind the replacement services to the runtime dependencies active for\n // this sign-in and permanently retire anything captured from the previous\n // session. The authorization flow above remains transactional: a rejected\n // sign-in leaves the existing graph untouched.\n const oldGraph = this._serviceGraph;\n this._serviceGraph = this.createServiceGraphLifetime();\n oldGraph.retire();\n this.tc.retireServices();\n\n // NodeUserAuthorization renames the constructor's \"default\" key when it\n // creates the signed-in session. Keep node-level key accessors in sync so\n // sessionDid and delegation flows use the active key instead of the old ID.\n const signedInSession = this.currentTinyCloudSession();\n if (signedInSession) {\n this.sessionKeyId = signedInSession.sessionKey;\n this.sessionKeyJwk = signedInSession.jwk;\n }\n\n // Initialize service context with session\n this.initializeServices();\n\n // Register the primary session's own recap as the highest-trust\n // (`provenance: \"primary\"`) runtime grant so it always wins invocation\n // selection over broader bootstrap/delegated grants (TC-111). Must run\n // after the primary session is established and after grants were cleared\n // above, so no dupes. `lastActivationSkippedSpaceIds` was already\n // populated by the auth layer's session activation inside `tc.signIn`\n // above, so the skipped-activation exclusion sees the real skip set here.\n const primarySession = this.currentTinyCloudSession();\n if (primarySession) {\n this.registerPrimarySessionGrant(primarySession);\n }\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 this._bootstrapSkipped = false;\n this._bootstrapStatus = { skipped: false };\n\n if (this.config.autoBootstrapAccount === false) {\n this._bootstrapStatus = { skipped: true, reason: \"auto-bootstrap-disabled\" };\n return false;\n }\n if (!this.auth || !this._address) {\n return false;\n }\n\n // Interactive signers (browser wallet / EIP-1193) prompt the user for\n // every signMessage() call. Running bootstrap through an interactive\n // signer would open 10+ sequential sign prompts. Skip client-side\n // bootstrap entirely: the server (OpenKey) handles bootstrap inside\n // POST /api/keys/{keyId}/sign before returning the first signature.\n if (isInteractiveSigner(this.config)) {\n console.debug(\n \"[TinyCloudNode] bootstrap skipped: interactive signer detected. \" +\n \"Server-side bootstrap (OpenKey) is expected to have provisioned the account.\",\n );\n this._bootstrapSkipped = true;\n this._bootstrapStatus = { skipped: true, reason: \"interactive-signer\" };\n return false;\n }\n\n const steps = bootstrapSteps(this._address, this._chainId);\n try {\n const decision = await this.resolveBootstrapDecision(steps);\n if (decision.action === \"skip\") {\n this._bootstrapStatus = { skipped: true, reason: \"already-provisioned\" };\n return false;\n }\n\n const warnings = await this.runAccountBootstrap(steps, { mode: decision.mode });\n await this.writeBootstrapCompletionMarker(steps);\n if (warnings.length > 0) {\n this._bootstrapStatus = { skipped: false, warnings };\n this.notificationHandler.warning(\n `Account bootstrap completed with warnings: ${warnings\n .map((w) => `${w.stepId} (${w.kind}: ${w.code})`)\n .join(\"; \")}`,\n );\n }\n } catch (err) {\n // Bootstrap is provisioning, not a precondition of the session the\n // user just signed: never fail signIn() because of it. Surface the\n // outcome instead so apps can offer a \"finish account setup\" action.\n const reason = err instanceof Error ? err.message : String(err);\n this._bootstrapSkipped = true;\n this._bootstrapStatus = { skipped: true, reason };\n this.notificationHandler.warning(\n `Account bootstrap did not complete: ${reason}`,\n );\n console.warn(`[TinyCloudNode] account bootstrap failed: ${reason}`);\n return false;\n }\n return true;\n }\n\n private async resolveBootstrapDecision(steps: BootstrapStep[]): Promise<BootstrapDecision> {\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 auth = this.auth;\n if (!auth) {\n throw new Error(\"Account bootstrap requires an active wallet session\");\n }\n const skipped = auth.lastActivationSkippedSpaceIds;\n if (skipped.some((spaceId) => enshrinedSpaceIds.has(spaceId))) {\n return { action: \"run\", mode: \"fresh\" };\n }\n\n try {\n const accountSpaceId = this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE);\n const markerPermission: PermissionEntry = {\n service: \"tinycloud.kv\",\n space: accountSpaceId,\n path: BOOTSTRAP_COMPLETION_MARKER_KEY,\n actions: [\"get\"],\n };\n\n if (!this.hasRuntimePermissions([markerPermission])) {\n return { action: \"run\", mode: \"repair\" };\n }\n\n const marker = await this.readBootstrapCompletionMarker();\n if (marker.ok) {\n if (this.isAcceptedBootstrapCompletionMarker(marker.data.data)) {\n return { action: \"skip\" };\n }\n return { action: \"run\", mode: \"repair\" };\n }\n\n if (\n marker.error.code === ErrorCodes.KV_NOT_FOUND &&\n this.markerReadIsUnhostedSpace(marker.error.meta)\n ) {\n return { action: \"run\", mode: \"fresh\" };\n }\n } catch (err) {\n // Marker decision and transport failures are unknown state: make one\n // bounded, idempotent repair attempt instead of treating them as\n // provisioned. Emit this separately from the repair result so callers\n // can diagnose the original decision failure.\n const reason = err instanceof Error ? err.message : String(err);\n this.notificationHandler.warning(\n `Account bootstrap decision failed; attempting one bounded repair: ${reason}`,\n );\n console.warn(`[TinyCloudNode] account bootstrap decision failed: ${reason}`);\n return { action: \"run\", mode: \"repair\" };\n }\n\n return { action: \"run\", mode: \"repair\" };\n }\n\n private async readBootstrapCompletionMarker() {\n return this.kvForSpace(this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE)).get<unknown>(\n BOOTSTRAP_COMPLETION_MARKER_KEY,\n );\n }\n\n private async writeBootstrapCompletionMarker(steps: BootstrapStep[]): Promise<void> {\n if (!this._address) {\n throw new Error(\"Bootstrap completion marker requires an active wallet session\");\n }\n const canonicalStepIds = new Set(\n bootstrapSteps(this._address, this._chainId).map((step) => step.id),\n );\n const providedStepIds = new Set(steps.map((step) => step.id));\n if (\n canonicalStepIds.size !== providedStepIds.size ||\n [...canonicalStepIds].some((stepId) => !providedStepIds.has(stepId))\n ) {\n throw new Error(\"Bootstrap completion marker requires the canonical bootstrap step set\");\n }\n\n const marker: BootstrapCompletionMarker = {\n v: BOOTSTRAP_COMPLETION_MARKER_VERSION,\n stepIds: [...canonicalStepIds],\n completedAt: new Date().toISOString(),\n };\n const written = await this.kvForSpace(this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE)).put(\n BOOTSTRAP_COMPLETION_MARKER_KEY,\n marker,\n );\n if (!written.ok) {\n throw Object.assign(\n new Error(`Failed to write bootstrap completion marker: ${written.error.message}`),\n { cause: written.error },\n );\n }\n }\n\n private isAcceptedBootstrapCompletionMarker(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const entries = Object.entries(value);\n const markerValue = (name: string): unknown =>\n entries.find(([key]) => key === name)?.[1];\n const version = markerValue(\"v\");\n return (\n typeof version === \"number\" &&\n Number.isInteger(version) &&\n ACCEPTED_MARKER_VERSIONS.some((acceptedVersion) => acceptedVersion === version)\n );\n }\n\n private markerReadIsUnhostedSpace(meta: Record<string, unknown> | undefined): boolean {\n return meta?.status === 404;\n }\n\n private async runAccountBootstrap(\n steps: BootstrapStep[],\n { mode }: { mode: \"fresh\" | \"repair\" } = { mode: \"fresh\" },\n ): Promise<BootstrapWarning[]> {\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 warnings: BootstrapWarning[] = [];\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 let session: TinyCloudSession;\n try {\n session = await auth.createBootstrapSession({\n spaceId: step.spaceId,\n capabilityRequest: step.request ?? BOOTSTRAP_SESSION_REQUESTS[step.space],\n rawAbilities,\n });\n } catch (err) {\n // Abort immediately — do not cascade into remaining bootstrap steps.\n // A single clear error is surfaced instead of one error per space.\n throw Object.assign(\n new Error(\n `Account bootstrap aborted: signature rejected for space \"${step.space}\". ` +\n `Cause: ${err instanceof Error ? err.message : String(err)}`,\n ),\n { cause: err },\n );\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.hostOwnedSpaceResult(step.spaceId, \"bootstrap-host\");\n if (!hosted.success) {\n throw Object.assign(\n new Error(`Failed to host bootstrap space ${step.spaceId}: ${describeHostFailure(hosted)}`),\n { cause: hosted },\n );\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 Object.assign(\n new Error(\n `Failed to activate bootstrap session for ${step.spaceId}: ${\n activated.success ? \"space was skipped\" : describeHostFailure(activated)\n }`,\n ),\n { cause: activated },\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 Object.assign(new Error(`Failed to create account index schema: ${ensured.error.message}`), { cause: ensured.error });\n }\n }\n\n if (step.kind === \"seed-spaces\") {\n // One batched KV write + one multi-row index write instead of 5\n // sequential register() calls (TC-373).\n const registered = await this.account.spaces.registerBatch(\n step.spaces.map((space) => ({\n spaceId: space.spaceId,\n name: space.name,\n ownerDid: this.did,\n type: \"owned\",\n permissions: [\"*\"],\n status: \"active\",\n })),\n );\n if (!registered.ok) {\n throw Object.assign(\n new Error(`Failed to seed account spaces: ${registered.error.message}`),\n { cause: registered.error },\n );\n }\n const batchError = registered.data.recoveredFromBatchError;\n if (batchError) {\n warnings.push({\n stepId: step.id,\n kind: \"batch-write-reconciled\",\n code: batchError.code,\n message: batchError.message,\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 // The write is an INSERT OR REPLACE and is safe to repeat during a\n // repair, so skip the manifest-hash pre-read.\n { assumeUnregistered: true },\n );\n if (!registered.ok) {\n throw Object.assign(new Error(`Failed to seed bootstrap applications: ${registered.error.message}`), { cause: registered.error });\n }\n }\n\n if (step.kind === \"encryption-network-create\") {\n // A repair probes before creating because the network may already\n // exist; a 409 remains a race guard in both modes.\n await this.ensureEncryptionNetwork(step.networkId, { assumeMissing: mode === \"fresh\" });\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 Object.assign(\n new Error(`Failed to create secret_records schema: ${migrated.error.message}`),\n { cause: migrated.error },\n );\n }\n }\n }\n\n return warnings;\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 provenance: \"bootstrap\",\n });\n }\n\n /**\n * Map the base session's OWN recap into runtime permission operations.\n *\n * Uses the RAW `parseRecapFromSiwe` binding — NOT `parseRecapCapabilities`,\n * whose `normalizeSpace` collapses `tinycloud:pkh:...:<owner>:<space>` to a\n * bare short name and would conflate two owners' identically-named spaces.\n * We must keep the full owner-scoped URI so a synthetic primary grant can\n * never cover an operation on a different owner's space.\n *\n * Only top-level encryption network entries (`space: \"encryption\"` or\n * absent) become `resource` ops. A network-shaped path nested under a\n * data space remains a `spaceId` op, not raw network authority.\n * One op per action.\n *\n * Returns `[]` for session-only / restored-without-siwe modes and for any\n * unparseable SIWE — the primary grant is simply not registered in that case.\n */\n private recapOperationsFromSession(\n session: TinyCloudSession,\n ): RuntimePermissionOperation[] {\n const siwe = session.siwe;\n if (!siwe) {\n return [];\n }\n if (this._recapOperationsCache?.siwe === siwe) {\n return this._recapOperationsCache.operations;\n }\n let operations: RuntimePermissionOperation[] = [];\n try {\n const entries = this.parseRecapWithCaveats(siwe);\n if (Array.isArray(entries)) {\n operations = entries.flatMap((entry) => {\n const service = this.invocationServiceName(entry.service);\n return entry.actions.map((action) => ({\n ...(this.isEncryptionNetworkOperation(service, entry.path, entry.space)\n ? { resource: entry.path }\n : { spaceId: entry.space }),\n service,\n path: entry.path,\n action,\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n });\n }\n } catch {\n operations = [];\n }\n this._recapOperationsCache = { siwe, operations };\n return operations;\n }\n\n /**\n * Register the base (primary) session's own recap as a synthetic runtime\n * grant tagged `provenance: \"primary\"` so it always out-ranks other covering\n * grants in {@link findGrantForOperations}. This closes the selection-design\n * hazard where a broad — possibly broken — bootstrap/delegated grant could\n * hijack an operation the primary session itself already authorized (TC-111).\n *\n * Two safety exclusions:\n * - Ops whose space is in `lastActivationSkippedSpaceIds` are dropped: the\n * node refused to activate those spaces this sign-in even though the recap\n * claims them. Including them would let the synthetic primary out-rank a\n * working grant and 401 (the \"skipped-activation inverted hijack\").\n * - Encryption `resource` ops are kept as-is (space-independent).\n *\n * No-ops when nothing remains after exclusion. Callers (`signIn`,\n * `restoreSession`) clear `runtimePermissionGrants` first, so no dupes.\n */\n private registerPrimarySessionGrant(session: TinyCloudSession): void {\n const skipped = this.auth\n ? (this.auth as NodeUserAuthorization).lastActivationSkippedSpaceIds ?? []\n : [];\n const operations = this.recapOperationsFromSession(session).filter(\n (operation) =>\n operation.spaceId === undefined ||\n !skipped.some((spaceId) => this.spaceIdsEqual(spaceId, operation.spaceId!)),\n );\n if (operations.length === 0) {\n return;\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 provenance: \"primary\",\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 Object.assign(\n new Error(`Failed to write manifest registry records: ${result.error.message}`),\n { cause: result.error },\n );\n }\n }\n\n private scheduleAccountRegistrySync(): void {\n const session = this.currentTinyCloudSession();\n if (!session || this.pendingAccountRegistrySync?.session === session) {\n return;\n }\n\n const promise = this.enqueueAccountRegistryOperation(session, async () => {\n await this.withAccountRegistryRetry(async () => {\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n await this.account.index.ensure();\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n await this.writeManifestRegistryRecords();\n\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n if (this.currentSessionCanListSpaces()) {\n const spaces = await this.account.spaces.syncAccessible();\n if (!spaces.ok) {\n throw Object.assign(\n new Error(`Failed to sync account spaces: ${spaces.error.message}`),\n { cause: spaces.error },\n );\n }\n }\n // Else: the current session carries a recap that does not grant\n // `tinycloud.space/list` (every manifest/recap session, and the default\n // non-manifest recap alike — its abilities table has no `space` service).\n // `syncAccessible()` depends on `tinycloud.space/list`, which such a\n // session does not hold — see {@link isOwnedSpaceRegistered} — so the\n // owned-space listing is a doomed request that 401s on the wire\n // (`Unauthorized Action: …/space/ tinycloud.space/list`). The account\n // spaces registry is instead maintained by bootstrap seeding +\n // `spaces.register()`, so we skip the invoke entirely rather than emit it.\n });\n });\n\n this.pendingAccountRegistrySync = { session, promise };\n const clearPendingSync = () => {\n if (this.pendingAccountRegistrySync?.promise === promise) {\n this.pendingAccountRegistrySync = undefined;\n }\n };\n void promise.then(clearPendingSync, clearPendingSync);\n }\n\n private enqueueAccountRegistryOperation(\n session: TinyCloudSession,\n task: () => Promise<void>,\n ): Promise<void> {\n const operation = this.accountRegistryTail.then(async () => {\n if (this.currentTinyCloudSession() === session) {\n await task();\n }\n });\n this.accountRegistryTail = operation.catch(() => {});\n return operation;\n }\n\n /**\n * Whether the current primary session may invoke `tinycloud.space/list`.\n *\n * A session with NO parseable recap (session-only / restored-without-siwe)\n * yields zero recap operations — we preserve today's behavior and let\n * `syncAccessible()` run. A session whose parseable recap has entries but\n * none granting `tinycloud.space/list` cannot list owned spaces; the guard\n * skips. Every wallet SIWE session in this stack carries a recap (manifest\n * sessions and the default non-manifest recap alike), and none grant\n * `space/list`, so all of them skip.\n *\n * Reuses the TC-111 {@link recapOperationsFromSession} primitive — no second\n * recap parser.\n */\n private currentSessionCanListSpaces(): boolean {\n const session = this.currentTinyCloudSession();\n const operations = session\n ? this.recapOperationsFromSession(session)\n : [];\n if (operations.length === 0) {\n return true;\n }\n return operations.some(\n (operation) =>\n operation.service === \"space\" &&\n this.actionContains(operation.action, \"tinycloud.space/list\"),\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 // Authorization verdicts are deterministic, not transient: retrying a\n // 401/403 only re-emits the doomed request (the 2026-07-03 recap-storm\n // incident). The typed status/code decides whatever the body says;\n // the message pattern is only a fallback for untyped errors. Warn once\n // and stop; generic errors still get the full retry budget below.\n const verdict = authorizationVerdictOf(error);\n const message = error instanceof Error ? error.message : String(error);\n const isAuthorizationVerdict = verdict === undefined\n ? /Unauthorized Action|\\b(?:401|403)\\b/.test(message)\n : verdict !== \"other\";\n if (isAuthorizationVerdict) {\n console.warn(\n \"TinyCloud account registry sync stopped: authorization verdict is not retryable\",\n error,\n );\n return;\n }\n // A full account space stays full until the owner frees space or\n // upgrades, so retrying only repeats a rejected write. The wrapped\n // SDK error decides; the message is the fallback for untyped errors.\n if (\n isStorageFullError(error as { code?: string }) ||\n isStorageFullError((error as { cause?: { code?: string } } | null)?.cause) ||\n message.includes(STORAGE_FULL_MESSAGE) ||\n message.includes(STORAGE_WRITE_TOO_LARGE_MESSAGE)\n ) {\n console.warn(\"TinyCloud account registry sync stopped: storage is full\", error);\n return;\n }\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 /**\n * Ensure one of this user's owned spaces is hosted, at most once per space\n * per sign-in.\n *\n * Account bootstrap funnels six calls through here (via\n * `AccountService.ensureAccountSpaceHosted`), and each one re-submits\n * `activateSessionWithHost` with the *primary* session. That session's recap\n * covers only `default` and `secrets`, so the account space appears in\n * neither `activated` nor `skipped` and the guard below returns immediately\n * — the repeat calls cannot change the outcome, they only cost round trips.\n *\n * The memo is per sign-in ({@link confirmedHostedSpaceIds} is cleared in\n * `signIn`) and only records confirmed successes. A wrong skip is\n * self-revealing: the next write to the space fails immediately and loudly\n * with `404 Space not found`.\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 if (this.confirmedHostedSpaceIds.has(spaceId)) {\n return;\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 this.confirmedHostedSpaceIds.add(spaceId);\n return;\n }\n\n if (!activation.success && activation.status !== 404) {\n throw Object.assign(\n new Error(`Failed to check owned space ${spaceId}: ${describeHostFailure(activation)}`),\n { cause: activation },\n );\n }\n\n const created = await (this.auth as NodeUserAuthorization).hostOwnedSpaceResult(spaceId);\n if (!created.success) {\n throw Object.assign(\n new Error(`Failed to create owned space ${spaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 Object.assign(\n new Error(\n `Failed to activate session after creating owned space ${spaceId}: ${\n retry.success ? \"space was skipped\" : describeHostFailure(retry)\n }`,\n ),\n { cause: retry },\n );\n }\n this.confirmedHostedSpaceIds.add(spaceId);\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 const session = this.auth?.tinyCloudSession;\n if (!this.auth || !session) {\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).hostOwnedSpaceResult(spaceId);\n if (!hosted.success) {\n throw Object.assign(\n new Error(`Failed to host owned space ${spaceId}: ${describeHostFailure(hosted)}`),\n { cause: hosted },\n );\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 session.delegationHeader,\n );\n if (!activation.success || activation.skipped?.includes(spaceId)) {\n throw Object.assign(\n new Error(\n `Failed to activate session for owned space ${spaceId}: ${\n activation.success ? \"space was skipped\" : describeHostFailure(activation)\n }`,\n ),\n { cause: activation },\n );\n }\n\n try {\n await this.enqueueAccountRegistryOperation(session, async () => {\n await this.account.spaces.register({\n spaceId,\n name,\n ownerDid: this.did,\n type: \"owned\",\n permissions: [\"*\"],\n status: \"active\",\n });\n });\n } catch {\n // Registry write is best-effort; the space is hosted regardless.\n }\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 // signIn schedules its registry sync before returning. Let that operation\n // finish before this explicit read/host/write sequence begins.\n await this.accountRegistryTail;\n\n const spaceId = this.ownedSpaceId(name);\n\n if (await this.isOwnedSpaceRegistered(spaceId)) {\n return spaceId;\n }\n\n return this.hostOwnedSpace(name);\n }\n\n /** Resolve and authenticate the owner encoded by an owned-space URI. */\n credentialSpaceOwnerDid(spaceId: string): string {\n const ownerDid = this.ownerDidFromSpaceId(spaceId);\n if (ownerDid === undefined || !didPrincipalMatches(ownerDid, this.did)) {\n throw new Error(\"Credential space owner does not match the active TinyCloud owner\");\n }\n return ownerDid;\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 /** Additional capability spaces persisted with the primary session. */\n spaces?: Record<string, 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`. When any signed-session\n * metadata is restored, this is required and verified in WASM before\n * local ReCap or expiry authority is installed.\n */\n signature?: string;\n /**\n * Persisted policy expiry. Required when an otherwise valid SIWE omits\n * `Expiration Time`; restore never invents a new renewable lifetime.\n */\n expiresAt?: 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 // Build every part of the restored state against a disposable manager.\n // Nothing live is touched until the commit below.\n let restoredJwk: object;\n try {\n restoredJwk = clonePersistedSessionJwk(sessionData.jwk);\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n if (\n sessionData.chainId !== undefined &&\n (!Number.isSafeInteger(sessionData.chainId) || sessionData.chainId <= 0)\n ) {\n throw new InvalidRestoredSessionError(\"Persisted session chain ID must be a positive safe integer.\");\n }\n const stagedManager = this.wasmBindings.createSessionManager();\n const stagedReplace = stagedManager.replaceSessionKey;\n const liveKeys = this.sessionManager.listSessionKeys;\n const stagedKeys = stagedManager.listSessionKeys;\n if (\n typeof stagedReplace !== \"function\" ||\n typeof liveKeys !== \"function\" ||\n typeof stagedKeys !== \"function\"\n ) {\n throw new UnsupportedSessionRestoreError();\n }\n let stagedKeyId: string;\n let stagedJwk: object;\n let canonicalVerificationMethod: string;\n // Replacing a primary signer without a complete key inventory silently\n // loses receive/share keys. Require the capability rather than guessing.\n const keyIds = liveKeys.call(this.sessionManager);\n if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === \"string\")) {\n throw new UnsupportedSessionRestoreError(\"it cannot reliably enumerate every live session signer\");\n }\n for (const keyId of keyIds) {\n if (keyId === this.sessionKeyId) continue;\n const jwk = this.sessionManager.jwk(keyId);\n if (!jwk) throw new Error(\"missing live session key\");\n stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);\n }\n try {\n stagedKeyId = stagedReplace.call(stagedManager, restoredJwk, this.sessionKeyId);\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n const stagedJwkJson = stagedManager.jwk(stagedKeyId);\n if (!stagedJwkJson) throw new Error(\"missing restored session key\");\n stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));\n canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);\n const restoredVerificationMethod = canonicalRestoredVerificationMethod(\n canonicalVerificationMethod,\n sessionData.verificationMethod,\n );\n if (!restoredVerificationMethod) {\n throw new InvalidRestoredSessionError(\n \"Persisted session verification method does not match its private Ed25519 session key.\",\n );\n }\n const proofValues = [\n sessionData.siwe,\n sessionData.signature,\n sessionData.address,\n sessionData.chainId,\n ];\n const hasPersistedProof = proofValues.every((value) => value !== undefined);\n if (!hasPersistedProof && (proofValues.some((value) => value !== undefined) || sessionData.expiresAt !== undefined)) {\n throw new InvalidRestoredSessionError(\"Persisted session authority metadata is incomplete.\");\n }\n\n let restoredAddress: string | undefined;\n try {\n restoredAddress = hasPersistedProof ? canonicalizeAddress(sessionData.address!) : undefined;\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid wallet address.\");\n }\n let stagedSessionExpiry = new Date(0);\n let stagedRecap: WasmRecapEntry[] = [];\n if (hasPersistedProof) {\n if (typeof this.wasmBindings.validatePersistedSession !== \"function\") {\n throw new UnsupportedSessionRestoreError(\"it cannot verify persisted SIWE authority\");\n }\n const verified = (() => {\n try {\n return this.wasmBindings.validatePersistedSession!({\n delegationHeader: sessionData.delegationHeader,\n delegationCid: sessionData.delegationCid,\n spaceId: sessionData.spaceId,\n jwk: stagedJwk,\n address: restoredAddress!,\n chainId: sessionData.chainId!,\n siwe: sessionData.siwe!,\n signature: sessionData.signature!,\n });\n } catch (error) {\n throw new InvalidRestoredSessionError(error instanceof Error ? error.message : String(error));\n }\n })();\n stagedRecap = exactVerifiedRecap(verified);\n const signedExpiry = verified.expiresAt === undefined\n ? undefined\n : persistedExpiry(verified.expiresAt);\n const persistedPolicyExpiry = sessionData.expiresAt === undefined\n ? undefined\n : persistedExpiry(sessionData.expiresAt);\n if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {\n throw new InvalidRestoredSessionError(\"Persisted session expiry does not match its signed SIWE authority.\");\n }\n stagedSessionExpiry = signedExpiry ?? persistedPolicyExpiry ?? persistedExpiry(undefined);\n }\n const resolvedHost = await this.resolveRestoredHost(\n sessionData.tinycloudHosts,\n restoredAddress,\n sessionData.chainId,\n );\n const stagedHost = resolvedHost ?? this.config.host!;\n // Never blend a metadata-light restore with the prior wallet identity.\n const stagedAddress = restoredAddress;\n const stagedChainId = sessionData.chainId ?? 1;\n const stagedNodeDid = stagedAddress\n ? pkhDid(stagedAddress, stagedChainId)\n : canonicalVerificationMethod;\n const serviceSession: ServiceSession = {\n delegationHeader: sessionData.delegationHeader,\n delegationCid: sessionData.delegationCid,\n spaceId: sessionData.spaceId,\n verificationMethod: restoredVerificationMethod,\n jwk: stagedJwk,\n };\n const stagedTcSession: TinyCloudSession | undefined =\n hasPersistedProof ? {\n address: restoredAddress!,\n chainId: sessionData.chainId!,\n sessionKey: JSON.stringify(stagedJwk),\n spaceId: sessionData.spaceId,\n spaces: sessionData.spaces,\n delegationCid: sessionData.delegationCid,\n delegationHeader: sessionData.delegationHeader,\n verificationMethod: restoredVerificationMethod,\n jwk: stagedJwk as { [k: string]: unknown },\n siwe: sessionData.siwe!,\n signature: sessionData.signature!,\n } : undefined;\n const stagedPrimary = this.stagePrimarySessionState(\n stagedTcSession,\n stagedNodeDid,\n stagedHost,\n stagedSessionExpiry,\n stagedRecap,\n );\n const stagedGraph = this.stageRestoredServiceGraph({\n host: stagedHost,\n manager: stagedManager,\n serviceSession,\n verificationMethod: canonicalVerificationMethod,\n nodeDid: stagedNodeDid,\n address: stagedAddress,\n chainId: stagedChainId,\n tinyCloudSession: stagedTcSession,\n sessionExpiry: stagedSessionExpiry,\n recap: stagedRecap,\n });\n\n // Every operation below is a non-throwing pointer/value swap.\n const oldGraph = this._serviceGraph;\n const oldCore = this.tc;\n this.sessionManager = stagedManager;\n this.sessionKeyId = stagedKeyId;\n this.sessionKeyJwk = stagedJwk;\n if (resolvedHost) this.config.host = resolvedHost;\n this._address = stagedAddress;\n this._chainId = stagedChainId;\n this._serviceContext = stagedGraph.serviceContext;\n this._kv = stagedGraph.kv;\n this._sql = stagedGraph.sql;\n this._duckdb = stagedGraph.duckdb;\n this._hooks = stagedGraph.hooks;\n this._vault = stagedGraph.vault;\n this._encryption = stagedGraph.encryption;\n this._capabilityRegistry = stagedGraph.capabilityRegistry;\n this._keyProvider = stagedGraph.keyProvider;\n this._sharingService = stagedGraph.sharingService;\n this._delegationManager = stagedGraph.delegationManager;\n this._spaceService = stagedGraph.spaceService;\n this._serviceGraph = stagedGraph.graph;\n this._activeServiceSession = serviceSession;\n this._baseSecrets = new Map();\n this._secrets = new Map();\n this._publicKV = undefined;\n this._account = undefined;\n this.tc = stagedGraph.core;\n this._recapOperationsCache = stagedPrimary.cache;\n this.runtimePermissionGrants = stagedPrimary.grants;\n this.confirmedHostedSpaceIds.clear();\n if (this.auth) {\n this.auth.installRestoredSession(stagedManager, stagedTcSession, [stagedHost]);\n this._restoredTcSession = undefined;\n } else {\n this._restoredTcSession = stagedTcSession;\n }\n oldGraph.retire();\n (oldCore as { retireServices?: () => void } | null)?.retireServices?.();\n }\n\n private stagePrimarySessionState(\n session: TinyCloudSession | undefined,\n verificationMethod: string,\n host: string,\n sessionExpiry: Date,\n recap: WasmRecapEntry[],\n ): { cache: { siwe: string; operations: RuntimePermissionOperation[] } | undefined; grants: RuntimePermissionGrant[] } {\n if (!session?.siwe) return { cache: undefined, grants: [] };\n let operations: RuntimePermissionOperation[] = [];\n operations = recap.flatMap((entry) => {\n const service = this.invocationServiceName(entry.service);\n return entry.actions.map((action) => ({\n ...(this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space }),\n service,\n path: entry.path,\n action,\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n });\n const cache = { siwe: session.siwe, operations };\n // Restored authority has no host-activation result yet. Importing a skip\n // list from an unrelated prior session would erase valid restored grants.\n if (operations.length === 0) return { cache, grants: [] };\n const expiresAt = sessionExpiry;\n return {\n cache,\n grants: [{\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: verificationMethod,\n spaceId: session.spaceId,\n path: \"\",\n actions: [...new Set(operations.map((operation) => operation.action))],\n expiry: expiresAt,\n allowSubDelegation: true,\n ownerAddress: session.address,\n chainId: session.chainId,\n host,\n },\n operations,\n expiresAt,\n provenance: \"primary\",\n }],\n };\n }\n\n private stageRestoredServiceGraph(input: {\n host: string;\n manager: ISessionManager;\n serviceSession: ServiceSession;\n verificationMethod: string;\n nodeDid: string;\n address: string | undefined;\n chainId: number;\n tinyCloudSession: TinyCloudSession | undefined;\n sessionExpiry: Date;\n recap: WasmRecapEntry[];\n }): {\n core: TinyCloud | null;\n graph: ServiceGraphLifetime;\n serviceContext: ServiceContext;\n kv: KVService;\n sql: SQLService;\n duckdb: DuckDbService;\n hooks: HooksService;\n vault: DataVaultService;\n encryption: EncryptionService;\n capabilityRegistry: CapabilityKeyRegistry;\n keyProvider: WasmKeyProvider;\n sharingService: SharingService;\n delegationManager: DelegationManager;\n spaceService: SpaceService;\n } {\n // TinyCloud owns the public-KV service graph. Stage a replacement core\n // context alongside the node graph so repeated cross-host restores cannot\n // leave publicKV pointed at a stale or uninitialized context.\n const graph = this.createServiceGraphLifetime();\n const core = this.auth\n ? new TinyCloud(this.auth, {\n invokeAny: graph.invokeAny,\n telemetry: this.config.telemetry,\n })\n : null;\n if (core) {\n core.initializeServices(graph.invoke, [input.host], graph.fetch);\n const coreContext = graph.track(core.serviceContext as ServiceContext);\n coreContext.setSession(input.serviceSession);\n }\n const serviceContext = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n const kv = new KVService({});\n kv.initialize(serviceContext);\n serviceContext.registerService('kv', kv);\n const sql = new SQLService({});\n sql.initialize(serviceContext);\n serviceContext.registerService('sql', sql);\n const duckdb = new DuckDbService({});\n duckdb.initialize(serviceContext);\n serviceContext.registerService('duckdb', duckdb);\n const hooks = new HooksService({});\n hooks.initialize(serviceContext);\n serviceContext.registerService('hooks', hooks);\n serviceContext.setSession(input.serviceSession);\n const encryption = this.createEncryptionService({\n graph,\n host: input.host,\n session: input.serviceSession,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n });\n encryption.initialize(serviceContext);\n serviceContext.registerService('encryption', encryption);\n const vault = this.createVaultService(input.serviceSession.spaceId, kv, encryption, {\n host: input.host,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n serviceGraph: graph,\n });\n vault.initialize(serviceContext);\n serviceContext.registerService('vault', vault);\n\n const capabilityRegistry = new CapabilityKeyRegistry();\n if (input.tinyCloudSession) {\n const session = input.tinyCloudSession;\n // ReCap entries are returned by the verifier that authenticated this\n // SIWE. Persisted space metadata is only a routing hint and cannot add\n // an unsigned space, path, or action to the registry.\n const delegations: Delegation[] = input.recap.map((entry) => ({\n cid: session.delegationCid,\n delegateDID: session.verificationMethod,\n spaceId: this.spaceIdsEqual(entry.space, session.spaceId) ? session.spaceId : entry.space,\n path: entry.path,\n actions: [...entry.actions],\n caveats: cloneRecapCaveats(entry.caveats),\n expiry: input.sessionExpiry,\n isRevoked: false,\n allowSubDelegation: true,\n }));\n if (delegations.length > 0) {\n capabilityRegistry.registerKey({\n id: session.sessionKey,\n did: session.verificationMethod,\n type: \"session\",\n jwk: session.jwk as JWK,\n priority: 0,\n }, delegations);\n }\n }\n const delegationManager = new DelegationManager({\n hosts: [input.host],\n session: input.serviceSession,\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n });\n const keyProvider = new WasmKeyProvider({ sessionManager: input.manager });\n const sharingService = new SharingService({\n hosts: [input.host],\n invoke: graph.invoke,\n fetch: graph.fetch,\n assertActive: () => graph.assertActive(),\n keyProvider,\n registry: capabilityRegistry,\n createDelegationWasm: (params) => this.createDelegationWrapper(params),\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\n createKVService: (config) => {\n const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, '') });\n const context = graph.track(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 context.setSession(config.session);\n service.initialize(context);\n return service;\n },\n });\n sharingService.updateConfig({\n session: input.serviceSession,\n delegationManager,\n sessionExpiry: input.sessionExpiry,\n createDelegationWasm: (params) => {\n graph.assertActive();\n return this.createDelegationWrapper(params);\n },\n onRootDelegationNeeded: this.signer ? async (params) => {\n graph.assertActive();\n const delegation = await this.createRootDelegationForSharing(\n params,\n () => graph.assertActive(),\n );\n graph.assertActive();\n return delegation;\n } : undefined,\n });\n const spaceService = new SpaceService({\n hosts: [input.host],\n session: input.serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n capabilityRegistry,\n userDid: input.nodeDid,\n createKVService: (spaceId) => {\n graph.assertActive();\n const scopedKv = new KVService({});\n const context = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n context.setSession({ ...input.serviceSession, spaceId });\n scopedKv.initialize(context);\n return scopedKv;\n },\n createVaultService: (spaceId) => {\n graph.assertActive();\n const scopedKv = new KVService({});\n const context = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n context.setSession({ ...input.serviceSession, spaceId });\n scopedKv.initialize(context);\n const scopedVault = this.createVaultService(spaceId, scopedKv, encryption, {\n host: input.host,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n serviceGraph: graph,\n });\n scopedVault.initialize(context);\n return scopedVault;\n },\n createSecretsService: (spaceId) => {\n graph.assertActive();\n return this.secretsForSpace(spaceId);\n },\n createDelegation: async (params) => {\n graph.assertActive();\n try {\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 ? params.expiry.getTime() - Date.now() : undefined,\n });\n return { ok: true as const, data: {\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 } catch (error) {\n return { ok: false as const, error: {\n code: \"CREATION_FAILED\",\n message: error instanceof Error ? error.message : String(error),\n service: \"delegation\",\n }};\n }\n },\n onSpaceRegistered: async (space) => {\n graph.assertActive();\n await this.account.spaces.register(space);\n },\n });\n spaceService.updateConfig({ sharingService });\n return { core, graph, serviceContext, kv, sql, duckdb, hooks, vault, encryption, capabilityRegistry, keyProvider, sharingService, delegationManager, spaceService };\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 * Mint a multi-capability invocation through the established session key.\n * Callers receive only the signed headers; session key material remains\n * owned by the session manager and is never part of the caller contract.\n */\n invokeAny(\n entries: Parameters<InvokeAnyFunction>[1],\n facts?: Parameters<InvokeAnyFunction>[2],\n ): ReturnType<InvokeAnyFunction> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return this._serviceGraph.invokeAny(session, entries, facts);\n }\n\n /** Sign protocol bytes with the established in-memory session key. */\n async signSessionBytes(bytes: Uint8Array): Promise<Uint8Array> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return signBytesWithJwk(bytes, session.jwk);\n }\n\n /** Author a proofless Policy/v3 owner root with the authenticated holder key. */\n async createUnifiedOwnerRoot(input: UnifiedOwnerRootInput): Promise<UnifiedOwnerRootReceipt> {\n const ownerDid = this.credentialHolderDid;\n if (input.ownerDid !== ownerDid) throw new Error(\"unified owner root signer does not match owner DID\");\n const facts = {\n role: input.role,\n mode: input.role === \"policy-authority\" ? \"policy-source\" : \"conditional-mint\",\n ownerDid,\n policyId: input.policyId,\n policyDigestHex: input.policyDigestHex,\n policyCid: input.policyCid,\n contentSourceDigestHex: input.contentSourceDigestHex,\n capabilityCeilingHashHex: input.capabilityCeilingHashHex,\n nativeProjectionHashHex: input.nativeProjectionHashHex,\n nodeAudience: input.nodeAudience,\n ...(input.role === \"policy-enforcement\" ? { enforcerDid: input.audienceDid } : {}),\n };\n const root = await signCompactUcanRootAuthorization({\n issuerDid: ownerDid,\n audienceDid: input.audienceDid,\n attenuation: unifiedRootAttenuation(input.capabilities),\n facts: [facts],\n notBefore: Math.floor(input.notBefore.getTime() / 1000),\n expiresAt: Math.floor(input.expiresAt.getTime() / 1000),\n nonce: base64UrlEncode(crypto.getRandomValues(new Uint8Array(16))),\n sign: (bytes) => this.signSessionBytes(bytes),\n });\n const kv = input.capabilities.find((capability) => capability.kind === \"kv\");\n const resource = kv?.resource ?? \"\";\n const marker = resource.indexOf(\"/kv/\");\n return {\n cid: root.cid,\n delegationHeader: { Authorization: root.authorization },\n delegateDID: input.audienceDid,\n spaceId: marker === -1 ? \"\" : resource.slice(\"tinycloud://\".length, marker),\n path: marker === -1 ? resource : resource.slice(marker + 4),\n actions: kv?.actions ?? [],\n expiry: input.expiresAt,\n };\n }\n\n /** Apply only an already-enabled signing policy to the exact credential request. */\n async autoSignCredentialBytes(bytes: Uint8Array): Promise<Uint8Array | undefined> {\n const strategy = this.config.signStrategy;\n if (strategy?.type === \"auto-sign\") return this.signSessionBytes(bytes);\n if (strategy?.type !== \"callback\" || !isOpenKeyAutoSignStrategy(strategy)) return undefined;\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n const request = {\n address: this.address ?? \"\",\n chainId: this.session?.chainId ?? this._chainId,\n message: new TextDecoder().decode(bytes),\n type: \"message\" as const,\n purpose: \"message\" as const,\n };\n const decision = await strategy.handler(request);\n if (!decision.approved) {\n if (decision.needsApproval) return undefined;\n throw new Error(decision.reason ?? \"OpenKey automatic credential signing was rejected\");\n }\n if (\n typeof decision.signature !== \"string\" ||\n !(await verifyEip191MessageSignature(\n request.message,\n decision.signature,\n request.address,\n ))\n ) {\n throw new Error(\"OpenKey credential signature evidence is invalid\");\n }\n return this.signSessionBytes(bytes);\n }\n\n /** Invoke the configured interactive approval strategy before session signing. */\n async approveCredentialBytes(bytes: Uint8Array): Promise<Uint8Array> {\n const strategy = this.config.signStrategy;\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n const request = {\n address: this.address ?? \"\",\n chainId: this.session?.chainId ?? this._chainId,\n message: new TextDecoder().decode(bytes),\n type: \"message\" as const,\n purpose: \"message\" as const,\n };\n const approval = isOpenKeyAutoSignStrategy(strategy)\n ? openKeyApproval(strategy)\n : strategy?.type === \"callback\"\n ? strategy.handler\n : undefined;\n if (approval) {\n const decision = await approval(request);\n if (!decision.approved) throw new Error(decision.reason ?? \"Credential signing was rejected\");\n if (\n decision.signature !== undefined &&\n !(await verifyEip191MessageSignature(\n request.message,\n decision.signature,\n request.address,\n ))\n ) {\n throw new Error(\"OpenKey credential signature evidence is invalid\");\n }\n return this.signSessionBytes(bytes);\n }\n if (strategy?.type === \"auto-reject\") throw new Error(\"Credential signing was rejected\");\n if (this.config.signer) {\n await this.config.signer.signMessage(request.message);\n return this.signSessionBytes(bytes);\n }\n throw new Error(\"Interactive OpenKey approval is not configured\");\n }\n\n /** Bind a session-signed invocation to the canonical service audience. */\n async bindInvocationAudience(authorization: string, audience: string): Promise<string> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return rewriteInvocationAudience(authorization, audience, session.jwk);\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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 ? this.config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 ? this.config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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(\n this._serviceGraph.invoke,\n [this.config.host!],\n this._serviceGraph.fetch,\n );\n this._serviceGraph.track(this.tc!.serviceContext as ServiceContext);\n\n // Create service context\n this._serviceContext = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceGraph.invoke,\n invokeAny: this._serviceGraph.invokeAny,\n fetch: this._serviceGraph.fetch,\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 getEncryptionNetworkIdForSpace(\n spaceId: string,\n name = DEFAULT_ENCRYPTION_NETWORK_NAME,\n ): string {\n const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? this.did;\n return `urn:tinycloud:encryption:${ownerDid}:${name}`;\n }\n\n private ownerDidFromSpaceId(spaceId: string): string | undefined {\n if (!spaceId.startsWith(\"tinycloud:\")) return undefined;\n const body = spaceId.slice(\"tinycloud:\".length);\n const lastSeparator = body.lastIndexOf(\":\");\n if (lastSeparator <= 0) return undefined;\n const owner = body.slice(0, lastSeparator);\n if (owner.startsWith(\"did:\")) return owner;\n if (!owner.includes(\":\")) return undefined;\n return `did:${owner}`;\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 /**\n * Runtime-permission helpers can be used from an authenticated Node session\n * before its public ServiceContext is initialized. They still need the\n * current signed session, never an optional or stale authority object.\n */\n private requireEncryptionSession(): ServiceSession {\n const session = this._serviceContext?.session ?? this.auth?.tinyCloudSession;\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 /**\n * The node DID for {@link config.host}.\n *\n * Sign-in already performs `GET /info` for the protocol-version check, and\n * that response carries `nodeId`, so reuse it rather than fetching `/info` a\n * second time. Only a value recorded for this exact host qualifies; older\n * nodes that omit `nodeId` fall through to the fetch.\n */\n private async fetchNodeId(): Promise<string> {\n const cached = this.auth?.nodeIdForHost(this.config.host!);\n if (cached) return cached;\n\n const response = await fetch(`${this.config.host}/info`);\n if (!response.ok) {\n throw await httpResponseError(response, \"Failed to fetch node info\");\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 }, binding?: {\n graph: ServiceGraphLifetime;\n session: ServiceSession;\n }): Promise<{ authorization: string; invocationCid: string }> {\n binding?.graph.assertActive();\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 = binding?.session ?? this.requireEncryptionSession();\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 binding?.graph.assertActive();\n return {\n authorization: audienceBound,\n invocationCid: this.wasmBindings.computeCid(\n new TextEncoder().encode(audienceBound),\n 0x55n,\n ),\n };\n }\n\n private async fetchEncryptionNetworkAt(\n host: string,\n networkId: string,\n fetchFn: FetchFunction,\n ): Promise<NetworkDescriptor | null> {\n const response = await fetchFn(\n `${host}/encryption/networks/${encodeURIComponent(networkId)}`,\n );\n if (response.status === 404) return null;\n if (!response.ok) {\n throw await httpResponseError(response, `Failed to fetch encryption network ${networkId}`);\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 private createEncryptionService(binding?: {\n graph: ServiceGraphLifetime;\n host: string;\n session: ServiceSession;\n did: string;\n address: string | undefined;\n chainId: number;\n }): EncryptionService {\n const graph = binding?.graph ?? this._serviceGraph;\n const host = binding?.host ?? this.config.host!;\n // The public service path always has a ServiceContext. Keep the auth-session\n // fallback for the internal runtime-permission helpers, which construct an\n // encryption service before a ServiceContext is installed. Both paths bind\n // the resulting service to this graph, so a later graph replacement still\n // retires the captured service permanently.\n const session = binding?.session ?? this.requireEncryptionSession();\n const did = binding?.did ?? this.did;\n const address = binding?.address ?? this._address;\n const chainId = binding?.chainId ?? this._chainId;\n const crypto = this.createEncryptionCrypto();\n // Successful descriptor lookups are immutable for a key version. Cache\n // and coalesce them for this session graph; replacing the graph replaces\n // this cache. Misses and failures remain retryable.\n const descriptorCache = new Map<string, Promise<NetworkDescriptor | null>>();\n const transport: DecryptTransport = {\n postDecrypt: async ({ networkId, authorization, canonicalBody, signal }) => {\n graph.assertActive();\n const response = await graph.fetch(\n `${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 signal,\n },\n );\n graph.assertActive();\n if (!response.ok) {\n // A decrypt denial identifies the attempted authority, not a permission\n // named by the response body, which may describe another operation.\n const permissionHint = response.status === 401 || response.status === 403\n ? parsePermissionHint({\n service: \"tinycloud.encryption\",\n path: networkId,\n actions: [\"tinycloud.encryption/decrypt\"],\n })\n : undefined;\n throw new DecryptTransportResponseError(response.status, permissionHint);\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 graph.assertActive();\n const signed = await this.signRawNetworkAuthorization({\n targetNode: input.targetNode,\n networkId: input.networkId,\n action: DECRYPT_ACTION,\n facts: input.facts,\n }, { graph, session });\n graph.assertActive();\n return {\n ...signed,\n canonicalBody: canonicalizeEncryptionJson(\n input.body as unknown as CanonicalizableEncryptionJson,\n ),\n };\n },\n },\n transport,\n node: {\n fetchByNetworkId: async (networkId) => {\n graph.assertActive();\n let pending = descriptorCache.get(networkId);\n if (!pending) {\n pending = this.fetchEncryptionNetworkAt(host, networkId, graph.fetch)\n .then((descriptor) => {\n if (descriptor === null) descriptorCache.delete(networkId);\n return descriptor;\n })\n .catch((error) => {\n descriptorCache.delete(networkId);\n throw error;\n });\n descriptorCache.set(networkId, pending);\n }\n const descriptor = await pending;\n graph.assertActive();\n return descriptor;\n },\n },\n wellKnown: {\n fetchWellKnown: async (principal, discoveryKey) => {\n graph.assertActive();\n if (!address || !didPrincipalMatches(principal, did)) {\n return null;\n }\n const publicSpaceId = makePublicSpaceId(address, chainId);\n const encodedKey = discoveryKey.split(\"/\").map(encodeURIComponent).join(\"/\");\n const response = await graph.fetch(\n `${host}/public/${encodeURIComponent(publicSpaceId)}/kv/${encodedKey}`,\n { method: \"GET\" },\n );\n graph.assertActive();\n if (!response.ok) {\n return null;\n }\n const body = await response.json() as\n | NetworkDescriptor\n | { descriptor?: NetworkDescriptor };\n graph.assertActive();\n return \"descriptor\" in body && body.descriptor\n ? body.descriptor\n : (body as NetworkDescriptor);\n },\n },\n assertActive: () => graph.assertActive(),\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(\n spaceId: string,\n kv: IKVService,\n encryptionService = this.getEncryptionService(),\n nodeContext?: {\n host: string;\n did: string;\n address: string | undefined;\n chainId: number;\n serviceGraph?: ServiceGraphLifetime;\n },\n ): DataVaultService {\n const wasm = this.wasmBindings;\n const serviceGraph = nodeContext?.serviceGraph ?? this._serviceGraph;\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 const did = nodeContext?.did ?? this.did;\n const address = nodeContext?.address ?? this._address;\n const chainId = nodeContext?.chainId ?? this._chainId;\n const host = nodeContext?.host ?? this.config.host!;\n const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? did;\n return new DataVaultService({\n spaceId,\n crypto: vaultCrypto,\n encryption: {\n networkId: `urn:tinycloud:encryption:${ownerDid}:${DEFAULT_ENCRYPTION_NETWORK_NAME}`,\n service: encryptionService,\n decryptCapabilityProof: () => ({\n proofs: [this.requireServiceSession().delegationCid],\n }),\n },\n tc: {\n kv,\n ensurePublicSpace: async () => {\n try {\n serviceGraph.assertActive();\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() {\n serviceGraph.assertActive();\n return self._publicKV ?? self.tc!.publicKV;\n },\n readPublicSpace: <T>(host: string, targetSpaceId: string, key: string) =>\n TinyCloud.readPublicSpace<T>(host, targetSpaceId, key),\n makePublicSpaceId: TinyCloud.makePublicSpaceId,\n did,\n address: address ?? \"\",\n chainId,\n hosts: [host],\n },\n });\n }\n\n /**\n * Initialize the v2 delegation system services.\n * @internal\n */\n private initializeV2Services(serviceSession: ServiceSession): void {\n const graph = this._serviceGraph;\n\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: [...ROOT_DELEGATION_ACTIONS],\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: [...ROOT_DELEGATION_ACTIONS],\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 accountSpaceId: this.accountSpaceId,\n session: serviceSession,\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n });\n\n // Initialize SpaceService\n this._spaceService = new SpaceService({\n hosts: [this.config.host!],\n session: serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n capabilityRegistry: this._capabilityRegistry,\n userDid: this.did,\n createKVService: (spaceId: string) => {\n graph.assertActive();\n return this.createSpaceScopedKVService(spaceId);\n },\n createVaultService: (spaceId: string) => {\n graph.assertActive();\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 createSecretsService: (spaceId: string) => {\n graph.assertActive();\n return this.secretsForSpace(spaceId);\n },\n // Enable space.delegations.create() via SIWE-based delegation\n createDelegation: async (params) => {\n try {\n graph.assertActive();\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 graph.assertActive();\n await this.account.spaces.register(space);\n },\n });\n\n // A SharingService retains its invoke/fetch functions and lifetime guard.\n // Recreate it for this graph instead of updating the receive-only instance\n // from the graph that was just retired during a subsequent sign-in.\n this._sharingService = new SharingService({\n hosts: [this.config.host!],\n session: serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n assertActive: () => graph.assertActive(),\n keyProvider: this._keyProvider,\n registry: this._capabilityRegistry,\n delegationManager: this._delegationManager,\n sessionExpiry: this.getSessionExpiry(),\n createDelegationWasm: (params) => {\n graph.assertActive();\n return this.createDelegationWrapper(params);\n },\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\n createKVService: (config) => {\n graph.assertActive();\n const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, \"\") });\n const context = graph.track(new ServiceContext({\n invoke: config.invoke,\n fetch: config.fetch ?? graph.fetch,\n hosts: config.hosts,\n telemetry: this.config.telemetry,\n }));\n context.setSession(config.session);\n service.initialize(context);\n return service;\n },\n onRootDelegationNeeded: this.signer\n ? async (params) => {\n graph.assertActive();\n const delegation = await this.createRootDelegationForSharing(\n params,\n () => graph.assertActive(),\n );\n graph.assertActive();\n return delegation;\n }\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 the SESSION tier (30 days) 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 // Session storage carries the verification method as a DID URL\n // (`did:key:...#key-id`). The Rust UCAN builder expects the principal\n // DID here and rejects the fragment as an invalid audience DID.\n verificationMethod: params.session.verificationMethod.split(\"#\", 1)[0],\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 async createOwnerDelegation(\n params: CreateOwnerDelegationParams,\n assertActive?: () => void,\n ): Promise<OwnerDelegationReceipt> {\n const assertOwnerGraphActive = assertActive ?? this._serviceGraph.assertActive.bind(this._serviceGraph);\n assertOwnerGraphActive();\n if (!params.delegateDid.startsWith(\"did:key:\")) {\n throw new Error(\"Owner delegation requires an external did:key audience and bounded capabilities\");\n }\n const permissions = ownerDelegationPermissions(params);\n const now = new Date();\n if (!(params.expiresAt instanceof Date) || params.expiresAt.getTime() <= now.getTime() || params.expiresAt.getTime() - now.getTime() > EXPIRY.MAX_MS) {\n throw new Error(\"Owner delegation expiry must be explicit, future, and within EXPIRY.MAX_MS\");\n }\n if (!this.signer) throw new Error(\"Owner wallet signer is required\");\n const session = this.currentTinyCloudSession();\n if (!session) throw new Error(\"Owner session is required\");\n const ownerDid = pkhDid(session.address, session.chainId);\n for (const permission of permissions) {\n if (\n permission.service === ENCRYPTION_PERMISSION_SERVICE\n && !principalDidEquals(parseNetworkId(permission.path).ownerDid, ownerDid)\n ) {\n throw new Error(\"Owner delegation cannot grant a foreign encryption network\");\n }\n }\n const { abilities, rawAbilities } = ownerPermissionsToAbilities(permissions);\n const primary = permissions[0]!;\n\n const host = this.config.host!;\n const prepared = this.wasmBindings.prepareSession({\n abilities,\n ...(Object.keys(rawAbilities).length === 0 ? {} : { rawAbilities }),\n address: this.wasmBindings.ensureEip55(session.address),\n chainId: session.chainId,\n domain: this.siweDomain,\n issuedAt: now.toISOString(),\n expirationTime: params.expiresAt.toISOString(),\n spaceId: params.spaceId,\n delegateUri: params.delegateDid,\n });\n const signature = await this.signer.signMessage(prepared.siwe);\n assertOwnerGraphActive();\n const delegationSession = this.wasmBindings.completeSessionSetup({ ...prepared, signature });\n const activation = await activateSessionWithHost(host, delegationSession.delegationHeader);\n assertOwnerGraphActive();\n if (!activation.success) {\n throw Object.assign(\n new Error(`Owner delegation import failed: ${activation.status} ${activation.error ?? \"\"}`.trim()),\n { cause: activation },\n );\n }\n const delegation: Delegation = {\n cid: delegationSession.delegationCid,\n delegateDID: params.delegateDid,\n delegatorDID: ownerDid,\n spaceId: params.spaceId,\n path: primary.path,\n actions: [...primary.actions],\n expiry: params.expiresAt,\n isRevoked: false,\n allowSubDelegation: true,\n createdAt: now,\n authHeader: delegationSession.delegationHeader.Authorization,\n };\n return {\n delegation,\n signedDagCbor: decodeAuthorizationBytes(delegationSession.delegationHeader.Authorization),\n delegationCid: delegationSession.delegationCid,\n permissions,\n nodeReceipt: {\n commitEventCid: (activation as typeof activation & { commitEventCid?: string }).commitEventCid,\n activated: activation.activated ?? [],\n skipped: activation.skipped ?? [],\n },\n };\n }\n\n /** Register a signed policy and sibling roots with this Node's Policy/v3 runtime. */\n async registerPolicy(\n params: Omit<RegisterPolicyV3Input, \"nodeOrigin\" | \"fetch\">,\n ): Promise<RegisterPolicyV3Receipt> {\n this._serviceGraph.assertActive();\n return registerPolicyV3({\n ...params,\n nodeOrigin: this.config.host!,\n fetch: globalThis.fetch.bind(globalThis),\n });\n }\n\n /** Authorize one short-lived v3 delivery against the signed v3 envelope and registered roots. */\n async authorizeShareDeliveryV3(input: {\n readonly envelope: Record<string, CanonicalJson | undefined>;\n /** Canonical sealed recipient envelope: version || nonce || ciphertext+tag. */\n readonly sealedEnvelope: string;\n /** Base64url 32-byte envelope key; it must also be the URL fragment key. */\n readonly envelopeKey: string;\n readonly shareCid: string;\n readonly resourcePath: string;\n readonly recipientEmail: string;\n readonly shareUrl: string;\n readonly documentName: string;\n readonly expiresAt: string;\n readonly deliveryAudience: string;\n /** Stable caller retry identity. It is hashed into the protocol's 16-byte JTI. */\n readonly idempotencyKey: string;\n }): Promise<ShareDeliveryAuthorizationV3Receipt> {\n const session = this.currentTinyCloudSession();\n const serviceSession = this._serviceContext?.session;\n if (!session || !serviceSession) throw new Error(\"Share delivery requires an authenticated session\");\n const idempotencyBytes = new TextEncoder().encode(input.idempotencyKey);\n if (idempotencyBytes.byteLength === 0 || idempotencyBytes.byteLength > 512) {\n throw new Error(\"Share delivery idempotency key is invalid\");\n }\n // Node and OpenCredentials deduplicate on the signed 16-byte JTI/nonce.\n // Never send the caller's opaque retry key over the wire: it can contain\n // application identifiers and has no protocol meaning beyond this binding.\n const jtiDigest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", idempotencyBytes));\n const body = {\n envelope: input.envelope,\n sealedEnvelope: input.sealedEnvelope,\n envelopeKey: input.envelopeKey,\n shareCid: input.shareCid,\n recipientEmail: input.recipientEmail,\n shareUrl: input.shareUrl,\n documentName: input.documentName,\n jti: base64UrlEncode(jtiDigest.slice(0, 16)),\n expiresAt: new Date(input.expiresAt).toISOString().replace(/\\.\\d{3}Z$/, \"Z\"),\n };\n const requestBodyDigest = base64UrlEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(canonicalizeEncryptionJson(body)))));\n const request = { ...body, requestBodyDigest };\n const authorization = authorizationHeader(this.invokeAnyWithRuntimePermissions(serviceSession, [{ spaceId: session.spaceId, service: \"kv\", path: input.resourcePath, action: \"tinycloud.kv/get\" }]));\n const response = await fetch(`${this.config.host!}/policy/v3/deliveries/authorize`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\", authorization },\n body: canonicalizeEncryptionJson(request),\n });\n if (!response.ok) throw await httpResponseError(response, \"V3 share delivery authorization failed\");\n const verified = validateShareDeliveryAuthorizationV3Bytes(new Uint8Array(await response.arrayBuffer()), {\n request,\n senderKeyDid: this.credentialHolderDid,\n deliveryAudience: input.deliveryAudience,\n });\n const requestDigest = new Uint8Array(await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`${CREDENTIAL_INVITATION_REQUEST_DOMAIN}${canonicalizeEncryptionJson(verified.request as any)}`),\n ));\n return {\n ...verified,\n proof: {\n alg: \"EdDSA\",\n kid: this.credentialHolderDid,\n signature: base64UrlEncode(await this.signSessionBytes(requestDigest)),\n },\n };\n }\n\n private async createRootDelegationForSharing(params: {\n shareKeyDID: string;\n spaceId: string;\n path: string;\n actions: string[];\n requestedExpiry: Date;\n }, assertActive?: () => void): Promise<Delegation | undefined> {\n try {\n return (await this.createOwnerDelegation({\n delegateDid: params.shareKeyDID,\n spaceId: params.spaceId,\n path: params.path,\n actions: params.actions,\n expiresAt: params.requestedExpiry,\n }, assertActive)).delegation;\n } catch {\n assertActive?.();\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 return this.fetchEncryptionNetworkAt(\n this.config.host!,\n networkId,\n globalThis.fetch.bind(globalThis),\n );\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 // `NetworkAlreadyExists` is the only error this route maps to Conflict\n // (`NetworkNotActive`, the other Conflict in the shared error mapper, is\n // reachable only from the decrypt routes). So a 409 means the network is\n // already there — which is exactly the post-condition `create` promises.\n // Read it back rather than failing an otherwise-successful ensure.\n if (response.status === 409) {\n const existing = await this.getEncryptionNetwork(networkId);\n if (existing) return existing;\n throw new Error(\n `Encryption network ${networkId} already exists but could not be read back`,\n );\n }\n if (!response.ok) {\n throw await httpResponseError(response, `Failed to create encryption network ${networkId}`);\n }\n const created = (await response.json()) as { descriptor: NetworkDescriptor };\n return created.descriptor;\n }\n\n /**\n * Ensure an encryption network exists, creating it if necessary.\n *\n * @param nameOrNetworkId - Network name or full `urn:tinycloud:encryption:` id.\n * @param options - See {@link EnsureEncryptionNetworkOptions}.\n */\n async ensureEncryptionNetwork(\n nameOrNetworkId = DEFAULT_ENCRYPTION_NETWORK_NAME,\n options: EnsureEncryptionNetworkOptions = {},\n ): Promise<NetworkDescriptor> {\n const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n ? nameOrNetworkId\n : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n // The existence probe is worth a round trip only when the network is\n // likely to be there. On a freshly bootstrapped account it always 404s,\n // so callers that know the account is new skip straight to the create —\n // which is itself safe to race, since 409 is handled above.\n if (!options.assumeMissing) {\n const existing = await this.getEncryptionNetwork(networkId);\n if (existing) {\n return existing;\n }\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 return this.secretsForSpace(\"secrets\");\n }\n\n /**\n * App-facing secrets API backed by the requested space's vault.\n */\n secretsForSpace(spaceId: string): ISecretsService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let secrets = this._secrets.get(resolvedSpace);\n if (!secrets) {\n secrets = new NodeSecretsService({\n getService: () => this.getBaseSecrets(resolvedSpace),\n space: resolvedSpace,\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.getEncryptionNetworkIdForSpace(resolvedSpace),\n resolveSpace: (space) => space.startsWith(\"tinycloud:\") ? space : this.ownedSpaceId(space),\n getUnlockSigner: () => this.signer ?? undefined,\n });\n this._secrets.set(resolvedSpace, secrets);\n }\n return secrets;\n }\n\n /**\n * Read a secret from an explicit target space without requesting or\n * auto-signing authority. Active runtime delegations are selected by the\n * normal KV and encryption invocation paths.\n */\n async readSecret(input: SecretReadInput): Promise<SecretReadResult> {\n const resolved = resolveSecretPath(input.name, { scope: input.scope });\n const targetSpace = input.space.startsWith(\"tinycloud:\")\n ? input.space\n : this.ownedSpaceId(input.space);\n const result = await this.getBaseVault(targetSpace).readNetworkEncrypted<unknown>(\n resolved.vaultKey,\n );\n\n if (result.status !== \"ok\") {\n if (result.status === \"permission_required\") {\n const hint = parsePermissionHint(result.hint);\n if (hint === undefined) return { status: \"read_failed\" };\n return {\n status: \"permission_required\",\n hint: {\n service: hint.service,\n ...(hint.space === undefined ? {} : { space: hint.space }),\n path: hint.path,\n actions: [...hint.actions],\n },\n };\n }\n return { status: result.status };\n }\n if (!isSecretPayload(result.entry.value)) {\n return { status: \"invalid_payload\" };\n }\n return { status: \"ok\", value: result.entry.value.value };\n }\n\n private getBaseSecrets(spaceId: string): ISecretsService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let secrets = this._baseSecrets.get(resolvedSpace);\n if (!secrets) {\n secrets = new SecretsService(() => this.getBaseVault(resolvedSpace));\n this._baseSecrets.set(resolvedSpace, secrets);\n }\n return secrets;\n }\n\n private getBaseVault(spaceId: string): DataVaultService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let vault = this._baseVaults.get(resolvedSpace);\n if (!vault) {\n vault = this.createVaultService(\n resolvedSpace,\n this.createSpaceScopedKVService(resolvedSpace),\n );\n if (this._serviceContext) {\n vault.initialize(this._serviceContext);\n }\n this._baseVaults.set(resolvedSpace, vault);\n }\n return vault;\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 // Exclude the synthetic primary grant: it represents the base session's\n // own recap, not an installed runtime delegation. Per this method's\n // contract, base-session manifest permissions are not represented here.\n return this.runtimePermissionGrants\n .filter((grant) => grant.provenance !== \"primary\")\n .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 * Return the effective capabilities of installed runtime grants.\n *\n * The result is projected from the SDK's activated, expiry-pruned grant\n * operations rather than from PortableDelegation transport metadata. Base\n * session authority is intentionally omitted; callers that need the full\n * live authority must combine this with {@link getVerifiedSessionCapabilities}.\n */\n getEffectiveRuntimePermissionEntries(): PermissionEntry[] {\n const session = this.currentTinyCloudSession();\n if (!session) return [];\n\n this.pruneExpiredRuntimePermissionGrants();\n const grouped = new Map<string, PermissionEntry>();\n for (const grant of this.runtimePermissionGrants) {\n if (grant.provenance === \"primary\") continue;\n for (const operation of grant.operations) {\n const service = SERVICE_SHORT_TO_LONG[operation.service];\n if (service === undefined || typeof operation.path !== \"string\" ||\n typeof operation.action !== \"string\") {\n continue;\n }\n\n let space: string | undefined;\n if (service !== \"tinycloud.encryption\" || operation.resource === undefined) {\n if (typeof operation.spaceId !== \"string\") continue;\n try {\n space = this.resolvePermissionSpace(operation.spaceId, session);\n } catch {\n continue;\n }\n }\n\n const caveats = operation.caveats === undefined || operation.caveats.length === 0\n ? undefined\n : cloneRecapCaveats(operation.caveats);\n const identity = JSON.stringify({\n service,\n ...(space === undefined ? {} : { space }),\n path: operation.path,\n caveats: canonicalizeRecapCaveats(caveats),\n });\n const existing = grouped.get(identity);\n if (existing === undefined) {\n grouped.set(identity, {\n service,\n ...(space === undefined ? {} : { space }),\n path: operation.path,\n actions: [operation.action],\n ...(caveats === undefined ? {} : { caveats }),\n });\n continue;\n }\n if (!existing.actions.includes(operation.action)) {\n existing.actions.push(operation.action);\n existing.actions.sort();\n }\n }\n }\n\n return [...grouped.values()].sort((left, right) =>\n left.service.localeCompare(right.service) ||\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")),\n );\n }\n\n /**\n * Verify a wallet-signed session grant (a CACAO built from a SIWE and its\n * EIP-191 signature) issued to this instance's live session key. The\n * verifier rebuilds the CACAO from `siwe` and `signature`, so the grant is\n * accepted only when its authorization bytes and CID are exactly that CACAO,\n * its signer is `address`, its audience is this session key, it is valid\n * now, and its ReCap covers `spaceId` or names only raw encryption networks\n * (a decrypt-only grant has no space). Returns the signed ReCap and expiry.\n * Bindings without `validateSessionGrant` fall back to the session verifier,\n * which also refuses decrypt-only grants.\n */\n verifySessionGrant(grant: SessionGrantProof): VerifiedSessionGrant {\n const bindings = this.wasmBindings;\n const validate = typeof bindings.validateSessionGrant === \"function\"\n ? bindings.validateSessionGrant.bind(bindings)\n : bindings.validatePersistedSession?.bind(bindings);\n if (validate === undefined) {\n throw new UnsupportedSessionRestoreError(\"it cannot verify persisted SIWE authority\");\n }\n const verified = validate({\n delegationHeader: { Authorization: grant.delegationHeader.Authorization },\n delegationCid: grant.delegationCid,\n spaceId: grant.spaceId,\n jwk: this.sessionKeyJwk,\n address: canonicalizeAddress(grant.address),\n chainId: grant.chainId,\n siwe: grant.siwe,\n signature: grant.signature,\n });\n if (typeof verified.expiresAt !== \"string\") {\n throw new Error(\"Session grant has no signed expiry.\");\n }\n const expiresAt = new Date(verified.expiresAt);\n if (!Number.isFinite(expiresAt.getTime())) {\n throw new Error(\"Session grant has an invalid signed expiry.\");\n }\n return { recap: exactVerifiedRecap(verified), expiresAt };\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 Object.assign(\n new Error(`Failed to activate runtime permission delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\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 this.assertDelegationCaveatsPreservable(expanded);\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 Object.assign(\n new Error(`Failed to activate runtime permission delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n const delegation = this.runtimeDelegationFromSession(\n delegatedSession,\n delegatedEntries,\n spaceId,\n session,\n expiresAt,\n { siwe: prepared.siwe, signature },\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 provenance: \"runtime\",\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 = [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA];\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 Object.assign(\n new Error(`Failed to activate public space delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceGraph.invoke,\n fetch: this._serviceGraph.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<DelegationRevocationReceipt>> {\n return this.delegationManager.revoke(cid);\n }\n\n /** Read node-confirmed lifecycle state for one delegation. */\n async getDelegationStatus(cid: string): Promise<DelegationResult<DelegationStatus>> {\n return this.delegationManager.status(cid);\n }\n\n /** Compute the canonical CID of a compact UCAN or DAG-CBOR delegation authorization. */\n computeDelegationCid(authorization: string): string {\n if (!authorization || !this.wasmBindings.computeCid) {\n throw new Error(\"Delegation CID computation is unavailable\");\n }\n const compact = authorization.replace(/^Bearer /i, \"\");\n return this.wasmBindings.computeCid(\n compact.includes(\".\")\n ? new TextEncoder().encode(compact)\n : decodeAuthorizationBytes(authorization),\n 0x55n,\n );\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\n // (DEFAULT_DELEGATION_EXPIRY_MS); ms-format (\"7d\") or a raw\n // millisecond count are both accepted. Cap at the session's own\n // expiry so we never emit a UCAN whose validity exceeds the parent\n // chain, which makes the default the longest the session allows.\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 this.assertDelegationCaveatsPreservable(expandedEntries);\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 = this.projectSignedRecapCapabilities(session.siwe);\n const { subset, missing } = this.signedCapabilitySubset(expandedEntries, granted);\n\n if (!subset) {\n // This branch only runs when the session recap is NOT a superset of the\n // requested entries. The synthetic primary grant is built from that same\n // recap, so it should never cover an entry the recap itself doesn't —\n // but `operationCovers` is strictly more permissive than\n // `isCapabilitySubset` (action `/*` and path `/*`/`/**` wildcards), so a\n // wildcard-bearing recap could slip through and mint a delegation with\n // the primary session's spaceId (the wrong-space class). Exclude the\n // primary explicitly; failure then degrades to\n // PermissionNotInManifestError instead of a wrong-space delegation.\n const runtimeOperations = this.permissionEntriesToOperations(expandedEntries, session);\n const runtimeGrant = this.findGrantForOperations(\n runtimeOperations,\n { excludePrimary: true },\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 runtimeOperations,\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 this.assertDelegationCaveatsPreservable(entries);\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 Object.assign(\n new Error(`Failed to activate delegation with host: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\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 requestedOperations: RuntimePermissionOperation[],\n ): Promise<PortableDelegation> {\n this.assertRuntimeGrantCaveatsPreservable(entries, requestedOperations, grant);\n this.assertDelegationCaveatsPreservable(entries);\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 Object.assign(\n new Error(`Failed to activate delegation with host: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\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 /**\n * The current WASM child-delegation APIs accept action-only maps. Refuse any\n * constrained branch rather than signing a broader action-only child UCAN.\n */\n private assertDelegationCaveatsPreservable(entries: PermissionEntry[]): void {\n const caveated = entries.filter((entry) =>\n !recapCaveatsEqual(entry.caveats, undefined)\n );\n if (caveated.length > 0) {\n throw new CaveatedDelegationUnsupportedError(caveated);\n }\n }\n\n /**\n * Runtime grant selection intentionally allows an uncaveated operation to\n * select a caveated grant so invocation can restore the signed caveat before\n * crossing the caveat-aware WASM boundary. Child delegation cannot do that:\n * it only accepts action maps, so reject the selected constrained branch.\n */\n private assertRuntimeGrantCaveatsPreservable(\n entries: PermissionEntry[],\n requestedOperations: RuntimePermissionOperation[],\n grant: RuntimePermissionGrant,\n ): void {\n let operationIndex = 0;\n const caveated: PermissionEntry[] = [];\n for (const entry of entries) {\n for (const action of entry.actions) {\n const requested = requestedOperations[operationIndex++];\n if (!requested) continue;\n const constrained = grant.operations.find((granted) =>\n this.operationCovers(granted, requested) &&\n !recapCaveatsEqual(granted.caveats, undefined),\n );\n if (constrained) {\n caveated.push({\n ...entry,\n actions: [action],\n caveats: cloneRecapCaveats(constrained.caveats),\n });\n }\n }\n }\n if (caveated.length > 0) {\n throw new CaveatedDelegationUnsupportedError(caveated);\n }\n }\n\n /** Reject caveated parent branches before action-only child signing. */\n private assertPortableDelegationCaveatsPreservable(\n delegation: PortableDelegation,\n ): void {\n const entries: PermissionEntry[] = [];\n const add = (\n service: string,\n space: string,\n path: string,\n actions: string[],\n caveats: readonly Record<string, unknown>[] | undefined,\n ): void => {\n if (recapCaveatsEqual(caveats, undefined)) return;\n entries.push({\n service: service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`,\n space,\n path,\n actions: [...actions],\n caveats: cloneRecapCaveats(caveats),\n });\n };\n\n add(\n delegation.actions[0]?.split(\"/\", 1)[0] ?? \"tinycloud.unknown\",\n delegation.spaceId,\n delegation.path,\n delegation.actions,\n delegation.caveats,\n );\n for (const resource of delegation.resources ?? []) {\n add(resource.service, resource.space, resource.path, resource.actions, resource.caveats);\n }\n if (entries.length > 0) {\n throw new CaveatedDelegationUnsupportedError(entries);\n }\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 this.isEncryptionNetworkOperation(\"encryption\", entry.path, entry.space);\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, entry.space)\n ? { resource: entry.path }\n : { spaceId }),\n service,\n path: entry.path,\n action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n }));\n });\n }\n\n /** Raw network authority cannot be covered by a nested encryption space. */\n private signedCapabilitySubset(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n ): { subset: boolean; missing: PermissionEntry[] } {\n const rawGranted = granted.filter((entry) => this.isEncryptionPermissionEntry(entry))\n .map((entry) => ({ ...entry, space: \"encryption\" }));\n const spaceGranted = granted.filter((entry) => !this.isEncryptionPermissionEntry(entry));\n const missing = requested.filter((entry) => {\n const raw = this.isEncryptionPermissionEntry(entry);\n const comparable = raw ? { ...entry, space: \"encryption\" } : entry;\n return !isCapabilitySubset([comparable], raw ? rawGranted : spaceGranted).subset;\n });\n return { subset: missing.length === 0, missing };\n }\n\n private sessionCoversPermissionEntries(\n session: TinyCloudSession,\n entries: PermissionEntry[],\n ): boolean {\n try {\n const granted = this.projectSignedRecapCapabilities(session.siwe);\n return this.signedCapabilitySubset(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, entry.space)\n ? { resource: entry.path }\n : { spaceId }),\n service,\n path: entry.path,\n action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 // Public surface: never surface the synthetic primary grant. It exists\n // only to win runtime invocation selection; the base session's own recap\n // is not an installed runtime delegation, so excluding it keeps the\n // `getRuntimePermissionDelegations` contract (base-session manifest\n // permissions are not represented here) airtight.\n const grant = this.findGrantForOperation(operation, { excludePrimary: true });\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 siweProof: { siwe: string; signature: string },\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 siweProof,\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 provenance: \"delegated\",\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 provenance: \"delegated\",\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 ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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, resource.space)\n ? { resource: resource.path }\n : { spaceId: resource.space }),\n service,\n path: resource.path,\n action,\n caveats: cloneRecapCaveats(resource.caveats),\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 ...(delegation.caveats === undefined ? {} : { caveats: cloneRecapCaveats(delegation.caveats) }),\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, resource.space)) {\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 if (!grant) {\n return fallback;\n }\n // \"Primary wins\" means the caller's own session already authorizes the op:\n // use the PASSED session, not the stored primary `ServiceSession`. The stored\n // primary carries the primary space's `spaceId`, but a multi-space recap can\n // cover scoped ops on OTHER spaces whose fallback session carries the correct\n // target `spaceId`. Returning `grant.session` there would mint the invocation\n // against the wrong space (TC-111 follow-up). Non-primary grants keep their\n // own session.\n return grant.provenance === \"primary\" ? fallback : grant.session;\n }\n\n private findGrantForOperations(\n operations: RuntimePermissionOperation[],\n options?: { excludePrimary?: boolean },\n ): RuntimePermissionGrant | undefined {\n if (operations.length === 0) {\n return undefined;\n }\n this.pruneExpiredRuntimePermissionGrants();\n const covering = this.runtimePermissionGrants.filter((grant) => {\n if (options?.excludePrimary && grant.provenance === \"primary\") {\n return false;\n }\n return operations.every((operation) =>\n grant.operations.some((granted) =>\n this.operationCovers(granted, operation),\n ),\n );\n });\n if (covering.length === 0) {\n return undefined;\n }\n // Provenance ranking: the synthetic primary grant (the base session's own\n // recap) always wins when it covers every op, so a broad bootstrap or\n // delegated grant can never hijack an operation the primary session itself\n // authorizes (TC-111). Otherwise fall back to insertion order — the same\n // semantics as the previous `.find`.\n return covering.find((grant) => grant.provenance === \"primary\") ?? covering[0];\n }\n\n private findGrantForOperation(\n operation: RuntimePermissionOperation,\n options?: { excludePrimary?: boolean },\n ): RuntimePermissionGrant | undefined {\n return this.findGrantForOperations([operation], options);\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 // A caller that already carries a caveat can only be covered by the exact\n // same signed attenuation. An uncaveated request is decorated with the\n // grant's caveat immediately before WASM signs it.\n if (requested.caveats !== undefined &&\n !recapCaveatsEqual(granted.caveats, requested.caveats)\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>`. Compare\n // only the embedded EIP-155 address without case sensitivity; chain, name,\n // and all non-PKH space identifiers remain byte-exact.\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 const match = /^(tinycloud:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.+)$/.exec(space);\n return match === null ? space : `${match[1]}${match[2]!.toLowerCase()}${match[3]}`;\n }\n\n private actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) {\n return true;\n }\n // `tinycloud.kv/sync` and `tinycloud.kv/retain` must be granted by name;\n // a `tinycloud.kv/*` runtime grant does not cover them (TC-732).\n if (isExplicitOnlyAction(requestedAction)) {\n return false;\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 /** Prefer the v2 caveat-preserving parser while retaining old custom WASM. */\n private parseRecapWithCaveats(siwe: string): WasmRecapEntry[] {\n const verified = this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe);\n return verified == null\n ? this.wasmBindings.parseRecapFromSiwe(siwe)\n : verifierRecapEntries(verified);\n }\n\n private isEncryptionNetworkOperation(service: string, path: string, space?: string): boolean {\n return service === \"encryption\" &&\n (space === undefined || space === \"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 caveats?: Record<string, unknown>[];\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 ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n };\n }\n if (entry.spaceId === undefined && this.isEncryptionNetworkOperation(service, entry.path)) {\n return {\n resource: entry.path,\n service,\n path: entry.path,\n action: entry.action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 Object.assign(\n new Error(`Failed to activate delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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: { \"\": [KV.GET, KV.PUT, 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: [KV.GET, KV.PUT, 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 // The activated session lasts as long as the delegation it is proven by.\n const expirationTime = delegation.expiry;\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 Object.assign(\n new Error(`Failed to activate delegated session: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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 in milliseconds from now; defaults to the parent's own expiry, the longest allowed. */\n expiryMs?: number;\n /** Explicit multi-resource projection, including encryption networks. */\n resources?: Array<{\n service: string;\n space?: string;\n path: string;\n actions: string[];\n }>;\n }\n ): Promise<PortableDelegation> {\n this.assertPortableDelegationCaveatsPreservable(parentDelegation);\n\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 const parentResources = parentDelegation.resources ?? [{\n service: parentDelegation.actions[0]?.split(\"/\", 1)[0]?.replace(/^tinycloud\\./, \"\") ?? \"kv\",\n space: parentDelegation.spaceId,\n path: parentDelegation.path,\n actions: parentDelegation.actions,\n }];\n const requestedResources = params.resources ?? [{\n service: params.actions[0]?.split(\"/\", 1)[0]?.replace(/^tinycloud\\./, \"\") ?? \"kv\",\n space: parentDelegation.spaceId,\n path: params.path,\n actions: params.actions,\n }];\n const resourceIsContained = (parent: typeof parentResources[number], child: typeof requestedResources[number]): boolean => {\n const parentEncryption = parent.service === \"encryption\" || parent.service === \"tinycloud.encryption\";\n const childEncryption = child.service === \"encryption\" || child.service === \"tinycloud.encryption\";\n if (parentEncryption || childEncryption) return parentEncryption && childEncryption && parent.path === child.path && child.actions.every((action) => parent.actions.includes(action));\n const pathContained = parent.path === child.path || parent.path.endsWith(\"/\") && child.path.startsWith(parent.path) || child.path.startsWith(`${parent.path}/`);\n return pathContained && child.actions.every((action) => parent.actions.includes(action));\n };\n if (requestedResources.length === 0 || requestedResources.some((child) => !parentResources.some((parent) => resourceIsContained(parent, child)))) {\n throw new Error(\n \"Sub-delegation resources exceed the received delegation\"\n );\n }\n\n // Default to the longest a sub-delegation may last: its parent's expiry.\n const now = new Date();\n const requestedExpiry = params.expiryMs === undefined\n ? parentDelegation.expiry\n : new Date(now.getTime() + params.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 rawAbilities: Record<string, string[]> = {};\n for (const resource of requestedResources) {\n const service = resource.service.replace(/^tinycloud\\./, \"\");\n if (service === \"encryption\") {\n rawAbilities[resource.path] = [...resource.actions];\n continue;\n }\n abilities[service] ??= {};\n abilities[service][resource.path] = [...resource.actions];\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 ...(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 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 Object.assign(\n new Error(`Failed to activate sub-delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n // Return the portable sub-delegation\n return {\n cid: subDelegationSession.delegationCid,\n delegationHeader: subDelegationSession.delegationHeader,\n spaceId: parentDelegation.spaceId,\n path: requestedResources[0]!.path,\n actions: requestedResources[0]!.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 resources: requestedResources.map((resource) => ({\n service: resource.service.replace(/^tinycloud\\./, \"\"),\n space: resource.service.replace(/^tinycloud\\./, \"\") === \"encryption\"\n ? \"encryption\"\n : resource.space ?? parentDelegation.spaceId,\n path: resource.path,\n actions: [...resource.actions],\n })),\n };\n }\n}\n","export { AccountService } from \"@tinycloud/sdk-core\";\nexport type {\n AccountApplication,\n AccountApplicationListOptions,\n AccountApplicationRegisterOptions,\n AccountDelegation,\n AccountDelegationListOptions,\n AccountDelegationRevokeOptions,\n AccountIndexEnsureResult,\n AccountIndexRebuildResult,\n AccountIndexStatus,\n AccountIndexedReadOptions,\n AccountServiceConfig,\n AccountSpace,\n AccountSpaceListOptions,\n AccountStatus,\n RegisterBatchSuccess,\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 * (30 days, the SESSION tier).\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(\n action: SecretAction,\n): \"get\" | \"put\" | \"del\" | \"list\" {\n return action;\n}\n\nfunction secretPermissionEntries(\n name: string,\n options: SecretScopeOptions | undefined,\n action: SecretAction,\n space: string,\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,\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\nfunction normalizeSpace(\n space: string | undefined,\n resolveSpace?: (space: string) => string,\n): string | undefined {\n if (!space) return undefined;\n if (space.startsWith(\"tinycloud:\")) return space;\n return resolveSpace?.(space) ?? space;\n}\n\nfunction spaceMatches(\n granted: string | undefined,\n requested: string | undefined,\n resolveSpace?: (space: string) => string,\n): boolean {\n if (!granted || !requested) return false;\n return (\n normalizeSpace(granted, resolveSpace) ===\n normalizeSpace(requested, resolveSpace)\n );\n}\n\nexport interface NodeSecretsServiceConfig {\n getService: () => ISecretsService;\n space?: string;\n getManifest: () => Manifest | Manifest[] | undefined;\n hasPermissions?: (permissions: PermissionEntry[]) => boolean;\n grantPermissions: (additional: PermissionEntry[]) => Promise<unknown>;\n canEscalate: () => boolean;\n getEncryptionNetworkId?: () => string;\n resolveSpace?: (space: string) => 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 private get space(): string {\n return this.config.space ?? SECRETS_SPACE;\n }\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(\n name: string,\n options?: SecretScopeOptions,\n ): 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(\n options?: SecretScopeOptions,\n ): 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 async listAll(): ReturnType<ISecretsService[\"listAll\"]> {\n const permission = await this.ensurePermission(\"\", undefined, \"list\");\n if (!permission.ok) return permission;\n return this.service.listAll();\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 this.space,\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(permissionEntries: PermissionEntry[]): 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 spaceMatches(\n resource.space,\n entry.space,\n this.config.resolveSpace,\n ) &&\n resource.path === entry.path &&\n entry.actions.every((action) => resource.actions.includes(action)),\n );\n }),\n );\n }\n}\n","import {\n canonicalizeRecapCaveats,\n decodeBase64Url,\n Delegation,\n DelegatedResource,\n PermissionEntry,\n principalDidEquals,\n} 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 * The wallet-signed SIWE message and EIP-191 signature behind a\n * `delegationHeader` that is a CACAO session grant (OpenKey `/delegate`,\n * {@link TinyCloudNode.grantRuntimePermissions}) rather than a compact UCAN.\n * Not authority: activation rebuilds the CACAO from them and accepts only\n * byte-identical authorization bytes.\n */\n siweProof?: { siwe: string; signature: string };\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 * Authority that the validated runtime-delegation activation helper needs.\n * `TinyCloudNode` implements this surface directly; keeping it structural\n * makes the helper usable by a compatible Node wrapper without exposing node\n * internals.\n */\nexport interface RuntimeDelegationActivator {\n readonly sessionDid: string;\n readonly did?: string;\n readonly isSessionOnly?: boolean;\n computeDelegationCid(authorization: string): string;\n useRuntimeDelegation(delegation: PortableDelegation): Promise<void>;\n useDelegation?(delegation: PortableDelegation): Promise<unknown>;\n getRuntimePermissionDelegations(): PortableDelegation[];\n /**\n * Verify a wallet-signed session grant issued to this runtime's live session\n * key. Required to activate a CACAO grant; compact UCANs do not use it.\n */\n verifySessionGrant?(grant: SessionGrantProof): VerifiedSessionGrant;\n}\n\n/** The installed authority returned by {@link activateValidatedRuntimeDelegation}. */\nexport interface ValidatedRuntimeDelegation {\n /** CID recomputed from the signed authorization bytes. */\n readonly cid: string;\n /** The authority object installed by the node runtime. */\n readonly delegation: PortableDelegation;\n /** Capabilities read from the signed compact UCAN attenuation. */\n readonly effectivePermissions: readonly PermissionEntry[];\n /** Expiry read from the signed compact UCAN payload. */\n readonly expiry: Date;\n /** Audience read from the signed compact UCAN payload. */\n readonly audience: string;\n /** Host selected for, and used by, the runtime activation. */\n readonly host: string;\n}\n\nexport interface CompactRuntimeDelegationInput {\n readonly authorization: string;\n readonly cid: string;\n readonly host: string;\n readonly ownerAddress: string;\n readonly chainId: number;\n}\n\n/** A CACAO session grant and the signed SIWE proof it was built from. */\nexport interface SessionGrantProof {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/** Authority read from a verified session grant's signed ReCap. */\nexport interface VerifiedSessionGrant {\n readonly recap: readonly {\n service: string;\n space: string;\n path: string;\n actions: string[];\n caveats?: Record<string, unknown>[];\n }[];\n readonly expiresAt: Date;\n}\n\n/**\n * Stable reasons {@link activateValidatedRuntimeDelegation} refuses a\n * delegation for. The error message is for the caller and may quote\n * transport fields or a node's response; the reason is safe to publish.\n */\nexport const RUNTIME_DELEGATION_REJECTIONS = [\n \"host_mismatch\",\n \"expired\",\n \"cid_mismatch\",\n \"authority_invalid\",\n \"proof_missing\",\n \"proof_invalid\",\n \"owner_mismatch\",\n \"audience_mismatch\",\n \"resources_mismatch\",\n \"unsupported\",\n \"activation_rejected\",\n] as const;\n\nexport type RuntimeDelegationRejection = typeof RUNTIME_DELEGATION_REJECTIONS[number];\n\nexport class RuntimeDelegationRejectedError extends Error {\n readonly reason: RuntimeDelegationRejection;\n\n constructor(reason: RuntimeDelegationRejection, message: string) {\n super(message);\n this.name = \"RuntimeDelegationRejectedError\";\n this.reason = reason;\n }\n}\n\nfunction reject(reason: RuntimeDelegationRejection, message: string): never {\n throw new RuntimeDelegationRejectedError(reason, message);\n}\n\ninterface SignedRuntimeAuthority {\n readonly issuer: string;\n readonly audience: string;\n readonly expiry: Date;\n readonly proofs: readonly string[];\n readonly remainingRedelegationDepth?: number;\n readonly permissions: readonly PermissionEntry[];\n readonly resources: readonly DelegatedResource[];\n}\n\nconst SERVICE_BY_SHORT_NAME: Record<string, string> = {\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n hooks: \"tinycloud.hooks\",\n};\n\nfunction authorizationWithoutBearer(authorization: string): string {\n return authorization.replace(/^Bearer /i, \"\");\n}\n\nfunction normalizedHost(host: string): string {\n if (typeof host !== \"string\" || host.length === 0) {\n throw new Error(\"Validated runtime delegation requires a non-empty host.\");\n }\n return host.replace(/\\/+$/, \"\");\n}\n\nfunction didPrincipalsMatch(left: string, right: string): boolean {\n try {\n return principalDidEquals(left, right);\n } catch {\n return left === right;\n }\n}\n\nfunction compactUcanPayload(authorization: string): Record<string, unknown> {\n const compact = authorizationWithoutBearer(authorization);\n const parts = compact.split(\".\");\n if (parts.length !== 3 || parts.some((part) => part.length === 0)) {\n throw new Error(\n \"Validated runtime delegation requires a compact UCAN authorization so its signed authority can be derived.\",\n );\n }\n try {\n const payload = JSON.parse(\n new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(parts[1]!)),\n ) as unknown;\n if (payload === null || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new Error(\"payload is not an object\");\n }\n return payload as Record<string, unknown>;\n } catch {\n throw new Error(\n \"Validated runtime delegation authorization has an invalid compact UCAN payload.\",\n );\n }\n}\n\nfunction canonicalPermissionEntries(\n permissions: PermissionEntry[],\n): PermissionEntry[] {\n return permissions\n .map((permission) => ({\n ...permission,\n actions: [...permission.actions].sort(),\n }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n );\n}\n\nfunction signedCaveats(value: unknown): Record<string, unknown>[] | undefined {\n if (!Array.isArray(value) || value.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n )) {\n throw new Error(\"Validated runtime delegation has malformed signed ReCap caveats.\");\n }\n const cloned = JSON.parse(JSON.stringify(value)) as Record<string, unknown>[];\n return canonicalizeRecapCaveats(cloned) === canonicalizeRecapCaveats(undefined)\n ? undefined\n : cloned;\n}\n\nfunction groupedSignedEntries(\n service: string,\n space: string | undefined,\n path: string,\n abilities: Record<string, unknown>,\n): PermissionEntry[] {\n const groups = new Map<string, { actions: string[]; caveats?: Record<string, unknown>[] }>();\n for (const [action, rawCaveats] of Object.entries(abilities)) {\n const caveats = signedCaveats(rawCaveats);\n const identity = canonicalizeRecapCaveats(caveats);\n const group = groups.get(identity) ?? { actions: [], caveats };\n group.actions.push(action);\n groups.set(identity, group);\n }\n return [...groups.values()].map((group) => ({\n service,\n ...(space === undefined ? {} : { space }),\n path,\n actions: group.actions.sort(),\n ...(group.caveats === undefined ? {} : { caveats: group.caveats }),\n }));\n}\n\nfunction signedAuthorityFromCompactUcan(\n authorization: string,\n): SignedRuntimeAuthority {\n const payload = compactUcanPayload(authorization);\n if (typeof payload.aud !== \"string\" || payload.aud.length === 0) {\n throw new Error(\"Validated runtime delegation is missing a signed audience.\");\n }\n if (typeof payload.iss !== \"string\" || payload.iss.length === 0) {\n throw new Error(\"Validated runtime delegation is missing a signed issuer.\");\n }\n if (!Array.isArray(payload.prf) || payload.prf.some((proof) =>\n typeof proof !== \"string\" || proof.length === 0\n )) {\n throw new Error(\"Validated runtime delegation has malformed signed proofs.\");\n }\n if (typeof payload.exp !== \"number\" || !Number.isFinite(payload.exp)) {\n throw new Error(\"Validated runtime delegation is missing a signed expiry.\");\n }\n const expiry = new Date(payload.exp * 1000);\n if (Number.isNaN(expiry.getTime())) {\n throw new Error(\"Validated runtime delegation has an invalid signed expiry.\");\n }\n if (payload.att === null || typeof payload.att !== \"object\" || Array.isArray(payload.att)) {\n throw new Error(\"Validated runtime delegation is missing a signed attenuation.\");\n }\n const fact = Array.isArray(payload.fct) && payload.fct.length > 0 &&\n payload.fct[0] !== null && typeof payload.fct[0] === \"object\" &&\n !Array.isArray(payload.fct[0])\n ? payload.fct[0] as Record<string, unknown>\n : undefined;\n const remainingRedelegationDepth = fact?.remainingRedelegationDepth;\n if (\n remainingRedelegationDepth !== undefined &&\n (!Number.isInteger(remainingRedelegationDepth) ||\n (remainingRedelegationDepth as number) < 0 ||\n (remainingRedelegationDepth as number) > 8)\n ) {\n throw new Error(\"Validated runtime delegation has invalid signed redelegation depth.\");\n }\n\n const permissions: PermissionEntry[] = [];\n for (const [resource, abilities] of Object.entries(payload.att)) {\n if (abilities === null || typeof abilities !== \"object\" || Array.isArray(abilities)) {\n throw new Error(\"Validated runtime delegation has an invalid signed attenuation.\");\n }\n const abilityEntries = Object.entries(abilities as Record<string, unknown>);\n if (abilityEntries.length === 0) {\n throw new Error(\"Validated runtime delegation has an empty signed capability.\");\n }\n\n if (resource.startsWith(\"urn:tinycloud:encryption:\")) {\n permissions.push(...groupedSignedEntries(\n \"tinycloud.encryption\",\n undefined,\n resource,\n abilities as Record<string, unknown>,\n ));\n continue;\n }\n\n const nativeMatch = /^(tinycloud:[^/]+)\\/(kv|sql|duckdb|hooks)\\/(.*)$/.exec(resource);\n const policyMatch = /^tinycloud:\\/\\/([^/]+)\\/(kv|sql|duckdb|hooks)\\/(.*)$/.exec(resource);\n const match = nativeMatch ?? policyMatch;\n if (!match) {\n throw new Error(\n `Validated runtime delegation has an unsupported signed resource '${resource}'.`,\n );\n }\n const [, space, shortService, path] = match;\n const service = SERVICE_BY_SHORT_NAME[shortService!];\n if (service === undefined) {\n throw new Error(\n `Validated runtime delegation has an unsupported signed service '${shortService}'.`,\n );\n }\n permissions.push(...groupedSignedEntries(\n service,\n space!,\n path!,\n abilities as Record<string, unknown>,\n ));\n }\n\n return canonicalSignedAuthority({\n issuer: payload.iss,\n audience: payload.aud,\n expiry,\n proofs: [...payload.prf],\n ...(remainingRedelegationDepth === undefined\n ? {}\n : { remainingRedelegationDepth: remainingRedelegationDepth as number }),\n }, permissions);\n}\n\nfunction canonicalSignedAuthority(\n signed: Omit<SignedRuntimeAuthority, \"permissions\" | \"resources\">,\n permissions: PermissionEntry[],\n): SignedRuntimeAuthority {\n if (permissions.length === 0) {\n throw new Error(\"Validated runtime delegation has no signed capabilities.\");\n }\n const canonicalPermissions = canonicalPermissionEntries(permissions);\n const canonicalResources = canonicalPermissions.map((permission) => ({\n service:\n permission.service === \"tinycloud.encryption\"\n ? \"encryption\"\n : permission.service.slice(\"tinycloud.\".length),\n space:\n permission.service === \"tinycloud.encryption\"\n ? \"encryption\"\n : permission.space!,\n path: permission.path,\n actions: [...permission.actions],\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n }));\n return { ...signed, permissions: canonicalPermissions, resources: canonicalResources };\n}\n\nconst RAW_ENCRYPTION_PREFIX = \"urn:tinycloud:encryption:\";\nconst PKH_SPACE = /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):(.+)$/;\n\n/** A space id with its owner address lowercased, so EIP-55 casing never decides a match. */\nfunction comparableSpace(space: string): string {\n const match = PKH_SPACE.exec(space);\n return match ? `tinycloud:pkh:eip155:${match[1]}:${match[2]!.toLowerCase()}:${match[3]}` : space;\n}\n\n/**\n * Authority of a CACAO session grant: the wallet-signed SIWE is rebuilt into\n * the exact CACAO and verified against this runtime's live session key, so\n * the signer (owner), audience, lifetime, space and ReCap all come from\n * signed bytes. The grant must be signed by the session's own owner, stay in\n * one owner space, and name only raw networks that owner holds.\n */\nfunction signedAuthorityFromSessionGrant(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n authorization: string,\n cid: string,\n): SignedRuntimeAuthority {\n const proof = delegation.siweProof;\n if (\n proof === undefined || proof === null || typeof proof !== \"object\" ||\n typeof proof.siwe !== \"string\" || typeof proof.signature !== \"string\"\n ) {\n reject(\n \"proof_missing\",\n \"Runtime delegation is a wallet-signed session grant stored without its signed SIWE proof, so its authority cannot be verified.\",\n );\n }\n if (typeof node.verifySessionGrant !== \"function\") {\n reject(\"unsupported\", \"This runtime cannot verify wallet-signed session grants.\");\n }\n const owner = `did:pkh:eip155:${delegation.chainId}:${delegation.ownerAddress}`;\n if (typeof node.did !== \"string\" || !didPrincipalsMatch(owner, node.did)) {\n reject(\"owner_mismatch\", \"Runtime delegation is not signed by this session's owner.\");\n }\n let verified: VerifiedSessionGrant;\n try {\n verified = node.verifySessionGrant({\n delegationHeader: { Authorization: authorization },\n delegationCid: cid,\n spaceId: delegation.spaceId,\n address: delegation.ownerAddress,\n chainId: delegation.chainId,\n siwe: proof.siwe,\n signature: proof.signature,\n });\n } catch (error) {\n reject(\"proof_invalid\", error instanceof Error ? error.message : String(error));\n }\n\n const space = comparableSpace(delegation.spaceId);\n const spaceOwner = PKH_SPACE.exec(delegation.spaceId);\n if (!spaceOwner || !didPrincipalsMatch(`did:pkh:eip155:${spaceOwner[1]}:${spaceOwner[2]}`, owner)) {\n reject(\"authority_invalid\", \"Runtime delegation space is not owned by its signer.\");\n }\n const groups = new Map<string, PermissionEntry>();\n for (const entry of verified.recap) {\n const service = entry.service.startsWith(\"tinycloud.\") ? entry.service : `tinycloud.${entry.service}`;\n const raw = entry.space === \"encryption\";\n if (raw) {\n if (service !== \"tinycloud.encryption\" || !entry.path.startsWith(RAW_ENCRYPTION_PREFIX)) {\n reject(\"authority_invalid\", \"Runtime delegation has an unsupported signed raw resource.\");\n }\n const networkOwner = entry.path.slice(RAW_ENCRYPTION_PREFIX.length, entry.path.lastIndexOf(\":\"));\n if (!didPrincipalsMatch(networkOwner, owner)) {\n reject(\"authority_invalid\", \"Runtime delegation names an encryption network its signer does not own.\");\n }\n } else if (service === \"tinycloud.encryption\" || comparableSpace(entry.space) !== space) {\n // Decrypt signed inside a space (older OpenKey) is not a usable network\n // grant, and one grant covers one space.\n reject(\"authority_invalid\", \"Runtime delegation has signed authority outside its space.\");\n }\n const caveats = signedCaveats(entry.caveats ?? []);\n const key = JSON.stringify([service, raw ? \"\" : entry.space, entry.path, canonicalizeRecapCaveats(caveats)]);\n const group = groups.get(key) ?? {\n service,\n ...(raw ? {} : { space: entry.space }),\n path: entry.path,\n actions: [],\n ...(caveats === undefined ? {} : { caveats }),\n };\n for (const action of entry.actions) {\n if (!group.actions.includes(action)) group.actions.push(action);\n }\n groups.set(key, group);\n }\n return canonicalSignedAuthority({\n issuer: owner,\n // The verifier bound the SIWE audience to this runtime's own session key.\n audience: node.sessionDid,\n expiry: verified.expiresAt,\n proofs: [],\n }, [...groups.values()]);\n}\n\nfunction canonicalResourcesFromPortableDelegation(\n delegation: PortableDelegation,\n): DelegatedResource[] {\n if (delegation.resources !== undefined && delegation.resources.length > 0) {\n return delegation.resources\n .map((resource) => ({ ...resource, actions: [...resource.actions].sort() }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n left.space.localeCompare(right.space) ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n );\n }\n const byService = new Map<string, string[]>();\n for (const action of delegation.actions) {\n const [service] = action.split(\"/\", 1);\n const shortService = service!.replace(/^tinycloud\\./, \"\");\n const values = byService.get(shortService) ?? [];\n values.push(action);\n byService.set(shortService, values);\n }\n return [...byService.entries()]\n .map(([service, actions]) => ({\n service,\n space: service === \"encryption\" ? \"encryption\" : delegation.spaceId,\n path: delegation.path,\n actions: [...new Set(actions)].sort(),\n ...(delegation.caveats === undefined ? {} : { caveats: delegation.caveats }),\n }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n left.space.localeCompare(right.space) ||\n left.path.localeCompare(right.path),\n );\n}\n\nfunction resourcesMatch(\n actual: readonly DelegatedResource[],\n expected: readonly DelegatedResource[],\n): boolean {\n const comparable = (resource: DelegatedResource) => ({\n ...resource,\n caveats: canonicalizeRecapCaveats(resource.caveats),\n });\n return JSON.stringify(actual.map(comparable)) === JSON.stringify(expected.map(comparable));\n}\n\n/**\n * CID-bind and activate one runtime delegation.\n *\n * A compact UCAN's audience, expiry and permissions come from its signed\n * payload, and its transport fields must agree with them. A CACAO session\n * grant (OpenKey `/delegate`, `grantRuntimePermissions`) is verified from its\n * `siweProof` against this runtime's live session key; its installed\n * authority is exactly the verified ReCap, and its transport `resources` are\n * display data that is never consulted. Either way the helper then invokes\n * {@link TinyCloudNode.useRuntimeDelegation}; the node activation call remains\n * the authority and delegation-chain validation boundary.\n *\n * `options.authorize`, when given, sees the signed capabilities before\n * anything is activated or installed; returning `false` refuses the\n * delegation.\n */\nexport async function activateValidatedRuntimeDelegation(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n options: {\n host: string;\n authorize?: (effectivePermissions: readonly PermissionEntry[]) => boolean;\n },\n): Promise<ValidatedRuntimeDelegation> {\n const host = normalizedHost(options.host);\n if (delegation.host !== undefined && normalizedHost(delegation.host) !== host) {\n reject(\n \"host_mismatch\",\n `Runtime delegation host '${delegation.host}' does not match expected host '${options.host}'.`,\n );\n }\n if (!(delegation.expiry instanceof Date) || Number.isNaN(delegation.expiry.getTime())) {\n reject(\"authority_invalid\", \"Runtime delegation has an invalid expiry.\");\n }\n if (delegation.expiry.getTime() <= Date.now()) {\n reject(\"expired\", \"Runtime delegation is expired.\");\n }\n\n const authorization = delegation.delegationHeader?.Authorization;\n if (typeof authorization !== \"string\" || authorization.length === 0) {\n reject(\"authority_invalid\", \"Runtime delegation is missing authorization bytes.\");\n }\n const cid = node.computeDelegationCid(authorization);\n if (cid !== delegation.cid) {\n reject(\"cid_mismatch\", \"Runtime delegation CID does not match authorization bytes.\");\n }\n\n const compact = authorizationWithoutBearer(authorization).split(\".\").length === 3;\n let signed: SignedRuntimeAuthority;\n try {\n signed = compact\n ? signedAuthorityFromCompactUcan(authorization)\n : signedAuthorityFromSessionGrant(node, delegation, authorization, cid);\n } catch (error) {\n if (error instanceof RuntimeDelegationRejectedError) throw error;\n reject(\"authority_invalid\", error instanceof Error ? error.message : String(error));\n }\n if (signed.expiry.getTime() <= Date.now()) {\n reject(\"expired\", \"Runtime delegation is expired.\");\n }\n if (delegation.expiry.getTime() !== signed.expiry.getTime()) {\n reject(\"authority_invalid\", \"Runtime delegation expiry does not match signed authority.\");\n }\n if (!didPrincipalsMatch(signed.audience, node.sessionDid)) {\n reject(\n \"audience_mismatch\",\n `Runtime delegation targets ${signed.audience} but this session is ${node.sessionDid}.`,\n );\n }\n if (!didPrincipalsMatch(delegation.delegateDID, signed.audience)) {\n reject(\"audience_mismatch\", \"Runtime delegation audience does not match signed authority.\");\n }\n\n if (compact && !resourcesMatch(canonicalResourcesFromPortableDelegation(delegation), signed.resources)) {\n reject(\"resources_mismatch\", \"Runtime delegation resources do not match signed authority.\");\n }\n if (options.authorize !== undefined && !options.authorize(signed.permissions)) {\n throw new Error(\"Runtime delegation is not authorized for this runtime.\");\n }\n const previouslyInstalled = node\n .getRuntimePermissionDelegations()\n .find((candidate) => candidate.cid === cid);\n if (\n previouslyInstalled !== undefined &&\n previouslyInstalled.delegationHeader.Authorization !== authorization\n ) {\n reject(\n \"cid_mismatch\",\n \"A different authorization is already installed for this runtime delegation CID.\",\n );\n }\n const primary = signed.resources[0]!;\n const signedSpace = signed.permissions.find(\n (permission) => permission.service !== \"tinycloud.encryption\",\n )?.space;\n const installedCandidate: PortableDelegation = {\n cid,\n delegationHeader: { Authorization: authorization },\n ownerAddress: delegation.ownerAddress,\n chainId: delegation.chainId,\n delegatorDID: signed.issuer,\n ...(signed.proofs.length === 1 ? { parentCid: signed.proofs[0] } : {}),\n ...(signed.remainingRedelegationDepth === undefined\n ? {}\n : {\n allowSubDelegation: signed.remainingRedelegationDepth > 0,\n disableSubDelegation: signed.remainingRedelegationDepth === 0,\n }),\n authHeader: authorization,\n spaceId: signedSpace ?? delegation.spaceId,\n path: primary.path,\n actions: [...primary.actions],\n ...(primary.caveats === undefined ? {} : { caveats: primary.caveats }),\n resources: signed.resources.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n expiry: new Date(signed.expiry),\n delegateDID: signed.audience,\n host,\n ...(compact ? {} : { siweProof: delegation.siweProof }),\n };\n\n try {\n if (\n node.isSessionOnly === true &&\n typeof node.did === \"string\" &&\n principalDidEquals(node.did, node.sessionDid) &&\n typeof node.useDelegation === \"function\"\n ) {\n await node.useDelegation(installedCandidate);\n } else {\n await node.useRuntimeDelegation(installedCandidate);\n }\n } catch (error) {\n reject(\"activation_rejected\", error instanceof Error ? error.message : String(error));\n }\n const installed = node\n .getRuntimePermissionDelegations()\n .find((candidate) => candidate.cid === cid);\n if (!installed) {\n reject(\"activation_rejected\", \"Runtime delegation activation did not install the validated authority.\");\n }\n if (\n installed.delegationHeader.Authorization !== authorization ||\n !didPrincipalsMatch(installed.delegateDID, signed.audience) ||\n installed.expiry.getTime() !== signed.expiry.getTime() ||\n !resourcesMatch(\n canonicalResourcesFromPortableDelegation(installed),\n signed.resources,\n ) ||\n normalizedHost(installed.host ?? \"\") !== host\n ) {\n reject(\n \"activation_rejected\",\n \"Runtime delegation activation installed authority that differs from the validated authority.\",\n );\n }\n\n return {\n cid,\n delegation: installed,\n effectivePermissions: signed.permissions,\n expiry: new Date(signed.expiry),\n audience: signed.audience,\n host: normalizedHost(installed.host ?? host),\n };\n}\n\n/**\n * Import compact UCAN bytes returned by an authority ceremony through the\n * ordinary runtime-delegation activation path. All transport projections are\n * derived from signed bytes before `/delegate` is called.\n */\nexport async function activateCompactRuntimeDelegation(\n node: RuntimeDelegationActivator,\n input: CompactRuntimeDelegationInput,\n): Promise<ValidatedRuntimeDelegation> {\n const authorization = input.authorization;\n const cid = node.computeDelegationCid(authorization);\n if (cid !== input.cid) {\n throw new Error(\"Compact runtime delegation CID does not match authorization bytes.\");\n }\n const signed = signedAuthorityFromCompactUcan(authorization);\n const primary = signed.resources[0]!;\n const signedSpace = signed.permissions.find(\n (permission) => permission.service !== \"tinycloud.encryption\",\n )?.space;\n const delegation: PortableDelegation = {\n cid,\n delegationHeader: { Authorization: authorization },\n ownerAddress: input.ownerAddress,\n chainId: input.chainId,\n delegatorDID: signed.issuer,\n authHeader: authorization,\n spaceId: signedSpace ?? primary.space,\n path: primary.path,\n actions: [...primary.actions],\n ...(primary.caveats === undefined ? {} : { caveats: primary.caveats }),\n resources: signed.resources.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n expiry: new Date(signed.expiry),\n delegateDID: signed.audience,\n host: normalizedHost(input.host),\n };\n return activateValidatedRuntimeDelegation(node, delegation, {\n host: input.host,\n });\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":";AAgBA,SAAS,aAAAA,kBAAiB;AA+B1B;AAAA,EACE,6BAAAC;AAAA,EACA,mCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;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;AAAA,IACT;AAGA,UAAM,YAAY,IAAI,KAAK,QAAQ,SAAS;AAC5C,QAAI,YAAY,oBAAI,KAAK,GAAG;AAC1B,WAAK,SAAS,OAAO,iBAAiB;AACtC,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAAM,S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A;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,OACK;AAcP;AAAA,EACE;AAAA,EACA;AAAA,EACA,2BAAAC;AAAA,EACA,iBAAAC;AAAA,OACK;AAGP,SAAS,kBAAAC,uBAAsB;","names":["TinyCloud","SilentNotificationHandler","AutoApproveSpaceCreationHandler","canonicalizeAddress","makePkhSpaceId","pkhDid","principalDidEquals","primarySpaceId","spaceAbilities","reject","activateSessionWithHost","KVService","SQLService","DuckDbService","HooksService","ServiceContext","ACCOUNT_REGISTRY_SPACE","SECRETS_SPACE","ErrorCodes","ENCRYPTION_PERMISSION_SERVICE","KV","SQL","DUCKDB","ENCRYPTION","EXPIRY","canonicalizeAddress","pkhDid","resolveTinyCloudHosts","principalDidEquals","parseNetworkId","resolveSecretPath","SiweMessage","EXPIRY","NETWORK_CREATE_ACTION","ENCRYPTION","DECRYPT_ACTION","KV","SQL","DUCKDB","EXPIRY","didPrincipalMatches","principalDidEquals","describeHostFailure","ENCRYPTION_PERMISSION_SERVICE","parseNetworkId","config","KVService","ServiceContext","pkhDid","ACCOUNT_REGISTRY_SPACE","canonicalizeAddress","SECRETS_SPACE","ErrorCodes","activateSessionWithHost","actions","SQLService","DuckDbService","HooksService","resolveTinyCloudHosts","crypto","descriptor","host","resolveSecretPath","now","delegation","spaceId","session","ACCOUNT_REGISTRY_SPACE","DEFAULT_MANIFEST_SPACE","CaveatedDelegationUnsupportedError","PermissionNotInManifestError","SessionExpiredError","composeManifestRequest","resolveManifest","isCapabilitySubset","expandPermissionEntries","parseExpiry","resourceCapabilitiesToSpaceAbilitiesMap","canonicalizeRecapCaveats","principalDidEquals","principalDidEquals","canonicalizeRecapCaveats","KVService","SQLService","DuckDbService","DataVaultService","createVaultCrypto","SecretsService","resolveSecretListPrefix","resolveSecretPath","DelegationManager","SharingService","CapabilityKeyRegistry","SpaceService","makePublicSpaceId","UnsupportedFeatureError","checkNodeInfo","ServiceContext"]}
|
|
1
|
+
{"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 UnsupportedSessionRestoreError,\n InvalidRestoredSessionError,\n type TinyCloudNodeConfig,\n type DelegateToOptions,\n type DelegateToResult,\n type RuntimePermissionGrantOptions,\n type EnsureEncryptionNetworkOptions,\n type SecretReadInput,\n type SecretPermissionHint,\n type SecretReadResult,\n type CreateOwnerDelegationParams,\n type OwnerDelegationReceipt,\n type RegisterPolicyV3Input,\n type RegisterPolicyV3Receipt,\n type UnifiedOwnerRootInput,\n type UnifiedOwnerRootReceipt,\n type BootstrapWarning,\n} from \"./TinyCloudNode\";\n\nexport { AccountService } from \"./account/AccountService\";\nexport type {\n AccountApplication,\n AccountApplicationListOptions,\n AccountApplicationRegisterOptions,\n AccountDelegation,\n AccountDelegationListOptions,\n AccountDelegationRevokeOptions,\n AccountIndexEnsureResult,\n AccountIndexRebuildResult,\n AccountIndexStatus,\n AccountIndexedReadOptions,\n AccountServiceConfig,\n AccountSpace,\n AccountSpaceListOptions,\n AccountStatus,\n RegisterBatchSuccess,\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 CaveatedDelegationUnsupportedError,\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 {\n activateCompactRuntimeDelegation,\n serializeDelegation,\n deserializeDelegation,\n} from \"./delegation\";\nexport type {\n CompactRuntimeDelegationInput,\n PortableDelegation,\n ValidatedRuntimeDelegation,\n} 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 KVBatchReadResponse,\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 parseSecretCatalogKey,\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 VaultNetworkReadResult,\n VaultError,\n ISecretsService,\n SecretCatalogEntry,\n SecretPayload,\n SecretsError,\n ResolvedSecretPath,\n ParsedSecretCatalogKey,\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 DelegateReceivedShareParams,\n DelegatedShareAccess,\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 { createHash } from \"node:crypto\";\nimport { SiweMessage } from \"siwe\";\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 type LocalNodeIdentityStore,\n EXPIRY,\n canonicalizeAddress,\n makePkhSpaceId,\n pkhDid,\n extractImmutableSiweFields,\n diffImmutableSiweFields,\n extractRecapAttenuations,\n unauthorizedRecapCapabilities,\n parseCanonicalRecapResource,\n ACCOUNT_REGISTRY_SPACE,\n ACCOUNT_MANIFEST_PERMISSIONS,\n KV,\n SQL,\n DUCKDB,\n CAPABILITIES,\n HOOKS,\n ENCRYPTION,\n type CapabilityPresentationEnvelopeV1,\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 = ENCRYPTION.DECRYPT;\n\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\n\n/** `<status> - <server text>` for a failed host activation. */\nfunction describeHostFailure(result: SpaceHostResult): string {\n const text = result.error?.trim();\n return text ? `${result.status} - ${text}` : `${result.status}`;\n}\n\ntype JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Canonical sorted-key JSON used by the OpenKey manifest-digest protocol.\n * Ordinary JSON semantics are applied first so undefined object fields are\n * omitted identically to a published JSON file.\n */\nexport function canonicalizeOpenKeyManifestJson(value: unknown): string {\n const json = JSON.stringify(value);\n if (json === undefined) {\n throw new TypeError(\"manifest is not JSON-serializable\");\n }\n return canonicalizeJsonValue(JSON.parse(json) as JsonValue);\n}\n\nfunction canonicalizeJsonValue(value: JsonValue): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalizeJsonValue).join(\",\")}]`;\n }\n return `{${Object.keys(value)\n .sort()\n .map(\n (key) =>\n `${JSON.stringify(key)}:${canonicalizeJsonValue(value[key]!)}`,\n )\n .join(\",\")}}`;\n}\n\n/** SHA-256 hex of the canonical JSON form of a published manifest. */\nexport function canonicalOpenKeyManifestSha256Hex(value: unknown): string {\n return createHash(\"sha256\")\n .update(canonicalizeOpenKeyManifestJson(value))\n .digest(\"hex\");\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\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\nfunction cloneAbilitiesMap(actions: AbilitiesMap): AbilitiesMap {\n return Object.fromEntries(\n Object.entries(actions).map(([service, paths]) => [\n service,\n Object.fromEntries(\n Object.entries(paths).map(([path, pathActions]) => [path, [...pathActions]]),\n ),\n ]),\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: 30 days, `EXPIRY.SESSION_MS`) */\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 /** Probe configured/registered local nodes before registry/fallback resolution. Default: true. */\n autoDiscoverLocalNode?: boolean;\n /** Local loopback node URL to probe. Omit to avoid probing loopback. */\n localNodeUrl?: string;\n /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n localLinkName?: string;\n /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n expectedNodeDid?: string;\n /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n localNodeIdentityStore?: LocalNodeIdentityStore;\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 /** Existing session manager to share with a higher-level SDK client. */\n sessionManager?: ISessionManager;\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 canonical account registry read/create-update/list permissions when composing `manifest` and plain sign-in. 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 autoDiscoverLocalNode?: boolean;\n private readonly localNodeUrl?: string;\n private readonly localLinkName?: string;\n private readonly expectedNodeDid?: string;\n private readonly localNodeIdentityStore?: LocalNodeIdentityStore;\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 activeSessionKeyId = \"default\";\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 /**\n * `nodeId` from the `GET /info` performed during sign-in/restore, tagged with\n * the host it came from. Callers that need the node DID (encryption-network\n * admin invocations) reuse this instead of re-fetching `/info`.\n */\n private _nodeInfoIdentity?: { host: string; nodeId: 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 \"\": [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA],\n },\n sql: {\n \"\": [SQL.READ, SQL.WRITE, SQL.SCHEMA, SQL.ADMIN, SQL.EXPORT],\n },\n duckdb: {\n \"\": [\n DUCKDB.READ,\n DUCKDB.WRITE,\n DUCKDB.ADMIN,\n DUCKDB.DESCRIBE,\n DUCKDB.EXPORT,\n DUCKDB.IMPORT,\n DUCKDB.EXECUTE,\n ],\n },\n capabilities: {\n \"\": [CAPABILITIES.READ],\n },\n hooks: {\n \"\": [HOOKS.SUBSCRIBE, HOOKS.REGISTER, HOOKS.LIST, HOOKS.UNREGISTER],\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.autoDiscoverLocalNode = config.autoDiscoverLocalNode;\n this.localNodeUrl = config.localNodeUrl;\n this.localLinkName = config.localLinkName;\n this.expectedNodeDid = config.expectedNodeDid;\n this.localNodeIdentityStore = config.localNodeIdentityStore;\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 // Reuse the caller's manager when authorization is owned by a higher-level\n // client so both layers address the same session keys.\n this.sessionManager = config.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 /** @internal Atomically adopt the state staged by TinyCloudNode.restoreSession. */\n installRestoredSession(\n sessionManager: ISessionManager,\n session: TinyCloudSession | undefined,\n hosts?: string[],\n ): void {\n this.sessionManager = sessionManager;\n // Restore is a complete session replacement, not an additive update. In\n // particular, a second restore may target a different host and must not\n // retain skip decisions from the previous activation.\n this.tinycloudHosts = hosts && hosts.length > 0 ? [...hosts] : undefined;\n this._lastActivationSkippedSpaceIds = [];\n if (!session) {\n this._session = undefined;\n this._tinyCloudSession = undefined;\n this._address = undefined;\n this._chainId = undefined;\n return;\n }\n this._tinyCloudSession = { ...session };\n this._address = session.address;\n this._chainId = session.chainId;\n this._session = {\n address: session.address,\n walletAddress: session.address,\n chainId: session.chainId,\n sessionKey: session.sessionKey,\n siwe: session.siwe,\n signature: session.signature,\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 autoDiscoverLocalNode: this.autoDiscoverLocalNode,\n localNodeUrl: this.localNodeUrl,\n localLinkName: this.localLinkName,\n expectedNodeDid: this.expectedNodeDid,\n localNodeIdentityStore: this.localNodeIdentityStore,\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 /**\n * The node DID reported by `GET /info` for `host`, if the sign-in (or\n * restore) that populated it targeted that same host. Returns `undefined`\n * for any other host, and for nodes whose `/info` omits `nodeId`, so callers\n * fall back to fetching it themselves rather than using a foreign node's DID.\n */\n nodeIdForHost(host: string): string | undefined {\n return this._nodeInfoIdentity?.host === host\n ? this._nodeInfoIdentity.nodeId\n : undefined;\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 const primaryActions =\n this.includeAccountRegistryPermissions && this.spacePrefix === ACCOUNT_REGISTRY_SPACE\n ? cloneAbilitiesMap(this.defaultActions)\n : this.defaultActions;\n const spaceAbilities: Record<string, AbilitiesMap> = {\n [primarySpaceId]: primaryActions,\n [secretsSpaceId]: {\n kv: {\n \"vault/secrets/\": [\n KV.GET,\n KV.PUT,\n KV.DEL,\n KV.LIST,\n KV.METADATA,\n ],\n },\n },\n };\n // Plain sessions receive the canonical account-manifest permissions in\n // the signer-derived account space. Do not duplicate the space object\n // when the primary space itself is `account`; merge into its existing\n // defaultActions map instead.\n if (\n this.includeAccountRegistryPermissions &&\n this.spacePrefix !== ACCOUNT_REGISTRY_SPACE\n ) {\n spaceAbilities[makePkhSpaceId(address, chainId, ACCOUNT_REGISTRY_SPACE)] =\n resourceCapabilitiesToAbilitiesMap(ACCOUNT_MANIFEST_PERMISSIONS);\n } else if (this.includeAccountRegistryPermissions) {\n const accountAbilities = resourceCapabilitiesToAbilitiesMap(\n ACCOUNT_MANIFEST_PERMISSIONS,\n );\n for (const [service, paths] of Object.entries(accountAbilities)) {\n const existingPaths = primaryActions[service] ?? (primaryActions[service] = {});\n for (const [path, actions] of Object.entries(paths)) {\n const existingActions = existingPaths[path] ?? (existingPaths[path] = []);\n for (const action of actions) {\n if (!existingActions.includes(action)) existingActions.push(action);\n }\n }\n }\n }\n return {\n abilities: primaryActions,\n spaceId: primarySpaceId,\n spaceAbilities,\n rawAbilities: {\n [defaultNetworkId]: [DECRYPT_ACTION, NETWORK_CREATE_ACTION],\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(\n targetSpaceId?: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<SpaceHostResult> {\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, purpose);\n\n // Convert to delegation headers and submit\n const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });\n return submitHostDelegation(host, headers);\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 (await this.hostSpace(spaceId)).success;\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(\n spaceId: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<boolean> {\n return (await this.hostOwnedSpaceResult(spaceId, purpose)).success;\n }\n\n /**\n * {@link hostOwnedSpace} with the full host-delegation result, so a failure\n * keeps its HTTP status (e.g. a typed 401/403) instead of collapsing to\n * `false`.\n */\n async hostOwnedSpaceResult(\n spaceId: string,\n purpose?: SignRequest[\"purpose\"],\n ): Promise<SpaceHostResult> {\n return this.hostSpace(spaceId, purpose);\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.success) {\n const err = Object.assign(\n new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 = Object.assign(\n new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),\n { cause: retryResult },\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.success) {\n const err = Object.assign(\n new Error(`Failed to create space ${primarySpaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 = Object.assign(\n new Error(`Failed to activate session after creating space: ${describeHostFailure(retryResult)}`),\n { cause: retryResult },\n );\n handler.onSpaceCreationFailed?.(creationContext, err);\n throw err;\n }\n\n handler.onSpaceCreated?.(creationContext);\n return;\n }\n\n throw Object.assign(\n new Error(`Failed to activate session: ${describeHostFailure(result)}`),\n { cause: result },\n );\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 purpose: \"bootstrap-session\",\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(this.activeSessionKeyId, keyId);\n this.activeSessionKeyId = 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 purpose: \"sign-in\",\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 infoHost = this.primaryTinyCloudHost;\n const nodeInfo = await checkNodeInfo(\n infoHost,\n this.wasm.protocolVersion(),\n );\n this._nodeFeatures = nodeInfo.features;\n // `/info` already told us the node DID. Keep it so encryption-network\n // admin invocations do not re-fetch `/info` just to learn it.\n this._nodeInfoIdentity = nodeInfo.nodeId\n ? { host: infoHost, nodeId: nodeInfo.nodeId }\n : undefined;\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(\n message: string,\n purpose?: SignRequest[\"purpose\"],\n ): 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 ...(purpose ? { purpose } : {}),\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(this.activeSessionKeyId, keyId);\n this.activeSessionKeyId = 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 infoHost = this.primaryTinyCloudHost;\n const nodeInfo = await checkNodeInfo(\n infoHost,\n this.wasm.protocolVersion(),\n );\n this._nodeFeatures = nodeInfo.features;\n // `/info` already told us the node DID. Keep it so encryption-network\n // admin invocations do not re-fetch `/info` just to learn it.\n this._nodeInfoIdentity = nodeInfo.nodeId\n ? { host: infoHost, nodeId: nodeInfo.nodeId }\n : undefined;\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 * End-to-end sign-in via OpenKey `authorizeTinyCloud()` (Sol CRITICAL-4).\n *\n * This is the production entry point that wires\n * {@link prepareSessionForSigning} → OpenKey `authorizeTinyCloud()` →\n * {@link signInWithOpenKeyResult} into one call. Consumers pass in a\n * caller-provided `authorizeFn` (typically a thin wrapper around\n * `openkey.authorizeTinyCloud()`) so this method has no direct\n * dependency on the OpenKey SDK — it works with any transport that\n * conforms to the versioned protocol.\n *\n * The `authorizeFn` MUST:\n * 1. Send the prepared SIWE bytes to OpenKey.\n * 2. Return the exact `TinyCloudAuthorizationResultV1` shape (with\n * `signedMessage` — the bytes the signature actually verifies\n * against — plus `selectedActionKeys` and `permissions`).\n *\n * NodeUserAuthorization then completes the session with `signedMessage`\n * (never the prepared bytes), verifying the signature, the immutable\n * SIWE fields, and every subset invariant enforced by\n * {@link signInWithOpenKeyResult}. This preserves the exact-byte\n * guarantee: if the user did NOT narrow, the returned `signedMessage`\n * equals the prepared SIWE byte-for-byte; if the user narrowed, only\n * the ReCap block differs and every immutable header field survives.\n *\n * Legacy exact-byte {@link signIn} callers are unaffected — this method\n * is opt-in.\n *\n * @param authorizeFn Callback that invokes the versioned OpenKey\n * `authorizeTinyCloud()` protocol and returns the result. Receives\n * the prepared SIWE bytes plus a `host` hint the widget should bind\n * into its /authorize-sign-prepare context.\n * @param options Optional overrides for the OpenKey request.\n */\n async signInWithOpenKey(\n authorizeFn: (input: {\n protocolVersion: 1;\n siwe: string;\n jwk: Record<string, unknown>;\n host?: string;\n /**\n * Sol MAJOR-3: OpenKey key ID (managed or external key) to sign\n * with. When omitted, the OpenKey SDK falls back to the last\n * connected key. Callers who want to bind the flow to a specific\n * OpenKey key can override via options.openkeyKeyId; otherwise the\n * bridge relies on the SDK's connected-key state.\n */\n keyId?: string;\n /**\n * Optional presentation envelope forwarded to the OpenKey widget.\n * Built from this instance's `_manifest` when set. Display-only —\n * the widget/server MUST NOT let it expand authority. The envelope\n * carries `manifests` payloads plus a stable SHA-256 digest so the\n * OpenKey server can origin-bind the browser origin against the\n * app's well-known manifest.\n */\n presentation?: CapabilityPresentationEnvelopeV1;\n }) => Promise<{\n protocolVersion: 1;\n address: string;\n signature: string;\n signedMessage: string;\n selectedActionKeys: string[];\n permissions: Array<{ service: string; space: string; path: string; actions: string[] }>;\n }>,\n options?: {\n host?: string;\n openkeyKeyId?: string;\n /**\n * Optional caller-supplied reason string forwarded in the\n * presentation envelope. Rendered as caller-supplied (never\n * verified) in the widget.\n */\n reason?: string;\n },\n ): Promise<ClientSession> {\n // A per-call host override is the host this session will actually use,\n // not merely a display hint for OpenKey. Install it before preparation so\n // the same value is bound into the authorization context and later used\n // for activation.\n if (options?.host !== undefined) {\n const overrideHost = options.host.trim();\n if (!overrideHost) {\n throw new Error(\"OpenKey authorization host must not be empty\");\n }\n this.tinycloudHosts = [overrideHost];\n }\n\n // OpenKey binds the target host into its authorization context. Resolve\n // the same host activation will use before asking OpenKey to prepare or\n // sign anything; signInWithPreparedSession is intentionally too late.\n const signingAddress = canonicalizeAddress(await this.signer.getAddress());\n const signingChainId = await this.signer.getChainId();\n await this.resolveTinyCloudHostsForSignIn(signingAddress, signingChainId);\n\n // 1. Prepare — this creates a SIWE bound to a fresh session key.\n const { prepared, keyId, jwk } = await this.prepareSessionForSigning();\n\n // 2. Build the presentation envelope from the instance manifest (if\n // any). This is the SUPPORTED production path for surfacing an\n // honest app identity in the OpenKey review UI — we NEVER\n // fabricate manifest fields, and the envelope is display-only.\n const presentation = this.buildPresentationEnvelope(options?.reason);\n\n // 3. Delegate signing to OpenKey via the caller-supplied bridge.\n // We forward the JWK so the OpenKey server can regenerate a\n // narrowed SIWE bound to the same session key when the user\n // edits the review — and never a caller-echoed JWK.\n //\n // We forward the TinyCloud host so the widget can bind it into\n // its authorization context (Sol MAJOR-2). Falls back to the\n // first resolved TinyCloud host when not overridden.\n //\n // Sol MAJOR-3: forward an OpenKey keyId when the caller supplied\n // one so the widget/SDK routes to the specific OpenKey key rather\n // than the SDK's connected-key default.\n const hostHint = this.primaryTinyCloudHost;\n const result = await authorizeFn({\n protocolVersion: 1,\n siwe: prepared.siwe,\n jwk,\n host: hostHint,\n keyId: options?.openkeyKeyId,\n presentation,\n });\n\n // 4. Complete with the EXACT bytes OpenKey signed. Every subset\n // invariant (immutable fields preserved, capabilities ⊆ prepared,\n // selectedActionKeys grounded in signedMessage, permissions\n // consistent) is enforced by signInWithOpenKeyResult before any\n // session state is created.\n return this.signInWithOpenKeyResult(result, prepared, keyId, jwk);\n }\n\n /**\n * Build a `CapabilityPresentationEnvelopeV1` from `this._manifest`. The\n * envelope is display-only — the OpenKey widget renders it under an\n * honest trust label, and the server /authorize-sign-prepare route\n * decides whether to upgrade the label to `origin-bound` by fetching\n * the well-known manifest and comparing its digest to\n * `manifestDigest`.\n *\n * Returns `undefined` when no manifest is set — the widget renders as\n * \"no manifest supplied\" (unsigned).\n *\n * The digest is a deterministic SHA-256 over canonical JSON of the\n * first manifest payload; OpenKey parses the fetched well-known manifest\n * and applies the same canonicalization before comparing digests.\n */\n private buildPresentationEnvelope(\n reason?: string,\n ): CapabilityPresentationEnvelopeV1 | undefined {\n const manifests = Array.isArray(this._manifest)\n ? this._manifest\n : this._manifest\n ? [this._manifest]\n : [];\n if (manifests.length === 0 && !reason) {\n return undefined;\n }\n // Canonical JSON: sort keys so the digest is stable across process\n // invocations and formatting/key-order changes in the published\n // well-known manifest.\n const primary = manifests[0];\n let displayName: string | undefined;\n let manifestId: string | undefined;\n let manifestDigest: string | undefined;\n const envelopeManifests: NonNullable<\n CapabilityPresentationEnvelopeV1[\"manifests\"]\n > = [];\n for (const m of manifests) {\n envelopeManifests.push({\n name: m.name,\n appId: m.app_id,\n // Deep-copy to prevent later mutations from affecting the digest.\n payload: JSON.parse(JSON.stringify(m)) as Record<string, unknown>,\n });\n }\n if (primary) {\n displayName = primary.name;\n manifestId = primary.app_id;\n manifestDigest = canonicalOpenKeyManifestSha256Hex(primary);\n }\n return {\n protocolVersion: 1,\n displayName,\n reason: reason && reason.length > 0 ? reason : undefined,\n manifestId,\n manifestDigest,\n manifests: envelopeManifests.length > 0 ? envelopeManifests : undefined,\n };\n }\n\n /**\n * Complete sign-in with a versioned OpenKey authorization result.\n *\n * Where `signInWithPreparedSession` completes with a signature over the\n * ORIGINAL prepared SIWE, this method completes with the SIWE bytes the\n * OpenKey widget actually presented and signed (`signedMessage`). It\n * exists because the versioned authorizeTinyCloud protocol lets the user\n * narrow capabilities; the returned bytes may differ from the original\n * request and are the only ones the signature actually verifies against.\n *\n * The `result` parameter is validated at the trust boundary via\n * `validateAuthorizationResultV1` (in sdk-core). Callers should validate\n * BEFORE calling this method so unknown/missing fields are rejected\n * before any session state is created.\n *\n * Validation performed here (defence-in-depth: even a \"valid\" v1 payload\n * must clear these checks before any session state is created):\n * 1. `result.address` matches the local signer's address.\n * 2. `result.signature` recovers to `result.address` when verified against\n * `result.signedMessage`.\n * 3. Every immutable SIWE header field (domain, address, URI, version,\n * chainId, nonce, issuedAt) in the original prepared SIWE is preserved\n * byte-for-byte in `result.signedMessage`. `statement` is NOT in this\n * list because the WASM renders it from the ReCap contents; it MUST\n * change when the ReCap is narrowed.\n * 4. Every capability in `result.signedMessage`'s ReCap block was present\n * in the original prepared SIWE — narrowing OK, broadening rejected.\n * 5. Every `result.selectedActionKeys` entry corresponds to a\n * (resource, action) pair in the returned SIWE.\n */\n async signInWithOpenKeyResult(\n result: {\n protocolVersion: 1;\n address: string;\n signature: string;\n signedMessage: string;\n selectedActionKeys: string[];\n permissions: Array<{ service: string; space: string; path: string; actions: string[] }>;\n },\n prepared: {\n /**\n * The ORIGINAL SIWE the SDK produced via {@link prepareSessionForSigning}.\n * Used as the source-of-truth reference for immutable-header and\n * capability-subset comparison against `result.signedMessage`.\n */\n siwe: string;\n jwk: Record<string, unknown>;\n spaceId: string;\n verificationMethod: string;\n },\n keyId: string,\n jwk: Record<string, unknown>,\n ): Promise<ClientSession> {\n if (result.protocolVersion !== 1) {\n throw new Error(`Unsupported OpenKey protocol version ${result.protocolVersion}`);\n }\n if (!result.signedMessage) {\n throw new Error(\"OpenKey result must include signedMessage\");\n }\n if (!prepared.siwe) {\n throw new Error(\n \"signInWithOpenKeyResult requires prepared.siwe (the SDK-generated SIWE the sign-in was proposed with)\",\n );\n }\n // Verify the signer matches what we expect. If the address that signed\n // does not match the address the local signer will present, refuse the\n // session — the widget returned bytes signed by someone else.\n const expectedAddress = canonicalizeAddress(await this.signer.getAddress());\n if (canonicalizeAddress(result.address) !== expectedAddress) {\n throw new Error(\n `OpenKey returned signature from ${result.address} but expected ${expectedAddress}`,\n );\n }\n\n // (2) Recover the signer from the signature over the exact bytes we are\n // about to complete the session with. SiweMessage.verify() calls\n // ethers.verifyMessage(EIP4361Message, signature) internally and matches\n // the recovered address (case-insensitive) against the message's address\n // field. Any mismatch throws, which is exactly the failure mode we want.\n let parsedSignedSiwe: SiweMessage;\n try {\n parsedSignedSiwe = new SiweMessage(result.signedMessage);\n } catch (err) {\n throw new Error(\n `OpenKey signedMessage is not a parseable SIWE: ${(err as Error).message}`,\n );\n }\n const verifyResult = await parsedSignedSiwe.verify(\n { signature: result.signature },\n { suppressExceptions: true },\n );\n if (!verifyResult.success) {\n const errData = verifyResult.error;\n const type =\n errData && typeof errData === \"object\" && \"type\" in errData\n ? (errData as { type?: string }).type\n : undefined;\n const details =\n errData && typeof errData === \"object\" && \"expected\" in errData\n ? ` (expected=${(errData as { expected?: unknown }).expected}, received=${(errData as { received?: unknown }).received})`\n : \"\";\n throw new Error(\n `OpenKey signature verification failed${type ? `: ${type}` : \"\"}${details}`,\n );\n }\n // Belt-and-braces: the SIWE `address` field must match what OpenKey\n // reported and what the local signer will present. verify() checks\n // signature-vs-siwe-address; we additionally cross-check the caller's\n // claim and the local signer.\n if (\n canonicalizeAddress(parsedSignedSiwe.address) !== expectedAddress\n ) {\n throw new Error(\n `OpenKey signedMessage.address (${parsedSignedSiwe.address}) does not match local signer address (${expectedAddress})`,\n );\n }\n\n // (3) Immutable-fields comparison. Any drift on domain/address/URI/version/\n // chainId/nonce/issuedAt/expirationTime/notBefore/requestId/nonRecapResources\n // means the widget is signing a materially different SIWE than we prepared —\n // potentially binding the session to a different relying party or a different\n // session key.\n //\n // Sol final continuation contract requirement 2: pass `originalHasRecap`\n // so `diffImmutableSiweFields` excludes `statement` for ReCap-bearing\n // SIWEs. WASM's `prepareSession` renders the entire statement from the\n // ReCap contents, so narrowing ALWAYS changes the statement — the\n // ReCap subset check below is the authoritative narrowing gate. For\n // plain SIWE flows (no urn:recap: resource) the statement remains\n // byte-immutable.\n const originalHasRecap = /(?:^|\\n)-\\s+urn:recap:/i.test(prepared.siwe);\n const originalFields = extractImmutableSiweFields(prepared.siwe);\n const signedFields = extractImmutableSiweFields(result.signedMessage);\n const changedFields = diffImmutableSiweFields(originalFields, signedFields, {\n originalHasRecap,\n });\n if (changedFields.length > 0) {\n throw new Error(\n `OpenKey signedMessage altered immutable SIWE fields: ${changedFields.join(\", \")}`,\n );\n }\n\n // (4) Capability subset. The widget may narrow the caller's request but\n // MUST NOT introduce (resource, action) pairs the caller never asked for.\n // Both sides are parsed from their `urn:recap:` resources.\n let originalCaps;\n let signedCaps;\n try {\n originalCaps = extractRecapAttenuations(prepared.siwe);\n } catch (err) {\n throw new Error(\n `Failed to decode prepared SIWE recap: ${(err as Error).message}`,\n );\n }\n try {\n signedCaps = extractRecapAttenuations(result.signedMessage);\n } catch (err) {\n throw new Error(\n `Failed to decode OpenKey signedMessage recap: ${(err as Error).message}`,\n );\n }\n const unauthorized = unauthorizedRecapCapabilities(signedCaps, originalCaps);\n if (unauthorized.length > 0) {\n const previewLimit = 5;\n const preview = unauthorized\n .slice(0, previewLimit)\n .map((u) => `${u.resource}::${u.action}`)\n .join(\", \");\n const overflow =\n unauthorized.length > previewLimit\n ? ` (and ${unauthorized.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey signedMessage broadened authorization beyond the original request: ${preview}${overflow}`,\n );\n }\n\n // Structural check: the signed SIWE must reference the expected spaceId.\n // We accept a substring match because the spaceId appears inside the\n // ReCap capability list rather than as a distinct header.\n if (!result.signedMessage.includes(prepared.spaceId)) {\n throw new Error(\n `OpenKey signedMessage does not reference the expected spaceId ${prepared.spaceId}`,\n );\n }\n\n // (5) `selectedActionKeys` and `permissions` must EXACTLY reflect the\n // capabilities in signedMessage — anything less is a trust boundary\n // violation. Two rules:\n //\n // Rule A (selectedActionKeys covers signedCaps):\n // If signedMessage grants capabilities beyond the structurally-required\n // ones (currently `tinycloud.capabilities/read`), then `selectedActionKeys`\n // MUST include a coverage entry for EVERY (resource, action) pair in\n // signedCaps. Otherwise the client has no evidence that the SDK-visible\n // selection matches the ReCap it is about to trust.\n //\n // Rule B (each selectedActionKeys entry is grounded in signedCaps):\n // Every ID the widget returns must correspond to a real (resource, action)\n // pair in signedCaps. Broadening rejected.\n //\n // Sol continuation contract: the CANONICAL OpenKey action ID format is\n // FOUR NUL-separated parts: `service\\0space\\0path\\0ability`. The keys of\n // `signedCaps` are the raw ReCap resource URIs — `space` for whole-space\n // grants, or `space/path` when a path is present. The action key is\n // `ability` (e.g. `tinycloud.kv/get`). We build a canonical index of\n // granted authority keyed by the four-part tuple and REJECT\n // selectedActionKeys that do not conform to it. Legacy 2-part\n // `resource\\0action` IDs are no longer accepted.\n const grantedPairs = new Set<string>();\n // 4-part index: `${service}\\0${space}\\0${path}\\0${ability}` → canonical\n // resource\\0action pair (used to populate the coverage-check set).\n // `service` is derived from the ability's namespace prefix\n // (`tinycloud.kv/get` → `tinycloud.kv`). `space` and `path` are derived\n // from the resource URI by splitting on the first `/` after the\n // `tinycloud:...:name` prefix.\n const grantedFourPartIndex = new Map<string, string>();\n for (const [resource, actions] of Object.entries(signedCaps)) {\n // Sol final continuation contract requirement 1: use the SHARED\n // canonical resource parser so consumer four-part IDs match the\n // producer's IDs byte-for-byte. Prior inline code left the service\n // segment inside `path` (e.g. `path=\"kv\"` for a `<space>/kv`\n // resource), which produced a different ID than OpenKey emits via\n // WASM `parseRecapFromSiwe` (which strips the service segment). The\n // divergence was the actual production round-trip failure Sol cited.\n const { space, path } = parseCanonicalRecapResource(resource);\n for (const action of Object.keys(actions)) {\n // Populate the coverage set with the canonical resource\\0action\n // pair so Rule A can check every non-required capability got\n // covered by a matching selectedActionKeys entry.\n grantedPairs.add(`${resource}\\0${action}`);\n // Canonical four-part index: derive `service` from the ability\n // prefix. Missing prefix (bare action) is refused server-side\n // in OpenKey — we simply skip it here rather than fabricate a\n // half-form 4-part ID.\n const slashIdx = action.indexOf(\"/\");\n const service = slashIdx > 0 ? action.slice(0, slashIdx) : \"\";\n if (service) {\n grantedFourPartIndex.set(\n `${service}\\0${space}\\0${path}\\0${action}`,\n `${resource}\\0${action}`,\n );\n }\n }\n }\n\n // Sol MAJOR-5: rich-result `permissions` MUST equal the signed\n // authority for EVERY resource/action pair, including structurally-\n // required capabilities. Removing required capabilities from the\n // coverage set let a widget silently omit them from the reported\n // grants — which is fine for user consent (the user cannot remove\n // them anyway) but a wire-format drift for the SDK's authoritative\n // return value. Callers that build a UI on top of `permissions` end\n // up under-reporting authority when required pairs are absent.\n // Track both the full set (for rich-result equality) and the\n // non-required set (retained for selectedActionKeys Rule A which\n // legitimately does not surface required pairs in the widget UI).\n const isStructurallyRequired = (action: string) =>\n action === \"tinycloud.capabilities/read\" || action === \"capabilities/read\";\n\n const nonRequiredGrantedPairs = new Set<string>();\n for (const pair of grantedPairs) {\n const idx = pair.indexOf(\"\\0\");\n const action = idx >= 0 ? pair.slice(idx + 1) : pair;\n if (!isStructurallyRequired(action)) {\n nonRequiredGrantedPairs.add(pair);\n }\n }\n // Sol MAJOR-5: the full granted-pair set — including required\n // capabilities — is what `permissions` must equal exactly.\n const allSignedGrantedPairs = new Set<string>(grantedPairs);\n\n // Rule B — validate each returned selectedActionKeys entry.\n // Build a set of grounded pairs so we can also enforce Rule A.\n // Sol MAJOR-4: dedupe using the raw key first — duplicates in the\n // client-supplied selection would let a subset be reported as\n // full coverage. Callers must send each ID exactly once.\n const seenRawKeys = new Set<string>();\n for (const rawKey of result.selectedActionKeys) {\n if (seenRawKeys.has(rawKey)) {\n throw new Error(\n `OpenKey selectedActionKeys contains duplicate entry ${rawKey}`,\n );\n }\n seenRawKeys.add(rawKey);\n }\n const selectedResourceActionPairs = new Set<string>();\n for (const rawKey of result.selectedActionKeys) {\n const parts = rawKey.split(\"\\0\");\n // Sol continuation contract: OpenKey emits ONLY the canonical\n // four-part `service\\0space\\0path\\0ability` shape. Legacy 2-part\n // IDs are no longer accepted — the previous fallback let a\n // malicious widget forward a `resource\\0action` pair that matched\n // by suffix without proving service canonicalization, which\n // silently expanded authority when service short-names collided.\n if (parts.length !== 4) {\n throw new Error(\n `OpenKey selectedActionKeys entry is malformed (expected canonical 4-part service\\\\0space\\\\0path\\\\0ability): ${rawKey}`,\n );\n }\n const canonical = grantedFourPartIndex.get(rawKey);\n if (!canonical) {\n throw new Error(\n `OpenKey selectedActionKeys entry ${rawKey} is not covered by any granted capability`,\n );\n }\n selectedResourceActionPairs.add(canonical);\n }\n\n // Rule A — every non-required granted pair MUST be covered by at least\n // one selectedActionKeys entry. If nonRequiredGrantedPairs is empty\n // (e.g. bootstrap-only session), we do not require selectedActionKeys\n // to be non-empty. If it is non-empty, the widget must have returned\n // selection metadata for every non-required capability the user was\n // shown; anything else is a UI/wire drift.\n if (nonRequiredGrantedPairs.size > 0) {\n const missingPairs: string[] = [];\n for (const pair of nonRequiredGrantedPairs) {\n if (!selectedResourceActionPairs.has(pair)) {\n missingPairs.push(pair);\n }\n }\n if (missingPairs.length > 0) {\n const previewLimit = 5;\n const preview = missingPairs\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n missingPairs.length > previewLimit\n ? ` (and ${missingPairs.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey selectedActionKeys is missing entries for signedMessage capabilities: ${preview}${overflow}`,\n );\n }\n }\n\n // Sol MAJOR-4: rich-result permissions MUST exactly equal the signed\n // authority. Strict rules:\n // 1. If the signed SIWE grants any capabilities, `permissions` MUST\n // cover ALL of them — an empty `permissions` array with a\n // capability-bearing SIWE is a wire-format drift and is rejected.\n // 2. Every permission entry MUST have a non-empty actions[].\n // 3. Every (permission, action) pair MUST resolve to a real\n // (resource, action) pair in signedCaps via a CANONICAL\n // resolution — no substring fallback (which would let a\n // permission on `space` match a resource on `space/leaked/path`\n // and silently expand authority to unintended paths).\n // 4. Permission entries MUST be duplicate-free after canonical\n // normalization; duplicates would let the same authority be\n // reported twice and mask a missing entry.\n // Sol MAJOR-5: reject empty `permissions` for a capability-bearing\n // SIWE regardless of whether the pairs are structurally required.\n // A signed SIWE with any granted authority MUST come back with a\n // matching non-empty permissions[] — otherwise the SDK cannot\n // reconcile local state with what was actually signed.\n if (\n allSignedGrantedPairs.size > 0 &&\n result.permissions.length === 0\n ) {\n throw new Error(\n \"OpenKey permissions is empty but signedMessage carries capabilities — refusing to accept a session without an authoritative grant list\",\n );\n }\n const permissionCanonicalKeys = new Set<string>();\n const permissionPairsCovered = new Set<string>();\n for (const perm of result.permissions) {\n const { service, space, path, actions } = perm;\n if (typeof service !== \"string\" || typeof space !== \"string\" || typeof path !== \"string\") {\n throw new Error(\n `OpenKey permissions entry has non-string service/space/path (service=${service}, space=${space}, path=${path})`,\n );\n }\n if (!Array.isArray(actions) || actions.length === 0) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) has empty actions — a capability-bearing entry must list at least one action`,\n );\n }\n const canonicalKey = `${service}\\0${space}\\0${path}`;\n if (permissionCanonicalKeys.has(canonicalKey)) {\n throw new Error(\n `OpenKey permissions has duplicate entry for (${service} ${space} ${path})`,\n );\n }\n permissionCanonicalKeys.add(canonicalKey);\n\n // Sol final continuation contract requirement 1: canonical\n // resource resolution matches the shared `parseCanonicalRecapResource`\n // used elsewhere. Two distinct on-wire resource shapes exist:\n // (a) `tinycloud:pkh:...` spaces derived from the WASM\n // `prepareSession` `abilities` map. These encode as\n // `<space>/<short-service>[/<sub-path>]` and the canonical\n // parser strips the `<short-service>` segment out of the\n // reported `path`. To match back to the raw ATT resource key\n // we RECONSTRUCT `<space>/<short>[/<path>]`.\n // (b) Non-`tinycloud:` URNs (e.g. `urn:tinycloud:encryption:...`)\n // emitted via `rawAbilities`. Here the resource URI IS the\n // space verbatim — there is no `<short-service>` segment to\n // reconstruct. `parseCanonicalRecapResource` returns\n // `{ space: uri, path: \"\" }` for these; the matched\n // resource is just `space`.\n //\n // We refuse the substring fallback that would let a permission on\n // `space` silently match a `<space>/leaked/path` resource.\n let expectedResource: string;\n if (space.startsWith(\"tinycloud:\")) {\n const shortService = service.startsWith(\"tinycloud.\")\n ? service.slice(\"tinycloud.\".length)\n : service;\n expectedResource = path\n ? `${space}/${shortService}/${path}`\n : `${space}/${shortService}`;\n } else {\n // Raw ability resource: URI is the resource key verbatim.\n // A non-empty `path` on a non-tinycloud URI would be a wire\n // shape drift — reject rather than silently permit.\n if (path) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) carries a path on a non-tinycloud: resource URI, which is not a recognized encoding`,\n );\n }\n expectedResource = space;\n }\n let matchedResource: string;\n if (signedCaps[expectedResource] !== undefined) {\n matchedResource = expectedResource;\n } else {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) claims grants not confirmed in signedMessage capabilities`,\n );\n }\n const grantedActionsForResource = new Set(\n Object.keys(signedCaps[matchedResource]),\n );\n for (const action of actions) {\n if (typeof action !== \"string\" || !action) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) has non-string action ${String(action)}`,\n );\n }\n if (!grantedActionsForResource.has(action)) {\n throw new Error(\n `OpenKey permissions entry (${service} ${space} ${path}) claims action ${action} not present in signedMessage capabilities`,\n );\n }\n permissionPairsCovered.add(`${matchedResource}\\0${action}`);\n }\n }\n // Sol MAJOR-5: EXACT equality between `permissions` coverage and the\n // signed authority — for every resource/action pair, including\n // structurally-required ones. Any missing or extra pair is a\n // wire-format drift and the SDK refuses to build a session state\n // that does not match the signed bytes byte-for-byte.\n if (allSignedGrantedPairs.size > 0) {\n const missingFromPerms: string[] = [];\n for (const pair of allSignedGrantedPairs) {\n if (!permissionPairsCovered.has(pair)) {\n missingFromPerms.push(pair);\n }\n }\n if (missingFromPerms.length > 0) {\n const previewLimit = 5;\n const preview = missingFromPerms\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n missingFromPerms.length > previewLimit\n ? ` (and ${missingFromPerms.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey permissions is missing entries for signedMessage capabilities: ${preview}${overflow}`,\n );\n }\n const extrasInPerms: string[] = [];\n for (const pair of permissionPairsCovered) {\n if (!allSignedGrantedPairs.has(pair)) {\n extrasInPerms.push(pair);\n }\n }\n if (extrasInPerms.length > 0) {\n const previewLimit = 5;\n const preview = extrasInPerms\n .slice(0, previewLimit)\n .map((p) => p.replace(\"\\0\", \"::\"))\n .join(\", \");\n const overflow =\n extrasInPerms.length > previewLimit\n ? ` (and ${extrasInPerms.length - previewLimit} more)`\n : \"\";\n throw new Error(\n `OpenKey permissions contains entries not present in the signed authority: ${preview}${overflow}`,\n );\n }\n }\n // Retain nonRequiredGrantedPairs reference so tsc doesn't drop it.\n void nonRequiredGrantedPairs;\n\n return this.signInWithPreparedSession(\n {\n siwe: result.signedMessage,\n jwk: prepared.jwk,\n spaceId: prepared.spaceId,\n verificationMethod: prepared.verificationMethod,\n },\n result.signature,\n keyId,\n jwk,\n );\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 authorizationVerdictOf,\n httpResponseError,\n type SpaceHostResult,\n KVService,\n IKVService,\n SQLService,\n ISQLService,\n DuckDbService,\n IDuckDbService,\n HooksService,\n DataVaultService,\n IDataVaultService,\n EncryptionService,\n DecryptTransportResponseError,\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 type FetchFunction,\n type SignRequest,\n type SignResponse,\n INotificationHandler,\n SilentNotificationHandler,\n IENSResolver,\n IWasmBindings,\n ISessionManager,\n type WasmRecapEntry,\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 DelegationStatus,\n DelegationRevocationReceipt,\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_DEFAULT_ONLY_SESSION_REQUEST,\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 ErrorCodes,\n ENCRYPTION_PERMISSION_SERVICE,\n CaveatedDelegationUnsupportedError,\n PermissionNotInManifestError,\n SessionExpiredError,\n canonicalizeRecapCaveats,\n recapCaveatsEqual,\n expandPermissionEntries as expandPermissionEntriesCore,\n isCapabilitySubset,\n isExplicitOnlyAction,\n parseRecapCapabilities,\n // Manifest-driven sign-in\n type Manifest,\n type AbilitiesMap,\n resourceCapabilitiesToAbilitiesMap,\n SERVICE_LONG_TO_SHORT,\n SERVICE_SHORT_TO_LONG,\n KV,\n SQL,\n DUCKDB,\n ENCRYPTION,\n EXPIRY,\n canonicalHashHex,\n canonicalizeEncryptionJson,\n verifyDidKeyEd25519Signature,\n canonicalizeAddress,\n pkhDid,\n resolveTinyCloudHosts,\n publishLocationRecord,\n type LocalNodeIdentityStore,\n principalDidEquals,\n parseNetworkId,\n resolveSecretPath,\n type BuildDecryptInvocationInput,\n type BuiltDecryptInvocation,\n type CanonicalJson,\n type DecryptResponseBody,\n type DecryptTransport,\n type EncryptionCrypto,\n type NetworkDescriptor,\n type CreateOwnerDelegationParams as CoreCreateOwnerDelegationParams,\n type OwnerDelegationPermission,\n type OwnerDelegationReceipt as CoreOwnerDelegationReceipt,\n registerPolicyV3,\n type RegisterPolicyV3Input,\n type RegisterPolicyV3Receipt,\n type ShareDeliveryAuthorizationV3Receipt,\n CREDENTIAL_INVITATION_REQUEST_DOMAIN,\n validateShareDeliveryAuthorizationV3Bytes,\n verifyEip191MessageSignature,\n signCompactUcanRootAuthorization,\n type UnifiedPolicyCapability,\n isStorageFullError,\n STORAGE_FULL_MESSAGE,\n STORAGE_WRITE_TOO_LARGE_MESSAGE,\n} from \"@tinycloud/sdk-core\";\nimport {\n parsePermissionHint,\n} from \"@tinycloud/sdk-services\";\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 type { PortableDelegation, SessionGrantProof, VerifiedSessionGrant } 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\nexport type {\n RegisterPolicyV3Input,\n RegisterPolicyV3Receipt,\n ShareDeliveryAuthorizationV3Receipt,\n} from \"@tinycloud/sdk-core\";\n\n/** Default TinyCloud host */\nconst DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nconst DEFAULT_ENCRYPTION_NETWORK_NAME = \"default\";\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\nconst DECRYPT_ACTION = ENCRYPTION.DECRYPT;\nexport const BOOTSTRAP_COMPLETION_MARKER_KEY = \"system/bootstrap/complete\";\nexport const BOOTSTRAP_COMPLETION_MARKER_VERSION = 1;\nexport const ACCEPTED_MARKER_VERSIONS: readonly number[] = [BOOTSTRAP_COMPLETION_MARKER_VERSION];\nconst NETWORK_ADMIN_TYPE = \"tinycloud.encryption.network-admin/v1\";\n\n/** Input for {@link TinyCloudNode.readSecret}. The target space is required. */\nexport interface SecretReadInput {\n /** Explicit full space URI or an owned-space name. */\n space: string;\n /** Env-style secret name. */\n name: string;\n /** Optional logical secret scope. */\n scope?: string;\n}\n\n/** Safe, validated capability hint returned when the node denies one read phase. */\nexport interface SecretPermissionHint {\n readonly service: \"tinycloud.kv\" | \"tinycloud.encryption\";\n readonly space?: string;\n readonly path: string;\n readonly actions: readonly string[];\n}\n\n/**\n * Safe classified result for an explicit-space secret read.\n *\n * Failure variants contain no raw node response, envelope, plaintext, keys,\n * tokens, or delegation data.\n */\nexport type SecretReadResult =\n | { status: \"ok\"; value: string }\n | { status: \"not_found\" }\n | { status: \"permission_required\"; hint: SecretPermissionHint }\n | { status: \"node_unreachable\" }\n | { status: \"read_failed\" }\n | { status: \"corrupt_envelope\" }\n | { status: \"decrypt_failed\" }\n | { status: \"invalid_payload\" };\n\nfunction isSecretPayload(\n value: unknown,\n): value is { value: string; createdAt: string; updatedAt: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"value\" in value &&\n typeof (value as { value?: unknown }).value === \"string\" &&\n \"createdAt\" in value &&\n typeof (value as { createdAt?: unknown }).createdAt === \"string\" &&\n \"updatedAt\" in value &&\n typeof (value as { updatedAt?: unknown }).updatedAt === \"string\"\n );\n}\n\n/**\n * Full actions the session key's root delegation grants over a space. Used for\n * both the primary space and any additional (e.g. public) spaces registered in\n * {@link TinyCloudNode.initializeV2Services}. URNs come from the canonical\n * capability registry in `@tinycloud/bootstrap` (TC-112).\n */\nconst ROOT_DELEGATION_ACTIONS: string[] = [\n KV.PUT,\n KV.GET,\n KV.DEL,\n KV.LIST,\n KV.METADATA,\n SQL.READ,\n SQL.WRITE,\n SQL.ADMIN,\n SQL.ALL,\n DUCKDB.READ,\n DUCKDB.WRITE,\n DUCKDB.ADMIN,\n DUCKDB.DESCRIBE,\n DUCKDB.EXPORT,\n DUCKDB.IMPORT,\n DUCKDB.ALL,\n];\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\nexport type CreateOwnerDelegationParams = CoreCreateOwnerDelegationParams;\n\nexport interface UnifiedOwnerRootInput {\n readonly ownerDid: string;\n readonly role: \"policy-authority\" | \"policy-enforcement\";\n readonly audienceDid: string;\n readonly policyId: string;\n readonly policyDigestHex: string;\n readonly policyCid: string;\n readonly contentSourceDigestHex: string;\n readonly capabilityCeilingHashHex: string;\n readonly nativeProjectionHashHex: string;\n readonly notBefore: Date;\n readonly expiresAt: Date;\n readonly nodeAudience: string;\n readonly capabilities: readonly UnifiedPolicyCapability[];\n}\n\nexport interface UnifiedOwnerRootReceipt {\n readonly cid: string;\n readonly delegationHeader: { readonly Authorization: string };\n readonly delegateDID: string;\n readonly spaceId: string;\n readonly path: string;\n readonly actions: readonly string[];\n readonly expiry: Date;\n}\n\nfunction unifiedRootAttenuation(\n capabilities: readonly UnifiedPolicyCapability[],\n): Record<string, Record<string, readonly Record<string, unknown>[]>> {\n const attenuation: Record<string, Record<string, readonly Record<string, unknown>[]>> = {};\n for (const capability of capabilities) {\n if (attenuation[capability.resource] !== undefined) throw new Error(\"unified owner root contains a duplicate resource\");\n attenuation[capability.resource] = capability.kind === \"encryption\"\n ? { [capability.action]: [{}] }\n : Object.fromEntries(capability.actions.map((action) => [action, [{\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n }]]));\n }\n return attenuation;\n}\n\nexport function decodeAuthorizationBytes(authorization: string): Uint8Array {\n const encoded = authorization.replace(/^Bearer /i, \"\");\n const match = /^([A-Za-z0-9_-]+)(={1,2})?$/.exec(encoded);\n const unpadded = match?.[1];\n const paddingLength = match?.[2]?.length ?? 0;\n const remainder = unpadded === undefined ? 1 : unpadded.length % 4;\n const expectedPaddingLength = remainder === 2 ? 2 : remainder === 3 ? 1 : 0;\n if (\n unpadded === undefined ||\n remainder === 1 ||\n (paddingLength !== 0 && paddingLength !== expectedPaddingLength)\n ) {\n throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n }\n const decoded = base64UrlDecode(unpadded);\n if (base64UrlEncode(decoded) !== unpadded) {\n throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n }\n return decoded;\n}\n\nexport interface OwnerDelegationReceipt extends CoreOwnerDelegationReceipt {\n readonly delegation: Delegation;\n readonly nodeReceipt: {\n /** Raw /delegate response CID: a commit-event id, not delegation identity. */\n readonly commitEventCid?: string;\n readonly activated: readonly string[];\n readonly skipped: readonly string[];\n };\n}\n\nfunction isOpenKeyAutoSignStrategy(strategy: SignStrategy | undefined): boolean {\n return (strategy as { openKeyAutoSign?: unknown } | undefined)?.openKeyAutoSign === true;\n}\n\nfunction openKeyApproval(\n strategy: SignStrategy | undefined,\n): ((request: SignRequest) => Promise<SignResponse>) | undefined {\n return (strategy as { openKeyRequestApproval?: unknown } | undefined)\n ?.openKeyRequestApproval as ((request: SignRequest) => Promise<SignResponse>) | undefined;\n}\n\n/**\n * Returns true when the signer is an external/interactive signer (browser\n * wallet, EIP-1193 provider, etc.) that will open a UI prompt for every\n * `signMessage()` call.\n *\n * Detection: the config provides a `signer` but NOT a `privateKey`, and the\n * `signStrategy` is neither the OpenKey auto-sign callback nor the auto-sign\n * strategy backed by a local key. In practice:\n * - `privateKey` present → local PrivateKeySigner → non-interactive\n * - `signStrategy.openKeyAutoSign === true` → OpenKey /api/delegate/sign → non-interactive\n * - `signer` only, no `privateKey`, no OpenKey strategy → interactive (browser wallet)\n */\nfunction isInteractiveSigner(config: TinyCloudNodeConfig): boolean {\n if (config.privateKey) {\n // Local key: always non-interactive.\n return false;\n }\n if (isOpenKeyAutoSignStrategy(config.signStrategy)) {\n // OpenKey auto-sign path: non-interactive.\n return false;\n }\n // External signer with no auto-sign strategy. Treat as interactive.\n return config.signer !== undefined;\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\nfunction clonePersistedSessionJwk(jwk: unknown): object {\n if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) {\n throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n\n try {\n const serialized = JSON.stringify(jwk);\n const cloned = serialized === undefined ? undefined : JSON.parse(serialized);\n if (cloned === null || typeof cloned !== \"object\" || Array.isArray(cloned)) {\n throw new Error(\"invalid JWK object\");\n }\n return cloned;\n } catch {\n throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n}\n\nfunction cloneRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): Record<string, unknown>[] {\n if (!caveats) return [];\n const cloneJson = (value: unknown): unknown => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value;\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return value.map(cloneJson);\n if (typeof value === \"object\") {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n const copy: Record<string, unknown> = Object.create(null);\n for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n copy[key] = cloneJson(nested);\n }\n return copy;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n try {\n return JSON.parse(JSON.stringify(caveats.map(cloneJson))) as Record<string, unknown>[];\n } catch {\n throw new Error(\"Verified persisted session ReCap contains invalid caveats.\");\n }\n}\n\n/**\n * The WASM verifier serializes ReCap caveats with serde-wasm-bindgen, which\n * returns JSON objects as `Map`s and JSON `null` as `undefined`. Convert\n * exactly those back to JSON: string-keyed `Map`s to plain objects and\n * `undefined` to `null`, recursively. Anything else is passed through for\n * cloneRecapCaveats to accept or reject.\n */\nfunction jsonFromVerifier(value: unknown): unknown {\n if (value === undefined) return null;\n if (Array.isArray(value)) return value.map(jsonFromVerifier);\n if (value instanceof Map) {\n const entries = [...value.entries()];\n if (!entries.every(([key]) => typeof key === \"string\")) return value;\n return Object.fromEntries(entries.map(([key, nested]) => [key, jsonFromVerifier(nested)]));\n }\n if (value !== null && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, jsonFromVerifier(nested)]));\n }\n return value;\n}\n\n/** Verifier ReCap entries with their caveats converted by jsonFromVerifier. */\nfunction verifierRecapEntries<T extends { caveats?: Record<string, unknown>[] }>(entries: T[]): T[] {\n return entries.map((entry) => Array.isArray(entry.caveats)\n ? { ...entry, caveats: entry.caveats.map((caveat) => jsonFromVerifier(caveat) as Record<string, unknown>) }\n : entry);\n}\n\n/**\n * The caveat-preserving ReCap a persisted-session verifier returned, as plain\n * JSON. A binding without the v2 witness cannot reconstruct signed authority.\n */\nfunction exactVerifiedRecap(verified: { verifiedRecap?: unknown }): WasmRecapEntry[] {\n // Caveats are verifier output (Maps, undefined for null): convert them\n // before the strict JSON checks below.\n const exactRecap = Array.isArray(verified.verifiedRecap)\n ? verifierRecapEntries(verified.verifiedRecap as WasmRecapEntry[])\n : verified.verifiedRecap;\n if (!Array.isArray(exactRecap) || !exactRecap.every((entry) =>\n entry !== null && typeof entry === \"object\" &&\n typeof entry.service === \"string\" &&\n typeof entry.space === \"string\" &&\n typeof entry.path === \"string\" &&\n Array.isArray(entry.actions) && entry.actions.every((action: unknown) => typeof action === \"string\") &&\n Array.isArray(entry.caveats) && entry.caveats.every((caveat: unknown) =>\n caveat !== null && typeof caveat === \"object\" && !Array.isArray(caveat)\n )\n )) {\n throw new UnsupportedSessionRestoreError(\n \"it cannot reconstruct caveat-preserving persisted ReCap authority\",\n );\n }\n return exactRecap.map((entry: WasmRecapEntry) => ({\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n}\n\n/** One replaceable set of services bound to a single host/session authority. */\nclass ServiceGraphLifetime {\n private readonly abortController = new AbortController();\n private readonly contexts = new Set<ServiceContext>();\n private retired = false;\n\n constructor(\n private readonly invokeFn: InvokeFunction,\n private readonly invokeAnyFn: InvokeAnyFunction,\n private readonly fetchFn: FetchFunction,\n ) {}\n\n readonly invoke: InvokeFunction = (session, service, path, action, facts) => {\n this.assertActive();\n return this.invokeFn(session, service, path, action, facts);\n };\n\n readonly invokeAny: InvokeAnyFunction = (session, entries, facts) => {\n this.assertActive();\n return this.invokeAnyFn(session, entries, facts);\n };\n\n readonly fetch: FetchFunction = (url, init) => {\n this.assertActive();\n return this.fetchFn(url, {\n ...init,\n signal: this.combineSignals(init?.signal),\n });\n };\n\n track(context: ServiceContext): ServiceContext {\n this.assertActive();\n this.contexts.add(context);\n return context;\n }\n\n retire(): void {\n if (this.retired) return;\n this.retired = true;\n this.abortController.abort();\n try {\n for (const context of this.contexts) {\n try {\n const retire = (context as ServiceContext & { retire?: () => void }).retire;\n if (retire) retire.call(context);\n else context.abort();\n } catch (error) {\n // Graph replacement is committed before retirement. A custom\n // service's best-effort cleanup must not roll that replacement back\n // or leave later contexts active.\n console.error(\"Error retiring service graph context:\", error);\n }\n }\n } finally {\n this.contexts.clear();\n }\n }\n\n assertActive(): void {\n if (this.retired) {\n throw new Error(\"Service graph has been retired by session replacement.\");\n }\n }\n\n private combineSignals(signal?: AbortSignal): AbortSignal {\n if (!signal) return this.abortController.signal;\n const combined = new AbortController();\n const abort = () => combined.abort();\n if (signal.aborted || this.abortController.signal.aborted) {\n abort();\n } else {\n signal.addEventListener(\"abort\", abort, { once: true });\n this.abortController.signal.addEventListener(\"abort\", abort, { once: true });\n }\n return combined.signal;\n }\n}\n\nexport class UnsupportedSessionRestoreError extends Error {\n readonly code = \"RESTORE_SESSION_KEY_REPLACEMENT_UNSUPPORTED\" as const;\n\n constructor(reason = \"it cannot replace and enumerate every live session signer\") {\n super(`Persisted session restore is unsupported by this WASM binding because ${reason}.`);\n this.name = \"UnsupportedSessionRestoreError\";\n }\n}\nexport class InvalidRestoredSessionError extends Error {\n readonly code = \"AUTH_EXPIRED\" as const;\n\n constructor(message = \"Persisted session authority is invalid or expired.\") {\n super(message);\n this.name = \"InvalidRestoredSessionError\";\n }\n}\n\nfunction canonicalRestoredVerificationMethod(\n canonicalVerificationMethod: string,\n persistedVerificationMethod: unknown,\n): string | undefined {\n if (typeof persistedVerificationMethod !== \"string\") return undefined;\n const principal = canonicalVerificationMethod.split(\"#\", 1)[0];\n return persistedVerificationMethod === principal ||\n persistedVerificationMethod === canonicalVerificationMethod\n ? canonicalVerificationMethod\n : undefined;\n}\n\nfunction persistedExpiry(value: unknown): Date {\n if (typeof value !== \"string\") throw new InvalidRestoredSessionError(\"Persisted session must include expiresAt.\");\n const expiry = new Date(value);\n if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {\n throw new InvalidRestoredSessionError();\n }\n return expiry;\n}\n\nfunction sameInstant(left: Date, right: Date): boolean {\n return left.getTime() === right.getTime();\n}\n\n/** `<status> - <server text>` for a failed host/activation request; never drops the status. */\nfunction describeHostFailure(result: SpaceHostResult): string {\n const text = result.error?.trim();\n return text ? `${result.status} - ${text}` : `${result.status}`;\n}\n\nfunction ownerDelegationPermissions(\n params: CreateOwnerDelegationParams,\n): OwnerDelegationPermission[] {\n const hasPermissions = Object.prototype.hasOwnProperty.call(params, \"permissions\");\n const hasLegacy = Object.prototype.hasOwnProperty.call(params, \"path\")\n || Object.prototype.hasOwnProperty.call(params, \"actions\");\n if (hasPermissions === hasLegacy) {\n throw new Error(\"Owner delegation requires exactly one authority shape: path/actions or permissions\");\n }\n\n const permissions: OwnerDelegationPermission[] = [];\n if (hasPermissions) {\n if (!Array.isArray(params.permissions)) {\n throw new Error(\"Owner delegation permissions are invalid\");\n }\n permissions.push(...params.permissions.map((permission) => ({\n service: permission.service,\n path: permission.path,\n actions: [...permission.actions],\n })));\n } else {\n if (typeof params.path !== \"string\" || !Array.isArray(params.actions)) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const byService = new Map<string, string[]>();\n for (const action of params.actions) {\n if (typeof action !== \"string\") {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n const slash = action.indexOf(\"/\");\n const service = slash === -1 ? \"\" : action.slice(0, slash);\n if (SERVICE_LONG_TO_SHORT[service] === undefined) {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n const actions = byService.get(service) ?? [];\n actions.push(action);\n byService.set(service, actions);\n }\n for (const [service, actions] of byService) {\n permissions.push({ service, path: params.path, actions });\n }\n }\n\n if (permissions.length === 0 || permissions.length > 16) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const resources = new Set<string>();\n for (const permission of permissions) {\n if (\n typeof permission.service !== \"string\"\n || SERVICE_LONG_TO_SHORT[permission.service] === undefined\n || typeof permission.path !== \"string\"\n || permission.path.length === 0\n || permission.path.trim() !== permission.path\n || /[\\u0000-\\u001f\\u007f\\\\*]/.test(permission.path)\n || !Array.isArray(permission.actions)\n || permission.actions.length === 0\n || permission.actions.length > 32\n ) {\n throw new Error(\"Owner delegation requires bounded capabilities\");\n }\n const resourceKey = `${permission.service}\\0${permission.path}`;\n if (resources.has(resourceKey)) {\n throw new Error(\"Owner delegation permissions contain duplicate resources\");\n }\n resources.add(resourceKey);\n const actions = new Set<string>();\n for (const action of permission.actions) {\n if (\n typeof action !== \"string\"\n || !action.startsWith(`${permission.service}/`)\n || action.length === permission.service.length + 1\n || actions.has(action)\n ) {\n throw new Error(\"Owner delegation capabilities are unsupported\");\n }\n actions.add(action);\n }\n if (permission.service === ENCRYPTION_PERMISSION_SERVICE) {\n try {\n parseNetworkId(permission.path);\n } catch {\n throw new Error(\"Owner delegation encryption permission requires a canonical network URN\");\n }\n }\n }\n return permissions;\n}\n\nfunction ownerPermissionsToAbilities(\n permissions: readonly OwnerDelegationPermission[],\n): { readonly abilities: AbilitiesMap; readonly rawAbilities: Record<string, string[]> } {\n const abilities: AbilitiesMap = {};\n const rawAbilities: Record<string, string[]> = {};\n for (const permission of permissions) {\n if (permission.service === ENCRYPTION_PERMISSION_SERVICE) {\n rawAbilities[permission.path] = [...permission.actions];\n continue;\n }\n const shortService = SERVICE_LONG_TO_SHORT[permission.service]!;\n abilities[shortService] ??= {};\n abilities[shortService][permission.path] = [...permission.actions];\n }\n return { abilities, rawAbilities };\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 /** Probe configured/registered local nodes before registry/fallback resolution. Default: true. */\n autoDiscoverLocalNode?: boolean;\n /** Local loopback node URL to probe. Omit to avoid probing loopback. */\n localNodeUrl?: string;\n /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n localLinkName?: string;\n /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n expectedNodeDid?: string;\n /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n localNodeIdentityStore?: LocalNodeIdentityStore;\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: 30 days, `EXPIRY.SESSION_MS`) */\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 account bootstrap support in plain sessions and implicit manifest permissions. 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\n * `EXPIRY.SESSION_MS` (30 days), still capped at the session's own expiry.\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 *\n * `onPrepared` runs after the delegation is fully built and signed (CID\n * included) and before it is activated with the host. It receives the same\n * `PortableDelegation` object that `delegateTo` returns as\n * `result.delegation`, so callers can durably record the grant before it\n * goes live. If the hook rejects, the delegation is not activated and\n * `delegateTo` rejects with the same error. It cannot be combined with\n * `forceWalletSign`, whose wallet path activates as part of signing.\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 * Called with the prepared delegation before host activation. A rejection\n * aborts activation and propagates from `delegateTo`.\n */\n onPrepared?: (prepared: PortableDelegation) => Promise<void>;\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\nexport interface EnsureEncryptionNetworkOptions {\n /**\n * Skip the `GET /encryption/networks/{id}` existence probe and go straight\n * to the create.\n *\n * The probe pays for itself only when the network already exists. On a\n * freshly bootstrapped account it is a guaranteed 404, so it costs a round\n * trip on the cold sign-in path and saves nothing. Creating without it is\n * safe: the server answers `409 Conflict` if the network is already there,\n * which {@link TinyCloudNode.createEncryptionNetwork} resolves by reading the\n * existing descriptor. Set this only when the caller knows the account was\n * just provisioned.\n */\n assumeMissing?: boolean;\n}\n\ninterface RuntimePermissionOperation {\n spaceId?: string;\n resource?: string;\n service: string;\n path: string;\n action: string;\n /** Exact signed ReCap attenuation for this action, if any. */\n caveats?: Record<string, unknown>[];\n}\n\ninterface RuntimePermissionGrant {\n session: ServiceSession;\n delegation: PortableDelegation;\n operations: RuntimePermissionOperation[];\n expiresAt: Date;\n /**\n * Where this grant came from. Drives precedence in\n * {@link TinyCloudNode.findGrantForOperations} (a `\"primary\"` grant — the\n * synthetic representation of the base session's own recap — always\n * out-ranks other covering grants) and gates the public-surface guardrails\n * that must never surface the synthetic primary grant. Optional so existing\n * test constructors and older call sites remain valid.\n */\n provenance?: \"primary\" | \"bootstrap\" | \"delegated\" | \"runtime\";\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 return signBytesWithJwk(new TextEncoder().encode(signingInput), jwk);\n}\n\nasync function signBytesWithJwk(bytes: Uint8Array, jwk: object): Promise<Uint8Array> {\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\n/**\n * A bootstrap step that COMPLETED but did so in a degraded way — e.g. a KV\n * batch write that failed ambiguously and was recovered by per-space\n * reconciliation. Structured (not prose) so callers can branch on `kind` and\n * `code` without parsing messages (TC-361).\n */\nexport interface BootstrapWarning {\n /** The BootstrapStep.id that degraded, e.g. \"account:seed-spaces\"\n * (BootstrapStepBase.id — packages/bootstrap/src/index.ts:642-645). */\n stepId: string;\n /** What kind of degradation. Additive union; one member today. */\n kind: \"batch-write-reconciled\";\n /** ServiceError.code of the underlying failure that was recovered from. */\n code: string;\n /** Human-readable detail. Diagnostics only — never parse this. */\n message: string;\n}\n\n/** Durable attestation that the canonical account bootstrap ceremony completed. */\nexport interface BootstrapCompletionMarker {\n v: number;\n stepIds: string[];\n completedAt: string;\n}\n\ntype BootstrapDecision =\n | { action: \"skip\" }\n | { action: \"run\"; mode: \"fresh\" | \"repair\" };\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 _serviceGraph!: ServiceGraphLifetime;\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 _baseVaults = new Map<string, DataVaultService>();\n private _baseSecrets = new Map<string, ISecretsService>();\n private _secrets = new Map<string, 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 * Memoized `recapOperationsFromSession` result, keyed by the exact SIWE it\n * was parsed from. The primary session is stable for the life of a sign-in,\n * so this avoids re-parsing the recap on every registration.\n */\n private _recapOperationsCache?: { siwe: string; operations: RuntimePermissionOperation[] };\n\n /**\n * Owned space ids this sign-in has already confirmed are hosted. Consulted by\n * {@link ensureOwnedSpaceHostedById}; cleared on every {@link signIn} because\n * hosting is confirmed against the session that was active at the time.\n */\n private readonly confirmedHostedSpaceIds = new Set<string>();\n\n /** Serializes account-registry writes for the active node instance. */\n private accountRegistryTail: Promise<void> = Promise.resolve();\n private pendingAccountRegistrySync?: {\n session: TinyCloudSession;\n promise: Promise<void>;\n };\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 private _activeServiceSession?: ServiceSession;\n\n /**\n * True when the last signIn() detected an interactive signer and skipped\n * client-side bootstrap. Apps can read this to know whether bootstrap was\n * deferred to the server (OpenKey) or requires a separate user action.\n */\n private _bootstrapSkipped = false;\n\n /**\n * Outcome of the last signIn()'s account-bootstrap attempt. `skipped` is\n * true when bootstrap did not complete in this invocation (interactive signer,\n * auto-bootstrap disabled, already provisioned, or a decision/provisioning\n * step failed). `already-provisioned` means the bootstrap was not run here;\n * it does not mean a prior provisioning attempt failed to complete.\n * `reason` carries the cause so apps can surface a \"finish account setup\"\n * call-to-action. `warnings` is\n * present when bootstrap completed, but one or more steps recovered from\n * an ambiguous failure (e.g. a KV batch write reconciled via per-space\n * fallback) — clean vs. recovered runs are otherwise byte-identical.\n */\n private _bootstrapStatus: { skipped: boolean; reason?: string; warnings?: BootstrapWarning[] } = {\n skipped: false,\n };\n\n /** Whether the last signIn() skipped client-side bootstrap because the\n * signer is interactive (browser wallet / EIP-1193 provider). */\n get bootstrapSkipped(): boolean {\n return this._bootstrapSkipped;\n }\n\n /** Outcome of the last signIn()'s account-bootstrap attempt. */\n get bootstrapStatus(): { skipped: boolean; reason?: string; warnings?: BootstrapWarning[] } {\n return this._bootstrapStatus;\n }\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 const operation: RuntimePermissionOperation = {\n spaceId: session.spaceId,\n service: this.invocationServiceName(service),\n path,\n action,\n };\n const grant = this.findGrantForOperation(operation);\n const grantedOperation = grant?.operations.find((candidate) =>\n this.operationCovers(candidate, operation),\n );\n const invocationSession = !grant || grant.provenance === \"primary\"\n ? session\n : grant.session;\n\n // The legacy single-capability binding has no caveat parameter. Calling\n // it for a restored caveated grant would silently broaden the authority,\n // so mint the equivalent one-entry aggregate invocation instead.\n if ((grantedOperation?.caveats?.length ?? 0) > 0) {\n if (!this.wasmBindings.invokeAny) {\n throw new Error(\"WASM binding does not support caveat-preserving invocation\");\n }\n return this.wasmBindings.invokeAny(invocationSession, [{\n spaceId: invocationSession.spaceId,\n service,\n path,\n action,\n caveats: cloneRecapCaveats(grantedOperation!.caveats),\n }], facts);\n }\n\n return this.wasmBindings.invoke(invocationSession, service, path, action, facts);\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 routedEntries = entries as Array<typeof entries[number] & {\n revokeAuthorityCid?: string;\n }>;\n const operations = routedEntries.flatMap((entry) => {\n const operation = this.operationFromInvokeAnyEntry(entry);\n return operation ? [operation] : [];\n });\n const authorityCid = routedEntries.length === 1\n ? routedEntries[0]?.revokeAuthorityCid\n : undefined;\n const explicitGrant = authorityCid === undefined\n ? undefined\n : this.runtimePermissionGrants.find((grant) => grant.delegation.cid === authorityCid);\n if (authorityCid !== undefined && !explicitGrant) {\n throw new Error(`Explicit revocation authority ${authorityCid} is not installed.`);\n }\n const grant = explicitGrant ?? this.findGrantForOperations(operations);\n const invocationSession = explicitGrant\n ? explicitGrant.session\n : !grant || grant.provenance === \"primary\" ? session : grant.session;\n const caveatPreservingEntries = routedEntries.map(({ revokeAuthorityCid: _cid, ...entry }) => {\n const requested = this.operationFromInvokeAnyEntry(entry);\n const granted = grant && requested && grant.operations.find((candidate) =>\n this.operationCovers(candidate, requested),\n );\n if (!granted?.caveats?.length) {\n return entry;\n }\n if (entry.caveats !== undefined &&\n !recapCaveatsEqual(entry.caveats, granted.caveats)) {\n throw new Error(\"Invocation caveats do not match signed ReCap authority.\");\n }\n return { ...entry, caveats: cloneRecapCaveats(granted.caveats) };\n });\n return this.wasmBindings.invokeAny(invocationSession, caveatPreservingEntries, 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 this._serviceGraph = this.createServiceGraphLifetime();\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 const receiveOnlyGraph = this._serviceGraph;\n this._sharingService = new SharingService({\n hosts: [this.config.host!],\n // session: undefined - not needed for receive()\n invoke: receiveOnlyGraph.invoke,\n fetch: receiveOnlyGraph.fetch,\n assertActive: () => receiveOnlyGraph.assertActive(),\n keyProvider: this._keyProvider,\n registry: this._capabilityRegistry,\n createDelegationWasm: (params) => this.createDelegationWrapper(params),\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\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 = receiveOnlyGraph.track(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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: config.autoDiscoverLocalNode,\n localNodeUrl: config.localNodeUrl,\n localLinkName: config.localLinkName,\n expectedNodeDid: config.expectedNodeDid,\n localNodeIdentityStore: config.localNodeIdentityStore,\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 ? config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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 createServiceGraphLifetime(): ServiceGraphLifetime {\n return new ServiceGraphLifetime(\n this.invokeWithRuntimePermissions,\n this.invokeAnyWithRuntimePermissions,\n // Resolve fetch at request time. This keeps the graph-owned lifetime\n // signal while preserving the SDK's existing injectable global fetch\n // behavior (including adapters that install it after construction).\n (url, init) => globalThis.fetch(url, init),\n );\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 /** The registry-resolved Node endpoint and the identity returned by that exact Node. */\n async activeNodeIdentity(): Promise<{ readonly origin: string; readonly nodeDid: string }> {\n const host = this.hosts[0];\n if (host === undefined) throw new Error(\"TinyCloud node host has not been resolved\");\n const parsed = new URL(host);\n if ((parsed.protocol !== \"https:\" && !(parsed.protocol === \"http:\" && (parsed.hostname === \"127.0.0.1\" || parsed.hostname === \"localhost\"))) || parsed.origin !== host) {\n throw new Error(\"TinyCloud node host is not a canonical origin\");\n }\n const nodeDid = await this.fetchNodeId();\n if (!nodeDid.startsWith(\"did:key:z\")) throw new Error(\"TinyCloud node identity is not a did:key\");\n return Object.freeze({ origin: parsed.origin, nodeDid });\n }\n\n /** Publish the active owner Node as a session-signed registry record. */\n async publishActiveNodeLocation(\n registryUrl: string,\n fetchFn: typeof fetch = globalThis.fetch.bind(globalThis),\n ) {\n const node = await this.activeNodeIdentity();\n return publishLocationRecord({\n registryUrl,\n subject: this.credentialHolderDid,\n nodeOrigin: node.origin,\n signer: { type: \"did:key\", signBytes: (bytes) => this.signSessionBytes(bytes) },\n fetch: fetchFn,\n });\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 /** Bare did:key principal used as the credential subject and holder binding. */\n get credentialHolderDid(): string {\n return this.sessionDid.split(\"#\", 1)[0];\n }\n\n /** Canonical verification method for the active credential holder key. */\n get credentialHolderKid(): string {\n const holder = this.credentialHolderDid;\n return `${holder}#${holder.slice(\"did:key:\".length)}`;\n }\n\n /**\n * Return the current session's signed ReCap capabilities after the session\n * has been authenticated or restored. This is intentionally distinct from\n * installed runtime delegations: it reports base-session authority only.\n *\n * Invalid or unparseable signed ReCap material throws so callers fail closed\n * rather than treating a malformed session as unrestricted authority.\n */\n getVerifiedSessionCapabilities(): PermissionEntry[] {\n const session = this.currentTinyCloudSession();\n return session?.siwe ? this.projectSignedRecapCapabilities(session.siwe) : [];\n }\n\n /** Normalize signed capabilities without collapsing nested encryption into raw authority. */\n private projectSignedRecapCapabilities(siwe: string): PermissionEntry[] {\n const projected = this.parseRecapWithCaveats(siwe).map((entry) => {\n const normalized = parseRecapCapabilities(() => [entry], siwe)[0]!;\n if (normalized.service !== \"tinycloud.encryption\") return normalized;\n if (!this.isEncryptionNetworkOperation(\"encryption\", entry.path, entry.space)) {\n return { ...normalized, space: entry.space };\n }\n return {\n service: normalized.service,\n path: normalized.path,\n actions: normalized.actions,\n ...(normalized.caveats === undefined ? {} : { caveats: normalized.caveats }),\n };\n });\n return projected.sort((left, right) =>\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.service.localeCompare(right.service) ||\n left.path.localeCompare(right.path)\n );\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 getDelegationManager: () => this.delegationManager,\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 * Get the currently active session in the shape callers can persist and later\n * pass back to {@link restoreSession}.\n */\n get restorableSession(): TinyCloudSession | undefined {\n return this.currentTinyCloudSession();\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 // Do not replace the active session while its best-effort registry sync is\n // still issuing writes with that session's authority.\n await this.accountRegistryTail;\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._baseVaults.clear();\n this._baseSecrets.clear();\n this._secrets.clear();\n this._spaceService = undefined;\n this._serviceContext = undefined;\n this.runtimePermissionGrants = [];\n this.confirmedHostedSpaceIds.clear();\n\n await this.tc.signIn(options);\n this.syncResolvedHostFromAuth();\n\n // Bind the replacement services to the runtime dependencies active for\n // this sign-in and permanently retire anything captured from the previous\n // session. The authorization flow above remains transactional: a rejected\n // sign-in leaves the existing graph untouched.\n const oldGraph = this._serviceGraph;\n this._serviceGraph = this.createServiceGraphLifetime();\n oldGraph.retire();\n this.tc.retireServices();\n\n // NodeUserAuthorization renames the constructor's \"default\" key when it\n // creates the signed-in session. Keep node-level key accessors in sync so\n // sessionDid and delegation flows use the active key instead of the old ID.\n const signedInSession = this.currentTinyCloudSession();\n if (signedInSession) {\n this.sessionKeyId = signedInSession.sessionKey;\n this.sessionKeyJwk = signedInSession.jwk;\n }\n\n // Initialize service context with session\n this.initializeServices();\n\n // Register the primary session's own recap as the highest-trust\n // (`provenance: \"primary\"`) runtime grant so it always wins invocation\n // selection over broader bootstrap/delegated grants (TC-111). Must run\n // after the primary session is established and after grants were cleared\n // above, so no dupes. `lastActivationSkippedSpaceIds` was already\n // populated by the auth layer's session activation inside `tc.signIn`\n // above, so the skipped-activation exclusion sees the real skip set here.\n const primarySession = this.currentTinyCloudSession();\n if (primarySession) {\n this.registerPrimarySessionGrant(primarySession);\n }\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 this._bootstrapSkipped = false;\n this._bootstrapStatus = { skipped: false };\n\n if (this.config.autoBootstrapAccount === false) {\n this._bootstrapStatus = { skipped: true, reason: \"auto-bootstrap-disabled\" };\n return false;\n }\n if (!this.auth || !this._address) {\n return false;\n }\n\n // Interactive signers (browser wallet / EIP-1193) prompt the user for\n // every signMessage() call. Running bootstrap through an interactive\n // signer would open 10+ sequential sign prompts. Skip client-side\n // bootstrap entirely: the server (OpenKey) handles bootstrap inside\n // POST /api/keys/{keyId}/sign before returning the first signature.\n if (isInteractiveSigner(this.config)) {\n console.debug(\n \"[TinyCloudNode] bootstrap skipped: interactive signer detected. \" +\n \"Server-side bootstrap (OpenKey) is expected to have provisioned the account.\",\n );\n this._bootstrapSkipped = true;\n this._bootstrapStatus = { skipped: true, reason: \"interactive-signer\" };\n return false;\n }\n\n const steps = bootstrapSteps(this._address, this._chainId);\n try {\n const decision = await this.resolveBootstrapDecision(steps);\n if (decision.action === \"skip\") {\n this._bootstrapStatus = { skipped: true, reason: \"already-provisioned\" };\n return false;\n }\n\n const warnings = await this.runAccountBootstrap(steps, { mode: decision.mode });\n await this.writeBootstrapCompletionMarker(steps);\n if (warnings.length > 0) {\n this._bootstrapStatus = { skipped: false, warnings };\n this.notificationHandler.warning(\n `Account bootstrap completed with warnings: ${warnings\n .map((w) => `${w.stepId} (${w.kind}: ${w.code})`)\n .join(\"; \")}`,\n );\n }\n } catch (err) {\n // Bootstrap is provisioning, not a precondition of the session the\n // user just signed: never fail signIn() because of it. Surface the\n // outcome instead so apps can offer a \"finish account setup\" action.\n const reason = err instanceof Error ? err.message : String(err);\n this._bootstrapSkipped = true;\n this._bootstrapStatus = { skipped: true, reason };\n this.notificationHandler.warning(\n `Account bootstrap did not complete: ${reason}`,\n );\n console.warn(`[TinyCloudNode] account bootstrap failed: ${reason}`);\n return false;\n }\n return true;\n }\n\n private async resolveBootstrapDecision(steps: BootstrapStep[]): Promise<BootstrapDecision> {\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 auth = this.auth;\n if (!auth) {\n throw new Error(\"Account bootstrap requires an active wallet session\");\n }\n const accountSpaceId = this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE);\n const skipped = auth.lastActivationSkippedSpaceIds;\n // Fresh blind-writes registry records; only an unhosted account space\n // proves the registry is empty.\n if (skipped.includes(accountSpaceId)) return { action: \"run\", mode: \"fresh\" };\n // Another canonical space is unhosted on an existing account (e.g. one\n // added after this account was bootstrapped): repair, never overwrite.\n if (skipped.some((spaceId) => enshrinedSpaceIds.has(spaceId))) {\n return { action: \"run\", mode: \"repair\" };\n }\n\n try {\n const markerPermission: PermissionEntry = {\n service: \"tinycloud.kv\",\n space: accountSpaceId,\n path: BOOTSTRAP_COMPLETION_MARKER_KEY,\n actions: [\"get\"],\n };\n\n if (!this.hasRuntimePermissions([markerPermission])) {\n return { action: \"run\", mode: \"repair\" };\n }\n\n const marker = await this.readBootstrapCompletionMarker();\n if (marker.ok) {\n if (this.isAcceptedBootstrapCompletionMarker(marker.data.data, steps.map((step) => step.id))) {\n return { action: \"skip\" };\n }\n return { action: \"run\", mode: \"repair\" };\n }\n\n if (\n marker.error.code === ErrorCodes.KV_NOT_FOUND &&\n this.markerReadIsUnhostedSpace(marker.error.meta)\n ) {\n return { action: \"run\", mode: \"fresh\" };\n }\n } catch (err) {\n // Marker decision and transport failures are unknown state: make one\n // bounded, idempotent repair attempt instead of treating them as\n // provisioned. Emit this separately from the repair result so callers\n // can diagnose the original decision failure.\n const reason = err instanceof Error ? err.message : String(err);\n this.notificationHandler.warning(\n `Account bootstrap decision failed; attempting one bounded repair: ${reason}`,\n );\n console.warn(`[TinyCloudNode] account bootstrap decision failed: ${reason}`);\n return { action: \"run\", mode: \"repair\" };\n }\n\n return { action: \"run\", mode: \"repair\" };\n }\n\n private async readBootstrapCompletionMarker() {\n return this.kvForSpace(this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE)).get<unknown>(\n BOOTSTRAP_COMPLETION_MARKER_KEY,\n );\n }\n\n private async writeBootstrapCompletionMarker(steps: BootstrapStep[]): Promise<void> {\n if (!this._address) {\n throw new Error(\"Bootstrap completion marker requires an active wallet session\");\n }\n const canonicalStepIds = new Set(\n bootstrapSteps(this._address, this._chainId).map((step) => step.id),\n );\n const providedStepIds = new Set(steps.map((step) => step.id));\n if (\n canonicalStepIds.size !== providedStepIds.size ||\n [...canonicalStepIds].some((stepId) => !providedStepIds.has(stepId))\n ) {\n throw new Error(\"Bootstrap completion marker requires the canonical bootstrap step set\");\n }\n\n const marker: BootstrapCompletionMarker = {\n v: BOOTSTRAP_COMPLETION_MARKER_VERSION,\n stepIds: [...canonicalStepIds],\n completedAt: new Date().toISOString(),\n };\n const written = await this.kvForSpace(this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE)).put(\n BOOTSTRAP_COMPLETION_MARKER_KEY,\n marker,\n );\n if (!written.ok) {\n throw Object.assign(\n new Error(`Failed to write bootstrap completion marker: ${written.error.message}`),\n { cause: written.error },\n );\n }\n }\n /**\n * A marker written before a canonical space was added triggers one bounded repair.\n */\n private isAcceptedBootstrapCompletionMarker(\n value: unknown,\n canonicalStepIds: readonly string[],\n ): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const entries = Object.entries(value);\n const markerValue = (name: string): unknown =>\n entries.find(([key]) => key === name)?.[1];\n const version = markerValue(\"v\");\n const stepIds = markerValue(\"stepIds\");\n return (\n typeof version === \"number\" &&\n Number.isInteger(version) &&\n ACCEPTED_MARKER_VERSIONS.some((acceptedVersion) => acceptedVersion === version) &&\n Array.isArray(stepIds) &&\n canonicalStepIds.every((stepId) => stepIds.includes(stepId))\n );\n }\n\n private markerReadIsUnhostedSpace(meta: Record<string, unknown> | undefined): boolean {\n return meta?.status === 404;\n }\n\n private async runAccountBootstrap(\n steps: BootstrapStep[],\n { mode }: { mode: \"fresh\" | \"repair\" } = { mode: \"fresh\" },\n ): Promise<BootstrapWarning[]> {\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 warnings: BootstrapWarning[] = [];\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 let session: TinyCloudSession;\n try {\n session = await auth.createBootstrapSession({\n spaceId: step.spaceId,\n capabilityRequest: step.request ?? BOOTSTRAP_SESSION_REQUESTS[step.space],\n rawAbilities,\n });\n } catch (err) {\n // Abort immediately — do not cascade into remaining bootstrap steps.\n // A single clear error is surfaced instead of one error per space.\n throw Object.assign(\n new Error(\n `Account bootstrap aborted: signature rejected for space \"${step.space}\". ` +\n `Cause: ${err instanceof Error ? err.message : String(err)}`,\n ),\n { cause: err },\n );\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.hostOwnedSpaceResult(step.spaceId, \"bootstrap-host\");\n if (!hosted.success) {\n throw Object.assign(\n new Error(`Failed to host bootstrap space ${step.spaceId}: ${describeHostFailure(hosted)}`),\n { cause: hosted },\n );\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 Object.assign(\n new Error(\n `Failed to activate bootstrap session for ${step.spaceId}: ${\n activated.success ? \"space was skipped\" : describeHostFailure(activated)\n }`,\n ),\n { cause: activated },\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 Object.assign(new Error(`Failed to create account index schema: ${ensured.error.message}`), { cause: ensured.error });\n }\n }\n\n if (step.kind === \"seed-spaces\") {\n const inputs = step.spaces.map((space) => ({\n spaceId: space.spaceId,\n name: space.name,\n ownerDid: this.did,\n type: \"owned\" as const,\n permissions: [\"*\"],\n status: \"active\" as const,\n }));\n if (mode === \"fresh\") {\n // Fresh batches because the registry is provably empty. Repair\n // preserves existing records and only creates missing spaces.\n const registered = await this.account.spaces.registerBatch(inputs);\n if (!registered.ok) {\n throw Object.assign(\n new Error(`Failed to seed account spaces: ${registered.error.message}`),\n { cause: registered.error },\n );\n }\n const batchError = registered.data.recoveredFromBatchError;\n if (batchError) {\n warnings.push({\n stepId: step.id,\n kind: \"batch-write-reconciled\",\n code: batchError.code,\n message: batchError.message,\n });\n }\n } else {\n const ensured = await this.account.spaces.registerMissing(inputs);\n if (!ensured.ok) {\n throw Object.assign(\n new Error(`Failed to seed account spaces: ${ensured.error.message}`),\n { cause: ensured.error },\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 // The write is an INSERT OR REPLACE and is safe to repeat during a\n // repair, so skip the manifest-hash pre-read.\n { assumeUnregistered: true },\n );\n if (!registered.ok) {\n throw Object.assign(new Error(`Failed to seed bootstrap applications: ${registered.error.message}`), { cause: registered.error });\n }\n }\n\n if (step.kind === \"encryption-network-create\") {\n // A repair probes before creating because the network may already\n // exist; a 409 remains a race guard in both modes.\n await this.ensureEncryptionNetwork(step.networkId, { assumeMissing: mode === \"fresh\" });\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 Object.assign(\n new Error(`Failed to create secret_records schema: ${migrated.error.message}`),\n { cause: migrated.error },\n );\n }\n }\n }\n\n return warnings;\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 provenance: \"bootstrap\",\n });\n }\n\n /**\n * Map the base session's OWN recap into runtime permission operations.\n *\n * Uses the RAW `parseRecapFromSiwe` binding — NOT `parseRecapCapabilities`,\n * whose `normalizeSpace` collapses `tinycloud:pkh:...:<owner>:<space>` to a\n * bare short name and would conflate two owners' identically-named spaces.\n * We must keep the full owner-scoped URI so a synthetic primary grant can\n * never cover an operation on a different owner's space.\n *\n * Only top-level encryption network entries (`space: \"encryption\"` or\n * absent) become `resource` ops. A network-shaped path nested under a\n * data space remains a `spaceId` op, not raw network authority.\n * One op per action.\n *\n * Returns `[]` for session-only / restored-without-siwe modes and for any\n * unparseable SIWE — the primary grant is simply not registered in that case.\n */\n private recapOperationsFromSession(\n session: TinyCloudSession,\n ): RuntimePermissionOperation[] {\n const siwe = session.siwe;\n if (!siwe) {\n return [];\n }\n if (this._recapOperationsCache?.siwe === siwe) {\n return this._recapOperationsCache.operations;\n }\n let operations: RuntimePermissionOperation[] = [];\n try {\n const entries = this.parseRecapWithCaveats(siwe);\n if (Array.isArray(entries)) {\n operations = entries.flatMap((entry) => {\n const service = this.invocationServiceName(entry.service);\n return entry.actions.map((action) => ({\n ...(this.isEncryptionNetworkOperation(service, entry.path, entry.space)\n ? { resource: entry.path }\n : { spaceId: entry.space }),\n service,\n path: entry.path,\n action,\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n });\n }\n } catch {\n operations = [];\n }\n this._recapOperationsCache = { siwe, operations };\n return operations;\n }\n\n /**\n * Register the base (primary) session's own recap as a synthetic runtime\n * grant tagged `provenance: \"primary\"` so it always out-ranks other covering\n * grants in {@link findGrantForOperations}. This closes the selection-design\n * hazard where a broad — possibly broken — bootstrap/delegated grant could\n * hijack an operation the primary session itself already authorized (TC-111).\n *\n * Two safety exclusions:\n * - Ops whose space is in `lastActivationSkippedSpaceIds` are dropped: the\n * node refused to activate those spaces this sign-in even though the recap\n * claims them. Including them would let the synthetic primary out-rank a\n * working grant and 401 (the \"skipped-activation inverted hijack\").\n * - Encryption `resource` ops are kept as-is (space-independent).\n *\n * No-ops when nothing remains after exclusion. Callers (`signIn`,\n * `restoreSession`) clear `runtimePermissionGrants` first, so no dupes.\n */\n private registerPrimarySessionGrant(session: TinyCloudSession): void {\n const skipped = this.auth\n ? (this.auth as NodeUserAuthorization).lastActivationSkippedSpaceIds ?? []\n : [];\n const operations = this.recapOperationsFromSession(session).filter(\n (operation) =>\n operation.spaceId === undefined ||\n !skipped.some((spaceId) => this.spaceIdsEqual(spaceId, operation.spaceId!)),\n );\n if (operations.length === 0) {\n return;\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 provenance: \"primary\",\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 Object.assign(\n new Error(`Failed to write manifest registry records: ${result.error.message}`),\n { cause: result.error },\n );\n }\n }\n\n private scheduleAccountRegistrySync(): void {\n const session = this.currentTinyCloudSession();\n if (!session || this.pendingAccountRegistrySync?.session === session) {\n return;\n }\n\n const promise = this.enqueueAccountRegistryOperation(session, async () => {\n await this.withAccountRegistryRetry(async () => {\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n await this.account.index.ensure();\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n await this.writeManifestRegistryRecords();\n\n if (this.currentTinyCloudSession() !== session) {\n return;\n }\n\n if (this.currentSessionCanListSpaces()) {\n const spaces = await this.account.spaces.syncAccessible();\n if (!spaces.ok) {\n throw Object.assign(\n new Error(`Failed to sync account spaces: ${spaces.error.message}`),\n { cause: spaces.error },\n );\n }\n }\n // Else: the current session carries a recap that does not grant\n // `tinycloud.space/list` (every manifest/recap session, and the default\n // non-manifest recap alike — its abilities table has no `space` service).\n // `syncAccessible()` depends on `tinycloud.space/list`, which such a\n // session does not hold — see {@link isOwnedSpaceRegistered} — so the\n // owned-space listing is a doomed request that 401s on the wire\n // (`Unauthorized Action: …/space/ tinycloud.space/list`). The account\n // spaces registry is instead maintained by bootstrap seeding +\n // `spaces.register()`, so we skip the invoke entirely rather than emit it.\n });\n });\n\n this.pendingAccountRegistrySync = { session, promise };\n const clearPendingSync = () => {\n if (this.pendingAccountRegistrySync?.promise === promise) {\n this.pendingAccountRegistrySync = undefined;\n }\n };\n void promise.then(clearPendingSync, clearPendingSync);\n }\n\n private enqueueAccountRegistryOperation(\n session: TinyCloudSession,\n task: () => Promise<void>,\n ): Promise<void> {\n const operation = this.accountRegistryTail.then(async () => {\n if (this.currentTinyCloudSession() === session) {\n await task();\n }\n });\n this.accountRegistryTail = operation.catch(() => {});\n return operation;\n }\n\n /**\n * Whether the current primary session may invoke `tinycloud.space/list`.\n *\n * A session with NO parseable recap (session-only / restored-without-siwe)\n * yields zero recap operations — we preserve today's behavior and let\n * `syncAccessible()` run. A session whose parseable recap has entries but\n * none granting `tinycloud.space/list` cannot list owned spaces; the guard\n * skips. Every wallet SIWE session in this stack carries a recap (manifest\n * sessions and the default non-manifest recap alike), and none grant\n * `space/list`, so all of them skip.\n *\n * Reuses the TC-111 {@link recapOperationsFromSession} primitive — no second\n * recap parser.\n */\n private currentSessionCanListSpaces(): boolean {\n const session = this.currentTinyCloudSession();\n const operations = session\n ? this.recapOperationsFromSession(session)\n : [];\n if (operations.length === 0) {\n return true;\n }\n return operations.some(\n (operation) =>\n operation.service === \"space\" &&\n this.actionContains(operation.action, \"tinycloud.space/list\"),\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 // Authorization verdicts are deterministic, not transient: retrying a\n // 401/403 only re-emits the doomed request (the 2026-07-03 recap-storm\n // incident). The typed status/code decides whatever the body says;\n // the message pattern is only a fallback for untyped errors. Warn once\n // and stop; generic errors still get the full retry budget below.\n const verdict = authorizationVerdictOf(error);\n const message = error instanceof Error ? error.message : String(error);\n const isAuthorizationVerdict = verdict === undefined\n ? /Unauthorized Action|\\b(?:401|403)\\b/.test(message)\n : verdict !== \"other\";\n if (isAuthorizationVerdict) {\n console.warn(\n \"TinyCloud account registry sync stopped: authorization verdict is not retryable\",\n error,\n );\n return;\n }\n // A full account space stays full until the owner frees space or\n // upgrades, so retrying only repeats a rejected write. The wrapped\n // SDK error decides; the message is the fallback for untyped errors.\n if (\n isStorageFullError(error as { code?: string }) ||\n isStorageFullError((error as { cause?: { code?: string } } | null)?.cause) ||\n message.includes(STORAGE_FULL_MESSAGE) ||\n message.includes(STORAGE_WRITE_TOO_LARGE_MESSAGE)\n ) {\n console.warn(\"TinyCloud account registry sync stopped: storage is full\", error);\n return;\n }\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 /**\n * Ensure one of this user's owned spaces is hosted, at most once per space\n * per sign-in.\n *\n * Account bootstrap funnels six calls through here (via\n * `AccountService.ensureAccountSpaceHosted`), and each one re-submits\n * `activateSessionWithHost` with the *primary* session. That session's recap\n * covers only `default` and `secrets`, so the account space appears in\n * neither `activated` nor `skipped` and the guard below returns immediately\n * — the repeat calls cannot change the outcome, they only cost round trips.\n *\n * The memo is per sign-in ({@link confirmedHostedSpaceIds} is cleared in\n * `signIn`) and only records confirmed successes. A wrong skip is\n * self-revealing: the next write to the space fails immediately and loudly\n * with `404 Space not found`.\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 if (this.confirmedHostedSpaceIds.has(spaceId)) {\n return;\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 this.confirmedHostedSpaceIds.add(spaceId);\n return;\n }\n\n if (!activation.success && activation.status !== 404) {\n throw Object.assign(\n new Error(`Failed to check owned space ${spaceId}: ${describeHostFailure(activation)}`),\n { cause: activation },\n );\n }\n\n const created = await (this.auth as NodeUserAuthorization).hostOwnedSpaceResult(spaceId);\n if (!created.success) {\n throw Object.assign(\n new Error(`Failed to create owned space ${spaceId}: ${describeHostFailure(created)}`),\n { cause: created },\n );\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 Object.assign(\n new Error(\n `Failed to activate session after creating owned space ${spaceId}: ${\n retry.success ? \"space was skipped\" : describeHostFailure(retry)\n }`,\n ),\n { cause: retry },\n );\n }\n this.confirmedHostedSpaceIds.add(spaceId);\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 const session = this.auth?.tinyCloudSession;\n if (!this.auth || !session) {\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).hostOwnedSpaceResult(spaceId);\n if (!hosted.success) {\n throw Object.assign(\n new Error(`Failed to host owned space ${spaceId}: ${describeHostFailure(hosted)}`),\n { cause: hosted },\n );\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 session.delegationHeader,\n );\n if (!activation.success || activation.skipped?.includes(spaceId)) {\n throw Object.assign(\n new Error(\n `Failed to activate session for owned space ${spaceId}: ${\n activation.success ? \"space was skipped\" : describeHostFailure(activation)\n }`,\n ),\n { cause: activation },\n );\n }\n\n try {\n await this.enqueueAccountRegistryOperation(session, async () => {\n await this.account.spaces.register({\n spaceId,\n name,\n ownerDid: this.did,\n type: \"owned\",\n permissions: [\"*\"],\n status: \"active\",\n });\n });\n } catch {\n // Registry write is best-effort; the space is hosted regardless.\n }\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 // signIn schedules its registry sync before returning. Let that operation\n // finish before this explicit read/host/write sequence begins.\n await this.accountRegistryTail;\n\n const spaceId = this.ownedSpaceId(name);\n\n if (await this.isOwnedSpaceRegistered(spaceId)) {\n return spaceId;\n }\n\n return this.hostOwnedSpace(name);\n }\n\n /** Resolve and authenticate the owner encoded by an owned-space URI. */\n credentialSpaceOwnerDid(spaceId: string): string {\n const ownerDid = this.ownerDidFromSpaceId(spaceId);\n if (ownerDid === undefined || !didPrincipalMatches(ownerDid, this.did)) {\n throw new Error(\"Credential space owner does not match the active TinyCloud owner\");\n }\n return ownerDid;\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 /** Additional capability spaces persisted with the primary session. */\n spaces?: Record<string, 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`. When any signed-session\n * metadata is restored, this is required and verified in WASM before\n * local ReCap or expiry authority is installed.\n */\n signature?: string;\n /**\n * Persisted policy expiry. Required when an otherwise valid SIWE omits\n * `Expiration Time`; restore never invents a new renewable lifetime.\n */\n expiresAt?: 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 // Build every part of the restored state against a disposable manager.\n // Nothing live is touched until the commit below.\n let restoredJwk: object;\n try {\n restoredJwk = clonePersistedSessionJwk(sessionData.jwk);\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n if (\n sessionData.chainId !== undefined &&\n (!Number.isSafeInteger(sessionData.chainId) || sessionData.chainId <= 0)\n ) {\n throw new InvalidRestoredSessionError(\"Persisted session chain ID must be a positive safe integer.\");\n }\n const stagedManager = this.wasmBindings.createSessionManager();\n const stagedReplace = stagedManager.replaceSessionKey;\n const liveKeys = this.sessionManager.listSessionKeys;\n const stagedKeys = stagedManager.listSessionKeys;\n if (\n typeof stagedReplace !== \"function\" ||\n typeof liveKeys !== \"function\" ||\n typeof stagedKeys !== \"function\"\n ) {\n throw new UnsupportedSessionRestoreError();\n }\n let stagedKeyId: string;\n let stagedJwk: object;\n let canonicalVerificationMethod: string;\n // Replacing a primary signer without a complete key inventory silently\n // loses receive/share keys. Require the capability rather than guessing.\n const keyIds = liveKeys.call(this.sessionManager);\n if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === \"string\")) {\n throw new UnsupportedSessionRestoreError(\"it cannot reliably enumerate every live session signer\");\n }\n for (const keyId of keyIds) {\n if (keyId === this.sessionKeyId) continue;\n const jwk = this.sessionManager.jwk(keyId);\n if (!jwk) throw new Error(\"missing live session key\");\n stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);\n }\n try {\n stagedKeyId = stagedReplace.call(stagedManager, restoredJwk, this.sessionKeyId);\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid private Ed25519 session key.\");\n }\n const stagedJwkJson = stagedManager.jwk(stagedKeyId);\n if (!stagedJwkJson) throw new Error(\"missing restored session key\");\n stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));\n canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);\n const restoredVerificationMethod = canonicalRestoredVerificationMethod(\n canonicalVerificationMethod,\n sessionData.verificationMethod,\n );\n if (!restoredVerificationMethod) {\n throw new InvalidRestoredSessionError(\n \"Persisted session verification method does not match its private Ed25519 session key.\",\n );\n }\n const proofValues = [\n sessionData.siwe,\n sessionData.signature,\n sessionData.address,\n sessionData.chainId,\n ];\n const hasPersistedProof = proofValues.every((value) => value !== undefined);\n if (!hasPersistedProof && (proofValues.some((value) => value !== undefined) || sessionData.expiresAt !== undefined)) {\n throw new InvalidRestoredSessionError(\"Persisted session authority metadata is incomplete.\");\n }\n\n let restoredAddress: string | undefined;\n try {\n restoredAddress = hasPersistedProof ? canonicalizeAddress(sessionData.address!) : undefined;\n } catch {\n throw new InvalidRestoredSessionError(\"Persisted session has an invalid wallet address.\");\n }\n let stagedSessionExpiry = new Date(0);\n let stagedRecap: WasmRecapEntry[] = [];\n if (hasPersistedProof) {\n if (typeof this.wasmBindings.validatePersistedSession !== \"function\") {\n throw new UnsupportedSessionRestoreError(\"it cannot verify persisted SIWE authority\");\n }\n const verified = (() => {\n try {\n return this.wasmBindings.validatePersistedSession!({\n delegationHeader: sessionData.delegationHeader,\n delegationCid: sessionData.delegationCid,\n spaceId: sessionData.spaceId,\n jwk: stagedJwk,\n address: restoredAddress!,\n chainId: sessionData.chainId!,\n siwe: sessionData.siwe!,\n signature: sessionData.signature!,\n });\n } catch (error) {\n throw new InvalidRestoredSessionError(error instanceof Error ? error.message : String(error));\n }\n })();\n stagedRecap = exactVerifiedRecap(verified);\n const signedExpiry = verified.expiresAt === undefined\n ? undefined\n : persistedExpiry(verified.expiresAt);\n const persistedPolicyExpiry = sessionData.expiresAt === undefined\n ? undefined\n : persistedExpiry(sessionData.expiresAt);\n if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {\n throw new InvalidRestoredSessionError(\"Persisted session expiry does not match its signed SIWE authority.\");\n }\n stagedSessionExpiry = signedExpiry ?? persistedPolicyExpiry ?? persistedExpiry(undefined);\n }\n const resolvedHost = await this.resolveRestoredHost(\n sessionData.tinycloudHosts,\n restoredAddress,\n sessionData.chainId,\n );\n const stagedHost = resolvedHost ?? this.config.host!;\n // Never blend a metadata-light restore with the prior wallet identity.\n const stagedAddress = restoredAddress;\n const stagedChainId = sessionData.chainId ?? 1;\n const stagedNodeDid = stagedAddress\n ? pkhDid(stagedAddress, stagedChainId)\n : canonicalVerificationMethod;\n const serviceSession: ServiceSession = {\n delegationHeader: sessionData.delegationHeader,\n delegationCid: sessionData.delegationCid,\n spaceId: sessionData.spaceId,\n verificationMethod: restoredVerificationMethod,\n jwk: stagedJwk,\n };\n const stagedTcSession: TinyCloudSession | undefined =\n hasPersistedProof ? {\n address: restoredAddress!,\n chainId: sessionData.chainId!,\n sessionKey: JSON.stringify(stagedJwk),\n spaceId: sessionData.spaceId,\n spaces: sessionData.spaces,\n delegationCid: sessionData.delegationCid,\n delegationHeader: sessionData.delegationHeader,\n verificationMethod: restoredVerificationMethod,\n jwk: stagedJwk as { [k: string]: unknown },\n siwe: sessionData.siwe!,\n signature: sessionData.signature!,\n } : undefined;\n const stagedPrimary = this.stagePrimarySessionState(\n stagedTcSession,\n stagedNodeDid,\n stagedHost,\n stagedSessionExpiry,\n stagedRecap,\n );\n const stagedAccountSpaceId = stagedAddress\n ? this.wasmBindings.makeSpaceId(stagedAddress, stagedChainId, ACCOUNT_REGISTRY_SPACE)\n : undefined;\n const stagedGraph = this.stageRestoredServiceGraph({\n host: stagedHost,\n manager: stagedManager,\n serviceSession,\n verificationMethod: canonicalVerificationMethod,\n nodeDid: stagedNodeDid,\n address: stagedAddress,\n chainId: stagedChainId,\n accountSpaceId: stagedAccountSpaceId,\n tinyCloudSession: stagedTcSession,\n sessionExpiry: stagedSessionExpiry,\n recap: stagedRecap,\n });\n\n // Every operation below is a non-throwing pointer/value swap.\n const oldGraph = this._serviceGraph;\n const oldCore = this.tc;\n this.sessionManager = stagedManager;\n this.sessionKeyId = stagedKeyId;\n this.sessionKeyJwk = stagedJwk;\n if (resolvedHost) this.config.host = resolvedHost;\n this._address = stagedAddress;\n this._chainId = stagedChainId;\n this._serviceContext = stagedGraph.serviceContext;\n this._kv = stagedGraph.kv;\n this._sql = stagedGraph.sql;\n this._duckdb = stagedGraph.duckdb;\n this._hooks = stagedGraph.hooks;\n this._vault = stagedGraph.vault;\n this._encryption = stagedGraph.encryption;\n this._capabilityRegistry = stagedGraph.capabilityRegistry;\n this._keyProvider = stagedGraph.keyProvider;\n this._sharingService = stagedGraph.sharingService;\n this._delegationManager = stagedGraph.delegationManager;\n this._spaceService = stagedGraph.spaceService;\n this._serviceGraph = stagedGraph.graph;\n this._activeServiceSession = serviceSession;\n this._baseSecrets = new Map();\n this._secrets = new Map();\n this._publicKV = undefined;\n this._account = undefined;\n this.tc = stagedGraph.core;\n this._recapOperationsCache = stagedPrimary.cache;\n this.runtimePermissionGrants = stagedPrimary.grants;\n this.confirmedHostedSpaceIds.clear();\n if (this.auth) {\n this.auth.installRestoredSession(stagedManager, stagedTcSession, [stagedHost]);\n this._restoredTcSession = undefined;\n } else {\n this._restoredTcSession = stagedTcSession;\n }\n oldGraph.retire();\n (oldCore as { retireServices?: () => void } | null)?.retireServices?.();\n }\n\n private stagePrimarySessionState(\n session: TinyCloudSession | undefined,\n verificationMethod: string,\n host: string,\n sessionExpiry: Date,\n recap: WasmRecapEntry[],\n ): { cache: { siwe: string; operations: RuntimePermissionOperation[] } | undefined; grants: RuntimePermissionGrant[] } {\n if (!session?.siwe) return { cache: undefined, grants: [] };\n let operations: RuntimePermissionOperation[] = [];\n operations = recap.flatMap((entry) => {\n const service = this.invocationServiceName(entry.service);\n return entry.actions.map((action) => ({\n ...(this.isEncryptionNetworkOperation(service, entry.path, entry.space) ? { resource: entry.path } : { spaceId: entry.space }),\n service,\n path: entry.path,\n action,\n caveats: cloneRecapCaveats(entry.caveats),\n }));\n });\n const cache = { siwe: session.siwe, operations };\n // Restored authority has no host-activation result yet. Importing a skip\n // list from an unrelated prior session would erase valid restored grants.\n if (operations.length === 0) return { cache, grants: [] };\n const expiresAt = sessionExpiry;\n return {\n cache,\n grants: [{\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: verificationMethod,\n spaceId: session.spaceId,\n path: \"\",\n actions: [...new Set(operations.map((operation) => operation.action))],\n expiry: expiresAt,\n allowSubDelegation: true,\n ownerAddress: session.address,\n chainId: session.chainId,\n host,\n },\n operations,\n expiresAt,\n provenance: \"primary\",\n }],\n };\n }\n\n private stageRestoredServiceGraph(input: {\n host: string;\n manager: ISessionManager;\n serviceSession: ServiceSession;\n verificationMethod: string;\n nodeDid: string;\n address: string | undefined;\n chainId: number;\n accountSpaceId: string | undefined;\n tinyCloudSession: TinyCloudSession | undefined;\n sessionExpiry: Date;\n recap: WasmRecapEntry[];\n }): {\n core: TinyCloud | null;\n graph: ServiceGraphLifetime;\n serviceContext: ServiceContext;\n kv: KVService;\n sql: SQLService;\n duckdb: DuckDbService;\n hooks: HooksService;\n vault: DataVaultService;\n encryption: EncryptionService;\n capabilityRegistry: CapabilityKeyRegistry;\n keyProvider: WasmKeyProvider;\n sharingService: SharingService;\n delegationManager: DelegationManager;\n spaceService: SpaceService;\n } {\n // TinyCloud owns the public-KV service graph. Stage a replacement core\n // context alongside the node graph so repeated cross-host restores cannot\n // leave publicKV pointed at a stale or uninitialized context.\n const graph = this.createServiceGraphLifetime();\n const core = this.auth\n ? new TinyCloud(this.auth, {\n invokeAny: graph.invokeAny,\n telemetry: this.config.telemetry,\n })\n : null;\n if (core) {\n core.initializeServices(graph.invoke, [input.host], graph.fetch);\n const coreContext = graph.track(core.serviceContext as ServiceContext);\n coreContext.setSession(input.serviceSession);\n }\n const serviceContext = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n const kv = new KVService({});\n kv.initialize(serviceContext);\n serviceContext.registerService('kv', kv);\n const sql = new SQLService({});\n sql.initialize(serviceContext);\n serviceContext.registerService('sql', sql);\n const duckdb = new DuckDbService({});\n duckdb.initialize(serviceContext);\n serviceContext.registerService('duckdb', duckdb);\n const hooks = new HooksService({});\n hooks.initialize(serviceContext);\n serviceContext.registerService('hooks', hooks);\n serviceContext.setSession(input.serviceSession);\n const encryption = this.createEncryptionService({\n graph,\n host: input.host,\n session: input.serviceSession,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n });\n encryption.initialize(serviceContext);\n serviceContext.registerService('encryption', encryption);\n const vault = this.createVaultService(input.serviceSession.spaceId, kv, encryption, {\n host: input.host,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n serviceGraph: graph,\n });\n vault.initialize(serviceContext);\n serviceContext.registerService('vault', vault);\n\n const capabilityRegistry = new CapabilityKeyRegistry();\n if (input.tinyCloudSession) {\n const session = input.tinyCloudSession;\n // ReCap entries are returned by the verifier that authenticated this\n // SIWE. Persisted space metadata is only a routing hint and cannot add\n // an unsigned space, path, or action to the registry.\n const delegations: Delegation[] = input.recap.map((entry) => ({\n cid: session.delegationCid,\n delegateDID: session.verificationMethod,\n spaceId: this.spaceIdsEqual(entry.space, session.spaceId) ? session.spaceId : entry.space,\n path: entry.path,\n actions: [...entry.actions],\n caveats: cloneRecapCaveats(entry.caveats),\n expiry: input.sessionExpiry,\n isRevoked: false,\n allowSubDelegation: true,\n }));\n if (delegations.length > 0) {\n capabilityRegistry.registerKey({\n id: session.sessionKey,\n did: session.verificationMethod,\n type: \"session\",\n jwk: session.jwk as JWK,\n priority: 0,\n }, delegations);\n }\n }\n const delegationManager = new DelegationManager({\n hosts: [input.host],\n accountSpaceId: input.accountSpaceId,\n session: input.serviceSession,\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n });\n const keyProvider = new WasmKeyProvider({ sessionManager: input.manager });\n const sharingService = new SharingService({\n hosts: [input.host],\n invoke: graph.invoke,\n fetch: graph.fetch,\n assertActive: () => graph.assertActive(),\n keyProvider,\n registry: capabilityRegistry,\n createDelegationWasm: (params) => this.createDelegationWrapper(params),\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\n createKVService: (config) => {\n const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, '') });\n const context = graph.track(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 context.setSession(config.session);\n service.initialize(context);\n return service;\n },\n });\n sharingService.updateConfig({\n session: input.serviceSession,\n delegationManager,\n sessionExpiry: input.sessionExpiry,\n createDelegationWasm: (params) => {\n graph.assertActive();\n return this.createDelegationWrapper(params);\n },\n onRootDelegationNeeded: this.signer ? async (params) => {\n graph.assertActive();\n const delegation = await this.createRootDelegationForSharing(\n params,\n () => graph.assertActive(),\n );\n graph.assertActive();\n return delegation;\n } : undefined,\n });\n const spaceService = new SpaceService({\n hosts: [input.host],\n session: input.serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n capabilityRegistry,\n userDid: input.nodeDid,\n createKVService: (spaceId) => {\n graph.assertActive();\n const scopedKv = new KVService({});\n const context = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n context.setSession({ ...input.serviceSession, spaceId });\n scopedKv.initialize(context);\n return scopedKv;\n },\n createVaultService: (spaceId) => {\n graph.assertActive();\n const scopedKv = new KVService({});\n const context = graph.track(new ServiceContext({\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n hosts: [input.host],\n telemetry: this.config.telemetry,\n }));\n context.setSession({ ...input.serviceSession, spaceId });\n scopedKv.initialize(context);\n const scopedVault = this.createVaultService(spaceId, scopedKv, encryption, {\n host: input.host,\n did: input.nodeDid,\n address: input.address,\n chainId: input.chainId,\n serviceGraph: graph,\n });\n scopedVault.initialize(context);\n return scopedVault;\n },\n createSecretsService: (spaceId) => {\n graph.assertActive();\n return this.secretsForSpace(spaceId);\n },\n createDelegation: async (params) => {\n graph.assertActive();\n try {\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 ? params.expiry.getTime() - Date.now() : undefined,\n });\n return { ok: true as const, data: {\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 } catch (error) {\n return { ok: false as const, error: {\n code: \"CREATION_FAILED\",\n message: error instanceof Error ? error.message : String(error),\n service: \"delegation\",\n }};\n }\n },\n onSpaceRegistered: async (space) => {\n graph.assertActive();\n await this.account.spaces.register(space);\n },\n });\n spaceService.updateConfig({ sharingService });\n return { core, graph, serviceContext, kv, sql, duckdb, hooks, vault, encryption, capabilityRegistry, keyProvider, sharingService, delegationManager, spaceService };\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 * Mint a multi-capability invocation through the established session key.\n * Callers receive only the signed headers; session key material remains\n * owned by the session manager and is never part of the caller contract.\n */\n invokeAny(\n entries: Parameters<InvokeAnyFunction>[1],\n facts?: Parameters<InvokeAnyFunction>[2],\n ): ReturnType<InvokeAnyFunction> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return this._serviceGraph.invokeAny(session, entries, facts);\n }\n\n /** Sign protocol bytes with the established in-memory session key. */\n async signSessionBytes(bytes: Uint8Array): Promise<Uint8Array> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return signBytesWithJwk(bytes, session.jwk);\n }\n\n /** Author a proofless Policy/v3 owner root with the authenticated holder key. */\n async createUnifiedOwnerRoot(input: UnifiedOwnerRootInput): Promise<UnifiedOwnerRootReceipt> {\n const ownerDid = this.credentialHolderDid;\n if (input.ownerDid !== ownerDid) throw new Error(\"unified owner root signer does not match owner DID\");\n const facts = {\n role: input.role,\n mode: input.role === \"policy-authority\" ? \"policy-source\" : \"conditional-mint\",\n ownerDid,\n policyId: input.policyId,\n policyDigestHex: input.policyDigestHex,\n policyCid: input.policyCid,\n contentSourceDigestHex: input.contentSourceDigestHex,\n capabilityCeilingHashHex: input.capabilityCeilingHashHex,\n nativeProjectionHashHex: input.nativeProjectionHashHex,\n nodeAudience: input.nodeAudience,\n ...(input.role === \"policy-enforcement\" ? { enforcerDid: input.audienceDid } : {}),\n };\n const root = await signCompactUcanRootAuthorization({\n issuerDid: ownerDid,\n audienceDid: input.audienceDid,\n attenuation: unifiedRootAttenuation(input.capabilities),\n facts: [facts],\n notBefore: Math.floor(input.notBefore.getTime() / 1000),\n expiresAt: Math.floor(input.expiresAt.getTime() / 1000),\n nonce: base64UrlEncode(crypto.getRandomValues(new Uint8Array(16))),\n sign: (bytes) => this.signSessionBytes(bytes),\n });\n const kv = input.capabilities.find((capability) => capability.kind === \"kv\");\n const resource = kv?.resource ?? \"\";\n const marker = resource.indexOf(\"/kv/\");\n return {\n cid: root.cid,\n delegationHeader: { Authorization: root.authorization },\n delegateDID: input.audienceDid,\n spaceId: marker === -1 ? \"\" : resource.slice(\"tinycloud://\".length, marker),\n path: marker === -1 ? resource : resource.slice(marker + 4),\n actions: kv?.actions ?? [],\n expiry: input.expiresAt,\n };\n }\n\n /** Apply only an already-enabled signing policy to the exact credential request. */\n async autoSignCredentialBytes(bytes: Uint8Array): Promise<Uint8Array | undefined> {\n const strategy = this.config.signStrategy;\n if (strategy?.type === \"auto-sign\") return this.signSessionBytes(bytes);\n if (strategy?.type !== \"callback\" || !isOpenKeyAutoSignStrategy(strategy)) return undefined;\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n const request = {\n address: this.address ?? \"\",\n chainId: this.session?.chainId ?? this._chainId,\n message: new TextDecoder().decode(bytes),\n type: \"message\" as const,\n purpose: \"message\" as const,\n };\n const decision = await strategy.handler(request);\n if (!decision.approved) {\n if (decision.needsApproval) return undefined;\n throw new Error(decision.reason ?? \"OpenKey automatic credential signing was rejected\");\n }\n if (\n typeof decision.signature !== \"string\" ||\n !(await verifyEip191MessageSignature(\n request.message,\n decision.signature,\n request.address,\n ))\n ) {\n throw new Error(\"OpenKey credential signature evidence is invalid\");\n }\n return this.signSessionBytes(bytes);\n }\n\n /** Invoke the configured interactive approval strategy before session signing. */\n async approveCredentialBytes(bytes: Uint8Array): Promise<Uint8Array> {\n const strategy = this.config.signStrategy;\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n const request = {\n address: this.address ?? \"\",\n chainId: this.session?.chainId ?? this._chainId,\n message: new TextDecoder().decode(bytes),\n type: \"message\" as const,\n purpose: \"message\" as const,\n };\n const approval = isOpenKeyAutoSignStrategy(strategy)\n ? openKeyApproval(strategy)\n : strategy?.type === \"callback\"\n ? strategy.handler\n : undefined;\n if (approval) {\n const decision = await approval(request);\n if (!decision.approved) throw new Error(decision.reason ?? \"Credential signing was rejected\");\n if (\n decision.signature !== undefined &&\n !(await verifyEip191MessageSignature(\n request.message,\n decision.signature,\n request.address,\n ))\n ) {\n throw new Error(\"OpenKey credential signature evidence is invalid\");\n }\n return this.signSessionBytes(bytes);\n }\n if (strategy?.type === \"auto-reject\") throw new Error(\"Credential signing was rejected\");\n if (this.config.signer) {\n await this.config.signer.signMessage(request.message);\n return this.signSessionBytes(bytes);\n }\n throw new Error(\"Interactive OpenKey approval is not configured\");\n }\n\n /** Bind a session-signed invocation to the canonical service audience. */\n async bindInvocationAudience(authorization: string, audience: string): Promise<string> {\n const session = this.currentTinyCloudSession() ?? this._activeServiceSession;\n if (session === undefined) throw new Error(\"Not signed in. Call signIn() first.\");\n return rewriteInvocationAudience(authorization, audience, session.jwk);\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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 ? this.config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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 sessionManager: this.sessionManager,\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 autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n localNodeUrl: this.config.localNodeUrl,\n localLinkName: this.config.localLinkName,\n expectedNodeDid: this.config.expectedNodeDid,\n localNodeIdentityStore: this.config.localNodeIdentityStore,\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 ? this.config.includeAccountRegistryPermissions === false\n ? BOOTSTRAP_DEFAULT_ONLY_SESSION_REQUEST\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(\n this._serviceGraph.invoke,\n [this.config.host!],\n this._serviceGraph.fetch,\n );\n this._serviceGraph.track(this.tc!.serviceContext as ServiceContext);\n\n // Create service context\n this._serviceContext = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceGraph.invoke,\n invokeAny: this._serviceGraph.invokeAny,\n fetch: this._serviceGraph.fetch,\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 getEncryptionNetworkIdForSpace(\n spaceId: string,\n name = DEFAULT_ENCRYPTION_NETWORK_NAME,\n ): string {\n const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? this.did;\n return `urn:tinycloud:encryption:${ownerDid}:${name}`;\n }\n\n private ownerDidFromSpaceId(spaceId: string): string | undefined {\n if (!spaceId.startsWith(\"tinycloud:\")) return undefined;\n const body = spaceId.slice(\"tinycloud:\".length);\n const lastSeparator = body.lastIndexOf(\":\");\n if (lastSeparator <= 0) return undefined;\n const owner = body.slice(0, lastSeparator);\n if (owner.startsWith(\"did:\")) return owner;\n if (!owner.includes(\":\")) return undefined;\n return `did:${owner}`;\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 /**\n * Runtime-permission helpers can be used from an authenticated Node session\n * before its public ServiceContext is initialized. They still need the\n * current signed session, never an optional or stale authority object.\n */\n private requireEncryptionSession(): ServiceSession {\n const session = this._serviceContext?.session ?? this.auth?.tinyCloudSession;\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 /**\n * The node DID for {@link config.host}.\n *\n * Sign-in already performs `GET /info` for the protocol-version check, and\n * that response carries `nodeId`, so reuse it rather than fetching `/info` a\n * second time. Only a value recorded for this exact host qualifies; older\n * nodes that omit `nodeId` fall through to the fetch.\n */\n private async fetchNodeId(): Promise<string> {\n const cached = this.auth?.nodeIdForHost(this.config.host!);\n if (cached) return cached;\n\n const response = await fetch(`${this.config.host}/info`);\n if (!response.ok) {\n throw await httpResponseError(response, \"Failed to fetch node info\");\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 }, binding?: {\n graph: ServiceGraphLifetime;\n session: ServiceSession;\n }): Promise<{ authorization: string; invocationCid: string }> {\n binding?.graph.assertActive();\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 = binding?.session ?? this.requireEncryptionSession();\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 binding?.graph.assertActive();\n return {\n authorization: audienceBound,\n invocationCid: this.wasmBindings.computeCid(\n new TextEncoder().encode(audienceBound),\n 0x55n,\n ),\n };\n }\n\n private async fetchEncryptionNetworkAt(\n host: string,\n networkId: string,\n fetchFn: FetchFunction,\n ): Promise<NetworkDescriptor | null> {\n const response = await fetchFn(\n `${host}/encryption/networks/${encodeURIComponent(networkId)}`,\n );\n if (response.status === 404) return null;\n if (!response.ok) {\n throw await httpResponseError(response, `Failed to fetch encryption network ${networkId}`);\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 private createEncryptionService(binding?: {\n graph: ServiceGraphLifetime;\n host: string;\n session: ServiceSession;\n did: string;\n address: string | undefined;\n chainId: number;\n }): EncryptionService {\n const graph = binding?.graph ?? this._serviceGraph;\n const host = binding?.host ?? this.config.host!;\n // The public service path always has a ServiceContext. Keep the auth-session\n // fallback for the internal runtime-permission helpers, which construct an\n // encryption service before a ServiceContext is installed. Both paths bind\n // the resulting service to this graph, so a later graph replacement still\n // retires the captured service permanently.\n const session = binding?.session ?? this.requireEncryptionSession();\n const did = binding?.did ?? this.did;\n const address = binding?.address ?? this._address;\n const chainId = binding?.chainId ?? this._chainId;\n const crypto = this.createEncryptionCrypto();\n // Successful descriptor lookups are immutable for a key version. Cache\n // and coalesce them for this session graph; replacing the graph replaces\n // this cache. Misses and failures remain retryable.\n const descriptorCache = new Map<string, Promise<NetworkDescriptor | null>>();\n const transport: DecryptTransport = {\n postDecrypt: async ({ networkId, authorization, canonicalBody, signal }) => {\n graph.assertActive();\n const response = await graph.fetch(\n `${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 signal,\n },\n );\n graph.assertActive();\n if (!response.ok) {\n // A decrypt denial identifies the attempted authority, not a permission\n // named by the response body, which may describe another operation.\n const permissionHint = response.status === 401 || response.status === 403\n ? parsePermissionHint({\n service: \"tinycloud.encryption\",\n path: networkId,\n actions: [\"tinycloud.encryption/decrypt\"],\n })\n : undefined;\n throw new DecryptTransportResponseError(response.status, permissionHint);\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 graph.assertActive();\n const signed = await this.signRawNetworkAuthorization({\n targetNode: input.targetNode,\n networkId: input.networkId,\n action: DECRYPT_ACTION,\n facts: input.facts,\n }, { graph, session });\n graph.assertActive();\n return {\n ...signed,\n canonicalBody: canonicalizeEncryptionJson(\n input.body as unknown as CanonicalizableEncryptionJson,\n ),\n };\n },\n },\n transport,\n node: {\n fetchByNetworkId: async (networkId) => {\n graph.assertActive();\n let pending = descriptorCache.get(networkId);\n if (!pending) {\n pending = this.fetchEncryptionNetworkAt(host, networkId, graph.fetch)\n .then((descriptor) => {\n if (descriptor === null) descriptorCache.delete(networkId);\n return descriptor;\n })\n .catch((error) => {\n descriptorCache.delete(networkId);\n throw error;\n });\n descriptorCache.set(networkId, pending);\n }\n const descriptor = await pending;\n graph.assertActive();\n return descriptor;\n },\n },\n wellKnown: {\n fetchWellKnown: async (principal, discoveryKey) => {\n graph.assertActive();\n if (!address || !didPrincipalMatches(principal, did)) {\n return null;\n }\n const publicSpaceId = makePublicSpaceId(address, chainId);\n const encodedKey = discoveryKey.split(\"/\").map(encodeURIComponent).join(\"/\");\n const response = await graph.fetch(\n `${host}/public/${encodeURIComponent(publicSpaceId)}/kv/${encodedKey}`,\n { method: \"GET\" },\n );\n graph.assertActive();\n if (!response.ok) {\n return null;\n }\n const body = await response.json() as\n | NetworkDescriptor\n | { descriptor?: NetworkDescriptor };\n graph.assertActive();\n return \"descriptor\" in body && body.descriptor\n ? body.descriptor\n : (body as NetworkDescriptor);\n },\n },\n assertActive: () => graph.assertActive(),\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(\n spaceId: string,\n kv: IKVService,\n encryptionService = this.getEncryptionService(),\n nodeContext?: {\n host: string;\n did: string;\n address: string | undefined;\n chainId: number;\n serviceGraph?: ServiceGraphLifetime;\n },\n ): DataVaultService {\n const wasm = this.wasmBindings;\n const serviceGraph = nodeContext?.serviceGraph ?? this._serviceGraph;\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 const did = nodeContext?.did ?? this.did;\n const address = nodeContext?.address ?? this._address;\n const chainId = nodeContext?.chainId ?? this._chainId;\n const host = nodeContext?.host ?? this.config.host!;\n const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? did;\n return new DataVaultService({\n spaceId,\n crypto: vaultCrypto,\n encryption: {\n networkId: `urn:tinycloud:encryption:${ownerDid}:${DEFAULT_ENCRYPTION_NETWORK_NAME}`,\n service: encryptionService,\n decryptCapabilityProof: () => ({\n proofs: [this.requireServiceSession().delegationCid],\n }),\n },\n tc: {\n kv,\n ensurePublicSpace: async () => {\n try {\n serviceGraph.assertActive();\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() {\n serviceGraph.assertActive();\n return self._publicKV ?? self.tc!.publicKV;\n },\n readPublicSpace: <T>(host: string, targetSpaceId: string, key: string) =>\n TinyCloud.readPublicSpace<T>(host, targetSpaceId, key),\n makePublicSpaceId: TinyCloud.makePublicSpaceId,\n did,\n address: address ?? \"\",\n chainId,\n hosts: [host],\n },\n });\n }\n\n /**\n * Initialize the v2 delegation system services.\n * @internal\n */\n private initializeV2Services(serviceSession: ServiceSession): void {\n const graph = this._serviceGraph;\n\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: [...ROOT_DELEGATION_ACTIONS],\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: [...ROOT_DELEGATION_ACTIONS],\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 accountSpaceId: this.accountSpaceId,\n session: serviceSession,\n invoke: graph.invoke,\n invokeAny: graph.invokeAny,\n fetch: graph.fetch,\n });\n\n // Initialize SpaceService\n this._spaceService = new SpaceService({\n hosts: [this.config.host!],\n session: serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n capabilityRegistry: this._capabilityRegistry,\n userDid: this.did,\n createKVService: (spaceId: string) => {\n graph.assertActive();\n return this.createSpaceScopedKVService(spaceId);\n },\n createVaultService: (spaceId: string) => {\n graph.assertActive();\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 createSecretsService: (spaceId: string) => {\n graph.assertActive();\n return this.secretsForSpace(spaceId);\n },\n // Enable space.delegations.create() via SIWE-based delegation\n createDelegation: async (params) => {\n try {\n graph.assertActive();\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 graph.assertActive();\n await this.account.spaces.register(space);\n },\n });\n\n // A SharingService retains its invoke/fetch functions and lifetime guard.\n // Recreate it for this graph instead of updating the receive-only instance\n // from the graph that was just retired during a subsequent sign-in.\n this._sharingService = new SharingService({\n hosts: [this.config.host!],\n session: serviceSession,\n invoke: graph.invoke,\n fetch: graph.fetch,\n assertActive: () => graph.assertActive(),\n keyProvider: this._keyProvider,\n registry: this._capabilityRegistry,\n delegationManager: this._delegationManager,\n sessionExpiry: this.getSessionExpiry(),\n createDelegationWasm: (params) => {\n graph.assertActive();\n return this.createDelegationWrapper(params);\n },\n computeCid: (data, codec) => {\n if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n return this.wasmBindings.computeCid(data, codec);\n },\n createKVService: (config) => {\n graph.assertActive();\n const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, \"\") });\n const context = graph.track(new ServiceContext({\n invoke: config.invoke,\n fetch: config.fetch ?? graph.fetch,\n hosts: config.hosts,\n telemetry: this.config.telemetry,\n }));\n context.setSession(config.session);\n service.initialize(context);\n return service;\n },\n onRootDelegationNeeded: this.signer\n ? async (params) => {\n graph.assertActive();\n const delegation = await this.createRootDelegationForSharing(\n params,\n () => graph.assertActive(),\n );\n graph.assertActive();\n return delegation;\n }\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 the SESSION tier (30 days) 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 // Session storage carries the verification method as a DID URL\n // (`did:key:...#key-id`). The Rust UCAN builder expects the principal\n // DID here and rejects the fragment as an invalid audience DID.\n verificationMethod: params.session.verificationMethod.split(\"#\", 1)[0],\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 async createOwnerDelegation(\n params: CreateOwnerDelegationParams,\n assertActive?: () => void,\n ): Promise<OwnerDelegationReceipt> {\n const assertOwnerGraphActive = assertActive ?? this._serviceGraph.assertActive.bind(this._serviceGraph);\n assertOwnerGraphActive();\n if (!params.delegateDid.startsWith(\"did:key:\")) {\n throw new Error(\"Owner delegation requires an external did:key audience and bounded capabilities\");\n }\n const permissions = ownerDelegationPermissions(params);\n const now = new Date();\n if (!(params.expiresAt instanceof Date) || params.expiresAt.getTime() <= now.getTime() || params.expiresAt.getTime() - now.getTime() > EXPIRY.MAX_MS) {\n throw new Error(\"Owner delegation expiry must be explicit, future, and within EXPIRY.MAX_MS\");\n }\n if (!this.signer) throw new Error(\"Owner wallet signer is required\");\n const session = this.currentTinyCloudSession();\n if (!session) throw new Error(\"Owner session is required\");\n const ownerDid = pkhDid(session.address, session.chainId);\n for (const permission of permissions) {\n if (\n permission.service === ENCRYPTION_PERMISSION_SERVICE\n && !principalDidEquals(parseNetworkId(permission.path).ownerDid, ownerDid)\n ) {\n throw new Error(\"Owner delegation cannot grant a foreign encryption network\");\n }\n }\n const { abilities, rawAbilities } = ownerPermissionsToAbilities(permissions);\n const primary = permissions[0]!;\n\n const host = this.config.host!;\n const prepared = this.wasmBindings.prepareSession({\n abilities,\n ...(Object.keys(rawAbilities).length === 0 ? {} : { rawAbilities }),\n address: this.wasmBindings.ensureEip55(session.address),\n chainId: session.chainId,\n domain: this.siweDomain,\n issuedAt: now.toISOString(),\n expirationTime: params.expiresAt.toISOString(),\n spaceId: params.spaceId,\n delegateUri: params.delegateDid,\n });\n const signature = await this.signer.signMessage(prepared.siwe);\n assertOwnerGraphActive();\n const delegationSession = this.wasmBindings.completeSessionSetup({ ...prepared, signature });\n const activation = await activateSessionWithHost(host, delegationSession.delegationHeader);\n assertOwnerGraphActive();\n if (!activation.success) {\n throw Object.assign(\n new Error(`Owner delegation import failed: ${activation.status} ${activation.error ?? \"\"}`.trim()),\n { cause: activation },\n );\n }\n const delegation: Delegation = {\n cid: delegationSession.delegationCid,\n delegateDID: params.delegateDid,\n delegatorDID: ownerDid,\n spaceId: params.spaceId,\n path: primary.path,\n actions: [...primary.actions],\n expiry: params.expiresAt,\n isRevoked: false,\n allowSubDelegation: true,\n createdAt: now,\n authHeader: delegationSession.delegationHeader.Authorization,\n };\n return {\n delegation,\n signedDagCbor: decodeAuthorizationBytes(delegationSession.delegationHeader.Authorization),\n delegationCid: delegationSession.delegationCid,\n permissions,\n nodeReceipt: {\n commitEventCid: (activation as typeof activation & { commitEventCid?: string }).commitEventCid,\n activated: activation.activated ?? [],\n skipped: activation.skipped ?? [],\n },\n };\n }\n\n /** Register a signed policy and sibling roots with this Node's Policy/v3 runtime. */\n async registerPolicy(\n params: Omit<RegisterPolicyV3Input, \"nodeOrigin\" | \"fetch\">,\n ): Promise<RegisterPolicyV3Receipt> {\n this._serviceGraph.assertActive();\n return registerPolicyV3({\n ...params,\n nodeOrigin: this.config.host!,\n fetch: globalThis.fetch.bind(globalThis),\n });\n }\n\n /** Authorize one short-lived v3 delivery against the signed v3 envelope and registered roots. */\n async authorizeShareDeliveryV3(input: {\n readonly envelope: Record<string, CanonicalJson | undefined>;\n /** Canonical sealed recipient envelope: version || nonce || ciphertext+tag. */\n readonly sealedEnvelope: string;\n /** Base64url 32-byte envelope key; it must also be the URL fragment key. */\n readonly envelopeKey: string;\n readonly shareCid: string;\n readonly resourcePath: string;\n readonly recipientEmail: string;\n readonly shareUrl: string;\n readonly documentName: string;\n readonly expiresAt: string;\n readonly deliveryAudience: string;\n /** Stable caller retry identity. It is hashed into the protocol's 16-byte JTI. */\n readonly idempotencyKey: string;\n }): Promise<ShareDeliveryAuthorizationV3Receipt> {\n const session = this.currentTinyCloudSession();\n const serviceSession = this._serviceContext?.session;\n if (!session || !serviceSession) throw new Error(\"Share delivery requires an authenticated session\");\n const idempotencyBytes = new TextEncoder().encode(input.idempotencyKey);\n if (idempotencyBytes.byteLength === 0 || idempotencyBytes.byteLength > 512) {\n throw new Error(\"Share delivery idempotency key is invalid\");\n }\n // Node and OpenCredentials deduplicate on the signed 16-byte JTI/nonce.\n // Never send the caller's opaque retry key over the wire: it can contain\n // application identifiers and has no protocol meaning beyond this binding.\n const jtiDigest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", idempotencyBytes));\n const body = {\n envelope: input.envelope,\n sealedEnvelope: input.sealedEnvelope,\n envelopeKey: input.envelopeKey,\n shareCid: input.shareCid,\n recipientEmail: input.recipientEmail,\n shareUrl: input.shareUrl,\n documentName: input.documentName,\n jti: base64UrlEncode(jtiDigest.slice(0, 16)),\n expiresAt: new Date(input.expiresAt).toISOString().replace(/\\.\\d{3}Z$/, \"Z\"),\n };\n const requestBodyDigest = base64UrlEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(canonicalizeEncryptionJson(body)))));\n const request = { ...body, requestBodyDigest };\n const authorization = authorizationHeader(this.invokeAnyWithRuntimePermissions(serviceSession, [{ spaceId: session.spaceId, service: \"kv\", path: input.resourcePath, action: \"tinycloud.kv/get\" }]));\n const response = await fetch(`${this.config.host!}/policy/v3/deliveries/authorize`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\", authorization },\n body: canonicalizeEncryptionJson(request),\n });\n if (!response.ok) throw await httpResponseError(response, \"V3 share delivery authorization failed\");\n const verified = validateShareDeliveryAuthorizationV3Bytes(new Uint8Array(await response.arrayBuffer()), {\n request,\n senderKeyDid: this.credentialHolderDid,\n deliveryAudience: input.deliveryAudience,\n });\n const requestDigest = new Uint8Array(await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`${CREDENTIAL_INVITATION_REQUEST_DOMAIN}${canonicalizeEncryptionJson(verified.request as any)}`),\n ));\n return {\n ...verified,\n proof: {\n alg: \"EdDSA\",\n kid: this.credentialHolderDid,\n signature: base64UrlEncode(await this.signSessionBytes(requestDigest)),\n },\n };\n }\n\n private async createRootDelegationForSharing(params: {\n shareKeyDID: string;\n spaceId: string;\n path: string;\n actions: string[];\n requestedExpiry: Date;\n }, assertActive?: () => void): Promise<Delegation | undefined> {\n try {\n return (await this.createOwnerDelegation({\n delegateDid: params.shareKeyDID,\n spaceId: params.spaceId,\n path: params.path,\n actions: params.actions,\n expiresAt: params.requestedExpiry,\n }, assertActive)).delegation;\n } catch {\n assertActive?.();\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceContext.invoke,\n invokeAny: this._serviceContext.invokeAny,\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 return this.fetchEncryptionNetworkAt(\n this.config.host!,\n networkId,\n globalThis.fetch.bind(globalThis),\n );\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 // `NetworkAlreadyExists` is the only error this route maps to Conflict\n // (`NetworkNotActive`, the other Conflict in the shared error mapper, is\n // reachable only from the decrypt routes). So a 409 means the network is\n // already there — which is exactly the post-condition `create` promises.\n // Read it back rather than failing an otherwise-successful ensure.\n if (response.status === 409) {\n const existing = await this.getEncryptionNetwork(networkId);\n if (existing) return existing;\n throw new Error(\n `Encryption network ${networkId} already exists but could not be read back`,\n );\n }\n if (!response.ok) {\n throw await httpResponseError(response, `Failed to create encryption network ${networkId}`);\n }\n const created = (await response.json()) as { descriptor: NetworkDescriptor };\n return created.descriptor;\n }\n\n /**\n * Ensure an encryption network exists, creating it if necessary.\n *\n * @param nameOrNetworkId - Network name or full `urn:tinycloud:encryption:` id.\n * @param options - See {@link EnsureEncryptionNetworkOptions}.\n */\n async ensureEncryptionNetwork(\n nameOrNetworkId = DEFAULT_ENCRYPTION_NETWORK_NAME,\n options: EnsureEncryptionNetworkOptions = {},\n ): Promise<NetworkDescriptor> {\n const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n ? nameOrNetworkId\n : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n // The existence probe is worth a round trip only when the network is\n // likely to be there. On a freshly bootstrapped account it always 404s,\n // so callers that know the account is new skip straight to the create —\n // which is itself safe to race, since 409 is handled above.\n if (!options.assumeMissing) {\n const existing = await this.getEncryptionNetwork(networkId);\n if (existing) {\n return existing;\n }\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 return this.secretsForSpace(\"secrets\");\n }\n\n /**\n * App-facing secrets API backed by the requested space's vault.\n */\n secretsForSpace(spaceId: string): ISecretsService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let secrets = this._secrets.get(resolvedSpace);\n if (!secrets) {\n secrets = new NodeSecretsService({\n getService: () => this.getBaseSecrets(resolvedSpace),\n space: resolvedSpace,\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.getEncryptionNetworkIdForSpace(resolvedSpace),\n resolveSpace: (space) => space.startsWith(\"tinycloud:\") ? space : this.ownedSpaceId(space),\n getUnlockSigner: () => this.signer ?? undefined,\n });\n this._secrets.set(resolvedSpace, secrets);\n }\n return secrets;\n }\n\n /**\n * Read a secret from an explicit target space without requesting or\n * auto-signing authority. Active runtime delegations are selected by the\n * normal KV and encryption invocation paths.\n */\n async readSecret(input: SecretReadInput): Promise<SecretReadResult> {\n const resolved = resolveSecretPath(input.name, { scope: input.scope });\n const targetSpace = input.space.startsWith(\"tinycloud:\")\n ? input.space\n : this.ownedSpaceId(input.space);\n const result = await this.getBaseVault(targetSpace).readNetworkEncrypted<unknown>(\n resolved.vaultKey,\n );\n\n if (result.status !== \"ok\") {\n if (result.status === \"permission_required\") {\n const hint = parsePermissionHint(result.hint);\n if (hint === undefined) return { status: \"read_failed\" };\n return {\n status: \"permission_required\",\n hint: {\n service: hint.service,\n ...(hint.space === undefined ? {} : { space: hint.space }),\n path: hint.path,\n actions: [...hint.actions],\n },\n };\n }\n return { status: result.status };\n }\n if (!isSecretPayload(result.entry.value)) {\n return { status: \"invalid_payload\" };\n }\n return { status: \"ok\", value: result.entry.value.value };\n }\n\n private getBaseSecrets(spaceId: string): ISecretsService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let secrets = this._baseSecrets.get(resolvedSpace);\n if (!secrets) {\n secrets = new SecretsService(() => this.getBaseVault(resolvedSpace));\n this._baseSecrets.set(resolvedSpace, secrets);\n }\n return secrets;\n }\n\n private getBaseVault(spaceId: string): DataVaultService {\n if (!this._spaceService) {\n throw new Error(\"Not signed in. Call signIn() first.\");\n }\n const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n ? spaceId\n : this.ownedSpaceId(spaceId);\n let vault = this._baseVaults.get(resolvedSpace);\n if (!vault) {\n vault = this.createVaultService(\n resolvedSpace,\n this.createSpaceScopedKVService(resolvedSpace),\n );\n if (this._serviceContext) {\n vault.initialize(this._serviceContext);\n }\n this._baseVaults.set(resolvedSpace, vault);\n }\n return vault;\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 // Exclude the synthetic primary grant: it represents the base session's\n // own recap, not an installed runtime delegation. Per this method's\n // contract, base-session manifest permissions are not represented here.\n return this.runtimePermissionGrants\n .filter((grant) => grant.provenance !== \"primary\")\n .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 * Return the effective capabilities of installed runtime grants.\n *\n * The result is projected from the SDK's activated, expiry-pruned grant\n * operations rather than from PortableDelegation transport metadata. Base\n * session authority is intentionally omitted; callers that need the full\n * live authority must combine this with {@link getVerifiedSessionCapabilities}.\n */\n getEffectiveRuntimePermissionEntries(): PermissionEntry[] {\n const session = this.currentTinyCloudSession();\n if (!session) return [];\n\n this.pruneExpiredRuntimePermissionGrants();\n const grouped = new Map<string, PermissionEntry>();\n for (const grant of this.runtimePermissionGrants) {\n if (grant.provenance === \"primary\") continue;\n for (const operation of grant.operations) {\n const service = SERVICE_SHORT_TO_LONG[operation.service];\n if (service === undefined || typeof operation.path !== \"string\" ||\n typeof operation.action !== \"string\") {\n continue;\n }\n\n let space: string | undefined;\n if (service !== \"tinycloud.encryption\" || operation.resource === undefined) {\n if (typeof operation.spaceId !== \"string\") continue;\n try {\n space = this.resolvePermissionSpace(operation.spaceId, session);\n } catch {\n continue;\n }\n }\n\n const caveats = operation.caveats === undefined || operation.caveats.length === 0\n ? undefined\n : cloneRecapCaveats(operation.caveats);\n const identity = JSON.stringify({\n service,\n ...(space === undefined ? {} : { space }),\n path: operation.path,\n caveats: canonicalizeRecapCaveats(caveats),\n });\n const existing = grouped.get(identity);\n if (existing === undefined) {\n grouped.set(identity, {\n service,\n ...(space === undefined ? {} : { space }),\n path: operation.path,\n actions: [operation.action],\n ...(caveats === undefined ? {} : { caveats }),\n });\n continue;\n }\n if (!existing.actions.includes(operation.action)) {\n existing.actions.push(operation.action);\n existing.actions.sort();\n }\n }\n }\n\n return [...grouped.values()].sort((left, right) =>\n left.service.localeCompare(right.service) ||\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")),\n );\n }\n\n /**\n * Verify a wallet-signed session grant (a CACAO built from a SIWE and its\n * EIP-191 signature) issued to this instance's live session key. The\n * verifier rebuilds the CACAO from `siwe` and `signature`, so the grant is\n * accepted only when its authorization bytes and CID are exactly that CACAO,\n * its signer is `address`, its audience is this session key, it is valid\n * now, and its ReCap covers `spaceId` or names only raw encryption networks\n * (a decrypt-only grant has no space). Returns the signed ReCap and expiry.\n * Bindings without `validateSessionGrant` fall back to the session verifier,\n * which also refuses decrypt-only grants.\n */\n verifySessionGrant(grant: SessionGrantProof): VerifiedSessionGrant {\n const bindings = this.wasmBindings;\n const validate = typeof bindings.validateSessionGrant === \"function\"\n ? bindings.validateSessionGrant.bind(bindings)\n : bindings.validatePersistedSession?.bind(bindings);\n if (validate === undefined) {\n throw new UnsupportedSessionRestoreError(\"it cannot verify persisted SIWE authority\");\n }\n const verified = validate({\n delegationHeader: { Authorization: grant.delegationHeader.Authorization },\n delegationCid: grant.delegationCid,\n spaceId: grant.spaceId,\n jwk: this.sessionKeyJwk,\n address: canonicalizeAddress(grant.address),\n chainId: grant.chainId,\n siwe: grant.siwe,\n signature: grant.signature,\n });\n if (typeof verified.expiresAt !== \"string\") {\n throw new Error(\"Session grant has no signed expiry.\");\n }\n const expiresAt = new Date(verified.expiresAt);\n if (!Number.isFinite(expiresAt.getTime())) {\n throw new Error(\"Session grant has an invalid signed expiry.\");\n }\n return { recap: exactVerifiedRecap(verified), expiresAt };\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 if (\n this.operationsFromDelegation(delegation).some((operation) =>\n operation.resource?.startsWith(\"urn:cid:\") === true &&\n operation.service === \"delegation\" &&\n operation.action === \"tinycloud.delegation/revoke\"\n ) &&\n activateResult.status === 401 &&\n /Cannot find parent delegation/i.test(activateResult.error ?? \"\")\n ) {\n throw Object.assign(\n new Error(\"The host cannot activate a root raw-CID revoke authority without a parent delegation.\"),\n { code: \"RAW_RECAP_RESOURCE_UNSUPPORTED\", cause: activateResult },\n );\n }\n throw Object.assign(\n new Error(`Failed to activate runtime permission delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\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 this.assertDelegationCaveatsPreservable(expanded);\n\n const rawEntries = expanded.filter((entry) =>\n this.isEncryptionPermissionEntry(entry) || this.isRawRevocationPermissionEntry(entry)\n );\n const spaceEntries = expanded.filter((entry) =>\n !this.isEncryptionPermissionEntry(entry) && !this.isRawRevocationPermissionEntry(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 = (() => {\n try {\n return 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 } catch (error) {\n if (\n rawForDelegation.some((entry) => this.isRawRevocationPermissionEntry(entry)) &&\n /invalid ReCap resource URI/i.test(error instanceof Error ? error.message : String(error))\n ) {\n throw Object.assign(\n new Error(\"This WASM build cannot encode raw urn:cid ReCap resources.\"),\n { code: \"RAW_RECAP_RESOURCE_UNSUPPORTED\", cause: error },\n );\n }\n throw error;\n }\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 if (\n rawForDelegation.some((entry) => this.isRawRevocationPermissionEntry(entry)) &&\n activateResult.status === 401 &&\n /Cannot find parent delegation/i.test(activateResult.error ?? \"\")\n ) {\n throw Object.assign(\n new Error(\"The host cannot activate a root raw-CID revoke authority without a parent delegation.\"),\n { code: \"RAW_RECAP_RESOURCE_UNSUPPORTED\", cause: activateResult },\n );\n }\n throw Object.assign(\n new Error(`Failed to activate runtime permission delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n const delegation = this.runtimeDelegationFromSession(\n delegatedSession,\n delegatedEntries,\n spaceId,\n session,\n expiresAt,\n { siwe: prepared.siwe, signature },\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 provenance: \"runtime\",\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 = [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA];\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 Object.assign(\n new Error(`Failed to activate public space delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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 = this._serviceGraph.track(new ServiceContext({\n invoke: this._serviceGraph.invoke,\n fetch: this._serviceGraph.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<DelegationRevocationReceipt>> {\n return this.delegationManager.revoke(cid);\n }\n\n /** Read node-confirmed lifecycle state for one delegation. */\n async getDelegationStatus(cid: string): Promise<DelegationResult<DelegationStatus>> {\n return this.delegationManager.status(cid);\n }\n\n /** Compute the canonical CID of a compact UCAN or DAG-CBOR delegation authorization. */\n computeDelegationCid(authorization: string): string {\n if (!authorization || !this.wasmBindings.computeCid) {\n throw new Error(\"Delegation CID computation is unavailable\");\n }\n const compact = authorization.replace(/^Bearer /i, \"\");\n return this.wasmBindings.computeCid(\n compact.includes(\".\")\n ? new TextEncoder().encode(compact)\n : decodeAuthorizationBytes(authorization),\n 0x55n,\n );\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 * @throws when `onPrepared` is combined with `forceWalletSign: true`,\n * before anything is signed.\n * @throws the `onPrepared` rejection, unchanged, without activating the\n * delegation.\n */\n async delegateTo(\n did: string,\n permissions: PermissionEntry[],\n options?: DelegateToOptions,\n ): Promise<DelegateToResult> {\n // 0. `onPrepared` needs a seam between signing and activation; the\n // legacy wallet path signs and activates in one step, so reject the\n // combination before any signing work.\n const onPrepared = options?.onPrepared;\n if (onPrepared && options?.forceWalletSign) {\n throw new Error(\n \"delegateTo: onPrepared cannot be combined with forceWalletSign=true; \" +\n \"the wallet-signed path activates the delegation before it could be \" +\n \"handed to onPrepared.\",\n );\n }\n\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\n // (DEFAULT_DELEGATION_EXPIRY_MS); ms-format (\"7d\") or a raw\n // millisecond count are both accepted. Cap at the session's own\n // expiry so we never emit a UCAN whose validity exceeds the parent\n // chain, which makes the default the longest the session allows.\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 this.assertDelegationCaveatsPreservable(expandedEntries);\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 = this.projectSignedRecapCapabilities(session.siwe);\n const { subset, missing } = this.signedCapabilitySubset(expandedEntries, granted);\n\n if (!subset) {\n // This branch only runs when the session recap is NOT a superset of the\n // requested entries. The synthetic primary grant is built from that same\n // recap, so it should never cover an entry the recap itself doesn't —\n // but `operationCovers` is strictly more permissive than\n // `isCapabilitySubset` (action `/*` and path `/*`/`/**` wildcards), so a\n // wildcard-bearing recap could slip through and mint a delegation with\n // the primary session's spaceId (the wrong-space class). Exclude the\n // primary explicitly; failure then degrades to\n // PermissionNotInManifestError instead of a wrong-space delegation.\n const runtimeOperations = this.permissionEntriesToOperations(expandedEntries, session);\n const runtimeGrant = this.findGrantForOperations(\n runtimeOperations,\n { excludePrimary: true },\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 runtimeOperations,\n onPrepared,\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 onPrepared,\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 onPrepared?: DelegateToOptions[\"onPrepared\"],\n ): Promise<PortableDelegation> {\n if (entries.length === 0) {\n throw new Error(\n \"createDelegationViaWasmPath requires a non-empty entries array\",\n );\n }\n this.assertDelegationCaveatsPreservable(entries);\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 const delegation: PortableDelegation = {\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 // Hand the caller the exact object we return before it goes live, so a\n // lost activation response can't leave an unrecorded active grant.\n if (onPrepared) {\n await onPrepared(delegation);\n }\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 Object.assign(\n new Error(`Failed to activate delegation with host: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n return delegation;\n }\n\n private async createDelegationViaRuntimeGrant(\n did: string,\n entries: PermissionEntry[],\n expirationTime: Date,\n grant: RuntimePermissionGrant,\n requestedOperations: RuntimePermissionOperation[],\n onPrepared?: DelegateToOptions[\"onPrepared\"],\n ): Promise<PortableDelegation> {\n this.assertRuntimeGrantCaveatsPreservable(entries, requestedOperations, grant);\n this.assertDelegationCaveatsPreservable(entries);\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 delegation: PortableDelegation = {\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 if (onPrepared) {\n await onPrepared(delegation);\n }\n\n const activateResult = await activateSessionWithHost(\n targetHost,\n delegationHeader,\n );\n if (!activateResult.success) {\n throw Object.assign(\n new Error(`Failed to activate delegation with host: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n return delegation;\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 /**\n * The current WASM child-delegation APIs accept action-only maps. Refuse any\n * constrained branch rather than signing a broader action-only child UCAN.\n */\n private assertDelegationCaveatsPreservable(entries: PermissionEntry[]): void {\n const caveated = entries.filter((entry) =>\n !recapCaveatsEqual(entry.caveats, undefined)\n );\n if (caveated.length > 0) {\n throw new CaveatedDelegationUnsupportedError(caveated);\n }\n }\n\n /**\n * Runtime grant selection intentionally allows an uncaveated operation to\n * select a caveated grant so invocation can restore the signed caveat before\n * crossing the caveat-aware WASM boundary. Child delegation cannot do that:\n * it only accepts action maps, so reject the selected constrained branch.\n */\n private assertRuntimeGrantCaveatsPreservable(\n entries: PermissionEntry[],\n requestedOperations: RuntimePermissionOperation[],\n grant: RuntimePermissionGrant,\n ): void {\n let operationIndex = 0;\n const caveated: PermissionEntry[] = [];\n for (const entry of entries) {\n for (const action of entry.actions) {\n const requested = requestedOperations[operationIndex++];\n if (!requested) continue;\n const constrained = grant.operations.find((granted) =>\n this.operationCovers(granted, requested) &&\n !recapCaveatsEqual(granted.caveats, undefined),\n );\n if (constrained) {\n caveated.push({\n ...entry,\n actions: [action],\n caveats: cloneRecapCaveats(constrained.caveats),\n });\n }\n }\n }\n if (caveated.length > 0) {\n throw new CaveatedDelegationUnsupportedError(caveated);\n }\n }\n\n /** Reject caveated parent branches before action-only child signing. */\n private assertPortableDelegationCaveatsPreservable(\n delegation: PortableDelegation,\n ): void {\n const entries: PermissionEntry[] = [];\n const add = (\n service: string,\n space: string,\n path: string,\n actions: string[],\n caveats: readonly Record<string, unknown>[] | undefined,\n ): void => {\n if (recapCaveatsEqual(caveats, undefined)) return;\n entries.push({\n service: service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`,\n space,\n path,\n actions: [...actions],\n caveats: cloneRecapCaveats(caveats),\n });\n };\n\n add(\n delegation.actions[0]?.split(\"/\", 1)[0] ?? \"tinycloud.unknown\",\n delegation.spaceId,\n delegation.path,\n delegation.actions,\n delegation.caveats,\n );\n for (const resource of delegation.resources ?? []) {\n add(resource.service, resource.space, resource.path, resource.actions, resource.caveats);\n }\n if (entries.length > 0) {\n throw new CaveatedDelegationUnsupportedError(entries);\n }\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 if (this.isRawRevocationPermissionEntry(entry)) continue;\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 this.isEncryptionNetworkOperation(\"encryption\", entry.path, entry.space);\n }\n private isRawRevocationPermissionEntry(entry: PermissionEntry): boolean {\n return entry.service === \"tinycloud.delegation\" &&\n entry.path === \"\" &&\n entry.space?.startsWith(\"urn:cid:\") === true &&\n entry.actions.includes(\"tinycloud.delegation/revoke\");\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.isRawRevocationPermissionEntry(entry)) {\n rawAbilities[entry.space!] = [...new Set(entry.actions)];\n continue;\n }\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.isRawRevocationPermissionEntry(entry)\n ? { resource: entry.space }\n : this.isEncryptionNetworkOperation(service, entry.path, entry.space)\n ? { resource: entry.path }\n : { spaceId }),\n service,\n path: entry.path,\n action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n }));\n });\n }\n\n /** Raw network authority cannot be covered by a nested encryption space. */\n private signedCapabilitySubset(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n ): { subset: boolean; missing: PermissionEntry[] } {\n const rawGranted = granted\n .filter((entry) => this.isEncryptionPermissionEntry(entry) || this.isRawRevocationPermissionEntry(entry))\n .map((entry) => this.isEncryptionPermissionEntry(entry) ? { ...entry, space: \"encryption\" } : entry);\n const spaceGranted = granted.filter((entry) =>\n !this.isEncryptionPermissionEntry(entry) && !this.isRawRevocationPermissionEntry(entry)\n );\n const missing = requested.filter((entry) => {\n const raw = this.isEncryptionPermissionEntry(entry) || this.isRawRevocationPermissionEntry(entry);\n const comparable = raw && this.isEncryptionPermissionEntry(entry)\n ? { ...entry, space: \"encryption\" }\n : entry;\n return !isCapabilitySubset([comparable], raw ? rawGranted : spaceGranted).subset;\n });\n return { subset: missing.length === 0, missing };\n }\n\n private sessionCoversPermissionEntries(\n session: TinyCloudSession,\n entries: PermissionEntry[],\n ): boolean {\n try {\n const granted = this.projectSignedRecapCapabilities(session.siwe);\n return this.signedCapabilitySubset(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 rawRevocation = this.isRawRevocationPermissionEntry(entry);\n const spaceId = rawRevocation ? undefined : this.resolvePermissionSpace(entry.space, session);\n const service = this.shortServiceName(entry.service);\n return entry.actions.map((action) => ({\n ...(rawRevocation\n ? { resource: entry.space }\n : this.isEncryptionNetworkOperation(service, entry.path, entry.space)\n ? { resource: entry.path }\n : { spaceId }),\n service,\n path: entry.path,\n action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 // Public surface: never surface the synthetic primary grant. It exists\n // only to win runtime invocation selection; the base session's own recap\n // is not an installed runtime delegation, so excluding it keeps the\n // `getRuntimePermissionDelegations` contract (base-session manifest\n // permissions are not represented here) airtight.\n const grant = this.findGrantForOperation(operation, { excludePrimary: true });\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 siweProof: { siwe: string; signature: string },\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 siweProof,\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 provenance: \"delegated\",\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 provenance: \"delegated\",\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.isRawRevocationPermissionEntry(entry)\n ? entry.space!\n : this.isEncryptionPermissionEntry(entry) ? \"encryption\" : spaceId,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 const rawRevocation = service === \"delegation\" &&\n resource.space.startsWith(\"urn:cid:\") &&\n resource.path === \"\";\n return resource.actions.map((action) => ({\n ...(rawRevocation\n ? { resource: resource.space }\n : this.isEncryptionNetworkOperation(service, resource.path, resource.space)\n ? { resource: resource.path }\n : { spaceId: resource.space }),\n service,\n path: resource.path,\n action,\n caveats: cloneRecapCaveats(resource.caveats),\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 ...(delegation.caveats === undefined ? {} : { caveats: cloneRecapCaveats(delegation.caveats) }),\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, resource.space)) {\n rawAbilities[resource.path] ??= [];\n addActions(rawAbilities[resource.path], resource.actions);\n continue;\n }\n if (service === \"delegation\" && resource.space.startsWith(\"urn:cid:\") && resource.path === \"\") {\n rawAbilities[resource.space] ??= [];\n addActions(rawAbilities[resource.space], 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 if (!grant) {\n return fallback;\n }\n // \"Primary wins\" means the caller's own session already authorizes the op:\n // use the PASSED session, not the stored primary `ServiceSession`. The stored\n // primary carries the primary space's `spaceId`, but a multi-space recap can\n // cover scoped ops on OTHER spaces whose fallback session carries the correct\n // target `spaceId`. Returning `grant.session` there would mint the invocation\n // against the wrong space (TC-111 follow-up). Non-primary grants keep their\n // own session.\n return grant.provenance === \"primary\" ? fallback : grant.session;\n }\n\n private findGrantForOperations(\n operations: RuntimePermissionOperation[],\n options?: { excludePrimary?: boolean },\n ): RuntimePermissionGrant | undefined {\n if (operations.length === 0) {\n return undefined;\n }\n this.pruneExpiredRuntimePermissionGrants();\n const covering = this.runtimePermissionGrants.filter((grant) => {\n if (options?.excludePrimary && grant.provenance === \"primary\") {\n return false;\n }\n return operations.every((operation) =>\n grant.operations.some((granted) =>\n this.operationCovers(granted, operation),\n ),\n );\n });\n if (covering.length === 0) {\n return undefined;\n }\n // Provenance ranking: the synthetic primary grant (the base session's own\n // recap) always wins when it covers every op, so a broad bootstrap or\n // delegated grant can never hijack an operation the primary session itself\n // authorizes (TC-111). Otherwise fall back to insertion order — the same\n // semantics as the previous `.find`.\n return covering.find((grant) => grant.provenance === \"primary\") ?? covering[0];\n }\n\n private findGrantForOperation(\n operation: RuntimePermissionOperation,\n options?: { excludePrimary?: boolean },\n ): RuntimePermissionGrant | undefined {\n return this.findGrantForOperations([operation], options);\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 // A caller that already carries a caveat can only be covered by the exact\n // same signed attenuation. An uncaveated request is decorated with the\n // grant's caveat immediately before WASM signs it.\n if (requested.caveats !== undefined &&\n !recapCaveatsEqual(granted.caveats, requested.caveats)\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>`. Compare\n // only the embedded EIP-155 address without case sensitivity; chain, name,\n // and all non-PKH space identifiers remain byte-exact.\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 const match = /^(tinycloud:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.+)$/.exec(space);\n return match === null ? space : `${match[1]}${match[2]!.toLowerCase()}${match[3]}`;\n }\n\n private actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) {\n return true;\n }\n // `tinycloud.kv/sync` and `tinycloud.kv/retain` must be granted by name;\n // a `tinycloud.kv/*` runtime grant does not cover them (TC-732).\n if (isExplicitOnlyAction(requestedAction)) {\n return false;\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 /** Prefer the v2 caveat-preserving parser while retaining old custom WASM. */\n private parseRecapWithCaveats(siwe: string): WasmRecapEntry[] {\n const verified = this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe);\n return verified == null\n ? this.wasmBindings.parseRecapFromSiwe(siwe)\n : verifierRecapEntries(verified);\n }\n\n private isEncryptionNetworkOperation(service: string, path: string, space?: string): boolean {\n return service === \"encryption\" &&\n (space === undefined || space === \"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 caveats?: Record<string, unknown>[];\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 ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n };\n }\n if (entry.spaceId === undefined && this.isEncryptionNetworkOperation(service, entry.path)) {\n return {\n resource: entry.path,\n service,\n path: entry.path,\n action: entry.action,\n ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\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 Object.assign(\n new Error(`Failed to activate delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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: { \"\": [KV.GET, KV.PUT, 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: [KV.GET, KV.PUT, 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 // The activated session lasts as long as the delegation it is proven by.\n const expirationTime = delegation.expiry;\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 Object.assign(\n new Error(`Failed to activate delegated session: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\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 in milliseconds from now; defaults to the parent's own expiry, the longest allowed. */\n expiryMs?: number;\n /** Explicit multi-resource projection, including encryption networks. */\n resources?: Array<{\n service: string;\n space?: string;\n path: string;\n actions: string[];\n }>;\n }\n ): Promise<PortableDelegation> {\n this.assertPortableDelegationCaveatsPreservable(parentDelegation);\n\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 const parentResources = parentDelegation.resources ?? [{\n service: parentDelegation.actions[0]?.split(\"/\", 1)[0]?.replace(/^tinycloud\\./, \"\") ?? \"kv\",\n space: parentDelegation.spaceId,\n path: parentDelegation.path,\n actions: parentDelegation.actions,\n }];\n const requestedResources = params.resources ?? [{\n service: params.actions[0]?.split(\"/\", 1)[0]?.replace(/^tinycloud\\./, \"\") ?? \"kv\",\n space: parentDelegation.spaceId,\n path: params.path,\n actions: params.actions,\n }];\n const resourceIsContained = (parent: typeof parentResources[number], child: typeof requestedResources[number]): boolean => {\n const parentEncryption = parent.service === \"encryption\" || parent.service === \"tinycloud.encryption\";\n const childEncryption = child.service === \"encryption\" || child.service === \"tinycloud.encryption\";\n if (parentEncryption || childEncryption) return parentEncryption && childEncryption && parent.path === child.path && child.actions.every((action) => parent.actions.includes(action));\n const pathContained = parent.path === child.path || parent.path.endsWith(\"/\") && child.path.startsWith(parent.path) || child.path.startsWith(`${parent.path}/`);\n return pathContained && child.actions.every((action) => parent.actions.includes(action));\n };\n if (requestedResources.length === 0 || requestedResources.some((child) => !parentResources.some((parent) => resourceIsContained(parent, child)))) {\n throw new Error(\n \"Sub-delegation resources exceed the received delegation\"\n );\n }\n\n // Default to the longest a sub-delegation may last: its parent's expiry.\n const now = new Date();\n const requestedExpiry = params.expiryMs === undefined\n ? parentDelegation.expiry\n : new Date(now.getTime() + params.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 rawAbilities: Record<string, string[]> = {};\n for (const resource of requestedResources) {\n const service = resource.service.replace(/^tinycloud\\./, \"\");\n if (service === \"encryption\") {\n rawAbilities[resource.path] = [...resource.actions];\n continue;\n }\n abilities[service] ??= {};\n abilities[service][resource.path] = [...resource.actions];\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 ...(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 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 Object.assign(\n new Error(`Failed to activate sub-delegation: ${describeHostFailure(activateResult)}`),\n { cause: activateResult },\n );\n }\n\n // Return the portable sub-delegation\n return {\n cid: subDelegationSession.delegationCid,\n delegationHeader: subDelegationSession.delegationHeader,\n spaceId: parentDelegation.spaceId,\n path: requestedResources[0]!.path,\n actions: requestedResources[0]!.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 resources: requestedResources.map((resource) => ({\n service: resource.service.replace(/^tinycloud\\./, \"\"),\n space: resource.service.replace(/^tinycloud\\./, \"\") === \"encryption\"\n ? \"encryption\"\n : resource.space ?? parentDelegation.spaceId,\n path: resource.path,\n actions: [...resource.actions],\n })),\n };\n }\n}\n","export { AccountService } from \"@tinycloud/sdk-core\";\nexport type {\n AccountApplication,\n AccountApplicationListOptions,\n AccountApplicationRegisterOptions,\n AccountDelegation,\n AccountDelegationListOptions,\n AccountDelegationRevokeOptions,\n AccountIndexEnsureResult,\n AccountIndexRebuildResult,\n AccountIndexStatus,\n AccountIndexedReadOptions,\n AccountServiceConfig,\n AccountSpace,\n AccountSpaceListOptions,\n AccountStatus,\n RegisterBatchSuccess,\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 * (30 days, the SESSION tier).\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(\n action: SecretAction,\n): \"get\" | \"put\" | \"del\" | \"list\" {\n return action;\n}\n\nfunction secretPermissionEntries(\n name: string,\n options: SecretScopeOptions | undefined,\n action: SecretAction,\n space: string,\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,\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\nfunction normalizeSpace(\n space: string | undefined,\n resolveSpace?: (space: string) => string,\n): string | undefined {\n if (!space) return undefined;\n if (space.startsWith(\"tinycloud:\")) return space;\n return resolveSpace?.(space) ?? space;\n}\n\nfunction spaceMatches(\n granted: string | undefined,\n requested: string | undefined,\n resolveSpace?: (space: string) => string,\n): boolean {\n if (!granted || !requested) return false;\n return (\n normalizeSpace(granted, resolveSpace) ===\n normalizeSpace(requested, resolveSpace)\n );\n}\n\nexport interface NodeSecretsServiceConfig {\n getService: () => ISecretsService;\n space?: string;\n getManifest: () => Manifest | Manifest[] | undefined;\n hasPermissions?: (permissions: PermissionEntry[]) => boolean;\n grantPermissions: (additional: PermissionEntry[]) => Promise<unknown>;\n canEscalate: () => boolean;\n getEncryptionNetworkId?: () => string;\n resolveSpace?: (space: string) => 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 private get space(): string {\n return this.config.space ?? SECRETS_SPACE;\n }\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(\n name: string,\n options?: SecretScopeOptions,\n ): 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(\n options?: SecretScopeOptions,\n ): 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 async listAll(): ReturnType<ISecretsService[\"listAll\"]> {\n const permission = await this.ensurePermission(\"\", undefined, \"list\");\n if (!permission.ok) return permission;\n return this.service.listAll();\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 this.space,\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(permissionEntries: PermissionEntry[]): 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 spaceMatches(\n resource.space,\n entry.space,\n this.config.resolveSpace,\n ) &&\n resource.path === entry.path &&\n entry.actions.every((action) => resource.actions.includes(action)),\n );\n }),\n );\n }\n}\n","import {\n canonicalizeRecapCaveats,\n decodeBase64Url,\n Delegation,\n DelegatedResource,\n PermissionEntry,\n principalDidEquals,\n} 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 * The wallet-signed SIWE message and EIP-191 signature behind a\n * `delegationHeader` that is a CACAO session grant (OpenKey `/delegate`,\n * {@link TinyCloudNode.grantRuntimePermissions}) rather than a compact UCAN.\n * Not authority: activation rebuilds the CACAO from them and accepts only\n * byte-identical authorization bytes.\n */\n siweProof?: { siwe: string; signature: string };\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 * Authority that the validated runtime-delegation activation helper needs.\n * `TinyCloudNode` implements this surface directly; keeping it structural\n * makes the helper usable by a compatible Node wrapper without exposing node\n * internals.\n */\nexport interface RuntimeDelegationActivator {\n readonly sessionDid: string;\n readonly did?: string;\n readonly isSessionOnly?: boolean;\n computeDelegationCid(authorization: string): string;\n useRuntimeDelegation(delegation: PortableDelegation): Promise<void>;\n useDelegation?(delegation: PortableDelegation): Promise<unknown>;\n getRuntimePermissionDelegations(): PortableDelegation[];\n /**\n * Verify a wallet-signed session grant issued to this runtime's live session\n * key. Required to activate a CACAO grant; compact UCANs do not use it.\n */\n verifySessionGrant?(grant: SessionGrantProof): VerifiedSessionGrant;\n}\n\n/** The installed authority returned by {@link activateValidatedRuntimeDelegation}. */\nexport interface ValidatedRuntimeDelegation {\n /** CID recomputed from the signed authorization bytes. */\n readonly cid: string;\n /** The authority object installed by the node runtime. */\n readonly delegation: PortableDelegation;\n /** Capabilities read from the signed compact UCAN attenuation. */\n readonly effectivePermissions: readonly PermissionEntry[];\n /** Expiry read from the signed compact UCAN payload. */\n readonly expiry: Date;\n /** Audience read from the signed compact UCAN payload. */\n readonly audience: string;\n /** Host selected for, and used by, the runtime activation. */\n readonly host: string;\n}\n\nexport interface CompactRuntimeDelegationInput {\n readonly authorization: string;\n readonly cid: string;\n readonly host: string;\n readonly ownerAddress: string;\n readonly chainId: number;\n}\n\n/** A CACAO session grant and the signed SIWE proof it was built from. */\nexport interface SessionGrantProof {\n readonly delegationHeader: { Authorization: string };\n readonly delegationCid: string;\n readonly spaceId: string;\n readonly address: string;\n readonly chainId: number;\n readonly siwe: string;\n readonly signature: string;\n}\n\n/** Authority read from a verified session grant's signed ReCap. */\nexport interface VerifiedSessionGrant {\n readonly recap: readonly {\n service: string;\n space: string;\n path: string;\n actions: string[];\n caveats?: Record<string, unknown>[];\n }[];\n readonly expiresAt: Date;\n}\n\n/**\n * Stable reasons {@link activateValidatedRuntimeDelegation} refuses a\n * delegation for. The error message is for the caller and may quote\n * transport fields or a node's response; the reason is safe to publish.\n */\nexport const RUNTIME_DELEGATION_REJECTIONS = [\n \"host_mismatch\",\n \"expired\",\n \"cid_mismatch\",\n \"authority_invalid\",\n \"proof_missing\",\n \"proof_invalid\",\n \"owner_mismatch\",\n \"audience_mismatch\",\n \"resources_mismatch\",\n \"unsupported\",\n \"activation_rejected\",\n] as const;\n\nexport type RuntimeDelegationRejection = typeof RUNTIME_DELEGATION_REJECTIONS[number];\n\nexport class RuntimeDelegationRejectedError extends Error {\n readonly reason: RuntimeDelegationRejection;\n\n constructor(reason: RuntimeDelegationRejection, message: string) {\n super(message);\n this.name = \"RuntimeDelegationRejectedError\";\n this.reason = reason;\n }\n}\n\nfunction reject(reason: RuntimeDelegationRejection, message: string): never {\n throw new RuntimeDelegationRejectedError(reason, message);\n}\n\ninterface SignedRuntimeAuthority {\n readonly issuer: string;\n readonly audience: string;\n readonly expiry: Date;\n readonly proofs: readonly string[];\n readonly remainingRedelegationDepth?: number;\n readonly permissions: readonly PermissionEntry[];\n readonly resources: readonly DelegatedResource[];\n}\n\nconst SERVICE_BY_SHORT_NAME: Record<string, string> = {\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n hooks: \"tinycloud.hooks\",\n};\n\nfunction authorizationWithoutBearer(authorization: string): string {\n return authorization.replace(/^Bearer /i, \"\");\n}\n\nfunction normalizedHost(host: string): string {\n if (typeof host !== \"string\" || host.length === 0) {\n throw new Error(\"Validated runtime delegation requires a non-empty host.\");\n }\n return host.replace(/\\/+$/, \"\");\n}\n\nfunction didPrincipalsMatch(left: string, right: string): boolean {\n try {\n return principalDidEquals(left, right);\n } catch {\n return left === right;\n }\n}\n\nfunction compactUcanPayload(authorization: string): Record<string, unknown> {\n const compact = authorizationWithoutBearer(authorization);\n const parts = compact.split(\".\");\n if (parts.length !== 3 || parts.some((part) => part.length === 0)) {\n throw new Error(\n \"Validated runtime delegation requires a compact UCAN authorization so its signed authority can be derived.\",\n );\n }\n try {\n const payload = JSON.parse(\n new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(parts[1]!)),\n ) as unknown;\n if (payload === null || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new Error(\"payload is not an object\");\n }\n return payload as Record<string, unknown>;\n } catch {\n throw new Error(\n \"Validated runtime delegation authorization has an invalid compact UCAN payload.\",\n );\n }\n}\n\nfunction canonicalPermissionEntries(\n permissions: PermissionEntry[],\n): PermissionEntry[] {\n return permissions\n .map((permission) => ({\n ...permission,\n actions: [...permission.actions].sort(),\n }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n );\n}\n\nfunction signedCaveats(value: unknown): Record<string, unknown>[] | undefined {\n if (!Array.isArray(value) || value.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n )) {\n throw new Error(\"Validated runtime delegation has malformed signed ReCap caveats.\");\n }\n const cloned = JSON.parse(JSON.stringify(value)) as Record<string, unknown>[];\n return canonicalizeRecapCaveats(cloned) === canonicalizeRecapCaveats(undefined)\n ? undefined\n : cloned;\n}\n\nfunction groupedSignedEntries(\n service: string,\n space: string | undefined,\n path: string,\n abilities: Record<string, unknown>,\n): PermissionEntry[] {\n const groups = new Map<string, { actions: string[]; caveats?: Record<string, unknown>[] }>();\n for (const [action, rawCaveats] of Object.entries(abilities)) {\n const caveats = signedCaveats(rawCaveats);\n const identity = canonicalizeRecapCaveats(caveats);\n const group = groups.get(identity) ?? { actions: [], caveats };\n group.actions.push(action);\n groups.set(identity, group);\n }\n return [...groups.values()].map((group) => ({\n service,\n ...(space === undefined ? {} : { space }),\n path,\n actions: group.actions.sort(),\n ...(group.caveats === undefined ? {} : { caveats: group.caveats }),\n }));\n}\n\nfunction signedAuthorityFromCompactUcan(\n authorization: string,\n): SignedRuntimeAuthority {\n const payload = compactUcanPayload(authorization);\n if (typeof payload.aud !== \"string\" || payload.aud.length === 0) {\n throw new Error(\"Validated runtime delegation is missing a signed audience.\");\n }\n if (typeof payload.iss !== \"string\" || payload.iss.length === 0) {\n throw new Error(\"Validated runtime delegation is missing a signed issuer.\");\n }\n if (!Array.isArray(payload.prf) || payload.prf.some((proof) =>\n typeof proof !== \"string\" || proof.length === 0\n )) {\n throw new Error(\"Validated runtime delegation has malformed signed proofs.\");\n }\n if (typeof payload.exp !== \"number\" || !Number.isFinite(payload.exp)) {\n throw new Error(\"Validated runtime delegation is missing a signed expiry.\");\n }\n const expiry = new Date(payload.exp * 1000);\n if (Number.isNaN(expiry.getTime())) {\n throw new Error(\"Validated runtime delegation has an invalid signed expiry.\");\n }\n if (payload.att === null || typeof payload.att !== \"object\" || Array.isArray(payload.att)) {\n throw new Error(\"Validated runtime delegation is missing a signed attenuation.\");\n }\n const fact = Array.isArray(payload.fct) && payload.fct.length > 0 &&\n payload.fct[0] !== null && typeof payload.fct[0] === \"object\" &&\n !Array.isArray(payload.fct[0])\n ? payload.fct[0] as Record<string, unknown>\n : undefined;\n const remainingRedelegationDepth = fact?.remainingRedelegationDepth;\n if (\n remainingRedelegationDepth !== undefined &&\n (!Number.isInteger(remainingRedelegationDepth) ||\n (remainingRedelegationDepth as number) < 0 ||\n (remainingRedelegationDepth as number) > 8)\n ) {\n throw new Error(\"Validated runtime delegation has invalid signed redelegation depth.\");\n }\n\n const permissions: PermissionEntry[] = [];\n for (const [resource, abilities] of Object.entries(payload.att)) {\n if (abilities === null || typeof abilities !== \"object\" || Array.isArray(abilities)) {\n throw new Error(\"Validated runtime delegation has an invalid signed attenuation.\");\n }\n const abilityEntries = Object.entries(abilities as Record<string, unknown>);\n if (abilityEntries.length === 0) {\n throw new Error(\"Validated runtime delegation has an empty signed capability.\");\n }\n\n if (resource.startsWith(\"urn:tinycloud:encryption:\")) {\n permissions.push(...groupedSignedEntries(\n \"tinycloud.encryption\",\n undefined,\n resource,\n abilities as Record<string, unknown>,\n ));\n continue;\n }\n\n const nativeMatch = /^(tinycloud:[^/]+)\\/(kv|sql|duckdb|hooks)\\/(.*)$/.exec(resource);\n const policyMatch = /^tinycloud:\\/\\/([^/]+)\\/(kv|sql|duckdb|hooks)\\/(.*)$/.exec(resource);\n const match = nativeMatch ?? policyMatch;\n if (!match) {\n throw new Error(\n `Validated runtime delegation has an unsupported signed resource '${resource}'.`,\n );\n }\n const [, space, shortService, path] = match;\n const service = SERVICE_BY_SHORT_NAME[shortService!];\n if (service === undefined) {\n throw new Error(\n `Validated runtime delegation has an unsupported signed service '${shortService}'.`,\n );\n }\n permissions.push(...groupedSignedEntries(\n service,\n space!,\n path!,\n abilities as Record<string, unknown>,\n ));\n }\n\n return canonicalSignedAuthority({\n issuer: payload.iss,\n audience: payload.aud,\n expiry,\n proofs: [...payload.prf],\n ...(remainingRedelegationDepth === undefined\n ? {}\n : { remainingRedelegationDepth: remainingRedelegationDepth as number }),\n }, permissions);\n}\n\nfunction canonicalSignedAuthority(\n signed: Omit<SignedRuntimeAuthority, \"permissions\" | \"resources\">,\n permissions: PermissionEntry[],\n): SignedRuntimeAuthority {\n if (permissions.length === 0) {\n throw new Error(\"Validated runtime delegation has no signed capabilities.\");\n }\n const canonicalPermissions = canonicalPermissionEntries(permissions);\n const canonicalResources = canonicalPermissions.map((permission) => ({\n service:\n permission.service === \"tinycloud.encryption\"\n ? \"encryption\"\n : permission.service.slice(\"tinycloud.\".length),\n space:\n permission.service === \"tinycloud.encryption\"\n ? \"encryption\"\n : permission.space!,\n path: permission.path,\n actions: [...permission.actions],\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n }));\n return { ...signed, permissions: canonicalPermissions, resources: canonicalResources };\n}\n\nconst RAW_ENCRYPTION_PREFIX = \"urn:tinycloud:encryption:\";\nconst PKH_SPACE = /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):(.+)$/;\n\n/** A space id with its owner address lowercased, so EIP-55 casing never decides a match. */\nfunction comparableSpace(space: string): string {\n const match = PKH_SPACE.exec(space);\n return match ? `tinycloud:pkh:eip155:${match[1]}:${match[2]!.toLowerCase()}:${match[3]}` : space;\n}\n\n/**\n * Authority of a CACAO session grant: the wallet-signed SIWE is rebuilt into\n * the exact CACAO and verified against this runtime's live session key, so\n * the signer (owner), audience, lifetime, space and ReCap all come from\n * signed bytes. The grant must be signed by the session's own owner, stay in\n * one owner space, and name only raw networks that owner holds.\n */\nfunction signedAuthorityFromSessionGrant(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n authorization: string,\n cid: string,\n): SignedRuntimeAuthority {\n const proof = delegation.siweProof;\n if (\n proof === undefined || proof === null || typeof proof !== \"object\" ||\n typeof proof.siwe !== \"string\" || typeof proof.signature !== \"string\"\n ) {\n reject(\n \"proof_missing\",\n \"Runtime delegation is a wallet-signed session grant stored without its signed SIWE proof, so its authority cannot be verified.\",\n );\n }\n if (typeof node.verifySessionGrant !== \"function\") {\n reject(\"unsupported\", \"This runtime cannot verify wallet-signed session grants.\");\n }\n const owner = `did:pkh:eip155:${delegation.chainId}:${delegation.ownerAddress}`;\n if (typeof node.did !== \"string\" || !didPrincipalsMatch(owner, node.did)) {\n reject(\"owner_mismatch\", \"Runtime delegation is not signed by this session's owner.\");\n }\n let verified: VerifiedSessionGrant;\n try {\n verified = node.verifySessionGrant({\n delegationHeader: { Authorization: authorization },\n delegationCid: cid,\n spaceId: delegation.spaceId,\n address: delegation.ownerAddress,\n chainId: delegation.chainId,\n siwe: proof.siwe,\n signature: proof.signature,\n });\n } catch (error) {\n reject(\"proof_invalid\", error instanceof Error ? error.message : String(error));\n }\n\n const space = comparableSpace(delegation.spaceId);\n const spaceOwner = PKH_SPACE.exec(delegation.spaceId);\n if (!spaceOwner || !didPrincipalsMatch(`did:pkh:eip155:${spaceOwner[1]}:${spaceOwner[2]}`, owner)) {\n reject(\"authority_invalid\", \"Runtime delegation space is not owned by its signer.\");\n }\n const groups = new Map<string, PermissionEntry>();\n for (const entry of verified.recap) {\n const service = entry.service.startsWith(\"tinycloud.\") ? entry.service : `tinycloud.${entry.service}`;\n const raw = entry.space === \"encryption\";\n if (raw) {\n if (service !== \"tinycloud.encryption\" || !entry.path.startsWith(RAW_ENCRYPTION_PREFIX)) {\n reject(\"authority_invalid\", \"Runtime delegation has an unsupported signed raw resource.\");\n }\n const networkOwner = entry.path.slice(RAW_ENCRYPTION_PREFIX.length, entry.path.lastIndexOf(\":\"));\n if (!didPrincipalsMatch(networkOwner, owner)) {\n reject(\"authority_invalid\", \"Runtime delegation names an encryption network its signer does not own.\");\n }\n } else if (service === \"tinycloud.encryption\" || comparableSpace(entry.space) !== space) {\n // Decrypt signed inside a space (older OpenKey) is not a usable network\n // grant, and one grant covers one space.\n reject(\"authority_invalid\", \"Runtime delegation has signed authority outside its space.\");\n }\n const caveats = signedCaveats(entry.caveats ?? []);\n const key = JSON.stringify([service, raw ? \"\" : entry.space, entry.path, canonicalizeRecapCaveats(caveats)]);\n const group = groups.get(key) ?? {\n service,\n ...(raw ? {} : { space: entry.space }),\n path: entry.path,\n actions: [],\n ...(caveats === undefined ? {} : { caveats }),\n };\n for (const action of entry.actions) {\n if (!group.actions.includes(action)) group.actions.push(action);\n }\n groups.set(key, group);\n }\n return canonicalSignedAuthority({\n issuer: owner,\n // The verifier bound the SIWE audience to this runtime's own session key.\n audience: node.sessionDid,\n expiry: verified.expiresAt,\n proofs: [],\n }, [...groups.values()]);\n}\n\nfunction canonicalResourcesFromPortableDelegation(\n delegation: PortableDelegation,\n): DelegatedResource[] {\n if (delegation.resources !== undefined && delegation.resources.length > 0) {\n return delegation.resources\n .map((resource) => ({ ...resource, actions: [...resource.actions].sort() }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n left.space.localeCompare(right.space) ||\n left.path.localeCompare(right.path) ||\n left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n );\n }\n const byService = new Map<string, string[]>();\n for (const action of delegation.actions) {\n const [service] = action.split(\"/\", 1);\n const shortService = service!.replace(/^tinycloud\\./, \"\");\n const values = byService.get(shortService) ?? [];\n values.push(action);\n byService.set(shortService, values);\n }\n return [...byService.entries()]\n .map(([service, actions]) => ({\n service,\n space: service === \"encryption\" ? \"encryption\" : delegation.spaceId,\n path: delegation.path,\n actions: [...new Set(actions)].sort(),\n ...(delegation.caveats === undefined ? {} : { caveats: delegation.caveats }),\n }))\n .sort((left, right) =>\n left.service.localeCompare(right.service) ||\n left.space.localeCompare(right.space) ||\n left.path.localeCompare(right.path),\n );\n}\n\nfunction resourcesMatch(\n actual: readonly DelegatedResource[],\n expected: readonly DelegatedResource[],\n): boolean {\n const comparable = (resource: DelegatedResource) => ({\n ...resource,\n caveats: canonicalizeRecapCaveats(resource.caveats),\n });\n return JSON.stringify(actual.map(comparable)) === JSON.stringify(expected.map(comparable));\n}\n\n/**\n * CID-bind and activate one runtime delegation.\n *\n * A compact UCAN's audience, expiry and permissions come from its signed\n * payload, and its transport fields must agree with them. A CACAO session\n * grant (OpenKey `/delegate`, `grantRuntimePermissions`) is verified from its\n * `siweProof` against this runtime's live session key; its installed\n * authority is exactly the verified ReCap, and its transport `resources` are\n * display data that is never consulted. Either way the helper then invokes\n * {@link TinyCloudNode.useRuntimeDelegation}; the node activation call remains\n * the authority and delegation-chain validation boundary.\n *\n * `options.authorize`, when given, sees the signed capabilities before\n * anything is activated or installed; returning `false` refuses the\n * delegation.\n */\nexport async function activateValidatedRuntimeDelegation(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n options: {\n host: string;\n authorize?: (effectivePermissions: readonly PermissionEntry[]) => boolean;\n },\n): Promise<ValidatedRuntimeDelegation> {\n const host = normalizedHost(options.host);\n if (delegation.host !== undefined && normalizedHost(delegation.host) !== host) {\n reject(\n \"host_mismatch\",\n `Runtime delegation host '${delegation.host}' does not match expected host '${options.host}'.`,\n );\n }\n if (!(delegation.expiry instanceof Date) || Number.isNaN(delegation.expiry.getTime())) {\n reject(\"authority_invalid\", \"Runtime delegation has an invalid expiry.\");\n }\n if (delegation.expiry.getTime() <= Date.now()) {\n reject(\"expired\", \"Runtime delegation is expired.\");\n }\n\n const authorization = delegation.delegationHeader?.Authorization;\n if (typeof authorization !== \"string\" || authorization.length === 0) {\n reject(\"authority_invalid\", \"Runtime delegation is missing authorization bytes.\");\n }\n const cid = node.computeDelegationCid(authorization);\n if (cid !== delegation.cid) {\n reject(\"cid_mismatch\", \"Runtime delegation CID does not match authorization bytes.\");\n }\n\n const compact = authorizationWithoutBearer(authorization).split(\".\").length === 3;\n let signed: SignedRuntimeAuthority;\n try {\n signed = compact\n ? signedAuthorityFromCompactUcan(authorization)\n : signedAuthorityFromSessionGrant(node, delegation, authorization, cid);\n } catch (error) {\n if (error instanceof RuntimeDelegationRejectedError) throw error;\n reject(\"authority_invalid\", error instanceof Error ? error.message : String(error));\n }\n if (signed.expiry.getTime() <= Date.now()) {\n reject(\"expired\", \"Runtime delegation is expired.\");\n }\n if (delegation.expiry.getTime() !== signed.expiry.getTime()) {\n reject(\"authority_invalid\", \"Runtime delegation expiry does not match signed authority.\");\n }\n if (!didPrincipalsMatch(signed.audience, node.sessionDid)) {\n reject(\n \"audience_mismatch\",\n `Runtime delegation targets ${signed.audience} but this session is ${node.sessionDid}.`,\n );\n }\n if (!didPrincipalsMatch(delegation.delegateDID, signed.audience)) {\n reject(\"audience_mismatch\", \"Runtime delegation audience does not match signed authority.\");\n }\n\n if (compact && !resourcesMatch(canonicalResourcesFromPortableDelegation(delegation), signed.resources)) {\n reject(\"resources_mismatch\", \"Runtime delegation resources do not match signed authority.\");\n }\n if (options.authorize !== undefined && !options.authorize(signed.permissions)) {\n throw new Error(\"Runtime delegation is not authorized for this runtime.\");\n }\n const previouslyInstalled = node\n .getRuntimePermissionDelegations()\n .find((candidate) => candidate.cid === cid);\n if (\n previouslyInstalled !== undefined &&\n previouslyInstalled.delegationHeader.Authorization !== authorization\n ) {\n reject(\n \"cid_mismatch\",\n \"A different authorization is already installed for this runtime delegation CID.\",\n );\n }\n const primary = signed.resources[0]!;\n const signedSpace = signed.permissions.find(\n (permission) => permission.service !== \"tinycloud.encryption\",\n )?.space;\n const installedCandidate: PortableDelegation = {\n cid,\n delegationHeader: { Authorization: authorization },\n ownerAddress: delegation.ownerAddress,\n chainId: delegation.chainId,\n delegatorDID: signed.issuer,\n ...(signed.proofs.length === 1 ? { parentCid: signed.proofs[0] } : {}),\n ...(signed.remainingRedelegationDepth === undefined\n ? {}\n : {\n allowSubDelegation: signed.remainingRedelegationDepth > 0,\n disableSubDelegation: signed.remainingRedelegationDepth === 0,\n }),\n authHeader: authorization,\n spaceId: signedSpace ?? delegation.spaceId,\n path: primary.path,\n actions: [...primary.actions],\n ...(primary.caveats === undefined ? {} : { caveats: primary.caveats }),\n resources: signed.resources.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n expiry: new Date(signed.expiry),\n delegateDID: signed.audience,\n host,\n ...(compact ? {} : { siweProof: delegation.siweProof }),\n };\n\n try {\n if (\n node.isSessionOnly === true &&\n typeof node.did === \"string\" &&\n principalDidEquals(node.did, node.sessionDid) &&\n typeof node.useDelegation === \"function\"\n ) {\n await node.useDelegation(installedCandidate);\n } else {\n await node.useRuntimeDelegation(installedCandidate);\n }\n } catch (error) {\n reject(\"activation_rejected\", error instanceof Error ? error.message : String(error));\n }\n const installed = node\n .getRuntimePermissionDelegations()\n .find((candidate) => candidate.cid === cid);\n if (!installed) {\n reject(\"activation_rejected\", \"Runtime delegation activation did not install the validated authority.\");\n }\n if (\n installed.delegationHeader.Authorization !== authorization ||\n !didPrincipalsMatch(installed.delegateDID, signed.audience) ||\n installed.expiry.getTime() !== signed.expiry.getTime() ||\n !resourcesMatch(\n canonicalResourcesFromPortableDelegation(installed),\n signed.resources,\n ) ||\n normalizedHost(installed.host ?? \"\") !== host\n ) {\n reject(\n \"activation_rejected\",\n \"Runtime delegation activation installed authority that differs from the validated authority.\",\n );\n }\n\n return {\n cid,\n delegation: installed,\n effectivePermissions: signed.permissions,\n expiry: new Date(signed.expiry),\n audience: signed.audience,\n host: normalizedHost(installed.host ?? host),\n };\n}\n\n/**\n * Import compact UCAN bytes returned by an authority ceremony through the\n * ordinary runtime-delegation activation path. All transport projections are\n * derived from signed bytes before `/delegate` is called.\n */\nexport async function activateCompactRuntimeDelegation(\n node: RuntimeDelegationActivator,\n input: CompactRuntimeDelegationInput,\n): Promise<ValidatedRuntimeDelegation> {\n const authorization = input.authorization;\n const cid = node.computeDelegationCid(authorization);\n if (cid !== input.cid) {\n throw new Error(\"Compact runtime delegation CID does not match authorization bytes.\");\n }\n const signed = signedAuthorityFromCompactUcan(authorization);\n const primary = signed.resources[0]!;\n const signedSpace = signed.permissions.find(\n (permission) => permission.service !== \"tinycloud.encryption\",\n )?.space;\n const delegation: PortableDelegation = {\n cid,\n delegationHeader: { Authorization: authorization },\n ownerAddress: input.ownerAddress,\n chainId: input.chainId,\n delegatorDID: signed.issuer,\n authHeader: authorization,\n spaceId: signedSpace ?? primary.space,\n path: primary.path,\n actions: [...primary.actions],\n ...(primary.caveats === undefined ? {} : { caveats: primary.caveats }),\n resources: signed.resources.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n expiry: new Date(signed.expiry),\n delegateDID: signed.audience,\n host: normalizedHost(input.host),\n };\n return activateValidatedRuntimeDelegation(node, delegation, {\n host: input.host,\n });\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":";AAgBA,SAAS,aAAAA,kBAAiB;AA+B1B;AAAA,EACE,6BAAAC;AAAA,EACA,mCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;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,EA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AAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,OACK;AAcP;AAAA,EACE;AAAA,EACA;AAAA,EACA,2BAAAC;AAAA,EACA,iBAAAC;AAAA,OACK;AAGP,SAAS,kBAAAC,uBAAsB;","names":["TinyCloud","SilentNotificationHandler","AutoApproveSpaceCreationHandler","canonicalizeAddress","makePkhSpaceId","pkhDid","principalDidEquals","primarySpaceId","spaceAbilities","reject","activateSessionWithHost","KVService","SQLService","DuckDbService","HooksService","ServiceContext","ACCOUNT_REGISTRY_SPACE","SECRETS_SPACE","ErrorCodes","ENCRYPTION_PERMISSION_SERVICE","KV","SQL","DUCKDB","ENCRYPTION","EXPIRY","canonicalizeAddress","pkhDid","resolveTinyCloudHosts","principalDidEquals","parseNetworkId","resolveSecretPath","SiweMessage","EXPIRY","NETWORK_CREATE_ACTION","ENCRYPTION","DECRYPT_ACTION","KV","SQL","DUCKDB","EXPIRY","didPrincipalMatches","principalDidEquals","describeHostFailure","ENCRYPTION_PERMISSION_SERVICE","parseNetworkId","grant","config","KVService","ServiceContext","pkhDid","ACCOUNT_REGISTRY_SPACE","canonicalizeAddress","SECRETS_SPACE","ErrorCodes","activateSessionWithHost","actions","SQLService","DuckDbService","HooksService","resolveTinyCloudHosts","crypto","descriptor","host","resolveSecretPath","now","delegation","spaceId","session","ACCOUNT_REGISTRY_SPACE","DEFAULT_MANIFEST_SPACE","CaveatedDelegationUnsupportedError","PermissionNotInManifestError","SessionExpiredError","composeManifestRequest","resolveManifest","isCapabilitySubset","expandPermissionEntries","parseExpiry","resourceCapabilitiesToSpaceAbilitiesMap","canonicalizeRecapCaveats","principalDidEquals","principalDidEquals","canonicalizeRecapCaveats","KVService","SQLService","DuckDbService","DataVaultService","createVaultCrypto","SecretsService","resolveSecretListPrefix","resolveSecretPath","DelegationManager","SharingService","CapabilityKeyRegistry","SpaceService","makePublicSpaceId","UnsupportedFeatureError","checkNodeInfo","ServiceContext"]}
|