"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeAuthMiddleware = makeAuthMiddleware;
function makeAuthMiddleware(authService) {
    return async (ws, data, next) => {
        if (!authService.isLocked()) {
            return next();
        }
        let parsed;
        try {
            const raw = typeof data === "string" ? data : data.toString("utf-8");
            parsed = JSON.parse(raw);
        }
        catch {
            ws.send(JSON.stringify({
                type: "auth:locked",
                message: "Worker is locked. Send { type: 'auth:getChallenge' } first.",
            }));
            return;
        }
        if (parsed.type === "auth:getChallenge") {
            const challenge = authService.generateChallenge();
            ws.send(JSON.stringify({
                type: "auth:challenge",
                challenge,
                credentialId: authService.getCredentialId(),
                timestamp: Math.floor(Date.now() / 1000),
            }));
            return;
        }
        if (parsed.type === "auth:response") {
            const result = await authService.unlock({
                signature: parsed.signature,
                credentialId: parsed.credentialId,
                authenticatorData: parsed.authenticatorData,
                clientDataJSON: parsed.clientDataJSON,
                challenge: parsed.challenge,
            });
            if (result.success) {
                const info = authService.getSessionInfo();
                ws.send(JSON.stringify({
                    type: "auth:success",
                    expiresAt: info.expiresAt,
                }));
            }
            else {
                ws.send(JSON.stringify({
                    type: "auth:failure",
                    reason: result.reason ?? "unknown",
                }));
            }
            return;
        }
        ws.send(JSON.stringify({
            type: "auth:locked",
            message: "Worker is locked. Send { type: 'auth:getChallenge' } to authenticate.",
        }));
    };
}
//# sourceMappingURL=authMiddleware.js.map