import "@js-temporal/polyfill";
import "urlpattern-polyfill";
globalThis.addEventListener = () => {};
import { J as getDocumentLoader, U as getTypeId, ot as name, s as CryptographicKey, st as version, t as Activity, v as Object$1 } from "./vocab-C5EUmVTj.mjs";
import { a as validateCryptoKey, n as fetchKey } from "./key-CvS3OKm_.mjs";
import { getLogger } from "@logtape/logtape";
import { SpanStatusCode, trace } from "@opentelemetry/api";
import jsonld from "jsonld";
import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
import { encodeHex } from "byte-encodings/hex";
//#region src/sig/ld.ts
const logger = getLogger([
	"fedify",
	"sig",
	"ld"
]);
const localContext = [
	"https://w3id.org/identity/v1",
	"https://www.w3.org/ns/activitystreams",
	"https://w3id.org/security/v1",
	"https://w3id.org/security/data-integrity/v1"
];
const localContextUrls = new Set(localContext);
const builtInContextLoader = getDocumentLoader();
const disallowedJsonLdKeywords = new Set([
	"@graph",
	"@included",
	"@reverse"
]);
/** @internal */
var UnsafeJsonLdError = class extends TypeError {
	constructor(keyword) {
		super(`Unsupported JSON-LD keyword: ${keyword}.`);
		this.keyword = keyword;
		this.name = "UnsafeJsonLdError";
	}
};
/** @internal */
var InvalidContextReferenceError = class extends TypeError {
	constructor(reference) {
		super(`Invalid JSON-LD context reference: ${reference}.`);
		this.reference = reference;
		this.name = "InvalidContextReferenceError";
	}
};
function createLoadingRemoteContextFailedError(reference, cause) {
	const message = cause instanceof Error ? cause.message : String(cause);
	const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
	error.name = "jsonld.InvalidUrl";
	error.details = {
		code: "loading remote context failed",
		url: reference
	};
	error.cause = cause;
	return error;
}
/** @internal */
function isClearlyMalformedContextReference(reference) {
	for (const char of reference) {
		const code = char.charCodeAt(0);
		if (code <= 32 || code === 127) return true;
	}
	if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
	for (let i = 0; i < reference.length; i++) {
		if (reference[i] !== "%") continue;
		if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
		i += 2;
	}
	if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
		for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
	}
	return false;
}
function cloneRemoteDocument(remoteDocument) {
	return structuredClone(remoteDocument);
}
function createMemoizedDocumentLoader(documentLoader) {
	const cache = /* @__PURE__ */ new Map();
	return async (url, options) => {
		const cacheKey = URL.canParse(url) ? new URL(url).href : url;
		let remoteDocument = cache.get(cacheKey);
		if (remoteDocument == null) {
			remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
			remoteDocument.catch(() => {
				if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
			});
			cache.set(cacheKey, remoteDocument);
		}
		return cloneRemoteDocument(await remoteDocument);
	};
}
/** @internal */
function wrapContextLoaderForJsonLd(contextLoader) {
	const loader = contextLoader ?? builtInContextLoader;
	return async (url, options) => {
		try {
			return await loader(url, options);
		} catch (error) {
			if (!isInvalidUrlTypeError(error)) throw error;
			if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
			throw createLoadingRemoteContextFailedError(url, error);
		}
	};
}
/** @internal */
function getNormalizationContextLoader(contextLoader) {
	const loader = wrapContextLoaderForJsonLd(contextLoader);
	return createMemoizedDocumentLoader(async (url, options) => {
		if (URL.canParse(url)) {
			const normalizedUrl = new URL(url).href;
			if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
		}
		return await loader(url, options);
	});
}
/** @internal */
async function compactJsonLd(jsonLd, contextLoader) {
	const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
	const signature = hasLds ? jsonLd.signature : void 0;
	const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
	const document = hasLds ? detachSignature(jsonLd) : jsonLd;
	await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
	const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
	if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
	assertSafeJsonLd(compacted);
	return compacted;
}
function createInvalidRemoteContextError(reference) {
	const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${reference}".`);
	error.name = "jsonld.InvalidUrl";
	error.details = {
		code: "invalid remote context",
		url: reference
	};
	return error;
}
function getRemoteContext(remoteDocument, reference) {
	const { contextUrl, documentUrl } = remoteDocument;
	let { document } = remoteDocument;
	if (typeof document === "string") document = JSON.parse(document);
	if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
	let context = "@context" in document ? document["@context"] : {};
	if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
	return {
		context,
		baseUrl: documentUrl ?? reference
	};
}
function createGraphAliasContextState() {
	return {
		graphTerms: /* @__PURE__ */ new Set(),
		jsonTerms: /* @__PURE__ */ new Set(),
		propertyContexts: /* @__PURE__ */ new Map(),
		termTargets: /* @__PURE__ */ new Map()
	};
}
function cloneGraphAliasContextState(state) {
	return {
		graphTerms: new Set(state.graphTerms),
		jsonTerms: new Set(state.jsonTerms),
		propertyContexts: new Map(state.propertyContexts),
		termTargets: new Map(state.termTargets)
	};
}
function resolveContextTarget(target, state) {
	if (target === "@graph") return target;
	const mapped = state.termTargets.get(target);
	if (mapped == null) return target;
	return mapped;
}
function getDirectContextTarget(definition) {
	if (definition === null) return null;
	if (typeof definition === "string") return definition;
	if (typeof definition === "object" && definition != null && "@id" in definition) {
		const id = definition["@id"];
		if (id === null) return null;
		if (typeof id === "string") return id;
	}
}
function isJsonTypedDefinition(definition) {
	return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
}
function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
	if (target === "@graph") return target;
	if (seen.has(target)) return target;
	seen.add(target);
	if (localTargets.has(target)) {
		const localTarget = localTargets.get(target);
		return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
	}
	return resolveContextTarget(target, state);
}
function refreshGraphAliases(state) {
	state.graphTerms.clear();
	for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
}
function normalizeContextReference(reference, baseUrl) {
	if (baseUrl != null) return new URL(reference, baseUrl).href;
	return URL.canParse(reference) ? new URL(reference).href : reference;
}
/** @internal */
function isInvalidUrlTypeError(error) {
	const code = error.code;
	return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
}
async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
	if (context === null) return createGraphAliasContextState();
	let nextState = cloneGraphAliasContextState(state);
	if (Array.isArray(context)) {
		for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
		return nextState;
	}
	if (typeof context === "string") {
		const reference = normalizeContextReference(context, baseUrl);
		const cacheKey = `${baseUrl ?? ""}\n${reference}`;
		if (processingContexts.has(cacheKey)) return nextState;
		processingContexts.add(cacheKey);
		try {
			let remoteContext = remoteContextCache.get(cacheKey);
			if (remoteContext == null) {
				remoteContext = (async () => {
					try {
						return getRemoteContext(await documentLoader(reference), reference);
					} catch (error) {
						if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
						throw error;
					}
				})();
				remoteContextCache.set(cacheKey, remoteContext);
			}
			const loadedRemoteContext = await remoteContext;
			return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
		} finally {
			processingContexts.delete(cacheKey);
		}
	}
	if (typeof context === "object" && context != null) {
		if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
		const localTargets = /* @__PURE__ */ new Map();
		for (const [term, definition] of globalThis.Object.entries(context)) {
			if (term.startsWith("@")) continue;
			const target = getDirectContextTarget(definition);
			if (target == null) localTargets.set(term, null);
			else if (typeof target === "string") localTargets.set(term, target);
			else localTargets.delete(term);
		}
		for (const [term, definition] of globalThis.Object.entries(context)) {
			if (term.startsWith("@")) continue;
			if (localTargets.has(term)) {
				const directTarget = localTargets.get(term);
				if (directTarget == null) nextState.termTargets.set(term, null);
				else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
			} else nextState.termTargets.delete(term);
			if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
				context: definition["@context"],
				baseUrl
			});
			else nextState.propertyContexts.delete(term);
			if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
			else nextState.jsonTerms.delete(term);
		}
		refreshGraphAliases(nextState);
	}
	return nextState;
}
async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
	if (Array.isArray(jsonLd)) {
		for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
		return;
	}
	if (typeof jsonLd !== "object" || jsonLd == null) return;
	const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
	let state = inheritedState;
	if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
	if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
	for (const [key, value] of globalThis.Object.entries(jsonLd)) {
		if (key === "@context") continue;
		if (jsonLiteralWrapper && key === "@value") continue;
		if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
		if (state.jsonTerms.has(key)) continue;
		await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
	}
}
function isJsonLiteralWrapper(value) {
	return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
}
/** @internal */
function assertSafeJsonLd(jsonLd) {
	if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
	else if (typeof jsonLd === "object" && jsonLd != null) {
		const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
		for (const [key, value] of globalThis.Object.entries(jsonLd)) {
			if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
			if (jsonLiteralWrapper && key === "@value") continue;
			assertSafeJsonLd(value);
		}
	}
}
/**
* Attaches a LD signature to the given JSON-LD document.
* @param jsonLd The JSON-LD document to attach the signature to.  It is not
*               modified.
* @param signature The signature to attach.
* @returns The JSON-LD document with the attached signature.
* @throws {TypeError} If the input document is not a valid JSON-LD document.
* @since 1.0.0
*/
function attachSignature(jsonLd, signature) {
	if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
	return {
		...jsonLd,
		signature
	};
}
/**
* Creates a LD signature for the given JSON-LD document.
* @param jsonLd The JSON-LD document to sign.
* @param privateKey The private key to sign the document.
* @param keyId The ID of the public key that corresponds to the private key.
* @param options Additional options for creating the signature.
*                See also {@link CreateSignatureOptions}.
* @return The created signature.
* @throws {TypeError} If the private key is invalid or unsupported.
* @since 1.0.0
*/
async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
	validateCryptoKey(privateKey, "private");
	if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
	const options = {
		"@context": "https://w3id.org/identity/v1",
		creator: keyId.href,
		created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
	};
	const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
	const messageBytes = new TextEncoder().encode(message);
	const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
	return {
		...options,
		type: "RsaSignature2017",
		signatureValue: encodeBase64(signature)
	};
}
/**
* Signs the given JSON-LD document with the private key and returns the signed
* JSON-LD document.
* @param jsonLd The JSON-LD document to sign.
* @param privateKey The private key to sign the document.
* @param keyId The key ID to use in the signature.  It will be used by the
*              verifier to fetch the corresponding public key.
* @param options Additional options for signing the document.
*                See also {@link SignJsonLdOptions}.
* @returns The signed JSON-LD document.
* @throws {TypeError} If the private key is invalid or unsupported.
* @since 1.0.0
*/
async function signJsonLd(jsonLd, privateKey, keyId, options) {
	return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
		try {
			const signature = await createSignature(jsonLd, privateKey, keyId, options);
			if (span.isRecording()) {
				span.setAttribute("ld_signatures.type", signature.type);
				span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
			}
			return attachSignature(jsonLd, signature);
		} catch (error) {
			span.setStatus({
				code: SpanStatusCode.ERROR,
				message: String(error)
			});
			throw error;
		} finally {
			span.end();
		}
	});
}
/**
* Checks if the given JSON-LD document has a Linked Data Signature.
* @param jsonLd The JSON-LD document to check.
* @returns `true` if the document has a signature; `false` otherwise.
* @since 1.0.0
*/
function hasSignature(jsonLd) {
	if (typeof jsonLd !== "object" || jsonLd == null) return false;
	if ("signature" in jsonLd) {
		const signature = jsonLd.signature;
		if (typeof signature !== "object" || signature == null) return false;
		return "type" in signature && signature.type === "RsaSignature2017" && "creator" in signature && typeof signature.creator === "string" && "created" in signature && typeof signature.created === "string" && "signatureValue" in signature && typeof signature.signatureValue === "string";
	}
	return false;
}
/**
* Detaches Linked Data Signatures from the given JSON-LD document.
* @param jsonLd The JSON-LD document to modify.
* @returns The modified JSON-LD document.  If the input document does not
*          contain a signature, the original document is returned.
* @since 1.0.0
*/
function detachSignature(jsonLd) {
	if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
	const doc = { ...jsonLd };
	delete doc.signature;
	return doc;
}
/**
* Verifies Linked Data Signatures of the given JSON-LD document.
* @param jsonLd The JSON-LD document to verify.
* @param options Options for verifying the signature.
* @returns The public key that signed the document or `null` if the signature
*          is invalid or the key is not found.
* @since 1.0.0
*/
async function verifySignature(jsonLd, options = {}) {
	if (!hasSignature(jsonLd)) return null;
	const sig = jsonLd.signature;
	let signature;
	try {
		signature = decodeBase64(sig.signatureValue);
	} catch (error) {
		logger.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
			...sig,
			error
		});
		return null;
	}
	const { key, cached } = await fetchKey(new URL(sig.creator), CryptographicKey, options);
	if (key == null) return null;
	const sigOpts = {
		...sig,
		"@context": "https://w3id.org/identity/v1"
	};
	delete sigOpts.type;
	delete sigOpts.id;
	delete sigOpts.signatureValue;
	let sigOptsHash;
	try {
		sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
	} catch (error) {
		logger.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
			signatureOptions: sigOpts,
			error
		});
		return null;
	}
	const document = { ...jsonLd };
	delete document.signature;
	let docHash;
	try {
		docHash = await hashJsonLd(document, options.contextLoader);
	} catch (error) {
		logger.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
			document,
			error
		});
		return null;
	}
	const encoder = new TextEncoder();
	const message = sigOptsHash + docHash;
	const messageBytes = encoder.encode(message);
	if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
	if (cached) {
		logger.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid.  Retrying with the freshly fetched key...", {
			keyId: sig.creator,
			...sig
		});
		const { key } = await fetchKey(new URL(sig.creator), CryptographicKey, {
			...options,
			keyCache: {
				get: () => Promise.resolve(void 0),
				set: async (keyId, key) => await options.keyCache?.set(keyId, key)
			}
		});
		if (key == null) return null;
		return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
	}
	logger.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid.  Check if the key is correct or if the signed message is correct.  The message to sign is:\n{message}", {
		keyId: sig.creator,
		...sig,
		message
	});
	return null;
}
/**
* Verify the authenticity of the given JSON-LD document using Linked Data
* Signatures.  If the document is signed, this function verifies the signature
* and checks if the document is attributed to the owner of the public key.
* If the document is not signed, this function returns `false`.
* @param jsonLd The JSON-LD document to verify.
* @param options Options for verifying the document.
* @returns `true` if the document is authentic; `false` otherwise.
*/
async function verifyJsonLd(jsonLd, options = {}) {
	return await verifyJsonLdInternal(jsonLd, options, true);
}
/** @internal */
async function verifyCompactJsonLd(jsonLd, options = {}) {
	return await verifyJsonLdInternal(jsonLd, options, false);
}
async function verifyJsonLdInternal(jsonLd, options, compact) {
	return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
		try {
			const verificationOptions = hasSignature(jsonLd) ? {
				...options,
				contextLoader: getNormalizationContextLoader(options.contextLoader)
			} : options;
			const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
			const object = await Object$1.fromJsonLd(compacted, verificationOptions);
			if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
			span.setAttribute("activitypub.object.type", getTypeId(object).href);
			if (typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd && typeof jsonLd.signature === "object" && jsonLd.signature != null) {
				if ("creator" in jsonLd.signature && typeof jsonLd.signature.creator === "string") span.setAttribute("ld_signatures.key_id", jsonLd.signature.creator);
				if ("signatureValue" in jsonLd.signature && typeof jsonLd.signature.signatureValue === "string") span.setAttribute("ld_signatures.signature", jsonLd.signature.signatureValue);
				if ("type" in jsonLd.signature && typeof jsonLd.signature.type === "string") span.setAttribute("ld_signatures.type", jsonLd.signature.type);
			}
			const attributions = new Set(object.attributionIds.map((uri) => uri.href));
			if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
			const key = await verifySignature(compacted, verificationOptions);
			if (key == null) return false;
			if (key.ownerId == null) {
				logger.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
				return false;
			}
			attributions.delete(key.ownerId.href);
			if (attributions.size > 0) {
				logger.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
				return false;
			}
			return true;
		} catch (error) {
			span.setStatus({
				code: SpanStatusCode.ERROR,
				message: String(error)
			});
			throw error;
		} finally {
			span.end();
		}
	});
}
async function hashJsonLd(jsonLd, contextLoader) {
	const canon = await jsonld.canonize(jsonLd, {
		format: "application/n-quads",
		documentLoader: contextLoader ?? getDocumentLoader()
	});
	const encoder = new TextEncoder();
	return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
}
//#endregion
export { compactJsonLd as a, getNormalizationContextLoader as c, isInvalidUrlTypeError as d, signJsonLd as f, wrapContextLoaderForJsonLd as g, verifySignature as h, attachSignature as i, hasSignature as l, verifyJsonLd as m, UnsafeJsonLdError as n, createSignature as o, verifyCompactJsonLd as p, assertSafeJsonLd as r, detachSignature as s, InvalidContextReferenceError as t, isClearlyMalformedContextReference as u };
