@tinycloud/sdk-core 2.11.0-beta.0 → 2.11.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -2,8 +2,8 @@ import { z } from 'zod';
2
2
  import { InvokeFunction, InvokeAnyFunction, ParsedNetworkId, ServiceError, Result, FetchFunction, ServiceConstructor, RetryPolicy, TelemetryConfig, IServiceContext, IService, IKVService, ISQLService, IDuckDbService, IHooksService, IDataVaultService, IEncryptionService, ISecretsService, ServiceSession, IDatabaseHandle, SqlValue, QueryResponse } from '@tinycloud/sdk-services';
3
3
  export { BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CanonicalDecryptRequest, CanonicalJson, ColumnInfo, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, DecryptTransportResponseError, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ErrorCode, ErrorCodes, ExecuteOptions, ExecuteResponse, FetchFunction, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IEncryptionService, IHooksService, IKVService, IPrefixedKVService, ISQLService, ISecretsService, IService, IServiceContext, InlineEncryptedEnvelope, InvokeAnyEntry, InvokeAnyFunction, InvokeFunction, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVDeleteOptions, KVGetOptions, KVHeadOptions, KVListOptions, KVListResponse, KVPutOptions, KVResponse, KVResponseHeaders, KVService, KVServiceConfig, KVSignedReadUrlResponse, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, ParsedNetworkId, PrefixedKVService, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiverKeyPair, ReceiverKeySigner, ResolvedSecretPath, Result, RetryPolicy, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceError, ServiceSession, SignedReceiverKeyInput, SqlStatement, SqlValue, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, canonicalHashHex, canonicalSignedResponse, canonicalizeEncryptionJson, canonicalizeSecretScope, checkDecryptInvocationInput, clearTinyCloudDebugLogs, createVaultCrypto, decryptEnvelopeWithKey, defaultRetryPolicy, deriveSignedReceiverKey, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, base64Decode as encryptionBase64Decode, base64Encode as encryptionBase64Encode, encryptionError, utf8Decode as encryptionUtf8Decode, utf8Encode as encryptionUtf8Encode, ensureNetworkUsableForDecrypt, err, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isNetworkId, networkDiscoveryKey, ok, openWrappedKey, parseNetworkId, resolveSecretListPrefix, resolveSecretPath, serviceError, tinyCloudDebugLogger, validateEnvelope, verifyDecryptResponse } from '@tinycloud/sdk-services';
4
4
  export { HOLDER_KEY_BINDING_PRESENTATION_SCHEMA, HolderKeyBindingPresentation, LISTEN_SQL_STATEMENT_CATALOG, ListenSqlStatementName, POLICY_ENGINE_CHALLENGE_REQUEST_SCHEMA, POLICY_ENGINE_CHALLENGE_RESPONSE_SCHEMA, POLICY_ENGINE_DENIAL_SCHEMA, POLICY_ENGINE_GRANT_PRESENTATION_DENIAL_CODES, POLICY_ENGINE_RESOLVE_REQUEST_SCHEMA, PORTABLE_DELEGATION_SCHEMA, PolicyEngineGrantPresentationDenialCode, PortableDelegation, REQUESTER_ENGINE_RETRY_ATTEMPTS, REQUESTER_ENGINE_RETRY_MAX_DELAY_MS, REQUESTER_NEAR_EXPIRY_SECONDS, RequesterEndpointResolution, RequesterHttpRequest, RequesterHttpResponse, RequesterInvocationCapability, RequesterSigningCapability, RequesterTransport, TranscriptRequester, TranscriptRequesterError, TranscriptRequesterErrorCode, TranscriptRequesterErrorState, TranscriptRequesterOptions, TranscriptRequesterReadKvResult, TranscriptRequesterReadSqlResult, createTranscriptRequester, deriveDelegationCid, parseNodeNativePortableDelegation } from './requester/index.cjs';
