From 6ada10a3405cfd73713a41e2a136a73812c5e3d2 Mon Sep 17 00:00:00 2001 From: Moon Man Date: Sun, 31 Dec 2023 05:32:39 -0500 Subject: [PATCH] revamp signatures --- module.d.ts | 2 +- src/net.ts | 55 ++++++++++++++++++++++++++++++++--------------------- 2 files changed, 34 insertions(+), 23 deletions(-) diff --git a/module.d.ts b/module.d.ts index 3fa44c1..5a0ce17 100644 --- a/module.d.ts +++ b/module.d.ts @@ -6,7 +6,7 @@ declare module "activitypub-express" { // Only enough here for what I need. declare module "activitypub-http-signatures" { 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; }; diff --git a/src/net.ts b/src/net.ts index 9388113..f5b6e36 100644 --- a/src/net.ts +++ b/src/net.ts @@ -22,34 +22,45 @@ export const signedFetch = async (url: string, init: RequestInit, signedInit: Si const signedHeaders: HeadersInit = [ ["Date", new Date().toUTCString()], ["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) { - signedHeaders.push(["Digest", signedInit.digest]); - } - else if (init.method === "POST" && init.body) { - if (Buffer.isBuffer(init.body) || typeof init.body === "string") { - signedHeaders.push(["Digest", hashDigest(init.body)]); + if (init.method === "POST") { + headerNames.push("digest"); + + if (init.body) { + if (signedInit.digest) { + signedHeaders.push(["Digest", signedInit.digest]); + } + else { + if (Buffer.isBuffer(init.body) || typeof init.body === "string") { + signedHeaders.push(["Digest", hashDigest(init.body)]); + } + else throw "unsupported body type"; + } } - else throw "unsupported body type"; - - const signer = new Sha256Signer({ - privateKey: signedInit.privateKey, - publicKeyId: signedInit.keyId - }); - - const signature = signer.sign({ - url, - method: init.method as string, - headers: signedHeaders - }); - - newHeaders.set("Authorization", `Signature ${signature}`); + else throw "missing body"; } + const signer = new Sha256Signer({ + privateKey: signedInit.privateKey, + publicKeyId: signedInit.keyId + }, headerNames); + + const signature = signer.sign({ + url, + method: init.method as string, + headers: signedHeaders + }); + + const newHeaders = new Headers( + [ + ["Signature", signature], + ["Content-Type", `application/ld+json; profile="${CONTEXT}"`] + ] + ); + if (Array.isArray(init.headers) || !init.headers) { for (const header of (init.headers || [])) { if (Array.isArray(header))