/**
 * Enbox Connect Protocol
 *
 * A capability delegation protocol for DWN access. Enables apps to request
 * scoped permission grants from a wallet (provider), receiving a delegate DID
 * with the granted permissions.
 *
 * Two transport modes:
 * - Local (`dwn://connect`): same-device, direct HTTP against the local DWN
 * - Remote (`enbox://connect`): cross-device, relay-mediated with QR/deep link
 *
 * The protocol uses JWTs for signing, JWE (XChaCha20-Poly1305) for encryption,
 * and ECDH (Ed25519 → X25519 + HKDF) for key agreement.
 */
import type { EnboxPlatformAgent } from './types/agent.js';
import type { RequireOnly } from '@enbox/common';
import type { BearerDid, DidDocument, PortableDid } from '@enbox/dids';
import type { ConnectSessionMetadata, ConnectSessionTransport, DwnDataEncodedRecordsWriteMessage, DwnPermissionScope, DwnProtocolDefinition } from './types/dwn.js';
import type { Jwk } from '@enbox/crypto';
/**
 * The protocols of permissions requested, along with the definition and permission scopes for each protocol.
 */
export type ConnectPermissionRequest = {
    /**
     * The definition of the protocol the permissions are being requested for.
     * In the event that the protocol is not already installed, the wallet will install this given protocol definition.
     */
    protocolDefinition: DwnProtocolDefinition;
    /** The scope of the permissions being requested for the given protocol */
    permissionScopes: DwnPermissionScope[];
};
/**
 * Client/environment details captured by the connect client for wallet session display.
 *
 * This data is self-reported by the requester, unauthenticated, and intended
 * only as display hints. Wallets must not treat it as verified app identity.
 */
export type ConnectClientMetadata = {
    /** Origin of the requesting app, when known. */
    origin?: string;
    /** Browser user agent string, when available. */
    userAgent?: string;
    /** Platform/device hint, when available. */
    platform?: string;
    /** Primary language, when available. */
    language?: string;
    /** Language preference list, when available. */
    languages?: string[];
    /** IANA timezone, when available. */
    timezone?: string;
};
export type CreateConnectSessionMetadataOptions = {
    id?: string;
    appName?: string;
    appIcon?: string;
    clientMetadata?: ConnectClientMetadata;
    transport?: ConnectSessionTransport;
    createdAt?: string;
    expiresAt?: string;
    ttlSeconds?: number;
};
export type ConnectPermissionGrantOptions = {
    /** Grant expiration timestamp. Defaults to the connect session expiration. */
    dateExpires?: string;
    /** Session metadata attached to every grant created by the approval. */
    connectSession?: ConnectSessionMetadata;
};
import { createGrantKeyRecordsForGrants as createGrantKeyRecordsForGrantsFn } from './dwn-encryption.js';
/**
 * Default lifetime for app delegate grants created by a connect approval.
 *
 * This is a hard grant expiry. There is intentionally no renewal path in this
 * protocol layer yet; clients should treat expired connect grants as
 * reconnect-required.
 */
export declare const CONNECT_SESSION_DEFAULT_TTL_SECONDS: number;
/** Maximum lifetime a wallet will stamp onto relay connect session grants. */
export declare const CONNECT_SESSION_MAX_TTL_SECONDS: number;
/**
 * Pushed to the connect server so the wallet can retrieve it later.
 * The request is encrypted (JWE) before being pushed.
 *
 * Inspired by RFC 9126 (Pushed Authorization Requests).
 */
export type ConnectPushedRequest = {
    /** The encrypted JWE containing the signed {@link EnboxConnectRequest} JWT. */
    request: string;
};
/**
 * Returned by the connect server after a {@link ConnectPushedRequest}.
 * Contains a URI the wallet uses to fetch the encrypted request,
 * and the TTL before it expires.
 */
export type ConnectPushedResponse = {
    /** URI where the wallet can fetch the encrypted auth request. */
    request_uri: string;
    /** Seconds until the request expires. */
    expires_in: number;
};
/**
 * A connect request from an app to a wallet, asking for DWN permissions.
 *
 * The app creates this, signs it as a JWT, encrypts it as a JWE, and pushes
 * it to the connect server. The wallet retrieves, decrypts, verifies, and
 * displays it in a consent UI.
 */