5
- import { m as Delegation, e as CreateDelegationParams, G as GenerateShareParams, az as ShareLink, b8 as SpaceInfo, I as ICapabilityKeyRegistry, y as ISharingService, D as DelegationManager, b as AccountDelegationQueryOptions, A as AccountDelegationPage, w as DelegationRevocationReceipt } from './recipient-types.schema-B2wH53_t.cjs';
6
- export { c as AccountDelegationRecord, d as AccountDelegationResource, C as CapabilityEntry, bH as CapabilityKeyRegistry, bI as CapabilityKeyRegistryErrorCode, bJ as CapabilityKeyRegistryErrorCodes, f as CreateDelegationWasmParams, g as CreateDelegationWasmResult, h as CreateOwnerDelegationParams, i as DelegateReceivedShareParams, j as DelegatedResource, k as DelegatedShareAccess, l as DelegatedShareKey, n as DelegationApiResponse, o as DelegationChain, p as DelegationChainV2, q as DelegationDirection, a as DelegationError, r as DelegationErrorCode, s as DelegationErrorCodes, t as DelegationFilters, u as DelegationManagerConfig, v as DelegationRecord, R as DelegationResult, x as DelegationStatus, E as EncodedShareData, z as IngestOptions, J as JWK, K as KeyInfo, B as KeyProvider, F as KeyType, M as MAX_CONTENT_BYTES, H as MAX_SEALED_SHARE_CONTENT_BYTES, L as MAX_SHARE_ARTIFACT_BYTES, N as MAX_SHARE_CONTENT_BYTES, O as MemorySenderShareKeyStorage, P as MemorySenderShareRecordStorage, Q as MemoryShareCache, S as OwnerDelegationReceipt, T as OwnerShareAction, U as OwnerShareMatcher, V as OwnerSharePolicyRegistration, W as OwnerSharePolicyRegistrationReceipt, X as OwnerSharePolicyV2, Y as ReceiveOptions, Z as RegisterOwnerSharePolicyParams, _ as SHARE_DELIVERY_AUTHORIZATION_DOMAIN, $ as SenderShareKeyStorage, a0 as SenderShareRecord, a1 as SenderShareRecordStorage, a2 as SenderShareRevocationScope, a3 as SenderShareStore, a4 as ShareAccess, a5 as ShareAccessError, a6 as ShareAccessV2, a7 as ShareAction, a9 as ShareAddressedDelegationEnvelopeV2, aa as ShareAddressedDelegationEnvelopeV2Schema, ab as ShareAddressedDelegationRequestV2, ac as ShareAddressedDelegationRequestV2Schema, ad as ShareAddressedDelegationResponseV2, ae as ShareAddressedDelegationResponseV2Schema, af as ShareAddressedRecipientMatcher, ag as ShareArtifactInput, ah as ShareArtifactResult, ai as ShareArtifactV2, aj as ShareCache, ak as ShareCacheEntry, al as ShareCacheKey, am as ShareCacheMetadata, an as ShareCapabilityLike, ao as ShareConflict, ap as ShareContentMetadata, aq as ShareContentSource, ar as ShareDeliveryAuthorization, as as ShareDeliveryAuthorizationReceipt, at as ShareDeliveryAuthorizationRequest, au as ShareDetachedProof, av as ShareEnvelopeError, aw as ShareEnvelopeV2, ax as ShareExpiryBounds, ay as ShareKvContentSource, aA as ShareLinkData, aB as ShareLinkLocation, aC as ShareListEntry, aD as ShareListResult, aE as ShareNativeAction, aF as ShareNativeInvokeEnvelopeV1, aG as ShareNativeInvokeErrorResult, aH as ShareNativeInvokeInput, aI as ShareNativeInvokeResult, aJ as ShareNativeInvokeSuccessResult, aK as ShareNativeResponse, aL as ShareNativeResponseSchema, aM as SharePolicy, aN as SharePolicyBinding, aO as SharePolicySession, aP as SharePolicySessionV1, aQ as SharePolicySessionWireV1, aR as ShareReadInvocationV1, aS as ShareReadResult, aT as ShareRecipientClient, aU as ShareRecipientClientOptions, aW as ShareRecipientPolicy, aY as ShareRecipientResult, aZ as ShareRecipientTarget, a$ as ShareResource, b1 as ShareSaveOptions, b2 as ShareSchema, b3 as ShareSqlContentSource, b4 as ShareWireAction, b5 as SharingService, b6 as SharingServiceConfig, b7 as SignedDelegation, b9 as SpaceOwnership, bK as StoredDelegationChain, ba as ValidateShareDeliveryAuthorizationExpected, bb as VerifyShareEnvelopeOptions, bc as canonicalOwnerSharePolicy, bd as computeOwnerShareRegistrationCid, be as computeShareCid, bL as createCapabilityKeyRegistry, bf as createDelegatedShareKey, bg as createPolicyEnforcementDelegation, bh as createShareArtifact, bi as createShareArtifactAsync, bj as createSharePolicy, bk as createSharingService, bl as decryptShareBytesAsync, bm as encodeInlineShareUrl, bn as encodeShareArtifact, bo as encodeShareUrl, bp as encryptShareBytes, bq as encryptShareBytesAsync, br as intersectShareCapabilities, bs as isV2ShareLink, bt as normalizeShareActions, bu as normalizeShareRecipientTarget, bv as normalizeShareResource, bw as parseShareArtifact, bx as parseShareUrl, by as restoreDelegatedShareKey, bz as shareCapabilityAllows, bA as shareDeliveryTrustedKid, bB as signShareEnvelope, bC as validateOwnerSharePolicyRegistration, bD as validateOwnerSharePolicyRegistrationBytes, bE as validateShareDeliveryAuthorizationBytes, bF as verifyShareCid, bG as verifyShareEnvelope } from './recipient-types.schema-B2wH53_t.cjs';
5
+ import { m as Delegation, e as CreateDelegationParams, G as GenerateShareParams, aB as ShareLink, ba as SpaceInfo, I as ICapabilityKeyRegistry, y as ISharingService, D as DelegationManager, b as AccountDelegationQueryOptions, A as AccountDelegationPage, w as DelegationRevocationReceipt } from './recipient-types.schema-CWIt63Qp.cjs';
6
+ export { c as AccountDelegationRecord, d as AccountDelegationResource, C as CapabilityEntry, bJ as CapabilityKeyRegistry, bK as CapabilityKeyRegistryErrorCode, bL as CapabilityKeyRegistryErrorCodes, f as CreateDelegationWasmParams, g as CreateDelegationWasmResult, h as CreateOwnerDelegationParams, i as DelegateReceivedShareParams, j as DelegatedResource, k as DelegatedShareAccess, l as DelegatedShareKey, n as DelegationApiResponse, o as DelegationChain, p as DelegationChainV2, q as DelegationDirection, a as DelegationError, r as DelegationErrorCode, s as DelegationErrorCodes, t as DelegationFilters, u as DelegationManagerConfig, v as DelegationRecord, R as DelegationResult, x as DelegationStatus, E as EncodedShareData, z as IngestOptions, J as JWK, K as KeyInfo, B as KeyProvider, F as KeyType, M as MAX_CONTENT_BYTES, H as MAX_SEALED_SHARE_CONTENT_BYTES, L as MAX_SHARE_ARTIFACT_BYTES, N as MAX_SHARE_CONTENT_BYTES, O as MemorySenderShareKeyStorage, P as MemorySenderShareRecordStorage, Q as MemoryShareCache, S as OwnerDelegationPermission, T as OwnerDelegationReceipt, U as OwnerShareAction, V as OwnerShareDecryption, W as OwnerShareMatcher, X as OwnerSharePolicyRegistration, Y as OwnerSharePolicyRegistrationReceipt, Z as OwnerSharePolicyV2, _ as ReceiveOptions, $ as RegisterOwnerSharePolicyParams, a0 as SHARE_DELIVERY_AUTHORIZATION_DOMAIN, a1 as SenderShareKeyStorage, a2 as SenderShareRecord, a3 as SenderShareRecordStorage, a4 as SenderShareRevocationScope, a5 as SenderShareStore, a6 as ShareAccess, a7 as ShareAccessError, a8 as ShareAccessV2, a9 as ShareAction, ab as ShareAddressedDelegationEnvelopeV2, ac as ShareAddressedDelegationEnvelopeV2Schema, ad as ShareAddressedDelegationRequestV2, ae as ShareAddressedDelegationRequestV2Schema, af as ShareAddressedDelegationResponseV2, ag as ShareAddressedDelegationResponseV2Schema, ah as ShareAddressedRecipientMatcher, ai as ShareArtifactInput, aj as ShareArtifactResult, ak as ShareArtifactV2, al as ShareCache, am as ShareCacheEntry, an as ShareCacheKey, ao as ShareCacheMetadata, ap as ShareCapabilityLike, aq as ShareConflict, ar as ShareContentMetadata, as as ShareContentSource, at as ShareDeliveryAuthorization, au as ShareDeliveryAuthorizationReceipt, av as ShareDeliveryAuthorizationRequest, aw as ShareDetachedProof, ax as ShareEnvelopeError, ay as ShareEnvelopeV2, az as ShareExpiryBounds, aA as ShareKvContentSource, aC as ShareLinkData, aD as ShareLinkLocation, aE as ShareListEntry, aF as ShareListResult, aG as ShareNativeAction, aH as ShareNativeInvokeEnvelopeV1, aI as ShareNativeInvokeErrorResult, aJ as ShareNativeInvokeInput, aK as ShareNativeInvokeResult, aL as ShareNativeInvokeSuccessResult, aM as ShareNativeResponse, aN as ShareNativeResponseSchema, aO as SharePolicy, aP as SharePolicyBinding, aQ as SharePolicySession, aR as SharePolicySessionV1, aS as SharePolicySessionWireV1, aT as ShareReadInvocationV1, aU as ShareReadResult, aV as ShareRecipientClient, aW as ShareRecipientClientOptions, aY as ShareRecipientPolicy, a_ as ShareRecipientResult, a$ as ShareRecipientTarget, b1 as ShareResource, b3 as ShareSaveOptions, b4 as ShareSchema, b5 as ShareSqlContentSource, b6 as ShareWireAction, b7 as SharingService, b8 as SharingServiceConfig, b9 as SignedDelegation, bb as SpaceOwnership, bM as StoredDelegationChain, bc as ValidateShareDeliveryAuthorizationExpected, bd as VerifyShareEnvelopeOptions, be as canonicalOwnerSharePolicy, bf as computeOwnerShareRegistrationCid, bg as computeShareCid, bN as createCapabilityKeyRegistry, bh as createDelegatedShareKey, bi as createPolicyEnforcementDelegation, bj as createShareArtifact, bk as createShareArtifactAsync, bl as createSharePolicy, bm as createSharingService, bn as decryptShareBytesAsync, bo as encodeInlineShareUrl, bp as encodeShareArtifact, bq as encodeShareUrl, br as encryptShareBytes, bs as encryptShareBytesAsync, bt as intersectShareCapabilities, bu as isV2ShareLink, bv as normalizeShareActions, bw as normalizeShareRecipientTarget, bx as normalizeShareResource, by as parseShareArtifact, bz as parseShareUrl, bA as restoreDelegatedShareKey, bB as shareCapabilityAllows, bC as shareDeliveryTrustedKid, bD as signShareEnvelope, bE as validateOwnerSharePolicyRegistration, bF as validateOwnerSharePolicyRegistrationBytes, bG as validateShareDeliveryAuthorizationBytes, bH as verifyShareCid, bI as verifyShareEnvelope } from './recipient-types.schema-CWIt63Qp.cjs';
7
7
  export { ACCOUNT_INDEX_SCHEMA, BOOTSTRAP_ALLOWLIST, BOOTSTRAP_DEFAULT_SPACE, BOOTSTRAP_ENCRYPTION_NETWORK_NAME, BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE, BOOTSTRAP_MANIFEST, BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS, BOOTSTRAP_PUBLIC_SPACE, BOOTSTRAP_SESSION_REQUESTS, BOOTSTRAP_SPACE_MANIFESTS, BOOTSTRAP_SPACE_NAMES, BootstrapAllowlistEntry, BootstrapAllowlistKind, BootstrapEncryptionNetworkStep, BootstrapManifest, BootstrapRawAbilityAllowlistEntry, BootstrapSchemaStep, BootstrapSeedApplicationsStep, BootstrapSeedSpacesStep, BootstrapSpaceDescriptor, BootstrapSpaceName, BootstrapSpaceStep, BootstrapStep, BootstrapStepKind, CAPABILITIES, CAPABILITY_REGISTRY, CapabilityRegistryEntry, CapabilityStatus, DUCKDB, ENCRYPTION, HOOKS, KV, SECRET_RECORDS_SCHEMA, SPACE, SQL, TINYCLOUD_ACCOUNT_SPACE_MANIFEST, TINYCLOUD_APPLICATIONS_SPACE_MANIFEST, TINYCLOUD_DEFAULT_SPACE_MANIFEST, TINYCLOUD_PUBLIC_SPACE_MANIFEST, TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST, bootstrapEncryptionNetworkId, bootstrapSpaceId, bootstrapSteps, composeBootstrapSpaceManifest } from '@tinycloud/bootstrap';
8
8
  export { E as ED25519_JCS_SIGNATURE_SUITE, b as EIP191_JCS_SIGNATURE_SUITE, J as JsonObject, c as POLICY_ENGINE_RECORD_SCHEMA, d as POLICY_SCHEMA, e as POLICY_STATUS_SCHEMA, a as Policy, P as PolicyEngineRecord, f as PolicyStatus, g as SignatureMaterialError, h as SignatureSuite, i as SignatureVerificationError, j as SignedObjectCanonicalizationError, k as SignedObjectDigestError, l as SignedObjectErrorCode, m as SignedObjectIdError, n as SignedObjectKind, o as SignedObjectMaterial, p as SignedObjectProfileError, q as SignedObjectSchemaError, r as SignedObjectSignature, S as SignedObjectSigner, s as SignedObjectVerificationResult, t as SignedPolicyObject, u as SigningKeyBindingError, v as UnsignedPolicy, U as UnsignedPolicyEngineRecord, w as UnsignedPolicyObject, x as UnsignedPolicyStatus, y as UnsupportedSignatureSuiteError, z as canonicalizeSignedObjectUnsigned, A as createAndSignPolicy, B as createAndSignPolicyEngineRecord, C as createAndSignPolicyStatus, D as createAndSignSignedObject, F as deriveSignedObjectMaterial, G as signedObjectIdFor, H as toSignedObjectError, I as validatePolicyEngineRecordSigned, K as validatePolicyEngineRecordSignedShape, L as validatePolicyEngineRecordUnsigned, M as validatePolicySigned, N as validatePolicySignedShape, O as validatePolicyStatusSigned, Q as validatePolicyStatusSignedShape, R as validatePolicyStatusUnsigned, T as validatePolicyUnsigned, V as verifyPolicy, W as verifyPolicyEngineRecord, X as verifyPolicyStatus, Y as verifySignedObject } from './signed-object-IMAm5a32.cjs';
9
9
  export { a as JsonValue, j as jcsCanonicalize, n as normalizeJson, s as serializeJcsJson } from './capability-BjzXwtNw.cjs';
