@fedify/fedify
Version:
An ActivityPub server framework
104 lines (103 loc) • 3.22 kB
JavaScript
import { trace } from "@opentelemetry/api";
import { getDocumentLoader, } from "../runtime/docloader.js";
import { isActor } from "../vocab/actor.js";
import { CryptographicKey, Object as ASObject, } from "../vocab/vocab.js";
export { exportJwk, generateCryptoKeyPair, importJwk } from "./key.js";
/**
* Checks if the actor of the given activity owns the specified key.
* @param activity The activity to check.
* @param key The public key to check.
* @param options Options for checking the key ownership.
* @returns Whether the actor is the owner of the key.
*/
export async function doesActorOwnKey(activity, key, options) {
if (key.ownerId != null) {
return key.ownerId.href === activity.actorId?.href;
}
const actor = await activity.getActor(options);
if (actor == null || !isActor(actor))
return false;
for (const publicKeyId of actor.publicKeyIds) {
if (key.id != null && publicKeyId.href === key.id.href)
return true;
}
return false;
}
/**
* Gets the actor that owns the specified key. Returns `null` if the key has no
* known owner.
*
* @param keyId The ID of the key to check, or the key itself.
* @param options Options for getting the key owner.
* @returns The actor that owns the key, or `null` if the key has no known
* owner.
* @since 0.7.0
*/
export async function getKeyOwner(keyId, options) {
const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
const documentLoader = options.documentLoader ?? getDocumentLoader();
const contextLoader = options.contextLoader ?? getDocumentLoader();
let object;
if (keyId instanceof CryptographicKey) {
object = keyId;
if (object.id == null)
return null;
keyId = object.id;
}
else {
let keyDoc;
try {
const { document } = await documentLoader(keyId.href);
keyDoc = document;
}
catch (_) {
return null;
}
try {
object = await ASObject.fromJsonLd(keyDoc, {
documentLoader,
contextLoader,
tracerProvider,
});
}
catch (e) {
if (!(e instanceof TypeError))
throw e;
try {
object = await CryptographicKey.fromJsonLd(keyDoc, {
documentLoader,
contextLoader,
tracerProvider,
});
}
catch (e) {
if (e instanceof TypeError)
return null;
throw e;
}
}
}
let owner = null;
if (object instanceof CryptographicKey) {
if (object.ownerId == null)
return null;
owner = await object.getOwner({
documentLoader,
contextLoader,
tracerProvider,
});
}
else if (isActor(object)) {
owner = object;
}
else {
return null;
}
if (owner == null)
return null;
for (const kid of owner.publicKeyIds) {
if (kid.href === keyId.href)
return owner;
}
return null;
}