"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loginWithConsent = loginWithConsent;
const signer_js_1 = require("../identity/signer.js");
const messages_js_1 = require("../signing/messages.js");
/**
 * Authenticate with Junction41 using the VerusID LoginConsent protocol.
 *
 * 1. Fetches a LoginConsentRequest signed by agentplatform@
 * 2. Verifies the request signature (TLS + known API URL)
 * 3. Signs the challengeHash with the agent's WIF key (offline)
 * 4. Submits the signed response for verification
 *
 * @param apiUrl - J41 API base URL (e.g., "https://api.junction41.io")
 * @param wif - Agent's WIF private key (never sent to server)
 * @param identityAddress - Agent's VerusID (e.g., "myagent@" or i-address)
 * @returns Session info with resolved identity and session token
 */
async function loginWithConsent(apiUrl, wif, identityAddress, network = 'verustest') {
    // 1. Get login consent challenge
    const controller1 = new AbortController();
    const timeout1 = setTimeout(() => controller1.abort(), 30000);
    const challengeRes = await fetch(`${apiUrl}/auth/consent/challenge`, { signal: controller1.signal }).finally(() => clearTimeout(timeout1));
    if (!challengeRes.ok) {
        const err = await challengeRes.json().catch(() => ({}));
        throw new Error(`Failed to get login challenge: ${err.error?.message || challengeRes.statusText}`);
    }
    const { data: challenge } = await challengeRes.json();
    // 2. Verify the request came from agentplatform@ (defense-in-depth)
    // Primary: TLS certificate proves server identity.
    // The LoginConsentRequest signature in challenge.requestSignature can be
    // independently verified against agentplatform@'s on-chain keys if needed.
    if (!challenge.challengeHash || !challenge.challengeId) {
        throw new Error('Invalid challenge response: missing challengeHash or challengeId');
    }
    // 3. Sign the challengeHash with agent's WIF (offline, never leaves this machine).
    // Audit 2026-06-02 H4: refuse to sign if the platform-supplied challengeHash
    // is shaped like a J41 protocol message (a MITM'd consent challenge could
    // otherwise mint a J41-DEPOSIT-REPORT / J41-COMPLETE signature here).
    (0, messages_js_1.assertNotProtocolMessage)(challenge.challengeHash);
    const sig = (0, signer_js_1.signMessage)(wif, challenge.challengeHash, network);
    // 4. Submit signed response
    const controller2 = new AbortController();
    const timeout2 = setTimeout(() => controller2.abort(), 30000);
    const verifyRes = await fetch(`${apiUrl}/auth/consent/verify`, {
        signal: controller2.signal,
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            challengeId: challenge.challengeId,
            verusId: identityAddress,
            signature: sig,
        }),
    });
    clearTimeout(timeout2);
    if (!verifyRes.ok) {
        const err = await verifyRes.json().catch(() => ({}));
        throw new Error(`Login verification failed: ${err.error?.message || verifyRes.statusText}`);
    }
    const { data } = await verifyRes.json();
    return data;
}
//# sourceMappingURL=login-consent.js.map