@tinycloud/node-sdk 3.8.0-beta.10 → 3.8.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ReplicationOptions, Manifest, PermissionEntry } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AuthorityRefusal, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, CaveatedDelegationUnsupportedError, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, EncodedShareData, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InvokeFunction, JWK, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVListPage, KVReadThrough, KVReplicaHandle, KVReplicaSpec, KVReplicaStorage, KVReplicationController, KVReplicationDeps, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, LocalGetResult, LocalListResult, LocalReadMeta, LocalReplicaStatus, LocalSyncResult, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedSecretCatalogKey, PendingWriteRecord, PendingWriteState, PendingWriteStore, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PinnedKey, PkhDidParts, PrefixedKVService, ProtocolMismatchError, PurgeTarget, QueryOptions, QueryResponse, ReceiveOptions, RegisterBatchSuccess, RegisterPolicyV3Input, RegisterPolicyV3Receipt, ReplicaAuthorityState, ReplicaCoverage, ReplicaDevice, ReplicaGatedHandle, ReplicaGrantInfo, ReplicaInspectedStatus, ReplicaState, ReplicaStatusEntry, ReplicationAuthority, ReplicationControl, ReplicationEvent, ReplicationIdentity, ReplicationOptions, ReplicationPurgeReport, ReplicationReason, ReplicationScheduler, ResolvedCapabilities, ResolvedDelegate, ResolvedReplicationOptions, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretCatalogEntry, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, disableTinyCloudDebug, enableTinyCloudDebug, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, getTinyCloudDebugLogs, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateManifest } from '@tinycloud/sdk-core';
3
3
  import { _ as __gated_network } from './gated-network-BEF2XSTC.cjs';
4
- import { _ as __authority } from './authority-Rbye1U4o.cjs';
4
+ import { _ as __authority } from './authority-DJ-PE4Xo.cjs';
5
5
  import { _ as __runtime } from './runtime-mRhSu-vJ.cjs';
6
6
  import { ReplicaDenyInput } from '@tinycloud/sdk-services/kv/replication';
7
- export { F as FileSessionStorage, M as MemorySessionStorage, W as WasmKeyProvider, a as WasmKeyProviderConfig, c as createWasmKeyProvider } from './WasmKeyProvider-5Ee7fcAw.cjs';
8
- export { B as BootstrapWarning, C as CreateOwnerDelegationParams, D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, E as EnsureEncryptionNetworkOptions, I as InvalidRestoredSessionError, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, R as RuntimePermissionGrantOptions, S as SecretPermissionHint, e as SecretReadInput, f as SecretReadResult, g as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, i as UnifiedOwnerRootReceipt, j as UnsupportedSessionRestoreError, k as defaultSignStrategy } from './TinyCloudNode-Dy65bxqs.cjs';
7
+ export { F as FileSessionStorage, M as MemorySessionStorage, W as WasmKeyProvider, a as WasmKeyProviderConfig, c as createWasmKeyProvider, i as isAppKeyHostBound } from './WasmKeyProvider-BKCPRC-c.cjs';
8
+ export { B as BootstrapWarning, C as CreateOwnerDelegationParams, D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, E as EnsureEncryptionNetworkOptions, I as InvalidRestoredSessionError, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, O as OpenKeyAuthorizeTinyCloud, e as OwnerDelegationReceipt, P as PreparedOpenKeyAuthorization, R as RuntimePermissionGrantOptions, S as SecretPermissionHint, f as SecretReadInput, g as SecretReadResult, h as SignStrategy, T as TinyCloudNode, i as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, j as UnifiedOwnerRootReceipt, k as UnsupportedSessionRestoreError, l as defaultSignStrategy, w as wireOpenKeyAuthorize } from './TinyCloudNode-BVDUdEcf.cjs';
9
9
  export { C as CompactRuntimeDelegationInput, P as PortableDelegation, R as RuntimeDelegationRejectedError, a as RuntimeDelegationRejection, V as ValidatedRuntimeDelegation, b as activateCompactRuntimeDelegation, c as activateValidatedRuntimeDelegation, d as deserializeDelegation, s as serializeDelegation } from './delegation-Ckc3UETl.cjs';
