Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"test-build": "esbuild ./dist/client/index.js ./dist/server/index.js ./dist/index.js --bundle --platform=neutral --outdir=dist/tmp-checks --outbase=./dist"
},
"dependencies": {
"jose": "^6.1.3",
"uuid": "^11.1.0"
},
"peerDependencies": {
Expand Down
9 changes: 8 additions & 1 deletion src/client/multitransport-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PushNotificationNotSupportedError } from '../errors.js';
import { AgentCardSignatureVerifier } from '../signature.js';
import {
MessageSendParams,
TaskPushNotificationConfig,
Expand Down Expand Up @@ -75,14 +76,20 @@ export class Client {
* If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
* Otherwise it will return the current agent card value.
*/
async getAgentCard(options?: RequestOptions): Promise<AgentCard> {
async getAgentCard(
options?: RequestOptions,
verifyAgentCardSignature?: AgentCardSignatureVerifier
): Promise<AgentCard> {
if (this.agentCard.supportsAuthenticatedExtendedCard) {
this.agentCard = await this.executeWithInterceptors(
{ method: 'getAgentCard' },
options,
(_, options) => this.transport.getExtendedAgentCard(options)
);
}
if (verifyAgentCardSignature) {
await verifyAgentCardSignature(this.agentCard);
}
return this.agentCard;
}

Expand Down
20 changes: 15 additions & 5 deletions src/server/request_handler/default_request_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import { PushNotificationSender } from '../push_notification/push_notification_sender.js';
import { DefaultPushNotificationSender } from '../push_notification/default_push_notification_sender.js';
import { ServerCallContext } from '../context.js';
import { AgentCardSignatureGenerator } from '../../signature.js';

const terminalStates: TaskState[] = ['completed', 'failed', 'canceled', 'rejected'];

Expand All @@ -45,6 +46,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
private readonly pushNotificationStore?: PushNotificationStore;
private readonly pushNotificationSender?: PushNotificationSender;
private readonly extendedAgentCardProvider?: AgentCard | ExtendedAgentCardProvider;
private readonly agentCardSignatureGenerator?: AgentCardSignatureGenerator;

constructor(
agentCard: AgentCard,
Expand All @@ -53,13 +55,15 @@ export class DefaultRequestHandler implements A2ARequestHandler {
eventBusManager: ExecutionEventBusManager = new DefaultExecutionEventBusManager(),
pushNotificationStore?: PushNotificationStore,
pushNotificationSender?: PushNotificationSender,
extendedAgentCardProvider?: AgentCard | ExtendedAgentCardProvider
extendedAgentCardProvider?: AgentCard | ExtendedAgentCardProvider,
agentCardSignatureGenerator?: AgentCardSignatureGenerator
) {
this.agentCard = agentCard;
this.taskStore = taskStore;
this.agentExecutor = agentExecutor;
this.eventBusManager = eventBusManager;
this.extendedAgentCardProvider = extendedAgentCardProvider;
this.agentCardSignatureGenerator = agentCardSignatureGenerator;

// If push notifications are supported, use the provided store and sender.
// Otherwise, use the default in-memory store and sender.
Expand All @@ -71,6 +75,9 @@ export class DefaultRequestHandler implements A2ARequestHandler {
}

async getAgentCard(): Promise<AgentCard> {
if (this.agentCardSignatureGenerator) {
return await this.agentCardSignatureGenerator(this.agentCard);
}
return this.agentCard;
}

Expand All @@ -81,13 +88,16 @@ export class DefaultRequestHandler implements A2ARequestHandler {
if (!this.extendedAgentCardProvider) {
throw A2AError.authenticatedExtendedCardNotConfigured();
}
let agentCard = this.agentCard;
if (typeof this.extendedAgentCardProvider === 'function') {
return this.extendedAgentCardProvider(context);
agentCard = await this.extendedAgentCardProvider(context);
} else if (context?.user?.isAuthenticated) {
agentCard = this.extendedAgentCardProvider;
}
if (context?.user?.isAuthenticated) {
return this.extendedAgentCardProvider;
if (this.agentCardSignatureGenerator) {
return await this.agentCardSignatureGenerator(agentCard);
}
return this.agentCard;
return agentCard;
}

private async _createRequestContext(
Expand Down
129 changes: 129 additions & 0 deletions src/signature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { AgentCard, AgentCardSignature } from './types.js';
import * as jose from 'jose';

export type AgentCardSignatureGenerator = (agentCard: AgentCard) => Promise<AgentCard>;

export function generateAgentCardSignature(
privateKey: jose.CryptoKey | jose.KeyObject | jose.JWK,
protectedHeader: jose.JWSHeaderParameters,
header?: jose.JWSHeaderParameters
): AgentCardSignatureGenerator {
return async (agentCard: AgentCard): Promise<AgentCard> => {
const cardCopy = JSON.parse(JSON.stringify(agentCard));
delete cardCopy.signatures;
const canonicalPayload = canonicalizeAgentCard(cardCopy);

const jws = await new jose.FlattenedSign(new TextEncoder().encode(canonicalPayload))
.setProtectedHeader(protectedHeader)
.setUnprotectedHeader(header)
.sign(privateKey);

const agentCardSignature: AgentCardSignature = {
protected: jws.protected,
signature: jws.signature,
header: jws.header,
};

if (!agentCard.signatures) agentCard.signatures = [];
agentCard.signatures.push(agentCardSignature);

return agentCard;
};
}

export type AgentCardSignatureVerifier = (agentCard: AgentCard) => Promise<void>;

export function verifyAgentCardSignature(
retrievePublicKey: (
kid: string,
jku?: string
) => Promise<jose.CryptoKey | jose.KeyObject | jose.JWK>
): AgentCardSignatureVerifier {
return async (agentCard: AgentCard): Promise<void> => {
if (!agentCard.signatures?.length) {
throw new Error('No signatures found on agent card to verify.');
}
const cardCopy = JSON.parse(JSON.stringify(agentCard));
delete cardCopy.signatures;
const canonicalPayload = canonicalizeAgentCard(cardCopy);
const payloadBytes = new TextEncoder().encode(canonicalPayload);
const encodedPayload = jose.base64url.encode(payloadBytes);

for (const signatureEntry of agentCard.signatures) {
try {
const protectedHeader = jose.decodeProtectedHeader(signatureEntry);
if (!protectedHeader.kid || !protectedHeader.typ || !protectedHeader.alg) {
throw new Error('Missing required header parameters (kid, typ, alg)');
}
const publicKey = await retrievePublicKey(protectedHeader.kid, protectedHeader.jku);
const jws: jose.FlattenedJWS = {
payload: encodedPayload,
protected: signatureEntry.protected,
signature: signatureEntry.signature,
header: signatureEntry.header,
};
await jose.flattenedVerify(jws, publicKey);
return;
} catch (error) {
console.warn('Signature verification failed:', error);
}
Comment on lines +67 to +69
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of logging verification failures to the console with console.warn, it would be more helpful for the library consumer if you collect all verification errors. Then, if no valid signatures are found, you can throw an error that includes the details of why each signature verification failed. This provides better debugging information without polluting the console.

You would need to declare an array for errors before the loop, push errors in this catch block, and then use that array in the final throw statement after the loop.

}
throw new Error('No valid signatures found on agent card.');
};
}

function cleanEmpty(d: unknown): unknown {
if (d === '' || d === null || d === undefined) {
return null;
}

if (Array.isArray(d)) {
const cleanedList = d.map((v) => cleanEmpty(v)).filter((v) => v !== null);
return cleanedList.length > 0 ? cleanedList : null;
}

if (typeof d === 'object') {
if (d instanceof Date) return d;
const cleanedDict: { [key: string]: unknown } = {};
for (const [key, v] of Object.entries(d)) {
const cleanedValue = cleanEmpty(v);
if (cleanedValue !== null) {
cleanedDict[key] = cleanedValue;
}
}
return Object.keys(cleanedDict).length > 0 ? cleanedDict : null;
}

return d;
}

/**
* JCS Canonicalization (RFC 8785)
* Sorts keys recursively and serializes to string.
*/
function jcsStringify(value: unknown): string {
if (value === null || typeof value !== 'object') {
return JSON.stringify(value);
}

if (Array.isArray(value)) {
return '[' + value.map((item) => jcsStringify(item)).join(',') + ']';
}

const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort();
const parts = keys.map((key) => {
return `${JSON.stringify(key)}:${jcsStringify(record[key])}`;
});

return '{' + parts.join(',') + '}';
}

export function canonicalizeAgentCard(agentCard: Omit<AgentCard, 'signatures'>): string {
const cleaned = cleanEmpty(agentCard);
if (!cleaned) {
return '{}';
}

return jcsStringify(cleaned);
}
Loading
Loading