@tinycloud/sdk-core 2.11.1-beta.0 → 3.0.0-beta.1

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
@@ -1543,6 +1543,89 @@ type SignStrategy = AutoSignStrategy | AutoRejectStrategy | CallbackStrategy | E
1543
1543
  */
1544
1544
  declare const defaultSignStrategy: SignStrategy;
1545
1545
 
1546
+ /** OAuth scope which grants a client access to the canonical TinyCloud key. */
1547
+ declare const TINYCLOUD_MANAGE_KEY_SCOPE: "tinycloud:manage-key";
1548
+ /** OIDC claim containing the canonical identity selected by OpenKey. */
1549
+ declare const TINYCLOUD_CANONICAL_IDENTITY_CLAIM: "https://tinycloud.xyz/canonical_identity";
1550
+ /**
1551
+ * Adds the canonical-key scope to an OAuth authorization request. Supplying
1552
+ * this value to the authorization server is the explicit user-consent step;
1553
+ * possession of an unrelated OAuth token is never treated as authority to
1554
+ * sign for the canonical key.
1555
+ */
1556
+ declare function requestTinyCloudManageKeyScope(scopes?: string | readonly string[]): string;
1557
+ /** True only when an OAuth grant explicitly includes `tinycloud:manage-key`. */
1558
+ declare function hasTinyCloudManageKeyScope(scopes: unknown): boolean;
1559
+ /** The one canonical identity an OAuth `tinycloud:manage-key` token may use. */
1560
+ interface CanonicalTinyCloudIdentity {
1561
+ version: "v1";
1562
+ keyId: string;
1563
+ address: CanonicalAddress;
1564
+ chainId: number;
1565
+ did: string;
1566
+ spaceId: string;
1567
+ }
1568
+ type OpenKeyManageKeyErrorCode = "CONSENT_REQUIRED" | "GRANT_DISABLED" | "USER_EXCLUSIVE" | "TOKEN_EXPIRED" | "MESSAGE_REJECTED" | "IDENTITY_MISMATCH" | "SIGNER_UNAVAILABLE";
1569
+ /** A typed denial or recoverable outage from the OAuth canonical-key boundary. */
1570
+ declare class OpenKeyManageKeyError extends Error {
1571
+ readonly code: OpenKeyManageKeyErrorCode;
1572
+ /** A user-visible OAuth recovery location, when the signer provides one. */
1573
+ readonly approvalUrl?: string | undefined;
1574
+ readonly retryable: boolean;
1575
+ constructor(code: OpenKeyManageKeyErrorCode, message: string,
1576
+ /** A user-visible OAuth recovery location, when the signer provides one. */
1577
+ approvalUrl?: string | undefined, retryable?: boolean);
1578
+ }
1579
+ /**
1580
+ * Parse and fail closed on the OpenID canonical identity claim. The DID and
1581
+ * space are derived from the checksummed address instead of trusted
1582
+ * independently. The identity claim chooses its chain and space name; this
1583
+ * shared contract does not impose an application's chain or space.
1584
+ */
1585
+ declare function parseCanonicalTinyCloudIdentity(value: unknown): CanonicalTinyCloudIdentity;
1586
+ /** Parse the canonical identity directly from an OAuth/OIDC claims object. */
1587
+ declare function parseCanonicalTinyCloudIdentityClaims(claims: unknown): CanonicalTinyCloudIdentity;
1588
+ interface OpenKeyManageKeySigningRequestBody {
1589
+ address: string;
1590
+ chainId: number;
1591
+ message: string;
1592
+ type: "siwe";
1593
+ }
1594
+ interface OpenKeyManageKeySigningResponseBody {
1595
+ approved?: boolean;
1596
+ signature?: string;
1597
+ canonicalIdentity?: unknown;
1598
+ code?: string;
1599
+ reason?: string;
1600
+ error?: string;
1601
+ approvalUrl?: string;
1602
+ }
1603
+ /** Minimal fetch surface used by the manage-key signer. */
1604
+ type OpenKeyManageKeyFetch = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
1605
+ interface OpenKeyManageKeySigningStrategyOptions {
1606
+ /** The OpenKey public signer route for a consented OAuth client. */
1607
+ endpoint: string;
1608
+ /** A bearer token obtained with `tinycloud:manage-key` consent. */
1609
+ token: string | (() => string | Promise<string | undefined>);
1610
+ /** OAuth grant scopes returned with the bearer token. */
1611
+ scopes: string | readonly string[];
1612
+ /** Canonical identity parsed from the token's OIDC claims. */
1613
+ identity: CanonicalTinyCloudIdentity;
1614
+ /** Fetch implementation. Defaults to `globalThis.fetch`. */
1615
+ fetch?: OpenKeyManageKeyFetch;
1616
+ }
1617
+ interface OpenKeyManageKeyCallbackStrategy extends CallbackStrategy {
1618
+ /** Lets the SDK avoid bootstrap paths that require broader signing authority. */
1619
+ openKeyAutoSign: true;
1620
+ }
1621
+ /**
1622
+ * Create a client-bound signer for an OAuth token consented for
1623
+ * `tinycloud:manage-key`. It sends exactly one bearer-authenticated, cookie-
1624
+ * free request for the original SIWE string and accepts only the claimed
1625
+ * canonical identity's EIP-191 signature.
1626
+ */
1627
+ declare function createOpenKeyManageKeySigningStrategy(options: OpenKeyManageKeySigningStrategyOptions): OpenKeyManageKeyCallbackStrategy;
1628
+
1546
1629
  /**
1547
1630
  * Space creation handler types for TinyCloud authorization.
1548
1631
  *
@@ -3346,4 +3429,4 @@ declare const EXPIRY: {
3346
3429
  declare const DEFAULT_SIGNED_READ_URL_EXPIRY_MS: number;
3347
3430
  type ExpiryTier = keyof typeof EXPIRY;
3348
3431
 
3349
- 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, CREDENTIAL_ERROR_CODES, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, type CapabilityPresentationEnvelopeV1, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, CredentialError, type CredentialErrorCode, CredentialFlowDescriptor, CredentialHolderBinding, CredentialIssuerMetadata, CredentialRequirement, CredentialStorageReceipt, 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, type ImmutableSiweFields, IssuedCredentialEnvelope, 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, OPENKEY_ACTION_ID_SEPARATOR, 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 RecapAttenuation, type RegisterBatchSuccess, 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, StoredCredentialRecord, type SubsetCheckResult, TinyCloud, type TinyCloudAuthorizationRequestV1, type TinyCloudAuthorizationResultV1, type TinyCloudConfig, type TinyCloudEffectiveGrantV1, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VerifiedCredential, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalDigest, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createHolderBinding, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, createStorageReceipt, createStoredCredentialRecord, credentialEndpointPath, credentialError, credentialIndexKey, credentialMatchesRequirement, credentialRecordKey, credentialRequirementDigest, decodeBase64Url, defaultSignStrategy, defaultSpaceCreationHandler, descriptorSatisfiesRequirement, didCacheKey, didEquals, diffImmutableSiweFields, discoverLocalTinyCloudNode, encodeBase64Url, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, extractImmutableSiweFields, extractRecapAttenuations, fetchLocationRecord, fetchPeerId, holderBindingCanonicalBytes, holderBindingSigningBytes, httpUrlToMultiaddr, isCapabilitySubset, isDigest, isEvmAddress, isPlausibleOpenKeyActionId, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseCanonicalRecapResource, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, sha256Base64Url, signLocationRecord, submitHostDelegation, unauthorizedRecapCapabilities, validateAuthorizationResultV1, validateClientSession, validateCredentialFlowDescriptor, validateCredentialHolderBinding, validateCredentialRequirement, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyEip191MessageSignature, verifyIssuedCredential, verifyLocationRecord, verifyStorageReceipt };
3432
+ 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, CREDENTIAL_ERROR_CODES, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, type CanonicalTinyCloudIdentity, type CapabilityPresentationEnvelopeV1, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, CredentialError, type CredentialErrorCode, CredentialFlowDescriptor, CredentialHolderBinding, CredentialIssuerMetadata, CredentialRequirement, CredentialStorageReceipt, 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, type ImmutableSiweFields, IssuedCredentialEnvelope, 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, OPENKEY_ACTION_ID_SEPARATOR, type OpenKeyCallbackStrategy, type OpenKeyManageKeyCallbackStrategy, OpenKeyManageKeyError, type OpenKeyManageKeyErrorCode, type OpenKeyManageKeyFetch, type OpenKeyManageKeySigningRequestBody, type OpenKeyManageKeySigningResponseBody, type OpenKeyManageKeySigningStrategyOptions, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type RecapAttenuation, type RegisterBatchSuccess, 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, StoredCredentialRecord, type SubsetCheckResult, TINYCLOUD_CANONICAL_IDENTITY_CLAIM, TINYCLOUD_MANAGE_KEY_SCOPE, TinyCloud, type TinyCloudAuthorizationRequestV1, type TinyCloudAuthorizationResultV1, type TinyCloudConfig, type TinyCloudEffectiveGrantV1, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VerifiedCredential, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalDigest, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createHolderBinding, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createOpenKeyManageKeySigningStrategy, createSpaceService, createStorageReceipt, createStoredCredentialRecord, credentialEndpointPath, credentialError, credentialIndexKey, credentialMatchesRequirement, credentialRecordKey, credentialRequirementDigest, decodeBase64Url, defaultSignStrategy, defaultSpaceCreationHandler, descriptorSatisfiesRequirement, didCacheKey, didEquals, diffImmutableSiweFields, discoverLocalTinyCloudNode, encodeBase64Url, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, extractImmutableSiweFields, extractRecapAttenuations, fetchLocationRecord, fetchPeerId, hasTinyCloudManageKeyScope, holderBindingCanonicalBytes, holderBindingSigningBytes, httpUrlToMultiaddr, isCapabilitySubset, isDigest, isEvmAddress, isPlausibleOpenKeyActionId, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseCanonicalRecapResource, parseCanonicalTinyCloudIdentity, parseCanonicalTinyCloudIdentityClaims, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, requestTinyCloudManageKeyScope, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, sha256Base64Url, signLocationRecord, submitHostDelegation, unauthorizedRecapCapabilities, validateAuthorizationResultV1, validateClientSession, validateCredentialFlowDescriptor, validateCredentialHolderBinding, validateCredentialRequirement, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyEip191MessageSignature, verifyIssuedCredential, verifyLocationRecord, verifyStorageReceipt };
package/dist/index.d.ts CHANGED
@@ -1543,6 +1543,89 @@ type SignStrategy = AutoSignStrategy | AutoRejectStrategy | CallbackStrategy | E
1543
1543
  */
