"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDelegationToken = createDelegationToken;
exports.validateDelegationToken = validateDelegationToken;
exports.requireScope = requireScope;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const config_1 = require("../../modules/config");
const MAX_TTL_SECONDS = 3600; // 1 hour
const DEFAULT_TTL_SECONDS = 300; // 5 minutes
/**
 * Create a scoped, short-lived delegation token.
 *
 * Delegation tokens authorize MCP tools to act on behalf of a user
 * with only the specified scopes.
 */
function createDelegationToken(userId, scopes, ttlSeconds = DEFAULT_TTL_SECONDS, options) {
    const ttl = Math.min(Math.max(ttlSeconds, 1), MAX_TTL_SECONDS);
    const payload = {
        type: 'delegation',
        sub: userId,
        scopes,
        workflowId: options?.workflowId,
        serverId: options?.serverId,
    };
    return jsonwebtoken_1.default.sign(payload, config_1.config.JWT_SECRET, {
        expiresIn: ttl,
        issuer: 'long-tail',
    });
}
/**
 * Validate a delegation token. Returns the decoded payload or throws.
 */
function validateDelegationToken(token) {
    const decoded = jsonwebtoken_1.default.verify(token, config_1.config.JWT_SECRET, {
        issuer: 'long-tail',
    });
    if (decoded.type !== 'delegation') {
        throw new Error('Token is not a delegation token');
    }
    return decoded;
}
/**
 * Check that a delegation token has the required scope.
 * Throws if the scope is missing.
 */
function requireScope(payload, requiredScope) {
    if (!payload.scopes.includes(requiredScope)) {
        throw new Error(`Delegation token missing required scope: ${requiredScope}`);
    }
}