10
10
  import '@tinycloud/sdk-services';
11
11
  import '@tinycloud/sdk-services/encryption/named-keys';
package/dist/core.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ReplicationOptions, Manifest, PermissionEntry } from '@tinycloud/sdk-core';
2
2
  export { ACCOUNT_REGISTRY_PATH, ACCOUNT_REGISTRY_SPACE, AccountApplication, AccountApplicationListOptions, AccountApplicationRegisterOptions, AccountDelegation, AccountDelegationListOptions, AccountDelegationRevokeOptions, AccountIndexEnsureResult, AccountIndexRebuildResult, AccountIndexStatus, AccountIndexedReadOptions, AccountService, AccountServiceConfig, AccountSpace, AccountSpaceListOptions, AccountStatus, AuthorityRefusal, AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CanonicalAddress, CanonicalParsedNetworkId, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, CaveatedDelegationUnsupportedError, ClientSession, ColumnInfo, ComposeManifestOptions, ComposedManifestRequest, CreateDelegationParams, DEFAULT_MANIFEST_SPACE, DEFAULT_MANIFEST_VERSION, DEFAULT_SIGNED_READ_URL_EXPIRY_MS, DataVaultConfig, DataVaultService, DatabaseHandle, DelegateReceivedShareParams, DelegatedShareAccess, Delegation, DelegationChain, DelegationChainV2, DelegationDirection, DelegationError, DelegationErrorCode, DelegationErrorCodes, DelegationFilters, DelegationManager, DelegationManagerConfig, DelegationRecord, DelegationResult, DidCacheKeyOptions, DidEqualsOptions, DuckDbAction, DuckDbActionType, DuckDbBatchOptions, DuckDbBatchResponse, DuckDbDatabaseHandle, DuckDbExecuteOptions, DuckDbExecuteResponse, DuckDbOptions, DuckDbQueryOptions, DuckDbQueryResponse, DuckDbService, DuckDbServiceConfig, DuckDbStatement, DuckDbValue, EncodedShareData, ExecuteOptions, ExecuteResponse, Extension, FetchFunction, GenerateShareParams, ICapabilityKeyRegistry, IDataVaultService, IDatabaseHandle, IDuckDbDatabaseHandle, IDuckDbService, IENSResolver, IKVService, INotificationHandler, IPrefixedKVService, ISQLService, ISecretsService, ISessionManager, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceCreationHandler, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, IWasmBindings, IdentityParseError, IngestOptions, InvokeFunction, JWK, KVBatchReadResponse, KVCreateSignedReadUrlOptions, KVListPage, KVReadThrough, KVReplicaHandle, KVReplicaSpec, KVReplicaStorage, KVReplicationController, KVReplicationDeps, KVResponse, KVService, KVServiceConfig, KVSignedReadUrlResponse, KeyInfo, KeyProvider, KeyType, LocalGetResult, LocalListResult, LocalReadMeta, LocalReplicaStatus, LocalSyncResult, Manifest, ManifestDefaults, ManifestRegistryRecord, ManifestSecretActions, ManifestValidationError, OpenKeyCallbackStrategy, OpenKeySigningRequestBody, OpenKeySigningResponseBody, OpenKeySigningStrategyOptions, ParsedSecretCatalogKey, PendingWriteRecord, PendingWriteState, PendingWriteStore, PermissionEntry, PermissionNotInManifestError, PersistedSessionData, PinnedKey, PkhDidParts, PrefixedKVService, ProtocolMismatchError, PurgeTarget, QueryOptions, QueryResponse, ReceiveOptions, RegisterBatchSuccess, RegisterPolicyV3Input, RegisterPolicyV3Receipt, ReplicaAuthorityState, ReplicaCoverage, ReplicaDevice, ReplicaGatedHandle, ReplicaGrantInfo, ReplicaInspectedStatus, ReplicaState, ReplicaStatusEntry, ReplicationAuthority, ReplicationControl, ReplicationEvent, ReplicationIdentity, ReplicationOptions, ReplicationPurgeReport, ReplicationReason, ReplicationScheduler, ResolvedCapabilities, ResolvedDelegate, ResolvedReplicationOptions, ResolvedSecretPath, ResourceCapability, SECRET_NAME_RE, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, SecretCatalogEntry, SecretPayload, SecretScopeOptions, SecretsError, SecretsService, ServiceContext, ServiceContextConfig, ServiceSession, SessionExpiredError, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignInOptions, SignRequest, SignResponse, SilentNotificationHandler, Space, SpaceAbilitiesMap, SpaceConfig, SpaceCreationContext, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TelemetryConfig, TelemetryEventHandler, TinyCloud, TinyCloudConfig, TinyCloudDebugEnableOptions, TinyCloudDebugEvent, TinyCloudDebugLevel, TinyCloudDebugLogger, TinyCloudDebugTimer, TinyCloudSession, UnsupportedFeatureError, VAULT_PERMISSION_SERVICE, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultNetworkReadResult, VaultPublicSpaceKVActions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, addressStorageKey, buildSpaceUri, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeSecretScope, checkNodeInfo, clearTinyCloudDebugLogs, composeManifestRequest, createCapabilityKeyRegistry, createOpenKeyCallbackSigningStrategy, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, didCacheKey, didEquals, disableTinyCloudDebug, enableTinyCloudDebug, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, getTinyCloudDebugLogs, installTinyCloudDebugGlobals, isCapabilitySubset, isEvmAddress, loadManifest, makePkhSpaceId, makePublicSpaceId, parseCanonicalNetworkId, parseExpiry, parsePkhDid, parseSecretCatalogKey, parseSpaceUri, pkhDid, principalDid, principalDidEquals, resolveManifest, resolveSecretListPrefix, resolveSecretPath, resourceCapabilitiesToSpaceAbilitiesMap, tinyCloudDebugLogger, validateManifest } from '@tinycloud/sdk-core';