1544
1544
  declare const defaultSignStrategy: SignStrategy;
1545
1545
 
1546
+ /** OAuth scope which grants a client access to the canonical TinyCloud key. */
1547
+ declare const TINYCLOUD_MANAGE_KEY_SCOPE: "tinycloud:manage-key";
1548
+ /** OIDC claim containing the canonical identity selected by OpenKey. */
1549
+ declare const TINYCLOUD_CANONICAL_IDENTITY_CLAIM: "https://tinycloud.xyz/canonical_identity";
1550
+ /**
1551
+ * Adds the canonical-key scope to an OAuth authorization request. Supplying
1552
+ * this value to the authorization server is the explicit user-consent step;
1553
+ * possession of an unrelated OAuth token is never treated as authority to
1554
+ * sign for the canonical key.
1555
+ */
1556
+ declare function requestTinyCloudManageKeyScope(scopes?: string | readonly string[]): string;
1557
+ /** True only when an OAuth grant explicitly includes `tinycloud:manage-key`. */
1558
+ declare function hasTinyCloudManageKeyScope(scopes: unknown): boolean;
1559
+ /** The one canonical identity an OAuth `tinycloud:manage-key` token may use. */
1560
+ interface CanonicalTinyCloudIdentity {
1561
+ version: "v1";
1562
+ keyId: string;
1563
+ address: CanonicalAddress;
1564
+ chainId: number;
1565
+ did: string;
1566
+ spaceId: string;
1567
+ }
1568
+ type OpenKeyManageKeyErrorCode = "CONSENT_REQUIRED" | "GRANT_DISABLED" | "USER_EXCLUSIVE" | "TOKEN_EXPIRED" | "MESSAGE_REJECTED" | "IDENTITY_MISMATCH" | "SIGNER_UNAVAILABLE";
1569
+ /** A typed denial or recoverable outage from the OAuth canonical-key boundary. */
1570
+ declare class OpenKeyManageKeyError extends Error {
1571
+ readonly code: OpenKeyManageKeyErrorCode;
1572
+ /** A user-visible OAuth recovery location, when the signer provides one. */
1573
+ readonly approvalUrl?: string | undefined;
1574
+ readonly retryable: boolean;
1575
+ constructor(code: OpenKeyManageKeyErrorCode, message: string,
1576
+ /** A user-visible OAuth recovery location, when the signer provides one. */
1577
+ approvalUrl?: string | undefined, retryable?: boolean);
1578
+ }
1579
+ /**
1580
+ * Parse and fail closed on the OpenID canonical identity claim. The DID and
1581
+ * space are derived from the checksummed address instead of trusted
1582
+ * independently. The identity claim chooses its chain and space name; this
1583
+ * shared contract does not impose an application's chain or space.
1584
+ */
1585
+ declare function parseCanonicalTinyCloudIdentity(value: unknown): CanonicalTinyCloudIdentity;
1586
+ /** Parse the canonical identity directly from an OAuth/OIDC claims object. */
1587
+ declare function parseCanonicalTinyCloudIdentityClaims(claims: unknown): CanonicalTinyCloudIdentity;
1588
+ interface OpenKeyManageKeySigningRequestBody {
1589
+ address: string;
1590
+ chainId: number;
1591
+ message: string;
1592
+ type: "siwe";
1593
+ }
1594
+ interface OpenKeyManageKeySigningResponseBody {
1595
+ approved?: boolean;
1596
+ signature?: string;
1597
+ canonicalIdentity?: unknown;
1598
+ code?: string;
1599
+ reason?: string;
1600
+ error?: string;
1601
+ approvalUrl?: string;
1602
+ }
1603
+ /** Minimal fetch surface used by the manage-key signer. */
1604
+ type OpenKeyManageKeyFetch = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
1605
+ interface OpenKeyManageKeySigningStrategyOptions {
1606
+ /** The OpenKey public signer route for a consented OAuth client. */
1607
+ endpoint: string;
1608
+ /** A bearer token obtained with `tinycloud:manage-key` consent. */
1609
+ token: string | (() => string | Promise<string | undefined>);
1610
+ /** OAuth grant scopes returned with the bearer token. */
1611
+ scopes: string | readonly string[];
1612
+ /** Canonical identity parsed from the token's OIDC claims. */
1613
+ identity: CanonicalTinyCloudIdentity;
1614
+ /** Fetch implementation. Defaults to `globalThis.fetch`. */
1615
+ fetch?: OpenKeyManageKeyFetch;
1616
+ }
1617
+ interface OpenKeyManageKeyCallbackStrategy extends CallbackStrategy {
1618
+ /** Lets the SDK avoid bootstrap paths that require broader signing authority. */
1619
+ openKeyAutoSign: true;
1620
+ }
1621
+ /**
1622
+ * Create a client-bound signer for an OAuth token consented for
1623
+ * `tinycloud:manage-key`. It sends exactly one bearer-authenticated, cookie-
1624
+ * free request for the original SIWE string and accepts only the claimed
1625
+ * canonical identity's EIP-191 signature.
1626
+ */
1627
+ declare function createOpenKeyManageKeySigningStrategy(options: OpenKeyManageKeySigningStrategyOptions): OpenKeyManageKeyCallbackStrategy;
1628
+
1546
1629
  /**
1547
1630
  * Space creation handler types for TinyCloud authorization.
1548
1631
  *
@@ -3346,4 +3429,4 @@ declare const EXPIRY: {
3346
3429
  declare const DEFAULT_SIGNED_READ_URL_EXPIRY_MS: number;
3347
3430
  type ExpiryTier = keyof typeof EXPIRY;
3348
3431
 
3349
- 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, CREDENTIAL_ERROR_CODES, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, type CapabilityPresentationEnvelopeV1, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, CredentialError, type CredentialErrorCode, CredentialFlowDescriptor, CredentialHolderBinding, CredentialIssuerMetadata, CredentialRequirement, CredentialStorageReceipt, 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, type ImmutableSiweFields, IssuedCredentialEnvelope, 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, OPENKEY_ACTION_ID_SEPARATOR, 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 RecapAttenuation, type RegisterBatchSuccess, 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, StoredCredentialRecord, type SubsetCheckResult, TinyCloud, type TinyCloudAuthorizationRequestV1, type TinyCloudAuthorizationResultV1, type TinyCloudConfig, type TinyCloudEffectiveGrantV1, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VerifiedCredential, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalDigest, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createHolderBinding, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createSpaceService, createStorageReceipt, createStoredCredentialRecord, credentialEndpointPath, credentialError, credentialIndexKey, credentialMatchesRequirement, credentialRecordKey, credentialRequirementDigest, decodeBase64Url, defaultSignStrategy, defaultSpaceCreationHandler, descriptorSatisfiesRequirement, didCacheKey, didEquals, diffImmutableSiweFields, discoverLocalTinyCloudNode, encodeBase64Url, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, extractImmutableSiweFields, extractRecapAttenuations, fetchLocationRecord, fetchPeerId, holderBindingCanonicalBytes, holderBindingSigningBytes, httpUrlToMultiaddr, isCapabilitySubset, isDigest, isEvmAddress, isPlausibleOpenKeyActionId, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseCanonicalRecapResource, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, sha256Base64Url, signLocationRecord, submitHostDelegation, unauthorizedRecapCapabilities, validateAuthorizationResultV1, validateClientSession, validateCredentialFlowDescriptor, validateCredentialHolderBinding, validateCredentialRequirement, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyEip191MessageSignature, verifyIssuedCredential, verifyLocationRecord, verifyStorageReceipt };
3432
+ 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, CREDENTIAL_ERROR_CODES, type CallbackStrategy, type CanonicalAddress, type CanonicalParsedNetworkId, type CanonicalTinyCloudIdentity, type CapabilityPresentationEnvelopeV1, CaveatedDelegationUnsupportedError, type ClientSession, ClientSessionSchema, CloudLocationResolutionError, type ComposeManifestOptions, type ComposedManifestRequest, type CreateDelegationFunction, CreateDelegationParams, CredentialError, type CredentialErrorCode, CredentialFlowDescriptor, CredentialHolderBinding, CredentialIssuerMetadata, CredentialRequirement, CredentialStorageReceipt, 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, type ImmutableSiweFields, IssuedCredentialEnvelope, 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, OPENKEY_ACTION_ID_SEPARATOR, type OpenKeyCallbackStrategy, type OpenKeyManageKeyCallbackStrategy, OpenKeyManageKeyError, type OpenKeyManageKeyErrorCode, type OpenKeyManageKeyFetch, type OpenKeyManageKeySigningRequestBody, type OpenKeyManageKeySigningResponseBody, type OpenKeyManageKeySigningStrategyOptions, type OpenKeySigningRequestBody, type OpenKeySigningResponseBody, type OpenKeySigningStrategyOptions, type ParseRecapFromSiwe, type PartialSiweMessage, type PermissionEntry, PermissionNotInManifestError, type PersistedSessionData, type PersistedSessionProof, type PersistedTinyCloudSession, type PkhDidParts, ProtocolMismatchError, type RecapAttenuation, type RegisterBatchSuccess, 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, StoredCredentialRecord, type SubsetCheckResult, TINYCLOUD_CANONICAL_IDENTITY_CLAIM, TINYCLOUD_MANAGE_KEY_SCOPE, TinyCloud, type TinyCloudAuthorizationRequestV1, type TinyCloudAuthorizationResultV1, type TinyCloudConfig, type TinyCloudEffectiveGrantV1, type TinyCloudSession, UnsupportedFeatureError, type UserAuthorizationConfig, VAULT_PERMISSION_SERVICE, type ValidatedPersistedSessionProof, type ValidationError, VerifiedCredential, VersionCheckError, type WasmRecapEntry, type WebStorageLike, actionContains, activateSessionWithHost, addressStorageKey, applyPrefix, buildSpaceUri, canonicalDigest, canonicalLocationPayload, canonicalizeAddress, canonicalizeDid, canonicalizeDidUrl, canonicalizeNetworkId, canonicalizeRecapCaveats, checkNodeInfo, composeManifestRequest, createHolderBinding, createInMemoryLocalNodeIdentityStore, createLocalStorageLocalNodeIdentityStore, createOpenKeyCallbackSigningStrategy, createOpenKeyManageKeySigningStrategy, createSpaceService, createStorageReceipt, createStoredCredentialRecord, credentialEndpointPath, credentialError, credentialIndexKey, credentialMatchesRequirement, credentialRecordKey, credentialRequirementDigest, decodeBase64Url, defaultSignStrategy, defaultSpaceCreationHandler, descriptorSatisfiesRequirement, didCacheKey, didEquals, diffImmutableSiweFields, discoverLocalTinyCloudNode, encodeBase64Url, expandActionShortNames, expandPermissionEntries, expandPermissionEntry, extractImmutableSiweFields, extractRecapAttenuations, fetchLocationRecord, fetchPeerId, hasTinyCloudManageKeyScope, holderBindingCanonicalBytes, holderBindingSigningBytes, httpUrlToMultiaddr, isCapabilitySubset, isDigest, isEvmAddress, isPlausibleOpenKeyActionId, loadManifest, locationPayloadForRecord, makePkhSpaceId, makePublicSpaceId, manifestAbilitiesUnion, multiaddrToHttpUrl, normalizeDefaults, parseCanonicalNetworkId, parseCanonicalRecapResource, parseCanonicalTinyCloudIdentity, parseCanonicalTinyCloudIdentityClaims, parseExpiry, parsePkhDid, parseRecapCapabilities, parseSpaceUri, pkhDid, principalDid, principalDidEquals, recapCaveatsEqual, requestTinyCloudManageKeyScope, resolveCloudLocation, resolveManifest, resolveManifestKnowledgeRoot, resolveTinyCloudHosts, resourceCapabilitiesToAbilitiesMap, resourceCapabilitiesToSpaceAbilitiesMap, sha256Base64Url, signLocationRecord, submitHostDelegation, unauthorizedRecapCapabilities, validateAuthorizationResultV1, validateClientSession, validateCredentialFlowDescriptor, validateCredentialHolderBinding, validateCredentialRequirement, validateLocationRecord, validateLocationRecordPayload, validateManifest, validatePersistedSessionData, verifyDidKeyEd25519Signature, verifyEip191MessageSignature, verifyIssuedCredential, verifyLocationRecord, verifyStorageReceipt };
package/dist/index.js CHANGED
@@ -15048,6 +15048,236 @@ function createOpenKeyCallbackSigningStrategy(options2) {
15048
15048
  }
15049
15049
  var defaultSignStrategy = { type: "auto-sign" };
15050
15050
 
15051
+ // src/authorization/manage-key.ts
15052
+ var TINYCLOUD_MANAGE_KEY_SCOPE = "tinycloud:manage-key";
15053
+ var TINYCLOUD_CANONICAL_IDENTITY_CLAIM = "https://tinycloud.xyz/canonical_identity";
15054
+ function requestTinyCloudManageKeyScope(scopes = []) {
15055
+ const requested = typeof scopes === "string" ? scopes.split(/\s+/u) : scopes;
15056
+ return [
15057
+ ...new Set([...requested, TINYCLOUD_MANAGE_KEY_SCOPE].filter(Boolean))
15058
+ ].sort().join(" ");
15059
+ }
15060
+ function hasTinyCloudManageKeyScope(scopes) {
15061
+ const values = Array.isArray(scopes) ? scopes : typeof scopes === "string" ? scopes.split(/\s+/u) : [];
15062
+ return values.includes(TINYCLOUD_MANAGE_KEY_SCOPE);
15063
+ }
15064
+ var OpenKeyManageKeyError = class extends Error {
15065
+ constructor(code3, message, approvalUrl, retryable = false) {
15066
+ super(message);
15067
+ this.code = code3;
15068
+ this.approvalUrl = approvalUrl;
15069
+ this.retryable = retryable;
15070
+ this.name = "OpenKeyManageKeyError";
15071
+ }
15072
+ };
15073
+ function isRecord2(value) {
15074
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15075
+ }
15076
+ function rejected(message) {
15077
+ return new OpenKeyManageKeyError("MESSAGE_REJECTED", message);
15078
+ }
15079
+ function identityMismatch(message) {
15080
+ return new OpenKeyManageKeyError("IDENTITY_MISMATCH", message);
15081
+ }
15082
+ function parseCanonicalTinyCloudIdentity(value) {
15083
+ if (!isRecord2(value))
15084
+ throw rejected("Canonical TinyCloud identity is missing");
15085
+ const expectedKeys = [
15086
+ "address",
15087
+ "chainId",
15088
+ "did",
15089
+ "keyId",
15090
+ "spaceId",
15091
+ "version"
15092
+ ];
15093
+ const actualKeys = Object.keys(value).sort();
15094
+ if (actualKeys.length !== expectedKeys.length || actualKeys.some((key, index) => key !== expectedKeys[index])) {
15095
+ throw rejected("Canonical TinyCloud identity has an invalid shape");
15096
+ }
15097
+ if (value.version !== "v1")
15098
+ throw rejected("Canonical TinyCloud identity version is unsupported");
15099
+ if (typeof value.keyId !== "string" || value.keyId.trim() === "") {
15100
+ throw rejected("Canonical TinyCloud identity key ID is invalid");
15101
+ }
15102
+ if (typeof value.address !== "string") {
15103
+ throw rejected("Canonical TinyCloud identity address is invalid");
15104
+ }
15105
+ let address;
15106
+ try {
15107
+ address = canonicalizeAddress(value.address);
15108
+ } catch {
15109
+ throw rejected("Canonical TinyCloud identity address is invalid");
15110
+ }
15111
+ if (address !== value.address) {
15112
+ throw rejected(
15113
+ "Canonical TinyCloud identity address must use EIP-55 checksum casing"
15114
+ );
15115
+ }
15116
+ if (typeof value.chainId !== "number" || !Number.isSafeInteger(value.chainId) || value.chainId <= 0) {
15117
+ throw rejected("Canonical TinyCloud identity chain ID is invalid");
15118
+ }
15119
+ const did = pkhDid(address, value.chainId);
15120
+ const spacePrefix = `tinycloud:pkh:eip155:${value.chainId}:${address}:`;
15121
+ if (typeof value.spaceId !== "string" || !value.spaceId.startsWith(spacePrefix)) {
15122
+ throw rejected("Canonical TinyCloud identity space is invalid");
15123
+ }
15124
+ const spaceName = value.spaceId.slice(spacePrefix.length);
15125
+ let spaceId;
15126
+ try {
15127
+ spaceId = makePkhSpaceId(address, value.chainId, spaceName);
15128
+ } catch {
15129
+ throw rejected("Canonical TinyCloud identity space is invalid");
15130
+ }
15131
+ if (value.did !== did || value.spaceId !== spaceId) {
15132
+ throw rejected("Canonical TinyCloud identity does not match its address");
15133
+ }
15134
+ return {
15135
+ version: "v1",
15136
+ keyId: value.keyId,
15137
+ address,
15138
+ chainId: value.chainId,
15139
+ did,
15140
+ spaceId
15141
+ };
15142
+ }
15143
+ function parseCanonicalTinyCloudIdentityClaims(claims) {
15144
+ if (!isRecord2(claims)) throw rejected("OAuth claims are missing");
15145
+ return parseCanonicalTinyCloudIdentity(
15146
+ claims[TINYCLOUD_CANONICAL_IDENTITY_CLAIM]
15147
+ );
15148
+ }
15149
+ function identitiesEqual(left, right) {
15150
+ return left.version === right.version && left.keyId === right.keyId && left.address === right.address && left.chainId === right.chainId && left.did === right.did && left.spaceId === right.spaceId;
15151
+ }
15152
+ function errorForResponse(body, status) {
15153
+ const message = body?.reason ?? body?.error ?? `OpenKey manage-key signing failed with HTTP ${status}`;
15154
+ switch (body?.code ?? body?.error) {
15155
+ case "missing_scope":
15156
+ case "consent_required":
15157
+ return new OpenKeyManageKeyError("CONSENT_REQUIRED", message, body?.approvalUrl);
15158
+ case "client_disabled":
15159
+ case "signing_disabled":
15160
+ case "grant_disabled":
15161
+ return new OpenKeyManageKeyError("GRANT_DISABLED", message, body?.approvalUrl);
15162
+ case "user_exclusive":
15163
+ return new OpenKeyManageKeyError("USER_EXCLUSIVE", message, body?.approvalUrl);
15164
+ case "token_expired":
15165
+ case "token_too_old":
15166
+ case "invalid_token":
15167
+ case "expired_token":
15168
+ return new OpenKeyManageKeyError("TOKEN_EXPIRED", message, body?.approvalUrl);
15169
+ case "canonical_key_unavailable":
15170
+ case "signer_failed":
15171
+ return new OpenKeyManageKeyError(
15172
+ "SIGNER_UNAVAILABLE",
15173
+ "The canonical key signer is temporarily unavailable",
15174
+ void 0,
15175
+ true
15176
+ );
15177
+ default:
15178
+ return new OpenKeyManageKeyError(
15179
+ status === 401 ? "TOKEN_EXPIRED" : "MESSAGE_REJECTED",
15180
+ message,
15181
+ body?.approvalUrl
15182
+ );
15183
+ }
15184
+ }
15185
+ async function resolveToken(token) {
15186
+ const value = typeof token === "function" ? await token() : token;
15187
+ if (typeof value !== "string" || value.trim() === "") {
15188
+ throw new OpenKeyManageKeyError(
15189
+ "CONSENT_REQUIRED",
15190
+ "A manage-key OAuth bearer token is required"
15191
+ );
15192
+ }
15193
+ return value;
15194
+ }
15195
+ function normalizeEndpoint(value) {
15196
+ let endpoint;
15197
+ try {
15198
+ endpoint = new URL(value);
15199
+ } catch {
15200
+ throw rejected("OpenKey manage-key signing endpoint must be an absolute URL");
15201
+ }
15202
+ const rawHttpAuthority = value.match(/^http:\/\/([^/?#]*)/iu)?.[1];
15203
+ const loopback = rawHttpAuthority !== void 0 && /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/u.test(rawHttpAuthority);
15204
+ if (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && loopback) || endpoint.username !== "" || endpoint.password !== "" || endpoint.search !== "" || endpoint.hash !== "") {
15205
+ throw rejected("OpenKey manage-key signing endpoint must use HTTPS or exact loopback HTTP");
15206
+ }
15207
+ return endpoint.href;
15208
+ }
15209
+ function assertSignInRequest(request, identity3) {
15210
+ if (request.type !== "siwe" || request.purpose !== "sign-in" || request.chainId !== identity3.chainId || request.address !== identity3.address || typeof request.message !== "string" || request.message.length === 0) {
15211
+ throw rejected(
15212
+ "Manage-key signing only permits the canonical sign-in SIWE request"
15213
+ );
15214
+ }
15215
+ }
15216
+ function createOpenKeyManageKeySigningStrategy(options2) {
15217
+ const identity3 = parseCanonicalTinyCloudIdentity(options2.identity);
15218
+ const endpoint = normalizeEndpoint(options2.endpoint);
15219
+ return {
15220
+ type: "callback",
15221
+ openKeyAutoSign: true,
15222
+ handler: async (request) => {
15223
+ assertSignInRequest(request, identity3);
15224
+ const fetchImpl = options2.fetch ?? globalThis.fetch;
15225
+ if (!fetchImpl)
15226
+ throw rejected("OpenKey manage-key signing requires fetch");
15227
+ if (!hasTinyCloudManageKeyScope(options2.scopes)) {
15228
+ throw new OpenKeyManageKeyError(
15229
+ "CONSENT_REQUIRED",
15230
+ "The OAuth bearer token was not granted tinycloud:manage-key"
15231
+ );
15232
+ }
15233
+ const token = await resolveToken(options2.token);
15234
+ const response = await fetchImpl(endpoint, {
15235
+ method: "POST",
15236
+ credentials: "omit",
15237
+ headers: {
15238
+ authorization: `Bearer ${token}`,
15239
+ "content-type": "application/json"
15240
+ },
15241
+ body: JSON.stringify({
15242
+ address: request.address,
15243
+ chainId: request.chainId,
15244
+ message: request.message,
15245
+ type: "siwe"
15246
+ })
15247
+ });
15248
+ let body;
15249
+ try {
15250
+ const value = await response.json();
15251
+ body = isRecord2(value) ? value : void 0;
15252
+ } catch {
15253
+ body = void 0;
15254
+ }
15255
+ if (!response.ok || body?.approved !== true)
15256
+ throw errorForResponse(body, response.status);
15257
+ if (typeof body.signature !== "string")
15258
+ throw rejected("OpenKey manage-key signer did not return a signature");
15259
+ const responseIdentity = parseCanonicalTinyCloudIdentity(
15260
+ body.canonicalIdentity
15261
+ );
15262
+ if (!identitiesEqual(identity3, responseIdentity)) {
15263
+ throw identityMismatch(
15264
+ "OpenKey manage-key signer returned a different canonical identity"
15265
+ );
15266
+ }
15267
+ if (!await verifyEip191MessageSignature(
15268
+ request.message,
15269
+ body.signature,
15270
+ identity3.address
15271
+ )) {
15272
+ throw rejected(
15273
+ "OpenKey manage-key signer returned an invalid signature"
15274
+ );
15275
+ }
15276
+ return { approved: true, signature: body.signature };
15277
+ }
15278
+ };
15279
+ }
15280
+
15051
15281
  // src/authorization/spaceCreation.ts
15052
15282
  var AutoApproveSpaceCreationHandler = class {
15053
15283
  /**
@@ -17816,6 +18046,7 @@ export {
17816
18046
  NETWORK_NAME_PATTERN,
17817
18047
  NetworkIdError,
17818
18048
  OPENKEY_ACTION_ID_SEPARATOR,
18049
+ OpenKeyManageKeyError,
17819
18050
  POLICY_CAPABILITY_V1_DOMAIN,
17820
18051
  POLICY_CAPABILITY_V1_SCHEMA,
17821
18052
  POLICY_CREDENTIAL_REQUIREMENT_V1_TYPE,
@@ -17886,7 +18117,9 @@ export {
17886
18117
  SpaceService,
17887
18118
  TINYCLOUD_ACCOUNT_SPACE_MANIFEST,
17888
18119
  TINYCLOUD_APPLICATIONS_SPACE_MANIFEST,
18120
+ TINYCLOUD_CANONICAL_IDENTITY_CLAIM,
17889
18121
  TINYCLOUD_DEFAULT_SPACE_MANIFEST,
18122
+ TINYCLOUD_MANAGE_KEY_SCOPE,
17890
18123
  TINYCLOUD_PUBLIC_SPACE_MANIFEST,
17891
18124
  TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,
17892
18125
  TinyCloud,
@@ -17947,6 +18180,7 @@ export {
17947
18180
  createInMemoryLocalNodeIdentityStore,
17948
18181
  createLocalStorageLocalNodeIdentityStore,
17949
18182
  createOpenKeyCallbackSigningStrategy,
18183
+ createOpenKeyManageKeySigningStrategy,
17950
18184
  createPolicyEnforcementDelegation,
17951
18185
  createShareArtifact,
17952
18186
  createShareArtifactAsync,
@@ -18005,6 +18239,7 @@ export {
18005
18239
  generateRandomReceiverKey,
18006
18240
  getPolicyRootStatusV3,
18007
18241
  getTinyCloudDebugLogs,
18242
+ hasTinyCloudManageKeyScope,
18008
18243
  hexDecode,
18009
18244
  hexEncode,
18010
18245
  holderBindingCanonicalBytes,
@@ -18037,6 +18272,8 @@ export {
18037
18272
  openWrappedKey,
18038
18273
  parseCanonicalNetworkId,
18039
18274
  parseCanonicalRecapResource,
18275
+ parseCanonicalTinyCloudIdentity,
18276
+ parseCanonicalTinyCloudIdentityClaims,
18040
18277
  parseCompactUcanAuthorization,
18041
18278
  parseExpiry,
18042
18279
  parseNetworkId2 as parseNetworkId,
@@ -18059,6 +18296,7 @@ export {
18059
18296
  projectUnifiedPolicyCapability,
18060
18297
  recapCaveatsEqual,
18061
18298
  renewPolicyRootStatusV3,
18299
+ requestTinyCloudManageKeyScope,
18062
18300
  resolveCloudLocation,
18063
18301
  resolveManifest,
18064
18302
  resolveManifestKnowledgeRoot,