import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, } from "@simplewebauthn/server";
export async function webAuthnRegistrationOptions(input) {
    return generateRegistrationOptions({
        rpName: input.rp.rpName,
        rpID: input.rp.rpId,
        userName: input.user.email,
        userDisplayName: input.user.displayName,
        userID: Buffer.from(input.user.id),
        attestationType: "none",
        excludeCredentials: input.credentials.map((credential) => ({
            id: credential.credentialId,
            transports: credential.transports,
        })),
        authenticatorSelection: {
            residentKey: "preferred",
            userVerification: "preferred",
        },
    });
}
export async function verifyWebAuthnRegistration(input) {
    const verification = await verifyRegistrationResponse({
        response: input.response,
        expectedChallenge: input.expectedChallenge,
        expectedOrigin: input.rp.origin,
        expectedRPID: input.rp.rpId,
        requireUserVerification: false,
    });
    if (!verification.verified) {
        return { verified: false };
    }
    const info = verification.registrationInfo;
    return {
        verified: true,
        credential: {
            credentialId: info.credential.id,
            publicKey: Buffer.from(info.credential.publicKey).toString("base64url"),
            counter: info.credential.counter,
            transports: input.response.response.transports,
            deviceType: info.credentialDeviceType,
            backedUp: info.credentialBackedUp,
        },
    };
}
export async function webAuthnAuthenticationOptions(input) {
    return generateAuthenticationOptions({
        rpID: input.rp.rpId,
        allowCredentials: input.credentials.map((credential) => ({
            id: credential.credentialId,
            transports: credential.transports,
        })),
        userVerification: "preferred",
    });
}
export async function verifyWebAuthnAuthenticationChallenge(input) {
    const verification = await verifyAuthenticationResponse({
        response: input.response,
        expectedChallenge: input.expectedChallenge,
        expectedOrigin: input.rp.origin,
        expectedRPID: input.rp.rpId,
        credential: webAuthnCredential(input.credential),
        requireUserVerification: false,
    });
    return {
        verified: verification.verified,
        newCounter: verification.authenticationInfo?.newCounter,
    };
}
function webAuthnCredential(credential) {
    return {
        id: credential.credentialId,
        publicKey: Buffer.from(credential.publicKey, "base64url"),
        counter: credential.counter,
        transports: credential.transports,
    };
}