export type EnboxConnectRequest = {
    /** Ephemeral DID (did:jwk) used for ECDH key agreement and request signing. */
    clientDid: string;
    /** Human-readable name of the requesting application, shown in the consent UI. */
    appName: string;
    /** Optional icon URL for the requesting application, shown in the consent UI. */
    appIcon?: string;
    /** Optional client/environment metadata for wallet session display. */
    clientMetadata?: ConnectClientMetadata;
    /** Preferred session TTL in seconds. Wallets may clamp this to their policy maximum. */
    requestedSessionTtlSeconds?: number;
    /**
     * Optional delegate DID supplied by the requester.
     *
     * When present, the wallet grants permissions to this DID instead of
     * minting a new delegate DID and returning its private key material.
     */
    delegateDid?: string;
    /** DWN protocols and permission scopes being requested. */
    permissionRequests: ConnectPermissionRequest[];
    /** Anti-replay nonce (random base64url). */
    nonce: string;
    /** State correlator for matching request to response (random base64url). */
    state: string;
    /** URL where the wallet should POST the encrypted response. */
    callbackUrl: string;
    /** Response mode — always `direct_post` (wallet POSTs response to callbackUrl). */
    responseMode: 'direct_post';
    /** Supported DID methods for the connected identity. */
    supportedDidMethods: string[];
};
/**
 * A connect response from a wallet, granting DWN permissions.
 *
 * The wallet creates this after user consent, signs it as a JWT with the
 * delegate DID, encrypts it via ECDH, and POSTs it to the connect server.
 * The app retrieves, decrypts (using ECDH + optional PIN), and verifies it.
 */
export type EnboxConnectResponse = {
    /** The wallet owner's real DID that authorised the delegation. */
    providerDid: string;
    /** The delegate DID identifier that received the grants. */
    delegateDid: string;
    /** Audience — must match the `clientDid` from the request. */
    aud: string;
    /** Issued-at timestamp (Unix seconds). */
    iat: number;
    /** Expiration timestamp (Unix seconds). */
    exp: number;
    /** Echo of the request nonce. */
    nonce?: string;
    /** DWN permission grant messages (serialised RecordsWrite with encoded data). */
    delegateGrants: DwnDataEncodedRecordsWriteMessage[];
    /**
     * The delegate DID's full portable form, including private keys.
     *
     * Present for wallet-minted delegate sessions and omitted when the request
     * supplied its own delegate DID.
     */
    delegatePortableDid?: PortableDid;
    /** Per-grant revocation mappings for session-bound self-revocation on disconnect. */
    sessionRevocations?: {
        grantId: string;
        revocationGrantId: string;
    }[];
};
/** The connect server endpoint types. */
export type ConnectEndpoint = 'pushedAuthorizationRequest' | 'authorize' | 'callback' | 'token';
/**
 * Builds the URL for a connect server endpoint.
 *
 * @param options.baseURL - The connect server base URL (e.g. `http://localhost:3000/connect/`)
 * @param options.endpoint - The endpoint type
 * @param options.authParam - Required for `authorize` endpoint (the request ID)
 * @param options.tokenParam - Required for `token` endpoint (the state value)
 */
declare function buildConnectUrl({ baseURL, endpoint, authParam, tokenParam, }: {
    baseURL: string;
    endpoint: ConnectEndpoint;
    authParam?: string;
    tokenParam?: string;
}): string;
/**
 * Signs an object as a JWT using an Ed25519 DID key.
 *
 * `data` is constrained to `object` so callers don't have to widen
 * typed payload shapes (e.g. `EnboxConnectResponse`) to
 * `Record<string, unknown>` at the call site. `Convert.object(data)`
 * stringifies whatever JSON-serializable shape is passed.
 */
declare function signJwt({ did, data, }: {
    did: BearerDid;
    data: object;
}): Promise<string>;
/**
 * Verifies a JWT signature using the DID in the `kid` header. Returns the
 * parsed payload as an untyped object.
 *
 * The return type is intentionally `Record<string, unknown>` rather than a
 * caller-supplied generic — a JWT payload is bytes from a remote party, and
 * we can't soundly assert its shape without runtime validation. Callers must
 * apply one of the {@link assertConnectRequest} / {@link assertConnectResponse}
 * assertion helpers (or their own type guard) to narrow the payload before
 * accessing fields.
 */
declare function verifyJwt({ jwt }: {
    jwt: string;
}): Promise<Record<string, unknown>>;
/**
 * Runtime assertion that a verified JWT payload has the shape of an
 * {@link EnboxConnectRequest}. Use immediately after `verifyJwt()` to narrow
 * a `Record<string, unknown>` payload before accessing fields.
 */
declare function assertConnectRequest(payload: Record<string, unknown>): asserts payload is EnboxConnectRequest;
/**
 * Runtime assertion that a verified JWT payload has the shape of an
 * {@link EnboxConnectResponse}. Use immediately after `verifyJwt()` to narrow
 * a `Record<string, unknown>` payload before accessing fields.
 */