3
3
  import { _ as __gated_network } from './gated-network-BEF2XSTC.js';
4
- import { _ as __authority } from './authority-BQnTX3fI.js';
4
+ import { _ as __authority } from './authority-i22vHbbp.js';
5
5
  import { _ as __runtime } from './runtime-CO4VXnPq.js';
6
6
  import { ReplicaDenyInput } from '@tinycloud/sdk-services/kv/replication';
7
- export { F as FileSessionStorage, M as MemorySessionStorage, W as WasmKeyProvider, a as WasmKeyProviderConfig, c as createWasmKeyProvider } from './WasmKeyProvider-5Ee7fcAw.js';
8
- export { B as BootstrapWarning, C as CreateOwnerDelegationParams, D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, E as EnsureEncryptionNetworkOptions, I as InvalidRestoredSessionError, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, O as OwnerDelegationReceipt, R as RuntimePermissionGrantOptions, S as SecretPermissionHint, e as SecretReadInput, f as SecretReadResult, g as SignStrategy, T as TinyCloudNode, h as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, i as UnifiedOwnerRootReceipt, j as UnsupportedSessionRestoreError, k as defaultSignStrategy } from './TinyCloudNode-DnD-SH6t.js';
7
+ export { F as FileSessionStorage, M as MemorySessionStorage, W as WasmKeyProvider, a as WasmKeyProviderConfig, c as createWasmKeyProvider, i as isAppKeyHostBound } from './WasmKeyProvider-BKCPRC-c.js';
8
+ export { B as BootstrapWarning, C as CreateOwnerDelegationParams, D as DelegateToOptions, a as DelegateToResult, b as DelegatedAccess, E as EnsureEncryptionNetworkOptions, I as InvalidRestoredSessionError, N as NodeEventEmitterStrategy, c as NodeUserAuthorization, d as NodeUserAuthorizationConfig, O as OpenKeyAuthorizeTinyCloud, e as OwnerDelegationReceipt, P as PreparedOpenKeyAuthorization, R as RuntimePermissionGrantOptions, S as SecretPermissionHint, f as SecretReadInput, g as SecretReadResult, h as SignStrategy, T as TinyCloudNode, i as TinyCloudNodeConfig, U as UnifiedOwnerRootInput, j as UnifiedOwnerRootReceipt, k as UnsupportedSessionRestoreError, l as defaultSignStrategy, w as wireOpenKeyAuthorize } from './TinyCloudNode-jMK_2Uj8.js';
9
9
  export { C as CompactRuntimeDelegationInput, P as PortableDelegation, R as RuntimeDelegationRejectedError, a as RuntimeDelegationRejection, V as ValidatedRuntimeDelegation, b as activateCompactRuntimeDelegation, c as activateValidatedRuntimeDelegation, d as deserializeDelegation, s as serializeDelegation } from './delegation-Ckc3UETl.js';