@@ -680,8 +680,11 @@ interface SubsetCheckResult {
680
680
  * - Action containment: every requested URN must be matched exactly or by a
681
681
  * service-scoped wildcard such as `tinycloud.kv/*`.
682
682
  *
683
- * Any `requested` entry that does not find a matching `granted` entry is
684
- * added to `missing` and the overall result is non-subset.
683
+ * Grant entries with the same service, space, path coverage, and caveats are
684
+ * considered together. This matters because ReCap parsers may return one
685
+ * entry per action even when the original manifest grouped those actions.
686
+ * Any `requested` entry whose actions are not collectively covered is added
687
+ * to `missing` and the overall result is non-subset.
685
688
  *
686
689
  * Both sides are expected to be in the canonical long-form shape (service
687
690
  * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}
@@ -2523,6 +2526,20 @@ interface AccountIndexedReadOptions {
2523
2526
  refreshIndex?: boolean;
2524
2527
  }
2525
2528
  type AccountApplicationListOptions = AccountIndexedReadOptions;
2529
+ interface AccountApplicationRegisterOptions {
2530
+ /**
2531
+ * Skip the `application_state` manifest-hash pre-read that normally
2532
+ * short-circuits a redundant write.
2533
+ *
2534
+ * The pre-read is a saving only when the application is already registered
2535
+ * with the same manifest hash. On a freshly bootstrapped account it is
2536
+ * definitionally a miss, so it costs a round trip and buys nothing — and the
2537
+ * write it guards is an `INSERT OR REPLACE`, so performing it unconditionally
2538
+ * is idempotent. Set this only when the caller knows the record cannot
2539
+ * already be current (i.e. the account bootstrap path).
2540
+ */
2541
+ assumeUnregistered?: boolean;
2542
+ }
2526
2543
  type AccountSpaceListOptions = AccountIndexedReadOptions;
2527
2544
  interface AccountDelegationListOptions {
2528
2545
  direction?: "granted" | "received" | "all";
@@ -2546,12 +2563,28 @@ interface AccountServiceConfig {
2546
2563
  }
2547
2564
  declare class AccountService {
2548
2565
  private readonly config;
2566
+ /**
2567
+ * Per-account-space memo for {@link ensureAccountIndex}.
2568
+ *
2569
+ * Applying the index migration is a no-op once the schema exists, but the
2570
+ * SQL service still spends two round trips discovering that (create the
2571
+ * migrations table, then read the applied-migration rows). Account bootstrap
2572
+ * touches the index eight times, so without a memo that is ~14 wasted
2573
+ * requests on the cold sign-in path. The in-flight dedupe inside SQLService
2574
+ * never helps here: the node SDK builds a fresh SQLService per
2575
+ * `getAccountDb()` call, so its lock map is always empty.
2576
+ *
2577
+ * Keyed by account space id, so a different account never reuses this entry.
2578
+ * Failures are evicted so a later call retries instead of inheriting a
2579
+ * permanently poisoned result.
2580
+ */
2581
+ private readonly accountIndexReady;
2549
2582
  constructor(config: AccountServiceConfig);
2550
2583
  status(): Promise<Result<AccountStatus>>;
2551
2584
  readonly applications: {
2552
2585
  list: (options?: AccountApplicationListOptions) => Promise<Result<AccountApplication[]>>;
2553
2586
  get: (appId: string) => Promise<Result<AccountApplication>>;
2554
- register: (manifest: Manifest | Manifest[]) => Promise<Result<AccountApplication>>;
2587
+ register: (manifest: Manifest | Manifest[], options?: AccountApplicationRegisterOptions) => Promise<Result<AccountApplication>>;
2555
2588
  remove: (appId: string) => Promise<Result<void>>;
2556
2589
  };
2557
2590
  readonly spaces: {
@@ -2596,7 +2629,19 @@ declare class AccountService {
2596
2629
  private replaceApplicationsIndexQuietly;
2597
2630
  private replaceSpacesIndexQuietly;
2598
2631
  private replaceDelegationsIndexQuietly;
2632
+ /**
2633
+ * Apply the account index schema at most once per account space.
2634
+ *
2635
+ * The index is a cache over canonical KV state, and every caller already
2636
+ * tolerates it being absent (`ignoreIndexFailure` / `isMissingIndexError`),
2637
+ * so a memo that is wrong in the "already applied" direction degrades to a
2638
+ * `no such table` read that the caller handles. A memo that is wrong in the
2639
+ * other direction would be a real bug, so failures are never cached.
2640
+ */
2599
2641
  private ensureAccountIndex;
2642
+ /** Drop the memo so the next {@link ensureAccountIndex} re-applies the schema. */
2643
+ private invalidateAccountIndexMemo;
2644
+ private applyAccountIndex;
2600
2645
  }
2601
2646
  interface AccountIndexStatus {
2602
2647
  database: string;
@@ -2943,4 +2988,4 @@ declare const EXPIRY: {
2943
2988
  declare const DEFAULT_SIGNED_READ_URL_EXPIRY_MS: number;
2944
2989
  type ExpiryTier = keyof typeof EXPIRY;
2945
2990
 
2946
- export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, type AbilitiesMap, type AccountApplication, type AccountApplicationListOptions, type AccountDelegation, type AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, type AccountDelegationRevokeOptions, type AccountIndexEnsureResult, type AccountIndexRebuildResult, type AccountIndexStatus, type AccountIndexedReadOptions, AccountService, type AccountServiceConfig, type AccountSpace, type AccountSpaceListOptions, type AccountStatus, AutoApproveSpaceCreationHandler, type AutoRejectStrategy, type AutoSignStrategy, type Bytes, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, DEFAULT_DEFAULTS, DEFAULT_EXPIRY, DEFAULT_KNOWLEDGE_ROOT, DEFAULT_LOCAL_NODE_PIN_STORAGE_KEY, DEFAULT_LOCAL_NODE_URL, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DEFAULT_TINYCLOUD_FALLBACK_HOST, DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL, Delegation, DelegationManager, DelegationRevocationReceipt, type DidCacheKeyOptions, type DidEqualsOptions, type DiscoverLocalTinyCloudNodeOptions, type DiscoveredLocalTinyCloudNode, ENCRYPTION_MANIFEST_SPACE, ENCRYPTION_PERMISSION_SERVICE, EXPIRY, type EnsData, EnsDataSchema, type EventEmitterStrategy, type ExpiryTier, type Extension, GenerateShareParams, ICapabilityKeyRegistry, type IENSResolver, type INotificationHandler, type ISessionManager, type ISessionStorage, ISharingService, type ISigner, type ISpace, type ISpaceCreationHandler, type ISpaceScopedDelegations, type ISpaceScopedSharing, type ISpaceService, type IUserAuthorization, type IWasmBindings, IdentityParseError, LOCAL_LINK_HOST_SUFFIX, LOCAL_LINK_PROBE_TIMEOUT_MS, LOCAL_LOOPBACK_PROBE_TIMEOUT_MS, type LocalNodeIdentityStore, type LocationCandidate, type LocationCandidateInput, type LocationRecord, type LocationRecordPayload, type LocationRecordSigner, LocationRecordValidationError, type LocationResolutionAttempt, type LocationSource, type Manifest, type ManifestDefaults, type ManifestKnowledge, type ManifestRegistryRecord, type ManifestSecretActions, ManifestValidationError, type NodeInfo, type OpenKeyCallbackStrategy, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type ResolveCloudLocationOptions, type ResolveTinyCloudHostsOptions, type ResolvedCapabilities, type ResolvedCloudLocation, type ResolvedDelegate, type ResolvedTinyCloudHosts, type ResourceCapability, SECRETS_SPACE, SERVICE_LONG_TO_SHORT, SERVICE_SHORT_TO_LONG, type ServerHost, SessionExpiredError, ShareLink, type SignCallback, type SignInOptions, type SignRequest, type SignResponse, type SignStrategy, SilentNotificationHandler, type SiweConfig, SiweConfigSchema, Space, type SpaceAbilitiesMap, type SpaceConfig, type SpaceCreationContext, type SpaceDelegationParams, type SpaceErrorCode, SpaceErrorCodes, type SpaceHostResult, SpaceInfo, SpaceService, type SpaceServiceConfig, type SubsetCheckResult, TinyCloud, type TinyCloudConfig, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, defaultSignStrategy, defaultSpaceCreationHandler, didCacheKey, didEquals, discoverLocalTinyCloudNode, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, fetchLocationRecord, fetchPeerId, httpUrlToMultiaddr, isCapabilitySubset, isEvmAddress, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, signLocationRecord, submitHostDelegation, validateClientSession, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyLocationRecord };
2991
+ export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, type AbilitiesMap, type AccountApplication, type AccountApplicationListOptions, type AccountApplicationRegisterOptions, type AccountDelegation, type AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, type AccountDelegationRevokeOptions, type AccountIndexEnsureResult, type AccountIndexRebuildResult, type AccountIndexStatus, type AccountIndexedReadOptions, AccountService, type AccountServiceConfig, type AccountSpace, type AccountSpaceListOptions, type AccountStatus, AutoApproveSpaceCreationHandler, type AutoRejectStrategy, type AutoSignStrategy, type Bytes, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, DEFAULT_DEFAULTS, DEFAULT_EXPIRY, DEFAULT_KNOWLEDGE_ROOT, DEFAULT_LOCAL_NODE_PIN_STORAGE_KEY, DEFAULT_LOCAL_NODE_URL, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DEFAULT_TINYCLOUD_FALLBACK_HOST, DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL, Delegation, DelegationManager, DelegationRevocationReceipt, type DidCacheKeyOptions, type DidEqualsOptions, type DiscoverLocalTinyCloudNodeOptions, type DiscoveredLocalTinyCloudNode, ENCRYPTION_MANIFEST_SPACE, ENCRYPTION_PERMISSION_SERVICE, EXPIRY, type EnsData, EnsDataSchema, type EventEmitterStrategy, type ExpiryTier, type Extension, GenerateShareParams, ICapabilityKeyRegistry, type IENSResolver, type INotificationHandler, type ISessionManager, type ISessionStorage, ISharingService, type ISigner, type ISpace, type ISpaceCreationHandler, type ISpaceScopedDelegations, type ISpaceScopedSharing, type ISpaceService, type IUserAuthorization, type IWasmBindings, IdentityParseError, LOCAL_LINK_HOST_SUFFIX, LOCAL_LINK_PROBE_TIMEOUT_MS, LOCAL_LOOPBACK_PROBE_TIMEOUT_MS, type LocalNodeIdentityStore, type LocationCandidate, type LocationCandidateInput, type LocationRecord, type LocationRecordPayload, type LocationRecordSigner, LocationRecordValidationError, type LocationResolutionAttempt, type LocationSource, type Manifest, type ManifestDefaults, type ManifestKnowledge, type ManifestRegistryRecord, type ManifestSecretActions, ManifestValidationError, type NodeInfo, type OpenKeyCallbackStrategy, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type ResolveCloudLocationOptions, type ResolveTinyCloudHostsOptions, type ResolvedCapabilities, type ResolvedCloudLocation, type ResolvedDelegate, type ResolvedTinyCloudHosts, type ResourceCapability, SECRETS_SPACE, SERVICE_LONG_TO_SHORT, SERVICE_SHORT_TO_LONG, type ServerHost, SessionExpiredError, ShareLink, type SignCallback, type SignInOptions, type SignRequest, type SignResponse, type SignStrategy, SilentNotificationHandler, type SiweConfig, SiweConfigSchema, Space, type SpaceAbilitiesMap, type SpaceConfig, type SpaceCreationContext, type SpaceDelegationParams, type SpaceErrorCode, SpaceErrorCodes, type SpaceHostResult, SpaceInfo, SpaceService, type SpaceServiceConfig, type SubsetCheckResult, TinyCloud, type TinyCloudConfig, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, defaultSignStrategy, defaultSpaceCreationHandler, didCacheKey, didEquals, discoverLocalTinyCloudNode, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, fetchLocationRecord, fetchPeerId, httpUrlToMultiaddr, isCapabilitySubset, isEvmAddress, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, signLocationRecord, submitHostDelegation, validateClientSession, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyLocationRecord };
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import { z } from 'zod';
2
2
  import { InvokeFunction, InvokeAnyFunction, ParsedNetworkId, ServiceError, Result, FetchFunction, ServiceConstructor, RetryPolicy, TelemetryConfig, IServiceContext, IService, IKVService, ISQLService, IDuckDbService, IHooksService, IDataVaultService, IEncryptionService, ISecretsService, ServiceSession, IDatabaseHandle, SqlValue, QueryResponse } from '@tinycloud/sdk-services';
3
3
  export { BatchOptions, BatchResponse, BuildCanonicalDecryptRequestInput, BuildDecryptFactsInput, BuildDecryptInvocationInput, BuiltDecryptInvocation, CanonicalDecryptRequest, CanonicalJson, ColumnInfo, DECRYPT_ACTION, DECRYPT_FACT_TYPE, DECRYPT_RESULT_TYPE, DEFAULT_ENCRYPTION_ALG, DEFAULT_KEY_VERSION, DataVaultConfig, DataVaultService, DatabaseHandle, DecryptCapabilityProof, DecryptEnvelopeOptions, DecryptInvocationFact, DecryptInvocationSigner, DecryptRequestBody, DecryptResponseBody, DecryptTransport, DecryptTransportResponseError, DiscoverNetworkInput, DiscoveredNetwork, DiscoverySource, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, ENCRYPTION_NETWORK_URN_PREFIX, ENCRYPTION_SERVICE, ENCRYPTION_SERVICE_SHORT, ENVELOPE_VERSION, EncryptToNetworkInput, EncryptToNetworkOptions, EncryptToNetworkResult, EncryptionCrypto, EncryptionError, EncryptionErrorInput, EncryptionService, EncryptionServiceConfig, ErrorCode, ErrorCodes, ExecuteOptions, ExecuteResponse, FetchFunction, HookEvent, HookServiceName, HookStreamEvent, HookSubscription, HookWebhookListOptions, HookWebhookRecord, HookWebhookRegistration, HookWebhookScope, HookWebhookUnregisterOptions, HooksService, HooksServiceConfig, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IEncryptionService, IHooksService, IKVService, IPrefixedKVService, ISQLService, ISecretsService, IService, IServiceContext, InlineEncryptedEnvelope, InvokeAnyEntry, InvokeAnyFunction, InvokeFunction, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVDeleteOptions, KVGetOptions, KVHeadOptions, KVListOptions, KVListResponse, KVPutOptions, KVResponse, KVResponseHeaders, KVService, KVServiceConfig, KVSignedReadUrlResponse, NETWORK_NAME_PATTERN, NetworkDescriptor, NetworkIdError, NodeDescriptorFetcher, ParsedNetworkId, PrefixedKVService, QueryOptions, QueryResponse, RandomReceiverKeyInput, ReceiverKeyPair, ReceiverKeySigner, ResolvedSecretPath, Result, RetryPolicy, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceError, ServiceSession, SignedReceiverKeyInput, SqlStatement, SqlValue, SubscribeOptions, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VerifyDecryptResponseInput, ViewInfo, WasmVaultFunctions, WellKnownDescriptorFetcher, buildCanonicalDecryptRequest, buildDecryptAttenuation, buildDecryptFacts, buildDecryptInvocation, buildNetworkId, canonicalHashHex, canonicalSignedResponse, canonicalizeEncryptionJson, canonicalizeSecretScope, checkDecryptInvocationInput, clearTinyCloudDebugLogs, createVaultCrypto, decryptEnvelopeWithKey, defaultRetryPolicy, deriveSignedReceiverKey, disableTinyCloudDebug, discoverNetwork, enableTinyCloudDebug, encryptToNetwork, base64Decode as encryptionBase64Decode, base64Encode as encryptionBase64Encode, encryptionError, utf8Decode as encryptionUtf8Decode, utf8Encode as encryptionUtf8Encode, ensureNetworkUsableForDecrypt, err, generateRandomReceiverKey, getTinyCloudDebugLogs, hexDecode, hexEncode, installTinyCloudDebugGlobals, isNetworkId, networkDiscoveryKey, ok, openWrappedKey, parseNetworkId, resolveSecretListPrefix, resolveSecretPath, serviceError, tinyCloudDebugLogger, validateEnvelope, verifyDecryptResponse } from '@tinycloud/sdk-services';
4
4
  export { HOLDER_KEY_BINDING_PRESENTATION_SCHEMA, HolderKeyBindingPresentation, LISTEN_SQL_STATEMENT_CATALOG, ListenSqlStatementName, POLICY_ENGINE_CHALLENGE_REQUEST_SCHEMA, POLICY_ENGINE_CHALLENGE_RESPONSE_SCHEMA, POLICY_ENGINE_DENIAL_SCHEMA, POLICY_ENGINE_GRANT_PRESENTATION_DENIAL_CODES, POLICY_ENGINE_RESOLVE_REQUEST_SCHEMA, PORTABLE_DELEGATION_SCHEMA, PolicyEngineGrantPresentationDenialCode, PortableDelegation, REQUESTER_ENGINE_RETRY_ATTEMPTS, REQUESTER_ENGINE_RETRY_MAX_DELAY_MS, REQUESTER_NEAR_EXPIRY_SECONDS, RequesterEndpointResolution, RequesterHttpRequest, RequesterHttpResponse, RequesterInvocationCapability, RequesterSigningCapability, RequesterTransport, TranscriptRequester, TranscriptRequesterError, TranscriptRequesterErrorCode, TranscriptRequesterErrorState, TranscriptRequesterOptions, TranscriptRequesterReadKvResult, TranscriptRequesterReadSqlResult, createTranscriptRequester, deriveDelegationCid, parseNodeNativePortableDelegation } from './requester/index.js';
5
- import { m as Delegation, e as CreateDelegationParams, G as GenerateShareParams, az as ShareLink, b8 as SpaceInfo, I as ICapabilityKeyRegistry, y as ISharingService, D as DelegationManager, b as AccountDelegationQueryOptions, A as AccountDelegationPage, w as DelegationRevocationReceipt } from './recipient-types.schema-B2wH53_t.js';
6
- export { c as AccountDelegationRecord, d as AccountDelegationResource, C as CapabilityEntry, bH as CapabilityKeyRegistry, bI as CapabilityKeyRegistryErrorCode, bJ as CapabilityKeyRegistryErrorCodes, f as CreateDelegationWasmParams, g as CreateDelegationWasmResult, h as CreateOwnerDelegationParams, i as DelegateReceivedShareParams, j as DelegatedResource, k as DelegatedShareAccess, l as DelegatedShareKey, n as DelegationApiResponse, o as DelegationChain, p as DelegationChainV2, q as DelegationDirection, a as DelegationError, r as DelegationErrorCode, s as DelegationErrorCodes, t as DelegationFilters, u as DelegationManagerConfig, v as DelegationRecord, R as DelegationResult, x as DelegationStatus, E as EncodedShareData, z as IngestOptions, J as JWK, K as KeyInfo, B as KeyProvider, F as KeyType, M as MAX_CONTENT_BYTES, H as MAX_SEALED_SHARE_CONTENT_BYTES, L as MAX_SHARE_ARTIFACT_BYTES, N as MAX_SHARE_CONTENT_BYTES, O as MemorySenderShareKeyStorage, P as MemorySenderShareRecordStorage, Q as MemoryShareCache, S as OwnerDelegationReceipt, T as OwnerShareAction, U as OwnerShareMatcher, V as OwnerSharePolicyRegistration, W as OwnerSharePolicyRegistrationReceipt, X as OwnerSharePolicyV2, Y as ReceiveOptions, Z as RegisterOwnerSharePolicyParams, _ as SHARE_DELIVERY_AUTHORIZATION_DOMAIN, $ as SenderShareKeyStorage, a0 as SenderShareRecord, a1 as SenderShareRecordStorage, a2 as SenderShareRevocationScope, a3 as SenderShareStore, a4 as ShareAccess, a5 as ShareAccessError, a6 as ShareAccessV2, a7 as ShareAction, a9 as ShareAddressedDelegationEnvelopeV2, aa as ShareAddressedDelegationEnvelopeV2Schema, ab as ShareAddressedDelegationRequestV2, ac as ShareAddressedDelegationRequestV2Schema, ad as ShareAddressedDelegationResponseV2, ae as ShareAddressedDelegationResponseV2Schema, af as ShareAddressedRecipientMatcher, ag as ShareArtifactInput, ah as ShareArtifactResult, ai as ShareArtifactV2, aj as ShareCache, ak as ShareCacheEntry, al as ShareCacheKey, am as ShareCacheMetadata, an as ShareCapabilityLike, ao as ShareConflict, ap as ShareContentMetadata, aq as ShareContentSource, ar as ShareDeliveryAuthorization, as as ShareDeliveryAuthorizationReceipt, at as ShareDeliveryAuthorizationRequest, au as ShareDetachedProof, av as ShareEnvelopeError, aw as ShareEnvelopeV2, ax as ShareExpiryBounds, ay as ShareKvContentSource, aA as ShareLinkData, aB as ShareLinkLocation, aC as ShareListEntry, aD as ShareListResult, aE as ShareNativeAction, aF as ShareNativeInvokeEnvelopeV1, aG as ShareNativeInvokeErrorResult, aH as ShareNativeInvokeInput, aI as ShareNativeInvokeResult, aJ as ShareNativeInvokeSuccessResult, aK as ShareNativeResponse, aL as ShareNativeResponseSchema, aM as SharePolicy, aN as SharePolicyBinding, aO as SharePolicySession, aP as SharePolicySessionV1, aQ as SharePolicySessionWireV1, aR as ShareReadInvocationV1, aS as ShareReadResult, aT as ShareRecipientClient, aU as ShareRecipientClientOptions, aW as ShareRecipientPolicy, aY as ShareRecipientResult, aZ as ShareRecipientTarget, a$ as ShareResource, b1 as ShareSaveOptions, b2 as ShareSchema, b3 as ShareSqlContentSource, b4 as ShareWireAction, b5 as SharingService, b6 as SharingServiceConfig, b7 as SignedDelegation, b9 as SpaceOwnership, bK as StoredDelegationChain, ba as ValidateShareDeliveryAuthorizationExpected, bb as VerifyShareEnvelopeOptions, bc as canonicalOwnerSharePolicy, bd as computeOwnerShareRegistrationCid, be as computeShareCid, bL as createCapabilityKeyRegistry, bf as createDelegatedShareKey, bg as createPolicyEnforcementDelegation, bh as createShareArtifact, bi as createShareArtifactAsync, bj as createSharePolicy, bk as createSharingService, bl as decryptShareBytesAsync, bm as encodeInlineShareUrl, bn as encodeShareArtifact, bo as encodeShareUrl, bp as encryptShareBytes, bq as encryptShareBytesAsync, br as intersectShareCapabilities, bs as isV2ShareLink, bt as normalizeShareActions, bu as normalizeShareRecipientTarget, bv as normalizeShareResource, bw as parseShareArtifact, bx as parseShareUrl, by as restoreDelegatedShareKey, bz as shareCapabilityAllows, bA as shareDeliveryTrustedKid, bB as signShareEnvelope, bC as validateOwnerSharePolicyRegistration, bD as validateOwnerSharePolicyRegistrationBytes, bE as validateShareDeliveryAuthorizationBytes, bF as verifyShareCid, bG as verifyShareEnvelope } from './recipient-types.schema-B2wH53_t.js';
5
+ import { m as Delegation, e as CreateDelegationParams, G as GenerateShareParams, aB as ShareLink, ba as SpaceInfo, I as ICapabilityKeyRegistry, y as ISharingService, D as DelegationManager, b as AccountDelegationQueryOptions, A as AccountDelegationPage, w as DelegationRevocationReceipt } from './recipient-types.schema-CWIt63Qp.js';
6
+ export { c as AccountDelegationRecord, d as AccountDelegationResource, C as CapabilityEntry, bJ as CapabilityKeyRegistry, bK as CapabilityKeyRegistryErrorCode, bL as CapabilityKeyRegistryErrorCodes, f as CreateDelegationWasmParams, g as CreateDelegationWasmResult, h as CreateOwnerDelegationParams, i as DelegateReceivedShareParams, j as DelegatedResource, k as DelegatedShareAccess, l as DelegatedShareKey, n as DelegationApiResponse, o as DelegationChain, p as DelegationChainV2, q as DelegationDirection, a as DelegationError, r as DelegationErrorCode, s as DelegationErrorCodes, t as DelegationFilters, u as DelegationManagerConfig, v as DelegationRecord, R as DelegationResult, x as DelegationStatus, E as EncodedShareData, z as IngestOptions, J as JWK, K as KeyInfo, B as KeyProvider, F as KeyType, M as MAX_CONTENT_BYTES, H as MAX_SEALED_SHARE_CONTENT_BYTES, L as MAX_SHARE_ARTIFACT_BYTES, N as MAX_SHARE_CONTENT_BYTES, O as MemorySenderShareKeyStorage, P as MemorySenderShareRecordStorage, Q as MemoryShareCache, S as OwnerDelegationPermission, T as OwnerDelegationReceipt, U as OwnerShareAction, V as OwnerShareDecryption, W as OwnerShareMatcher, X as OwnerSharePolicyRegistration, Y as OwnerSharePolicyRegistrationReceipt, Z as OwnerSharePolicyV2, _ as ReceiveOptions, $ as RegisterOwnerSharePolicyParams, a0 as SHARE_DELIVERY_AUTHORIZATION_DOMAIN, a1 as SenderShareKeyStorage, a2 as SenderShareRecord, a3 as SenderShareRecordStorage, a4 as SenderShareRevocationScope, a5 as SenderShareStore, a6 as ShareAccess, a7 as ShareAccessError, a8 as ShareAccessV2, a9 as ShareAction, ab as ShareAddressedDelegationEnvelopeV2, ac as ShareAddressedDelegationEnvelopeV2Schema, ad as ShareAddressedDelegationRequestV2, ae as ShareAddressedDelegationRequestV2Schema, af as ShareAddressedDelegationResponseV2, ag as ShareAddressedDelegationResponseV2Schema, ah as ShareAddressedRecipientMatcher, ai as ShareArtifactInput, aj as ShareArtifactResult, ak as ShareArtifactV2, al as ShareCache, am as ShareCacheEntry, an as ShareCacheKey, ao as ShareCacheMetadata, ap as ShareCapabilityLike, aq as ShareConflict, ar as ShareContentMetadata, as as ShareContentSource, at as ShareDeliveryAuthorization, au as ShareDeliveryAuthorizationReceipt, av as ShareDeliveryAuthorizationRequest, aw as ShareDetachedProof, ax as ShareEnvelopeError, ay as ShareEnvelopeV2, az as ShareExpiryBounds, aA as ShareKvContentSource, aC as ShareLinkData, aD as ShareLinkLocation, aE as ShareListEntry, aF as ShareListResult, aG as ShareNativeAction, aH as ShareNativeInvokeEnvelopeV1, aI as ShareNativeInvokeErrorResult, aJ as ShareNativeInvokeInput, aK as ShareNativeInvokeResult, aL as ShareNativeInvokeSuccessResult, aM as ShareNativeResponse, aN as ShareNativeResponseSchema, aO as SharePolicy, aP as SharePolicyBinding, aQ as SharePolicySession, aR as SharePolicySessionV1, aS as SharePolicySessionWireV1, aT as ShareReadInvocationV1, aU as ShareReadResult, aV as ShareRecipientClient, aW as ShareRecipientClientOptions, aY as ShareRecipientPolicy, a_ as ShareRecipientResult, a$ as ShareRecipientTarget, b1 as ShareResource, b3 as ShareSaveOptions, b4 as ShareSchema, b5 as ShareSqlContentSource, b6 as ShareWireAction, b7 as SharingService, b8 as SharingServiceConfig, b9 as SignedDelegation, bb as SpaceOwnership, bM as StoredDelegationChain, bc as ValidateShareDeliveryAuthorizationExpected, bd as VerifyShareEnvelopeOptions, be as canonicalOwnerSharePolicy, bf as computeOwnerShareRegistrationCid, bg as computeShareCid, bN as createCapabilityKeyRegistry, bh as createDelegatedShareKey, bi as createPolicyEnforcementDelegation, bj as createShareArtifact, bk as createShareArtifactAsync, bl as createSharePolicy, bm as createSharingService, bn as decryptShareBytesAsync, bo as encodeInlineShareUrl, bp as encodeShareArtifact, bq as encodeShareUrl, br as encryptShareBytes, bs as encryptShareBytesAsync, bt as intersectShareCapabilities, bu as isV2ShareLink, bv as normalizeShareActions, bw as normalizeShareRecipientTarget, bx as normalizeShareResource, by as parseShareArtifact, bz as parseShareUrl, bA as restoreDelegatedShareKey, bB as shareCapabilityAllows, bC as shareDeliveryTrustedKid, bD as signShareEnvelope, bE as validateOwnerSharePolicyRegistration, bF as validateOwnerSharePolicyRegistrationBytes, bG as validateShareDeliveryAuthorizationBytes, bH as verifyShareCid, bI as verifyShareEnvelope } from './recipient-types.schema-CWIt63Qp.js';
7
7
  export { ACCOUNT_INDEX_SCHEMA, BOOTSTRAP_ALLOWLIST, BOOTSTRAP_DEFAULT_SPACE, BOOTSTRAP_ENCRYPTION_NETWORK_NAME, BOOTSTRAP_ENCRYPTION_NETWORK_RESOURCE_TEMPLATE, BOOTSTRAP_MANIFEST, BOOTSTRAP_PERSISTED_APPLICATION_MANIFESTS, BOOTSTRAP_PUBLIC_SPACE, BOOTSTRAP_SESSION_REQUESTS, BOOTSTRAP_SPACE_MANIFESTS, BOOTSTRAP_SPACE_NAMES, BootstrapAllowlistEntry, BootstrapAllowlistKind, BootstrapEncryptionNetworkStep, BootstrapManifest, BootstrapRawAbilityAllowlistEntry, BootstrapSchemaStep, BootstrapSeedApplicationsStep, BootstrapSeedSpacesStep, BootstrapSpaceDescriptor, BootstrapSpaceName, BootstrapSpaceStep, BootstrapStep, BootstrapStepKind, CAPABILITIES, CAPABILITY_REGISTRY, CapabilityRegistryEntry, CapabilityStatus, DUCKDB, ENCRYPTION, HOOKS, KV, SECRET_RECORDS_SCHEMA, SPACE, SQL, TINYCLOUD_ACCOUNT_SPACE_MANIFEST, TINYCLOUD_APPLICATIONS_SPACE_MANIFEST, TINYCLOUD_DEFAULT_SPACE_MANIFEST, TINYCLOUD_PUBLIC_SPACE_MANIFEST, TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST, bootstrapEncryptionNetworkId, bootstrapSpaceId, bootstrapSteps, composeBootstrapSpaceManifest } from '@tinycloud/bootstrap';
8
8
  export { E as ED25519_JCS_SIGNATURE_SUITE, b as EIP191_JCS_SIGNATURE_SUITE, J as JsonObject, c as POLICY_ENGINE_RECORD_SCHEMA, d as POLICY_SCHEMA, e as POLICY_STATUS_SCHEMA, a as Policy, P as PolicyEngineRecord, f as PolicyStatus, g as SignatureMaterialError, h as SignatureSuite, i as SignatureVerificationError, j as SignedObjectCanonicalizationError, k as SignedObjectDigestError, l as SignedObjectErrorCode, m as SignedObjectIdError, n as SignedObjectKind, o as SignedObjectMaterial, p as SignedObjectProfileError, q as SignedObjectSchemaError, r as SignedObjectSignature, S as SignedObjectSigner, s as SignedObjectVerificationResult, t as SignedPolicyObject, u as SigningKeyBindingError, v as UnsignedPolicy, U as UnsignedPolicyEngineRecord, w as UnsignedPolicyObject, x as UnsignedPolicyStatus, y as UnsupportedSignatureSuiteError, z as canonicalizeSignedObjectUnsigned, A as createAndSignPolicy, B as createAndSignPolicyEngineRecord, C as createAndSignPolicyStatus, D as createAndSignSignedObject, F as deriveSignedObjectMaterial, G as signedObjectIdFor, H as toSignedObjectError, I as validatePolicyEngineRecordSigned, K as validatePolicyEngineRecordSignedShape, L as validatePolicyEngineRecordUnsigned, M as validatePolicySigned, N as validatePolicySignedShape, O as validatePolicyStatusSigned, Q as validatePolicyStatusSignedShape, R as validatePolicyStatusUnsigned, T as validatePolicyUnsigned, V as verifyPolicy, W as verifyPolicyEngineRecord, X as verifyPolicyStatus, Y as verifySignedObject } from './signed-object-C6mWbTbB.js';
9
9
  export { a as JsonValue, j as jcsCanonicalize, n as normalizeJson, s as serializeJcsJson } from './capability-BjzXwtNw.js';
@@ -680,8 +680,11 @@ interface SubsetCheckResult {
680
680
  * - Action containment: every requested URN must be matched exactly or by a
681
681
  * service-scoped wildcard such as `tinycloud.kv/*`.
682
682
  *
683
- * Any `requested` entry that does not find a matching `granted` entry is
684
- * added to `missing` and the overall result is non-subset.
683
+ * Grant entries with the same service, space, path coverage, and caveats are
684
+ * considered together. This matters because ReCap parsers may return one
685
+ * entry per action even when the original manifest grouped those actions.
686
+ * Any `requested` entry whose actions are not collectively covered is added
687
+ * to `missing` and the overall result is non-subset.
685
688
  *
686
689
  * Both sides are expected to be in the canonical long-form shape (service
687
690
  * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}
@@ -2523,6 +2526,20 @@ interface AccountIndexedReadOptions {
2523
2526
  refreshIndex?: boolean;
2524
2527
  }
2525
2528
  type AccountApplicationListOptions = AccountIndexedReadOptions;
2529
+ interface AccountApplicationRegisterOptions {
2530
+ /**
2531
+ * Skip the `application_state` manifest-hash pre-read that normally
2532
+ * short-circuits a redundant write.
2533
+ *
2534
+ * The pre-read is a saving only when the application is already registered
2535
+ * with the same manifest hash. On a freshly bootstrapped account it is
2536
+ * definitionally a miss, so it costs a round trip and buys nothing — and the
2537
+ * write it guards is an `INSERT OR REPLACE`, so performing it unconditionally
2538
+ * is idempotent. Set this only when the caller knows the record cannot
2539
+ * already be current (i.e. the account bootstrap path).
2540
+ */
2541
+ assumeUnregistered?: boolean;
2542
+ }
2526
2543
  type AccountSpaceListOptions = AccountIndexedReadOptions;
2527
2544
  interface AccountDelegationListOptions {
2528
2545
  direction?: "granted" | "received" | "all";
@@ -2546,12 +2563,28 @@ interface AccountServiceConfig {
2546
2563
  }
2547
2564
  declare class AccountService {
2548
2565
  private readonly config;
2566
+ /**
2567
+ * Per-account-space memo for {@link ensureAccountIndex}.
2568
+ *
2569
+ * Applying the index migration is a no-op once the schema exists, but the
2570
+ * SQL service still spends two round trips discovering that (create the
2571
+ * migrations table, then read the applied-migration rows). Account bootstrap
2572
+ * touches the index eight times, so without a memo that is ~14 wasted
2573
+ * requests on the cold sign-in path. The in-flight dedupe inside SQLService
2574
+ * never helps here: the node SDK builds a fresh SQLService per
2575
+ * `getAccountDb()` call, so its lock map is always empty.
2576
+ *
2577
+ * Keyed by account space id, so a different account never reuses this entry.
2578
+ * Failures are evicted so a later call retries instead of inheriting a
2579
+ * permanently poisoned result.
2580
+ */
2581
+ private readonly accountIndexReady;
2549
2582
  constructor(config: AccountServiceConfig);
2550
2583
  status(): Promise<Result<AccountStatus>>;
2551
2584
  readonly applications: {
2552
2585
  list: (options?: AccountApplicationListOptions) => Promise<Result<AccountApplication[]>>;
2553
2586
  get: (appId: string) => Promise<Result<AccountApplication>>;
2554
- register: (manifest: Manifest | Manifest[]) => Promise<Result<AccountApplication>>;
2587
+ register: (manifest: Manifest | Manifest[], options?: AccountApplicationRegisterOptions) => Promise<Result<AccountApplication>>;
2555
2588
  remove: (appId: string) => Promise<Result<void>>;
2556
2589
  };
2557
2590
  readonly spaces: {
@@ -2596,7 +2629,19 @@ declare class AccountService {
2596
2629
  private replaceApplicationsIndexQuietly;
2597
2630
  private replaceSpacesIndexQuietly;
2598
2631
  private replaceDelegationsIndexQuietly;
2632
+ /**
2633
+ * Apply the account index schema at most once per account space.
2634
+ *
2635
+ * The index is a cache over canonical KV state, and every caller already
2636
+ * tolerates it being absent (`ignoreIndexFailure` / `isMissingIndexError`),
2637
+ * so a memo that is wrong in the "already applied" direction degrades to a
2638
+ * `no such table` read that the caller handles. A memo that is wrong in the
2639
+ * other direction would be a real bug, so failures are never cached.
2640
+ */
2599
2641
  private ensureAccountIndex;
2642
+ /** Drop the memo so the next {@link ensureAccountIndex} re-applies the schema. */
2643
+ private invalidateAccountIndexMemo;
2644
+ private applyAccountIndex;
2600
2645
  }
2601
2646
  interface AccountIndexStatus {
2602
2647
  database: string;
@@ -2943,4 +2988,4 @@ declare const EXPIRY: {
2943
2988
  declare const DEFAULT_SIGNED_READ_URL_EXPIRY_MS: number;
2944
2989
  type ExpiryTier = keyof typeof EXPIRY;
2945
2990
 
2946
- export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, type AbilitiesMap, type AccountApplication, type AccountApplicationListOptions, type AccountDelegation, type AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, type AccountDelegationRevokeOptions, type AccountIndexEnsureResult, type AccountIndexRebuildResult, type AccountIndexStatus, type AccountIndexedReadOptions, AccountService, type AccountServiceConfig, type AccountSpace, type AccountSpaceListOptions, type AccountStatus, AutoApproveSpaceCreationHandler, type AutoRejectStrategy, type AutoSignStrategy, type Bytes, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, DEFAULT_DEFAULTS, DEFAULT_EXPIRY, DEFAULT_KNOWLEDGE_ROOT, DEFAULT_LOCAL_NODE_PIN_STORAGE_KEY, DEFAULT_LOCAL_NODE_URL, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DEFAULT_TINYCLOUD_FALLBACK_HOST, DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL, Delegation, DelegationManager, DelegationRevocationReceipt, type DidCacheKeyOptions, type DidEqualsOptions, type DiscoverLocalTinyCloudNodeOptions, type DiscoveredLocalTinyCloudNode, ENCRYPTION_MANIFEST_SPACE, ENCRYPTION_PERMISSION_SERVICE, EXPIRY, type EnsData, EnsDataSchema, type EventEmitterStrategy, type ExpiryTier, type Extension, GenerateShareParams, ICapabilityKeyRegistry, type IENSResolver, type INotificationHandler, type ISessionManager, type ISessionStorage, ISharingService, type ISigner, type ISpace, type ISpaceCreationHandler, type ISpaceScopedDelegations, type ISpaceScopedSharing, type ISpaceService, type IUserAuthorization, type IWasmBindings, IdentityParseError, LOCAL_LINK_HOST_SUFFIX, LOCAL_LINK_PROBE_TIMEOUT_MS, LOCAL_LOOPBACK_PROBE_TIMEOUT_MS, type LocalNodeIdentityStore, type LocationCandidate, type LocationCandidateInput, type LocationRecord, type LocationRecordPayload, type LocationRecordSigner, LocationRecordValidationError, type LocationResolutionAttempt, type LocationSource, type Manifest, type ManifestDefaults, type ManifestKnowledge, type ManifestRegistryRecord, type ManifestSecretActions, ManifestValidationError, type NodeInfo, type OpenKeyCallbackStrategy, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type ResolveCloudLocationOptions, type ResolveTinyCloudHostsOptions, type ResolvedCapabilities, type ResolvedCloudLocation, type ResolvedDelegate, type ResolvedTinyCloudHosts, type ResourceCapability, SECRETS_SPACE, SERVICE_LONG_TO_SHORT, SERVICE_SHORT_TO_LONG, type ServerHost, SessionExpiredError, ShareLink, type SignCallback, type SignInOptions, type SignRequest, type SignResponse, type SignStrategy, SilentNotificationHandler, type SiweConfig, SiweConfigSchema, Space, type SpaceAbilitiesMap, type SpaceConfig, type SpaceCreationContext, type SpaceDelegationParams, type SpaceErrorCode, SpaceErrorCodes, type SpaceHostResult, SpaceInfo, SpaceService, type SpaceServiceConfig, type SubsetCheckResult, TinyCloud, type TinyCloudConfig, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, defaultSignStrategy, defaultSpaceCreationHandler, didCacheKey, didEquals, discoverLocalTinyCloudNode, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, fetchLocationRecord, fetchPeerId, httpUrlToMultiaddr, isCapabilitySubset, isEvmAddress, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, signLocationRecord, submitHostDelegation, validateClientSession, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyLocationRecord };
2991
+ export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, type AbilitiesMap, type AccountApplication, type AccountApplicationListOptions, type AccountApplicationRegisterOptions, type AccountDelegation, type AccountDelegationListOptions, AccountDelegationPage, AccountDelegationQueryOptions, type AccountDelegationRevokeOptions, type AccountIndexEnsureResult, type AccountIndexRebuildResult, type AccountIndexStatus, type AccountIndexedReadOptions, AccountService, type AccountServiceConfig, type AccountSpace, type AccountSpaceListOptions, type AccountStatus, AutoApproveSpaceCreationHandler, type AutoRejectStrategy, type AutoSignStrategy, type Bytes, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, DEFAULT_DEFAULTS, DEFAULT_EXPIRY, DEFAULT_KNOWLEDGE_ROOT, DEFAULT_LOCAL_NODE_PIN_STORAGE_KEY, DEFAULT_LOCAL_NODE_URL, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DEFAULT_TINYCLOUD_FALLBACK_HOST, DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL, Delegation, DelegationManager, DelegationRevocationReceipt, type DidCacheKeyOptions, type DidEqualsOptions, type DiscoverLocalTinyCloudNodeOptions, type DiscoveredLocalTinyCloudNode, ENCRYPTION_MANIFEST_SPACE, ENCRYPTION_PERMISSION_SERVICE, EXPIRY, type EnsData, EnsDataSchema, type EventEmitterStrategy, type ExpiryTier, type Extension, GenerateShareParams, ICapabilityKeyRegistry, type IENSResolver, type INotificationHandler, type ISessionManager, type ISessionStorage, ISharingService, type ISigner, type ISpace, type ISpaceCreationHandler, type ISpaceScopedDelegations, type ISpaceScopedSharing, type ISpaceService, type IUserAuthorization, type IWasmBindings, IdentityParseError, LOCAL_LINK_HOST_SUFFIX, LOCAL_LINK_PROBE_TIMEOUT_MS, LOCAL_LOOPBACK_PROBE_TIMEOUT_MS, type LocalNodeIdentityStore, type LocationCandidate, type LocationCandidateInput, type LocationRecord, type LocationRecordPayload, type LocationRecordSigner, LocationRecordValidationError, type LocationResolutionAttempt, type LocationSource, type Manifest, type ManifestDefaults, type ManifestKnowledge, type ManifestRegistryRecord, type ManifestSecretActions, ManifestValidationError, type NodeInfo, type OpenKeyCallbackStrategy, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type ResolveCloudLocationOptions, type ResolveTinyCloudHostsOptions, type ResolvedCapabilities, type ResolvedCloudLocation, type ResolvedDelegate, type ResolvedTinyCloudHosts, type ResourceCapability, SECRETS_SPACE, SERVICE_LONG_TO_SHORT, SERVICE_SHORT_TO_LONG, type ServerHost, SessionExpiredError, ShareLink, type SignCallback, type SignInOptions, type SignRequest, type SignResponse, type SignStrategy, SilentNotificationHandler, type SiweConfig, SiweConfigSchema, Space, type SpaceAbilitiesMap, type SpaceConfig, type SpaceCreationContext, type SpaceDelegationParams, type SpaceErrorCode, SpaceErrorCodes, type SpaceHostResult, SpaceInfo, SpaceService, type SpaceServiceConfig, type SubsetCheckResult, TinyCloud, type TinyCloudConfig, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, defaultSignStrategy, defaultSpaceCreationHandler, didCacheKey, didEquals, discoverLocalTinyCloudNode, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, fetchLocationRecord, fetchPeerId, httpUrlToMultiaddr, isCapabilitySubset, isEvmAddress, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, signLocationRecord, submitHostDelegation, validateClientSession, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyLocationRecord };
package/dist/index.js CHANGED
@@ -6360,15 +6360,28 @@ function normalizeSpace(space) {
6360
6360
  function isCapabilitySubset(requested, granted) {
6361
6361
  const missing = [];
6362
6362
  for (const req of requested) {
6363
- const match = granted.find((g) => canonicalizeEntryMatches(req, g));
6364
- if (match === void 0) {
6363
+ const matchingScope = granted.filter(
6364
+ (entry) => canonicalizeEntryScopeMatches(req, entry)
6365
+ );
6366
+ const requestedActions = expandActionShortNames(
6367
+ req.service,
6368
+ req.actions
6369
+ );
6370
+ const grantedActions = matchingScope.flatMap(
6371
+ (entry) => expandActionShortNames(entry.service, entry.actions)
6372
+ );
6373
+ const covered = requestedActions.every(
6374
+ (requestedAction) => grantedActions.some(
6375
+ (grantedAction) => actionContains(grantedAction, requestedAction)
6376
+ )
6377
+ );
6378
+ if (!covered) {
6365
6379
  missing.push(cloneEntry(req));
6366
- continue;
6367
6380
  }
6368
6381
  }
6369
6382
  return { subset: missing.length === 0, missing };
6370
6383
  }
6371
- function canonicalizeEntryMatches(requested, granted) {
6384
+ function canonicalizeEntryScopeMatches(requested, granted) {
6372
6385
  if (requested.service !== granted.service) {
6373
6386
  return false;
6374
6387
  }
@@ -6378,15 +6391,6 @@ function canonicalizeEntryMatches(requested, granted) {
6378
6391
  if (!pathContains2(granted.path, requested.path)) {
6379
6392
  return false;
6380
6393
  }
6381
- const reqActions = new Set(
6382
- expandActionShortNames(requested.service, requested.actions)
6383
- );
6384
- const grantedActions = expandActionShortNames(granted.service, granted.actions);
6385
- for (const a of reqActions) {
6386
- if (!grantedActions.some((grantedAction) => actionContains(grantedAction, a))) {
6387
- return false;
6388
- }
6389
- }
6390
6394
  if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {
6391
6395
  return false;
6392
6396
  }
@@ -9788,6 +9792,10 @@ async function createPolicyEnforcementDelegation(input) {
9788
9792
  spaceId: input.spaceId,
9789
9793
  path: input.path,
9790
9794
  actions: [...input.actions],
9795
+ ...input.decryption === void 0 ? {} : {
9796
+ decryptionNetworkId: input.decryption.networkId,
9797
+ decryptionAction: input.decryption.action
9798
+ },
9791
9799
  contentSourceDigest: input.contentSourceDigest,
9792
9800
  expiresAt: input.expiresAt
9793
9801
  };
@@ -9807,7 +9815,9 @@ function computeOwnerShareRegistrationCid(registration) {
9807
9815
  function validateOwnerSharePolicyRegistration(value, expected) {
9808
9816
  if (cid(expected.policy.bytes) !== expected.policy.cid) throw new Error("submitted owner-share policy bytes do not match its CID");
9809
9817
  const root = assertObject(value, ["registration", "proof"], "owner-share registration response");
9810
- const registration = assertObject(root.registration, ["registrationCid", "policyCid", "ownerDelegationCid", "enforcementDelegationCid", "ownerDid", "shareKeyDid", "enforcerDid", "shareId", "recipientMatcher", "target", "resource", "actions", "contentSource", "contentSourceDigest", "registeredAt", "expiresAt"], "owner-share registration");
9818
+ const rawRegistration = root.registration;
9819
+ const hasDecryption = typeof rawRegistration === "object" && rawRegistration !== null && Object.prototype.hasOwnProperty.call(rawRegistration, "decryption");
9820
+ const registration = assertObject(root.registration, ["registrationCid", "policyCid", "ownerDelegationCid", "enforcementDelegationCid", "ownerDid", "shareKeyDid", "enforcerDid", "shareId", "recipientMatcher", "target", "resource", "actions", ...hasDecryption ? ["decryption"] : [], "contentSource", "contentSourceDigest", "registeredAt", "expiresAt"], "owner-share registration");
9811
9821
  const proof = assertObject(root.proof, ["alg", "kid", "signature"], "owner-share registration proof");
9812
9822
  if (registration.policyCid !== expected.policy.cid || registration.ownerDelegationCid !== expected.ownerDelegation.delegationCid || registration.enforcementDelegationCid !== expected.enforcementDelegation.cid || registration.contentSourceDigest !== expected.contentSourceDigest) throw new Error("owner-share registration is not bound to the submitted chain");
9813
9823
  let policyValue;
@@ -9823,7 +9833,9 @@ function validateOwnerSharePolicyRegistration(value, expected) {
9823
9833
  const registrationTarget = registration.target;
9824
9834
  const registrationResource = registration.resource;
9825
9835
  const enforcementFacts = expected.enforcementDelegation.facts;
9826
- if (typeof target?.origin !== "string" || typeof target.nodeAudience !== "string" || typeof target.enforcerDid !== "string" || typeof target.spaceId !== "string" || typeof resource?.kind !== "string" || !["exact", "prefix"].includes(resource.kind) || typeof resource?.path !== "string" || !Array.isArray(policy.actions) || policy.ownerDid !== registration.ownerDid || policy.shareKeyDid !== registration.shareKeyDid || policy.shareId !== registration.shareId || canonicalizeSignedObjectUnsigned(policy.recipientMatcher) !== canonicalizeSignedObjectUnsigned(registration.recipientMatcher) || target.origin !== registrationTarget.origin || target.nodeAudience !== registrationTarget.nodeAudience || target.enforcerDid !== registration.enforcerDid || target.spaceId !== registrationTarget.spaceId || resource.kind !== registrationResource.kind || resource.path !== registrationResource.path || canonicalizeSignedObjectUnsigned(policy.actions) !== canonicalizeSignedObjectUnsigned(registration.actions) || canonicalizeSignedObjectUnsigned(policy.contentSource) !== canonicalizeSignedObjectUnsigned(registration.contentSource) || policy.expiresAt !== registration.expiresAt || policy.contentSourceDigest !== registration.contentSourceDigest || enforcementFacts.ownerDelegationCid !== registration.ownerDelegationCid || enforcementFacts.policyCid !== registration.policyCid || enforcementFacts.shareKeyDid !== registration.shareKeyDid || enforcementFacts.enforcerDid !== registration.enforcerDid || enforcementFacts.nodeAudience !== registrationTarget.nodeAudience || enforcementFacts.spaceId !== registrationTarget.spaceId || enforcementFacts.path !== registrationResource.path || canonicalizeSignedObjectUnsigned(enforcementFacts.actions) !== canonicalizeSignedObjectUnsigned(registration.actions) || enforcementFacts.expiresAt !== registration.expiresAt) throw new Error("owner-share registration is not bound to the canonical policy");
9836
+ const decryption = policy.decryption;
9837
+ const decryptionMatches = decryption === void 0 ? registration.decryption === void 0 : registration.decryption !== void 0 && canonicalizeSignedObjectUnsigned(decryption) === canonicalizeSignedObjectUnsigned(registration.decryption);
9838
+ if (typeof target?.origin !== "string" || typeof target.nodeAudience !== "string" || typeof target.enforcerDid !== "string" || typeof target.spaceId !== "string" || typeof resource?.kind !== "string" || !["exact", "prefix"].includes(resource.kind) || typeof resource?.path !== "string" || !Array.isArray(policy.actions) || policy.ownerDid !== registration.ownerDid || policy.shareKeyDid !== registration.shareKeyDid || policy.shareId !== registration.shareId || canonicalizeSignedObjectUnsigned(policy.recipientMatcher) !== canonicalizeSignedObjectUnsigned(registration.recipientMatcher) || target.origin !== registrationTarget.origin || target.nodeAudience !== registrationTarget.nodeAudience || target.enforcerDid !== registration.enforcerDid || target.spaceId !== registrationTarget.spaceId || resource.kind !== registrationResource.kind || resource.path !== registrationResource.path || canonicalizeSignedObjectUnsigned(policy.actions) !== canonicalizeSignedObjectUnsigned(registration.actions) || !decryptionMatches || canonicalizeSignedObjectUnsigned(policy.contentSource) !== canonicalizeSignedObjectUnsigned(registration.contentSource) || policy.expiresAt !== registration.expiresAt || policy.contentSourceDigest !== registration.contentSourceDigest || enforcementFacts.ownerDelegationCid !== registration.ownerDelegationCid || enforcementFacts.policyCid !== registration.policyCid || enforcementFacts.shareKeyDid !== registration.shareKeyDid || enforcementFacts.enforcerDid !== registration.enforcerDid || enforcementFacts.nodeAudience !== registrationTarget.nodeAudience || enforcementFacts.spaceId !== registrationTarget.spaceId || enforcementFacts.path !== registrationResource.path || canonicalizeSignedObjectUnsigned(enforcementFacts.actions) !== canonicalizeSignedObjectUnsigned(registration.actions) || enforcementFacts.decryptionNetworkId !== decryption?.networkId || enforcementFacts.decryptionAction !== decryption?.action || enforcementFacts.expiresAt !== registration.expiresAt) throw new Error("owner-share registration is not bound to the canonical policy");
9827
9839
  if (typeof registration.registrationCid !== "string" || typeof registration.expiresAt !== "string" || typeof registration.registeredAt !== "string") throw new Error("owner-share registration timestamps are invalid");
9828
9840
  if (new Date(registration.expiresAt).toISOString() !== registration.expiresAt || Date.parse(registration.expiresAt) <= Date.now()) throw new Error("owner-share registration is expired or non-canonical");
9829
9841
  const { registrationCid: _registrationCid, ...registrationCore } = registration;
@@ -11791,6 +11803,22 @@ var ACCOUNT_SPACES_PATH = "spaces/";
11791
11803
  var AccountService = class {
11792
11804
  constructor(config) {
11793
11805
  this.config = config;
11806
+ /**
11807
+ * Per-account-space memo for {@link ensureAccountIndex}.
11808
+ *
11809
+ * Applying the index migration is a no-op once the schema exists, but the
11810
+ * SQL service still spends two round trips discovering that (create the
11811
+ * migrations table, then read the applied-migration rows). Account bootstrap
11812
+ * touches the index eight times, so without a memo that is ~14 wasted
11813
+ * requests on the cold sign-in path. The in-flight dedupe inside SQLService
11814
+ * never helps here: the node SDK builds a fresh SQLService per
11815
+ * `getAccountDb()` call, so its lock map is always empty.
11816
+ *
11817
+ * Keyed by account space id, so a different account never reuses this entry.
11818
+ * Failures are evicted so a later call retries instead of inheriting a
11819
+ * permanently poisoned result.
11820
+ */
11821
+ this.accountIndexReady = /* @__PURE__ */ new Map();
11794
11822
  this.applications = {
11795
11823
  list: async (options2 = {}) => {
11796
11824
  if (options2.preferIndex) {
@@ -11824,7 +11852,7 @@ var AccountService = class {
11824
11852
  if (!loaded.ok) return accountErr(loaded.error);
11825
11853
  return ok3(applicationFromRecord(key, loaded.data.data));
11826
11854
  },
11827
- register: async (manifest) => {
11855
+ register: async (manifest, options2 = {}) => {
11828
11856
  const manifests = Array.isArray(manifest) ? manifest : [manifest];
11829
11857
  const request = composeManifestRequest(manifests);
11830
11858
  if (request.registryRecords.length === 0) {
@@ -11842,7 +11870,7 @@ var AccountService = class {
11842
11870
  let registered;
11843
11871
  for (const record of request.registryRecords) {
11844
11872
  const manifestHash = hashJson(record.manifests);
11845
- if (await this.indexHasApplicationHash(record.app_id, manifestHash)) {
11873
+ if (!options2.assumeUnregistered && await this.indexHasApplicationHash(record.app_id, manifestHash)) {
11846
11874
  registered = {
11847
11875
  appId: record.app_id,
11848
11876
  manifests: record.manifests,
@@ -12023,6 +12051,7 @@ var AccountService = class {
12023
12051
  const delegations = await this.delegations.list();
12024
12052
  if (!delegations.ok) return delegations;
12025
12053
  const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
12054
+ this.invalidateAccountIndexMemo();
12026
12055
  const schema = await this.ensureAccountIndex(dbResult.data);
12027
12056
  if (!schema.ok) return schema;
12028
12057
  const statements = [
@@ -12422,7 +12451,41 @@ var AccountService = class {
12422
12451
  ]);
12423
12452
  });
12424
12453
  }
12454
+ /**
12455
+ * Apply the account index schema at most once per account space.
12456
+ *
12457
+ * The index is a cache over canonical KV state, and every caller already
12458
+ * tolerates it being absent (`ignoreIndexFailure` / `isMissingIndexError`),
12459
+ * so a memo that is wrong in the "already applied" direction degrades to a
12460
+ * `no such table` read that the caller handles. A memo that is wrong in the
12461
+ * other direction would be a real bug, so failures are never cached.
12462
+ */
12425
12463
  async ensureAccountIndex(db) {
12464
+ const key = this.config.getAccountSpaceId() ?? "";
12465
+ const cached = this.accountIndexReady.get(key);
12466
+ if (cached) return cached;
12467
+ const pending = this.applyAccountIndex(db);
12468
+ this.accountIndexReady.set(key, pending);
12469
+ const evict = () => {
12470
+ if (this.accountIndexReady.get(key) === pending) {
12471
+ this.accountIndexReady.delete(key);
12472
+ }
12473
+ };
12474
+ let settled;
12475
+ try {
12476
+ settled = await pending;
12477
+ } catch (error) {
12478
+ evict();
12479
+ throw error;
12480
+ }
12481
+ if (!settled.ok) evict();
12482
+ return settled;
12483
+ }
12484
+ /** Drop the memo so the next {@link ensureAccountIndex} re-applies the schema. */
12485
+ invalidateAccountIndexMemo() {
12486
+ this.accountIndexReady.delete(this.config.getAccountSpaceId() ?? "");
12487
+ }
12488
+ async applyAccountIndex(db) {
12426
12489
  const migrated = await db.migrations.apply({
12427
12490
  namespace: ACCOUNT_INDEX_NAMESPACE,
12428
12491
  migrations: [