revamp signatures

This commit is contained in:
Moon Man 2023-12-31 05:32:39 -05:00
parent 3544c61468
commit 6ada10a340
2 changed files with 34 additions and 23 deletions

2
module.d.ts vendored
View File

@ -6,7 +6,7 @@ declare module "activitypub-express" {
// Only enough here for what I need. // Only enough here for what I need.
declare module "activitypub-http-signatures" { declare module "activitypub-http-signatures" {
export class Sha256Signer { export class Sha256Signer {
constructor(options: { publicKeyId: string, privateKey: string }); constructor(options: { publicKeyId: string, privateKey: string }, headerNames?: string[]);
sign: (options: { url: string, method: string, headers: any[] }) => string; sign: (options: { url: string, method: string, headers: any[] }) => string;
}; };

View File

@ -22,24 +22,31 @@ export const signedFetch = async (url: string, init: RequestInit, signedInit: Si
const signedHeaders: HeadersInit = [ const signedHeaders: HeadersInit = [
["Date", new Date().toUTCString()], ["Date", new Date().toUTCString()],
["Host", new URL(url).host], ["Host", new URL(url).host],
["Content-Type", `application/ld+json; profile="${CONTEXT}"`]
]; ];
const newHeaders = new Headers(); const headerNames = ["(request-target)", "host", "date"];
if (signedInit.digest && init.body) { if (init.method === "POST") {
headerNames.push("digest");
if (init.body) {
if (signedInit.digest) {
signedHeaders.push(["Digest", signedInit.digest]); signedHeaders.push(["Digest", signedInit.digest]);
} }
else if (init.method === "POST" && init.body) { else {
if (Buffer.isBuffer(init.body) || typeof init.body === "string") { if (Buffer.isBuffer(init.body) || typeof init.body === "string") {
signedHeaders.push(["Digest", hashDigest(init.body)]); signedHeaders.push(["Digest", hashDigest(init.body)]);
} }
else throw "unsupported body type"; else throw "unsupported body type";
}
}
else throw "missing body";
}
const signer = new Sha256Signer({ const signer = new Sha256Signer({
privateKey: signedInit.privateKey, privateKey: signedInit.privateKey,
publicKeyId: signedInit.keyId publicKeyId: signedInit.keyId
}); }, headerNames);
const signature = signer.sign({ const signature = signer.sign({
url, url,
@ -47,8 +54,12 @@ export const signedFetch = async (url: string, init: RequestInit, signedInit: Si
headers: signedHeaders headers: signedHeaders
}); });
newHeaders.set("Authorization", `Signature ${signature}`); const newHeaders = new Headers(
} [
["Signature", signature],
["Content-Type", `application/ld+json; profile="${CONTEXT}"`]
]
);
if (Array.isArray(init.headers) || !init.headers) { if (Array.isArray(init.headers) || !init.headers) {
for (const header of (init.headers || [])) { for (const header of (init.headers || [])) {