10
10
  import '@tinycloud/sdk-services';
11
11
  import '@tinycloud/sdk-services/encryption/named-keys';
package/dist/core.js CHANGED
@@ -299,6 +299,18 @@ function appKeyHostBinding(domain, appId) {
299
299
  const reversed = labels.reverse().join(".");
300
300
  return appId === reversed || appId.startsWith(`${reversed}.`);
301
301
  }
302
+ function isAppKeyHostBound(keysAppId, origin) {
303
+ if (typeof origin === "string" && !origin.includes("://")) {
304
+ return appKeyHostBinding(origin, keysAppId);
305
+ }
306
+ let url;
307
+ try {
308
+ url = typeof origin === "string" ? new URL(origin) : origin;
309
+ } catch {
310
+ return false;
311
+ }
312
+ return appKeyHostBinding(url.host, keysAppId);
313
+ }
302
314
 
303
315
  // src/replication/authority-sign-in.ts
304
316
  import {
@@ -436,6 +448,7 @@ function cloneAbilitiesMap(actions) {
436
448
  var NodeUserAuthorization = class {
437
449
  constructor(config) {
438
450
  this.activeSessionKeyId = "default";
451
+ this.preparedSessionCounter = 0;
439
452
  /** Incremented by resetSession; a sign-in started earlier publishes nothing. */
440
453
  this.sessionGeneration = 0;
441
454
  /**
@@ -1569,9 +1582,8 @@ var NodeUserAuthorization = class {
1569
1582
  const address = canonicalizeAddress(await this.signer.getAddress());
1570
1583
  const chainId = await this.signer.getChainId();
1571
1584
  await this.refreshNamedKeyFeatureForSignIn(address, chainId);
1572
- const keyId = `session-${Date.now()}`;
1573
- this.sessionManager.renameSessionKeyId(this.activeSessionKeyId, keyId);
1574
- this.activeSessionKeyId = keyId;
1585
+ const keyId = `openkey-session-${Date.now()}-${++this.preparedSessionCounter}`;
1586
+ this.sessionManager.createSessionKey(keyId);
1575
1587
  const jwkString = this.sessionManager.jwk(keyId);
1576
1588
  if (!jwkString) {
1577
1589
  throw new Error("Failed to create session key");
@@ -1652,6 +1664,7 @@ var NodeUserAuthorization = class {
1652
1664
  await this.sessionStorage.save(address, persistedData);
1653
1665
  this._session = clientSession;
1654
1666
  this._tinyCloudSession = tinyCloudSession;
1667
+ this.activeSessionKeyId = keyId;
1655
1668
  this._address = address;
1656
1669
  this._chainId = chainId;
1657
1670
  await this.refreshNodeInfo();
@@ -1698,6 +1711,11 @@ var NodeUserAuthorization = class {
1698
1711
  * @param options Optional overrides for the OpenKey request.
1699
1712
  */
1700
1713
  async signInWithOpenKey(authorizeFn, options) {
1714
+ const pending = await this.prepareOpenKeySignIn(options);
1715
+ return this.completeOpenKeySignIn(pending, authorizeFn(pending.request), options);
1716
+ }
1717
+ /** Finish address, host and SIWE preparation before an approval click. */
1718
+ async prepareOpenKeySignIn(options) {
1701
1719
  refuseCaveated(this.getCapabilityRequest()?.manifests);
1702
1720
  if (options?.host !== void 0) {
1703
1721
  const overrideHost = options.host.trim();
@@ -1709,7 +1727,7 @@ var NodeUserAuthorization = class {
1709
1727
  const signingAddress = canonicalizeAddress(await this.signer.getAddress());
1710
1728
  const signingChainId = await this.signer.getChainId();
1711
1729
  await this.resolveTinyCloudHostsForSignIn(signingAddress, signingChainId);
1712
- const { prepared, keyId, jwk } = await this.prepareSessionForSigning();
1730
+ const { prepared, keyId, jwk, address, chainId } = await this.prepareSessionForSigning();
1713
1731
  const presentation = this.buildPresentationEnvelope(options?.reason);
1714
1732
  const hostHint = this.primaryTinyCloudHost;
1715
1733
  const originalRequest = {
@@ -1721,12 +1739,32 @@ var NodeUserAuthorization = class {
1721
1739
  keyId: options?.openkeyKeyId,
1722
1740
  presentation
1723
1741
  };
1742
+ return {
1743
+ request: originalRequest,
1744
+ prepared,
1745
+ keyId,
1746
+ jwk,
1747
+ address,
1748
+ chainId,
1749
+ generation: this.sessionGeneration,
1750
+ createdAt: Date.now()
1751
+ };
1752
+ }
1753
+ /** Complete a prepared approval. The caller starts authorization before awaiting this method. */
1754
+ async completeOpenKeySignIn(pending, authorization, options) {
1755
+ if (Date.now() - pending.createdAt > 5 * 6e4) {
1756
+ throw new Error("Prepared OpenKey sign-in expired; prepare again");
1757
+ }
1758
+ if (pending.generation !== this.sessionGeneration) {
1759
+ throw new Error("Prepared OpenKey sign-in expired after sign-out");
1760
+ }
1761
+ const { request: originalRequest, prepared, keyId, jwk } = pending;
1724
1762
  let result;
1725
1763
  let signed;
1726
1764
  let signature;
1727
1765
  for (let attempt = 0; ; ) {
1728
1766
  try {
1729
- result ?? (result = await authorizeFn(originalRequest));
1767
+ result ?? (result = await authorization);
1730
1768
  signed = await this.verifyOpenKeyResult(result, prepared);
1731
1769
  signature = result.signature;
1732
1770
  break;
@@ -2147,6 +2185,50 @@ var NodeUserAuthorization = class {
2147
2185
  }
2148
2186
  };
2149
2187
 
2188
+ // src/authorization/openKeyBridge.ts
2189
+ function wireOpenKeyAuthorize(openkey, opts) {
2190
+ return async (input) => {
2191
+ const result = await openkey.authorizeTinyCloud({
2192
+ protocolVersion: 1,
2193
+ siwe: input.siwe,
2194
+ keyId: input.keyId,
2195
+ jwk: input.jwk,
2196
+ host: input.host,
2197
+ // Forward the presentation envelope verbatim — the OpenKey SDK
2198
+ // validates and size-bounds it before use.
2199
+ presentation: input.presentation
2200
+ }, opts);
2201
+ if (result.protocolVersion !== 1) {
2202
+ throw new Error(
2203
+ `wireOpenKeyAuthorize: OpenKey returned unsupported protocolVersion ${result.protocolVersion}`
2204
+ );
2205
+ }
2206
+ if (typeof result.signedMessage !== "string" || !result.signedMessage) {
2207
+ throw new Error(
2208
+ "wireOpenKeyAuthorize: OpenKey returned no signedMessage \u2014 cannot complete a TinyCloud session"
2209
+ );
2210
+ }
2211
+ if (!Array.isArray(result.selectedActionKeys)) {
2212
+ throw new Error(
2213
+ "wireOpenKeyAuthorize: OpenKey returned no selectedActionKeys"
2214
+ );
2215
+ }
2216
+ if (!Array.isArray(result.permissions)) {
2217
+ throw new Error(
2218
+ "wireOpenKeyAuthorize: OpenKey returned no permissions"
2219
+ );
2220
+ }
2221
+ return {
2222
+ protocolVersion: 1,
2223
+ address: result.address,
2224
+ signature: result.signature,
2225
+ signedMessage: result.signedMessage,
2226
+ selectedActionKeys: result.selectedActionKeys,
2227
+ permissions: result.permissions
2228
+ };
2229
+ };
2230
+ }
2231
+
2150
2232
  // src/recordingServiceContext.ts
2151
2233
  import {
2152
2234
  ServiceContext
@@ -3871,6 +3953,7 @@ var _TinyCloudNode = class _TinyCloudNode {
3871
3953
  constructor(config = {}) {
3872
3954
  this.signer = null;
3873
3955
  this.auth = null;
3956
+ this.consumedOpenKeyPendings = /* @__PURE__ */ new WeakSet();
3874
3957
  this.tc = null;
3875
3958
  this._chainId = 1;
3876
3959
  this.replicaPurgeFailedHandlers = /* @__PURE__ */ new Set();
@@ -4811,6 +4894,37 @@ var _TinyCloudNode = class _TinyCloudNode {
4811
4894
  }
4812
4895
  await this.signInWith(() => this.auth.signInWithOpenKey(authorizeFn, options));
4813
4896
  }
4897
+ /** Prepare the OpenKey request before the approval click. */
4898
+ async prepareOpenKeySignIn() {
4899
+ if (!this.signer || !this.tc || !this.auth) {
4900
+ throw new Error("Cannot prepare OpenKey sign-in in session-only mode. Provide a signer in config.");
4901
+ }
4902
+ await this.signOutInFlight;
4903
+ await this.accountRegistryTail;
4904
+ await this.wasmBindings.ensureInitialized?.();
4905
+ return this.auth.prepareOpenKeySignIn();
4906
+ }
4907
+ /** Start OpenKey authorization synchronously, then complete normal session setup. */
4908
+ signInWithPreparedOpenKey(pending, authorizeFn) {
4909
+ if (!this.signer || !this.tc || !this.auth || this.signOutInFlight) {
4910
+ throw new Error("Prepared OpenKey sign-in is unavailable");
4911
+ }
4912
+ if (this.consumedOpenKeyPendings.has(pending)) {
4913
+ throw new Error("Prepared OpenKey sign-in was already used");
4914
+ }
4915
+ if (Date.now() - pending.createdAt > 5 * 6e4) {
4916
+ throw new Error("Prepared OpenKey sign-in expired; prepare again");
4917
+ }
4918
+ this.consumedOpenKeyPendings.add(pending);
4919
+ const authorization = authorizeFn(pending.request);
4920
+ void authorization.catch(() => void 0);
4921
+ return this.signInWith(() => {
4922
+ if (this._address !== pending.address || this._chainId !== pending.chainId) {
4923
+ throw new Error("OpenKey account changed after sign-in preparation");
4924
+ }
4925
+ return this.auth.completeOpenKeySignIn(pending, authorization);
4926
+ });
4927
+ }
4814
4928
  async signInWith(performSignIn) {
4815
4929
  refuseCaveated(this.auth?.capabilityRequest?.manifests);
4816
4930
  const epoch = this.sessionEpoch;
@@ -10319,6 +10433,7 @@ export {
10319
10433
  getNodeReplicationLoaders,
10320
10434
  getTinyCloudDebugLogs,
10321
10435
  installTinyCloudDebugGlobals,
10436
+ isAppKeyHostBound,
10322
10437
  isCapabilitySubset3 as isCapabilitySubset,
10323
10438
  isEvmAddress,
10324
10439
  loadManifest,
@@ -10340,6 +10455,7 @@ export {
10340
10455
  resourceCapabilitiesToSpaceAbilitiesMap2 as resourceCapabilitiesToSpaceAbilitiesMap,
10341
10456
  serializeDelegation,
10342
10457
  tinyCloudDebugLogger2 as tinyCloudDebugLogger,
10343
- validateManifest
10458
+ validateManifest,
10459
+ wireOpenKeyAuthorize
10344
10460
  };
10345
10461
  //# sourceMappingURL=core.js.map