declare function assertConnectResponse(payload: Record<string, unknown>): asserts payload is EnboxConnectResponse;
/** Encrypts the connect request JWT with a symmetric key (shared via QR code or deep link). */
declare function encryptRequest({ jwt, encryptionKey, }: {
    jwt: string;
    encryptionKey: Uint8Array;
}): Promise<string>;
/** Decrypts an encrypted connect request JWE using the symmetric key from the QR/deep link. */
declare function decryptRequest({ jwe, encryptionKey, }: {
    jwe: string;
    encryptionKey: string;
}): Promise<string>;
/** Derives a shared ECDH key for encrypting/decrypting the connect response. */
declare function deriveSharedKey(privateKeyDid: BearerDid, publicKeyDid: DidDocument): Promise<Uint8Array>;
/**
 * Encrypts the connect response JWT.
 *
 * For remote (relay-mediated) flows, `pin` is required — it is added to the
 * AAD to prevent MITM attacks via the untrusted relay.
 *
 * For local (same-device) flows, `pin` may be omitted — the ECDH encryption
 * alone is sufficient when there is no untrusted intermediary.
 */
declare function encryptResponse({ jwt, encryptionKey, delegatePublicKeyJwk, pin, }: {
    jwt: string;
    encryptionKey: Uint8Array;
    delegatePublicKeyJwk: Jwk;
    pin?: string;
}): Promise<string>;
/**
 * Decrypts the connect response JWE using ECDH + optional PIN.
 *
 * @param clientDid - The ephemeral DID used at connect initiation (for ECDH).
 * @param jwe - The encrypted response JWE.
 * @param pin - The PIN entered by the user (required for remote flows, omit for local).
 */
declare function decryptResponse(clientDid: BearerDid, jwe: string, pin?: string): Promise<string>;
/** Creates an {@link EnboxConnectRequest}. */
declare function createConnectRequest(options: RequireOnly<EnboxConnectRequest, 'clientDid' | 'callbackUrl' | 'permissionRequests' | 'appName'>): Promise<EnboxConnectRequest>;
/**
 * Fetches an encrypted connect request from the authorize endpoint
 * and decrypts it using the encryption key from the QR/deep link.
 */
declare function getConnectRequest(requestUri: string, encryptionKey: string): Promise<EnboxConnectRequest>;
/** Creates an {@link EnboxConnectResponse} with timestamps. */
declare function createConnectResponse(options: RequireOnly<EnboxConnectResponse, 'providerDid' | 'delegateDid' | 'aud' | 'delegateGrants'>): Promise<EnboxConnectResponse>;
declare function createConnectSessionMetadata(options?: CreateConnectSessionMetadataOptions): ConnectSessionMetadata;
/**
 * Creates permission grants that assign the requested scopes to a delegate DID.
 */
declare function createPermissionGrants(selectedDid: string, delegateDid: string, agent: EnboxPlatformAgent, scopes: DwnPermissionScope[], options?: ConnectPermissionGrantOptions): Promise<DwnDataEncodedRecordsWriteMessage[]>;
/**
 * Executes the full wallet-side (provider) flow:
 * 1. Uses a requester-supplied delegate DID, or creates one when omitted
 * 2. Installs requested protocols
 * 3. Creates permission grants
 * 4. Builds, signs, and encrypts the response
 * 5. POSTs the encrypted response to the callback URL
 *
 * @param selectedDid - The provider's DID that is granting access.
 * @param connectRequest - The decoded connect request from the app.
 * @param pin - The PIN for response encryption AAD (required for remote flows).
 * @param agent - The agent instance for DWN operations.
 */
declare function submitConnectResponse(selectedDid: string, connectRequest: EnboxConnectRequest, pin: string | undefined, agent: EnboxPlatformAgent): Promise<void>;
export declare const EnboxConnectProtocol: {
    buildConnectUrl: typeof buildConnectUrl;
    signJwt: typeof signJwt;
    verifyJwt: typeof verifyJwt;
    assertConnectRequest: typeof assertConnectRequest;
    assertConnectResponse: typeof assertConnectResponse;
    encryptRequest: typeof encryptRequest;
    decryptRequest: typeof decryptRequest;
    encryptResponse: typeof encryptResponse;
    decryptResponse: typeof decryptResponse;
    deriveSharedKey: typeof deriveSharedKey;
    createConnectRequest: typeof createConnectRequest;
    getConnectRequest: typeof getConnectRequest;
    createConnectResponse: typeof createConnectResponse;
    createConnectSessionMetadata: typeof createConnectSessionMetadata;
    createPermissionGrants: typeof createPermissionGrants;
    createGrantKeyRecordsForGrants: typeof createGrantKeyRecordsForGrantsFn;
    submitConnectResponse: typeof submitConnectResponse;
};
export {};
//# sourceMappingURL=enbox-connect-protocol.d.ts.map