@agentauth/sdk
Version:
MCP-native identity generation and authentication for AI agents.
86 lines (85 loc) • 3.08 kB
JavaScript
/*
* Copyright (c) 2025 AgentAuth
* SPDX-License-Identifier: MIT
*/
import { verifySignature, generateId, generateIdentity as coreGenerateIdentity, deriveAddress } from '@agentauth/core';
import { Buffer } from 'buffer';
const SIXTY_SECONDS_IN_MS = 60 * 1000;
/**
* Defines the headers used for AgentAuth.
*/
export const AGENTAUTH_HEADERS = {
ADDRESS: 'x-agentauth-address',
PAYLOAD: 'x-agentauth-payload',
SIGNATURE: 'x-agentauth-signature',
};
/**
* Core verification function for AgentAuth.
* It is stateless and performs address-based signature verification and timestamp validation.
*
* @param request The incoming request object containing headers.
* @param options Optional configuration for verification.
* @returns VerificationResult with valid flag and agentauth_id if successful.
*/
export function verify(request, options = {}) {
const { headers } = request;
const freshness = options.freshness ?? SIXTY_SECONDS_IN_MS;
const agentauth_address = headers[AGENTAUTH_HEADERS.ADDRESS];
const signature = headers[AGENTAUTH_HEADERS.SIGNATURE];
const payloadB64 = headers[AGENTAUTH_HEADERS.PAYLOAD];
if (!agentauth_address || !signature || !payloadB64) {
return { valid: false };
}
try {
// 1. Decode payload
const payloadStr = Buffer.from(payloadB64, 'base64').toString('utf-8');
const payload = JSON.parse(payloadStr);
// 2. Verify signature against address
const isSignatureValid = verifySignature(signature, payload, agentauth_address);
if (!isSignatureValid) {
return { valid: false };
}
// 3. Check timestamp freshness
const requestTimestamp = new Date(payload.timestamp).getTime();
const now = Date.now();
if (Math.abs(now - requestTimestamp) > freshness) {
return { valid: false };
}
// 4. Generate stable ID from address
const agentauth_id = generateId(agentauth_address);
// Verification successful
return { valid: true, agentauth_id };
}
catch (error) {
// Any parsing or verification error results in invalid
return { valid: false };
}
}
/**
* Generates a new AgentAuth identity with AgentAuth Token, ID, and Address.
*
* @returns GeneratedIdentity containing the AgentAuth Token, ID, and Address.
*/
export function generateIdentity() {
const { agentauth_token, agentauth_id } = coreGenerateIdentity();
const agentauth_address = deriveAddress(agentauth_token);
return {
agentauth_token,
agentauth_id,
agentauth_address,
};
}
/**
* Derives an AgentAuth ID and Address from an existing AgentAuth Token.
*
* @param agentauth_token The AgentAuth Token to derive from.
* @returns DerivedIdentity containing the ID and Address.
*/
export function deriveFromToken(agentauth_token) {
const agentauth_address = deriveAddress(agentauth_token);
const agentauth_id = generateId(agentauth_address);
return {
agentauth_id,
agentauth_address,
};
}