ActivityPub HTTP Signatures
A library for creating, parsing, and verifying HTTP signature headers, as per the Signing HTTP Messages draft 08 specification.
Basic use
Signing
Signed Fetch
The simplest way to make a signed request is using SignedFetch. In this method you create a
fetch-like function that automatically signs requests before sending them.
Note that this function only supports a subset of fetch
's options - for more advanced
usage or for use with other HTTP libraries, see the next section.
import { Sha256Signer } from 'activitypub-http-signatures';
import fetch from 'node-fetch';
const publicKeyId = 'http://my-site.example/@paul#main-key';
const privateKey = `-----BEGIN RSA PRIVATE KEY-----
${process.env.PRIVATE_KEY}
-----END RSA PRIVATE KEY-----`;
export async function postResource(url, body) {
const signedFetch = SignedFetch.sha256(fetch, { publicKeyId, privateKey });
const res = await signedFetch(url, {
method: 'POST',
headers: {
'content-type': 'application/ld+json'
},
body
});
return res.ok;
}
The following example illustrates using the lower-level library functions to sign requests:
import { Sha256Signer } from 'activitypub-http-signatures';
import fetch from 'node-fetch';
const publicKeyId = 'http://my-site.example/@paul#main-key';
const privateKey = `-----BEGIN RSA PRIVATE KEY-----
${process.env.PRIVATE_KEY}
-----END RSA PRIVATE KEY-----`;
export function getResource(url) {
const signer = new Sha256Signer({ publicKeyId, privateKey });
const headers = {
accept: 'application/ld+json'
}
const method = 'GET';
const signedHeaders = signer.generateHeaders({
url,
method,
headers
});
return fetch(
url,
{
headers: signedHeaders,
}
)
}
Verifying
import parser from 'activitypub-http-signatures';
import fetch from 'node-fetch';
export async function verifyIncomingRequestSignature(req){
const { url, method, headers } = req;
const signature = parser.parse({ url, method, headers });
if(signature === null) {
throw new Error('The headers object has no `signature` key');
}
const keyRes = await fetch(
signature.keyId,
{
headers: {
accept: 'application/ld+json, application/json'
}
}
);
const { publicKey } = await keyRes.json();
const success = signature.verify(
publicKey.publicKeyPem,
);
if(!success){
throw new Error('http signature validation failed')
} else {
return publicKey.owner
}
}
Changes in V2
Version 2 of this package has a completely new and hopefully simpler API.
All previous exports have been removed,
you now need to use Sha256Signer
to sign outgoing requests
and Parser
to parse and verify incoming requests.
See the examples above for details.
Typescript definitions are included since V2.1.0