"use strict";
/**
 * AWS Signature Version 4 — shared signing utility.
 *
 * Extracted from duplicate inline implementations in:
 *   - src/llm-adapters/bedrock.ts  (Bedrock InvokeModel / Converse)
 *   - packages/governance-server/src/attestation-kms-aws.ts  (KMS Encrypt/Decrypt)
 *
 * Filed as F-NEW-SIGV4-CONSOLIDATE. Both call sites import from this module.
 * A matching canonical copy lives at
 * packages/governance-server/src/util/sigv4.ts for use within the
 * governance-server package boundary (zero third-party runtime deps rule).
 *
 * Reference: https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
 *
 * @connexum/ai-governance
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.signSigV4 = signSigV4;
exports.sha256Hex = sha256Hex;
exports.hmacSha256 = hmacSha256;
exports.hmacSha256Hex = hmacSha256Hex;
exports.deriveSigningKey = deriveSigningKey;
exports.formatAmzDate = formatAmzDate;
exports.formatDate = formatDate;
const crypto = __importStar(require("crypto"));
// ---------------------------------------------------------------------------
// Core signing function
// ---------------------------------------------------------------------------
/**
 * Sign an AWS request with SigV4 and return the signed headers to attach.
 *
 * The returned object always contains 'Authorization' and 'x-amz-date'.
 * If sessionToken is provided, 'x-amz-security-token' is included.
 * If includeContentSha256Header is true, 'x-amz-content-sha256' is included.
 *
 * Test vectors: AWS SigV4 Test Suite
 * https://docs.aws.amazon.com/general/latest/gr/sigv4-test-suite.html
 */
function signSigV4(opts) {
    const now = new Date();
    const amzDate = formatAmzDate(now);
    const dateStamp = formatDate(now);
    const payloadHash = sha256Hex(opts.body);
    // Build the canonical headers map. Keys must be lowercase.
    const headersMap = {
        host: opts.url.hostname,
        'x-amz-date': amzDate,
    };
    if (opts.sessionToken) {
        headersMap['x-amz-security-token'] = opts.sessionToken;
    }
    if (opts.includeContentSha256Header) {
        headersMap['x-amz-content-sha256'] = payloadHash;
    }
    // Merge caller-provided extra headers (lowercased)
    for (const [k, v] of Object.entries(opts.extraHeaders ?? {})) {
        headersMap[k.toLowerCase()] = v;
    }
    const sortedKeys = Object.keys(headersMap).sort();
    const canonicalHeaders = sortedKeys.map((k) => `${k}:${headersMap[k].trim()}`).join('\n') + '\n';
    const signedHeadersStr = sortedKeys.join(';');
    const canonicalPath = opts.url.pathname || '/';
    const canonicalQuery = opts.url.search ? opts.url.search.slice(1) : '';
    const canonicalRequest = [
        opts.method.toUpperCase(),
        canonicalPath,
        canonicalQuery,
        canonicalHeaders,
        signedHeadersStr,
        payloadHash,
    ].join('\n');
    const credentialScope = `${dateStamp}/${opts.region}/${opts.service}/aws4_request`;
    const stringToSign = [
        'AWS4-HMAC-SHA256',
        amzDate,
        credentialScope,
        sha256Hex(canonicalRequest),
    ].join('\n');
    const signingKey = deriveSigningKey(opts.secretAccessKey, dateStamp, opts.region, opts.service);
    const signature = hmacSha256Hex(signingKey, stringToSign);
    const authorization = `AWS4-HMAC-SHA256 Credential=${opts.accessKeyId}/${credentialScope}, ` +
        `SignedHeaders=${signedHeadersStr}, Signature=${signature}`;
    const result = {
        Authorization: authorization,
        'x-amz-date': amzDate,
    };
    if (opts.sessionToken) {
        result['x-amz-security-token'] = opts.sessionToken;
    }
    if (opts.includeContentSha256Header) {
        result['x-amz-content-sha256'] = payloadHash;
    }
    return result;
}
// ---------------------------------------------------------------------------
// Low-level primitives (exported for testing against AWS test vectors)
// ---------------------------------------------------------------------------
function sha256Hex(data) {
    return crypto.createHash('sha256').update(data).digest('hex');
}
function hmacSha256(key, data) {
    return crypto.createHmac('sha256', key).update(data, 'utf-8').digest();
}
function hmacSha256Hex(key, data) {
    return hmacSha256(key, data).toString('hex');
}
function deriveSigningKey(secret, dateStamp, region, service) {
    const kDate = hmacSha256(Buffer.from(`AWS4${secret}`, 'utf-8'), dateStamp);
    const kRegion = hmacSha256(kDate, region);
    const kService = hmacSha256(kRegion, service);
    return hmacSha256(kService, 'aws4_request');
}
/** Format a Date as YYYYMMDDTHHMMSSZ (AWS amz-date format). */
function formatAmzDate(d) {
    return d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
}
/** Format a Date as YYYYMMDD (AWS date-stamp format). */
function formatDate(d) {
    return d.toISOString().slice(0, 10).replace(/-/g, '');
}
//# sourceMappingURL=sigv4.js.map